Skip to main content
The useAgentContext hook allows you to provide dynamic context information to AI agents. This context is automatically included in agent requests, helping agents understand the current state of your application.

Basic Usage

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

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

Parameters

The hook accepts a single context object with the following properties:
description
string
required
A human-readable description of what this context represents. This helps the agent understand how to use the information.
value
JsonSerializable
required
The context value to provide to the agent. Can be any JSON-serializable type:
  • string
  • number
  • boolean
  • null
  • Arrays of JSON-serializable values
  • Objects with JSON-serializable values
If the value is not a string, it will be automatically converted using JSON.stringify().

Return Value

This hook does not return any value. It automatically manages context registration and cleanup.

Examples

Simple Context

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

function ThemeContext() {
  const theme = useTheme();
  
  useAgentContext({
    description: "Current UI theme preference",
    value: theme.mode // "light" or "dark"
  });
  
  return null;
}

Complex Object Context

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

function DocumentContext({ document }) {
  useAgentContext({
    description: "Currently open document with metadata",
    value: {
      id: document.id,
      title: document.title,
      author: document.author,
      lastModified: document.lastModified,
      wordCount: document.content.split(" ").length,
      tags: document.tags
    }
  });
  
  return (
    <div>
      <h1>{document.title}</h1>
      <p>By {document.author}</p>
    </div>
  );
}

Dynamic Context Updates

import { useAgentContext } from "@copilotkit/react-core";
import { useState, useEffect } from "react";

function ShoppingCart() {
  const [cart, setCart] = useState([]);
  
  useAgentContext({
    description: "Shopping cart contents and total",
    value: {
      items: cart,
      itemCount: cart.length,
      total: cart.reduce((sum, item) => sum + item.price, 0)
    }
  });
  
  return (
    <div>
      <h2>Cart ({cart.length} items)</h2>
      {/* Cart UI */}
    </div>
  );
}

Multiple Contexts

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

function MultiContextComponent({ user, project, settings }) {
  // Provide user context
  useAgentContext({
    description: "Current user information",
    value: {
      id: user.id,
      name: user.name,
      role: user.role
    }
  });
  
  // Provide project context
  useAgentContext({
    description: "Active project details",
    value: {
      id: project.id,
      name: project.name,
      status: project.status
    }
  });
  
  // Provide settings context
  useAgentContext({
    description: "User preferences and settings",
    value: settings
  });
  
  return <div>Working on {project.name}</div>;
}

Array Context

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

function RecentFiles({ files }) {
  useAgentContext({
    description: "Recently opened files",
    value: files.map(f => ({
      name: f.name,
      path: f.path,
      lastOpened: f.lastOpened
    }))
  });
  
  return (
    <ul>
      {files.map(file => (
        <li key={file.id}>{file.name}</li>
      ))}
    </ul>
  );
}

Conditional Context

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

function ConditionalContext({ user, isEditing, currentDocument }) {
  // Always provide user context
  useAgentContext({
    description: "Current user",
    value: { id: user.id, name: user.name }
  });
  
  // Only provide editing context when in edit mode
  if (isEditing && currentDocument) {
    useAgentContext({
      description: "Document being edited",
      value: {
        id: currentDocument.id,
        title: currentDocument.title,
        selectionStart: currentDocument.selectionStart,
        selectionEnd: currentDocument.selectionEnd
      }
    });
  }
  
  return <div>{/* UI */}</div>;
}

Context Lifecycle

The context is automatically managed by the hook:
  1. Registration: When the component mounts, the context is registered with CopilotKit
  2. Updates: When value or description changes, the context is automatically updated
  3. Cleanup: When the component unmounts, the context is removed

How Agents Use Context

When you provide context via useAgentContext, agents receive this information with their requests. The agent can use this context to:
  • Understand the current application state
  • Provide more relevant responses
  • Make better decisions about which tools to use
  • Personalize interactions based on user data
Example agent prompt might include:
Context:
- Current user information: {"id": "123", "name": "Alice", "role": "admin"}
- Shopping cart contents: {"items": [...], "itemCount": 3, "total": 99.99}

Best Practices

Provide Descriptive Labels

Use clear, descriptive text for the description field. This helps the agent understand what the context represents and how to use it.

Keep Context Relevant

Only include information that’s relevant to the agent. Avoid providing sensitive data or unnecessary details.

Update Context Dynamically

Context automatically updates when your component’s props or state change. The agent always receives the most current information.

Use Multiple Contexts

Don’t hesitate to call useAgentContext multiple times in different components. Each context is managed independently.

Performance Considerations

  • Context is converted to a string internally, so large objects may impact performance
  • Context updates trigger re-registration, so avoid unnecessary re-renders with rapidly changing values
  • Consider memoizing complex context values with useMemo
import { useAgentContext } from "@copilotkit/react-core";
import { useMemo } from "react";

function OptimizedContext({ data }) {
  const contextValue = useMemo(() => ({
    summary: data.summary,
    keyMetrics: data.metrics
  }), [data.summary, data.metrics]);
  
  useAgentContext({
    description: "Processed data summary",
    value: contextValue
  });
  
  return null;
}

TypeScript

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

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

Common Use Cases

User State

Provide current user information, preferences, and permissions to personalize agent responses.

Application State

Share the current page, selected items, or active workflows so agents understand the context.

Document Content

Provide information about the current document, selection, or cursor position for document-aware agents.

Form Data

Share form values and validation state to help agents assist with form completion.