Page Context Injection
Inject page context (such as product IDs, ticket numbers, or user identifiers) into the AI assistant's LLM System Prompt via the embed SDK's auth.contextData
When Web Chat is embedded in your website, the AI assistant by default has no idea "which page the user is on or what they are looking at." contextData lets the embedding site pass arbitrary key-value data in the embed configuration. This data is automatically sent with every message and injected into the LLM System Prompt, so the AI assistant can use it directly in conversations and tool calls (Tool / Function Calling).
Common use cases:
E-commerce product pages: Inject
productIdso the assistant doesn't have to ask "Which product are you asking about?" and can directly call the "product lookup" API tool with that product IDCustomer support systems: Inject
ticketIdandcustomerIdso the assistant can reference the ticket context directly when handling support workflowsHealthcare / form services: Inject an identifier read from a QR code (such as an issuance serial number) so the assistant automatically includes it when calling the submission API
Membership / financial services: Inject attributes such as membership tier so the assistant provides personalized responses based on identity
1. Quick Start
Add auth.contextData to maiagentChatbotConfig before the embed script:
<script>
window.maiagentChatbotConfig = {
webChatId: 'your-web-chat-id',
baseUrl: 'https://yourdomain.com/web-chats',
auth: {
sourceId: 'user-12345', // Required: unique user identifier
name: 'John Wang', // Optional: display name
contextData: { // Arbitrary key-value pairs, injected into the LLM system prompt
productId: '3021',
productName: 'Wireless Noise-Canceling Headphones',
},
},
}
</script>
<script src="https://yourdomain.com/js/embed.min.js"></script>After the SDK finishes loading, it automatically runs auth.setup(). From then on, every message the user sends carries these key-value pairs in its metadata, and the backend appends them to the System Prompt in the following format:
The AI assistant can then reference these values directly in responses and tool calls.
2. How It Works
Key characteristics:
Sent with each message, not persisted to the database:
contextDataexists only in frontend memory and is sent with each message's payload. After the user refreshes the page, the embedding page must re-inject it (well suited for short-lived data such as QR codes or sessions)Effective on every conversation turn: Because it is sent with every message, the AI has continuous access to the latest context throughout the conversation
No extra API calls: It reuses the existing message channel, adding no performance overhead
Difference from queryMetadata
The two serve completely different purposes—do not mix them up:
auth.contextData
queryMetadata
Purpose
Tell the AI about page context (goes into the System Prompt)
Control knowledge base retrieval scope (RAG permission filtering)
Visible to the LLM
✅ Appears in the System Prompt
❌ Not in the prompt, not passed to tools
Suitable for
Product IDs, ticket numbers, user identifiers
Knowledge management permissions, document access scope
If you want the AI to "know" a value (for example, to fill it into an API tool parameter), use contextData; if you want to restrict "which knowledge documents the AI can retrieve," use Knowledge Management Permissions (Query Metadata).
3. Data Rules and Limits
The SDK sanitizes the contextData you pass in, according to the following rules:
Value types
string is supported; number / boolean are automatically converted to strings; other types (object, array, null, etc.) cause the key to be dropped
Maximum number of keys
Up to 50 key-value pairs; anything beyond that is dropped
Reserved keys
Keys that conflict with existing system metadata are dropped (see the list below)
Empty object {}
After sanitization it is empty, treated as not provided; metadata contains no custom keys
Sanitization behavior
Silent—no errors are raised, and message sending is not blocked
Reserved key list (dropped if passed in, to avoid overwriting system fields):
contact_name, timezone, latitude, longitude, accuracy, locale, language, working_directory
Security is the embedding site's responsibility: contextData is injected by the embedding page, and MaiAgent does not verify its origin with signatures or encryption. Do not inject confidential data that end users should not learn (values go into the LLM prompt and the AI may repeat them in responses). If the data is personally identifiable (such as a national ID number), the embedding site must ensure the source is trustworthy (for example, a signed QR code / session) and comply with personal data protection regulations.
4. Updating and Clearing
The lifecycle of contextData follows auth.setup():
Update: Calling
MaiAgent.auth.setup()again fully overwrites the currentcontextData(it does not merge)Clear: Calling
auth.setup()withoutcontextDataclears previously injected values;MaiAgent.auth.signOut()also clears it, preventing carryover across identities
5. Examples
1. E-commerce product page: AI answers based on the current product
Scenario: The AI assistant is configured with a "product lookup" API tool (queries product details by product ID). Web Chat is embedded on the product detail page. When the user asks "Is this right for me?", the assistant should answer about the current product directly instead of asking back.
When the user asks "How long does the battery last on this one?", the System Prompt already contains productId: 3021, so the AI directly calls the "product lookup" tool with id=3021 to fetch the product details and answer—no need to ask "Which product are you asking about?".
2. Customer support system: bring in ticket context
When the user opens the conversation, the AI already knows the ticket number and the customer's plan tier, so it can handle the ticket's follow-up workflow directly without the customer repeating the details.
3. Identifier injection: QR code / URL parameters
Scenario: The service page is opened via a QR code or a parameterized link, and the AI needs to automatically include the identifier when calling the submission API.
After the AI guides the user through the flow, it automatically fills formId and userRef into the request body when calling the submission tool (such as SubmitAnswers).
6. Verification and Troubleshooting
How do I confirm contextData is taking effect?
Open the Network tab in the browser developer tools and watch the WebSocket messages: the
metadatain the outgoing message payload should contain the keys you injectedAsk the AI assistant directly: "Do you know what my productId is?"—if injection succeeded, the AI can answer directly
In the admin console's conversation monitoring, inspect the actual prompt used for that message; it should contain the
Contact custom attributessection
Common issues
contextData has no effect at all
Confirm that auth.sourceId is provided (required; without it, auth.setup() does not run)
Some keys are missing
Check whether they use reserved keys, whether the value is an unsupported type (object / array), or whether the 50-pair limit was exceeded
Context disappears after refresh
Expected behavior: it is not persisted to the database, so the page must re-inject it on each load
The AI does not use the context in tool calls
Add explicit guidance in the system prompt (see the hint in Example 1 above)
Last updated
Was this helpful?
