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

Solutions

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

Partners

  • Claude on AWS
  • Claude on Google Cloud

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
Messages/工具基礎架構

細粒度工具串流

針對延遲敏感的應用程式,無需伺服器端 JSON 緩衝即可串流工具輸入。


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

細粒度工具串流適用於所有模型和所有平台。它能夠在不進行緩衝或 JSON 驗證的情況下,對工具使用參數值進行串流(streaming),從而減少開始接收大型參數的延遲。



使用細粒度工具串流時,您可能會收到無效或不完整的 JSON 輸入。請務必在您的程式碼中處理這些邊緣情況。

如何使用細粒度工具串流

細粒度工具串流支援 Claude API、AWS 上的 Claude Platform、Amazon Bedrock、Vertex AI 以及 Microsoft Foundry。若要使用此功能,請在您想要啟用細粒度串流的任何使用者定義工具上,將 eager_input_streaming 設定為 true,並在您的請求中啟用串流。

以下是如何透過 API 使用細粒度工具串流的範例:

client = anthropic.Anthropic()

with client.messages.stream(
    max_tokens=65536,
    model="claude-opus-4-8",
    tools=[
        {
            "name": "make_file",
            "description": "Write text to a file",
            "eager_input_streaming": True,
            "input_schema": {
                "type": "object",
                "properties": {
                    "filename": {
                        "type": "string",
                        "description": "The filename to write text to",
                    },
                    "lines_of_text": {
                        "type": "array",
                        "description": "An array of lines of text to write to the file",
                    },
                },
                "required": ["filename", "lines_of_text"],
            },
        }
    ],
    messages=[
        {
            "role": "user",
            "content": "Can you write a long poem and make a file called poem.txt?",
        }
    ],
) as stream:
    final_message = stream.get_final_message()

print(f"Input tokens: {final_message.usage.input_tokens}")
print(f"Output tokens: {final_message.usage.output_tokens}")

在此範例中,細粒度工具串流使 Claude 能夠將一首長詩的各行串流到工具呼叫 make_file 中,而無需緩衝以驗證 lines_of_text 參數是否為有效的 JSON。這表示您可以在參數到達時即時看到串流內容,而無需等待整個參數完成緩衝和驗證。



使用細粒度工具串流時,工具輸入區塊會更快開始到達,因為伺服器會跳過 JSON 驗證緩衝。作為副作用,區塊通常會更長,且較少出現 token 中間斷開的情況。



由於細粒度串流在傳送參數時不進行緩衝或 JSON 驗證,因此無法保證產生的串流會以有效的 JSON 字串完成。 特別是,如果達到 stop reason(停止原因)max_tokens,串流可能會在參數中途結束,且可能不完整。您通常需要編寫特定的支援程式碼來處理達到 max_tokens 的情況。

累積工具輸入增量

當 tool_use 內容區塊進行串流時,初始的 content_block_start 事件包含 input: {}(一個空物件)。這是一個佔位符。實際的輸入會以一系列 input_json_delta 事件的形式到達,每個事件都攜帶一個 partial_json 字串片段。若要組合完整的輸入,請串接這些片段,並在區塊關閉時解析結果。

如果您的 SDK 提供累積器輔助工具(如本頁第一個範例所使用的),它會為您處理這些工作。手動模式適用於沒有輔助工具的 SDK,或當您需要在區塊關閉之前對部分輸入做出反應時。

累積規則如下:

  1. 在 type: "tool_use" 的 content_block_start 事件上,初始化一個空字串:input_json = ""
  2. 對於每個 type: "input_json_delta" 的 content_block_delta 事件,進行附加:input_json += event.delta.partial_json
  3. 在 content_block_stop 事件上,解析累積的字串:json.loads(input_json)

初始 input: {}(物件)與 partial_json(字串)之間的型別不匹配是刻意設計的。空物件標記了內容陣列中的位置;增量字串則建構實際的值。



當您需要在區塊關閉之前對部分輸入做出反應時(例如,呈現進度指示器),請使用手動模式。否則,請優先使用您 SDK 的累積器輔助工具,如本頁第一個範例所示。

處理工具回應中的無效 JSON

使用細粒度工具串流時,您可能會從模型收到無效或不完整的 JSON。如果您需要在錯誤回應區塊中將此無效 JSON 傳回給模型,您可以將其包裝在 JSON 物件中以確保正確處理(使用合理的鍵名)。例如:

{
  "INVALID_JSON": "<your invalid json string>"
}

這種方法有助於模型理解該內容是無效的 JSON,同時保留原始的格式錯誤資料以供除錯之用。



包裝無效 JSON 時,請務必正確跳脫無效 JSON 字串中的任何引號或特殊字元,以維持包裝物件中有效的 JSON 結構。

後續步驟

串流訊息

伺服器傳送事件和串流事件類型的完整參考。

處理工具呼叫

執行工具並以所需的訊息格式回傳結果。

工具參考

Anthropic 結構描述工具及其版本字串的完整目錄。

Was this page helpful?

  • 如何使用細粒度工具串流
  • 累積工具輸入增量
  • 處理工具回應中的無效 JSON
  • 後續步驟
client = anthropic.Anthropic()

tool_inputs: dict[int, str] = {}  # index -> accumulated JSON string

with client.messages.stream(
    model="claude-opus-4-8",
    max_tokens=1024,
    tools=[
        {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "eager_input_streaming": True,
            "input_schema": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        }
    ],
    messages=[{"role": "user", "content": "Weather in Paris?"}],
) as stream:
    for event in stream:
        match event.type:
            case "content_block_start" if event.content_block.type == "tool_use":
                tool_inputs[event.index] = ""
            case "content_block_delta" if event.delta.type == "input_json_delta":
                tool_inputs[event.index] += event.delta.partial_json
            case "content_block_stop" if event.index in tool_inputs:
                parsed = json.loads(tool_inputs[event.index])
                print(f"Tool input: {parsed}")