C.W.K.
Stream
Lesson 04 of 06 · published

Function Call Streaming — fragment 조립

~22 min · streaming, function-calls

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Function call 의 arguments 는 streaming 에서 JSON fragment 로 와. 개별 fragment 는 valid JSON 아냐 — {"loc, ation":", Seoul"} 같이 split. Concat 후 한 번에 json.loads.

왜 fragment 야?

모델이 token 단위로 생성하니까 arguments JSON 도 token 단위로 chunked. 매 token 이 한 chunk. 중간 fragment 에 json.loads 박는 건 guaranteed crash.

Accumulator 패턴

tool_call_id 별로 arguments_str 들고 있고, 매 fragment 를 append, stream 이 tool-call complete 신호 (또는 stream 끝) 일 때만 parse. SDK 가 이걸 abstract 하지만 raw httpx 에선 직접 작성.

여러 tool call 동시

한 turn 에 여러 tool call 이 가능 — tool_calls[i].function.arguments 의 i 가 인덱스. 각 인덱스별 accumulator 따로 — 섞지 마.

Code

Streamed tool arguments 재조립·python
import json

stream = client.chat.completions.create(
    model="gpt-5.4",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather",
            "parameters": {
                "type": "object",
                "properties": {"location": {"type": "string"}},
                "required": ["location"],
            }
        }
    }],
    stream=True,
)

tool_call_accumulator = {}
for chunk in stream:
    delta = chunk.choices[0].delta
    if delta.tool_calls:
        for tc in delta.tool_calls:
            idx = tc.index
            if idx not in tool_call_accumulator:
                tool_call_accumulator[idx] = {"id": "", "name": "", "arguments": ""}
            if tc.id:
                tool_call_accumulator[idx]["id"] = tc.id
            if tc.function.name:
                tool_call_accumulator[idx]["name"] = tc.function.name
            if tc.function.arguments:
                tool_call_accumulator[idx]["arguments"] += tc.function.arguments

# Process accumulated tool calls
for tc in tool_call_accumulator.values():
    args = json.loads(tc["arguments"])
    print(f"Tool: {tc['name']}({args})")

External links

Exercise

Tool 쓰는 stream 실행 + 매 chunk 의 tool_calls fragment log. Concat 으로 full arguments JSON 재현. json.loads 가 끝에서만 성공 검증.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.