Skip to main content

What you’ll build

Instead of waiting for the full AI response, stream it token-by-token for a ChatGPT-like experience.

How streaming works

When you set stream: true on the messages endpoint, the API returns a Server-Sent Events (SSE) stream instead of a JSON response. The stream emits these events:

TypeScript example

stream.ts
Run it:

Python example

stream.py

React hook example

Build a streaming chat component in React:
useStreamingChat.ts
Usage in a component:

Tips

Use streaming for user-facing chat interfaces where perceived speed matters. Use non-streaming (stream: false) for automated pipelines where you need the complete response before proceeding.
Listen for the error event in the SSE stream. If the connection drops unexpectedly, retry the request. The message won’t be duplicated because the failed message isn’t saved.
First token typically arrives in 300-800ms depending on the model. Total streaming time depends on response length.