Skip to main content

Overview

The useAgentContext hook allows you to inject dynamic context into agent conversations. Context helps agents understand the current application state, user information, or any other relevant data when generating responses.

Usage

import { useAgentContext } from "@copilotkit/react";

function UserProfile({ user }) {
  useAgentContext({
    description: "Current user profile information",
    value: {
      id: user.id,
      name: user.name,
      preferences: user.preferences,
    }
  });
  
  return <div>...</div>;
}

Type Signature

function useAgentContext(context: AgentContextInput): void

type JsonSerializable = 
  | string 
  | number 
  | boolean 
  | null 
  | JsonSerializable[] 
  | { [key: string]: JsonSerializable }

interface AgentContextInput {
  description: string;
  value: JsonSerializable;
}

Parameters

context
AgentContextInput
required
Context configuration object with the following properties:

Return Value

This hook does not return a value. Context is automatically added when the component mounts and removed when it unmounts.

Examples

User Information Context

import { useAgentContext } from "@copilotkit/react";

function App({ user }) {
  useAgentContext({
    description: "Authenticated user information",
    value: {
      userId: user.id,
      username: user.username,
      email: user.email,
      role: user.role,
      memberSince: user.createdAt,
    }
  });
  
  return <YourApp />;
}

Application State Context

import { useAgentContext } from "@copilotkit/react";

function Dashboard({ activeView, filters, dateRange }) {
  useAgentContext({
    description: "Current dashboard state and filters",
    value: {
      activeView,
      filters: {
        status: filters.status,
        category: filters.category,
      },
      dateRange: {
        start: dateRange.start.toISOString(),
        end: dateRange.end.toISOString(),
      }
    }
  });
  
  return <DashboardContent />;
}

Shopping Cart Context

import { useAgentContext } from "@copilotkit/react";
import { useCart } from "./hooks/useCart";

function CartProvider({ children }) {
  const cart = useCart();
  
  useAgentContext({
    description: "Shopping cart contents and total",
    value: {
      items: cart.items.map(item => ({
        id: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
      })),
      itemCount: cart.items.length,
      subtotal: cart.subtotal,
      tax: cart.tax,
      total: cart.total,
    }
  });
  
  return <>{children}</>;
}

Document Context

import { useAgentContext } from "@copilotkit/react";

function DocumentEditor({ document }) {
  useAgentContext({
    description: "Current document being edited",
    value: {
      id: document.id,
      title: document.title,
      content: document.content,
      wordCount: document.content.split(" ").length,
      lastModified: document.updatedAt,
      author: document.author,
    }
  });
  
  return <Editor document={document} />;
}

Feature Flags Context

import { useAgentContext } from "@copilotkit/react";
import { useFeatureFlags } from "./hooks/useFeatureFlags";

function FeatureFlagsProvider({ children }) {
  const flags = useFeatureFlags();
  
  useAgentContext({
    description: "Enabled feature flags for current session",
    value: {
      experimentalFeatures: flags.experimental,
      betaFeatures: flags.beta,
      availableIntegrations: flags.integrations,
    }
  });
  
  return <>{children}</>;
}

Multi-Layer Context

You can use multiple useAgentContext calls to provide different layers of context:
import { useAgentContext } from "@copilotkit/react";

function App({ user, workspace }) {
  // User context
  useAgentContext({
    description: "Current user information",
    value: {
      userId: user.id,
      name: user.name,
      role: user.role,
    }
  });
  
  // Workspace context
  useAgentContext({
    description: "Active workspace information",
    value: {
      workspaceId: workspace.id,
      name: workspace.name,
      plan: workspace.plan,
      members: workspace.memberCount,
    }
  });
  
  return <YourApp />;
}

Conditional Context

import { useAgentContext } from "@copilotkit/react";

function ProjectView({ project, userHasAccess }) {
  // Only provide context if user has access
  if (userHasAccess) {
    useAgentContext({
      description: "Current project details",
      value: {
        projectId: project.id,
        name: project.name,
        status: project.status,
        deadline: project.deadline,
        teamSize: project.team.length,
      }
    });
  }
  
  return <ProjectContent project={project} />;
}

String Context

Context values can be plain strings:
import { useAgentContext } from "@copilotkit/react";

function ThemeProvider({ theme }) {
  useAgentContext({
    description: "Current UI theme",
    value: theme // "light" or "dark"
  });
  
  return <YourApp />;
}

Complex Nested Context

import { useAgentContext } from "@copilotkit/react";

function AnalyticsContext({ metrics }) {
  useAgentContext({
    description: "Current analytics metrics and trends",
    value: {
      overview: {
        totalUsers: metrics.users.total,
        activeUsers: metrics.users.active,
        newUsers: metrics.users.new,
      },
      revenue: {
        current: metrics.revenue.current,
        previous: metrics.revenue.previous,
        growth: metrics.revenue.growth,
      },
      topPages: metrics.pages.map(page => ({
        url: page.url,
        views: page.views,
        avgTime: page.avgTimeOnPage,
      })),
      period: {
        start: metrics.period.start,
        end: metrics.period.end,
      }
    }
  });
  
  return <AnalyticsDashboard />;
}

Behavior

Lifecycle

  • Context is registered when the component mounts
  • Context is automatically removed when the component unmounts
  • If the description or value changes, the old context is removed and new context is registered

Serialization

  • String values are used as-is
  • Non-string values (objects, arrays, numbers, booleans, null) are automatically converted to JSON strings
  • The agent receives the context in a format it can understand and use in its reasoning

Context ID

Each context entry is assigned a unique ID internally. This allows multiple components to provide context simultaneously without conflicts.

Use Cases

User Personalization

Provide user profile data so agents can personalize responses based on user preferences, history, or permissions.

Application State

Share current UI state, filters, selections, or navigation context to help agents understand what the user is viewing.

Document/Data Context

Inject the current document, record, or data being worked on so agents can provide relevant assistance.

Feature Availability

Communicate enabled features, integrations, or capabilities so agents know what actions are available.

Business Logic

Share business rules, constraints, or configuration that agents should consider in their responses.

Notes

Context is scoped to the CopilotKit instance. All agents managed by the same CopilotKitProvider will have access to the provided context.
Keep context values focused and relevant. Very large context objects may impact agent performance. Consider providing summaries or specific subsets of data rather than entire application state trees.

Best Practices

  1. Be descriptive: Write clear, informative descriptions that help the agent understand the context
  2. Stay relevant: Only include information that’s likely to be useful for agent responses
  3. Update appropriately: Use the hook in components that re-render when context changes
  4. Structure clearly: Organize complex context objects with clear, nested structures
  5. Avoid PII: Be mindful of sensitive user data; only include what’s necessary