Skip to content

案例:OpenAI 流式 Tool Calls

流式输出下,OpenAI 的 tool call 信息可能按增量到达。

你需要处理的事情

  • 记录当前 tool call id
  • 拼接函数名
  • 拼接 arguments 字符串
  • 在结构完整后再解析 JSON

一个简化思路

python
buffers = {}

for event in stream:
    delta = event.choices[0].delta
    if not delta.tool_calls:
        continue

    for tc in delta.tool_calls:
        idx = tc.index
        buffers.setdefault(idx, {"id": None, "name": "", "arguments": ""})

        if getattr(tc, "id", None):
            buffers[idx]["id"] = tc.id
        if getattr(tc.function, "name", None):
            buffers[idx]["name"] += tc.function.name
        if getattr(tc.function, "arguments", None):
            buffers[idx]["arguments"] += tc.function.arguments

# 流结束后再统一解析 buffers

为什么不要边收边 parse

因为 arguments 往往是分块到达的,半截 JSON 基本一定会解析失败。

聚焦 OpenClaw、tool_calls、function calling 与 agent 实战。