Context Management
Context allows you to provide additional information about the user or session to personalize agent responses.
Sending Context
import { AiAgent, createContextMessage } from "@egain/ai-agent-sdk";
const agent = new AiAgent({
id: "agent-id",
endpoint: "https://your-endpoint.com",
auth: { type: "pre-auth", accessToken: "your-access-token" }
});
await agent.initialize();
await agent.connect();
// Send context information
await agent.send(createContextMessage({
context: {
userId: "user-123",
accountType: "premium",
language: "en",
timezone: "America/New_York",
previousInteractions: 15
}
}));Automatic Caching
Context messages are automatically cached by the SDK. You can also pass context at initialize() so it is stored before connect and used to auto-select portal/profile when the portal pipeline runs (see Portal initialization).
For profile selection, egain_personalization_profile_id in that context takes priority over the server’s last-used profile when both match rows in the fetched list (v0.2.1+). After a mid-session switch via updateUserProfile(), keep context in sync (or rely on the SDK’s stored context) so session recovery resolves the same profile.
await agent.initialize({
context: {
egain_portal_id: { value: "123", type: "string", notInLLM: true },
egain_personalization_profile_id: { value: "456", type: "string", notInLLM: true },
},
});Context messages sent over the WebSocket are also cached:
// Send context - automatically cached
await agent.send(createContextMessage({
context: { userId: "user-123" }
}));
// Context persists across page refreshes (session storage by default)Session creation (POST context)
When the SDK fetches a new session id (connect(), restartConnection() without sessionId, etc.), it calls POST .../session with stored context when available. If the platform gateway does not support POST, the SDK falls back to GET.
After portal selection, the SDK also injects egain_portal_id into that session body from the last selected portal (merged with any stored portal attribute metadata).
setContext() merge and delta send
setContext() merges into the cached context. With sendImmediately: true, only keys whose values changed since the last stored context are sent over the WebSocket:
await agent.setContext({ userId: "user-123", plan: "premium" });
await agent.setContext({ plan: "enterprise" }, { sendImmediately: true });
// Sends only { plan: "enterprise" }Restarting connections
// New session from API — context is included in the POST body
await agent.restartConnection();
// Caller-provided session — legacy WebSocket context restore after connect
await agent.restartConnection({ sessionId: "existing-session-id" });Retrieving Context
// Get stored context
const context = agent.getContext();
console.log(context);
// { userId: "user-123", accountType: "premium", ... }Removing Context
// Remove context (e.g., on user logout)
agent.removeContext();Context Best Practices
1. Send Context Early
await agent.initialize();
await agent.connect();
// Send context before any user messages
await agent.send(createContextMessage({
context: {
userId: currentUser.id,
name: currentUser.name
}
}));
// Now start the conversation
await agent.send("Hello!");2. Include Relevant Information
const context = {
// User identification
userId: user.id,
accountId: user.accountId,
// Preferences
language: user.preferredLanguage,
timezone: user.timezone,
// Account details
accountType: user.subscription,
memberSince: user.createdAt,
// Session info
currentPage: window.location.pathname,
referrer: document.referrer,
// Support context
openTickets: user.ticketCount,
lastInteraction: user.lastSupportDate
};
await agent.send(createContextMessage({ context }));3. Update Context When Needed
// Initial context
await agent.send(createContextMessage({
context: { page: "home" }
}));
// User navigates
function onPageChange(newPage) {
agent.send(createContextMessage({
context: { page: newPage }
}));
}Cache Configuration
Context caching uses the same configuration as the agent:
const agent = new AiAgent({
// ...
cache: {
enabled: true,
storageType: "session", // "local", "session", "memory"
ttl: 300000 // 5 minutes
}
});| Storage Type | Persistence | Use Case |
|---|---|---|
session | Tab lifetime | Most apps (default) |
local | Browser lifetime | Persistent sessions |
memory | Page lifetime | Sensitive data |
Custom Cache Adapter
const customAdapter: CacheAdapter = {
get: (key) => myStore.get(key),
set: (key, entry) => myStore.set(key, entry),
delete: (key) => myStore.delete(key),
clear: (prefix) => myStore.clear(prefix),
keys: (prefix) => myStore.keys(prefix)
};
const agent = new AiAgent({
// ...
cache: {
enabled: true,
adapter: customAdapter
}
});