旧版 API

文本补全 API 是一个旧版 API。未来的模型和功能将需要使用 Messages API,我们建议尽快迁移

在创建文本补全时,您可以设置 "stream": true 来使用服务器发送事件 (SSE)增量流式传输响应。如果您使用我们的客户端库,这些事件的解析将自动为您处理。但是,如果您正在构建直接的 API 集成,则需要自行处理这些事件。

示例

Request
curl https://api.anthropic.com/v1/complete \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --data '
{
  "model": "claude-2",
  "prompt": "\n\nHuman: Hello, world!\n\nAssistant:",
  "max_tokens_to_sample": 256,
  "stream": true
}
'
Response
event: completion
data: {"type": "completion", "completion": " Hello", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": "!", "stop_reason": null, "model": "claude-2.0"}

event: ping
data: {"type": "ping"}

event: completion
data: {"type": "completion", "completion": " My", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": " name", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": " is", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": " Claude", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": ".", "stop_reason": null, "model": "claude-2.0"}

event: completion
data: {"type": "completion", "completion": "", "stop_reason": "stop_sequence", "model": "claude-2.0"}

事件

每个事件都包含一个命名的事件类型和相关的 JSON 数据。

事件类型:completionpingerror

错误事件类型

我们可能偶尔会在事件流中发送错误。例如,在高使用率期间,您可能会收到 overloaded_error,这在非流式上下文中通常对应于 HTTP 529:

Example error
event: completion
data: {"completion": " Hello", "stop_reason": null, "model": "claude-2.0"}

event: error
data: {"error": {"type": "overloaded_error", "message": "Overloaded"}}

旧版 API 版本

如果您使用的是 2023-06-01 之前的 API 版本,响应格式会有所不同。详情请参阅版本控制