Streaming Responses in AI Agents: Implementation Guide for 2026
Waiting 30 seconds for an AI agent to respond kills user experience. Streaming responses in AI agents transforms perceived latency from frustrating to magical—users see responses appear in real-time, word by word.

A 30-second wait while an AI agent "thinks" is the single fastest way to make users abandon it. Streaming fixes this by sending each token to the browser as the model generates it, so the first words appear in under a second even when the full answer takes half a minute. This guide covers how to implement streaming for AI agents with the current Anthropic and OpenAI APIs, the transport choices (SSE vs WebSockets), and the production failure modes most tutorials skip.
What streaming changes for an AI agent
Without streaming, the request cycle looks like this: user sends a message, the agent runs tools, the model generates a full response, and only then does anything render. A complex agentic query can take 20 to 60 seconds of dead air.
With streaming, the same query renders progressively:
- Under 1 second: user sees an acknowledgment or the first sentence
- During tool calls: user sees status updates ("searching your knowledge base", "running the calculation")
- During generation: the answer appears word by word
- On failure: the error surfaces immediately, not after a timeout
The perceived speedup is large even when total latency is unchanged. A worked example with round numbers: assume a model generates 600 tokens at 40 tokens per second. Non-streamed, the user waits the full 15 seconds. Streamed, the first sentence (roughly 20 tokens) arrives in about half a second, and a fast reader is halfway through the answer before the model finishes writing it. You did not make the model faster; you made the wait productive.
How streaming works: SSE vs WebSockets
Server-Sent Events
Most agent streaming uses server-sent events, a plain HTTP response with Content-Type: text/event-stream where the server keeps writing events separated by blank lines. The browser's EventSource API handles parsing and, importantly, auto-reconnects if the connection drops.
A minimal client:
const eventSource = new EventSource('/api/agent/stream?q=' + encodeURIComponent(query));
eventSource.onmessage = (event) => {
const chunk = JSON.parse(event.data);
appendToMessage(chunk.content);
};
eventSource.onerror = () => {
// EventSource retries automatically; close it yourself on fatal errors
eventSource.close();
};
The server keeps the connection open and writes chunks:
app.get('/api/agent/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('X-Accel-Buffering', 'no'); // stops nginx buffering the stream
for await (const chunk of agent.stream(req.query.q)) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
});
That X-Accel-Buffering: no header matters. Nginx and several managed proxies buffer response bodies by default, which silently turns your stream back into a 15-second wait. If streaming works locally but not in production, proxy buffering is the first thing to check.
WebSockets
Use WebSockets when the channel must be bidirectional: the user interrupting the agent mid-answer, voice input streaming in while text streams out, or a long-lived session with many turns over one connection. OpenAI now offers a persistent WebSocket mode for the Responses API for exactly this case.
const ws = new WebSocket('wss://api.example.com/agent');
ws.onmessage = (event) => {
const chunk = JSON.parse(event.data);
if (chunk.type === 'text') appendToMessage(chunk.data);
if (chunk.type === 'done') finalizeMessage();
};
// User clicked "stop"
stopButton.onclick = () => ws.send(JSON.stringify({ type: 'interrupt' }));
The trade-off: WebSockets need explicit reconnection logic, heartbeat pings, and more care with load balancers. For a request-response chat UI, SSE is simpler and usually the right default.
Streaming from the model APIs
Anthropic Claude
The Messages API streams with "stream": true. The Python SDK wraps it in a context manager:
from anthropic import Anthropic
client = Anthropic()
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Summarize this support ticket"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Underneath, the wire format is a documented event sequence: message_start, then per content block a content_block_start, multiple content_block_delta events (text, thinking, or partial tool-input JSON), and content_block_stop, finishing with message_delta (which carries the stop reason and final token usage) and message_stop. ping events can arrive at any time, and Anthropic's streaming docs recommend handling unknown event types gracefully since new ones get added.
Two details worth knowing:
- Token usage only arrives at the end, in
message_delta. Do not try to bill mid-stream. - Tool use streams as partial JSON (
input_json_delta). If you want tool arguments as they generate rather than in one block, enable fine-grained streaming witheager_input_streamingon the tool definition.
OpenAI
The current streaming surface is the Responses API with stream=True:
from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model="gpt-5.5",
input=[{"role": "user", "content": "Summarize this support ticket"}],
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif event.type == "response.completed":
usage = event.response.usage
The Responses API emits typed semantic events (response.created, response.output_text.delta, response.completed, error) rather than raw deltas, so you subscribe to the ones you care about. As with Claude, true token usage is only present in the final response.completed event.
Streaming agent steps, not just tokens
A chatbot streams text. An agent also has intermediate state: which tool it picked, what the tool returned, whether it is retrying. Streaming only the final answer wastes the biggest UX win.
Define a small event protocol between your agent and the UI:
async def stream_agent(query):
yield {"type": "status", "content": "Understanding the request"}
tools = select_tools(query)
for tool in tools:
yield {"type": "tool_start", "tool": tool.name}
result = await tool.run()
yield {"type": "tool_end", "tool": tool.name, "ok": result.ok}
yield {"type": "status", "content": "Writing the answer"}
async with client.messages.stream(...) as stream:
async for text in stream.text_stream:
yield {"type": "text", "content": text}
yield {"type": "done"}
The UI renders each type differently: status lines in muted text, tool calls as collapsible blocks, the answer as normal prose. This is also what makes long-running autonomous work tolerable to watch; the same pattern underpins the always-on agents we describe in our guide to autonomous AI agents for business, and it is how the AI employees service surfaces what a digital employee is doing in real time.
Error handling and reconnection
Streams fail in ways batch requests do not. Plan for three cases.
Mid-stream disconnect. Keep the partial text you already yielded. On retry, send it back as an assistant message so the model continues instead of restarting from zero:
async def stream_with_recovery(messages, max_retries=3):
partial = ""
for attempt in range(max_retries):
try:
request_messages = messages[:]
if partial:
request_messages.append({"role": "assistant", "content": partial})
async with client.messages.stream(
model="claude-sonnet-4-5", max_tokens=1024,
messages=request_messages,
) as stream:
async for text in stream.text_stream:
partial += text
yield text
return
except anthropic.APIConnectionError:
if attempt == max_retries - 1:
raise
await asyncio.sleep(2 ** attempt)
Timeouts. A stream can hang with no error. Wrap consumption in an overall deadline (30 to 120 seconds depending on the task) and treat expiry as a retryable failure.
Client disconnects. If the user closes the tab, detect the broken pipe on res.write and cancel the upstream model request. Otherwise you pay to generate tokens nobody reads. This gets expensive fast on customer-facing workloads; teams running agents in production should pair streaming with the tracing practices in our AI agent monitoring and observability guide.
When streaming is the wrong choice
Streaming is not free complexity. Skip it when:
- The output must be parsed before use. If the agent returns JSON that feeds another system, you need the whole object anyway. Stream to a log if you want progress, but do not build a progressive UI around partial JSON.
- The work is batch or back-office. Nightly report generation, document processing pipelines, and customer service automations that post to a queue gain nothing from token-by-token delivery.
- You are on a platform that cannot hold connections. Some serverless runtimes cap response durations or buffer bodies. Check limits before designing around streaming; a polling pattern ("job started" / "job done") is more robust there.
- Latency is already low. For short answers from a fast model, the difference between streaming and a 1.5-second wait is marginal.
Testing a streaming implementation
Two tests catch most regressions:
- It actually streams. Assert the response arrives in more than one chunk, and measure time to first byte separately from total time. A buffered proxy fails this test even though the final text is correct.
- It survives failure. Kill the connection mid-stream in a test and verify the client either resumes or shows a clean error with the partial answer preserved.
Load testing matters too: a streaming endpoint holds a connection (and usually an upstream model request) per concurrent user. Capacity-plan concurrent connections, not requests per second.
Frequently asked questions
Should I use SSE or WebSockets for an AI chatbot?
Start with SSE. It is plain HTTP, works through most proxies with the right headers, and the browser reconnects automatically. Move to WebSockets only when you need the client to send mid-stream, such as interrupting the agent or streaming voice input alongside output.
Why does my stream arrive all at once in production?
A proxy is buffering it. Nginx needs X-Accel-Buffering: no on the response or proxy_buffering off in its config. Some managed platforms buffer regardless; check their docs before assuming your code is wrong.
How do I stream tool calls as well as the final answer?
Emit your own event types (tool_start, tool_end) around each tool execution and interleave them with the model's text deltas on the same SSE channel. For the arguments themselves, Claude supports fine-grained tool streaming via eager_input_streaming, which yields partial tool-input JSON as it generates.
Does streaming cost more?
No. Token pricing is identical streamed or not. You pay for the same input and output tokens; the usage simply arrives at the end of the stream instead of in a single response body. The only extra cost is holding connections open longer, which is an infrastructure consideration, not a billing one.
Can I stream structured JSON output?
You can stream the tokens, but the JSON is not parseable until it completes. If the consumer is a UI, consider streaming a human-readable answer and fetching the structured version separately. If the consumer is another system, skip streaming entirely.
Where to go from here
Streaming is one piece of a production agent; tool design, evaluation, and observability decide whether it is reliable. If you are building an agent that has to survive real users rather than a demo, our custom builds team designs and ships these systems, and can review an existing implementation that is holding up under load poorly.
About AI Agents Plus Editorial
AI automation expert and thought leader in business transformation through artificial intelligence.



