This prompt is for real-time agent developers who need to consume, classify, and act on Server-Sent Event (SSE) streams from external tools. The core job is to turn a raw, potentially unreliable stream of text events into structured, actionable tool-call lifecycle states—such as tool_start, tool_progress, tool_result, and tool_error—while maintaining connection health and ordering guarantees. The ideal user is an AI platform engineer or integration developer building a production agent harness that must survive connection drops, out-of-order events, and malformed payloads without corrupting the agent's downstream state.
Prompt
Server-Sent Event Tool Stream Parsing Prompt Template

When to Use This Prompt
Define the job, reader, and constraints for the Server-Sent Event Tool Stream Parsing Prompt Template.
Use this prompt when your agent directly consumes SSE from an API, an MCP server, or a long-running tool endpoint, and you need the model to act as a programmable stream parser. This is appropriate when the stream protocol is known but the event types, reconnection logic, and error-recovery rules must be enforced by the agent itself rather than by a separate middleware service. Do not use this prompt for simple request-response tool calls, for WebSocket-based streams that require binary frame handling, or for streams where the tool's event schema is completely unknown and must be discovered at runtime. The prompt assumes you can provide the expected event type catalog, the Last-Event-ID tracking rules, and the reconnection policy as part of the input context.
Before deploying, validate the prompt against at least three failure scenarios: a mid-stream connection drop with partial event delivery, an event with a malformed data field that violates the expected schema, and a stream that resumes after a reconnect with an out-of-order id. If the agent's downstream actions include state mutations, database writes, or user-visible conclusions, require a human review gate or a strict idempotency check before acting on the parsed stream output. This prompt is a parsing and classification layer—it does not replace the application logic that consumes the parsed events.
Use Case Fit
Where the SSE Tool Stream Parsing prompt works, where it fails, and the operational prerequisites for production use.
Good Fit: Real-Time Agent Dashboards
Use when: you are building an agent UI that must display tool output as it arrives, such as a log stream, progress bar, or live data feed. The prompt excels at classifying event, error, and done types while maintaining last-event-id for reconnection. Guardrail: always pair the prompt with a client-side buffer that can reassemble partial chunks before rendering.
Bad Fit: Strictly Ordered Transactional Workflows
Avoid when: the downstream system requires exactly-once, in-order processing of every event without gaps. SSE inherently allows gaps during reconnection, and the prompt's multiplexing logic trades strict ordering for liveness. Guardrail: for transactional guarantees, use a pull-based or message-queue tool contract instead and validate sequence numbers at the application layer.
Required Input: Connection State Context
What to watch: the prompt cannot function without the current connection state, including last-event-id, reconnect count, and active stream identifiers. Missing state causes duplicate processing or silent data loss. Guardrail: inject a structured [CONNECTION_STATE] object into the prompt template on every invocation, and validate it before the model call.
Required Input: Event Schema Registry
What to watch: the model will hallucinate event type classifications if it does not know the valid event types and their expected fields. Guardrail: provide a [EVENT_SCHEMA_REGISTRY] as part of the prompt context, listing each event type, its required fields, and an example payload. Update the registry when the tool API evolves.
Operational Risk: Reconnection Storms
What to watch: a flapping connection can cause the agent to loop on reconnection logic, burning tokens and hitting rate limits. The prompt's reconnection state handling can amplify this if not bounded. Guardrail: implement a circuit breaker outside the prompt that limits reconnection attempts per time window and escalates to a human operator after a threshold.
Operational Risk: Stream Multiplexing Drift
What to watch: when multiple tool streams are multiplexed over a single connection, the model can miscorrelate events to the wrong stream, especially under high throughput. Guardrail: include a [STREAM_MAP] in the prompt that explicitly maps stream IDs to tool names, and add an eval check that verifies the stream_id field is present on every classified event.
Copy-Ready Prompt Template
A reusable prompt template for parsing Server-Sent Event streams from tool calls, handling reconnection, event classification, and stream multiplexing.
This prompt template is designed for real-time agent developers who need to consume and interpret Server-Sent Event (SSE) streams from tool calls. It instructs the model to act as a stream parser that classifies event types, tracks last-event-id for reconnection state, and handles multiplexed streams where multiple logical event sequences arrive over a single connection. The template is structured to produce a deterministic JSON output that your application can consume directly, making it suitable for wiring into an AI harness that processes live tool streams.
textYou are an SSE stream parser for a real-time agent system. Your job is to consume a raw Server-Sent Event stream from a tool call and produce a structured analysis of the stream state. ## INPUT Raw SSE stream text: [SSE_STREAM_INPUT] ## CONTEXT - The stream may contain multiple event types: `data`, `event`, `id`, `retry`, and comment lines starting with `:`. - The stream may be multiplexed, containing events from multiple logical streams identified by an `event` field prefix (e.g., `stream1:data`, `stream2:data`). - The `id` field carries the last-event-id for reconnection. You must track the most recent `id` value seen. - The `retry` field specifies the reconnection time in milliseconds. - The stream may be truncated mid-chunk. You must identify incomplete events. ## OUTPUT SCHEMA Produce a valid JSON object with the following structure: { "events": [ { "event_type": "string", // The event type, or "unknown" if not specified "data": "string", // The data payload "id": "string | null", // The event ID if present "stream_id": "string | null" // The logical stream identifier if multiplexed } ], "last_event_id": "string | null", // The most recent event ID for reconnection "retry_ms": "number | null", // The reconnection interval if specified "truncated": "boolean", // True if the input ended mid-event "multiplexed_streams": ["string"] // List of unique logical stream IDs detected } ## CONSTRAINTS - Do not invent events not present in the input. - If the input is empty or only contains comments, return an empty events array. - For multiplexed streams, extract the stream ID from the event type prefix before the colon. - If a data field spans multiple lines, join them with newlines. - If the input ends with an incomplete event (no blank line terminator), set truncated to true and include the partial event if possible. ## EXAMPLES Input: id: 1\nevent: stream1:data\ndata: {\"value\": 42}\n\nid: 2\nevent: stream2:data\ndata: {\"value\": 99}\n\n Output: { "events": [ {"event_type": "stream1:data", "data": "{\"value\": 42}", "id": "1", "stream_id": "stream1"}, {"event_type": "stream2:data", "data": "{\"value\": 99}", "id": "2", "stream_id": "stream2"} ], "last_event_id": "2", "retry_ms": null, "truncated": false, "multiplexed_streams": ["stream1", "stream2"] } ## RISK LEVEL [RISK_LEVEL] Parse the input stream and return only the JSON object.
To adapt this template for your application, replace the [SSE_STREAM_INPUT] placeholder with the raw text from your SSE connection. Set [RISK_LEVEL] to guide the model's handling of ambiguous or malformed events—use low for best-effort parsing in non-critical paths, or high to instruct the model to flag anomalies explicitly and avoid guessing. For production use, always validate the output JSON against your expected schema before passing parsed events to downstream agent logic. If your stream contains sensitive data, ensure the SSE input is sanitized before reaching the model, or run this prompt in a local deployment where data does not leave your environment.
Prompt Variables
Inputs the prompt needs to reliably parse, classify, and manage Server-Sent Event (SSE) tool streams. Wire these variables into your application before sending the prompt.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SSE_STREAM] | The raw, unparsed SSE text stream from the tool connection. | event: tool_progress data: {"pct": 45} | Must be a non-empty string. Validate that it contains at least one event: or data: line. If empty, abort the prompt call and trigger a connection health check. |
[EVENT_TYPE_SCHEMA] | A JSON Schema or list of known event type strings the agent should classify. | ["tool_progress", "tool_result", "tool_error", "heartbeat"] | Must be a valid JSON array of strings. Validate with a JSON parser. If null or empty, the prompt should default to generic event classification without domain-specific labels. |
[LAST_EVENT_ID] | The last event ID the client successfully processed, used for reconnection state. | "evt_9a3f2" | Must be a string or null. If null, the prompt should assume a fresh connection with no prior state. Validate that it does not contain newline characters to prevent log injection. |
[RECONNECTION_POLICY] | Instructions for how the agent should handle stream interruptions. | "exponential_backoff_5_retries" | Must be one of a predefined set of policy strings (e.g., 'fail_fast', 'exponential_backoff_5_retries'). Validate against an allowlist in application code before prompt injection. |
[STREAM_IDENTIFIER] | A unique label for this stream to enable multiplexing logic. | "db_migration_42" | Must be a non-empty string. Validate that it matches the pattern ^[a-zA-Z0-9_-]+$ to prevent injection or routing errors in multiplexed environments. |
[OUTPUT_SCHEMA] | The strict JSON schema the final parsed output must conform to. | {"type": "object", "properties": {"events": {"type": "array"}}, "required": ["events"]} | Must be a valid, parseable JSON Schema object. Validate with a schema validator before passing to the prompt. If null, the prompt should return a default event array without strict field enforcement. |
[CONNECTION_TIMEOUT_MS] | The maximum time in milliseconds the client will wait for a new event before considering the connection stale. | 30000 | Must be a positive integer. Validate that the value is between 1000 and 300000. If null, the prompt should assume a default of 30 seconds and flag any gaps longer than that as potential stalls. |
Implementation Harness Notes
How to wire the SSE parsing prompt into a production agent loop with validation, retries, and observability.
This prompt is designed to sit inside a real-time agent's event ingestion pipeline, not as a standalone chat interaction. The model receives raw Server-Sent Event text—potentially interleaved from multiple streams—and must produce structured classification, state tracking, and multiplexing decisions that downstream code can act on. The implementation harness wraps this prompt in a thin application layer that handles connection lifecycle, buffers partial event text, calls the model when a decision boundary is reached, validates the structured output, and applies the resulting instructions to the active stream handlers.
The core integration pattern is a decision-point dispatcher. Your SSE client accumulates raw event lines in a per-stream buffer. When a decision boundary is reached—such as a dispatch event, a reconnection signal, an id field change, or a buffer-size threshold—the harness assembles the prompt with the current [RAW_EVENT_TEXT], [STREAM_STATE] (including lastEventId, reconnectStatus, and activeStreamIds), and [OUTPUT_SCHEMA] (a strict JSON schema for the expected classification and action payload). The model response is parsed and validated before any action is taken. If validation fails, the harness retries with the validation error injected into [PREVIOUS_ERRORS]. After a configurable retry limit (typically 2), the harness falls back to a safe default: log the raw event, increment a parse_failure metric, and either drop the event or route it to a dead-letter queue depending on the [RISK_LEVEL] parameter.
For connection-drop recovery, the harness must track lastEventId outside the prompt and feed it back in on reconnect. The prompt's reconnection classification output tells the harness whether to replay from the last acknowledged ID or start fresh. Implement this as a state machine with three modes: NORMAL, RECONNECTING, and DRAINING. The prompt's output transitions between these modes. Log every mode transition with the triggering event text and the model's classification for post-incident trace analysis. For stream multiplexing, maintain a map of streamId -> buffer and only pass the buffer for the stream that triggered the decision boundary, plus a summary of other active stream states. This prevents cross-stream contamination while giving the model enough context to detect ordering anomalies across streams.
Model choice matters here. This is a low-latency, high-reliability classification task. Use a fast model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small open-weight model) with response_format set to JSON mode and a low temperature (0.0–0.1). Do not use a large reasoning model for this hot path—the added latency will break real-time stream processing guarantees. Instrument every model call with a trace span that captures: prompt version, input token count, output token count, latency, validation pass/fail, retry count, and the resulting action. This trace data is essential for debugging silent stream corruption and for tuning buffer-size thresholds.
Before shipping, build an eval harness that replays recorded SSE streams—including connection drops, out-of-order events, duplicate IDs, and malformed event text—and asserts that the harness produces the correct classifications, state transitions, and multiplexing decisions. Add adversarial cases: empty event data, events with only comments, streams that never send a dispatch signal, and rapid-fire reconnections. The eval should also measure end-to-end latency from event arrival to action dispatch, with a p99 target appropriate for your real-time requirements. If the prompt or harness logic changes, rerun the full eval suite and compare trace-by-trace before deployment.
Expected Output Contract
Defines the structured JSON output the model must produce after parsing an SSE stream. Use this contract to validate the response before passing it to downstream tool orchestration logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
events | Array of objects | Must be a non-empty array. If no events are parsed, return an empty array with a populated | |
events[].event_type | String (enum) | Must match one of the predefined event types: | |
events[].event_id | String or null | If present in the SSE | |
events[].data | Object or null | Parsed JSON payload of the SSE | |
events[].retry_ms | Integer or null | Extracted from the SSE | |
events[].timestamp_iso | String (ISO 8601) | The time the event was parsed by the system, not the event's own timestamp. Used for ordering and latency checks. Must be a valid ISO 8601 string. | |
stream_metadata | Object | Contains summary information about the stream processing session. | |
stream_metadata.last_event_id | String or null | The | |
stream_metadata.connection_state | String (enum) | Final state of the stream connection. Must be one of: | |
parse_errors | Array of objects | Must be an empty array if parsing was clean. Otherwise, contains objects describing each unparseable chunk. | |
parse_errors[].raw_chunk | String | The raw, unparseable text from the stream. Truncate to 500 characters. | |
parse_errors[].reason | String (enum) | Must be one of: |
Common Failure Modes
SSE stream parsing breaks in predictable ways under production load. These are the most common failure modes and the specific guardrails that prevent them.
Silent Connection Drop During Incomplete Event
What to watch: The SSE connection terminates mid-event before the double-newline delimiter arrives. The parser holds a partial event in the buffer but never flushes it, causing silent data loss with no error surfaced to the agent. Guardrail: Implement a buffer flush timeout. If no new data arrives within [STREAM_STALL_MS], flush the partial buffer as a truncated event with a truncated: true flag and emit a stream:stall diagnostic event.
Last-Event-ID Drift After Reconnection
What to watch: On reconnect, the client sends Last-Event-ID from a stale local state, causing the server to replay already-processed events or skip events that arrived during the disconnection window. Duplicate processing and gaps both corrupt agent state. Guardrail: Maintain a persistent, monotonically increasing event sequence counter independent of the SSE id field. On reconnect, compare the server's id against the local counter and explicitly request replay or acknowledge the gap before processing resumes.
Event Type Misclassification Under Partial Chunk Arrival
What to watch: The event: field arrives in a separate chunk from the data: field. A naive line-by-line parser classifies the event type as unknown or defaults to message before the event: line is received, routing the tool result to the wrong handler. Guardrail: Buffer all lines belonging to a single event until the double-newline delimiter is received. Only classify and dispatch after the complete event is assembled. Validate that event: and data: fields are both present before routing.
Multiline Data Field Assembly Corruption
What to watch: SSE data: fields spanning multiple lines are joined incorrectly—extra newlines are inserted, trailing whitespace is stripped, or lines are concatenated without the required single newline separator. The resulting JSON payload fails to parse downstream. Guardrail: Collect all consecutive data: lines into an array, join with , and validate the assembled string against the expected output schema before passing it to the tool result handler. Log assembly failures with the raw line buffer for debugging.
Reconnection Storm Under Transient Server Errors
What to watch: The server returns a 5xx or the connection is refused. The client retries immediately without backoff, creating a tight reconnect loop that amplifies server load and prevents recovery. Guardrail: Implement exponential backoff with jitter on reconnect attempts. Start at [INITIAL_RETRY_DELAY_MS], double on each failure up to [MAX_RETRY_DELAY_MS]. Emit a stream:backoff event so the agent can decide whether to escalate or wait.
Stream Multiplexing Cross-Contamination
What to watch: Multiple tool streams share a single SSE connection identified by a stream ID in the event data. A parser bug routes chunks from stream A to stream B's handler when IDs collide or when a chunk arrives without an explicit stream identifier. Guardrail: Enforce strict stream ID extraction from every event before dispatch. Reject events with missing or unknown stream IDs. Maintain per-stream buffers keyed by stream ID and validate that no event is routed to a stream that has already been closed or finalized.
Evaluation Rubric
Criteria for evaluating the quality of an SSE stream parsing prompt's output before deploying to production. Each criterion targets a specific failure mode common in real-time event stream processing.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Event Type Classification Accuracy | All standard SSE event types (event, data, id, retry, comment) are correctly classified with 100% accuracy on a golden set of 50 mixed events. | A 'data' event is misclassified as a 'comment', or a custom event type is forced into a standard bucket. | Run prompt against a labeled dataset of raw SSE lines and compare classification output to ground truth labels. |
Last-Event-ID Tracking | The [LAST_EVENT_ID] is correctly extracted, stored, and included in the reconnection request after a simulated connection drop. | The reconnection request omits the Last-Event-ID header, or uses the ID from a stale event that was not the most recent. | Simulate a disconnect after event 5, verify the reconnection request body contains |
Reconnection State Recovery | After a simulated connection drop, the prompt correctly outputs a | The prompt outputs a | Inject a connection error after a valid event stream, then check the parsed output for the |
Stream Multiplexing Isolation | When processing a stream with two interleaved event types, the output correctly separates events into distinct logical streams without cross-contamination. | A data field from Stream A appears in the parsed output for Stream B, or a single event is duplicated across both streams. | Feed a multiplexed stream with two distinct event name prefixes and verify that the parsed output maintains strict field isolation. |
Malformed Chunk Handling | A line missing a colon delimiter (e.g., | The parser crashes, outputs a null event, or silently drops the malformed line and the next valid event. | Inject a malformed line into a valid stream and assert that the output contains a |
Event Ordering Guarantee | The parsed output array maintains the exact chronological order of events as they appeared in the raw stream. | An event with a later timestamp appears before an earlier one in the output array, or the order is non-deterministic. | Provide a stream with monotonically increasing timestamps and assert that the output array's timestamps are strictly ascending. |
Comment and Whitespace Resilience | Lines beginning with a colon (:) or empty lines are correctly ignored and do not appear in the parsed event payload. | A comment line is included as a | Inject comment lines and blank lines into a stream and verify they are absent from the final structured output. |
Retry Field Parsing | A | The retry value is parsed as a string, is null, or defaults to an incorrect value. | Include a |
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
Start with the base SSE parsing prompt but relax strict event ordering and schema validation. Focus on classifying the main event types (event:, data:, id:, retry:) and extracting payloads. Use a simple accumulator pattern without full reconnection state.
codeYou are an SSE stream parser. Classify each received event line into one of: [EVENT_TYPE], [DATA_CHUNK], [EVENT_ID], [RETRY_MS], or [COMMENT]. For [DATA_CHUNK] lines, accumulate the payload until an empty line signals event completion. Input stream chunk: [RAW_SSE_CHUNK]
Watch for
- Multi-line
data:fields not being joined correctly - Missing
event:type defaulting tomessagewithout explicit handling - Comments (
:) being treated as data - No reconnection or
Last-Event-IDtracking, so stream resume will fail

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