Sub topic 8
Sending a message and getting a reply
This chapter covers the synchronous message call: you send one message to an open session and wait for the agent's full reply in a single HTTP response. It assumes you can already get an access token and create a session, as covered in earlier chapters. You should also be comfortable with REST calls, JSON bodies, and short Python examples.
What a synchronous message call does
After you create a session, you have a sessionId. Every message you send belongs to that session. The agent keeps the conversation history on the Salesforce side, so each call only needs the new user message, not the earlier turns.
The synchronous endpoint holds the HTTP connection open while the agent reasons, runs its topics and actions, and writes the answer. It returns the finished reply in one response body. This is the simplest way to integrate, and it fits batch jobs, back-end services, and tests. If a user is watching a screen and waiting, the streaming endpoint covered later gives a better experience.
The request
Send a POST to the messages endpoint of the session:
POST https://api.salesforce.com/einstein/ai-agent/v1/sessions/{sessionId}/messagesThe request needs two headers:
Authorization: Bearer <access token>, the token from the client credentials flow.Content-Type: application/json.
The body has one top-level message object:
| Field | Meaning |
|---|---|
| `sequenceId` | A number that identifies this message's position in the conversation. |
| `type` | The kind of message. For user input this is `Text`. |
| `text` | The words the user typed. |
The sequenceId is the field people most often get wrong. Start at 1 for the first message in a session and increase it by one for every message you send after that. The API uses it to keep turns in order. If you reuse a number or skip around, expect an error or a confusing reply. Your client should own this counter for the lifetime of the session.
A minimal body looks like this:
{
"message": {
"sequenceId": 1,
"type": "Text",
"text": "Where is my order 10042?"
}
}The response
A successful call returns HTTP 200 and a JSON body. The reply sits in a messages array. Each item has its own type and message text, plus other fields such as an identifier. A shortened response looks like this:
{
"messages": [
{
"type": "Inform",
"id": "0f0e1d2c-0000-0000-0000-000000000000",
"message": "Order 10042 shipped yesterday and should arrive on Friday."
}
]
}The exact set of fields can grow over time, so read only the ones you need and ignore the rest. The next chapter covers the message types in detail. For now, treat messages as a list that can hold more than one entry and read the text from each entry's message field.
A working example
The code below sends one message and prints the reply. It reuses the session you created earlier and keeps the sequenceId in a small class, so you can send several turns without mixing up the numbers.
import os
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
class AgentConversation:
"""Sends messages to one existing session and tracks sequenceId."""
def __init__(self, token: str, session_id: str):
self.session_id = session_id
self.sequence_id = 0
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def send(self, user_text: str) -> list[str]:
self.sequence_id += 1
response = requests.post(
f"{API_BASE}/sessions/{self.session_id}/messages",
headers=self.headers,
json={
"message": {
"sequenceId": self.sequence_id,
"type": "Text",
"text": user_text,
}
},
timeout=60,
)
response.raise_for_status()
body = response.json()
return [item["message"] for item in body.get("messages", []) if "message" in item]
if __name__ == "__main__":
conversation = AgentConversation(
token=os.environ["ACCESS_TOKEN"],
session_id=os.environ["SESSION_ID"],
)
for text in conversation.send("Where is my order 10042?"):
print(text)
for text in conversation.send("Can I change the delivery address?"):
print(text)Run it with ACCESS_TOKEN and SESSION_ID set in the environment. The second call sends sequenceId 2, and the agent answers with the first turn still in mind. You do not resend the earlier question.
A few details in this code are deliberate:
- The counter is incremented before the request. If the request fails, you decide whether to resend the same number or move on. Section "Failures and retries" below explains the choice.
timeout=60is longer than the 30 seconds used for token and session calls. Agent replies can take several seconds when the agent calls Flows, Apex, or other actions.body.get("messages", [])and the"message" in itemcheck keep the function from raisingKeyErrorwhen an entry has no text.
Timing and timeouts
A synchronous reply takes as long as the agent's slowest step. A simple answer from instructions alone may return in a couple of seconds. A turn that queries records, calls an external service, and then summarizes can take noticeably longer.
Set the client timeout above the longest turn you expect. If the client gives up first, the agent may still finish the work on the Salesforce side. That matters when the action has side effects, such as creating a case, because a blind retry can run the action twice.
Also consider whatever sits between your code and Salesforce, such as a load balancer or API gateway. Its idle timeout must be longer than your client timeout, or it will cut the call first.
Failures and retries
Most errors on this call fall into a few groups.
| Status | Usual cause | What to do |
|---|---|---|
| 400 | Malformed body, missing field, or a bad `sequenceId` | Fix the request. Do not retry unchanged. |
| 401 | Expired or invalid access token | Get a new token, then retry once. |
| 404 | Unknown or already ended session | Create a new session. |
| 429 | Too many requests | Wait, then retry with backoff. |
| 5xx | Temporary problem on the service side | Retry with backoff, with care for side effects. |
The retry rule for messages is stricter than for token requests. Fetching a token twice is harmless. Sending a message twice can make the agent act twice. Before you retry after a timeout or a 5xx, ask whether the action behind the message is safe to repeat. If it is not, prefer to surface the failure to the user or check the result in Salesforce first.
Handling of expired tokens and backoff is covered in full in the error handling chapter. Here it is enough to know that a 401 on a message call means the token has expired, not that the session is gone. The session may still be alive.
Common mistakes
- Reusing a
sequenceId. Keep one counter per session and never reset it mid-conversation. - Sending to an ended session. Once you delete a session, its ID is dead. Create a new one for a new conversation.
- Assuming exactly one reply. The
messagesarray is a list. Loop over it instead of reading index 0 blindly, as the simple example in the earlier session chapter did for brevity. - Sharing one session between users. The session holds conversation history. Mixing users in one session leaks context from one person to another.
- Setting a short timeout. A 5 second timeout will fail on any turn that runs a real action.
Trying it with curl
You can test the same call from a terminal without writing code:
curl -X POST "https://api.salesforce.com/einstein/ai-agent/v1/sessions/$SESSION_ID/messages" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message": {"sequenceId": 1, "type": "Text", "text": "Where is my order 10042?"}}'This is a quick way to separate problems in your code from problems in the agent. If curl works and your program does not, compare headers and body. If both fail the same way, look at the agent, the session, or the token.
Exercise
Your client sent sequenceId 3, the request timed out after 60 seconds, and the agent's action was "create a support case". What should you check before sending the message again, and which sequenceId considerations apply?
Show answer
First check in Salesforce whether the case was created, because the server may have finished the work after the client gave up. Retrying blindly could create a duplicate case. If you decide the message was not processed, resend it with the same sequenceId 3 so the conversation numbering stays consistent. If you move on to a new message after a confirmed result, use 4.
Exercise
A response arrives with HTTP 401 on the second message of a conversation. Is the session lost, and what is the correct next step?
Show answer
No. A 401 means the access token is expired or invalid, not that the session ended. Request a new token, then resend the same message with the same sequenceId and the new token. Only create a new session if you get a 404 for the session.