Loading...
    • 構建
    • 管理
    • 模型和定價
    • 客戶端 SDK
    • API 參考
    Search...
    ⌘K
    第一步
    Claude 簡介快速開始
    使用 Claude 構建
    功能概覽使用 Messages APIClaude API 技能處理停止原因
    模型功能
    擴展思考自適應思考努力任務預算 (測試版)快速模式 (測試版:研究預覽)結構化輸出引用流式傳輸消息批量處理搜索結果流式傳輸拒絕多語言支持嵌入
    工具
    概覽工具使用如何運作網絡搜索工具網絡獲取工具代碼執行工具顧問工具記憶工具Bash 工具計算機使用工具文本編輯器工具
    工具基礎設施
    工具參考工具搜索程序化工具調用細粒度工具流式傳輸
    上下文管理
    上下文窗口壓縮上下文編輯提示詞緩存令牌計數
    處理文件
    Files APIPDF 支持圖像和視覺
    技能
    概覽快速開始最佳實踐企業技能API 中的技能
    MCP
    遠程 MCP 服務器MCP 連接器
    提示詞工程
    概覽提示詞最佳實踐Console 提示詞工具
    測試和評估
    定義成功並構建評估在 Console 中使用評估工具降低延遲
    加強護欄
    減少幻覺提高輸出一致性緩解越獄減少提示詞洩露
    資源
    詞彙表
    發佈說明
    Claude Platform
    Console
    Log in
    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 offers two ways to build with Claude, each suited to different use cases:

    Messages APIClaude Managed Agents
    What it isDirect model prompting accessPre-built, configurable agent harness that runs in managed infrastructure
    Best forCustom agent loops and fine-grained controlLong-running tasks and asynchronous work
    Learn moreMessages API docsClaude Managed Agents docs

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

    This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

    基本請求和回應

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

    多輪對話

    Messages API 是無狀態的,這意味著您始終將完整的對話歷史發送到 API。您可以使用此模式隨著時間推移建立對話。早期的對話輪次不一定需要實際來自 Claude。您可以使用合成的 assistant 訊息。

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

    把話放進 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 Mythos Preview、Claude Opus 4.7、Claude Opus 4.6 和 Claude Sonnet 4.6 上不受支援。使用預填充的這些模型的請求會返回 400 錯誤。改用 結構化輸出 或系統提示指令。請參閱 遷移指南 以了解遷移模式。

    視覺

    Claude 可以在請求中讀取文本和圖像。圖像可以使用 base64、url 或 file 源類型提供。file 源類型引用通過 Files API 上傳的圖像。支持的媒體類型為 image/jpeg、image/png、image/gif 和 image/webp。有關更多詳細信息,請參閱 視覺指南。

    import base64
    import httpx
    
    # Option 1: Base64-encoded image
    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-7",
        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)
    
    # Option 2: URL-referenced image
    message_from_url = anthropic.Anthropic().messages.create(
        model="claude-opus-4-7",
        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)
    輸出
    {
      "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-7",
      "stop_reason": "end_turn",
      "stop_sequence": null,
      "usage": {
        "input_tokens": 1551,
        "output_tokens": 71
      }
    }

    工具使用和計算機使用

    有關如何在 Messages API 中使用工具的示例,請參閱 工具使用指南。 有關如何使用 Messages API 控制桌面計算機環境的示例,請參閱 計算機使用指南。 有關保證 JSON 輸出,請參閱 結構化輸出。

    Was this page helpful?

    • 把話放進 Claude 的嘴裡