Sub topic 2
Understanding the Agent API Session Lifecycle
Assume you know basic REST, JSON, HTTP methods, and OAuth 2.0 access tokens. A session is a temporary conversation between your application and an Agentforce agent. Your application creates the session, sends one or more messages, reads replies, and later ends the session.
Creating a session
Send an authenticated POST request to the agent's sessions endpoint. Include the agent ID and an instance configuration containing your Salesforce My Domain. The response contains a sessionId. Keep that identifier for later requests.
import os
import uuid
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
TOKEN = os.environ["SF_ACCESS_TOKEN"]
AGENT_ID = os.environ["SF_AGENT_ID"]
MY_DOMAIN = os.environ["SF_MY_DOMAIN"]
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
}
response = 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,
)
response.raise_for_status()
session_id = response.json()["sessionId"]
print(session_id)Sending a message and getting a reply
Use the session ID in the message URL. Each message has a sequenceId, which identifies its order within the session. A synchronous request waits for the complete response.
Reading the response and message types
The response contains a messages collection. A text reply commonly has type set to Text, with the generated content in its message field. Other message types can represent structured events, such as actions or errors. Inspect the type before assuming the payload is plain text.
A production client should check for an empty collection and preserve the complete response for troubleshooting. It should also end the session when the conversation is finished, including after failures.
Exercise
Why should a client inspect a response message's type before reading its text?
Show answer
Because the response may contain an action, event, or error rather than a plain text message, and each type can have a different payload.