Skip to main content
Set stream: true. Responses normally use text/event-stream. Prefer SDK parsing: a network chunk is not an SSE event, and one event can span multiple chunks.

Endpoint differences

Role, tool-call, and usage chunks may have no text; choices can be empty. Chat’s length means a generation limit was reached. tool_calls requires tool handling and is not a complete natural-language answer. An HTTP 200 can still be followed by an event-level error or a dropped connection. Mark retained partial text as incomplete. Do not treat EOF as success or automatically replay a generation that has already started.

Python: Chat Completions

Follow the Python SDK guide to install dependencies and set environment variables. Save as stream-chat.py and run python stream-chat.py. This text-only example treats only finish_reason=stop as complete.

TypeScript: Responses

Follow the TypeScript SDK guide. Save as stream-responses.mts and run node stream-responses.mts. Select a model that supports streaming Responses.

Deployment and usage

If all text arrives at once, check response buffering and timeouts in the gateway or reverse proxy. Cancelling a client reader does not guarantee that upstream execution stops. Chat’s stream_options.include_usage requires channel support; usage events may have no choices. Responses usage usually appears in the final response. A dropped connection may prevent final usage from arriving. Consult console logs; missing usage does not mean zero usage. Reference: OpenAI streaming events.

Native protocols and streaming tools

Claude Messages and Gemini generateContent provide dedicated native protocol examples. For argument assembly and function execution, see Chat / Responses streaming tools. Runnable native SSE and tool loops for Claude and Gemini include completion validation and signature preservation. 简体中文