Sub topic 10
Ending the Session
This chapter assumes you can already get an access token, create a session, and send a message, as covered in the earlier chapters. It covers how to close a session and why you should always do so.
Why end a session
A session holds the conversation state on the Salesforce side. This includes the history of messages and any variables the agent has collected. Ending the session tells Salesforce that your client has finished. It releases the resources the session uses, and it gives the platform a clear end reason for its records.
If you skip this step, the session stays open until it times out. An abandoned session is not harmful on its own. In a busy integration, though, many abandoned sessions make usage harder to track and harder to debug.
The end-session request
Ending a session is a single DELETE request to the session URL. You send the same bearer token you used for the other calls. You also add an x-session-end-reason header. The value UserRequest means the end user or your application chose to finish.
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 request needs no body. After it succeeds, the session ID is no longer valid. Sending another message to it returns an error, so you must create a new session to continue talking to the agent.
Ending the session in code
The most common mistake is to end the session only on the success path. If the message call raises an exception, the DELETE never runs. Put the cleanup in a finally block so it runs either way.
The function from the earlier chapter already does this. Here is the pattern in isolation:
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
def end_session(token: str, session_id: str) -> None:
response = requests.delete(
f"{API_BASE}/sessions/{session_id}",
headers={
"Authorization": f"Bearer {token}",
"x-session-end-reason": "UserRequest",
},
timeout=30,
)
# A failed cleanup should not hide the original result,
# so report it instead of raising.
if not response.ok:
print(f"Could not end session {session_id}: {response.status_code}")Notice that this helper logs a failure and does not raise one. If the conversation succeeded and only the cleanup failed, your caller should still receive the reply. Raising from a finally block also replaces any exception already in flight, which hides the real cause.
The session lifecycle
Both final states are permanent. Neither can be reopened.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `401 Unauthorized` on `DELETE` | The access token expired during a long conversation | Request a new token, then retry the `DELETE` |
| `404 Not Found` | The session already ended or expired, or the ID is wrong | Treat as already closed, and check the ID if it is unexpected |
| Cleanup never runs | `DELETE` sits after the return statement or outside `finally` | Move it into `finally` |
| Reply lost after an error | The cleanup helper raised an exception | Log cleanup failures instead of raising them |
Exercise
Exercise
Your code sends a message, and the call fails with a timeout. The DELETE call comes right after the message call in the same try block, so it never runs. What change makes sure the session is still ended, and why should the cleanup helper avoid raising its own exception?
Show answer
Move the DELETE call into a finally block, which runs whether the message call succeeds or fails. The helper should log a failure and not raise, because an exception raised inside finally replaces the original exception and hides the real cause of the failure, and it can also discard a reply that was received successfully.