Using the Messages API
Request patterns for the Messages API: a basic request, multi-turn conversations, mid-conversation system messages, prefill and its alternatives, and images.
This page covers a basic request, multi-turn conversations, mid-conversation system messages, prefilling a response, alternatives to a prefill, and images in requests.
Anthropic offers two ways to build with Claude, each suited to different use cases:
| Messages API | Claude Managed Agents | |
|---|---|---|
| What it is | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |
| Best for | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |
For complete API specifications, see the Messages API referencePreview with links to the API reference available — press Tab until focus enters the card, Escape to return.. For the managed agent harness instead, see the Claude Managed Agents overview.
Basic request and response
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}Refusal responses (stop_reason: "refusal") also include a stop_details object identifying the policy category that triggered the refusal, on every model. See What a refusal looks like for the field reference and example handling code.
Multiple conversational turns
By default, the Messages API is stateless, so you send the full conversation history with each request. To continue a conversation, add the response’s content to messages as an assistant message. Keep it unchanged. It can hold thinking and tool_use blocks, and during tool use, those blocks must go back as they came. Then, add the next user message.
Earlier assistant messages don’t have to come from Claude. You can write them yourself, as the following example does. In a request, content can be a string or an array of blocks. A response has an array of blocks. The last message is a special case. See Prefilling Claude’s response.
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message){
"id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Sure, I'd be happy to provide..."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 30,
"output_tokens": 309
}
}With message threads, in beta, the API can keep the conversation, so that each later request sends only the new messages. A thread expires 5 minutes after its last request and is deleted no more than 1 hour after its last use.
System role in messages
To add a new system instruction partway through a conversation, include a message with "role": "system" right after a user turn. That message can’t be the first entry in messages. This works on Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, Claude Opus 5.5, Claude Opus 5, Claude Opus 4.8, Claude Sonnet 5.5, and Claude Haiku 5.5. See the full placement rules.
A mid-conversation system message has the same authority as the top-level system field, but because it is appended to the end of the message history, it does not invalidate any cached prefix that came before it. Use the top-level system field for instructions that should apply from the very first turn, and a mid-conversation system message for instructions that only become relevant later.
See Mid-conversation system messages and tool changes for the complete guide, including how to combine it with prompt caching.
Prefilling Claude’s response
A prefill is text that you write in an assistant message and put last in messages. An assistant message anywhere else in messages isn’t a prefill. Claude continues the prefilled text, and the response holds only the continuation.
Use a prefill to set how a response starts, for example, to start it in a fixed format or to skip a preamble.
Whether the API accepts a prefill depends on the model, not on the API version:
- Claude 4.5 and earlier models: The API accepts a prefill unless the model is retired on the platform that you use. All requests to a retired model fail. To check a model’s status, see Model deprecations.
- All other models: The API returns a 400 error (see the Prefill not supported section of the Claude API errors page). Use one of the alternatives to a prefill instead.
Claude Opus 4.5 is deprecated on Anthropic-operated platforms. Claude Sonnet 4.5 is retired on the same platforms. For retirement dates and recommended replacements, see Deprecation history on the Model deprecations page. Partner-operated platforms set their own retirement schedules.
The recommended replacements for Claude Opus 4.5 and Claude Sonnet 4.5 don’t accept a prefill.
The following example runs on Claude Opus 4.5 and sets the format of a multiple-choice answer. The prefill, The answer is (, ends right before the answer’s letter so that Claude writes the letter first. Because the answer is one letter, the example also sets max_tokens to 1. For a longer answer, set a higher max_tokens.
message = anthropic.Anthropic().messages.create(
model="claude-opus-4-5-20251101",
max_tokens=1,
messages=[
{
"role": "user",
"content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
},
{"role": "assistant", "content": "The answer is ("},
],
)
print(message){
"id": "msg_01Q8Faay6S7QPTvEUUQARt7h",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "C"
}
],
"model": "claude-opus-4-5-20251101",
"stop_reason": "max_tokens",
"stop_sequence": null,
"usage": {
"input_tokens": 42,
"output_tokens": 1
}
}Note two fields in this response:
text: The value isC. It holds only the continuation, not the prefill.stop_reason: The value ismax_tokensbecause the example ends the response after one token.
To get the full text, The answer is (C, join the prefill and the text value in your code.
On Claude 4.5 and earlier models, these limits apply to a prefill:
- Whitespace: If the prefill ends with whitespace, the API returns a 400 error.
- Structured outputs: If the request also sets
output_config.format, the API returns a 400 error (see the Feature compatibility section of the Structured outputs page). - Extended thinking: If the request also sets
thinking.typetoenabled, the prefill causes no error. The API treats thinking as off, so the response has nothinkingblock.
The message in each 400 error says what caused it.
Alternatives to a prefill
In place of a prefill, end messages with a user message. Then, choose an approach by what you want from the response:
- JSON that follows a schema: Use structured outputs, which constrain the response to follow the schema. With an
enumin the schema, they also constrain a value to fixed options, apart from its capitalization (see the Invalid outputs section of that page). - Another output format: Describe the format in the system prompt, which is the request’s
systemfieldPreview with links to the API reference available — press Tab until focus enters the card, Escape to return.. - No preamble: Ask in the system prompt for a direct answer.
- A continuation, fewer refusals, or a consistent role: See the Migrating away from prefilled responses section of the Prompting best practices page.
Unlike a prefill, a system prompt instruction doesn’t guarantee how the response starts, so check the response’s text in your code.
The following example sets an output format in the system prompt for the multiple-choice question from the prefill example. It has no assistant message, and its system prompt asks for only the answer’s letter.
Thinking is on for the example’s model even though the request has no thinking field. Because thinking tokens count toward max_tokens, the example sets max_tokens to 1024, not 1.
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system="Answer with only the letter of the correct option.",
messages=[
{
"role": "user",
"content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
}
],
)
answer = next(
(block.text.strip() for block in message.content if block.type == "text"), None
)
if answer not in ("A", "B", "C"):
raise ValueError(f"Unexpected answer: {answer}")
print(answer)The API returns the following response. With the SDK, the example prints only the answer, C.
{
"id": "msg_01HCDu5LRGeP2o7s2xGmxyx8",
"type": "message",
"role": "assistant",
"content": [
{
"type": "thinking",
"thinking": "",
"signature": "EosnCkYICxIMMb3LzNrMu..."
},
{
"type": "text",
"text": "C"
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 60,
"output_tokens": 32
}
}In this response, a thinking block comes before the text block, which can occur when thinking is on. Its thinking field is empty unless the request asks for a summary (see the Controlling thinking display section of the Thinking page).
Thinking tokens are billed as output tokens, so output_tokens is 32 for a one-letter answer. To use fewer, set a lower effort level.
To read the answer, find the text block by its type, not by its position. Then, trim the text’s whitespace and check that it’s A, B, or C. With the SDK, the example does both.
What to do when the check fails depends on the response’s stop_reason:
max_tokens: The response might have notextblock. Raisemax_tokensand send the request again.refusal: Claude declined to respond. To retry on another model, see Refusals and fallback.- Any other value: Send the request again or report the failure.
Vision
Claude can read both text and images in requests. You can supply images using the base64, url, or file source types. The file source type references an image uploaded through the Files API. Supported media types are image/jpeg, image/png, image/gif, and image/webp. See the Vision guide for more details.
The following example makes two separate requests with the same image, the first as base64 and the second as a url. In your own code, send only one.
import base64
import httpx2
# Option 1: base64-encoded image
image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message)
# Option 2: URL-referenced image
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message_from_url){
"id": "msg_011CdKmWtV3oFx1C5yUbf5CY",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "This image is a beautiful minimalist/flat-design illustration of a sunset landscape. Here's what it contains:\n\n**Sky & Sun:**\n- A warm gradient sky transitioning from golden-yellow at the top to deep orange toward the horizon\n- A large pale yellow sun positioned in the upper-right area\n\n**Birds:**\n- Three small silhouetted birds flying in the upper-left portion of the sky, depicted as simple \"M\" or \"v\" shapes\n\n**Mountains:**\n- Multiple layered mountain peaks in purple and maroon tones\n- The mountains overlap to create depth, with varying shades of dusty purple and deep burgundy\n\n**Water:**\n- A dark purple body of water at the bottom of the image\n- A reflection of the sun shown as horizontal cream/peach colored lines in the center-bottom area\n\nThe overall style is clean, geometric, and uses a warm sunset color palette (oranges, yellows, purples, and maroons), giving it a peaceful, serene aesthetic typical of modern vector/flat design artwork."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 1030,
"output_tokens": 350
}
}Next steps
Handle each stop_reason value and decide what to do when a response ends.
Give Claude tools to call external services and APIs from within the Messages API.
Control desktop computer environments with the Messages API.
Let Claude navigate, read, and interact with webpages in a browser you run.
Get guaranteed, schema-validated JSON output from Claude.
Set an advisory token budget across a full agentic loop with output_config.task_budget.
Availability
Claude API
- Models
- All models
Amazon Bedrock
- Models
- All models
Amazon Bedrock (bedrock-runtime)
- Models
- All models
Claude Platform on AWS
- Models
- All models
Claude Models on Google Cloud (Anthropic managed)
- Models
- All models
Claude Models on Google Cloud (Google managed)
- Models
- All models
Microsoft Foundry
- Models
- All models
Data handling
Data handling overviewApplicable endpoints
/v1/messages
Excludes Covered Models
Standard API calls for generating Claude responses.
Was this page helpful?