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
Parameters
The hook accepts a singlecontext object with the following properties:
A human-readable description of what this context represents. This helps the agent understand how to use the information.
The context value to provide to the agent. Can be any JSON-serializable type:
stringnumberbooleannull- Arrays of JSON-serializable values
- Objects with JSON-serializable values
JSON.stringify().Return Value
This hook does not return any value. It automatically manages context registration and cleanup.Examples
Simple Context
Complex Object Context
Dynamic Context Updates
Multiple Contexts
Array Context
Conditional Context
Context Lifecycle
The context is automatically managed by the hook:- Registration: When the component mounts, the context is registered with CopilotKit
- Updates: When
valueordescriptionchanges, the context is automatically updated - Cleanup: When the component unmounts, the context is removed
How Agents Use Context
When you provide context viauseAgentContext, 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
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
TypeScript
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.
Related
- useAgent - Access the agent instance
- useFrontendTool - Register tools for agents
- CopilotChat - Full-featured chat component
