Sub topic 10
Ending the Session
This chapter assumes you can already obtain an access token, create a session, and send a message, as covered in the earlier chapters. It focuses on closing the session you opened, and on what can go wrong when you don't.
Why ending a session matters
A session is the server-side conversation state for one agent interaction. It holds the message history, the variables the agent has collected, and any context that topics and actions rely on. Creating a session allocates that state. Ending it releases the state and tells Salesforce the conversation is finished.
If you never end a session, it does not stay open forever. It eventually times out on the Salesforce side. Relying on that timeout has costs:
- The conversation stays "in progress" in the agent's session records and analytics until the timeout fires. Reports then mix finished conversations with abandoned ones.
- Your integration cannot tell Salesforce why the conversation stopped, so the end reason is lost.
- A long-running service that opens many sessions and never closes them leaves a large number of dangling sessions.
Ending the session explicitly is a small cost for a clean record.
The end session request
Ending a session is one HTTP call. You send DELETE to the session resource and include a header that states the reason.
| Part | Value |
|---|---|
| Method | `DELETE` |
| URL | `https://api.salesforce.com/einstein/ai-agent/v1/sessions/{sessionId}` |
| `Authorization` header | `Bearer` followed by a valid access token |
| `x-session-end-reason` header | `UserRequest` |
| Body | None |
The x-session-end-reason header records why the session ended. UserRequest is the right value when your application ends the conversation because the user finished or left. Use it for normal closure.
Here is the same call with curl:
curl -X DELETE "https://api.salesforce.com/einstein/ai-agent/v1/sessions/$SESSION_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "x-session-end-reason: UserRequest"The call needs the same access token type as the other session calls. If the token has expired since you created the session, the delete fails with an authorization error, and you must refresh the token and retry. The next chapters on error handling cover refresh in detail.
Where the call belongs in your code
The most common mistake is placing the delete call after the code that reads the reply. If reading the reply raises an exception, the delete line never runs. Put it in a finally block so it runs on both success and failure.
The example from the earlier chapter already does this. Here it is again, with the end step highlighted by its comment:
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"]
def run_conversation(token: str, user_text: str) -> str:
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
# 1. Create the session
session = requests.post(
f"{API_BASE}/agents/{AGENT_ID}/sessions",
headers=headers,
json={
"externalSessionKey": str(uuid.uuid4()),
"instanceConfig": {"endpoint": MY_DOMAIN},
"streamingCapabilities": {"chunkTypes": ["Text"]},
"bypassUser": True,
},
timeout=30,
)
session.raise_for_status()
session_id = session.json()["sessionId"]
try:
# 2. Send a message and wait for the full reply
reply = requests.post(
f"{API_BASE}/sessions/{session_id}/messages",
headers=headers,
json={"message": {"sequenceId": 1, "type": "Text", "text": user_text}},
timeout=60,
)
reply.raise_for_status()
return reply.json()["messages"][0]["message"]
finally:
# 3. Always end the session
requests.delete(
f"{API_BASE}/sessions/{session_id}",
headers={**headers, "x-session-end-reason": "UserRequest"},
timeout=30,
)Notice two details.
- The
tryblock starts only after the session exists. If session creation fails, there is no session to end, so thefinallyblock must not run. Putting thetrybefore creation would call delete with an undefinedsession_id. - The delete call sets a timeout. Without one, a network stall during cleanup can hang your program.
Why the `finally` block is not the whole story
The code above has a weakness. If the delete call itself fails, for example because of a network error or an expired token, the exception raised inside finally replaces the original result or error. A successful reply would be lost because cleanup failed.
Cleanup should never change the outcome of the conversation. A safer version catches errors from the delete call and logs them:
import logging
import requests
logger = logging.getLogger(__name__)
def end_session(api_base: str, token: str, session_id: str) -> None:
try:
response = requests.delete(
f"{api_base}/sessions/{session_id}",
headers={
"Authorization": f"Bearer {token}",
"x-session-end-reason": "UserRequest",
},
timeout=30,
)
response.raise_for_status()
except requests.RequestException as exc:
# Do not raise: the conversation result matters more than cleanup.
logger.warning("Could not end session %s: %s", session_id, exc)Call end_session(API_BASE, token, session_id) from the finally block instead of the inline requests.delete. A failed cleanup is now logged, and the original reply still reaches the caller.
Multi-turn conversations
Many integrations send more than one message in a session. A chat widget, for example, keeps the session open across turns. In that case the end call does not belong in the function that sends a single message. It belongs where the conversation's lifetime is managed.
Typical triggers for ending a session:
- The user clicks a close or "end chat" control.
- The user's own browser session or login expires on your side.
- Your backend finishes a task, such as a batch job that asked the agent one question per record.
- Your application shuts down and still holds open sessions.
Keep a record of open session IDs in your application, such as an in-memory map keyed by your user or conversation ID. On shutdown, loop over the map and end each one. Remember that each session was created under a token, so make sure you have a valid token at shutdown time.
The session lifecycle at a glance
The diagram shows the states a session passes through and which calls move it between them.
An explicit delete and a timeout both reach the ended state. The difference is that the delete is immediate and carries your end reason, while the timeout happens later and leaves no reason from your side.
Edge cases
Ending a session that has already ended
If the session has timed out, or was already deleted, a second delete call will probably fail with a client error such as a not-found response. Treat this as harmless. The goal, a closed session, is already met. The logging approach above handles this: it records a warning and continues.
Sending a message after the session ends
Once a session is ended, you cannot send further messages to it. A message request against an ended session returns an error. If your application needs to continue the conversation, create a new session. The new session starts with no memory of the old one, so pass any context the agent needs again, using variables or the first message.
Ending during a streamed reply
If you use the streaming endpoint, wait until the stream finishes before you end the session. Ending the session while the stream is still open can cut off the reply. In a streaming client, put the delete call after you have consumed the stream to its end, or in the cleanup path if the stream fails.
Parallel sessions
Each session has its own ID and is ended independently. Ending one session has no effect on others, even if they share the same token or the same agent. When you run many conversations in parallel, track each ID separately and make sure each one has its own cleanup path.
Token expiry between create and end
Tokens are short-lived. A conversation that runs for a long time may outlast the token it began with. Before the delete call, check that the token is still valid, or be ready to request a new one and retry once. A new token works for the same session, since the session is identified by its ID and your access, not by the token that created it.
Quick checks for a clean shutdown
Use this list to review your integration:
- Every code path that creates a session has a matching end call.
- The end call runs in a
finallyblock, or in an equivalent cleanup handler. - The end call sets a timeout and sends
x-session-end-reason. - Failure to end a session is logged and does not mask the real result.
- Open session IDs are tracked so a shutdown can close them.
Exercises
Exercise
Why should the try block in the example start after the session is created, and the delete call sit in finally?
Show answer
The finally block needs a valid session_id. If creation fails, no session exists, so there is nothing to delete and session_id would be undefined. Starting the try after creation avoids that. Placing the delete in finally makes it run whether the message call succeeds or raises an error.
Exercise
A delete call fails with a network error inside the finally block, and your caller receives an exception instead of the agent's reply. What change fixes this, and why?
Show answer
Wrap the delete call in its own try/except for requests.RequestException and log the error instead of raising it. An exception raised in finally replaces the original result, so a failed cleanup would hide a successful reply. Cleanup should not change the outcome of the conversation.
Exercise
Your service sends five messages in one session. Where should the end call go, and name two events that should trigger it.
Show answer
It belongs in the code that manages the conversation's lifetime, not in the function that sends one message. Triggers include the user closing the chat, the user's login expiring on your side, the task finishing, or the application shutting down.