Anthropic | 消息

发送带有文本内容的结构化输入消息列表,模型将生成对话中的下一条消息。

简单示例

向 Claude 发送 Hello 消息。


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';
WriteLn(Anthropic._CreateMessage('claude-sonnet-4-20250514', 'Hello!'));

系统提示词示例

发送带有系统提示的消息以控制 Claude 的行为。


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';
WriteLn(Anthropic._CreateMessageWithSystem('claude-sonnet-4-20250514',
  'You are a helpful assistant that responds in Spanish.',
  'What is the capital of France?'));

高级示例

使用类型化的请求/响应类对消息参数进行完全控制。


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';

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 := 'Hello!';
  oMessages := oRequest.Messages;
  SetLength(oMessages, 1);
  oMessages[0] := oMessage;
  oRequest.Messages := oMessages;

  oResponse := Anthropic.CreateMessage(oRequest);
  Try
    if Length(oResponse.Content) > 0 then
      WriteLn(oResponse.Content[0].Text);
  Finally
    oResponse.Free;
  End;
Finally
  oMessage.Free;
  oRequest.Free;
End;

流式示例

使用 Server-Sent Events(SSE)实时流式传输响应。分配 OnHTTPAPISSE 事件处理程序以接收流式事件。


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';
Anthropic.OnHTTPAPISSE := OnSSEEvent;
Anthropic._CreateMessageStream('claude-sonnet-4-20250514', 'Tell me a story.');

procedure TForm1.OnSSEEvent(Sender: TObject; const aEvent, aData: string;
  var Cancel: Boolean);
begin
  // aEvent contains the event type (e.g. content_block_delta)
  // aData contains the JSON data for this event
  Memo1.Lines.Add(aData);
end;