Sub topic 7
Creating a session
A session is the conversation container that every later call refers to. In this chapter you will build the HTTP request that creates one, learn what each field in the body does, and read the response. Sending messages and ending the session are covered in later chapters.
This chapter assumes you can already:
- Request an access token from your My Domain with the client credentials flow.
- Find your agent's ID and confirm the agent is active.
- Read short Python and JSON examples.
What a session is
The Agent API is stateless on the HTTP level, so the server needs a way to tie your calls together. The session does this. When you create one, Salesforce starts a conversation with the agent and returns a sessionId. You send that ID in the path of every later message and in the final delete call. The agent keeps the conversation history, its topic selection, and any variables on the server side, and it associates them with the ID.
Three consequences follow:
- Each session is one conversation. If you want a fresh conversation with no memory of the last one, create a new session.
- Your client does not need to resend the history. It only needs to remember the
sessionIdand the next sequence number. - Sessions use server resources and expire, so you should end them when you are done.
The request
You create a session with a POST to the agent's sessions collection:
POST https://api.salesforce.com/einstein/ai-agent/v1/agents/{agentId}/sessionsTwo details trip people up here:
- The host is
api.salesforce.com, not your My Domain. Your My Domain appears inside the request body instead. - The access token you got from your My Domain goes in the
Authorization: Bearerheader.
Body fields
| Field | Required | Purpose |
|---|---|---|
| `externalSessionKey` | Yes | A unique string you generate to identify this conversation on your side. A UUID works well. |
| `instanceConfig.endpoint` | Yes | Your org's My Domain URL, for example `https://mycompany.my.salesforce.com`. It tells the API which org hosts the agent. |
| `streamingCapabilities.chunkTypes` | Yes | The kinds of streamed chunks your client can handle. `["Text"]` is enough for a text client. |
| `bypassUser` | Depends on the auth flow | When `true`, the session runs as the run-as user of your External Client App instead of requiring a signed-in end user. |
| `variables` | No | Context variables to seed the conversation. A later chapter covers these. |
| `tz` | No | A time zone name such as `Europe/London`. Include it if the agent's answers depend on local time. |
externalSessionKey is yours to define. Pick a value you can find later in your own logs, such as a UUID that you also store next to your own ticket or chat record. Do not reuse a key across conversations.
Why `bypassUser` is true in this tutorial
With the client credentials flow, no human logs in. The token represents the External Client App, and the app acts as the run-as user you configured. Setting bypassUser to true tells the API to use that user for the session. If you leave it false in this setup, the request can fail because there is no end-user identity to attach. The consequence is that every record the agent reads or writes is governed by the run-as user's permissions. A broadly privileged run-as user gives the agent broad reach, which the security chapter returns to.
A working Python function
This function creates a session and returns both the ID and the agent's opening message. It reads its settings from environment variables, as the earlier chapters did.
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 create_session(token: str) -> tuple[str, str]:
"""Create an Agent API session. Returns (session_id, greeting_text)."""
response = requests.post(
f"{API_BASE}/agents/{AGENT_ID}/sessions",
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
json={
"externalSessionKey": str(uuid.uuid4()),
"instanceConfig": {"endpoint": MY_DOMAIN},
"streamingCapabilities": {"chunkTypes": ["Text"]},
"bypassUser": True,
},
timeout=30,
)
response.raise_for_status()
body = response.json()
session_id = body["sessionId"]
messages = body.get("messages", [])
greeting = messages[0].get("message", "") if messages else ""
return session_id, greeting
if __name__ == "__main__":
from get_token import get_access_token # your function from the token chapter
sid, hello = create_session(get_access_token())
print("Session:", sid)
print("Agent says:", hello)The last block imports get_access_token from a module named get_token. Save the token function from the previous chapter in a file of that name, or paste the function into the same file.
The response
A successful call returns HTTP 200 with a JSON body. The parts you will use are:
sessionId: the ID to put in later URLs.messages: a list that normally holds one entry, the agent's opening message. This is the greeting you configured for the agent. Show it to your user, or ignore it if your system does not display greetings._links: URLs for related operations, such as sending messages and ending the session. You can build these paths yourself, as this tutorial does, but the links are useful when you want to confirm what the API expects.
An abbreviated response looks like this:
{
"sessionId": "a1b2c3d4-0000-4000-8000-1234567890ab",
"_links": {
"self": { "href": "https://api.salesforce.com/einstein/ai-agent/v1/sessions/a1b2c3d4-0000-4000-8000-1234567890ab" },
"messages": { "href": "https://api.salesforce.com/einstein/ai-agent/v1/sessions/a1b2c3d4-0000-4000-8000-1234567890ab/messages" },
"end": { "href": "https://api.salesforce.com/einstein/ai-agent/v1/sessions/a1b2c3d4-0000-4000-8000-1234567890ab" }
},
"messages": [
{ "type": "Inform", "id": "0f0e0d0c", "message": "Hi, I'm your assistant. How can I help?" }
]
}The exact link names and message fields can vary by API version, so read the fields you need defensively. For example, use .get() for optional keys, as the function above does.
What to store after creation
Keep these values for the rest of the conversation:
sessionId, used in every message URL and in the delete call.- Your
externalSessionKey, so you can match the session to your own records. - A counter for
sequenceId. The first message you send uses1, and each later message uses the next number. The greeting does not use up a number from your side. - The time of the last activity, so you can decide when a session is idle and should be ended.
If your client is a web service handling many users, keep these in a per-conversation record such as a cache or database row, not in a global variable. Mixing up session IDs between users would send one person's messages into another person's conversation.
Common errors
| Status | Typical cause | What to check |
|---|---|---|
| 400 | Malformed body or a missing required field | Confirm `externalSessionKey`, `instanceConfig.endpoint`, and `streamingCapabilities` are all present, and that the JSON is valid. |
| 401 | Expired or invalid token | Request a new token and retry once. |
| 403 | The app or run-as user lacks access | Check the External Client App's scopes and the run-as user's permissions on the agent. |
| 404 | Wrong agent ID | Confirm the ID belongs to this org and the agent is active. |
| 5xx | Temporary server problem | Retry with a short delay, as covered in the error handling chapter. |
Two causes of failure are easy to miss. First, an agent that was deactivated or has not been activated yet will not accept sessions, so activate the current version and use the ID of that agent. Second, the endpoint value must match the org that issued the token. A sandbox token with a production My Domain in the body is a frequent mistake when you move code between environments.
Idempotence and retries
Creating a session is not safe to retry blindly. If a request times out, you cannot tell whether Salesforce created the session before the connection dropped. A new attempt with a new externalSessionKey might leave an orphaned session behind. Two sensible approaches are:
- Retry only on clear failures, such as a 401 followed by a token refresh, or a 5xx response, and log the key used for each attempt.
- If a timeout occurs, treat it as a failure, create a fresh session with a new key, and let the orphaned one expire.
Checking your work from the command line
You can test creation without writing Python. With a token in ACCESS_TOKEN, your agent ID in AGENT_ID, and your My Domain in MY_DOMAIN, run:
curl -s -X POST "https://api.salesforce.com/einstein/ai-agent/v1/agents/$AGENT_ID/sessions" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"externalSessionKey\": \"$(uuidgen)\",
\"instanceConfig\": {\"endpoint\": \"$MY_DOMAIN\"},
\"streamingCapabilities\": {\"chunkTypes\": [\"Text\"]},
\"bypassUser\": true
}"A JSON body containing sessionId confirms that your token, scopes, run-as user, and agent are all set up correctly. If this call works but your code fails, compare the body field by field.
Exercise
Your service gets a 200 response from the create-session call. List the values you should store before moving on, and explain why you should not create a new session for each user message.
Show answer
Store the sessionId (needed in every later URL and in the delete call), the externalSessionKey (to match the session to your own records and logs), a sequenceId counter starting at 1 for the first message you send, and the last-activity time (to detect idle sessions to end). A new session is a new conversation with no memory of earlier turns, so creating one per message would lose the context the agent depends on and would add extra sessions that use resources and count against usage.
Exercise
A create-session request returns 401 in the middle of the day, although it worked this morning. What is the most likely cause, and what is the safe response in code?
Show answer
The access token has most likely expired. The safe response is to request a new token with the client credentials flow and retry the create-session call once. A 401 means no session was created, so the retry cannot leave an orphaned session. If the retry also fails, stop and report the error instead of looping.