Page history
working-with-messages
build-with-claude/working-with-messages
History
build-with-claude/working-with-messages Changed · +1 / -1 lines
from line 20
## Basic request and response <Note> - 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/about-claude/models/migration-guide#migrating-from-claude-opus-47). + 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). </Note> <CodeGroup>
build-with-claude/working-with-messages Changed · +2 / -2 lines
from line 592
```python Python import base64 - import httpx + 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(httpx.get(image_url).content).decode("utf-8") + image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8") message = anthropic.Anthropic().messages.create( model="claude-opus-5",
build-with-claude/working-with-messages Changed · +4 / -0 lines
from line 1046
Control desktop computer environments with the Messages API. </Card> + <Card title="Browser use tool" icon="browser" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool"> + Let Claude navigate, read, and interact with webpages in a browser you run. + </Card> + <Card title="Structured outputs" icon="code-brackets" href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs"> Get guaranteed, schema-validated JSON output from Claude. </Card>
build-with-claude/working-with-messages First recorded · 1056 lines, first recorded
## Basic request and response ## Multiple conversational turns ### System role in messages ## Prefilling Claude's response ## Vision ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Using the Messages API
url: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
description: 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 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 |
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 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).
<Note>
For 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).
</Note>
## Basic request and response
<Note>
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/about-claude/models/migration-guide#migrating-from-claude-opus-47).
</Note>
<CodeGroup>
```bash cURL
#!/bin/sh
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, Claude"}
]
}'
```
```bash CLI
ant messages create \
--model claude-opus-5 \
--max-tokens 1024 \
--message '{role: user, content: "Hello, Claude"}'
```
```python Python
message = anthropic.Anthropic().messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message)
```
```typescript TypeScript
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }]
});
console.log(message);
```
```csharp C#
AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus5,
MaxTokens = 1024,
Messages = [new() { Role = Role.User, Content = "Hello, Claude" }]
};
var message = await client.Messages.Create(parameters);
Console.WriteLine(message);
```
```go Go
client := anthropic.NewClient()
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
```
```java Java
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_5)
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.build();
Message response = client.messages().create(params);
System.out.println(response);
```
```php PHP
$client = new Client();
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
);
echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;
```
```ruby Ruby
client = Anthropic::Client.new
message = client.messages.create(
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{ role: "user", content: "Hello, Claude" }
]
)
puts message
```
</CodeGroup>
```json Output
{
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-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 [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.
## 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.
<CodeGroup>
```bash cURL
#!/bin/sh
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"}
]
}'
```
```bash CLI
ant messages create \
--model claude-opus-5 \
--max-tokens 1024 \
--message '{role: user, content: "Hello, Claude"}' \
--message '{role: assistant, content: "Hello!"}' \
--message '{role: user, content: "Can you describe LLMs to me?"}'
```
```python Python
message = anthropic.Anthropic().messages.create(
model="claude-opus-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)
```
```typescript TypeScript
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{ role: "user", content: "Hello, Claude" },
{ role: "assistant", content: "Hello!" },
{ role: "user", content: "Can you describe LLMs to me?" }
]
});
console.log(message);
```
```csharp C#
AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus5,
MaxTokens = 1024,
Messages =
[
new() { Role = Role.User, Content = "Hello, Claude" },
new() { Role = Role.Assistant, Content = "Hello!" },
new() { Role = Role.User, Content = "Can you describe LLMs to me?" }
]
};
var message = await client.Messages.Create(parameters);
Console.WriteLine(message);
```
```go Go
client := anthropic.NewClient()
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
anthropic.NewAssistantMessage(anthropic.NewTextBlock("Hello!")),
anthropic.NewUserMessage(anthropic.NewTextBlock("Can you describe LLMs to me?")),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
```
```java Java
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_5)
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.addAssistantMessage("Hello!")
.addUserMessage("Can you describe LLMs to me?")
.build();
Message response = client.messages().create(params);
System.out.println(response);
```
```php PHP
$client = new Client();
$message = $client->messages->create(
maxTokens: 1024,
messages: [
['role' => 'user', 'content' => 'Hello, Claude'],
['role' => 'assistant', 'content' => 'Hello!'],
['role' => 'user', 'content' => 'Can you describe LLMs to me?'],
],
model: 'claude-opus-5',
);
echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;
```
```ruby Ruby
client = Anthropic::Client.new
message = client.messages.create(
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{ role: "user", content: "Hello, Claude" },
{ role: "assistant", content: "Hello!" },
{ role: "user", content: "Can you describe LLMs to me?" }
]
)
puts message
```
Cut at 300 lines.