Context Management

Make AI aware of your application state and manage the context window

Give the AI awareness of your application state so it can provide relevant, contextual responses. The SDK also provides advanced context window management for long conversations.


Application Context

Inject your app state into the AI's context so it can answer questions about what's happening in your app.

Without context

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

ParameterTypeRequiredDescription
keystringYesUnique identifier for this context
dataanyYesThe data to expose to AI
descriptionstringNoHelps AI understand when to use this context
parentIdstringNoFor 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 }) {
  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 }) {
  useAIContext({
    key: `member-${member.id}`,
    data: { name: member.name, role: member.role, tasks: member.tasks },
    description: `Team member: ${member.name}`,
    parentId,
  });

  return <div>{member.name}</div>;
}

Hierarchical contexts help AI understand relationships. When a 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 }) {
  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 — 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,
  },
});

Never include sensitive data (passwords, API keys, credit cards) in AI context. The context is sent to the LLM provider.


Advanced Context Window Management

For long conversations, the SDK provides tools to control what the AI sees and how history is managed.


Next Steps

On this page