发送消息
用 Anthropic Messages 格式发送对话消息,返回模型回复;支持流式输出。
/model/v1/messages● 支持请求体
modelstring必填◐ 部分支持Body param: The model that will complete your prompt. See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
deepseek-v4-pro、glm-5.3-flash、qwen3.8-flash、claude-opus-5 可调用;deepseek-v4-flash 在此协议面返回 400。
messagesarray必填◐ 部分支持Body param: Input messages. Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn. Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages. If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response. Example with a single `user` message: ```json [{ "role": "user", "content": "Hello, Claude" }] ``` Example with multiple conversational turns: ```json [ { "role": "user", "content": "Hello there." }, { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, { "role": "user", "content": "Can you explain LLMs in plain English?" } ] ``` Example with a partially-filled response from Claude: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `"text"`. The following input messages are equivalent: ```json { "role": "user", "content": "Hello, Claude" } ``` ```json { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } ``` See [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). Note that if you want to include a [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. There is a limit of 100,000 messages in a single request.
文本和工具往返生效;document 的托管 file_id 返回 400,qwen3.8-flash 可读取内联 PDF;图片有模型尺寸限制。
▸ 展开子字段(2)
contentstring | array必填Message content: a plain string (shorthand for one text block) or an array of content blocks such as text, image, document, tool_use and tool_result.
rolestring必填Who produced the message. Use user for your turns and assistant to replay earlier model turns; system-role messages are accepted by the shape but system instructions normally go in the top-level system field.
max_tokensnumber必填Body param: The maximum number of tokens to generate before stopping. Note that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. Set to `0` to populate the [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache) without generating a response. Different models have different maximum values for this parameter. See [models](https://platform.claude.com/docs/en/about-claude/models/overview) for details.
限制输出 token,思考也占用预算。
streamboolean可选◐ 部分支持Body param: Whether to incrementally stream the response using server-sent events. See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) for details.
流式正文和工具事件可用;可能在正文前出现额外 message_delta,message_start 的用量为 0。
systemstring | array可选Body param: System prompt. A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
已验证生效。
temperaturenumber可选Sampling temperature between 0 and 1; defaults are model specific.
top_pnumber可选Nucleus sampling: only tokens within this cumulative probability are considered.
toolsarray可选Body param: Definitions of tools that the model may use. If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks. There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). Each tool definition includes: - `name`: Name of the tool. - `description`: Optional, but strongly-recommended description of the tool. - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks. For example, if you defined `tools` as: ```json [ { "name": "get_stock_price", "description": "Get the current stock price for a given ticker symbol.", "input_schema": { "type": "object", "properties": { "ticker": { "type": "string", "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." } }, "required": ["ticker"] } } ] ``` And then asked the model "What's the S&P 500 at today?", the model might produce `tool_use` content blocks in the response like this: ```json [ { "type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_stock_price", "input": { "ticker": "^GSPC" } } ] ``` You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an input, and return the following back to the model in a subsequent `user` message: ```json [ { "type": "tool_result", "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "content": "259.75 USD" } ] ``` Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output. See our [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) for more details.
已验证生效。
tool_choiceobject可选◐ 部分支持Body param: How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
qwen3.8-flash 四种模式生效;deepseek-v4-pro 忽略 any/tool/none;glm-5.3-flash 忽略 none。
▸ 展开子字段(3)
typestring必填Disable tool calls for this request.
disable_parallel_tool_useboolean可选○ 当前不生效Whether to disable parallel tool use. Defaults to `false`. If set to `true`, the model will output exactly one tool use.
接受但当前不生效。true 仍可能返回多个工具调用。
namestring必填The name of the tool to use.
cache_controlobject可选◐ 部分支持Body param: Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request.
deepseek-v4-pro、qwen3.8-flash、glm-5.3-flash 有隐式缓存命中,但不能据此确认标记生效;claude-opus-5 未命中缓存,ttl=1h 未见效果。
▸ 展开子字段(2)
typestring必填Always `ephemeral`. Discriminator that marks this object as a CacheControlEphemeral in a `type`-tagged union.
ttlstring可选The time-to-live for the cache control breakpoint. This may be one the following values: - `5m`: 5 minutes - `1h`: 1 hour Defaults to `5m`. See [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for details.
▸ 更多参数(16)
containerstring | object可选○ 当前不生效接受并忽略 container;平台尚未实现此能力。
▸ 展开子字段(2)
idstring可选Container id
skillsarray可选List of skills to load in the container
inference_geostring可选○ 当前不生效接受并忽略 inference_geo;平台尚未实现此能力。
metadataobject可选◐ 部分支持Body param: An object describing metadata about the request.
接受 metadata;metadata.user_id 由同协议线路传递,不承诺上游回显。
▸ 展开子字段(1)
user_idstring可选An external identifier for the user who is associated with the request. This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.
output_configobject可选Body param: Configuration options for the model's output, such as the output format.
▸ 展开子字段(2)
effortstring可选◐ 部分支持All possible effort levels.
deepseek-v4-pro 仅 high/xhigh 可用,其余返回 400;qwen3.8-flash 全档返回 400;glm-5.3-flash 接受各档但消耗不随档位单调变化。
formatobject可选◐ 部分支持A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
json_schema 在 deepseek-v4-pro、qwen3.8-flash 生效;glm-5.3-flash 与 thinking 同传返回 400。
service_tierstring可选○ 当前不生效接受并忽略 service_tier;平台尚未实现此能力。
stop_sequencesarray可选◐ 部分支持Body param: Custom text sequences that will cause the model to stop generating. Our models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `"end_turn"`. If you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `"stop_sequence"` and the response `stop_sequence` value will contain the matched stop sequence.
deepseek-v4-pro、qwen3.8-flash 生效;glm-5.3-flash 文本截断但 stop_reason 和 stop_sequence 未准确反映。
thinkingobject可选◐ 部分支持Body param: Configuration for enabling Claude's extended thinking. When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit. See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for details.
disabled 在 deepseek-v4-pro、qwen3.8-flash 生效;glm-5.3-flash 携带任何 thinking 都返回 400。adaptive 在已测的 deepseek-v4-pro、qwen3.8-flash 也返回 400。
▸ 展开子字段(3)
budget_tokensnumber必填◐ 部分支持Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality. Must be ≥1024 and less than `max_tokens`. See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for details.
deepseek-v4-pro、qwen3.8-flash 接受,但预算不构成可靠上限;glm-5.3-flash 返回 400。
typestring必填Let the model choose its reasoning budget, subject to output_config.effort when supplied.
displaystring可选○ 当前不生效Controls how thinking content appears in the response. When set to `summarized`, thinking is returned normally. When set to `omitted`, thinking content is redacted but a signature is returned for multi-turn continuity. Defaults to `summarized`.
接受但当前不生效。omitted 仍返回完整思考内容。
top_knumber可选Sample only from the top K options for each token.
context_managementobject可选○ 当前不生效接受并忽略 context_management;平台尚未实现此能力。
diagnosticsobject可选○ 当前不生效接受并忽略 diagnostics;平台尚未实现此能力。
mcp_serversarray可选○ 当前不生效接受并忽略 mcp_servers;平台尚未实现此能力。
speedstring可选○ 当前不生效接受并忽略 speed;平台尚未实现此能力。
output_formatobject可选○ 当前不生效接受并忽略此旧字段;结构化输出使用 output_config.format。
compactionobject可选○ 未支持已识别 compaction;尚未实现,传入返回 400 并明确说明不支持。
fallback_credit_tokenstring可选○ 未支持已识别 fallback_credit_token;尚未实现,传入返回 400 并明确说明不支持。
fallbacksstring可选○ 未支持已识别 fallbacks;尚未实现,传入返回 400 并明确说明不支持。
返回
200
stream=true 时以 SSE 增量返回(text/event-stream)。
未知顶层字段原样转发给同协议上游,由上游决定是否接受;已声明字段的类型与取值范围仍会校验,不合法时返回 400 并点名字段。
鉴权、限流、参数校验等平台错误按 problem+json 返回;OCR 的错误也为 problem+json,其它模型调用的错误按该端点所属格式(OpenAI 或 Anthropic)返回,参见 错误码
响应
HTTP 200
Message created
application/json
| 名称 | 类型 | 说明 |
|---|---|---|
| id | string | Unique object identifier. The format and length of IDs may change over time. |
| container | null | object | Information about the container used in the request (for the code execution tool) |
| container.id | string | Identifier for the container used in this request |
| container.expires_at | string | The time at which the container will expire. |
| container.skills | null | array<object> | Skills loaded in the container |
| content | array<object> | Content generated by the model. This is an array of content blocks, each of which has a `type` that determines its shape. Example: ```json [{ "type": "text", "text": "Hi, I'm Claude." }] ``` If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output. For example, if the input `messages` were: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Then the response `content` might be: ```json [{ "type": "text", "text": "B)" }] ``` |
| content[].citations | null | array<object> | Citations supporting the text block. The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`. |
| content[].text | string | The text generated by the model. |
| content[].type | string | Always `text`. Discriminator that marks this object as a TextBlock in a `type`-tagged union. / Always `thinking`. Discriminator that marks this object as a ThinkingBlock in a `type`-tagged union. / Always `redacted_thinking`. Discriminator that marks this object as a RedactedThinkingBlock in a `type`-tagged union. / Always `tool_use`. Discriminator that marks this object as a ToolUseBlock in a `type`-tagged union. / Always `server_tool_use`. Discriminator that marks this object as a ServerToolUseBlock in a `type`-tagged union. / Always `web_search_tool_result`. Discriminator that marks this object as a WebSearchToolResultBlock in a `type`-tagged union. / Always `web_fetch_tool_result`. Discriminator that marks this object as a WebFetchToolResultBlock in a `type`-tagged union. / Always `code_execution_tool_result`. Discriminator that marks this object as a CodeExecutionToolResultBlock in a `type`-tagged union. / Always `bash_code_execution_tool_result`. Discriminator that marks this object as a BashCodeExecutionToolResultBlock in a `type`-tagged union. / Always `text_editor_code_execution_tool_result`. Discriminator that marks this object as a TextEditorCodeExecutionToolResultBlock in a `type`-tagged union. / Always `tool_search_tool_result`. Discriminator that marks this object as a ToolSearchToolResultBlock in a `type`-tagged union. / Always `container_upload`. Discriminator that marks this object as a ContainerUploadBlock in a `type`-tagged union. |
| content[].signature | string | A value used to verify that this thinking block was generated by Claude when it is passed back to the API. This is an opaque field and should not be interpreted or parsed. When passing thinking blocks back to the API (required when using tools with extended thinking), pass them back exactly as received, with this field intact. See extended thinking for details. |
| content[].thinking | string | The text of Claude's thinking process for this block. |
| content[].data | string | The contents of this redacted thinking block, returned when portions of the model's thinking were safety-redacted. This field is opaque and encrypted, with no readable content. Pass `redacted_thinking` blocks back to the API unchanged when continuing a multi-turn conversation. See extended thinking for details. |
| content[].id | string | Id of the tool call; send it back as tool_use_id in the tool_result block that answers it. / Id of the server tool call; the matching result block repeats it as tool_use_id. |
| content[].caller | object | Which party invoked the tool: the model directly or a code execution tool. / Which party invoked the server tool: the model directly or a code execution tool. / Which party invoked the search: the model directly or a code execution tool. / Which party invoked the fetch: the model directly or a code execution tool. |
| content[].input | any | Arguments the model chose, as a JSON object that follows the tool's input_schema. / Arguments the model passed to the server tool, as a JSON object. |
| content[].name | string | Name of the tool the model wants to call. / Name of the server tool the model called, such as web_search, web_fetch or code_execution. |
| content[].toolset_name | null | string | For a toolset member tool_use, the toolset family. |
| content[].content | object | array<object> | object | object | object | object | object | Search results (array of web_search_result blocks) or an error object. / The fetched document or an error object. / Result of the code execution: a result block, an encrypted result block, or an error object. / Result of the bash command: a result block or an error object. / Result of the text editor command: a view, create or str_replace result block, or an error object. / Result of the tool search: a search result block that lists tool references, or an error object. |
| content[].tool_use_id | string | Id of the web_search server tool call this result belongs to. / Id of the web_fetch server tool call this result belongs to. / Id of the code_execution server tool call this result belongs to. / Id of the bash_code_execution server tool call this result belongs to. / Id of the text_editor_code_execution server tool call this result belongs to. / Id of the tool search server tool call this result belongs to. |
| content[].file_id | string | Id of the file that was uploaded into the code execution container. |
| model | string | The model that will complete your prompt. See models for additional details and options. |
| role | string | Conversational role of the generated message. This will always be `"assistant"`. |
| stop_details | null | object | Structured information about a refusal. |
| stop_details.category | null | string | The policy category that triggered a refusal. - `cyber` - The request could enable cyber harm, such as malware or exploit development. Benign cybersecurity work can also trigger this category. - `bio` - The request could enable biological harm, such as dangerous lab methods. Beneficial life sciences work can also trigger this category. - `frontier_llm` - The request could assist the development of competing AI models, which is restricted under Anthropic's commercial terms. Benign machine learning work can also trigger this category. - `reasoning_extraction` - The request asks the model to reproduce its internal reasoning in the response text. To get reasoning in a structured form instead, use adaptive thinking. - `general_harms` - The request could be related to an area that was determined as harmful. Benign work might sometimes trigger this category. |
| stop_details.explanation | null | string | Human-readable explanation of the refusal. This text is not guaranteed to be stable. `null` when no explanation is available for the category. |
| stop_details.type | string | Always `refusal`. Discriminator that marks this object as a RefusalStopDetails in a `type`-tagged union. |
| stop_reason | null | string | The reason that we stopped. This may be one the following values: - `"end_turn"`: the model reached a natural stopping point - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - `"tool_use"`: the model invoked one or more tools - `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue. - `"refusal"`: when streaming classifiers intervene to handle potential policy violations - `"model_context_window_exceeded"`: we exceeded the model's context window In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise. |
| stop_sequence | null | string | Which custom stop sequence was generated, if any. This value will be a non-null string if one of your custom stop sequences was generated. |
| type | string | Object type. For Messages, this is always `"message"`. |
| usage | object | Billing and rate-limit usage. Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems. Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response. For example, `output_tokens` will be non-zero, even for an empty string response from Claude. Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. |
| usage.cache_creation | null | object | Breakdown of cached tokens by TTL |
| usage.cache_creation_input_tokens | null | number | The number of input tokens used to create the cache entry. |
| usage.cache_read_input_tokens | null | number | The number of input tokens read from the cache. |
| usage.inference_geo | null | string | The geographic region where inference was performed for this request. |
| usage.input_tokens | number | The number of input tokens which were used. |
| usage.output_tokens | number | The number of output tokens which were used. |
| usage.output_tokens_details | null | object | Breakdown of output tokens by category. `output_tokens` remains the inclusive, authoritative total used for billing. This object provides a read-only decomposition for observability — for example, how many of the billed output tokens were spent on internal reasoning that may have been summarized before being returned to you. |
| usage.server_tool_use | null | object | The number of server tool requests. |
| usage.service_tier | null | string | If the request used the priority, standard, or batch tier. |
text/event-stream — chunk / 事件对象
| 名称 | 类型 | 说明 |
|---|---|---|
| id | string | Optional id of the server-sent event. |
| event | string | Name of the server-sent event. |
| data | object | 完整 SDK RawMessageStreamEvent union |
| data.delta | object | Final fields of the message sent with message_delta: why generation stopped and the container. / The incremental change to the content block at index. |
| data.type | string | Always `message_delta`. Discriminator that marks this object as a RawMessageDeltaEvent in a `type`-tagged union. / Always `content_block_delta`. Discriminator that marks this object as a RawContentBlockDeltaEvent in a `type`-tagged union. / Always `message_start`. Discriminator that marks this object as a RawMessageStartEvent in a `type`-tagged union. / Always `message_stop`. Discriminator that marks this object as a RawMessageStopEvent in a `type`-tagged union. / Always `content_block_start`. Discriminator that marks this object as a RawContentBlockStartEvent in a `type`-tagged union. / Always `content_block_stop`. Discriminator that marks this object as a RawContentBlockStopEvent in a `type`-tagged union. |
| data.usage | object | Billing and rate-limit usage. Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems. Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response. For example, `output_tokens` will be non-zero, even for an empty string response from Claude. Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. |
| data.index | number | Zero-based index of the content block this delta applies to. / Zero-based index of the content block that starts. / Zero-based index of the content block that ends. |
| data.message | object | The complete Message object being started; its content is empty at message_start and filled by the following content_block events. |
| data.content_block | object | The content block as it starts, with empty text or input to be filled by deltas. |