Two assembly protocols
Fragments from different calls may interleave. Accumulate arguments per call; never parse or execute partial JSON. The Chat example expects complete IDs/names when first supplied, then omission or repetition of the same value; it does not concatenate names. The SDK decodes SSE and UTF-8. The example does not independently verify the
[DONE] string consumed by the SDK.
Setup
Install the existing OpenAI SDK following TypeScript or Python; no new dependencies are required. Set the gateway token inAPI_KEY, then configure a Base URL including /v1:
node examples/stream-tools.mts or .venv/bin/python examples/stream-responses-tools.py. If you save the code separately, run node stream-tools.mts or python stream-responses-tools.py. The prompt requests 7 × 8; the model chooses the wording of its final answer.
TypeScript: Chat Completions
stream-tools.mts
Python: Responses
stream-responses-tools.py
Execution and failure policy
- Both scripts wait for the complete turn, validate allowed tool names, IDs, and all arguments, and implement only a local
multiplyoperation without external effects. Strict schemas do not replace local validation. - Limits are four calls and 512 events per turn, with at most three model requests; the third must return final text. Arguments are limited to 16,384 UTF-16 code units in TypeScript or characters in Python. Chat text is limited to 100,000 code units. These are example safeguards, not server limits, and do not bound individual event bytes before SDK decoding.
- Responses compares argument deltas, done arguments, and final output, then replays complete output items, including reasoning / encrypted_content / phase, and tool results.
store: falseavoids response-ID continuation; field preservation still depends on the channel. - Final text is buffered until stream completion validates. HTTP 401/429, event errors, refusals, truncation, missing completion markers, unknown tools, repeated IDs, invalid arguments, and limit violations exit nonzero without another request or automatic retry.
Local verification and protocol scope
npm run check:examples executes these files against a local HTTP fixture. It checks interleaved calls, UTF-8 split across network chunks, complete history and result association, second requests, and absence of further requests after failures. Simulated responses cannot prove that a real model selects tools or that a channel preserves every event. Validate with an authorized test model before deployment.
Native Claude and native Gemini use different blocks, events, and result structures; these scripts do not implement those native protocols.
References: OpenAI function calling, Responses streaming events.
Runnable native SSE and tool loops for Claude and Gemini include completion validation and signature preservation.
阅读中文