Repository Public
1---2title: Using the Messages API3url: https://platform.claude.com/docs/en/build-with-claude/working-with-messages4description: Practical patterns and examples for using the Messages API effectively5---67Anthropic offers two ways to build with Claude, each suited to different use cases:89| | Messages API | Claude Managed Agents |10| -------------- | ------------------------------------------- | ------------------------------------------------------------------------- |11| **What it is** | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |12| **Best for** | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |1314This 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).1516<Note>17 To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).18</Note>1920## Basic request and response2122<Note>23 The `temperature`, `top_p`, and `top_k` sampling parameters are not supported on Claude 4.7 and later models and Claude Mythos Preview. Setting them to a non-default value returns a 400 error. Omit them from request payloads and use prompting to guide the model's behavior instead. See the [migration guide](https://platform.claude.com/docs/en/models/opus-5/migration-guide#migrating-from-claude-opus-47).24</Note>2526<CodeGroup>27 ```bash cURL28 #!/bin/sh29 curl https://api.anthropic.com/v1/messages \30 -H "x-api-key: $ANTHROPIC_API_KEY" \31 -H "anthropic-version: 2023-06-01" \32 -H "content-type: application/json" \33 -d '{34 "model": "claude-opus-5",35 "max_tokens": 1024,36 "messages": [37 {"role": "user", "content": "Hello, Claude"}38 ]39 }'40 ```4142 ```bash CLI43 ant messages create \44 --model claude-opus-5 \45 --max-tokens 1024 \46 --message '{role: user, content: "Hello, Claude"}'47 ```4849 ```python Python50 message = anthropic.Anthropic().messages.create(51 model="claude-opus-5",52 max_tokens=1024,53 messages=[{"role": "user", "content": "Hello, Claude"}],54 )55 print(message)56 ```5758 ```typescript TypeScript59 const anthropic = new Anthropic();6061 const message = await anthropic.messages.create({62 model: "claude-opus-5",63 max_tokens: 1024,64 messages: [{ role: "user", content: "Hello, Claude" }]65 });66 console.log(message);67 ```6869 ```csharp C#70 AnthropicClient client = new();7172 var parameters = new MessageCreateParams73 {74 Model = Model.ClaudeOpus5,75 MaxTokens = 1024,76 Messages = [new() { Role = Role.User, Content = "Hello, Claude" }]77 };78 var message = await client.Messages.Create(parameters);79 Console.WriteLine(message);80 ```8182 ```go Go83 client := anthropic.NewClient()8485 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{86 Model: anthropic.ModelClaudeOpus5,87 MaxTokens: 1024,88 Messages: []anthropic.MessageParam{89 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),90 },91 })92 if err != nil {93 log.Fatal(err)94 }95 fmt.Println(response)96 ```9798 ```java Java99 AnthropicClient client = AnthropicOkHttpClient.fromEnv();100101 MessageCreateParams params = MessageCreateParams.builder()102 .model(Model.CLAUDE_OPUS_5)103 .maxTokens(1024L)104 .addUserMessage("Hello, Claude")105 .build();106107 Message response = client.messages().create(params);108 System.out.println(response);109 ```110111 ```php PHP112 $client = new Client();113114 $message = $client->messages->create(115 maxTokens: 1024,116 messages: [['role' => 'user', 'content' => 'Hello, Claude']],117 model: 'claude-opus-5',118 );119 echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;120 ```121122 ```ruby Ruby123 client = Anthropic::Client.new124125 message = client.messages.create(126 model: "claude-opus-5",127 max_tokens: 1024,128 messages: [129 { role: "user", content: "Hello, Claude" }130 ]131 )132 puts message133 ```134</CodeGroup>135136```json Output137{138 "id": "msg_01XFDUDYJgAACzvnptvVoYEL",139 "type": "message",140 "role": "assistant",141 "content": [142 {143 "type": "text",144 "text": "Hello!"145 }146 ],147 "model": "claude-opus-5",148 "stop_reason": "end_turn",149 "stop_sequence": null,150 "usage": {151 "input_tokens": 12,152 "output_tokens": 6153 }154}155```156157Refusal responses (`stop_reason: "refusal"`) also include a `stop_details` object identifying the policy category that triggered the refusal, on every model. See [Handling stop reasons](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response) for the field reference and example handling code.158159## Multiple conversational turns160161The 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.162163<CodeGroup>164 ```bash cURL165 #!/bin/sh166 curl https://api.anthropic.com/v1/messages \167 -H "x-api-key: $ANTHROPIC_API_KEY" \168 -H "anthropic-version: 2023-06-01" \169 -H "content-type: application/json" \170 -d '{171 "model": "claude-opus-5",172 "max_tokens": 1024,173 "messages": [174 {"role": "user", "content": "Hello, Claude"},175 {"role": "assistant", "content": "Hello!"},176 {"role": "user", "content": "Can you describe LLMs to me?"}177178 ]179 }'180 ```181182 ```bash CLI183 ant messages create \184 --model claude-opus-5 \185 --max-tokens 1024 \186 --message '{role: user, content: "Hello, Claude"}' \187 --message '{role: assistant, content: "Hello!"}' \188 --message '{role: user, content: "Can you describe LLMs to me?"}'189 ```190191 ```python Python192 message = anthropic.Anthropic().messages.create(193 model="claude-opus-5",194 max_tokens=1024,195 messages=[196 {"role": "user", "content": "Hello, Claude"},197 {"role": "assistant", "content": "Hello!"},198 {"role": "user", "content": "Can you describe LLMs to me?"},199 ],200 )201 print(message)202 ```203204 ```typescript TypeScript205 const anthropic = new Anthropic();206207 const message = await anthropic.messages.create({208 model: "claude-opus-5",209 max_tokens: 1024,210 messages: [211 { role: "user", content: "Hello, Claude" },212 { role: "assistant", content: "Hello!" },213 { role: "user", content: "Can you describe LLMs to me?" }214 ]215 });216 console.log(message);217 ```218219 ```csharp C#220 AnthropicClient client = new();221222 var parameters = new MessageCreateParams223 {224 Model = Model.ClaudeOpus5,225 MaxTokens = 1024,226 Messages =227 [228 new() { Role = Role.User, Content = "Hello, Claude" },229 new() { Role = Role.Assistant, Content = "Hello!" },230 new() { Role = Role.User, Content = "Can you describe LLMs to me?" }231 ]232 };233234 var message = await client.Messages.Create(parameters);235 Console.WriteLine(message);236 ```237238 ```go Go239 client := anthropic.NewClient()240241 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{242 Model: anthropic.ModelClaudeOpus5,243 MaxTokens: 1024,244 Messages: []anthropic.MessageParam{245 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),246 anthropic.NewAssistantMessage(anthropic.NewTextBlock("Hello!")),247 anthropic.NewUserMessage(anthropic.NewTextBlock("Can you describe LLMs to me?")),248 },249 })250 if err != nil {251 log.Fatal(err)252 }253 fmt.Println(response)254 ```255256 ```java Java257 AnthropicClient client = AnthropicOkHttpClient.fromEnv();258259 MessageCreateParams params = MessageCreateParams.builder()260 .model(Model.CLAUDE_OPUS_5)261 .maxTokens(1024L)262 .addUserMessage("Hello, Claude")263 .addAssistantMessage("Hello!")264 .addUserMessage("Can you describe LLMs to me?")265 .build();266267 Message response = client.messages().create(params);268 System.out.println(response);269 ```270271 ```php PHP272 $client = new Client();273274 $message = $client->messages->create(275 maxTokens: 1024,276 messages: [277 ['role' => 'user', 'content' => 'Hello, Claude'],278 ['role' => 'assistant', 'content' => 'Hello!'],279 ['role' => 'user', 'content' => 'Can you describe LLMs to me?'],280 ],281 model: 'claude-opus-5',282 );283284 echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;285 ```286287 ```ruby Ruby288 client = Anthropic::Client.new289290 message = client.messages.create(291 model: "claude-opus-5",292 max_tokens: 1024,293 messages: [294 { role: "user", content: "Hello, Claude" },295 { role: "assistant", content: "Hello!" },296 { role: "user", content: "Can you describe LLMs to me?" }297 ]298 )299 puts message300 ```301</CodeGroup>302303```json Output304{305 "id": "msg_018gCsTGsXkYJVqYPxTgDHBU",306 "type": "message",307 "role": "assistant",308 "content": [309 {310 "type": "text",311 "text": "Sure, I'd be happy to provide..."312 }313 ],314 "model": "claude-opus-5",315 "stop_reason": "end_turn",316 "stop_sequence": null,317 "usage": {318 "input_tokens": 30,319 "output_tokens": 309320 }321}322```323324### System role in messages325326On Claude Fable 5.1, [Claude Mythos 5.1](https://anthropic.com/glasswing), Claude Fable 5, [Claude Mythos 5](https://anthropic.com/glasswing), Claude Opus 4.8, and Claude Opus 5, you can include messages with `"role": "system"` after a user turn (subject to [placement rules](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations)) to add a new system instruction partway through a conversation. A `system` message cannot be the first entry in `messages`. Use the top-level `system` field for instructions that apply from the start.327328A 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.329330See [Mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) for the complete guide, including how to combine it with [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).331332## Prefilling Claude's response333334You can pre-fill part of Claude's response in the last position of the input messages list. Use this technique to shape Claude's response. The following example uses `"max_tokens": 1` to get a single multiple choice answer from Claude.335336<Warning>337 Prefilling is not supported on Claude 4.6 and later models and [Claude Mythos Preview](https://anthropic.com/glasswing). Requests using prefill with these models return a 400 error. Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) on models that support it, or system prompt instructions, instead. See the [migration guide](https://platform.claude.com/docs/en/about-claude/models/migration-guide) for migration patterns.338</Warning>339340<CodeGroup>341 ```bash cURL342 #!/bin/sh343 curl https://api.anthropic.com/v1/messages \344 -H "x-api-key: $ANTHROPIC_API_KEY" \345 -H "anthropic-version: 2023-06-01" \346 -H "content-type: application/json" \347 -d '{348 "model": "claude-sonnet-4-5",349 "max_tokens": 1,350 "messages": [351 {"role": "user", "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"},352 {"role": "assistant", "content": "The answer is ("}353 ]354 }'355 ```356357 ```bash CLI358 ant messages create <<'YAML'359 model: claude-sonnet-4-5360 max_tokens: 1361 messages:362 - role: user363 content: "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"364 - role: assistant365 content: "The answer is ("366 YAML367 ```368369 ```python Python370 message = anthropic.Anthropic().messages.create(371 model="claude-sonnet-4-5",372 max_tokens=1,373 messages=[374 {375 "role": "user",376 "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",377 },378 {"role": "assistant", "content": "The answer is ("},379 ],380 )381 print(message)382 ```383384 ```typescript TypeScript385 const anthropic = new Anthropic();386387 const message = await anthropic.messages.create({388 model: "claude-sonnet-4-5",389 max_tokens: 1,390 messages: [391 {392 role: "user",393 content: "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"394 },395 { role: "assistant", content: "The answer is (" }396 ]397 });398 console.log(message);399 ```400401 ```csharp C#402 AnthropicClient client = new();403404 var parameters = new MessageCreateParams405 {406 Model = Model.ClaudeSonnet4_5,407 MaxTokens = 1,408 Messages = [409 new() { Role = Role.User, Content = "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae" },410 new() { Role = Role.Assistant, Content = "The answer is (" }411 ]412 };413414 var message = await client.Messages.Create(parameters);415 Console.WriteLine(message);416 ```417418 ```go Go419 client := anthropic.NewClient()420421 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{422 Model: anthropic.ModelClaudeSonnet4_5,423 MaxTokens: 1,424 Messages: []anthropic.MessageParam{425 anthropic.NewUserMessage(anthropic.NewTextBlock("What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")),426 anthropic.NewAssistantMessage(anthropic.NewTextBlock("The answer is (")),427 },428 })429 if err != nil {430 log.Fatal(err)431 }432 fmt.Println(response)433 ```434435 ```java Java436 AnthropicClient client = AnthropicOkHttpClient.fromEnv();437438 MessageCreateParams params = MessageCreateParams.builder()439 .model(Model.CLAUDE_SONNET_4_5)440 .maxTokens(1L)441 .addUserMessage("What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")442 .addAssistantMessage("The answer is (")443 .build();444445 Message response = client.messages().create(params);446 System.out.println(response);447 ```448449 ```php PHP450 $client = new Client();451452 $message = $client->messages->create(453 maxTokens: 1,454 messages: [455 ['role' => 'user', 'content' => 'What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae'],456 ['role' => 'assistant', 'content' => 'The answer is ('],457 ],458 model: 'claude-sonnet-4-5',459 );460 echo $message->content[0]->text;461 ```462463 ```ruby Ruby464 client = Anthropic::Client.new465466 message = client.messages.create(467 model: "claude-sonnet-4-5",468 max_tokens: 1,469 messages: [470 {471 role: "user",472 content: "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"473 },474 { role: "assistant", content: "The answer is (" }475 ]476 )477 puts message478 ```479</CodeGroup>480481```json Output482{483 "id": "msg_01Q8Faay6S7QPTvEUUQARt7h",484 "type": "message",485 "role": "assistant",486 "content": [487 {488 "type": "text",489 "text": "C"490 }491 ],492 "model": "claude-sonnet-4-5",493 "stop_reason": "max_tokens",494 "stop_sequence": null,495 "usage": {496 "input_tokens": 42,497 "output_tokens": 1498 }499}500```501502## Vision503504Claude 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 guide](https://platform.claude.com/docs/en/build-with-claude/vision) for more details.505506<CodeGroup>507 ```bash cURL508 #!/bin/sh509510 # Option 1: Base64-encoded image511 IMAGE_URL="https://platform.claude.com/docs/images/vision-example.jpg"512 IMAGE_MEDIA_TYPE="image/jpeg"513 IMAGE_BASE64=$(curl "$IMAGE_URL" | base64 | tr -d '\n')514515 curl https://api.anthropic.com/v1/messages \516 -H "x-api-key: $ANTHROPIC_API_KEY" \517 -H "anthropic-version: 2023-06-01" \518 -H "content-type: application/json" \519 -d @- <<EOF520 {521 "model": "claude-opus-5",522 "max_tokens": 1024,523 "messages": [524 {"role": "user", "content": [525 {"type": "image", "source": {526 "type": "base64",527 "media_type": "$IMAGE_MEDIA_TYPE",528 "data": "$IMAGE_BASE64"529 }},530 {"type": "text", "text": "What is in the above image?"}531 ]}532 ]533 }534 EOF535536 # Option 2: URL-referenced image537 curl https://api.anthropic.com/v1/messages \538 -H "x-api-key: $ANTHROPIC_API_KEY" \539 -H "anthropic-version: 2023-06-01" \540 -H "content-type: application/json" \541 -d '{542 "model": "claude-opus-5",543 "max_tokens": 1024,544 "messages": [545 {"role": "user", "content": [546 {"type": "image", "source": {547 "type": "url",548 "url": "https://platform.claude.com/docs/images/vision-example.jpg"549 }},550 {"type": "text", "text": "What is in the above image?"}551 ]}552 ]553 }'554 ```555556 ```bash CLI557 IMAGE_URL="https://platform.claude.com/docs/images/vision-example.jpg"558559 # Option 1: Base64-encoded image (CLI auto-encodes binary @file refs)560 curl -s "$IMAGE_URL" -o ./vision-example.jpg561562 ant messages create <<'YAML'563 model: claude-opus-5564 max_tokens: 1024565 messages:566 - role: user567 content:568 - type: image569 source:570 type: base64571 media_type: image/jpeg572 data: "@./vision-example.jpg"573 - type: text574 text: What is in the above image?575 YAML576577 # Option 2: URL-referenced image578 ant messages create <<YAML579 model: claude-opus-5580 max_tokens: 1024581 messages:582 - role: user583 content:584 - type: image585 source:586 type: url587 url: $IMAGE_URL588 - type: text589 text: What is in the above image?590 YAML591 ```592593 ```python Python594 import base64595 import httpx2596597 # Option 1: Base64-encoded image598 image_url = "https://platform.claude.com/docs/images/vision-example.jpg"599 image_media_type = "image/jpeg"600 image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")601602 message = anthropic.Anthropic().messages.create(603 model="claude-opus-5",604 max_tokens=1024,605 messages=[606 {607 "role": "user",608 "content": [609 {610 "type": "image",611 "source": {612 "type": "base64",613 "media_type": image_media_type,614 "data": image_data,615 },616 },617 {"type": "text", "text": "What is in the above image?"},618 ],619 }620 ],621 )622 print(message)623624 # Option 2: URL-referenced image625 message_from_url = anthropic.Anthropic().messages.create(626 model="claude-opus-5",627 max_tokens=1024,628 messages=[629 {630 "role": "user",631 "content": [632 {633 "type": "image",634 "source": {635 "type": "url",636 "url": "https://platform.claude.com/docs/images/vision-example.jpg",637 },638 },639 {"type": "text", "text": "What is in the above image?"},640 ],641 }642 ],643 )644 print(message_from_url)645 ```646647 ```typescript TypeScript648 const anthropic = new Anthropic();649650 // Option 1: Base64-encoded image651 const imageUrl = "https://platform.claude.com/docs/images/vision-example.jpg";652 const imageMediaType = "image/jpeg";653 const imageArrayBuffer = await (await fetch(imageUrl)).arrayBuffer();654 const imageData = Buffer.from(imageArrayBuffer).toString("base64");655656 const message = await anthropic.messages.create({657 model: "claude-opus-5",658 max_tokens: 1024,659 messages: [660 {661 role: "user",662 content: [663 {664 type: "image",665 source: {666 type: "base64",667 media_type: imageMediaType,668 data: imageData669 }670 },671 {672 type: "text",673 text: "What is in the above image?"674 }675 ]676 }677 ]678 });679 console.log(message);680681 // Option 2: URL-referenced image682 const messageFromUrl = await anthropic.messages.create({683 model: "claude-opus-5",684 max_tokens: 1024,685 messages: [686 {687 role: "user",688 content: [689 {690 type: "image",691 source: {692 type: "url",693 url: "https://platform.claude.com/docs/images/vision-example.jpg"694 }695 },696 {697 type: "text",698 text: "What is in the above image?"699 }700 ]701 }702 ]703 });704 console.log(messageFromUrl);705 ```706707 ```csharp C#708 using System.Collections.Generic;709 using System.Net.Http;710 using Anthropic;711 using Anthropic.Models.Messages;712713 AnthropicClient client = new();714715 // Option 1: Base64-encoded image716 string imageUrl = "https://platform.claude.com/docs/images/vision-example.jpg";717718 using HttpClient httpClient = new();719 byte[] imageBytes = await httpClient.GetByteArrayAsync(imageUrl);720 string imageData = Convert.ToBase64String(imageBytes);721722 var parameters = new MessageCreateParams723 {724 Model = Model.ClaudeOpus5,725 MaxTokens = 1024,726 Messages =727 [728 new()729 {730 Role = Role.User,731 Content = new MessageParamContent(new List<ContentBlockParam>732 {733 new ContentBlockParam(new ImageBlockParam(734 new ImageBlockParamSource(new Base64ImageSource()735 {736 Data = imageData,737 MediaType = MediaType.ImageJpeg,738 })739 )),740 new ContentBlockParam(new TextBlockParam("What is in the above image?")),741 }),742 }743 ]744 };745746 var message = await client.Messages.Create(parameters);747 Console.WriteLine(message);748749 // Option 2: URL-referenced image750 var parametersFromUrl = new MessageCreateParams751 {752 Model = Model.ClaudeOpus5,753 MaxTokens = 1024,754 Messages =755 [756 new()757 {758 Role = Role.User,759 Content = new MessageParamContent(new List<ContentBlockParam>760 {761 new ContentBlockParam(new ImageBlockParam(762 new ImageBlockParamSource(new UrlImageSource()763 {764 Url = "https://platform.claude.com/docs/images/vision-example.jpg",765 })766 )),767 new ContentBlockParam(new TextBlockParam("What is in the above image?")),768 }),769 }770 ]771 };772773 var messageFromUrl = await client.Messages.Create(parametersFromUrl);774 Console.WriteLine(messageFromUrl);775 ```776777 ```go Go778 client := anthropic.NewClient()779780 // Option 1: Base64-encoded image781 imageURL := "https://platform.claude.com/docs/images/vision-example.jpg"782783 req, err := http.NewRequest("GET", imageURL, nil)784 if err != nil {785 log.Fatal(err)786 }787 req.Header.Set("User-Agent", "AnthropicDocsBot/1.0")788789 resp, err := http.DefaultClient.Do(req)790 if err != nil {791 log.Fatal(err)792 }793 defer resp.Body.Close()794795 imageBytes, err := io.ReadAll(resp.Body)796 if err != nil {797 log.Fatal(err)798 }799 imageData := base64.StdEncoding.EncodeToString(imageBytes)800801 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{802 Model: anthropic.ModelClaudeOpus5,803 MaxTokens: 1024,804 Messages: []anthropic.MessageParam{805 anthropic.NewUserMessage(806 anthropic.NewImageBlockBase64("image/jpeg", imageData),807 anthropic.NewTextBlock("What is in the above image?"),808 ),809 },810 })811 if err != nil {812 log.Fatal(err)813 }814 fmt.Println(message)815816 // Option 2: URL-referenced image817 messageFromURL, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{818 Model: anthropic.ModelClaudeOpus5,819 MaxTokens: 1024,820 Messages: []anthropic.MessageParam{821 anthropic.NewUserMessage(822 anthropic.NewImageBlock(anthropic.URLImageSourceParam{823 URL: "https://platform.claude.com/docs/images/vision-example.jpg",824 }),825 anthropic.NewTextBlock("What is in the above image?"),826 ),827 },828 })829 if err != nil {830 log.Fatal(err)831 }832 fmt.Println(messageFromURL)833 ```834835 ```java Java836 AnthropicClient client = AnthropicOkHttpClient.fromEnv();837838 // Option 1: Base64-encoded image839 String imageUrl = "https://platform.claude.com/docs/images/vision-example.jpg";840841 HttpClient httpClient = HttpClient.newHttpClient();842 HttpRequest request = HttpRequest.newBuilder().uri(URI.create(imageUrl)).build();843 HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());844 String imageData = Base64.getEncoder().encodeToString(response.body());845846 List<ContentBlockParam> base64Content = List.of(847 ContentBlockParam.ofImage(848 ImageBlockParam.builder()849 .source(Base64ImageSource.builder()850 .data(imageData)851 .mediaType(Base64ImageSource.MediaType.IMAGE_JPEG)852 .build())853 .build()),854 ContentBlockParam.ofText(855 TextBlockParam.builder()856 .text("What is in the above image?")857 .build())858 );859860 Message message = client.messages().create(861 MessageCreateParams.builder()862 .model(Model.CLAUDE_OPUS_5)863 .maxTokens(1024L)864 .addUserMessageOfBlockParams(base64Content)865 .build());866 System.out.println(message);867868 // Option 2: URL-referenced image869 List<ContentBlockParam> urlContent = List.of(870 ContentBlockParam.ofImage(871 ImageBlockParam.builder()872 .source(UrlImageSource.builder()873 .url("https://platform.claude.com/docs/images/vision-example.jpg")874 .build())875 .build()),876 ContentBlockParam.ofText(877 TextBlockParam.builder()878 .text("What is in the above image?")879 .build())880 );881882 Message messageFromUrl = client.messages().create(883 MessageCreateParams.builder()884 .model(Model.CLAUDE_OPUS_5)885 .maxTokens(1024L)886 .addUserMessageOfBlockParams(urlContent)887 .build());888 System.out.println(messageFromUrl);889 ```890891 ```php PHP892 $client = new Client();893894 // Option 1: Base64-encoded image895 $image_url = 'https://platform.claude.com/docs/images/vision-example.jpg';896 $image_media_type = "image/jpeg";897 $image_data = base64_encode(file_get_contents($image_url));898899 $message = $client->messages->create(900 maxTokens: 1024,901 messages: [902 [903 'role' => 'user',904 'content' => [905 [906 'type' => 'image',907 'source' => [908 'type' => 'base64',909 'media_type' => $image_media_type,910 'data' => $image_data,911 ],912 ],913 [914 'type' => 'text',915 'text' => 'What is in the above image?',916 ],917 ],918 ],919 ],920 model: 'claude-opus-5',921 );922 echo $message;923924 // Option 2: URL-referenced image925 $message_from_url = $client->messages->create(926 maxTokens: 1024,927 messages: [928 [929 'role' => 'user',930 'content' => [931 [932 'type' => 'image',933 'source' => [934 'type' => 'url',935 'url' => 'https://platform.claude.com/docs/images/vision-example.jpg',936 ],937 ],938 [939 'type' => 'text',940 'text' => 'What is in the above image?',941 ],942 ],943 ],944 ],945 model: 'claude-opus-5',946 );947 echo $message_from_url;948 ```949950 ```ruby Ruby951 require "base64"952 require "net/http"953954 client = Anthropic::Client.new955956 # Option 1: Base64-encoded image957 image_url = "https://platform.claude.com/docs/images/vision-example.jpg"958 image_media_type = "image/jpeg"959 image_data = Base64.strict_encode64(Net::HTTP.get(URI(image_url)))960961 message = client.messages.create(962 model: "claude-opus-5",963 max_tokens: 1024,964 messages: [965 {966 role: "user",967 content: [968 {969 type: "image",970 source: {971 type: "base64",972 media_type: image_media_type,973 data: image_data974 }975 },976 {977 type: "text",978 text: "What is in the above image?"979 }980 ]981 }982 ]983 )984 puts message985986 # Option 2: URL-referenced image987 message_from_url = client.messages.create(988 model: "claude-opus-5",989 max_tokens: 1024,990 messages: [991 {992 role: "user",993 content: [994 {995 type: "image",996 source: {997 type: "url",998 url: "https://platform.claude.com/docs/images/vision-example.jpg"999 }1000 },1001 {1002 type: "text",1003 text: "What is in the above image?"1004 }1005 ]1006 }1007 ]1008 )1009 puts message_from_url1010 ```1011</CodeGroup>10121013```json Output1014{1015 "id": "msg_011CdKmWtV3oFx1C5yUbf5CY",1016 "type": "message",1017 "role": "assistant",1018 "content": [1019 {1020 "type": "text",1021 "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."1022 }1023 ],1024 "model": "claude-opus-5",1025 "stop_reason": "end_turn",1026 "stop_sequence": null,1027 "usage": {1028 "input_tokens": 1030,1029 "output_tokens": 3501030 }1031}1032```10331034## Next steps10351036<CardGroup cols={2}>1037 <Card title="Stop reasons and fallback" icon="list" href="https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons">1038 Handle each `stop_reason` value and decide what to do when a response ends.1039 </Card>10401041 <Card title="Tool use with Claude" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">1042 Give Claude tools to call external services and APIs from within the Messages API.1043 </Card>10441045 <Card title="Computer use tool" icon="computer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool">1046 Control desktop computer environments with the Messages API.1047 </Card>10481049 <Card title="Browser use tool" icon="browser" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool">1050 Let Claude navigate, read, and interact with webpages in a browser you run.1051 </Card>10521053 <Card title="Structured outputs" icon="code-brackets" href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">1054 Get guaranteed, schema-validated JSON output from Claude.1055 </Card>10561057 <Card title="Task budgets" icon="gauge" href="https://platform.claude.com/docs/en/build-with-claude/task-budgets">1058 Set an advisory token budget across a full agentic loop with `output_config.task_budget`.1059 </Card>1060</CardGroup>1061