Context
Learn how to pass application context to make AI responses more relevant and personalized.
What is Context?
InAppAI provides two forms of context to the AI:
- Application context (the
contextprop) — A snapshot of your app’s current state, sent with every message. This is what this page covers. - Conversation history (the
messagesarray) — The full conversation including previous messages and tool action records. This is sent automatically — see Architecture: Conversation Memory for details.
Application context is information about your application’s current state that you pass to the AI. This allows the AI to:
- Answer questions about the current page or user
- Provide personalized recommendations
- Understand user intent better
- Reference specific data from your application
The context Prop
The context prop lets you pass real-time application state to the AI agent. Context is sent with every message, giving the AI immediate access to relevant information.
Static Context
When context doesn’t change frequently, pass a plain object:
import { useState } from 'react';
import { InAppAI, Message } from '@inappai/react';
function App() {
const [messages, setMessages] = useState<Message[]>([]);
const user = { name: 'Alice', role: 'admin', plan: 'professional' };
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
context={{
page: 'dashboard',
userName: user.name,
userRole: user.role,
plan: user.plan,
}}
/>
);
}
Now when the user asks “What plan am I on?”, the AI can respond: “You’re on the Professional plan.”
Dynamic Context
When context changes frequently, use a function to capture fresh state on each message:
function App() {
const [messages, setMessages] = useState<Message[]>([]);
const [selectedItems, setSelectedItems] = useState<string[]>([]);
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
context={() => ({
page: window.location.pathname,
selectedItems: selectedItems,
scrollPosition: window.scrollY,
timestamp: new Date().toISOString(),
})}
/>
);
}
The function is called every time the user sends a message, ensuring the AI gets current information.
Real-World Examples
E-commerce Product Page
function ProductPage() {
const [messages, setMessages] = useState<Message[]>([]);
const product = {
id: 'shirt-001',
name: 'Blue T-Shirt',
price: 29.99,
inStock: true,
sizes: ['S', 'M', 'L', 'XL'],
};
const cart = [
{ name: 'Jeans', quantity: 1, price: 59.99 },
];
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
context={{
currentProduct: product,
cartItemCount: cart.length,
cartTotal: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
}}
/>
);
}
User: “Is this shirt available in large?” AI: “Yes! The Blue T-Shirt is available in Large. Would you like me to add it to your cart?”
SaaS Dashboard
function Dashboard() {
const [messages, setMessages] = useState<Message[]>([]);
const user = {
name: 'Alice Chen',
email: 'alice@company.com',
role: 'admin',
};
const stats = {
projects: 12,
activeUsers: 45,
storageUsed: '34.2 GB',
storageLimit: '100 GB',
};
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
context={{
userName: user.name,
userRole: user.role,
...stats,
}}
/>
);
}
User: “How much storage do I have left?” AI: “You’ve used 34.2 GB of your 100 GB storage limit, so you have about 65.8 GB remaining.”
Documentation Site
function DocsPage() {
const [messages, setMessages] = useState<Message[]>([]);
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
displayMode="sidebar-right"
context={() => ({
section: 'getting-started',
pageTitle: document.title,
url: window.location.pathname,
selectedText: window.getSelection()?.toString() || '',
})}
/>
);
}
User: “Can you explain this?” (with text selected) AI: sees selectedText in context “That code snippet creates a new React component…”
Context vs Tools
Understanding the distinction is important:
| Feature | Context | Tools |
|---|---|---|
| Purpose | Provide read-only state snapshot | Execute actions and modify state |
| Passed via | context prop | tools prop |
| When sent | With every message automatically | Only when AI decides to call them |
| AI capability | Can read and reference data | Can call functions to take actions |
Use context when: You want the AI to always have access to current state (user info, page data, settings)
Use tools when: You want the AI to take actions (create, update, delete) or fetch data on-demand
Combining Context and Tools
For the best experience, use both together:
function TodoApp() {
const [messages, setMessages] = useState<Message[]>([]);
const [todos, setTodos] = useState([
{ id: 1, text: 'Buy groceries', completed: false },
{ id: 2, text: 'Finish report', completed: true },
]);
return (
<InAppAI
agentId="your-agent-id"
messages={messages}
onMessagesChange={setMessages}
// Context: AI always knows current state
context={{
todoCount: todos.length,
completedCount: todos.filter(t => t.completed).length,
pendingCount: todos.filter(t => !t.completed).length,
}}
// Tools: AI can take actions
tools={[
{
name: 'addTodo',
description: 'Add a new todo item',
parameters: {
type: 'object',
properties: {
text: { type: 'string', description: 'The todo text' },
},
required: ['text'],
},
handler: async ({ text }) => {
const newTodo = { id: Date.now(), text, completed: false };
setTodos([...todos, newTodo]);
return { success: true, todo: newTodo };
},
},
]}
/>
);
}
User: “How many tasks do I have left?” AI: reads from context “You have 1 pending task out of 2 total.”
User: “Add a task to call mom” AI: calls addTodo tool “Done! I’ve added ‘call mom’ to your list.”
Best Practices
1. Include Only Relevant Data
// ❌ Too much data
context={{
entireUserObject: user,
allProducts: products,
fullHistory: history,
}}
// ✅ Just what's needed
context={{
userName: user.name,
userPlan: user.plan,
currentProductId: product.id,
}}
2. Never Include Sensitive Data
// ❌ NEVER include sensitive data
context={{
password: user.password,
apiKey: process.env.SECRET_KEY,
creditCard: user.creditCard,
}}
// ✅ Safe, public information only
context={{
userName: user.name,
userRole: user.role,
}}
3. Keep Context Lightweight
Context is sent with every message. Keep it under 2-3KB:
// ❌ Heavy context
context={{
allOrders: orders, // Could be huge
fullProductCatalog: products,
}}
// ✅ Lightweight summary
context={{
recentOrderCount: orders.slice(-5).length,
cartTotal: calculateTotal(cart),
}}
4. Memoize for Performance
import { useMemo } from 'react';
function App() {
const context = useMemo(() => ({
userId: user.id,
userName: user.name,
}), [user.id, user.name]);
return (
<InAppAI
context={context}
// ...
/>
);
}
5. Structure Your Data
context={{
user: {
name: user.name,
role: user.role,
},
page: {
type: 'product',
id: product.id,
},
app: {
version: '2.1.0',
},
}}
Next Steps
- Tools - Enable the AI to execute actions
- Persistence - Save and restore conversations
- API Reference - Complete props documentation