Streaming Guide
How to use Server-Sent Events for real-time progressive output
Streaming Guide
MarketIntell supports real-time streaming via Server-Sent Events (SSE). Instead of waiting for the full pipeline to complete, you receive progressive updates as each specialist runs.
How SSE Streaming Works
When you set stream: true in your chat request, the API keeps the connection open and sends events as they happen:
- tool_call_started — The agent has begun processing (data gathering + reasoning)
- tool_call_completed — Agent processing finished with latency info
- text_delta — Chunks of the response content (may be one large chunk or multiple)
- done — Stream complete with session ID, specialists used, and latency
- error — If something goes wrong mid-stream
Each event uses named SSE events with an event: field, a JSON data: payload, and an incrementing id::
event: tool_call_started
data: {"tool":"agent"}
id: 0
There is always a blank line between events. This is part of the SSE specification.
JavaScript Example
Using Fetch with ReadableStream
async function streamChat(message: string, apiKey: string) {
const response = await fetch("https://api.marketintell.ai/v1/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": apiKey,
},
body: JSON.stringify({ message, stream: true }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
const reader = response.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullContent = "";
let currentEvent = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Process complete lines
const lines = buffer.split("\n");
buffer = lines.pop() || ""; // Keep incomplete line in buffer
for (const line of lines) {
if (line.startsWith("event: ")) {
currentEvent = line.slice(7);
continue;
}
if (!line.startsWith("data: ")) continue;
const data = JSON.parse(line.slice(6));
switch (currentEvent) {
case "tool_call_started":
showLoadingIndicator(data.tool);
break;
case "tool_call_completed":
hideLoadingIndicator(data.tool, data.latencyMs);
break;
case "text_delta":
fullContent += data.delta;
renderMarkdown(fullContent);
break;
case "done":
displaySpecialists(data.specialists_used);
displayLatency(data.latency_ms);
break;
case "error":
showError(data.error);
break;
}
}
}
return fullContent;
}Using EventSource (GET-only Alternative)
EventSource only supports GET requests. For POST-based SSE like MarketIntell, use the Fetch API with ReadableStream as shown above, or use a library like
eventsource-parser.
Using eventsource-parser
import { createParser } from "eventsource-parser";
const response = await fetch("https://api.marketintell.ai/v1/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": "YOUR_API_KEY",
},
body: JSON.stringify({ message: "BTC analysis", stream: true }),
});
const parser = createParser((event) => {
if (event.type === "event" && event.data) {
const data = JSON.parse(event.data);
// event.event contains the SSE event name: tool_call_started, text_delta, done, etc.
console.log(event.event, data);
}
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
parser.feed(decoder.decode(value, { stream: true }));
}Python Example
import requests
import json
def stream_chat(message: str, api_key: str):
response = requests.post(
"https://api.marketintell.ai/v1/chat",
headers={
"Content-Type": "application/json",
"X-API-Key": api_key,
},
json={"message": message, "stream": True},
stream=True,
)
response.raise_for_status()
full_content = ""
current_event = ""
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8")
# Track the SSE event name
if decoded.startswith("event: "):
current_event = decoded[7:]
continue
if not decoded.startswith("data: "):
continue
data = json.loads(decoded[6:])
if current_event == "tool_call_started":
print(f"[Started] {data['tool']}")
elif current_event == "tool_call_completed":
print(f"[Completed] {data['tool']} in {data['latencyMs']}ms")
elif current_event == "text_delta":
full_content += data["delta"]
print(data["delta"], end="", flush=True)
elif current_event == "done":
print(f"\n\nSpecialists: {data['specialists_used']}")
print(f"Latency: {data['latency_ms']}ms")
elif current_event == "error":
print(f"Error: {data['error']}")
break
return full_contentParsing Events
Events use named SSE events — the type is in the event: field, not inside the JSON payload. Each data: line contains a JSON object whose shape depends on the event type:
| SSE Event Name | Data Fields | Description |
|---|---|---|
tool_call_started | tool | Agent processing has begun (always "agent") |
tool_call_completed | tool, latencyMs | Agent processing finished with timing info |
text_delta | delta | A chunk of the response content (append to build full text) |
done | session_id, specialists_used, latency_ms, timestamp | Final metadata |
error | session_id, error, latency_ms, timestamp | Error description |
Rendering Progressive Output
For the best user experience:
- Show a loading indicator when
tool_call_startedarrives - Hide loading / show timing when
tool_call_completedarrives - Render text_delta incrementally — append each delta and re-render the Markdown
- Show metadata after done — display specialists used and latency
// React-style pseudocode
function ChatMessage() {
const [loading, setLoading] = useState(false);
const [content, setContent] = useState("");
const [meta, setMeta] = useState(null);
// In your stream handler:
// case "tool_call_started": setLoading(true)
// case "tool_call_completed": setLoading(false)
// case "text_delta": setContent(prev => prev + data.delta)
// case "done": setMeta({ specialists: data.specialists_used, latency: data.latency_ms })
}Error Handling During Streams
Streams can fail mid-delivery. Always handle errors:
- HTTP errors — Check
response.okbefore reading the stream - Stream errors — Handle the
errorevent type - Connection drops — Catch exceptions from
reader.read() - Timeouts — Implement a client-side timeout (recommended: 60 seconds)
try {
const response = await fetch(url, options);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || `HTTP ${response.status}`);
}
// Read stream...
} catch (err) {
if (err.name === "AbortError") {
console.log("Request timed out");
} else {
console.error("Stream error:", err.message);
}
}Use an
AbortControllerwith a timeout for production implementations. See the Error Handling Guide for complete retry strategies.