Search Tutorials
--Ads--Streaming RAG Responses
Stream answers token by token for a responsive user experience.
A RAG answer can take several seconds to generate. Waiting for the whole response before showing anything feels slow; showing words as they are produced feels fast, even when the total time is the same. Streaming sends the answer token by token as the model writes it. This lesson shows streaming in a script and how to structure a streaming RAG response with sources.
Streaming with the Python SDK
The SDK's messages.stream() helper gives you an iterator over text as it arrives, and the complete message at the end.
import anthropic
client = anthropic.Anthropic()
def stream_answer(prompt: str, system: str) -> str:
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=4000,
output_config={"effort": "low"},
system=system,
messages=[{"role": "user", "content": prompt}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True) # show each piece immediately
final = stream.get_final_message()
print()
if final.stop_reason == "max_tokens":
print("[answer was cut off: increase max_tokens]")
elif final.stop_reason == "refusal":
print("[the model declined this request]")
return "".join(b.text for b in final.content if b.type == "text")
get_final_message() returns the same object a non-streaming call would have returned, including usage for token accounting and stop_reason. Always check the stop reason: a response that ends with max_tokens is incomplete.
The order of a streaming RAG response
Retrieval happens before generation, so you already know the sources when the first token arrives. A good streaming interface sends events in this order:
- Sources: the retrieved documents (titles and links), so the UI can show them immediately.
- Answer tokens, as they are generated.
- Done: final metadata, such as which sources were actually cited, and token usage.
import json
import re
def rag_events(question: str, retriever):
"""A generator of JSON events for a streaming API (see the FastAPI lesson)."""
hits = retriever.search(question, k=5)
yield json.dumps({"type": "sources",
"sources": [{"id": i, "title": h.metadata.get("title", h.id)}
for i, h in enumerate(hits, start=1)]})
sources = "\n".join(f'<source id="{i}">\n{h.text}\n</source>' for i, h in enumerate(hits, start=1))
prompt = (f"<sources>\n{sources}\n</sources>\n\nAnswer using the sources and cite ids like [1]. "
f"Say so if they don't contain the answer.\n\nQuestion: {question}")
with client.messages.stream(model="claude-opus-5-5", max_tokens=2000,
output_config={"effort": "low"},
messages=[{"role": "user", "content": prompt}]) as stream:
for text in stream.text_stream:
yield json.dumps({"type": "token", "text": text})
final = stream.get_final_message()
answer = "".join(b.text for b in final.content if b.type == "text")
yield json.dumps({"type": "done",
"cited": sorted({int(n) for n in re.findall(r"\[(\d+)\]", answer)}),
"stop_reason": final.stop_reason,
"output_tokens": final.usage.output_tokens})
In a web application, these events travel to the browser as Server-Sent Events (SSE). The lesson Serving RAG as an API with FastAPI wires this generator into an HTTP endpoint.
Measuring what users feel
With streaming, the important latency is time to first token (TTFT): the time from the question to the first visible word. In RAG it equals retrieval time plus the model's time to start generating. Measure it separately from total time:
import time
start = time.perf_counter()
first_token_at = None
for event in rag_events("Can I work from home on Fridays?", retriever):
if first_token_at is None and '"type": "token"' in event:
first_token_at = time.perf_counter()
print(f"time to first token: {first_token_at - start:.2f}s, total: {time.perf_counter() - start:.2f}s")
Practical notes
- Errors mid-stream. A network or API error can happen after some text has been shown. Send an "error" event and let the UI show a retry option instead of leaving a half-finished answer.
- Markdown rendering. Streaming Markdown renders incomplete syntax (an unclosed
**) for a moment. Most chat UI libraries handle this; if yours does not, render on each line break. - Long outputs. Streaming also avoids HTTP timeouts on long generations, so use it for any request with a large
max_tokens. - Post-processing. Checks that need the whole answer, such as citation validation or guardrails, run after the "done" event. If a check fails, the UI can replace or annotate the streamed text.
Key takeaways
- Streaming shows the answer as it is generated, which greatly improves perceived speed.
- Use
messages.stream(), iteratetext_stream, then readget_final_message()for the stop reason and usage. - Send sources first, then tokens, then a final "done" event with metadata.
- Track time to first token, and handle mid-stream errors and post-stream checks.