Sub topic 3
Ending an Agentforce Agent Session
Assume you know REST, JSON, HTTP methods, and OAuth 2.0 access tokens. The session lifecycle is: create a session, send one or more messages, then end the session.
End the session cleanly
After the final reply, send DELETE to the session endpoint. Include the bearer token and an end reason.
import requests
def end_session(api_base: str, session_id: str, token: str) -> None:
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()Use a finally block so the session closes when sending a message raises an exception. Ending sessions reduces abandoned conversations and makes failures easier to diagnose.
Stream replies
For a long response, use the streaming endpoint. It returns server-sent events, which let the client display text as it arrives.
curl -N -X POST "https://api.salesforce.com/einstein/ai-agent/v1/sessions/$SESSION_ID/messages/stream" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{"message":{"sequenceId":2,"type":"Text","text":"What is the status of my order?"}}'The client must read events until the server indicates that the response is complete. Always end the session after the stream finishes or fails.
Pass context and handle failures
Pass context variables through the session or message fields supported by your agent and API version. Keep machine-readable values separate from the user's text. For example, an order identifier should be a context value, not an instruction embedded in a sentence.
Handle failures by checking HTTP status codes:
401or403: refresh the access token or check scopes and the run-as user.429: apply bounded exponential backoff.5xxor network timeout: retry idempotent operations carefully.- Message failures: preserve the session ID and sequence ID for diagnosis.
Protect and test the integration
Store the client ID and secret in environment variables or a secret manager. Do not commit them or log access tokens. Grant the External Client App only the scopes it needs, and use a dedicated run-as user with limited permissions.
Test successful sessions, expired tokens, rejected scopes, malformed responses, timeouts, streaming disconnects, and cleanup after exceptions. Log status codes and correlation data, but redact secrets and message content when it may contain sensitive information.
Exercise
When should the client end a session?
Show answer
After the final response, and also from cleanup code when a message or stream fails.