工具使用現在支援參數值的細粒度串流。這讓開發者能夠串流工具使用參數而無需緩衝/JSON驗證,減少開始接收大型參數的延遲。

細粒度工具串流是一個測試版功能。請確保在生產環境中使用之前評估您的回應。

請使用此表單提供關於模型回應品質、API本身或文件品質的回饋意見——我們迫不及待想聽到您的意見!

使用細粒度工具串流時,您可能會收到無效或部分的JSON輸入。請確保在您的程式碼中考慮這些邊緣情況。

如何使用細粒度工具串流

要使用此測試版功能,只需在工具使用請求中添加測試版標頭fine-grained-tool-streaming-2025-05-14並開啟串流。

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

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: fine-grained-tool-streaming-2025-05-14" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 65536,
    "tools": [
      {
        "name": "make_file",
        "description": "Write text to a file",
        "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?"
      }
    ],
    "stream": true
  }' | jq '.usage'

在此範例中,細粒度工具串流讓Claude能夠將長詩的行串流到工具呼叫make_file中,而無需緩衝來驗證lines_of_text參數是否為有效的JSON。這意味著您可以在參數到達時看到參數串流,而無需等待整個參數緩衝和驗證。

使用細粒度工具串流時,工具使用區塊開始串流得更快,通常更長且包含較少的斷詞。這是由於分塊行為的差異。

範例:

沒有細粒度串流(15秒延遲):

區塊1:'{"'
區塊2:'query": "Ty'
區塊3:'peScri'
區塊4:'pt 5.0 5.1 '
區塊5:'5.2 5'
區塊6:'.3'
區塊8:' new f'
區塊9:'eatur'
...

使用細粒度串流(3秒延遲):

區塊1:'{"query": "TypeScript 5.0 5.1 5.2 5.3'
區塊2:' new features comparison'

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