• 訊息
  • 託管代理
  • 管理
Search...
⌘K
第一步
Claude 簡介快速入門
使用 Claude 進行建構
功能概覽使用 Messages API停止原因與備援拒絕與備援備援額度
模型能力
擴展思考自適應思考努力程度任務預算(測試版)快速模式(研究預覽)結構化輸出引用串流訊息批次處理搜尋結果串流拒絕多語言支援嵌入
工具
概覽工具使用的運作方式教學:建構使用工具的代理定義工具處理工具呼叫平行工具使用工具執行器(SDK)嚴格工具使用搭配提示快取的工具使用伺服器工具疑難排解網頁搜尋工具網頁擷取工具程式碼執行工具顧問工具記憶體工具Bash 工具電腦使用工具文字編輯器工具
工具基礎架構
工具參考管理工具上下文工具組合工具搜尋程式化工具呼叫細粒度工具串流
上下文管理
上下文視窗壓縮上下文編輯提示快取對話中系統訊息建構協調模式快取診斷(測試版)Token 計數
處理檔案
Files APIPDF 支援圖片與視覺
技能
概覽快速入門最佳實務企業技能API 中的技能
MCP
遠端 MCP 伺服器MCP 連接器
雲端平台上的 Claude
Amazon BedrockAmazon Bedrock(舊版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI
Log in
使用 Messages API
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
訊息/使用 Claude 進行建構

使用 Messages API

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

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

Messages APIClaude Managed Agents
說明直接存取模型提示功能預先建構、可配置的代理框架,在託管基礎架構中執行
最適合自訂代理迴圈與細粒度控制長時間執行的任務與非同步工作
了解更多Messages API 文件Claude Managed Agents 文件

本指南涵蓋使用 Messages API 的常見模式,包括基本請求、多輪對話、預填技巧以及視覺功能。如需完整的 API 規格,請參閱 Messages API 參考文件。

此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。

基本請求與回應

Claude Opus 4.7 及更新的模型(包括 Claude Opus 4.8)不支援 temperature、top_p 和 top_k 取樣參數。將這些參數設定為非預設值會回傳 400 錯誤。請從請求內容中省略這些參數,改用提示來引導模型的行為。請參閱遷移指南。

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-8",
    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-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 6
  }
}

在 Claude Opus 4.7 及更新的模型上,拒絕回應(stop_reason: "refusal")也會包含一個 stop_details 物件,用於識別觸發拒絕的政策類別。請參閱處理停止原因以取得欄位參考和範例處理程式碼。

多輪對話

Messages API 是無狀態的,這表示您每次都需要將完整的對話歷史傳送給 API。您可以使用此模式逐步建立對話。較早的對話輪次不一定需要實際來自 Claude,您可以使用合成的 assistant 訊息。

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-8",
    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-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 30,
    "output_tokens": 309
  }
}

訊息中的 System 角色

在 Claude Opus 4.8 上,您可以在使用者輪次之後加入 "role": "system" 的訊息(須遵守放置規則),以便在對話進行到一半時新增系統指令。system 訊息不能是 messages 中的第一個項目;對於從一開始就應套用的指令,請使用頂層的 system 欄位。

對話中途的系統訊息與頂層 system 欄位具有相同的權限,但由於它被附加在訊息歷史的末尾,因此不會使其之前的任何快取前綴失效。對於應從第一輪就套用的指令,請使用頂層 system 欄位;對於稍後才變得相關的指令,則使用對話中途的系統訊息。

請參閱對話中途的系統訊息以取得完整指南,包括如何將其與提示快取結合使用。

預填 Claude 的回應

您可以在輸入訊息清單的最後一個位置預先填入 Claude 回應的一部分。這可用於塑造 Claude 的回應。以下範例使用 "max_tokens": 1 從 Claude 取得單一選擇題答案。

Claude Fable 5、Claude Mythos 5、Claude Mythos Preview、Claude Opus 4.8、Claude Opus 4.7、Claude Opus 4.6 和 Claude Sonnet 4.6 不支援預填功能。對這些模型使用預填的請求會回傳 400 錯誤。請改用支援該功能的模型上的結構化輸出,或使用系統提示指令。請參閱遷移指南以了解遷移模式。

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 httpx

# 選項 1:Base64 編碼的圖片
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-8",
    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-4-8",
    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?"},
            ],
        }
    ],
)
print(message_from_url)
Output
{
  "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-opus-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 1551,
    "output_tokens": 71
  }
}

工具使用與電腦使用

請參閱工具使用指南以取得如何透過 Messages API 使用工具的範例。 請參閱電腦使用指南以取得如何透過 Messages API 控制桌面電腦環境的範例。 如需保證的 JSON 輸出,請參閱結構化輸出。 如需在完整代理迴圈中設定建議性的 token 預算,請設定 output_config.task_budget;請參閱任務預算。

Was this page helpful?

  • 基本請求與回應
  • 多輪對話
  • 訊息中的 System 角色
  • 預填 Claude 的回應
  • 視覺
  • 工具使用與電腦使用