Claude Platform Docs
Messages使用 Claude 進行開發

使用 Messages API

有效使用 Messages API 的實用模式與範例

Anthropic 提供兩種使用 Claude 進行建構的方式,各自適用於不同的使用情境:

Messages APIClaude Managed Agents
這是什麼直接的模型提示存取預先建構、可設定的代理框架(agent harness),在受管理的基礎設施中執行
最適合自訂代理迴圈與細粒度控制長時間執行的任務與非同步工作

本指南涵蓋使用 Messages API 的常見模式,包括基本請求、多輪對話、「prefill」(預填)技巧以及視覺功能。如需完整的 API 規格,請參閱 Messages API 參考文件可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。。若您想改用受管理的代理程式框架,請參閱 Claude Managed Agents 概觀。

基本請求與回應

message = anthropic.Anthropic().messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message)
Output
{
  "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 訊息。

透過目前處於 beta 階段的訊息串,API 可以將對話保留下來,讓之後的每個請求只需傳送新的訊息。訊息串會在最後一次請求後 5 分鐘過期,且會在最後一次使用後不超過 1 小時內被刪除。

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)
Output
{
  "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
  }
}

訊息中的系統角色

您可以在使用者輪次之後加入帶有 "role": "system" 的訊息,以在對話進行中途加入新的系統指示,但須遵守放置規則。此功能適用於 Claude Fable 5.2、Claude Mythos 5.2、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、Claude Sonnet 5.5 和 Claude Haiku 5.5。帶有內容的 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)
Output
{
  "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)
Output
{
  "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
  }
}

後續步驟

處理每個 stop_reason 值,並決定回應結束時該如何處理。

為 Claude 提供工具,以便在 Messages API 中呼叫外部服務和 API。

透過 Messages API 控制桌面電腦環境。

讓 Claude 在您執行的瀏覽器中瀏覽、閱讀網頁並與之互動。

從 Claude 取得保證符合結構描述驗證的 JSON 輸出。

使用 output_config.task_budget 為完整的代理迴圈設定建議性的 token 預算。

可用性

Messages API
Availability requirements for Messages API are the same across all supported platforms.
模型
  • 所有模型

資料處理

資料處理概覽

適用端點

  • /v1/messages
零資料保留符合資格

不含 涵蓋的模型

用於產生 Claude 回應的標準 API 呼叫。

HIPAA符合資格

這個頁面有幫助嗎?