Delphi 애플리케이션에 Anthropic Claude API 통합하기
sgcWebSockets는 텍스트 생성, 비전, 도구 사용, 확장 사고 등 전체 Anthropic Claude API를 위한 프로덕션 준비 완료 Delphi 컴포넌트를 제공해요.
Anthropic Claude is one of the most advanced AI model families available today, renowned for its exceptional reasoning, safety-first design, and versatile capabilities across text, code, vision, and structured data. For Delphi developers looking to harness these capabilities, sgcWebSockets provides TsgcHTTP_API_Anthropic — a comprehensive, native component that wraps the entire Anthropic API surface.
Whether you are building intelligent chatbots, automating document analysis, orchestrating complex tool pipelines, or processing thousands of requests in batch, this component gives you direct access to every Claude feature through clean, type-safe Delphi code. No REST boilerplate. No JSON wrangling. Just drop the component, set your API key, and start building.
완전한 API 지원
Anthropic Claude API의 모든 주요 기능을 별도 설정 없이 지원해요.
| Messages & Streaming Send messages with system prompts, receive responses synchronously or streamed in real-time via Server-Sent Events. |
Vision Analyze images in JPEG, PNG, GIF, and WebP formats. Claude describes, interprets, and reasons about visual content. |
Tool Use Define custom tools with JSON Schema and let Claude call them. Build agentic workflows with function calling. |
| Extended Thinking Enable step-by-step reasoning for complex tasks. Ideal for math, analysis, and multi-step problem solving. |
Document Processing Send PDF documents and text files for analysis, summarization, and question answering with citation support. |
Structured Outputs Force Claude to return valid JSON conforming to your schema. Guaranteed parseable, type-safe responses. |
| Web Search Let Claude search the web for real-time information during conversations using built-in server-side tools. | Prompt Caching Cache system prompts, content blocks, and tool definitions. Reduce costs by up to 90% on repeated context. | Message Batches Process thousands of requests asynchronously. Perfect for bulk content generation and data processing pipelines. |
| Files API Upload, list, download, and manage files on Anthropic's servers. Reference them across multiple conversations. | MCP Connector Connect Claude to external Model Context Protocol servers. Extend capabilities with third-party tools and services. | Token Counting Count tokens before sending requests. Accurately estimate costs and manage context window budgets. |
시작하기
Delphi 프로젝트에 Claude를 1분 이내에 통합하세요. 컴포넌트를 추가하고, API 키를 설정한 후, 첫 메시지를 보내요.
// Create the component and configure the API key
var
Anthropic: TsgcHTTP_API_Anthropic;
vResponse: string;
begin
Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Try
Anthropic.AnthropicOptions.ApiKey := 'YOUR_API_KEY';
// Send a simple message to Claude
vResponse := Anthropic._CreateMessage(
'claude-sonnet-4-20250514', 'Hello, Claude!');
ShowMessage(vResponse);
Finally
Anthropic.Free;
End;
end;
메시지 & 스트리밍
Messages API는 모든 Claude 상호작용의 기반이에요. 선택적인 시스템 프롬프트와 함께 텍스트를 보내고, 동기 또는 실시간 스트리밍 방식으로 응답을 받으세요.
시스템 프롬프트컨텍스트, 페르소나, or constraints for the conversation.
vResponse := Anthropic._CreateMessageWithSystem( 'claude-sonnet-4-20250514', 'You are a helpful assistant that responds in Spanish.', 'What is the capital of France?'); // Returns: "La capital de Francia es París."
실시간 스트리밍
반응형 사용자 인터페이스를 위해 Server-Sent Events를 사용해 Claude 응답을 토큰 단위로 스트리밍하세요. OnHTTPAPISSE 이벤트 핸들러를 할당하고 _CreateMessageStream을 호출해요.
// Enable streaming via SSE
Anthropic.OnHTTPAPISSE := OnSSEEvent;
Anthropic._CreateMessageStream('claude-sonnet-4-20250514',
'Tell me a story about a brave explorer.');
procedure TForm1.OnSSEEvent(Sender: TObject;
const aEvent, aData: string; var Cancel: Boolean);
begin
// aEvent: event type (e.g., content_block_delta)
// aData: JSON payload for this event
Memo1.Lines.Add(aData);
end;
고급 타입드 API
temperature, top-p, stop sequences, metadata 등 요청 매개변수를 완전히 제어하려면 타입드 요청 및 응답 클래스를 사용하세요.
var
oRequest: TsgcAnthropicClass_Request_Messages;
oMessage: TsgcAnthropicClass_Request_Message;
oResponse: TsgcAnthropicClass_Response_Messages;
begin
oRequest := TsgcAnthropicClass_Request_Messages.Create;
Try
oRequest.Model := 'claude-sonnet-4-20250514';
oRequest.MaxTokens := 1024;
oRequest.System := 'You are a helpful assistant.';
oRequest.Temperature := 0.7;
oMessage := TsgcAnthropicClass_Request_Message.Create;
oMessage.Role := 'user';
oMessage.Content := 'Explain quantum computing in simple terms.';
// ... add message to request, send, and process response
oResponse := Anthropic.CreateMessage(oRequest);
Try
if Length(oResponse.Content) > 0 then
ShowMessage(oResponse.Content[0].Text);
Finally
oResponse.Free;
End;
Finally
oMessage.Free;
oRequest.Free;
End;
end;
비전 — 이미지 이해
Claude는 이미지를 분석하고 추론할 수 있어요. 사진, 스크린샷, 다이어그램, 차트를 보내고 상세한 설명, 데이터 추출, 시각적 Q&A를 받으세요.
지원 형식은 JPEG, PNG, GIF, WebP를 포함해요. Images are sent as base64-encoded content blocks.
// Load an image and ask Claude to describe it
var
vBase64: string;
begin
vBase64 := sgcBase64Encode(LoadFileToBytes('product-photo.png'));
ShowMessage(Anthropic._CreateVisionMessage(
'claude-sonnet-4-20250514',
'Describe this product image for an e-commerce listing.',
vBase64, 'image/png'));
end;
도구 사용 — 함수 호출
JSON Schema로 커스텀 도구를 정의하면 Claude가 언제 어떻게 호출할지 결정해요. 이는 에이전트 기반의 다단계 워크플로우를 구축하기 위한 기반이에요.
도구 사용 흐름은 명확한 패턴을 따라요. 도구를 정의하고, 요청을 보내고, 응답에서 tool_use를 감지하고, 함수를 실행해요ction locally, and return the result to Claude for the final answer.
// Define a weather tool with JSON Schema input
oTool := TsgcAnthropicClass_Request_Tool.Create;
oTool.Name := 'get_weather';
oTool.Description := 'Get the current weather in a given location';
oTool.InputSchema :=
'{"type":"object","properties":{"location":{"type":"string",' +
'"description":"The city and state"}},"required":["location"]}';
// Send request with tools defined
oResponse := Anthropic.CreateMessage(oRequest);
// Check if Claude wants to call a tool
if oResponse.StopReason = 'tool_use' then
begin
for i := 0 to Length(oResponse.Content) - 1 do
begin
if oResponse.Content[i].ContentType = 'tool_use' then
begin
vToolUseId := oResponse.Content[i].Id;
vToolName := oResponse.Content[i].Name;
vToolInput := oResponse.Content[i].Input;
// Execute the tool and return the result to Claude
end;
end;
end;
문서 처리 & 인용
분석, 요약, 질의응답을 위해 Claude에 PDF 문서와 텍스트 파일을 보내세요. 인용 기능을 활성화하면 원본 자료로 돌아가는 검증 가능한 참조를 받을 수 있어요.
// Send a PDF and ask Claude to summarize it
vBase64 := sgcBase64Encode(LoadFileToBytes('annual-report.pdf'));
vResponse := Anthropic._CreateDocumentMessage(
'claude-sonnet-4-20250514',
'Summarize the key findings of this report.',
vBase64, 'application/pdf');
인용
문서 콘텐츠 블록에서 인용을 활성화하면 Claude 응답에서 페이지 번호, 문자 범위, 인용된 텍스트를 포함한 원본 참조를 받을 수 있어요.
oDocBlock := TsgcAnthropicClass_Request_Content_Block.Create; oDocBlock.ContentType := 'document'; oDocBlock.SourceType := 'base64'; oDocBlock.MediaType := 'application/pdf'; oDocBlock.Data := vBase64; oDocBlock.Title := 'Annual Report'; oDocBlock.CitationsEnabled := True;
MCP 커넥터
외부 Model Context Protocol(MCP) 서버에 Claude를 연결해 데이터베이스, CRM, 내부 API 등 서드파티 도구와 서비스로 기능을 확장하세요.
Anthropic.AnthropicOptions.BetaHeaders := 'mcp-client-2025-11-20'; // Connect to an MCP server with one method call vResponse := Anthropic._CreateMessageWithMCP( 'claude-sonnet-4-20250514', 'What tools are available?', 'https://my-mcp-server.example.com/sse', 'my-mcp-server');
인증된 MCP 서버
인증이 필요한 서버를 위해 타입드 API는 OAuth Bearer 토큰을 지원해요.
oServer := TsgcAnthropicClass_Request_MCPServer.Create; oServer.ServerType := 'url'; oServer.Url := 'https://my-mcp-server.example.com/sse'; oServer.Name := 'my-server'; oServer.AuthorizationToken := 'OAUTH_TOKEN'; oTool := TsgcAnthropicClass_Request_Tool.Create; oTool.ToolType := 'mcp_toolset'; oTool.MCPServerName := 'my-server';
