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.
세밀한 도구 스트리밍은 모든 모델과 모든 플랫폼에서 일반적으로 사용 가능합니다. 이 기능은 버퍼링이나 JSON 유효성 검사 없이 도구 사용 매개변수 값의 스트리밍을 가능하게 하여, 대용량 매개변수 수신을 시작하는 데 걸리는 지연 시간을 줄입니다.
세밀한 도구 스트리밍을 사용할 때 유효하지 않거나 불완전한 JSON 입력을 받을 수 있습니다. 코드에서 이러한 엣지 케이스를 반드시 처리하세요.
세밀한 도구 스트리밍은 모든 모델과 모든 플랫폼(Claude API, Amazon Bedrock, Google Vertex AI, Microsoft Foundry)에서 사용 가능합니다. 사용하려면 세밀한 스트리밍을 활성화하려는 사용자 정의 도구에서 eager_input_streaming을 true로 설정하고, 요청에서 스트리밍을 활성화하세요.
다음은 API와 함께 세밀한 도구 스트리밍을 사용하는 예시입니다:
Was this page helpful?
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" \
-d '{
"model": "claude-opus-4-6",
"max_tokens": 65536,
"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?"
}
],
"stream": true
}'이 예시에서 세밀한 도구 스트리밍은 Claude가 lines_of_text 매개변수가 유효한 JSON인지 검증하기 위해 버퍼링하지 않고 긴 시의 행들을 도구 호출 make_file로 스트리밍할 수 있게 합니다. 즉, 전체 매개변수가 버퍼링되고 검증될 때까지 기다리지 않고 도착하는 대로 매개변수 스트림을 볼 수 있습니다.
세밀한 도구 스트리밍을 사용하면 도구 사용 청크가 더 빠르게 스트리밍되기 시작하며, 종종 더 길고 단어 구분이 적습니다. 이는 청킹 동작의 차이 때문입니다.
예시:
세밀한 스트리밍 없이 (15초 지연):
Chunk 1: '{"'
Chunk 2: 'query": "Ty'
Chunk 3: 'peScri'
Chunk 4: 'pt 5.0 5.1 '
Chunk 5: '5.2 5'
Chunk 6: '.3'
Chunk 8: ' new f'
Chunk 9: 'eatur'
...세밀한 스트리밍 사용 시 (3초 지연):
Chunk 1: '{"query": "TypeScript 5.0 5.1 5.2 5.3'
Chunk 2: ' new features comparison'세밀한 스트리밍은 버퍼링이나 JSON 유효성 검사 없이 매개변수를 전송하기 때문에, 결과 스트림이 유효한 JSON 문자열로 완료된다는 보장이 없습니다.
특히 중지 이유 max_tokens에 도달하면 스트림이 매개변수 중간에 종료되어 불완전할 수 있습니다. 일반적으로 max_tokens에 도달했을 때를 처리하기 위한 특별한 지원 코드를 작성해야 합니다.
tool_use 콘텐츠 블록이 스트리밍될 때, 초기 content_block_start 이벤트에는 input: {}(빈 객체)가 포함됩니다. 이것은 플레이스홀더입니다. 실제 입력은 각각 partial_json 문자열 조각을 포함하는 일련의 input_json_delta 이벤트로 도착합니다. 코드는 이 조각들을 연결하고 블록이 닫히면 결과를 파싱해야 합니다.
누적 계약:
type: "tool_use"인 content_block_start에서 빈 문자열을 초기화합니다: input_json = ""type: "input_json_delta"인 각 content_block_delta에 대해 추가합니다: input_json += event.delta.partial_jsoncontent_block_stop에서 누적된 문자열을 파싱합니다: json.loads(input_json)초기 input: {}(객체)와 partial_json(문자열) 사이의 타입 불일치는 의도적인 설계입니다. 빈 객체는 콘텐츠 배열의 슬롯을 표시하고, 델타 문자열이 실제 값을 구성합니다.
import json
import anthropic
client = anthropic.Anthropic()
tool_inputs = {} # index -> accumulated JSON string
with client.messages.stream(
model="claude-opus-4-6",
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:
if (
event.type == "content_block_start"
and event.content_block.type == "tool_use"
):
tool_inputs[event.index] = ""
elif (
event.type == "content_block_delta"
and event.delta.type == "input_json_delta"
):
tool_inputs[event.index] += event.delta.partial_json
elif event.type == "content_block_stop" and event.index in tool_inputs:
parsed = json.loads(tool_inputs[event.index])
print(f"Tool input: {parsed}")Python 및 TypeScript SDK는 이 누적을 자동으로 수행하는 상위 수준 스트림 헬퍼(stream.get_final_message(), stream.finalMessage())를 제공합니다. 위의 수동 패턴은 블록이 닫히기 전에 부분 입력에 반응해야 할 때, 예를 들어 진행 표시기를 렌더링하거나 다운스트림 요청을 일찍 시작할 때만 사용하세요.
세밀한 도구 스트리밍을 사용할 때 모델에서 유효하지 않거나 불완전한 JSON을 받을 수 있습니다. 이 유효하지 않은 JSON을 오류 응답 블록에서 모델에 다시 전달해야 하는 경우, 적절한 처리를 위해 JSON 객체로 감쌀 수 있습니다(합리적인 키 사용). 예를 들어:
{
"INVALID_JSON": "<your invalid json string>"
}이 접근 방식은 모델이 콘텐츠가 유효하지 않은 JSON임을 이해하는 데 도움을 주면서 디버깅 목적으로 원래의 잘못된 형식의 데이터를 보존합니다.
유효하지 않은 JSON을 감쌀 때, 래퍼 객체에서 유효한 JSON 구조를 유지하기 위해 유효하지 않은 JSON 문자열의 따옴표나 특수 문자를 적절히 이스케이프해야 합니다.