Sub topic 9
Reading the response and message types
This chapter assumes you can already create a session and send a synchronous message, as covered in the previous chapters. You should also be comfortable with Python dictionaries and JSON. Here you will learn what the reply body contains, how to tell the message types apart, and how to write a parser that does not break when the agent does something unexpected.
The shape of a reply
A synchronous call to POST /sessions/{sessionId}/messages returns a JSON object. The important part is the messages array. A reply with one message looks like this:
{
"messages": [
{
"type": "Inform",
"id": "0f2c7a1e-3b4d-4c5e-8a9b-1c2d3e4f5a6b",
"feedbackId": "",
"planId": "",
"isContentSafe": true,
"message": "Your order 10482 shipped yesterday and arrives Friday.",
"result": [],
"citedReferences": []
}
],
"_links": {}
}The fields you will use most often are these:
| Field | Meaning |
|---|---|
| `type` | What kind of message this is. It decides how your code should react. |
| `id` | A unique identifier for this message. |
| `message` | The text for the user. It may be absent or empty for some types. |
| `isContentSafe` | Whether the content passed the trust layer's safety checks. |
| `result` | Structured output attached to the message, often an empty list. |
| `citedReferences` | Sources the agent used, when the agent is set up to cite them. |
| `feedbackId` and `planId` | Identifiers for linking feedback or tracing the plan the agent ran. |
Treat the exact set of fields as something that can grow. Salesforce can add fields, so read the ones you need by name and ignore the rest.
Why `messages` is a list
Your earlier example returned reply.json()["messages"][0]["message"]. That works for a simple agent, but it makes an assumption: that every turn produces exactly one message, and that it carries text.
A single turn can produce more than one message. A turn can also produce a message that is not an answer at all, such as a failure notice or an end-of-session notice. A production client should loop over the whole array and decide what to do with each item.
Message types
The type value tells you what the agent is doing. These are the types you will meet in synchronous replies:
| Type | What it means | What your client should do |
|---|---|---|
| `Inform` | The agent is giving information or an answer. | Show `message` to the user. |
| `Inquire` | The agent needs more input before it can continue. | Show `message` as a question and send the user's answer as the next message. |
| `Failure` | The agent could not complete the turn. | Log the details, show a safe fallback, and decide whether to retry. |
| `Escalate` | The agent is handing off to a human or another channel. | Start your handoff flow and stop sending the agent messages for this conversation. |
| `SessionEnded` | The session is over. | Stop using the session ID. |
The streaming endpoint adds further types, such as progress indicators and text chunks. A later chapter covers those. Check the current Agent API reference for the full list in your org's API version, because the list can change.
The most important rule is this: do not treat a message as an answer just because it has a message field. A Failure can carry text too, and showing it to a customer as if it were a normal reply is a common bug.
A defensive parser
The following program turns a reply body into a small result object and handles each type deliberately. It runs as shown, with no network access, because it parses a sample body.
from dataclasses import dataclass, field
@dataclass
class ParsedReply:
texts: list = field(default_factory=list)
needs_input: bool = False
failed: bool = False
escalated: bool = False
session_ended: bool = False
unknown_types: list = field(default_factory=list)
def parse_reply(body: dict) -> ParsedReply:
parsed = ParsedReply()
for item in body.get("messages", []):
kind = item.get("type")
text = item.get("message") or ""
if item.get("isContentSafe") is False:
# Never show content that failed the safety check.
parsed.failed = True
continue
if kind == "Inform":
parsed.texts.append(text)
elif kind == "Inquire":
parsed.texts.append(text)
parsed.needs_input = True
elif kind == "Failure":
parsed.failed = True
elif kind == "Escalate":
parsed.escalated = True
if text:
parsed.texts.append(text)
elif kind == "SessionEnded":
parsed.session_ended = True
else:
parsed.unknown_types.append(kind)
return parsed
sample = {
"messages": [
{
"type": "Inquire",
"id": "a1",
"message": "Which order number do you mean?",
"isContentSafe": True,
}
]
}
result = parse_reply(sample)
print(result.texts) # ['Which order number do you mean?']
print(result.needs_input) # TrueThree design choices in this parser are worth copying.
- It uses
.get()everywhere. A missing key becomes a default value instead of aKeyError. This matters most formessage, which is not guaranteed on every type. - It checks
isContentSafefirst. If the flag isfalse, the parser does not pass the text on. - It records unknown types instead of raising. If a newer API version adds a type, the client logs it and carries on.
Handling an `Inquire` turn
An Inquire message means the conversation is not finished. The agent has asked something, and your next call must answer it in the same session. Here is the loop in outline:
def converse(send, first_text: str) -> list:
"""send(text) -> parsed reply. Returns all agent texts from the exchange."""
collected = []
reply = send(first_text)
collected.extend(reply.texts)
while reply.needs_input and not (reply.failed or reply.escalated):
answer = input("> ")
reply = send(answer)
collected.extend(reply.texts)
return collectedHere send is any function that posts a message and returns a ParsedReply. Remember that each message needs a sequenceId that is higher than the one before it in the same session. Keep a counter alongside the session ID and increase it on every call.
Failures and the HTTP status code
There are two different kinds of failure, and they look different.
- HTTP-level failure. The request itself was rejected. You get a 4xx or 5xx status code, and
raise_for_status()raises an exception. Examples are an expired token, a bad session ID, or a malformed body. The next chapters cover how to recover from these. - Agent-level failure. The request succeeded with a 200 status code, but the body contains a message of type
Failure. The agent ran into a problem while working on the turn.
A client that only checks the status code will miss the second kind. Always inspect the body, even after a 200.
Citations and structured results
If your agent is configured to ground answers in knowledge, the citedReferences array can list the sources. You can render these as footnotes or links. Treat the array as optional: it is often empty, and your code should not depend on it.
The result array can carry structured data that sits beside the text. Its contents depend on the agent's actions and are not the same for every agent. Print one real reply from your own agent before you write code against result.
Logging for later
Keep the id of each message and the session ID in your logs, and never log tokens. When a user reports a wrong answer, these identifiers let you find the exact turn. If you also store planId, you have a handle for tracing which plan the agent ran, in case you need to raise the issue with your Salesforce admin or with Salesforce support.
Common mistakes
- Reading only
messages[0]and dropping the rest of the array. - Assuming every message has a
messagefield. - Treating
FailureorEscalateas ordinary answers. - Raising an exception on an unknown
type, which breaks the client when the API adds a type. - Reusing a
sequenceId, so the API treats the new message as a duplicate or out of order.
Exercise
Your client receives a 200 response whose body contains one message with type "Failure" and a text field. A teammate's code prints the text to the customer. What is wrong, and what should the client do instead?
Show answer
The code checked only the HTTP status and treated any message with text as an answer. A Failure message means the agent could not complete the turn, and its text may contain internal wording. The client should branch on the message type, log the message id and session ID, show a safe fallback such as "Sorry, I couldn't complete that. Please try again", and decide whether to retry the turn.
Exercise
Why does the parser in this chapter store unknown message types in a list instead of raising an error?
Show answer
The set of message types can grow with new API versions. If the parser raised an exception on an unfamiliar type, a harmless addition would break the whole client. Recording the type lets the client keep working while the team sees in the logs that a new type appeared.