working-with-messages changedbuild-with-claude/working-with-messages
Nearest release: v2.1.333, published 4 hours after this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Recorded here
Lines+256added
Lines−23removed
From line
1
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits35to this page, all time
The whole hunk
from line 1, old and new numbered
/
from line 1
11---
22title: Using the Messages API
33url: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
4description: Practical patterns and examples for using the Messages API effectively
4description: "Request patterns for the Messages API: a basic request, multi-turn conversations, mid-conversation system messages, prefill and its alternatives, and images."
55featureMetadata:
66 status: stable
77 zdr:
from line 37
3737 Microsoft Foundry: stable
3838---
3939
40This page covers a [basic request](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#basic-request-and-response), [multi-turn conversations](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#multiple-conversational-turns), [mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#system-role-in-messages), [prefilling a response](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#putting-words-in-claudes-mouth), [alternatives to a prefill](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#alternatives-to-a-prefill), and [images in requests](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#vision).
41
4042Anthropic offers two ways to build with Claude, each suited to different use cases:
4143
4244| | Messages API | Claude Managed Agents |
from line 46
4446| **What it is** | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |
4547| **Best for** | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |
4648
47This 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 reference](https://platform.claude.com/docs/en/api/messages/create). For the managed agent harness instead, see the [Claude Managed Agents overview](https://platform.claude.com/docs/en/managed-agents/overview).
49For complete API specifications, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create). For the managed agent harness instead, see the [Claude Managed Agents overview](https://platform.claude.com/docs/en/managed-agents/overview).
4850
4951## Basic request and response
5052
from line 123
121123 if err != nil {
122124 log.Fatal(err)
123125 }
124 fmt.Println(response)
126 fmt.Println(response.RawJSON())
125127 ```
126128
127129 ```java Java
from line 189
187189
188190## Multiple conversational turns
189191
190The 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.
192By 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.
191193
192With [message threads](https://platform.claude.com/docs/en/build-with-claude/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.
194Earlier `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](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#putting-words-in-claudes-mouth).
193195
194196<CodeGroup>
195197 ```bash cURL
from line 207
205207 {"role": "user", "content": "Hello, Claude"},
206208 {"role": "assistant", "content": "Hello!"},
207209 {"role": "user", "content": "Can you describe LLMs to me?"}
208
209210 ]
210211 }'
211212 ```
from line 282
281282 if err != nil {
282283 log.Fatal(err)
283284 }
284 fmt.Println(response)
285 fmt.Println(response.RawJSON())
285286 ```
286287
287288 ```java Java
from line 353
352353}
353354```
354355
356With [message threads](https://platform.claude.com/docs/en/build-with-claude/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.
357
355358### System role in messages
356359
357360To 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](https://platform.claude.com/docs/en/models/mythos-5-2/overview), Claude Fable 5.1, [Claude Mythos 5.1](https://platform.claude.com/docs/en/models/mythos-5-1/overview), Claude Fable 5, [Claude Mythos 5](https://platform.claude.com/docs/en/models/mythos-5/overview), 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](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations).
from line 457
454457 ```go Go
455458 client := anthropic.NewClient()
456459
457 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
460 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
458461 Model: anthropic.ModelClaudeOpus4_5_20251101,
459462 MaxTokens: 1,
460463 Messages: []anthropic.MessageParam{
from line 468
465468 if err != nil {
466469 log.Fatal(err)
467470 }
468 fmt.Println(response)
471 fmt.Println(message.RawJSON())
469472 ```
470473
471474 ```java Java
from line 481
478481 .addAssistantMessage("The answer is (")
479482 .build();
480483
481 Message response = client.messages().create(params);
482 System.out.println(response);
484 Message message = client.messages().create(params);
485 IO.println(message);
483486 ```
484487
485488 ```php PHP
from line 557
554557
555558In place of a prefill, end `messages` with a `user` message. Then, choose an approach by what you want from the response:
556559
557* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema.
560* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema. With an `enum` in the schema, they also constrain a value to fixed options, apart from its capitalization (see the [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs) section of that page).
558561* **Another output format:** Describe the format in the system prompt, which is the request’s [`system` field](https://platform.claude.com/docs/en/api/messages/create#create.system).
559562* **No preamble:** Ask in the system prompt for a direct answer.
563* **A continuation, fewer refusals, or a consistent role:** See the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
560564
561565Unlike a prefill, a system prompt instruction doesn’t guarantee how the response starts, so check the response’s text in your code.
562566
563For what to use in place of other common prefills, see the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
567The 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.
564568
565To move the multiple-choice example to a model that doesn’t accept a prefill, follow these steps:
569Thinking 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`.
566570
5671. Change the model and remove the `assistant` message.
5682. Ask in the system prompt for only the answer’s letter.
5693. Set `max_tokens` high enough for the whole response. On [models with thinking on by default](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking), thinking tokens also count toward `max_tokens`.
5704. Read the letter from the response’s `text` block. This block can follow a `thinking` block. Don’t join the letter to the prefill.
571<CodeGroup>
572 ```bash cURL
573 #!/bin/sh
574 curl https://api.anthropic.com/v1/messages \
575 -H "x-api-key: $ANTHROPIC_API_KEY" \
576 -H "anthropic-version: 2026-10-21" \
577 -H "content-type: application/json" \
578 -d '{
579 "model": "claude-opus-5-5",
580 "max_tokens": 1024,
581 "system": "Answer with only the letter of the correct option.",
582 "messages": [
583 {"role": "user", "content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"}
584 ]
585 }'
586 ```
571587
588 ```bash CLI
589 ant messages create \
590 --model claude-opus-5-5 \
591 --max-tokens 1024 \
592 --system "Answer with only the letter of the correct option." \
593 --message '{role: user, content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"}'
594 ```
595
596 ```python Python
597 message = anthropic.Anthropic().messages.create(
598 model="claude-opus-5-5",
599 max_tokens=1024,
600 system="Answer with only the letter of the correct option.",
601 messages=[
602 {
603 "role": "user",
604 "content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
605 }
606 ],
607 )
608 answer = next(
609 (block.text.strip() for block in message.content if block.type == "text"), None
610 )
611 if answer not in ("A", "B", "C"):
612 raise ValueError(f"Unexpected answer: {answer}")
613 print(answer)
614 ```
615
616 ```typescript TypeScript
617 const anthropic = new Anthropic();
618
619 const message = await anthropic.messages.create({
620 model: "claude-opus-5-5",
621 max_tokens: 1024,
622 system: "Answer with only the letter of the correct option.",
623 messages: [
624 {
625 role: "user",
626 content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
627 }
628 ]
629 });
630 const answer = message.content.find((block) => block.type === "text")?.text.trim();
631 if (answer === undefined || !["A", "B", "C"].includes(answer)) {
632 throw new Error(`Unexpected answer: ${answer}`);
633 }
634 console.log(answer);
635 ```
636
637 ```csharp C#
638 AnthropicClient client = new();
639
640 var parameters = new MessageCreateParams
641 {
642 Model = Model.ClaudeOpus5_5,
643 MaxTokens = 1024,
644 System = "Answer with only the letter of the correct option.",
645 Messages = [
646 new UserMessageParam { Content = "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae" }
647 ]
648 };
649
650 var message = await client.Messages.Create(parameters);
651 string? answer = null;
652 foreach (var block in message.Content)
653 {
654 if (block.TryPickText(out var textBlock))
655 {
656 answer = textBlock.Text.Trim();
657 break;
658 }
659 }
660 if (answer is not ("A" or "B" or "C"))
661 {
662 throw new InvalidOperationException($"Unexpected answer: {answer}");
663 }
664 Console.WriteLine(answer);
665 ```
666
667 ```go Go
668 client := anthropic.NewClient()
669
670 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
671 Model: anthropic.ModelClaudeOpus5_5,
672 MaxTokens: 1024,
673 System: []anthropic.TextBlockParam{
674 {Text: "Answer with only the letter of the correct option."},
675 },
676 Messages: []anthropic.MessageParam{
677 anthropic.NewUserMessage(anthropic.NewTextBlock("What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")),
678 },
679 })
680 if err != nil {
681 log.Fatal(err)
682 }
683 var answer string
684 for _, block := range message.Content {
685 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
686 answer = strings.TrimSpace(textBlock.Text)
687 break
688 }
689 }
690 if !slices.Contains([]string{"A", "B", "C"}, answer) {
691 log.Fatalf("unexpected answer: %q", answer)
692 }
693 fmt.Println(answer)
694 ```
695
696 ```java Java
697 AnthropicClient client = AnthropicOkHttpClient.fromEnv();
698
699 MessageCreateParams params = MessageCreateParams.builder()
700 .model(Model.CLAUDE_OPUS_5_5)
701 .maxTokens(1024L)
702 .system("Answer with only the letter of the correct option.")
703 .addUserMessage("What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")
704 .build();
705
706 Message message = client.messages().create(params);
707 String answer = message.content().stream()
708 .flatMap(block -> block.text().stream())
709 .map(textBlock -> textBlock.text().strip())
710 .findFirst()
711 .orElse("");
712 if (!List.of("A", "B", "C").contains(answer)) {
713 throw new IllegalStateException("Unexpected answer: " + answer);
714 }
715 IO.println(answer);
716 ```
717
718 ```php PHP
719 $client = new Client();
720
721 $message = $client->messages->create(
722 maxTokens: 1024,
723 messages: [
724 ['role' => 'user', 'content' => 'What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae'],
725 ],
726 model: Model::CLAUDE_OPUS_5_5,
727 system: 'Answer with only the letter of the correct option.',
728 );
729 $answer = null;
730 foreach ($message->content as $block) {
731 if ($block instanceof \Anthropic\Messages\TextBlock) {
732 $answer = trim($block->text);
733 break;
734 }
735 }
736 if (!in_array($answer, ['A', 'B', 'C'], true)) {
737 throw new \UnexpectedValueException("Unexpected answer: {$answer}");
738 }
739 echo $answer, PHP_EOL;
740 ```
741
742 ```ruby Ruby
743 client = Anthropic::Client.new
744
745 message = client.messages.create(
746 model: Anthropic::Model::CLAUDE_OPUS_5_5,
747 max_tokens: 1024,
748 system: "Answer with only the letter of the correct option.",
749 messages: [
750 {
751 role: "user",
752 content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
753 }
754 ]
755 )
756 text_block = message.content.find { |block| block.is_a?(Anthropic::Models::TextBlock) }
757 answer = text_block&.text&.strip
758 raise "Unexpected answer: #{answer.inspect}" unless %w[A B C].include?(answer)
759 puts answer
760 ```
761</CodeGroup>
762
763The API returns the following response. With the SDK, the example prints only the answer, `C`.
764
765```json Output
766{
767 "id": "msg_01HCDu5LRGeP2o7s2xGmxyx8",
768 "type": "message",
769 "role": "assistant",
770 "content": [
771 {
772 "type": "thinking",
773 "thinking": "",
774 "signature": "EosnCkYICxIMMb3LzNrMu..."
775 },
776 {
777 "type": "text",
778 "text": "C"
779 }
780 ],
781 "model": "claude-opus-5-5",
782 "stop_reason": "end_turn",
783 "stop_sequence": null,
784 "usage": {
785 "input_tokens": 60,
786 "output_tokens": 32
787 }
788}
789```
790
791In this response, a `thinking` block comes before the `text` block, which can occur [when thinking is on](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking). Its `thinking` field is empty unless the request asks for a summary (see the [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) section of the Thinking page).
792
793Thinking tokens are billed as output tokens, so `output_tokens` is `32` for a one-letter answer. To use fewer, set a lower [effort level](https://platform.claude.com/docs/en/build-with-claude/effort).
794
795To 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.
796
797What to do when the check fails depends on the response’s `stop_reason`:
798
799* **`max_tokens`:** The response might have no `text` block. Raise `max_tokens` and send the request again.
800* **`refusal`:** Claude declined to respond. To retry on another model, see [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback).
801* **Any other value:** Send the request again or report the failure.
802
572803## Vision
573804
574805Claude 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](https://platform.claude.com/docs/en/build-with-claude/files). Supported media types are `image/jpeg`, `image/png`, `image/gif`, and `image/webp`. See the [Vision](https://platform.claude.com/docs/en/build-with-claude/vision) guide for more details.
575806
807The 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.
808
576809<CodeGroup>
577810 ```bash cURL
578811 #!/bin/sh
from line 1109
8761109 if err != nil {
8771110 log.Fatal(err)
8781111 }
879 fmt.Println(message)
1112 fmt.Println(message.RawJSON())
8801113
8811114 // Option 2: URL-referenced image
8821115 messageFromURL, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
from line 1127
8941127 if err != nil {
8951128 log.Fatal(err)
8961129 }
897 fmt.Println(messageFromURL)
1130 fmt.Println(messageFromURL.RawJSON())
8981131 ```
8991132
9001133 ```java Java
No line in this hunk matches that.