Sub topic 6
Understanding the session lifecycle
This chapter assumes you can already get an access token from your My Domain, as covered in the previous chapters. You should also know the agent ID of an activated agent and be comfortable reading short Python and HTTP examples. Here you will learn what a session is, how it moves through its states, and what your code must do at each step.
What a session is
A session is one conversation between your external system and one agent. The agent keeps the history of that conversation on the Salesforce side. When you send "What about the blue one?", the agent can resolve "the blue one" because it remembers your earlier messages in the same session.
Your client therefore does not resend the whole history with each request. It sends only the new message and identifies the conversation by its session ID.
A session also fixes the following for the conversation:
- The agent that answers. You choose it once, in the URL used to create the session.
- The org that hosts the agent, set by the
instanceConfig.endpointvalue (your My Domain URL). - The streaming capabilities the client accepts, set by
streamingCapabilities. - Any context variables supplied at creation. A later chapter covers these.
Changing any of these means creating a new session.
The four stages
Every integration goes through the same four stages.
- Authenticate. Get an access token. This is not part of the session, but every session call needs it.
- Create. Send
POST /agents/{agentId}/sessions. The response contains asessionId. - Exchange messages. Send
POST /sessions/{sessionId}/messages, or the/messages/streamvariant, as many times as the conversation needs. - End. Send
DELETE /sessions/{sessionId}.
The diagram is a model, not a list of values returned by the API. The API does not give you a status field named AwaitingReply. The model helps you decide when each call is legal and what to do when one fails.
Creating the session
The body of the create request carries four fields.
| Field | Purpose |
|---|---|
| `externalSessionKey` | A unique string you generate. A UUID works well. |
| `instanceConfig.endpoint` | Your My Domain URL. |
| `streamingCapabilities.chunkTypes` | The chunk types your client can handle when streaming, for example `["Text"]`. |
| `bypassUser` | When `true`, the session runs as the run-as user configured on your External Client App. |
The externalSessionKey is your handle for the conversation. Store it next to your own record of the conversation, such as a ticket ID or a chat ID. It lets you log, correlate, and debug without depending on the Salesforce-generated ID alone.
The response includes the sessionId. It may also include initial messages, such as a greeting configured on the agent. Check the messages array in the create response before you assume the agent is silent until you speak.
Exchanging messages
Each message you send carries a sequenceId. It is an integer that numbers your messages within the session. Start at 1 and increase it by one for every message you send.
{
"message": {
"sequenceId": 2,
"type": "Text",
"text": "And what about the blue one?"
}
}Three rules keep this stage healthy:
- One message at a time. Wait for the reply to message 1 before you send message 2. The conversation is ordered, and overlapping requests make the order ambiguous.
- Keep the counter on the client. The server does not choose the number for you. If your process restarts mid-conversation, you must restore the last number you used, or end the session and start a new one.
- Reuse the token, not the session, across token refreshes. A session is tied to the conversation. It is not a login. When your access token expires you get a new token and continue using the same session ID. Chapter 13 covers the error handling for this.
The synchronous endpoint returns the whole reply in one response. The streaming endpoint returns the same reply as server-sent events. In both cases the session stays active afterward and is ready for the next message.
Ending the session
End the session with a DELETE request and an x-session-end-reason header. The example below uses UserRequest, which means the person or system on the other side decided the conversation was over.
Ending a session matters for three reasons:
- It tells the platform the conversation is finished, so the work associated with it can be released.
- It marks a clear boundary in the platform's records, which helps when you review conversations later.
- It keeps your own integration tidy. A leaked, never-ended session is hard to tell apart from a conversation still in progress.
Do not rely on expiry as your normal way to end sessions. Idle sessions do expire, but the timing is a platform detail that can change. Check the current Agentforce documentation for the limit that applies to your org. Treat expiry as a safety net for crashes and network loss.
A session wrapper in Python
The code below wraps the whole lifecycle in a context manager. The with block guarantees that the end call runs, and the class owns the sequence counter so callers cannot get it wrong. It assumes the SF_MY_DOMAIN and SF_AGENT_ID environment variables are set, and that you pass in a valid token.
import os
import uuid
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
MY_DOMAIN = os.environ["SF_MY_DOMAIN"]
AGENT_ID = os.environ["SF_AGENT_ID"]
class AgentSession:
def __init__(self, token: str):
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
self.external_key = str(uuid.uuid4())
self.session_id = None
self.sequence_id = 0
def __enter__(self):
response = requests.post(
f"{API_BASE}/agents/{AGENT_ID}/sessions",
headers=self.headers,
json={
"externalSessionKey": self.external_key,
"instanceConfig": {"endpoint": MY_DOMAIN},
"streamingCapabilities": {"chunkTypes": ["Text"]},
"bypassUser": True,
},
timeout=30,
)
response.raise_for_status()
self.session_id = response.json()["sessionId"]
return self
def send(self, text: str) -> 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": text,
}
},
timeout=60,
)
response.raise_for_status()
return response.json()["messages"][0]["message"]
def __exit__(self, exc_type, exc, tb):
if self.session_id:
requests.delete(
f"{API_BASE}/sessions/{self.session_id}",
headers={**self.headers, "x-session-end-reason": "UserRequest"},
timeout=30,
)
return False # do not swallow exceptions
if __name__ == "__main__":
from auth import get_access_token # the function from the token chapter
with AgentSession(get_access_token()) as session:
print(session.send("I want to return an order."))
print(session.send("It was order 1042."))Notes on the design:
__exit__returnsFalse, so an exception inside thewithblock still propagates after the session is ended.- The sequence counter increments before the request. If the request fails, the number is already spent. Decide on a policy for retries, and see the error-handling chapter for the details. Reusing a number is not always safe.
- If
__enter__fails,__exit__does not run, so there is nothing to clean up. That is the correct behavior, because no session exists.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Never ending sessions | Unfinished conversations pile up until they expire | Use a `with` block or `try/finally` |
| Creating a new session per message | The agent forgets all earlier turns | Create once per conversation |
| Sharing one session between users | Users see each other's context | One session per end user conversation |
| Restarting the sequence counter at 1 mid-session | Rejected or misordered messages | Persist the counter, or start a new session |
| Treating a token expiry as a session failure | Needless loss of conversation history | Refresh the token and keep the session ID |
Choosing a session boundary
Deciding when one conversation ends and the next begins is a design choice. Three common patterns:
- One session per customer interaction. A support chat opens a session when the customer starts and ends it when the chat closes. This is the default and the safest choice.
- One session per task. A back-office job that asks the agent to summarize one case opens a session, asks one or two questions, and ends it. Short sessions keep context small and unrelated.
- Long-lived sessions. Only use these when the agent needs memory over a long time. They need careful handling of expiry, so be ready to create a new session and, if needed, give it a summary of the earlier conversation as context.
Exercise
Your service creates a session, sends two messages, and then the access token expires before the third message. What should the service do with the session, and what sequenceId should the third message carry?
Show answer
Request a new access token and keep using the same session ID, because the session is not tied to the token's lifetime. The third message carries sequenceId 3, because the counter continues from the two messages already sent. Create a new session only if the session itself has ended or expired.
Exercise
Why does the wrapper in this chapter end the session in __exit__ instead of at the end of the last send call?
Show answer
__exit__ runs even when an exception is raised inside the with block, so the session is ended on both success and failure paths. Ending it inside send would close it after the first message and break multi-turn conversations.