Sub topic 11
Streaming replies as they are generated
This chapter assumes you can already get an access token, create a session, and send a synchronous message, as covered in earlier chapters. You should also be comfortable reading short Python and curl examples.
Why stream a reply
A synchronous call to the messages endpoint returns only after the agent has finished. If the agent runs several actions and writes a long answer, the user waits with no feedback. Streaming sends the reply in pieces as the agent produces it. Your application can show text as it arrives, which makes a chat window feel responsive.
Streaming does not make the agent faster. The total time is about the same. What changes is the time until the first visible output.
| Aspect | Synchronous | Streaming |
|---|---|---|
| Endpoint | `/sessions/{sessionId}/messages` | `/sessions/{sessionId}/messages/stream` |
| Accept header | `application/json` | `text/event-stream` |
| Response | One JSON body | A series of server-sent events |
| First output | After the whole reply is ready | As soon as the first chunk is ready |
| Client code | Simple | Must parse an event stream |
Choose streaming for interactive chat interfaces. Choose the synchronous call for batch jobs, background workflows, and any case where you only need the final text.
How server-sent events work
The streaming endpoint uses server-sent events (SSE). SSE is a standard way for a server to push a sequence of messages over one long-lived HTTP response. The connection stays open and the server writes events to it over time.
Each event is a block of text lines followed by a blank line. Lines that start with event: name the event type. Lines that start with data: carry the payload, which here is JSON. A simplified stream looks like this:
event: PROGRESS_INDICATOR
data: {"message": {"type": "ProgressIndicator", "message": "Looking up your order"}}
event: TEXT_CHUNK
data: {"message": {"type": "TextChunk", "message": "Your order "}}
event: TEXT_CHUNK
data: {"message": {"type": "TextChunk", "message": "shipped yesterday."}}
event: INFORM
data: {"message": {"type": "Inform", "message": "Your order shipped yesterday."}}
event: END_OF_TURN
data: {"message": {"type": "EndOfTurn"}}The event names and payload fields above are a simplified illustration. Check the current Agent API reference for the exact names in your org's release, and log a few raw streams before you write a parser.
Opting in at session creation
The session creation request includes a streamingCapabilities object with a list of chunkTypes. The earlier example used ["Text"]. This declares what kinds of streamed chunks your client can handle.
{
"externalSessionKey": "b5c1f1de-7a0e-4a8e-9a42-2f2f4e7d6a11",
"instanceConfig": { "endpoint": "https://mycompany.my.salesforce.com" },
"streamingCapabilities": { "chunkTypes": ["Text"] },
"bypassUser": true
}Set this when you create the session, even if you plan to use the synchronous endpoint for some messages. Then the same session can serve either style.
Sending a streaming request with curl
The curl command below posts a message to the streaming endpoint. The -N flag turns off curl's output buffering, so events print as they arrive instead of after the connection closes.
curl -N -X POST "https://api.salesforce.com/einstein/ai-agent/v1/sessions/$SESSION_ID/messages/stream" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{"message": {"sequenceId": 2, "type": "Text", "text": "What is the status of my order?"}}'Two details matter here:
- The
Accept: text/event-streamheader tells the server you want an event stream. Without it you may get an error or a normal JSON reply. - The
sequenceIdmust increase with each message in a session. This is the second message, so it uses 2.
Reading the stream in Python
In a real application you read the stream line by line and handle each event as it arrives. The requests library supports this with stream=True and iter_lines.
import json
import os
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
def stream_message(token: str, session_id: str, sequence_id: int, user_text: str):
"""Yield (event_name, payload) pairs from the streaming endpoint."""
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "text/event-stream",
}
body = {"message": {"sequenceId": sequence_id, "type": "Text", "text": user_text}}
with requests.post(
f"{API_BASE}/sessions/{session_id}/messages/stream",
headers=headers,
json=body,
stream=True,
timeout=(10, 120),
) as response:
response.raise_for_status()
event_name = None
for raw_line in response.iter_lines(decode_unicode=True):
if raw_line is None:
continue
line = raw_line.strip()
if not line:
event_name = None # a blank line ends one event
elif line.startswith("event:"):
event_name = line[len("event:"):].strip()
elif line.startswith("data:"):
data_text = line[len("data:"):].strip()
try:
payload = json.loads(data_text)
except json.JSONDecodeError:
continue # ignore a malformed or partial data line
yield event_name, payload
if __name__ == "__main__":
token = os.environ["ACCESS_TOKEN"]
session_id = os.environ["SESSION_ID"]
for name, payload in stream_message(token, session_id, 2, "What is the status of my order?"):
message = payload.get("message", {})
if message.get("type") == "TextChunk":
print(message.get("message", ""), end="", flush=True)
print()The function is a generator. It yields each event as soon as it is parsed, so the caller can print text immediately. The timeout is a pair: 10 seconds to connect, then 120 seconds allowed between bytes received. A long agent action can leave the stream quiet for a while, so do not set the read timeout too low.
The shape of a streamed turn
A streamed turn follows a predictable order. Progress events may appear first while the agent works. Text chunks follow as the answer is written. A final event marks the end of the turn.
Your client should treat the end-of-turn event as the signal that the agent has finished. Only then should you enable the input box again or send the next message.
Edge cases and failure modes
Streaming adds failure modes that the synchronous call does not have.
- Errors after the stream starts. The HTTP status code is sent before the body. If the agent fails halfway, the status is still 200, and the failure appears as an error event or a dropped connection. Check for error events inside the stream, not only the status code.
- Dropped connections. Networks and proxies close idle connections. If the stream ends without an end-of-turn event, treat the turn as incomplete. Do not assume the partial text is the full answer.
- Proxy buffering. Some reverse proxies and load balancers buffer responses, which defeats streaming. Disable response buffering for the route that relays the stream.
- Retries and duplicates. If you retry a failed streaming request with the same
sequenceId, you may get unexpected behavior. Decide whether to resend the message or start a fresh turn, and test that case. - Expired tokens. A token that expires during a long stream does not interrupt the open connection, but your next request will fail with 401. Refresh the token before starting a new turn if it is close to expiring.
- Partial chunks. A text chunk is a fragment, not a word or sentence. Concatenate chunks in order. Do not try to format or parse them until the turn is complete.
Relaying a stream to a browser
If your own users sit behind a web page, do not send the Salesforce access token to the browser. Run the Agent API call on your server and relay the events. Your server can forward each text chunk to the browser over its own SSE endpoint or a WebSocket. This keeps the client secret and token on the server and lets you add your own logging and rate limits.
Summary of the practical rules
- Declare
streamingCapabilitieswhen you create the session. - Call the
/messages/streamendpoint withAccept: text/event-stream. - Read line by line, group lines into events, and parse the
data:JSON. - Append text chunks in order and wait for the end-of-turn event.
- Use generous read timeouts and handle dropped connections.
- Keep tokens on the server.
Exercise
Your streaming client prints text as it arrives, but the connection drops after two chunks and no end-of-turn event is received. The HTTP status was 200. What should the client do, and why is the status code not enough to detect this failure?
Show answer
The client should treat the turn as incomplete. It should discard the partial text or label it as incomplete, and then retry or start a new turn according to its retry policy. The status code is not enough because the server sends the 200 status before the body begins. A failure partway through the stream cannot change it. The only reliable signs of success are an end-of-turn event, and the absence of error events.
Exercise
A colleague runs the Python streaming example through a corporate proxy. Nothing prints for 30 seconds, and then all the text appears at once. The same code works when run directly. What is the most likely cause, and what would you change?
Show answer
The proxy is probably buffering the response, so the events arrive in one batch when the connection closes or a buffer fills. Disable response buffering for that route in the proxy configuration, or route the call around the proxy. Testing with curl -N through the same proxy confirms the diagnosis.