大模型 API 参考
创建 Chat Completion
POST https://api.openai.com/v1/chat/completions
调用这个接口,根据 messages 中的对话生成下一条助手消息。多轮对话要把模型看到的历史一并放进 messages;响应里的 id
不能用来恢复上下文。可用的输入类型、工具和参数由 model 决定。
POST /v1/chat/completions HTTP/1.1Host: api.openai.comAuthorization: Bearer <OPENAI_API_KEY>Content-Type: application/json
{ "model": "gpt-6-astra", "messages": [ {"role": "developer", "content": "用中文简短回答。"}, {"role": "user", "content": "什么是 HTTP?"} ]}请求头
| 名称 | 必填 | 说明 |
|---|---|---|
Authorization | 是 | Bearer <API_KEY> 形式的 API 密钥 |
Content-Type | 是 | application/json |
OpenAI-Organization | 否 | 指定组织,适用于密钥可访问多个组织的情况 |
OpenAI-Project | 否 | 指定项目 |
X-Client-Request-Id | 否 | 调用方生成的请求标识,用于关联日志,不等于幂等键 |
响应头中的 x-request-id 用于定位请求,限额信息见 x-ratelimit-*。
请求参数
必填字段
| 字段 | 类型 | 说明 |
|---|---|---|
model | string | 模型 ID |
messages | object[] | 完整的对话消息列表;消息结构见下一节 |
生成与采样
| 字段 | 类型 | 说明 |
|---|---|---|
max_completion_tokens | integer / null | 生成 token 的上限,包含可见输出和推理 token |
temperature | number / null | 采样温度,范围 0 到 2。通常只调整它或 top_p 中的一项 |
top_p | number / null | 核采样的累计概率阈值 |
frequency_penalty | number / null | 范围 -2 到 2,按已出现的频率影响重复 token |
presence_penalty | number / null | 范围 -2 到 2,按 token 是否出现过影响后续生成 |
stop | string / string[] / null | 最多四个停止序列;命中序列不会出现在返回文本中。部分推理模型不支持 |
n | integer / null | 为同一输入生成的候选数量,返回到 choices;费用与所有候选的生成量有关 |
logit_bias | object / null | token ID 到偏置值的映射,偏置范围 -100 到 100 |
logprobs | boolean / null | 是否返回输出 token 的对数概率 |
top_logprobs | integer / null | 每个位置返回的候选 token 数量,范围 0 到 20;要求 logprobs: true |
seed | integer / null | Beta 参数,尽力复现采样结果;不能保证确定性,可结合 system_fingerprint 排查差异 |
输出、推理与工具
| 字段 | 类型 | 说明 |
|---|---|---|
modalities | string[] / null | 输出类型,例如 ["text"] 或 ["text", "audio"] |
audio | object / null | 音频输出的声音与格式。请求音频输出时需要配置 |
response_format | object | 文本、JSON 对象或 JSON Schema 输出约束 |
reasoning_effort | string / null | 推理投入,可选值包括 none、minimal、low、medium、high、xhigh、max;模型只支持其中一部分 |
verbosity | string / null | 输出详细程度:low、medium、high |
prediction | object / null | 预先提供大部分已知输出,适用于支持 Predicted Outputs 的模型 |
tools | object[] | 函数工具或自定义文本工具的定义 |
tool_choice | string / object | none、auto、required,或指定工具 |
parallel_tool_calls | boolean | 是否允许同一轮产生多个工具调用 |
web_search_options | object | 支持搜索的模型使用的搜索配置 |
moderation | object / null | 请求输入与输出的审核配置;包含审核 model 和可选 policy |
流式、存储与缓存
| 字段 | 类型 | 说明 |
|---|---|---|
stream | boolean / null | 为 true 时返回 SSE 流;返回对象的 object 从 chat.completion 变成 chat.completion.chunk |
stream_options | object / null | 仅在 stream: true 时使用,例如请求流末尾的用量 |
store | boolean / null | 是否存储本次 Chat Completion,受组织的数据策略约束 |
metadata | object / null | 最多 16 组字符串键值;键最长 64 字符,值最长 512 字符 |
service_tier | string / null | 处理等级,例如 auto、default、flex、scale、priority、fast,取决于项目权限 |
safety_identifier | string / null | 稳定的最终用户标识,最长 128 字符;避免直接放姓名或邮箱 |
prompt_cache_key | string / null | 将相似请求归入缓存,不能用它代替对话历史 |
prompt_cache_options | object | 新版提示缓存配置,包含 mode 与 ttl;仅适用于支持该配置的模型 |
已弃用或兼容字段
| 字段 | 类型 | 当前对应字段 |
|---|---|---|
max_tokens | integer / null | 使用 max_completion_tokens;不兼容部分推理模型 |
functions | object[] | 使用 tools |
function_call | string / object | 使用 tool_choice |
user | string | 缓存归类使用 prompt_cache_key,用户安全标识使用 safety_identifier |
prompt_cache_retention | string / null | 旧缓存保留策略,值为 in_memory 或 24h;新版配置为 prompt_cache_options.ttl,两者语义不同 |
消息对象
messages[].role
| 角色 | 用途 | 主要字段 |
|---|---|---|
developer | 开发者指令;是否支持取决于模型 | content、可选 name |
system | 系统指令 | content、可选 name |
user | 用户输入 | content、可选 name |
assistant | 历史模型输出或工具调用 | content、tool_calls、refusal、audio、可选 name |
tool | 客户端工具执行结果 | tool_call_id、content |
function | 已弃用的函数结果角色 | name、content |
developer 与 system 的内容可以是字符串或文本块数组。user 还可以包含图片、音频和文件块。assistant 发起工具调用时,
content 可以为空。
内容块
type | 主要结构 | 说明 |
|---|---|---|
text | {"type":"text","text":"你好"} | 普通文本 |
image_url | {"type":"image_url","image_url":{"url":"…","detail":"auto"}} | 远程图片 URL 或含 base64 的 data URL;detail 取值受模型支持范围约束 |
input_audio | {"type":"input_audio","input_audio":{"data":"…","format":"wav"}} | base64 音频;格式为 wav 或 mp3 |
file | {"type":"file","file":{"file_id":"file_…"}} | 已上传文件,也可以按接口支持的方式提供 file_data 和 filename |
refusal | {"type":"refusal","refusal":"…"} | 助手消息中的拒绝内容 |
图片输入示例:
[ { "role": "user", "content": [ { "type": "text", "text": "描述这张图片。" }, { "type": "image_url", "image_url": { "url": "https://www.example.com/example.jpg", "detail": "auto" } } ] }]多轮消息
多轮消息要把模型看到的历史一起发过来。响应体里的 id 只是本次返回的标识,不能拿它把旧对话自动接进新的请求。
{ "model": "gpt-6-astra", "messages": [ { "role": "system", "content": "用中文简短回答。" }, { "role": "user", "content": "什么是 HTTP?" }, { "role": "assistant", "content": "HTTP 是客户端和服务器交换请求与响应的协议。" }, { "role": "user", "content": "HTTPS 多了什么?" } ]}返回对象
查看返回 JSON 示例
{ "id": "chatcmpl_example", "object": "chat.completion", "created": 1792454400, "model": "gpt-6-astra", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "HTTP 是客户端和服务器交换请求与响应的协议。", "refusal": null }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 20, "completion_tokens": 15, "total_tokens": 35 }}Chat Completion
| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 本次生成的标识 |
object | string | 固定为 chat.completion |
created | integer | Unix 秒级时间戳 |
model | string | 实际使用的模型 |
choices | object[] | 候选输出,按 index 区分 |
usage | object / null | token 计数与明细 |
service_tier | string / null | 实际处理等级,可能不同于请求值 |
system_fingerprint | string / null | 后端配置指纹,不是模型内容的哈希 |
metadata | object / null | 附加元数据 |
moderation | object / null | 请求审核时的输入、输出审核结果或审核错误 |
choices[]
| 字段 | 说明 |
|---|---|
index | 候选序号 |
message.role | 生成消息的角色,通常是 assistant |
message.content | 文本内容或 null;工具调用场景不能只读取此字段 |
message.tool_calls | 函数或自定义工具调用数组 |
message.refusal | 拒绝内容或 null |
message.audio | 音频输出对象,包含 id、data、expires_at、transcript |
message.annotations | 注解,例如搜索引用的 URL、标题与文本区间 |
message.function_call | 已弃用的旧式函数调用 |
logprobs | 文本或拒绝内容的 token 概率,含 token、logprob、bytes 和候选列表 |
finish_reason | 本候选结束的原因 |
finish_reason:stop 表示自然结束或命中停止序列;length 表示达到上限;tool_calls 表示需要处理工具调用;
content_filter 表示内容被过滤;function_call 是旧式工具结束原因。
usage
| 字段 | 说明 |
|---|---|
prompt_tokens | 输入 token 数 |
completion_tokens | 生成 token 数 |
total_tokens | 输入与生成 token 总数 |
prompt_tokens_details.cached_tokens | 输入中命中缓存的 token 数 |
prompt_tokens_details.audio_tokens | 音频输入 token 数 |
completion_tokens_details.reasoning_tokens | 推理 token 数,属于生成用量 |
completion_tokens_details.audio_tokens | 音频输出 token 数 |
completion_tokens_details.accepted_prediction_tokens | 预测输出中被接受的 token 数 |
completion_tokens_details.rejected_prediction_tokens | 预测输出中未被采用的 token 数 |
工具调用
函数工具定义
tools[].type 为 function,函数定义放在 tools[].function 中。
{ "model": "gpt-6-astra", "messages": [ { "role": "user", "content": "杭州现在的天气如何?" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "查询指定城市的当前天气。", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false }, "strict": true } } ], "tool_choice": "auto"}name 是调用名称;description 用于说明用途;parameters 是 JSON Schema;strict 控制严格匹配,具体 Schema
需符合接口支持的子集。强制调用某个函数时,使用 {"type":"function","function":{"name":"get_weather"}}。
调用与回传
模型返回的 arguments 是字符串形式的 JSON,客户端负责解析、校验、执行工具,再回传结果。示例只展示 messages
的增量;实际请求还要保留之前的消息和工具定义。
[ { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_weather_1", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\":\"杭州\"}" } } ] }, { "role": "tool", "tool_call_id": "call_weather_1", "content": "{\"temperature_c\":22,\"condition\":\"晴\"}" }]有多个调用时,每个 tool_call_id 都要对应其结果。
自定义文本工具
自定义工具使用 {"type":"custom","custom":{"name":"…","description":"…","format":{"type":"text"}}}。也可以通过 grammar
格式约束自由文本输入;返回调用的文本在 custom.input 中,而非 function.arguments。
格式化输出与高级配置
response_format
{"type":"text"} 输出普通文本;{"type":"json_object"} 只约束 JSON 语法:
{ "type": "json_schema", "json_schema": { "name": "city_result", "strict": true, "schema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false } }}Schema 正确也要检查 refusal 和结束原因。截断响应不能当作完整 JSON 使用。
audio、prediction 与搜索
audio 包含 voice 与 format,格式包括 wav、mp3、flac、opus、pcm16 等已定义值,具体以音频模型为准。音频输出配合
modalities 使用。
prediction 的形式为 {"type":"content","content":"已知的大部分输出"},content 也可以是文本块数组。
web_search_options 包含 search_context_size(low、medium、high)及可选 user_location。近似位置结构为
{"type":"approximate","approximate":{"country":"CN","city":"杭州","timezone":"Asia/Shanghai"}};approximate 还可以包含
region。
缓存与审核
新版 prompt_cache_options 使用 mode: "implicit" | "explicit" 和 ttl: "30m"。显式缓存断点写在支持该能力的内容块上,是否支持及断点数量需与模型指南一并确认。
prompt_cache_key 只影响缓存归类,不传递历史消息。
moderation 的结构为{"model":"omni-moderation-latest","policy":{"input":{"mode":"score"},"output":{"mode":"block"}}}。
score 与 block的行为不同,不应把审核结果当成普通模型文本。
流式事件
请求设置 stream: true。若需要结束时的用量,增加 "stream_options":{"include_usage":true}。
每个 SSE data 事件是一份 chat.completion.chunk,通过空行分隔。下面省略与当前片段无关的可选字段:
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1792454400,"model":"gpt-6-astra","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1792454400,"model":"gpt-6-astra","choices":[{"index":0,"delta":{"content":"你好"},"finish_reason":null}]}
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1792454400,"model":"gpt-6-astra","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1792454400,"model":"gpt-6-astra","choices":[],"usage":{"prompt_tokens":8,"completion_tokens":2,"total_tokens":10}}
data: [DONE]chunk 拼接规则
| 字段 | 处理方式 |
|---|---|
choices[].index | 分开维护每个候选,不能把多个候选串成一份文本 |
delta.role | 设置消息角色,通常只在开头出现 |
delta.content | 追加文本增量,允许为空或缺失 |
delta.refusal | 单独累计拒绝内容 |
delta.tool_calls[].index | 同一候选内部的工具序号,用它定位待拼接调用 |
delta.tool_calls[].function.arguments | 字符串增量,完整收到后再解析 JSON |
finish_reason | 标记对应候选结束,后面仍可能有用量事件 |
usage | 启用 include_usage 后的最终用量;断流时可能收不到 |
从网络读到的一段字节,不等于一个 SSE 事件。先缓冲到空行,拼好这一事件的所有 data: 行,再解析 JSON;[DONE] 是终止标记,不是
JSON。
错误
{ "error": { "message": "Invalid value for a request parameter.", "type": "invalid_request_error", "param": "messages", "code": "invalid_value" }}| HTTP 状态 | 检查方向 |
|---|---|
400 | JSON、字段类型、模型参数支持范围、上下文长度 |
401 | API 密钥是否有效 |
403 | 项目、组织或资源权限 |
404 | 模型或资源标识是否存在且可访问 |
429 | 请求速率、token 速率或额度;根据错误码区分,避免无限重试 |
500 / 503 | 服务端错误或繁忙,结合响应头进行有限次数退避重试 |
参考文档
创建 Response
POST https://api.openai.com/v1/responses
调用这个接口,提交文本或输入项,得到消息、工具调用及其他输出项。输入和输出都按 type 区分。多轮状态既可以自己维护,也可以交给服务端托管。
POST /v1/responses HTTP/1.1Host: api.openai.comAuthorization: Bearer <OPENAI_API_KEY>Content-Type: application/json
{ "model": "gpt-6-astra", "instructions": "用中文简短回答。", "input": "什么是 HTTP?"}请求头
| 名称 | 必填 | 说明 |
|---|---|---|
Authorization | 是 | Bearer <API_KEY> 形式的 API 密钥 |
Content-Type | 是 | application/json |
OpenAI-Organization | 否 | 指定组织 |
OpenAI-Project | 否 | 指定项目 |
X-Client-Request-Id | 否 | 调用方的日志关联标识,不提供去重执行保证 |
响应头中的 x-request-id 用于定位请求,限额信息见 x-ratelimit-*。
请求参数
模型与输入
| 字段 | 类型 | 说明 |
|---|---|---|
model | string | 模型 ID |
input | string / object[] | 文本快捷形式,或消息、工具结果、引用等输入项数组 |
instructions | string / null | 本次生成的系统或开发者指令。使用 previous_response_id 时,上一次的此字段不会自动继承 |
previous_response_id | string / null | 关联上一条 Response;不能与 conversation 同时使用 |
conversation | string / object / null | 会话 ID,或包含 id 的引用对象;会话内容参与上下文,输入输出随后加入该会话 |
prompt | object / null | 提示模板引用,包含 id、可选 version 和 variables |
context_management | object[] / null | 上下文管理配置,如 {"type":"compaction","compact_threshold":…} |
truncation | string / null | disabled 为默认策略,超出上下文时失败;auto 允许删除较早的输入项以适配上下文 |
输出与生成控制
| 字段 | 类型 | 说明 |
|---|---|---|
max_output_tokens | integer / null | 输出上限,包含可见输出与推理 token |
temperature | number / null | 采样温度,范围 0 到 2 |
top_p | number / null | 核采样阈值,通常不要与 temperature 同时调节 |
text | object | 文本格式和详细程度,包含 format 与 verbosity |
reasoning | object / null | 推理投入、摘要、上下文和执行模式配置 |
include | string[] / null | 要额外返回的详细数据,例如搜索结果、引用来源或加密推理内容 |
top_logprobs | integer / null | 每个 token 位置返回的候选概率数量,范围 0 到 20 |
moderation | object / null | 审核模型与输入、输出审核策略 |
工具
| 字段 | 类型 | 说明 |
|---|---|---|
tools | object[] | 函数工具、自定义工具及内置工具定义 |
tool_choice | string / object | none、auto、required,或者指定工具、限制可选工具集合 |
parallel_tool_calls | boolean / null | 是否允许并行工具调用 |
max_tool_calls | integer / null | 一次 Response 内所有内置工具的总调用上限,不是每个工具各自的上限 |
流式、存储与服务配置
| 字段 | 类型 | 说明 |
|---|---|---|
stream | boolean / null | 返回带事件类型的 SSE 流 |
stream_options | object / null | 流配置,目前包括 include_obfuscation |
background | boolean / null | 后台运行。后台生成可能先返回排队或进行中的状态 |
store | boolean / null | 是否存储以供后续访问;省略时默认为 true,仍受组织保留策略约束 |
metadata | object / null | 最多 16 组字符串键值,键最长 64 字符、值最长 512 字符 |
service_tier | string / null | 服务处理等级,取决于模型、账户与项目配置 |
safety_identifier | string / null | 稳定的最终用户标识,避免直接发送个人身份信息 |
prompt_cache_key | string / null | 缓存归类键 |
prompt_cache_options | object | 新版缓存模式、TTL、预热与诊断配置 |
access_programs | object | 特定领域的访问计划;例如 cyber,需要相应权限 |
user | string | 兼容字段,由 safety_identifier 与 prompt_cache_key 分别承担对应用途 |
prompt_cache_retention | string / null | 已弃用的缓存保留策略;新版配置使用 prompt_cache_options.ttl,并非直接改名 |
输入项
消息
消息的 role 可以是 user、assistant、system 或 developer。输入快捷消息的 content 可以是字符串,也可以是内容块数组;详细类型通过
type: "message" 标识。
[ { "role": "user", "content": [ { "type": "input_text", "text": "描述这张图片。" }, { "type": "input_image", "image_url": "https://www.example.com/example.jpg", "detail": "auto" } ] }]| 内容类型 | 主要字段 | 说明 |
|---|---|---|
input_text | text | 文本 |
input_image | image_url / file_id、detail | 图片 URL、data URL 或已上传图片 |
input_file | file_id / file_url / file_data、filename | 文件引用、远程文件或内联文件数据;使用符合当前文件输入要求的一种来源 |
返回的助手消息里可能是 output_text,也可能是 refusal。把已经生成的输出项用于后续轮次时,保留它的原始结构。
工具结果与引用
input 还接受 function_call_output、自定义工具结果、计算机操作结果、历史工具调用与推理项等。item_reference 通过 id
引用已有项。
函数结果示例:
{ "model": "gpt-6-astra", "previous_response_id": "resp_weather_example", "input": [ { "type": "function_call_output", "call_id": "call_weather_1", "output": "{\"temperature_c\":22,\"condition\":\"晴\"}" } ]}注意,call_id 对应的是模型发起的调用,不是函数调用项自己的 id。
多轮状态
多轮状态可以自己维护,也可以交给服务端托管。自己维护时,把需要保留的历史输入和 output 项继续放进下一次 input;交给服务端时,用
previous_response_id 接上一条响应,或用 conversation 接一个会话。这两个参数互斥,不能同时传。
{ "model": "gpt-6-astra", "previous_response_id": "resp_example", "instructions": "继续用中文简短回答。", "input": "HTTPS 多了什么?"}引用上一条响应时,历史输入仍参与上下文与用量计算。
返回对象
查看返回 JSON 示例
{ "id": "resp_example", "object": "response", "created_at": 1792454400, "status": "completed", "model": "gpt-6-astra", "error": null, "incomplete_details": null, "output": [ { "id": "msg_example", "type": "message", "status": "completed", "role": "assistant", "content": [ { "type": "output_text", "text": "HTTP 是客户端和服务器交换请求与响应的协议。", "annotations": [] } ] } ], "usage": { "input_tokens": 20, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 15, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 35 }}Response 字段
| 字段 | 说明 |
|---|---|
id、object | 响应标识;object 固定为 response |
created_at、completed_at | Unix 秒级时间;完成时间在对应状态下出现 |
model | 实际使用的模型 |
status | queued、in_progress、completed、failed、cancelled 或 incomplete |
error | 生成错误,包含 code、message,成功时通常为空 |
incomplete_details | 未完成的原因,如 max_output_tokens、max_messages、content_filter;部分传输流程还会使用 steered |
output | 输出项数组,可能同时出现推理、工具调用和消息 |
usage | 输入、输出、缓存、推理及总 token 数 |
instructions | 生效的指令 |
conversation、previous_response_id | 关联会话与前一条响应 |
tools、tool_choice、parallel_tool_calls、max_tool_calls | 生效的工具配置 |
text、reasoning | 生效的文本、推理配置 |
temperature、top_p、top_logprobs、max_output_tokens | 生成配置 |
background、service_tier | 执行方式与实际处理等级 |
metadata、prompt、safety_identifier、user | 元数据、模板引用及用户标识 |
prompt_cache_key、prompt_cache_retention、prompt_cache_options | 缓存配置 |
prompt_cache_diagnostics | 请求缓存比较时的诊断结果 |
moderation、access_programs | 审核结果与实际访问计划 |
truncation | 输入截断策略 |
HTTP 返回的文本位于 output 消息项的 content 中,筛选 type: "output_text" 后读取 text。部分 SDK 的 output_text
是聚合属性。
输出项类型
| 类型 | 主要字段或用途 |
|---|---|
message | id、role、status、content[] |
function_call | id、call_id、name、字符串 arguments、status |
custom_tool_call | call_id、name、自由文本 input |
reasoning | id、summary[]、可选 encrypted_content,以及模型支持的推理内容 |
web_search_call | 搜索动作、状态及可选来源 |
file_search_call | 查询、状态和按需包含的搜索结果 |
code_interpreter_call | 容器、代码、执行状态和结果 |
computer_call | 计算机操作动作、调用 ID 与安全检查 |
mcp_call、mcp_list_tools、mcp_approval_request | 远程 MCP 调用、工具目录及审批 |
image_generation_call | 图片生成状态与结果 |
local_shell_call、shell_call、apply_patch_call | 受支持环境中的 Shell 或文件补丁调用 |
tool_search_call | 工具搜索及延迟加载相关输出 |
compaction | 上下文压缩项,应按原始类型保存和回传 |
output_text.annotations 可以包含文件引用、URL 引用、文件路径或容器文件引用,具体结构由注解类型区分。
工具定义
函数工具
函数的 name、parameters 等字段直接放在工具对象上。
{ "model": "gpt-6-astra", "input": "杭州现在的天气如何?", "tools": [ { "type": "function", "name": "get_weather", "description": "查询指定城市的当前天气。", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false }, "strict": true } ], "tool_choice": "auto"}模型产生 function_call 后,客户端读取 arguments、校验并执行,再用 function_call_output 回传。
工具类型目录
| 配置类型 | 配置与执行要点 |
|---|---|
function | 客户端执行;name、parameters、description、strict |
custom | 客户端接收自由文本;name、description、format,格式可为普通文本或 grammar |
web_search / web_search_preview | 服务端搜索;支持范围、过滤器、近似位置等随工具版本变化 |
file_search | 指定 vector_store_ids,可配置 max_num_results、filters、ranking_options |
code_interpreter | 配置 container,使用已有容器或自动容器及其文件配置 |
image_generation | 图片大小、质量、格式、背景等配置,输出为对应生成项 |
computer_use_preview / computer | 屏幕尺寸与运行环境;客户端负责执行操作和回传结果 |
mcp | server_label、服务器或连接器、允许工具、认证与审批配置 |
local_shell / shell | 客户端或托管环境执行;按工具类型处理结果与权限 |
apply_patch | 文件修改操作,必须由实际执行环境校验和应用 |
tool_search | 按需查找并加载工具,支持范围取决于模型 |
programmatic_tool_calling | 以程序方式编排工具,要求相应模型和运行环境 |
各工具的嵌套字段见参考文档中的官方 ToolParam 类型定义。
tool_choice
常用字符串为 none、auto、required。指定函数的结构是 {"type":"function","name":"get_weather"}。限制允许工具时使用
allowed_tools 类型及工具列表;MCP、自定义工具、Shell 等使用各自的选择对象。
格式化输出与高级配置
text
text.verbosity 为 low、medium、high。text.format.type 可以是 text、json_object 或 json_schema;JSON Schema
的定义如下:
{ "text": { "format": { "type": "json_schema", "name": "city_result", "strict": true, "schema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false } } }}reasoning
| 字段 | 取值与含义 |
|---|---|
effort | none、minimal、low、medium、high、xhigh、max;按模型选择 |
summary | auto、concise、detailed,请求可公开的推理摘要 |
context | auto、current_turn、all_turns,控制后续轮次使用哪些推理项 |
mode | 推理执行模式,如 standard 或 pro,依赖模型能力 |
generate_summary | 旧字段,使用 summary |
无状态传递推理项时,可用 include: ["reasoning.encrypted_content"] 获取加密项并原样回传。
include
可选路径包括 file_search_call.results、web_search_call.results、web_search_call.action.sources、
message.input_image.image_url、computer_call_output.output.image_url、code_interpreter_call.outputs、
reasoning.encrypted_content、message.output_text.logprobs。
缓存、审核与访问计划
prompt_cache_options 包含 mode(implicit / explicit)、ttl(30m)、prewarm、comparison_response_id
。其中预热和诊断需要相应能力;诊断可能返回缓存命中、未命中原因、比较对象不存在或不可用等结果。
moderation 指定审核 model,可配置 policy.input.mode 与 policy.output.mode 为 score 或 block。
access_programs.cyber 的类型包含 standard、daybreak_blue、daybreak_red。需要对应的访问权限。
流式事件
设置 stream: true 后,事件按类型区分生命周期、输出项、内容块、文本和工具参数。
event: response.createddata: {"type":"response.created","sequence_number":0,"response":{"id":"resp_example","object":"response","status":"in_progress","output":[]}}
event: response.output_text.deltadata: {"type":"response.output_text.delta","sequence_number":3,"item_id":"msg_example","output_index":0,"content_index":0,"delta":"你好","logprobs":[]}
event: response.output_text.donedata: {"type":"response.output_text.done","sequence_number":4,"item_id":"msg_example","output_index":0,"content_index":0,"text":"你好","logprobs":[]}
event: response.completeddata: {"type":"response.completed","sequence_number":7,"response":{"id":"resp_example","object":"response","status":"completed","output":[{"id":"msg_example","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"你好","annotations":[]}]}]}}示例省略了部分事件和 Response 字段,因此 sequence_number 不连续。
生命周期与内容事件
| 事件族 | 作用 |
|---|---|
response.created、response.queued、response.in_progress | 已创建、排队、生成中。具体事件由执行模式决定 |
response.completed | 本次生成成功完成,最终 Response 中可以包含用量 |
response.failed、response.incomplete | 失败或未完成,不能作为完整成功处理 |
response.output_item.added / .done | 创建或结束某个输出项 |
response.content_part.added / .done | 创建或结束消息中的内容块 |
response.output_text.delta / .done | 文本增量或完整文本 |
response.output_text.annotation.added | 为文本增加引用等注解 |
response.refusal.delta / .done | 拒绝内容 |
response.reasoning_summary_part.*、response.reasoning_summary_text.* | 推理摘要块及其文本 |
response.reasoning_text.* | 支持对应输出的推理文本事件 |
error | 流内错误;HTTP 连接已经成功也仍可能收到 |
工具与专用事件
函数参数使用 response.function_call_arguments.delta / .done;自定义工具使用 response.custom_tool_call_input.delta /
.done。内置工具还有搜索、代码解释器、图片生成、MCP、Shell、补丁和工具搜索各自的状态及增量事件,完整名称见官方事件类型目录。
用 item_id / output_index 定位输出项,用 content_index 定位内容块。把对应的 delta 拼起来;.done
已经带完整结果,不要再追加一次。工具参数收全后再解析 JSON。Responses 的终止以生命周期事件为准,没有 [DONE] 标记。
错误
HTTP 错误通常返回 error 对象;已创建的 Response 还可能通过 status: "failed" 与 error 表达失败,或通过
status: "incomplete" 与 incomplete_details 表达未完成。
{ "error": { "message": "The request contains an unsupported parameter.", "type": "invalid_request_error", "param": "reasoning", "code": "unsupported_parameter" }}400 检查字段与模型能力,401 检查密钥,403 检查权限,404 检查模型或资源可见性,429 区分限流和额度,5xx
根据服务状态有限退避重试。
参考文档
创建 Message
POST https://api.anthropic.com/v1/messages
调用这个接口,提交对话消息,得到一条包含内容块数组的助手消息。系统指令放在顶层 system,常规对话放在 messages。
POST /v1/messages HTTP/1.1Host: api.anthropic.comx-api-key: <ANTHROPIC_API_KEY>anthropic-version: 2023-06-01Content-Type: application/json
{ "model": "claude-opus-5-5", "max_tokens": 1024, "system": "用中文简短回答。", "messages": [{"role": "user", "content": "什么是 HTTP?"}]}请求头
| 名称 | 必填 | 说明 |
|---|---|---|
x-api-key | 是 | Anthropic API 密钥 |
anthropic-version | 建议显式指定 | API 版本,示例使用 2023-06-01 |
Content-Type | 是 | application/json |
anthropic-beta | 否 | 特定 Beta 能力的标识 |
anthropic-workspace-id | 否 | 需要从多个 Workspace 中选择时使用;SDK 的 workspace_id 参数映射到此头 |
anthropic-user-profile-id | 否 | 请求归属的用户档案,需要相应 Beta 权限;SDK 参数名为 user_profile_id |
响应头里的 request-id 用于定位请求;限流信息见 retry-after 和 anthropic-ratelimit-*。
请求参数
必填字段
| 字段 | 类型 | 说明 |
|---|---|---|
model | string | 模型 ID |
max_tokens | integer | 最大生成 token 数。模型可以提前结束;在支持缓存预热的配置里,也可以用 0 请求预热 |
messages | object[] | 对话消息,包含 role 与 content |
指令、生成与工具
| 字段 | 类型 | 说明 |
|---|---|---|
system | string / object[] | 系统提示词,数组形式为文本块 |
stop_sequences | string[] | 自定义停止序列;命中时在响应中返回 stop_reason 与 stop_sequence |
stream | boolean | 是否通过 SSE 增量返回 |
thinking | object | 推理配置,支持的类型与默认行为由模型决定 |
output_config | object | 输出格式与 effort 配置 |
tools | object[] | 客户端工具和服务端工具定义 |
tool_choice | object | 自动选择、强制调用、指定工具或禁用工具 |
缓存与执行配置
| 字段 | 类型 | 说明 |
|---|---|---|
cache_control | object / null | 顶层自动缓存控制,将标记应用到最后一个可缓存块 |
metadata | object | 请求元数据,例如 user_id |
container | object / null | 容器引用与复用配置,适用于支持容器工具的请求 |
diagnostics | object / null | 通过 previous_message_id 请求缓存差异诊断 |
inference_geo | string / null | 推理处理区域;省略时使用 Workspace 默认配置 |
service_tier | string | auto 或 standard_only,控制是否使用可用的优先容量 |
speed | string / null | standard 或 fast;部分模型需要相应 Beta 头 |
消息与内容块
messages[]
常规对话使用 user、assistant 两种角色。content 可以是字符串,也可以是内容块数组;字符串等价于只有一个 text 块。
[ { "role": "user", "content": "你好,Claude。" }, { "role": "assistant", "content": [ { "type": "text", "text": "你好。" } ] }]连续的同角色消息可能合并为同一轮;助手消息预填能不能用,取决于模型。
输入块目录
type | 主要字段 | 说明 |
|---|---|---|
text | text、cache_control、可选 citations | 普通文本 |
image | source、cache_control | 图片来源为 URL、base64 或受支持的文件引用 |
document | source、title、context、citations、cache_control | PDF、文本或其他受支持的文档来源 |
search_result | source、title、content、引用设置 | 调用方提供的检索结果,供引用与生成使用 |
thinking | thinking、signature | 历史推理块,继续对话时应原样回传 |
redacted_thinking | data | 已隐去的推理内容,回传时保留原值 |
tool_use | id、name、对象形式的 input | 助手要求客户端执行工具 |
tool_result | tool_use_id、content、可选 is_error | 用户侧回传工具执行结果 |
server_tool_use | 工具名称、标识和输入 | 服务端工具调用 |
web_search_tool_result、web_fetch_tool_result | 工具关联 ID、结果或错误 | 服务端搜索与抓取结果 |
code_execution_tool_result | 代码执行结果或错误 | 由对应服务端工具产生 |
bash_code_execution_tool_result、text_editor_code_execution_tool_result | 终端或编辑器结果 | 按各自结果类型处理 |
tool_search_tool_result | 工具搜索结果 | 返回按需加载的工具引用等内容 |
container_upload | 上传到容器的文件引用 | 用于对应容器流程 |
图片
{ "role": "user", "content": [ { "type": "image", "source": { "type": "url", "url": "https://www.example.com/example.jpg" } }, { "type": "text", "text": "描述这张图片。" } ]}base64 来源包含 type: "base64"、media_type、data。data 只放 base64 编码,不带 data URL 前缀。图片尺寸、数量和 MIME
类型受当前模型约束。
文档与引用
{ "type": "document", "source": { "type": "text", "media_type": "text/plain", "data": "HTTP 采用请求与响应的交互方式。" }, "title": "HTTP 摘要", "citations": { "enabled": true }}文档来源还包括 URL PDF、base64 PDF、内容块和文件引用。引用位置可以是字符区间、页码、内容块区间或搜索结果位置,由
citations[].type 区分。
多轮消息
多轮消息要把模型看到的历史一起发过来。响应体里的 id 只是这条返回消息的标识,不能拿它自动恢复对话;继续工具轮次或服务端暂停的轮次时,把对应的助手内容按原始结构加回
messages。
{ "model": "claude-opus-5-5", "max_tokens": 1024, "system": "用中文简短回答。", "messages": [ { "role": "user", "content": "什么是 HTTP?" }, { "role": "assistant", "content": [ { "type": "text", "text": "HTTP 是请求与响应协议。" } ] }, { "role": "user", "content": "HTTPS 多了什么?" } ]}返回对象
查看返回 JSON 示例
{ "id": "msg_example", "type": "message", "role": "assistant", "model": "claude-opus-5-5", "content": [ { "type": "text", "text": "HTTP 是客户端和服务器交换请求与响应的协议。" } ], "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 20, "output_tokens": 15 }}Message 字段
| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 消息标识 |
type | string | 固定为 message |
role | string | 固定为 assistant |
model | string | 使用的模型 |
content | object[] | 按类型区分的内容块,可以混合文本、工具调用和推理等 |
stop_reason | string / null | 结束原因;流式开始阶段可能为空 |
stop_sequence | string / null | 实际命中的自定义停止序列 |
stop_details | object / null | 结束原因的额外结构化细节,例如拒绝信息 |
usage | object | token、缓存、服务等级和工具用量 |
container | object / null | 本次使用的容器信息 |
diagnostics | object / null | 请求开启诊断时的差异信息,未发现差异也可能为空 |
stop_reason
| 值 | 含义 |
|---|---|
end_turn | 模型自然结束当前轮次 |
max_tokens | 达到请求或模型的输出上限;内容可能未完成 |
stop_sequence | 命中自定义停止序列 |
tool_use | 需要处理工具调用 |
pause_turn | 长任务暂停;按服务端工具的继续方式发送后续请求 |
refusal | 模型拒绝请求 |
model_context_window_exceeded | 达到模型上下文限制 |
输出块
文本位于 content 数组的 text 块中。其他块包括 thinking、redacted_thinking、tool_use、server_tool_use
、搜索、抓取、代码执行和工具搜索结果等,按 type 解析。
usage
| 字段 | 说明 |
|---|---|
input_tokens | 当前用量定义中的普通输入 token |
output_tokens | 输出 token 总量,包含相关推理用量,是计费用量的总口径 |
cache_creation_input_tokens | 用于创建缓存的输入 token |
cache_read_input_tokens | 从缓存读取的输入 token |
cache_creation | 按缓存 TTL 区分的写入明细 |
output_tokens_details | 输出分类明细,不应再次与 output_tokens 相加 |
server_tool_use | 服务端工具请求次数等 |
service_tier | 实际服务等级,如 standard、priority、batch |
inference_geo、speed | 实际处理区域与速度模式 |
总输入用量要把普通输入、缓存写入和缓存读取都算进去。
工具定义
客户端工具
{ "model": "claude-opus-5-5", "max_tokens": 1024, "messages": [ { "role": "user", "content": "杭州现在的天气如何?" } ], "tools": [ { "name": "get_weather", "description": "查询指定城市的当前天气。", "input_schema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false } } ], "tool_choice": { "type": "auto" }}| 工具字段 | 必填 | 说明 |
|---|---|---|
name | 是 | 工具名,与返回的 tool_use.name 对应 |
input_schema | 是 | 输入的 JSON Schema,根类型为对象 |
description | 否 | 描述工具用途、输入约束及使用条件 |
strict | 否 | 严格验证工具名称与输入,要求模型支持 |
type | 否 | 自定义工具可使用 custom |
cache_control | 否 | 工具定义的缓存断点 |
defer_loading | 否 | 延迟加载,配合工具搜索 |
allowed_callers | 否 | 允许直接调用或指定代码执行环境调用 |
input_examples | 否 | 示例输入对象数组 |
eager_input_streaming | 否 | 是否尽早流式发送输入参数,默认行为由相关 Beta 配置决定 |
tool_choice
{"type":"auto"} 让模型选择;{"type":"any"} 要求调用工具;{"type":"tool","name":"get_weather"} 指定工具;
{"type":"none"} 禁用工具。支持相应配置时,可通过 disable_parallel_tool_use 禁止并行工具使用。
tool_use 与 tool_result
模型的工具输入已经是 JSON 对象。客户端校验、执行后,把原助手块和工具结果一起加入历史,结果放在后续的 user 消息中。
[ { "role": "assistant", "content": [ { "type": "tool_use", "id": "toolu_weather_1", "name": "get_weather", "input": { "city": "杭州" } } ] }, { "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "toolu_weather_1", "content": "{\"temperature_c\":22,\"condition\":\"晴\"}" } ] }]回传工具结果时,有几条顺序要求:
- 工具结果要紧跟对应的工具调用;
- 在同一条用户消息里,工具结果排在普通文本之前;
- 并行调用的每个结果都要对应回传;
- 历史推理块及其签名按原样回传。
工具失败时可以设置 is_error: true。
服务端工具目录
服务端工具以带版本的 type 选择 Schema,name 使用对应工具名。当前类型目录包含网页搜索、网页抓取、代码执行、Bash、文本编辑器、记忆、工具搜索以及浏览器或计算机工具集。
例如网页搜索类型 web_search_20250305 配合 name: "web_search",还可包含使用次数、域名和位置配置。完整版本集合和字段见官方
ToolUnionParam 目录。
推理、结构化输出与缓存
thinking
自适应模式的结构是 {"type":"adaptive"}。手动扩展推理使用 {"type":"enabled","budget_tokens":2048},预算至少为
1024;模型是否接受、预算与 max_tokens 怎么配合,要按模型确认。关闭模式为 {"type":"disabled"}。
输出里可能带 signature 的 thinking,也可能是 redacted_thinking,继续对话时原样回传。
output_config
effort 的类型包含 low、medium、high、xhigh、max,模型只接受其中一部分。JSON 输出格式放在 format:
{ "output_config": { "format": { "type": "json_schema", "schema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": [ "city" ], "additionalProperties": false } } }}除了 JSON 本身,还要检查 stop_reason:达到 token 上限时,文本可能不是完整的 JSON。
cache_control 与诊断
缓存标记的结构是 {"type":"ephemeral"},可使用支持的 ttl(如 5m、1h
)。顶层标记自动作用于最后一个可缓存块,显式标记也可以放在文本、文档、系统块或工具定义等支持的位置。缓存命中还依赖模型、工具、系统提示和内容前缀是否一致。
diagnostics 可以包含 previous_message_id,用于比较前一次请求的缓存差异;它不会恢复那次对话。
流式事件
请求设置 stream: true。常见顺序为 message_start,随后多组内容块事件,再到 message_delta 与 message_stop。服务端还可能发送
ping 或错误。
event: message_startdata: {"type":"message_start","message":{"id":"msg_example","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"output_tokens":1}}}
event: content_block_startdata: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_deltadata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"你好"}}
event: content_block_stopdata: {"type":"content_block_stop","index":0}
event: message_deltadata: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
event: message_stopdata: {"type":"message_stop"}事件对象
| 事件 | 主要字段 | 处理 |
|---|---|---|
message_start | message | 初始化消息和初始用量 |
content_block_start | index、content_block | 为索引创建内容块,保留类型和已有字段 |
content_block_delta | index、delta | 更新对应块,按增量类型解析 |
content_block_stop | index | 对应内容块结束 |
message_delta | delta、usage | 更新结束原因和累计用量 |
message_stop | type | 消息流结束 |
ping | type | 保活,不追加到内容 |
error | error.type、error.message | 流内错误,不能当作正常结束 |
content_block_delta.delta
| 类型 | 增量字段 | 处理 |
|---|---|---|
text_delta | text | 追加到文本块 |
input_json_delta | partial_json | 追加字符串,工具块完整后再解析为 JSON |
thinking_delta | thinking | 累计推理块内容 |
signature_delta | signature | 保存推理签名 |
citations_delta | citation | 为文本块追加引用 |
用 index 定位内容块,不能把所有增量拼成一个字符串。流里的用量是累计值,不要把每次 message_delta.usage.output_tokens再相加。
错误
{ "type": "error", "error": { "type": "invalid_request_error", "message": "The request is not valid." }, "request_id": "req_example"}| HTTP 状态 | 错误类型 | 检查方向 |
|---|---|---|
400 | invalid_request_error | 参数、消息结构、模型能力 |
401 | authentication_error | API 密钥 |
402 | billing_error | 账户计费状态与额度 |
403 | permission_error | 资源或功能权限 |
404 | not_found_error | 资源或模型是否存在且可访问 |
413 | request_too_large | 请求体大小限制 |
429 | rate_limit_error | 请求和 token 限速,结合 retry-after |
500 | api_error | 服务端内部错误 |
529 | overloaded_error | 服务过载,有限次数退避重试 |
