工具使用现在支持参数值的细粒度流式传输。这允许开发者在不缓冲/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的情况。