關於「zero data retention」(零資料保留),即 ZDR 如何適用於此功能,請參閱 API 與資料保留。
細粒度工具串流(fine-grained tool streaming)會在 Claude 生成工具輸入的同時將其傳遞給您的客戶端,無需伺服器端緩衝或 JSON 驗證。跳過緩衝步驟可以縮短取得大型參數(例如文件或程式碼區塊)第一個片段的時間,而且這些片段會透過與標準工具使用相同的串流訊息事件送達。
由於 API 在串流工具輸入之前不會進行緩衝或驗證,您可能會收到部分或無效的 JSON。以 stop reason(停止原因)max_tokens 結束的回應也可能在參數中途被截斷。請累積片段、保護解析過程,並參閱處理工具回應中的無效 JSON 以了解如何將無法解析的輸入回傳給 Claude。
所有模型都在 Claude API、Amazon Bedrock、Claude Platform on AWS、Google Cloud 和 Microsoft Foundry 上支援細粒度工具串流。若要使用它,請在任何您想啟用細粒度串流的使用者定義工具上將 eager_input_streaming 設為 true,並在您的請求上啟用串流。
eager_input_streaming 欄位是選用的。將其設為 true 會為該工具開啟細粒度串流,而省略它則會使用標準的緩衝串流,即 API 會在串流回傳之前緩衝並驗證每個參數值。例外情況是仍然傳送舊版 fine-grained-tool-streaming-2025-05-14 beta 標頭的請求,這會為未設定該欄位的工具開啟細粒度串流。此逐工具欄位取代了該標頭,而明確設為 false 則會讓工具保持緩衝串流,即使請求仍然傳送該標頭。請參閱工具參考以了解欄位定義。
以下範例為 make_file 工具開啟細粒度串流,並要求 Claude 寫一首長詩,讓工具輸入大到足以觀察其串流過程:
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=65536,
model="claude-opus-5",
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:
for event in stream:
if event.type == "input_json":
print(event.partial_json, end="", flush=True)
final_message = stream.get_final_message()
print()
for block in final_message.content:
if block.type == "tool_use":
print(f"Complete tool input: {block.input}")每個分頁都為 make_file 工具開啟了細粒度串流。SDK 分頁會在每個輸入片段送達的瞬間將其印出,然後在串流結束後印出完整累積的輸入。cURL 分頁顯示原始事件串流,而 CLI 分頁使用 jq 只印出片段。由於印出的片段會組合成完整的工具輸入,這首詩會隨著 Claude 的撰寫填滿您的終端機:
{"filename": "poem.txt", "lines_of_text": ["The Wanderer's Journey", "", "I.", "", "Beneath the vast and star-strewn sky,", "Where silver moonbeams softly lie,", ...
Complete tool input: {"filename": "poem.txt", "lines_of_text": ["The Wanderer's Journey", ...]}如果沒有 eager_input_streaming,API 會在串流回傳之前緩衝並驗證每個參數值,因此在 Claude 完成生成之前,大型參數不會印出任何內容。有了它,片段會在 Claude 開始生成參數時立即開始送達,而且通常更長,單字中間被截斷的情況也更少。
累積的約定與標準工具使用串流相同,因此本節在有無 eager_input_streaming 的情況下都適用。請參閱串流訊息中的 Input JSON delta 以了解事件格式。細粒度工具串流改變的是您對結果可以做出的假設:伺服器在串流片段時不會驗證它們,因此累積的字串可能不是有效的 JSON。
當 tool_use 內容區塊進行串流時,初始的 content_block_start 事件包含 input: {}(一個空物件)。這是一個佔位符。實際的輸入會以一系列 input_json_delta 事件的形式送達,每個事件都帶有一個 partial_json 字串片段。若要組合完整的輸入,請串接這些片段,並在區塊關閉時解析結果。
如果您的 SDK 提供累積器輔助工具(如前一個範例中的 Python、TypeScript、Go、Java 和 Ruby 分頁所示),它會為您處理這些工作。手動模式適用於沒有輔助工具的 SDK,或者當您想要完全控制輸入的組合方式時。
累積的約定:
type: "tool_use" 的 content_block_start 上,初始化一個空字串:input_json = ""type: "input_json_delta" 的 content_block_delta,附加:input_json += event.delta.partial_jsoncontent_block_stop 上,解析累積的字串請保護解析過程,如以下 SDK 範例所示。回應也可能在參數中途因 max_tokens 而停止。請檢查 stop reason(停止原因),並決定是要以更高的 max_tokens 重試請求,還是修復部分輸入。
初始的 input: {}(物件)與 partial_json(字串)之間的型別不匹配是刻意設計的。空物件標記了內容陣列中的位置。增量字串則建構出真正的值。
client = anthropic.Anthropic()
tool_inputs: dict[int, str] = {} # index -> accumulated JSON string
with client.messages.stream(
model="claude-opus-5",
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:
raw_input = tool_inputs[event.index]
try:
parsed = json.loads(raw_input)
except json.JSONDecodeError:
# 累積的字串不保證是有效的 JSON。
# 請參閱本頁的「處理工具回應中的無效 JSON」。
print(f"Invalid tool input: {raw_input}")
else:
print(f"Tool input: {parsed}")對片段做出反應和組合片段是兩個不同的關注點。第一個範例在每個片段送達時對其做出反應,並且在使用累積器輔助工具的分頁中仍然將組合工作交給 SDK。當您不使用累積器輔助工具,或者想要完全控制組合過程時,請使用手動模式。
使用細粒度工具串流時,工具呼叫的累積輸入可能是無效或不完整的 JSON。在這種情況下,您無法執行該工具,因此請改為將失敗回報給 Claude。工具結果的 content 不一定要是 JSON,但將原始字串包裝在一個只有單一鍵的 JSON 物件中,可以讓 Claude 明確知道您收到了無效的 JSON,並保留原始輸入以供除錯:
{
"INVALID_JSON": "<the unparseable input you received>"
}將序列化為字串的包裝物件作為 tool result 內容區塊的 content 回傳,並將 is_error 設為 true:
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"is_error": true,
"content": "{\"INVALID_JSON\": \"<the unparseable input you received>\"}"
}請使用您的 JSON 函式庫來建構包裝物件,而不是透過串接字串,這樣無效輸入中的引號和其他特殊字元才能被正確跳脫。
了解上下文視窗的運作方式、擴展思考和工具使用如何計入其中,以及如何隨著對話增長管理上下文。
使用伺服器傳送事件以增量方式串流 Messages API 回應,包括文字、工具使用和擴展思考增量。
解析 tool_use 區塊、格式化 tool_result 回應,並使用 is_error 處理錯誤。
Anthropic 提供的工具目錄以及選用工具定義屬性的參考。
Was this page helpful?