Integre a Anthropic Claude API em seus aplicativos Delphi
sgcWebSockets delivers um production-ready componente Delphi para o full Anthropic Claude API — um partir de text generation e vision para tool use, extended thinking, e beyond.
Anthropic Claude is one do most advanced AI model families available today, renowned para its exceptional reasoning, safety-first design, e versatile capabilities across text, code, vision, e structured data. For desenvolvedores Delphi looking para harness these capabilities, sgcWebSockets provides TsgcHTTP_API_Anthropic — um comprehensive, nativo component that wraps o entire Anthropic API surface.
Whether you are building intelligent chatbots, automating document analysis, orchestrating complexo tool pipelines, ou processing thousands de requests em batch, this component gives you direct access para every Claude feature through clean, type-safe Delphi code. No REST boilerplate. No JSON wrangling. Just drop o componente, set your chave de API, e iniciar building.
Cobertura Completa da API
Every major feature do Anthropic Claude API é suportado out do box.
| Messages & Streaming Envie mensagens com system prompts, receive responses synchronously ou streamed em em tempo real via Server-Sent Events. |
Vision Analyze images em JPEG, PNG, GIF, e WebP formats. Claude describes, interprets, e reasons about visual content. |
Tool Use Define custom tools com JSON Schema e let Claude call them. Build agentic workflows com function calling. |
| Extended Thinking Enable step-by-step reasoning para complexo tasks. Ideal para math, analysis, e multi-step problem solving. |
Document Processing Send PDF documents e text files para analysis, summarization, e question answering com citation support. |
Structured Outputs Force Claude para return valid JSON conforming para your schema. Guaranteed parseable, type-safe responses. |
| Web Search Let Claude search o web para em tempo real information during conversations using built-in server-side tools. | Prompt Caching Cache system prompts, content blocks, e tool definitions. Reduce costs por até 90% em repeated context. | Message Batches Process thousands de requests asynchronously. Perfect para bulk content generation e data processing pipelines. |
| Files API Upload, list, download, e manage files em da Anthropic servers. Reference them across multiple conversations. | MCP Connector Conectar Claude para external Model Context Protocol servers. Extend capabilities com third-party tools e services. | Token Counting Count tokens before sending requests. Accurately estimate costs e manage context window budgets. |
Primeiros passos
Integrate Claude into your Delphi project em under um minute. Drop o componente, configure your chave de API, e send your first message.
// 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;
Mensagens & Streaming
The Messages API is o foundation de every Claude interaction. Send text com optional system prompts, e receive responses synchronously ou streamed em em tempo real.
System PromptsControl Claude's behavior por providing um system prompt that sets o context, personality, ou constraints para o 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."
Real-Time Streaming
For responsive user interfaces, stream Claude's response token-by-token using Server-Sent Events. Assign o OnHTTPAPISSE event handler e call _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;
Advanced Typed API
For full control over request parâmetros — temperature, top-p, parar sequences, metadata — use o typed request e response classes.
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;
Visão — Compreensão de Imagens
Claude can analyze e reason about images. Send photographs, screenshots, diagrams, ou charts e receive detailed descriptions, data extraction, ou visual Q&A.
Suportado formats include JPEG, PNG, GIF, e WebP. Images are sent como 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;
Uso de Ferramentas — Chamada de Funções
Define custom tools com JSON Schema, e Claude will decide when e como invoke them. This is o foundation para building agentic, multi-step workflows.
The tool use flow follows um clear pattern: define tools, send um request, detect tool_use em um resposta, execute o function locally, e return o resultado para Claude para o 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;
Processamento de Documentos & Citações
Send PDF documents e text files para Claude para analysis, summarization, e question answering. Enable citations para receber verifiable references back para o source material.
// 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');
Citations
Enable citations em document content blocks para receber source references — incluindo page numbers, character ranges, e cited text — em Claude's response.
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;
Conector MCP
Conectar Claude para external Model Context Protocol (MCP) servers para extend its capabilities com third-party tools e services — databases, CRMs, internal APIs, e more.
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');
Authenticated MCP Servers
For servers that require autenticação, o typed API suporta OAuth Bearer tokens.
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';
