Sub topic 15
Testing and troubleshooting the integration
This chapter assumes you have built the full flow from the earlier chapters: an External Client App, a token request, a session, a message, and session end. It shows how to test each stage separately and how to read the failures you are most likely to see.
Test one stage at a time
Most failures come from one stage, and later stages only repeat the error. Check the stages in order:
- Token: does the My Domain token endpoint return an
access_token? - Session: does creating a session return a
sessionId? - Message: does a message return a reply?
- End: does the delete call succeed?
The script below runs these four stages and stops at the first failure. It prints the HTTP status and the start of the response body, which usually names the cause.
import os
import sys
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 check(step: str, response: requests.Response) -> dict:
if not response.ok:
print(f"FAIL {step}: HTTP {response.status_code}")
print(response.text[:500])
sys.exit(1)
print(f"OK {step}: HTTP {response.status_code}")
return response.json() if response.text else {}
token = check("token", requests.post(
f"{MY_DOMAIN}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
))["access_token"]
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
session_id = check("create session", 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,
))["sessionId"]
try:
body = check("send message", requests.post(
f"{API_BASE}/sessions/{session_id}/messages",
headers=headers,
json={"message": {"sequenceId": 1, "type": "Text", "text": "Hello"}},
timeout=60,
))
print("Reply:", body["messages"][0]["message"])
finally:
check("end session", requests.delete(
f"{API_BASE}/sessions/{session_id}",
headers={**headers, "x-session-end-reason": "UserRequest"},
timeout=30,
))Run it after every change to the agent, the External Client App, or your credentials.
Common symptoms and causes
| Symptom | Likely cause | What to check |
|---|---|---|
| Token request returns 400 | Wrong grant type, client ID, or secret, or the flow is not enabled | Re-copy the credentials and confirm client credentials is enabled on the app |
| Token request fails against `login.salesforce.com` | Wrong host | Use your My Domain URL, as in the earlier chapter |
| 401 on session or message calls | Expired or missing token | Request a new token and retry once |
| 403 on session creation | Missing scope or a run-as user without access | Review the app's OAuth scopes and the run-as user |
| 404 on session creation | Wrong agent ID or inactive agent | Re-copy the ID and confirm the agent is activated |
| 404 on a message | Session ended or expired | Create a new session |
| Reply is empty or unhelpful | Agent configuration, not the API | Test the same prompt in the agent builder |
Practical habits
- Log the HTTP status and response body on every failure, but never log the token or the client secret.
- Reuse one
sequenceIdcounter per session and increase it with each message. - Reproduce a failing call with curl before changing code. If curl fails the same way, the problem is in the org configuration, not your client.
- Test the agent's behavior in the agent builder first. If a prompt gives a poor answer there, it will give the same answer through the API.
Exercise
Your smoke test prints "OK token" and then "FAIL create session: HTTP 404". Which two causes do you check first, and why do you not need to look at your token request?
Show answer
Check that the agent ID is correct and that the agent is activated. The token stage already succeeded, so the credentials, My Domain URL, and grant type are working. A 404 at session creation points to the agent being addressed, not to authentication.