使用 Messages API
有效使用 Messages API 的實用模式與範例
Anthropic 提供兩種使用 Claude 進行建構的方式,各自適用於不同的使用情境:
| Messages API | Claude Managed Agents | |
|---|---|---|
| 這是什麼 | 直接的模型提示存取 | 預先建構、可設定的代理框架(agent harness),在受管理的基礎設施中執行 |
| 最適合 | 自訂代理迴圈與細粒度控制 | 長時間執行的任務與非同步工作 |
本指南涵蓋使用 Messages API 的常見模式,包括基本請求、多輪對話、預填技巧以及視覺功能。如需完整的 API 規格,請參閱 Messages API 參考文件。若要改用受管代理框架,請參閱 Claude Managed Agents 概覽。
基本請求與回應
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"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
}
}拒絕回應(stop_reason: "refusal")在每個模型上也都會包含一個 stop_details 物件,用以標識觸發拒絕的政策類別。請參閱處理停止原因以取得欄位參考與範例處理程式碼。
多輪對話
Messages API 是無狀態的(stateless),這表示您每次都必須將完整的對話歷史傳送給 API。您可以使用此模式隨時間逐步建立對話。先前的對話輪次不一定需要實際來自 Claude。您可以使用合成的 assistant 訊息。
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){
"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 角色
在 Claude Fable 5.1、Claude Mythos 5.1、Claude Fable 5、Claude Mythos 5、Claude Opus 5.5、Claude Opus 4.8 和 Claude Opus 5 上,您可以在使用者輪次之後加入帶有 "role": "system" 的訊息(須遵守放置規則),以便在對話進行到一半時新增系統指令。system 訊息不能是 messages 中的第一個項目。對於從一開始就適用的指令,請使用頂層的 system 欄位。
對話中途的系統訊息與頂層 system 欄位具有相同的權威性,但由於它是附加在訊息歷史的末尾,因此不會使其之前的任何已快取前綴失效。對於應從第一輪就適用的指令,請使用頂層 system 欄位;對於稍後才變得相關的指令,則使用對話中途的系統訊息。
請參閱對話中途的系統訊息以取得完整指南,包括如何將其與「prompt caching」(提示快取)提示快取結合使用。
預填 Claude 的回應
您可以在輸入訊息列表的最後一個位置預先填入 Claude 回應的一部分。使用此技巧來塑造 Claude 的回應。以下範例使用 "max_tokens": 1 從 Claude 取得單一的選擇題答案。
message = anthropic.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 ("},
],
)
print(message){
"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
}
}視覺
Claude 可以讀取請求中的文字與圖片。您可以使用 base64、url 或 file 來源類型來提供圖片。file 來源類型會參照透過 Files API 上傳的圖片。支援的媒體類型為 image/jpeg、image/png、image/gif 和 image/webp。請參閱視覺指南以了解更多詳細資訊。
import base64
import httpx2
# 選項 1:Base64 編碼的圖片
image_url = "https://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)
# 選項 2:以 URL 參照的圖片
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://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message_from_url){
"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
}
}後續步驟
Was this page helpful?