POST/v1/messages

Create a Message

Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.

The Messages API can be used for either single queries or stateless multi-turn conversations.

Learn more about the Messages API in our user guide

  • IdempotentThe SDK sends Idempotency-Key, so a retried request is only applied once.

3 parameters · 18 body fields
anthropic-versionstringoptional
The version of the Claude API you want to use. Read more about versioning and our version history [here](https://platform.claude.com/docs/en/api/versioning).
anthropic-user-profile-idstringoptional
The user profile ID to attribute this request to. Use when acting on behalf of a party other than your organization. Requires the `user-profiles` beta header.
anthropic-workspace-idstringoptional
Optional header to select the Workspace for this request. The value is a Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). Only needed for credentials that can act on more than one Workspace. A credential that belongs to a specific Workspace may omit it; if sent, it must match that Workspace.
modelstringrequired
The model that will complete your prompt. See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
messagesarray<InputMessage>required
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.
cache_controlobjectoptional
Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request.
containerobjectoptional
Container identifier for reuse across requests.
inference_geostringoptional
Specifies the geographic region for inference processing. If not specified, the workspace's `default_inference_geo` is used.
max_tokensintegerrequired
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.
metadataobjectoptional
An object describing metadata about the request.
output_configobjectoptional
Configuration options for the model's output, such as the output format.
service_tierstringoptional
Determines whether to use priority capacity (if available) or standard capacity for this request. Anthropic offers different levels of service for your API requests. See [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for details.
Allowed:autostandard_only
stop_sequencesarray<string>optional
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.
streambooleanoptional
Whether to incrementally stream the response using server-sent events. See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) for details.
systemstringoptional
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).
temperaturenumberdeprecatedoptional
Amount of randomness injected into the response. Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks. Note that even with `temperature` of `0.0`, the results will not be fully deterministic.
thinkingobjectoptional
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.
tool_choiceobjectoptional
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.
toolsarray<Tool>optional
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.
top_kintegerdeprecatedoptional
Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). Recommended for advanced use cases only.
top_pnumberdeprecatedoptional
Use nucleus sampling. In nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. Recommended for advanced use cases only.

17 status codes
200Message object.
idstringrequired
Unique object identifier. The format and length of IDs may change over time.
typestringrequired
Object type. For Messages, this is always `"message"`.
Default:message
rolestringrequired
Conversational role of the generated message. This will always be `"assistant"`.
Default:assistant
contentarray<ResponseTextBlock>required
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)"}] ```
modelstringrequired
The model that will complete your prompt. See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
stop_reasonstringrequired
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.
Allowed:end_turnmax_tokensstop_sequencetool_usepause_turnrefusalmodel_context_window_exceeded
stop_sequencestringrequired
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.
Default:null
stop_detailsobjectrequired
Structured information about why model output stopped. This is `null` when the `stop_reason` has no additional detail to report.
Default:null
usageobjectrequired
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`.
containerobjectrequired
Information about the container used in this request. This will be non-null if a container tool (e.g. code execution) was used.
Default:null
400Invalid argument - The client specified an invalid argument
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
401Unauthenticated - The request does not have valid authentication credentials
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
403Permission denied - The caller does not have permission to execute the specified operation
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
404Not found - Some requested entity was not found
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
408Deadline exceeded - The deadline expired before the operation could complete
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
409Aborted - The operation was aborted due to concurrency issue
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
412Failed precondition - Operation was rejected because the system is not in required state
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
413Out of range - Operation was attempted past the valid range
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
429Resource exhausted - Some resource has been exhausted (rate limiting)
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
431Request header fields too large - Request metadata was too large
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
499Cancelled - The operation was cancelled by the client
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
500Internal - Internal server error
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
501Unimplemented - The operation is not implemented or supported
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
503Unavailable - The service is currently unavailable
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
504Deadline exceeded - Upstream service did not respond in time
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error
529Overloaded - The service is temporarily overloaded
errorobjectrequired
request_idstringrequired
Default:null
typestringrequired
Default:error

Error handling

A 400 is returned: Invalid argument - The client specified an invalid argument. A 401 is returned: Unauthenticated - The request does not have valid authentication credentials. A 403 is returned: Permission denied - The caller does not have permission to execute the specified operation. A 404 is returned: Not found - Some requested entity was not found. A 408 is returned: Deadline exceeded - The deadline expired before the operation could complete. A 409 is returned: Aborted - The operation was aborted due to concurrency issue. A 412 is returned: Failed precondition - Operation was rejected because the system is not in required state. A 413 is returned: Out of range - Operation was attempted past the valid range. A 429 is returned: Resource exhausted - Some resource has been exhausted (rate limiting). A 431 is returned: Request header fields too large - Request metadata was too large. A 499 is returned: Cancelled - The operation was cancelled by the client. A 500 is returned: Internal - Internal server error. A 501 is returned: Unimplemented - The operation is not implemented or supported. A 503 is returned: Unavailable - The service is currently unavailable. A 504 is returned: Deadline exceeded - Upstream service did not respond in time. A 529 is returned: Overloaded - The service is temporarily overloaded.