Sub topic 12
Passing variables and context to the agent
An agent often needs facts that the user never typed: the customer's account ID, the language of the app, or the page they are on. This chapter shows how to send those facts with the Agent API, and what to expect when you do.
This chapter assumes you can already get an access token, create a session, and send a message, as covered in earlier chapters. It also assumes you can edit the agent in Agentforce Builder.
Why variables exist
The text of a message is what the user says. Variables are structured values that travel alongside it. The agent can read them in its instructions and topics, and actions can use them as inputs.
Use variables when the value comes from your system and should not depend on the model reading it correctly from free text. An order ID passed as a variable is exact. An order ID the user types might contain a typo.
Variables are also useful for these cases:
- Identifying the end user or account, so the agent does not have to ask.
- Setting the language, so the reply matches the user's locale.
- Giving page or app context, such as which product screen the user is on.
- Passing flags your agent logic branches on, such as
isPremiumCustomer.
Two kinds of variables
The Agent API accepts two kinds of variables, and they behave differently.
| Kind | Example name | Defined where | Notes |
|---|---|---|---|
| Standard context variable | `$Context.EndUserLanguage` | Provided by the platform | Available without extra setup. |
| Custom variable | `$Context.accountId` or a name your agent defines | In the agent configuration | Must exist in the agent before you send it. |
Each variable in a request has three fields:
name: the variable name, which must match the agent's definition exactly.type: the data type, such asText,Boolean, orNumber.value: the value to set.
The exact set of supported types and standard names can change between releases. Check the Agent API reference for your org's release before relying on a type other than Text.
Where you can send them
You can send variables in two places.
- When you create the session. Use this for values that stay fixed for the whole conversation, such as the user's language or account.
- With a message. Use this for values that change during the conversation, such as the page the user is viewing now.
The session body is the same one you built earlier, with one extra field, variables.
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, variables: list[dict]) -> str:
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,
"variables": variables,
},
timeout=30,
)
response.raise_for_status()
return response.json()["sessionId"]
if __name__ == "__main__":
token = os.environ["SF_ACCESS_TOKEN"]
session_id = create_session(
token,
[
{"name": "$Context.EndUserLanguage", "type": "Text", "value": "en_US"},
],
)
print("Session started:", session_id)The access token comes from an environment variable here so the example runs on its own. In your integration, use the get_access_token function from the earlier chapter.
Sending variables with a message
A message request can carry its own variables list next to the message object. Here is a helper that sends one message and attaches variables.
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
def send_message(
token: str,
session_id: str,
sequence_id: int,
text: str,
variables: list[dict] | None = None,
) -> str:
body = {"message": {"sequenceId": sequence_id, "type": "Text", "text": text}}
if variables:
body["variables"] = variables
response = requests.post(
f"{API_BASE}/sessions/{session_id}/messages",
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
json=body,
timeout=60,
)
response.raise_for_status()
return response.json()["messages"][0]["message"]Call it with a custom variable like this:
reply = send_message(
token,
session_id,
sequence_id=1,
text="Where is my order?",
variables=[{"name": "$Context.currentOrderId", "type": "Text", "value": "801xx0000001AbC"}],
)
print(reply)The name $Context.currentOrderId is an example. Use the name your agent defines.
Defining a custom variable in the agent
The API does not create variables. The agent must define them first. In Agentforce Builder, add the variable to the agent and note its exact name and type. Then reference it where the agent should use it, for example in a topic's instructions or as the input to an action.
Treat the name as part of a contract between your code and the agent. If someone renames the variable in the builder, your API calls will stop having the intended effect. Keep the names in one constants module on your side, and document them next to the agent's configuration.
How the agent uses what you send
Sending a variable does not force the agent to use it. The agent uses a variable only if its instructions or actions refer to it. If a value seems ignored, the cause is usually on the agent side, not in the request.
A variable bound to an action input is the most dependable pattern. The action receives the exact value, and the model does not need to repeat it correctly. Variables mentioned only in prose instructions are weaker, because the model reads them like any other text.
Edge cases and common errors
- Wrong name. A variable whose name does not match any definition is typically ignored or rejected, depending on the release. Check the exact spelling, including the
$Context.prefix if the agent uses it. - Wrong type. Sending
"true"asTextwhen the agent expects aBooleancan cause a validation error or a silent mismatch. Match the type to the definition. - Sending too late. A value set at session start does not apply to a different session. Each new session needs its variables again.
- Overwriting. A variable sent with a later message may replace the earlier value for the rest of the conversation. If the agent branches on the value, send the new one only when it really changes.
- Missing optional values. Do not send empty strings for unknown values. Leave the variable out so the agent can ask the user.
- Sensitive data. Anything you send as a variable can be read by the agent and used in replies, and it may appear in logs and traces. Send identifiers, not secrets such as passwords or tokens.
A checklist for adding a variable
- Decide whether the value is fixed for the session or changes per message.
- Define the variable in the agent with a name and type.
- Reference it in an action input or in the agent's instructions.
- Send it in the
variableslist at the matching point. - Test with and without the variable and compare the replies.
Exercise
Your support app knows the customer's account ID and language when a chat opens, and knows the open product page, which changes as the user navigates. Which variables belong in the session request, which belong in message requests, and what must exist on the agent side before either works?
Show answer
Account ID and language are fixed for the conversation, so send them in the variables list of the create-session request. The product page changes, so send it in the variables list of each message where it changed. Before either works, the agent must define the custom variables (for example the account ID and the page) with matching names and types, and its instructions or actions must refer to them. Language can use the standard $Context.EndUserLanguage variable.
Exercise
You send a custom variable and the agent's replies do not change. Name two likely causes.
Show answer
The variable name or type does not match the agent's definition, or the agent's instructions and actions never refer to the variable, so it has no effect on the reply.