Smart AI Context
Make AI aware of your application state
Smart AI Context
Give the AI awareness of your application state so it can provide relevant, contextual responses.
Overview
Without context, AI doesn't know what's happening in your app:
User: "Is this in stock?"
AI: "I don't know what product you're referring to."With context:
useAIContext({
key: 'current-product',
data: { name: 'Wireless Headphones', stock: 42, price: 79.99 },
});User: "Is this in stock?"
AI: "Yes! The Wireless Headphones are in stock with 42 units available at $79.99."useAIContext
Register a single context:
import { useAIContext } from '@yourgpt/copilot-sdk-react';
function ProductPage({ product }) {
useAIContext({
key: 'current-product',
data: {
id: product.id,
name: product.name,
price: product.price,
description: product.description,
inStock: product.inventory > 0,
category: product.category,
},
description: 'The product the user is currently viewing',
});
return <ProductView product={product} />;
}Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Unique identifier for this context |
data | any | Yes | The data to expose to AI |
description | string | No | Helps AI understand when to use this context |
parentId | string | No | For hierarchical contexts |
Returns
Returns a context ID string that can be used as parentId for nested contexts.
useAIContexts
Register multiple contexts at once:
import { useAIContexts } from '@yourgpt/copilot-sdk-react';
function AppContext() {
useAIContexts([
{
key: 'user',
data: {
name: user.name,
email: user.email,
plan: user.subscription,
role: user.role,
},
description: 'Current logged-in user information',
},
{
key: 'cart',
data: {
items: cart.items,
total: cart.total,
itemCount: cart.items.length,
},
description: 'Shopping cart contents',
},
{
key: 'page',
data: {
route: router.pathname,
params: router.query,
},
description: 'Current page location',
},
]);
return null;
}Hierarchical Contexts
Create parent-child relationships for complex data:
function TeamDashboard({ team }) {
// Parent context
const teamContextId = useAIContext({
key: 'team',
data: {
name: team.name,
memberCount: team.members.length,
},
description: 'The team being viewed',
});
return (
<div>
<h1>{team.name}</h1>
{team.members.map(member => (
<MemberCard
key={member.id}
member={member}
parentId={teamContextId}
/>
))}
</div>
);
}
function MemberCard({ member, parentId }) {
// Child context - linked to team
useAIContext({
key: `member-${member.id}`,
data: {
name: member.name,
role: member.role,
tasks: member.tasks,
},
description: `Team member: ${member.name}`,
parentId, // Links to team context
});
return <div>{member.name}</div>;
}Hierarchical contexts help AI understand relationships. When user asks about "John's tasks", AI knows John is part of the team context.
Dynamic Context Updates
Context updates automatically when data changes:
function LiveDashboard() {
const [metrics, setMetrics] = useState(null);
useEffect(() => {
const interval = setInterval(async () => {
const data = await fetchMetrics();
setMetrics(data);
}, 5000);
return () => clearInterval(interval);
}, []);
// Context auto-updates when metrics change
useAIContext({
key: 'live-metrics',
data: metrics,
description: 'Real-time dashboard metrics (updates every 5s)',
});
return <MetricsDisplay data={metrics} />;
}Context Cleanup
Contexts are automatically removed when components unmount:
function ConditionalContext({ showDetails }) {
// This context only exists when showDetails is true
if (showDetails) {
return <DetailedContext />;
}
return null;
}
function DetailedContext() {
useAIContext({
key: 'details',
data: { /* ... */ },
});
// Context removed when this component unmounts
return <Details />;
}What to Include in Context
Good Context Data
// User state
{
name: 'John',
plan: 'pro',
permissions: ['read', 'write'],
}
// Current view
{
page: 'checkout',
step: 2,
items: cart.items,
}
// Form state
{
formType: 'contact',
fields: Object.keys(formData),
hasErrors: errors.length > 0,
}Avoid Including
// Too much data (token waste)
{
allProducts: products, // Could be thousands
fullUserHistory: history, // Unnecessary detail
}
// Sensitive data
{
password: user.password, // Never!
creditCard: payment.card, // Never!
apiKeys: config.keys, // Never!
}
// Irrelevant data
{
buildHash: process.env.BUILD_ID, // AI doesn't need this
internalIds: uuids, // No user value
}Never include sensitive data in AI context. The context is sent to the LLM provider.
Best Practices
1. Keep Context Focused
// ✅ Good - relevant, scoped data
useAIContext({
key: 'order-details',
data: {
orderId: order.id,
status: order.status,
items: order.items.map(i => ({ name: i.name, qty: i.qty })),
total: order.total,
},
});
// ❌ Bad - too much unnecessary detail
useAIContext({
key: 'order',
data: order, // Full order object with internal fields
});2. Use Descriptive Keys
// ✅ Good
useAIContext({ key: 'current-product', data });
useAIContext({ key: 'user-preferences', data });
useAIContext({ key: 'checkout-cart', data });
// ❌ Bad
useAIContext({ key: 'data1', data });
useAIContext({ key: 'ctx', data });3. Add Helpful Descriptions
useAIContext({
key: 'filters',
data: { category: 'electronics', priceRange: [0, 500] },
description: 'Active product filters the user has applied',
});4. Structure for AI Understanding
// ✅ Good - clear structure
useAIContext({
key: 'selected-item',
data: {
name: 'Widget Pro',
canPurchase: true,
reasonIfNot: null,
},
});
// ❌ Bad - ambiguous
useAIContext({
key: 'item',
data: {
n: 'Widget Pro',
p: true,
},
});Full Example
function EcommercePage({ product, user, cart }) {
// Global contexts (in layout/provider)
useAIContexts([
{
key: 'user',
data: {
name: user.name,
memberSince: user.createdAt,
tier: user.loyaltyTier,
},
description: 'Logged-in user',
},
{
key: 'cart',
data: {
itemCount: cart.items.length,
subtotal: cart.subtotal,
hasDiscount: cart.discount > 0,
},
description: 'Shopping cart summary',
},
]);
// Page-specific context
useAIContext({
key: 'viewing-product',
data: {
name: product.name,
price: product.price,
rating: product.rating,
inStock: product.stock > 0,
stockLevel: product.stock > 10 ? 'high' : product.stock > 0 ? 'low' : 'none',
},
description: 'Product the user is currently viewing',
});
return <ProductPage product={product} />;
}Now AI can answer:
- "Is this in stock?" → Uses viewing-product context
- "What's in my cart?" → Uses cart context
- "Am I eligible for member discounts?" → Uses user context
Next Steps
- Custom Tools - Build tools that use context
- Agentic Loop - Multi-step AI reasoning