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. 本文涵盖了与 Messages API 相关的一些常见模式,包括基本请求、多轮对话、预填技术和视觉功能。有关完整的 API 规范,请参阅 Messages API 参考。
platform.claude.com/docs/en/api…
Basic request and response 基本请求和响应
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [
{"role": "user", "content": "Hello, Claude"}
]
});
console.log(message);
响应如下:
{
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-sonnet-4-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}
注意 type 有2处
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. 消息 API 是无状态的,这意味着你总是将完整的对话历史发送给 API。你可以使用这种模式随着时间的推移来构建对话。较早的对话回合不一定需要实际上来自 Claude——你可以使用合成的 assistant 消息。
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"}
]
});
可以看到 messages 里面放了多轮对话的内容。
响应如下:
{
"id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Sure, I'd be happy to provide..."
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 30,
"output_tokens": 309
}
}
Putting words in Claude's mouth 预填Claude的响应
You can pre-fill part of Claude's response in the last position of the input messages list. This can be used to shape Claude's response. The example below uses "max_tokens": 1 to get a single multiple choice answer from Claude. 您可以在输入消息列表的最后一个位置预填 Claude 的部分回复。这可以用来引导 Claude 的回复。下面的示例使用 "max_tokens": 1 从 Claude 获取一个单选答案。
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1,
messages: [
{"role": "user", "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"},
{"role": "assistant", "content": "The answer is ("}
]
});
console.log(message);
蚂蚁的拉丁语是什么?(A) Apoidea,(B) Rhopalocera,(C) Formicidae
上面在 assistant 里面的 content部分预填了一些响应内容。 响应如下:
{
"id": "msg_01Q8Faay6S7QPTvEUUQARt7h",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "C"
}
],
"model": "claude-sonnet-4-5",
"stop_reason": "max_tokens",
"stop_sequence": null,
"usage": {
"input_tokens": 42,
"output_tokens": 1
}
}
答案C放在text字段里面,
Vision 视觉
Claude can read both text and images in requests. We support both base64 and url source types for images, and the image/jpeg, image/png, image/gif, and image/webp media types. Claude 可以在请求中读取文本和图像。支持图像的 base64 和 url 源类型,以及 image/jpeg 、 image/png 、 image/gif 和 image/webp 媒体类型。
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
// Option 1: Base64-encoded image
const image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
const image_media_type = "image/jpeg"
const image_array_buffer = await ((await fetch(image_url)).arrayBuffer());
const image_data = Buffer.from(image_array_buffer).toString('base64');
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-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?"
}
],
}
]
});
console.log(message);
// Option 2: URL-referenced image
const messageFromUrl = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg",
},
},
{
"type": "text",
"text": "What is in the above image?"
}
],
}
]
});
console.log(messageFromUrl);
响应如下:
{
"id": "msg_01EcyWo6m4hyW8KHs2y2pei5",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "This image shows an ant, specifically a close-up view of an ant. The ant is shown in detail, with its distinct head, antennae, and legs clearly visible. The image is focused on capturing the intricate details and features of the ant, likely taken with a macro lens to get an extreme close-up perspective."
}
],
"model": "claude-sonnet-4-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 1551,
"output_tokens": 71
}
}
这张图片展示了一只蚂蚁,特别是蚂蚁的特写镜头。蚂蚁的头部、触角和腿部细节清晰可见。这张图片专注于捕捉蚂蚁的复杂细节和特征,可能使用微距镜头拍摄,以获得极端的特写视角。
Tool use and computer use 工具使用和计算机使用
See our guide for examples of how to use tools with the Messages API. See our computer use guide for examples of how to control desktop computer environments with the Messages API. For guaranteed JSON output, see Structured Outputs. 查看platform.claude.com/docs/en/age… Messages API 一起工作。 查看platform.claude.com/docs/en/age… Messages API 控制桌面计算机环境。 要保证 JSON 输出,请参阅结构化输出。