This prompt is designed for streaming infrastructure teams that consume raw Server-Sent Events (SSE) directly from LLM providers, real-time APIs, or internal event buses. The core job-to-be-done is transforming an unstructured, multi-event text stream into a single, validated, and ordered payload. Use this prompt when you have captured the raw text of an SSE stream—including event:, data:, and id: fields—and need a model to interpret the stream's structure, deduplicate data fields, and handle reconnection gaps signaled by Last-Event-ID headers. The ideal user is a backend engineer or platform developer who already has the raw SSE text in hand and needs to offload the complex parsing logic to an LLM before the assembled payload is passed to downstream application code.
Prompt
SSE Event Stream Parsing and Assembly Prompt Template

When to Use This Prompt
Identifies the specific production scenarios where the SSE Event Stream Parsing and Assembly prompt is the right tool, and when to choose a different approach.
This prompt is not a general-purpose streaming text assembler. Do not use it for simple text chunk assembly from streaming LLM APIs that lack SSE framing; for that scenario, use the Streaming Chunk Assembly Prompt Template. This prompt assumes the input is a complete, captured SSE stream, not a live, incremental feed. It excels at interpreting the protocol-level structure of the stream: extracting multiple data: lines, associating them with their event types, ordering them by id: where present, and resolving the state after a reconnection. A concrete example is processing a stream from an LLM provider that sends tool call arguments across multiple data: events, where the final payload must be a single, valid JSON object with all arguments correctly merged and ordered.
Before using this prompt, ensure you have already captured the raw SSE text and that your application has handled the HTTP connection lifecycle. The prompt's output should be validated against your expected schema using a deterministic post-processing step. If your primary challenge is real-time chunk buffering, overlap detection, or incremental rendering, start with the streaming-specific sibling prompts in this content group. This prompt is the right choice when the problem is interpreting the SSE protocol itself, not managing the live stream.
Use Case Fit
Where the SSE Event Stream Parsing and Assembly prompt template delivers value—and where it introduces risk. Use these cards to decide if this template fits your production context before wiring it into a streaming pipeline.
Good Fit: Real-Time SSE Ingestion Pipelines
Use when: your infrastructure consumes raw Server-Sent Events from LLM providers or backend services and needs to reassemble data: fields into complete, ordered payloads. Guardrail: pair this prompt with a buffer that accumulates events until a termination signal or timeout fires before invoking assembly.
Good Fit: Reconnection Gap Recovery
Use when: SSE connections drop and reconnect, leaving gaps in event streams. The prompt can detect missing id: fields or sequence discontinuities and flag incomplete segments. Guardrail: always include the last known event ID in the prompt context so the model can identify where the gap begins.
Bad Fit: Binary or Non-Text Event Streams
Avoid when: your event stream contains binary payloads, protobuf-encoded data, or non-UTF-8 content. This prompt template assumes text-based SSE fields and will hallucinate or corrupt binary content. Guardrail: decode and validate encoding before the prompt ever sees the payload; use a pre-processing layer for binary-to-text conversion.
Required Input: Event Buffer with Metadata
Risk: without event IDs, timestamps, and retry hints, the model cannot detect ordering violations or gaps. Guardrail: always pass a structured buffer containing id, event, data, and retry fields per event, plus a lastEventId for continuity checks. The prompt should receive this as a typed array, not raw text.
Operational Risk: Silent Data Loss on Partial Assembly
Risk: the model may produce a valid-looking assembled payload that silently drops events from a gap it failed to detect. Guardrail: require the prompt output to include an assembly_gaps array listing any detected discontinuities, and fail closed if gaps exist without explicit human or rule-based approval.
Operational Risk: Ordering Drift Under Load
Risk: high-throughput SSE streams can deliver events out of order, and the model may reorder them incorrectly or miss subtle sequence violations. Guardrail: include explicit sequence numbers or timestamps in each event and instruct the model to sort by those fields before assembly, logging any anomalies for ops review.
Copy-Ready Prompt Template
A reusable prompt template for parsing raw SSE event streams, extracting data fields, handling reconnection gaps, and assembling complete responses with ordering guarantees.
This template is designed for streaming infrastructure teams that consume Server-Sent Events (SSE) and need to reassemble discrete event fragments into coherent, validated payloads. The prompt expects a raw SSE stream as input and produces a structured output that includes the assembled content, a gap report, and an ordering audit. Use this template when your application layer receives raw event text that must be parsed, deduplicated, and validated before downstream consumption. Do not use this template for WebSocket streams, chunked transfer encoding, or non-SSE streaming protocols without adapting the event boundary logic.
textYou are an SSE event stream parser and assembly engine. Your job is to consume a raw Server-Sent Events stream, extract data fields from each event, detect and report gaps caused by reconnection or dropped events, and assemble the complete response payload in correct order. ## INPUT Raw SSE stream text:
[RAW_SSE_STREAM]
code## OUTPUT SCHEMA Return a single valid JSON object with the following structure: { "assembled_content": string, // The complete reassembled payload from all data fields, concatenated in event order "event_count": integer, // Total number of events processed "last_event_id": string | null, // The id of the final event in the stream, or null if no id field present "gaps_detected": boolean, // True if any event sequence gaps were found "gap_report": [ // List of detected gaps, empty if none { "expected_id": string | null, // The event id that was expected but missing "received_id": string | null, // The event id that was actually received after the gap "gap_type": "missing" | "duplicate" | "out_of_order" | "unknown", "description": string // Human-readable explanation of the gap } ], "ordering_valid": boolean, // True if all events arrived in ascending id order (when ids are present) "truncated_stream": boolean, // True if the stream appears to end mid-event or with an unclosed data block "warnings": [string] // Any non-fatal issues encountered during parsing (encoding artifacts, empty data fields, etc.) } ## CONSTRAINTS - Parse event boundaries using the standard SSE double-newline delimiter (\n\n). - Extract the `data` field from each event. If an event contains multiple `data` lines, join them with newlines. - Track event `id` fields for sequence validation. If no id field is present, rely on event order in the stream. - If the stream contains a `retry` field, note it in warnings but do not apply it. - Handle comment lines (starting with `:`) by ignoring them. - If the stream ends with an incomplete event (no double-newline terminator), set `truncated_stream` to true and assemble whatever partial data is available. - Do not invent or hallucinate event content. Only use data explicitly present in the input stream. - If the input is empty or contains no valid SSE events, return `assembled_content` as an empty string with `event_count` set to 0. ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL]
Adaptation guidance: Replace [RAW_SSE_STREAM] with the actual SSE text your application received. The [EXAMPLES] placeholder should be replaced with 2-3 few-shot examples showing correct parsing behavior, including at least one example with a detected gap and one with a truncated stream. Set [RISK_LEVEL] to low, medium, or high based on your use case—this controls whether the prompt includes additional validation instructions or requests for human review. For high-risk applications such as financial transaction streams or clinical data feeds, add a constraint requiring that any gap of type missing triggers an immediate escalation rather than silent assembly.
Before deploying this prompt, validate the output against the JSON schema defined above. Common failure modes include the model treating SSE comment lines as data, failing to join multi-line data fields correctly, or misidentifying out-of-order events when id fields are non-numeric. Run this prompt against a golden dataset of known SSE streams—including streams with injected gaps, duplicates, and truncation—and confirm that gaps_detected, ordering_valid, and truncated_stream match expected values before releasing to production.
Prompt Variables
Replace each placeholder with concrete values before sending to the model. Validation notes describe how to programmatically verify the input before prompt assembly.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_SSE_STREAM] | The raw Server-Sent Events text stream to parse, including event boundaries, data fields, IDs, and retry directives | event: message\ndata: {"chunk": 1}\n\nevent: message\ndata: {"chunk": 2}\n\n | Non-empty string required. Validate presence of at least one event boundary (\n\n). Reject empty or whitespace-only input. |
[EXPECTED_EVENT_TYPES] | Whitelist of event type names the parser should extract; all other event types are ignored | ["message", "error", "done"] | Must be a valid JSON array of strings. Each element must be a non-empty string. Empty array means no events will be extracted—warn if empty. |
[OUTPUT_SCHEMA] | JSON Schema describing the expected shape of the assembled output payload | {"type": "object", "properties": {"full_text": {"type": "string"}, "chunks_received": {"type": "integer"}}, "required": ["full_text", "chunks_received"]} | Must parse as valid JSON Schema draft-07 or later. Validate with a schema validator before prompt assembly. Reject if schema is malformed. |
[ID_FIELD] | The SSE event ID field name used to detect gaps and reconnection boundaries | "id" | Must be a non-empty string matching a key present in SSE event data lines. If null, gap detection is disabled. Validate against known SSE field names. |
[MAX_GAP_TOLERANCE] | Maximum number of missing event IDs allowed before the assembly is flagged as incomplete | 3 | Must be a non-negative integer. Value of 0 means no gaps tolerated. Validate as integer >= 0. If null, treat as unlimited tolerance. |
[TIMEOUT_MS] | Maximum wall-clock time in milliseconds to wait for missing events before finalizing assembly | 5000 | Must be a positive integer. Used by the application layer, not the model. Validate as integer > 0. If null, no timeout is applied. |
[REQUIRE_COMPLETION_SIGNAL] | Whether the assembler must wait for an explicit completion event before finalizing output | Must be boolean true or false. When true, assembly is incomplete until a done or complete event type is received. Validate as strict boolean. | |
[COMPLETION_EVENT_TYPE] | The event type name that signals the stream is complete and assembly should finalize | "done" | Must be a non-empty string present in [EXPECTED_EVENT_TYPES]. Validate membership in the expected event types array. Reject if not whitelisted. |
Implementation Harness Notes
How to wire the SSE parsing prompt into a production streaming infrastructure with validation, retries, and observability.
This prompt template is designed to sit inside a stream-processing worker that consumes raw Server-Sent Events from an upstream provider or internal service. The worker's job is to accumulate discrete data: lines, detect event boundaries, handle reconnection gaps, and pass the assembled buffer to the LLM only when assembly is required—typically after a connection drop, an out-of-order sequence, or a malformed event payload. Do not call the model for every event; reserve it for repair and assembly scenarios where deterministic parsing fails.
Wire the prompt into an event-processing pipeline with the following stages: (1) Raw ingestion—a long-lived HTTP client or WebSocket listener that buffers SSE lines and tracks id and retry fields. (2) Deterministic pre-processing—a lightweight parser that extracts data fields, decodes UTF-8, and appends to an ordered buffer keyed by event ID or sequence number. (3) Anomaly detection—a rules engine that flags gaps in sequence numbers, unclosed JSON objects, duplicate IDs, or events arriving outside the expected time window. (4) LLM assembly gate—only when anomalies exceed a threshold (e.g., missing sequence range > 3 events, or unparseable JSON), construct the prompt with [RAW_EVENT_STREAM], [GAP_DESCRIPTION], and [EXPECTED_SCHEMA], then call the model. (5) Output validation—run the model's assembled output through a JSON Schema validator matching [EXPECTED_SCHEMA]. On failure, retry once with the validation error injected into [PREVIOUS_ERRORS]. If the retry also fails, log the raw events and assembled output, then escalate to a dead-letter queue for human review or offline repair.
Model choice and latency budget: Use a fast, instruction-following model with strong JSON output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet, or a fine-tuned open-weight model). Set response_format to json_object or equivalent structured output mode. Keep the prompt concise—token overhead directly adds latency to an already-latent repair path. Target < 500ms p95 for the LLM call; if your provider cannot meet this, consider a local model for the assembly path. Retry strategy: Implement exponential backoff with jitter for transient provider errors (429, 503). For validation failures, retry exactly once with the error context. Do not retry on safety refusals or content policy blocks—escalate immediately. Logging and observability: Emit structured logs at each stage: sse.raw.received, sse.anomaly.detected, sse.assembly.llm_called, sse.assembly.validation_passed, sse.assembly.dead_letter. Include the event range, gap description, model latency, and validation result. This trace is essential for tuning anomaly thresholds and identifying upstream providers that frequently produce malformed streams.
What to avoid: Do not send the entire event stream history to the model on every call—include only the affected window plus a small context buffer (e.g., 2 events before and after the gap). Do not use this prompt for real-time event-by-event processing; it is a repair path, not a hot path. Do not trust the model's output without schema validation—models can hallucinate event data to fill gaps. Finally, ensure your dead-letter queue has retention and alerting; silent data loss in event assembly can corrupt downstream state for hours before detection.
Expected Output Contract
Defines the fields, types, and validation rules for the assembled SSE event stream output. Use this contract to build post-processing validators before the payload enters downstream systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
assembled_payload | string | Must be non-empty and contain the concatenated data fields from all processed events in correct order. | |
event_count | integer | Must equal the number of data-carrying events processed. Parse check: count matches the number of extracted event blocks. | |
event_sequence | array of objects | Each object must contain id, event_type, and data fields. Array order must match the original SSE stream order. Schema check: validate against [EVENT_SEQUENCE_SCHEMA]. | |
first_event_id | string or null | Must match the id field of the first event in the stream. Null allowed only if the stream contained zero events. | |
last_event_id | string or null | Must match the id field of the last event in the stream. Null allowed only if the stream contained zero events. | |
truncated | boolean | Must be true if the stream ended without a closing event or if max_events limit was reached before stream completion. Parse check: inspect stream termination condition. | |
gap_detected | boolean | Must be true if any event id discontinuity was found. Parse check: compare sequential event ids against expected increment pattern. | |
reconnection_events | array of objects | If present, each object must contain reconnect_at index and missing_event_ids array. Schema check: validate against [RECONNECTION_SCHEMA]. Empty array allowed if no reconnections occurred. |
Common Failure Modes
SSE streams break in predictable ways. Here are the most common failure modes when parsing and assembling event streams, and how to guard against them in production.
Silent Event Boundary Corruption
What to watch: Network intermediaries, proxies, or load balancers can inject extra newlines or strip `
delimiters, causing events to merge or split incorrectly. The parser silently concatenates adjacent data fields or treats a single event as two. **Guardrail:** Validate event boundaries with a strict state machine that resets on double-newline only. Reject or quarantine events whereid:anddata:` fields arrive in unexpected order. Log boundary anomalies as structured metrics.
Reconnection Gap Data Loss
Multi-Line Data Field Fragmentation
What to watch: SSE allows multi-line data: fields, but naive parsers that read line-by-line may treat each line as a separate data payload. JSON objects split across lines become unparseable fragments. Guardrail: Buffer all consecutive data: lines until an empty line or a different field type appears. Concatenate with newline separators before parsing. Unit-test with multi-line JSON payloads containing embedded newlines.
Stale Event Type Routing
What to watch: Custom event: fields route payloads to typed handlers, but if the server reuses event type names with changed schemas after a deployment, the assembly logic applies the wrong parser. Guardrail: Version event type names (e.g., message.v2) or include a schema version field in the data payload. Validate the data against the expected schema before assembly. Reject events with unknown or mismatched schema versions.
Duplicate Event Delivery After Reconnect
What to watch: SSE Last-Event-ID is best-effort. Servers may resend the last event or replay from an earlier point, causing duplicate events in the assembled output. Guardrail: Maintain a set of processed event IDs. Deduplicate on receipt before assembly. If the server does not provide event IDs, use a content hash of the data field. Log deduplication rates to detect server-side replay bugs.
Partial UTF-8 Sequence at Chunk Boundary
What to watch: Streaming HTTP responses may split a multi-byte UTF-8 character across two TCP packets or read buffers. The parser sees an invalid byte sequence and either replaces it with a replacement character or crashes. Guardrail: Use a streaming UTF-8 decoder that handles incomplete sequences at buffer boundaries. Never assume each chunk is valid UTF-8 independently. Test with emoji and non-Latin scripts that use 3-4 byte encodings.
Evaluation Rubric
Run these checks against a golden dataset of known SSE streams with expected assembled outputs. Each criterion targets a specific failure mode in streaming assembly.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Event Boundary Integrity | All SSE event boundaries are correctly identified; no events are merged or split incorrectly | Adjacent events concatenated into one; single event split across multiple parsed events | Compare parsed event count and boundaries against golden stream annotations |
Data Field Extraction Accuracy | All data fields extracted from events match golden data exactly, including whitespace and special characters | Missing data field content; extra characters included; escape sequences not decoded | String equality check between extracted data fields and golden expected values per event |
Event Ordering Preservation | Assembled events maintain the exact sequence order from the source SSE stream | Events appear out of order; timestamp or sequence number gaps indicate reordering | Compare event ID or sequence number order in assembled output against golden stream order |
Reconnection Gap Handling | Gaps from Last-Event-ID reconnection are detected and flagged; no silent data loss | Missing events between reconnection points not detected; assembled output appears complete but is missing segments | Inject known gaps into golden streams; verify gap detection flag is raised and missing range is reported |
Assembled Payload Completeness | Final assembled output contains all expected content from all events, with no truncation | Missing content from one or more events; final output shorter than sum of event data fields | Concatenate all golden event data fields; compare length and content against assembled output |
Duplicate Event Filtering | Duplicate events (same event ID) are detected and only one instance retained in assembly | Duplicate content appears in assembled output; event ID collisions not resolved | Inject duplicate event IDs into test stream; verify exactly one instance per ID in output |
Multiline Data Field Assembly | Data fields spanning multiple lines are correctly reassembled with newline characters preserved | Multiline data fields truncated at first newline; extra line breaks inserted; blank lines mishandled | Include events with known multiline data fields in golden set; verify exact newline preservation |
Comment and Non-Data Field Handling | SSE comment lines and non-standard fields are ignored in data assembly but logged for observability | Comment content leaks into assembled data; non-data fields treated as data; events with only comments produce empty data entries | Include comment-only events and mixed comment-data events in test stream; verify data assembly excludes comments |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add explicit reconnection gap handling, schema validation, and idempotency checks. Include the last known event ID and timestamp so the model can detect gaps. Require the model to output a structured assembly report alongside the payload.
code[RAW_SSE_EVENTS] [LAST_EVENT_ID_BEFORE_RECONNECT] [EXPECTED_OUTPUT_SCHEMA] Reassemble events into a valid [OUTPUT_FORMAT] payload. Flag any gaps in the event sequence. Report: missing_event_ids, duplicate_event_ids, truncation_detected.
Watch for
- Schema drift when the SSE source changes its event shape
- High-latency streams where buffering strategy affects ordering
- Missing human review for critical event types (e.g., payment confirmations)

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us