Claude Platform Docs
MessagesBuilding with Claude

Using the Messages API

Practical patterns and examples for using the Messages API effectively

Anthropic offers two ways to build with Claude, each suited to different use cases:

Messages APIClaude Managed Agents
What it isDirect model prompting accessPre-built, configurable agent harness that runs in managed infrastructure
Best forCustom agent loops and fine-grained controlLong-running tasks and asynchronous work

This guide covers common patterns for working with the Messages API, including basic requests, multi-turn conversations, prefill techniques, and vision capabilities. 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)
Output
{
  "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

The Messages API is stateless, which means that you always send the full conversational history to the API. You can use this pattern to build up a conversation over time. Earlier conversational turns don’t necessarily need to actually originate from Claude. You can use synthetic assistant messages.

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.

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)
Output
{
  "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
  }
}

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.

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)
Output
{
  "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 is C. It holds only the continuation, not the prefill.
  • stop_reason: The value is max_tokens because 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.type to enabled, the prefill causes no error. The API treats thinking as off, so the response has no thinking block.

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.
  • Another output format: Describe the format in the system prompt, which is the request’s system fieldPreview 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.

Unlike a prefill, a system prompt instruction doesn’t guarantee how the response starts, so check the response’s text in your code.

For what to use in place of other common prefills, see the Migrating away from prefilled responses section of the Prompting best practices page.

To move the multiple-choice example to a model that doesn’t accept a prefill, follow these steps:

  1. Change the model and remove the assistant message.
  2. Ask in the system prompt for only the answer’s letter.
  3. Set max_tokens high enough for the whole response. On models with thinking on by default, thinking tokens also count toward max_tokens.
  4. Read the letter from the response’s text block. This block can follow a thinking block. Don’t join the letter to the prefill.

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.

import base64
import httpx2

# Option 1: base64-encoded image
image_url = "https://code.saschaberens.de/_h/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://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg",
                    },
                },
                {"type": "text", "text": "What is in the above image?"},
            ],
        }
    ],
)
print(message_from_url)
Output
{
  "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

Messages API
Availability requirements for Messages API are the same across all supported platforms.
Models
  • All models

Applicable endpoints

  • /v1/messages
Zero data retentionEligible

Excludes Covered Models

Standard API calls for generating Claude responses.

HIPAAEligible

Was this page helpful?