LLM Response Streaming, Citations, and Server-Sent Events
How major APIs stream LLM tokens, citations, and metadata over SSE—and how to parse each format without losing sources or markup.
Documentation from Perplexity, Cloudflare, Brave Search, and Chrome for Developers describes the same user experience—text that appears token by token—but different wire formats, citation timing, and client responsibilities. This page focuses on those streaming contracts: when to enable streaming, how to read answer text, and how to attach trustworthy sources while the response is still in flight.
Streaming responses: why APIs split output into chunks
Section titled “Streaming responses: why APIs split output into chunks”A streamed LLM response is data emitted incrementally over the network instead of one finished JSON body. That pattern suits long answers, chat UIs, and retrieval-augmented flows where users should see progress immediately.
Streaming allows you to receive partial responses from the Sonar API as they are generated, rather than waiting for the complete response. This is particularly useful for real-time user experiences, long responses, and interactive applications.
— Perplexity, Core Features
Key Term: Streaming breaks up a resource you want to send or receive over a network into smaller chunks. This is common for browsers when receiving media assets, such as video buffering or partial loading of images.
— Chrome for Developers, How LLMs stream responses
By contrast, non-streaming APIs wait for the full generation before returning. Built-in browser APIs illustrate both modes on the client: request-based output versus streaming callbacks or ReadableStream iteration (Built-in AI glossary).
Perplexity Agent API: typed SSE events and the output array
Section titled “Perplexity Agent API: typed SSE events and the output array”The Perplexity Agent API does not mirror legacy Sonar chat completions. Final text lives in the output array as message items with output_text parts—not in choices[0].message.content.
Without an SDK, read the answer from the output array: take items with “type”: “message”, then their content entries with “type”: “output_text”. Agent API responses have no choices[0].message.content; that field belongs to the legacy Sonar Chat Completions format.
— Perplexity, Agent API quickstart
For streaming, enable stream: true on responses.create. Consume typed events, not only text deltas:
Sonar streaming returns incremental chunks with a delta.content field on each choice. The Agent API streams typed server-sent events, so update stream consumers to branch on each event’s type. For the answer text, consume response.output_text.delta events; tool calls and reasoning arrive as their own response.output_item.* and response.reasoning.* events, not as text deltas.
— Perplexity, How to migrate from Sonar
| Concern | Legacy Sonar (chat.completions) |
Agent API (responses) |
|---|---|---|
| Answer text while streaming | choices[0].delta.content |
response.output_text.delta |
| Web citations / search hits | Often in final chunk(s) of Sonar stream | response.reasoning.search_results events and search_results items in output when complete |
| Completed body shape | choices, top-level citations |
output[] with search_results, message, tool items |
Web search is opt-in on the Agent API: a request with only model and input returns no citations unless you add effort or tools: [{"type": "web_search"}] (Agent API quickstart).
Agent API: read citations from structured output, not prose
Section titled “Agent API: read citations from structured output, not prose”For grounded answers, URLs and metadata belong in search_results (or streaming response.reasoning.search_results), not in the model’s paraphrased links.
Read URLs and source metadata from the response payload, not from the model’s written answer. For non-streaming responses, search results are inside response.output[] as items where type == “search_results” … For streaming, listen for response.reasoning.search_results events (again, one per search).
— Perplexity, Prompt Guide
Never ask the model to generate source URLs. Always use the search_results output from the API response. Model-generated URLs can be hallucinated.
— Perplexity, Streaming Citation Parsing
The Web Search tool documents each result’s id, url, title, and snippet; citation markers like [1] map to id when the prompt asks for inline citations.
Legacy Sonar streaming: delta.content and late metadata
Section titled “Legacy Sonar streaming: delta.content and late metadata”Sonar chat completions still follow an OpenAI-style stream of chat.completion.chunk objects with choices[].delta.content (OpenAI SDK Compatibility). Important limitation for UI design:
When streaming, you receive: Content chunks which arrive progressively in real-time … Search results (delivered in the final chunk(s)) … Search results and metadata are delivered in the final chunk(s) of a streaming response, not progressively during the stream.
— Perplexity, Core Features
stream_mode: "concise" splits the stream into multiple object types (chat.reasoning, chat.completion.chunk, chat.completion.done, etc.) so reasoning and search can surface earlier; search results in concise mode appear primarily in chat.reasoning.done and chat.completion.done chunks (Stream Mode: Concise vs Full).
Brave Search Answers: tagged deltas inside delta.content
Section titled “Brave Search Answers: tagged deltas inside delta.content”Brave’s Answers API streams with progressive citations. Because Answers uses richer payloads than plain OpenAI chat, streaming may wrap structured data in tagged strings inside choices[0].delta.content:
Because Answers uses custom messages with richer data than standard OpenAI responses, messages are stringified with special tags. When streaming, you’ll receive: Regular answer content streamed as text.
— Brave, Answers service documentation
Typical handling (from Brave’s streaming example):
- Plain text: append
delta.contentto the visible answer. <citation>…</citation>: parse JSON inside the tags fornumberandurl, render inline links.<usage>…</usage>: parse usage JSON; when streaming, usage metadata arrives as the last message (sync responses expose cost fields in headers).
The OpenAPI-style Answers endpoint documents streaming chunks with choices[].delta.content and optional usage on the final chunk.
For RAG context without full answer generation, Brave LLM Context returns structured grounding.generic[] snippets separately from a chat stream—useful when your app streams tokens from another model but needs grounded passages upfront.
Cloudflare: SSE for Workers AI, AI Search, and Agents
Section titled “Cloudflare: SSE for Workers AI, AI Search, and Agents”Workers AI and gateway streaming
Section titled “Workers AI and gateway streaming”Most Workers AI models accept stream: true and return server-sent events (text/event-stream on some models). Synchronous calls return a single response string plus usage and optional tool_calls.
AI Gateway can relay streams over WebSockets as universal.stream messages with partial response text, bookended by universal.created and universal.done.
AI Search: chunks event before answer tokens
Section titled “AI Search: chunks event before answer tokens”AI Search changed streaming so clients can show sources before generation finishes:
In the new AI Search API, streaming responses include the chunks. The retrieved chunks are sent first as a chunks event, followed by the streamed response data. This allows you to display the source chunks immediately while streaming the generated response to the user.
— Cloudflare, REST API migration
With the Workers binding, chatCompletions({ stream: true }) yields SSE: an event: chunks line with retrieved passages, then data: lines with choices[0].delta.content, ending in data: [DONE].
The Vercel AI SDK integration notes that toTextStreamResponse() streams text only and drops sources; toUIMessageStreamResponse({ sendSources: true }) forwards retrieved chunks as source-url parts before the first text part—matching the native chunks-first ordering.
Show source citations walks through parsing the chunks SSE event and re-emitting a citations event for your UI, including scores and item.key source paths.
Agents platform: SSE, data parts, and WebSockets
Section titled “Agents platform: SSE, data parts, and WebSockets”HTTP and SSE positions SSE for incremental model output on long HTTP connections. Chat agents attach data parts—typed JSON for progress, citations, and usage—alongside message text.
For Workers, streaming over WebSockets with streamText sends { type: "chunk", content } frames until { type: "done" }. Lifecycle onChunk fires per token for observability only.
Autonomous responses expose a finalized UIMessage, status (completed | error | aborted), and requestId after a turn—distinct from the live token stream.
Client rendering: tokens, Markdown, and citation timing
Section titled “Client rendering: tokens, Markdown, and citation timing”Chrome’s streaming guide explains a common UI pitfall: Markdown and code fences can span chunk boundaries, so parsing each chunk independently breaks formatting.
This means if you want to output formatted Markdown, you can’t just process each chunk individually with a Markdown parser.
— Chrome for Developers, How LLMs stream responses
Practical approaches:
- Accumulate raw text, render Markdown on a throttle or at stream end, or use a streaming-safe renderer.
- Track citation markers against accumulated text; a single delta may split
[1]across events (Streaming Citation Parsing). - For Perplexity Agent API streams, extend
search_resultsfrom everyresponse.reasoning.search_resultsevent—multi-step effort levels emit one batch per search, sharing one citation id space (Streaming Citation Parsing).
Gemini URL grounding (when using tools that return annotations) places url_citation on text blocks with start_index / end_index (URL context)—a parallel pattern to bracket citations.
Perplexity Orchestrator and OpenAI-compatible streams
Section titled “Perplexity Orchestrator and OpenAI-compatible streams”The Perplexity Orchestrator supports stream: true on chat completions with SSE. Set stream_options: {"include_usage": true} to receive token usage in a final chunk before data: [DONE].
Routing & Reliability adds operational rules: failures before the first token may failover transparently; if a stream fails mid-output, treat an unterminated stream as incomplete and expect in-band error events.
Common mistakes when implementing streaming
Section titled “Common mistakes when implementing streaming”- Using Sonar parsers on Agent API streams — listen for
response.output_text.delta, notchoices[0].delta.content(migration guide). - Keeping only the first
search_resultsbatch — deep or multi-search runs produce many items; overwriting drops most[N]links (Prompt Guide). - Dropping AI Search
chunkswhen using AI SDK helpers that strip sources (AI SDK). - Ignoring Brave tag messages — failing to handle
<citation>/<usage>breaks inline sources and billing metadata (Answers documentation). - Trusting model-written URLs — bind links to API
search_resultsor chunk metadata (Streaming Citation Parsing). - Assuming Sonar search results stream early — in default full mode they often arrive only in final chunks (Core Features).
How to check this on your site
Section titled “How to check this on your site”- Run a minimal streaming request against your provider’s documented endpoint—for example Perplexity Agent API quickstart, Brave Answers streaming example, or Cloudflare AI Search Workers binding—and confirm tokens arrive before the connection closes.
- Log event types or SSE
event:lines and verify you handle text deltas, source events (chunks,response.reasoning.search_results, or Brave citation tags), and terminal usage/metadata. - Compare structured
search_results/chunksURLs to any[N]markers in accumulated text; unresolved references usually mean a missed batch (Streaming Citation Parsing). - For browser UIs, follow How LLMs stream responses and defer full Markdown rendering until boundaries stabilize.
- You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.