Agent App Context
Share app specific context with your agent.
What is this?#
One of the most common use cases for CopilotKit is to register app state and context using useAgentContext.
This way, you can notify your agent of what is going on in your app in real time.
When should I use this?#
You can use this when you want to provide the user with feedback about what is in your working memory. As your agent's state updates, you can reflect these updates natively in your application.
Some examples might be: the current user, the current page, etc. This can be shared with your agent in real time.
Implementation#
Share data with your agent#
The useAgentContext hook is used to add data as context to the Copilot.
"use client" // only necessary if you are using Next.js with the App Router.
import { useAgentContext } from "@copilotkit/react-core/v2";
import { useState } from 'react';
export function YourComponent() {
// Create colleagues state with some sample data
const [colleagues, setColleagues] = useState([
{ id: 1, name: "John Doe", role: "Developer" },
{ id: 2, name: "Jane Smith", role: "Designer" },
{ id: 3, name: "Bob Wilson", role: "Product Manager" }
]);
// Define agent context
useAgentContext({
description: "The current user's colleagues",
value: colleagues,
});
return (
// Your custom UI component
<>...</>
);
}Consume the data in your Mastra agent#
Mastra has RuntimeContext class that can be used to set and access the extra context at run time.
The context from CopilotKit is automatically injected there, and can be used immediately.
You can read more about it here
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const colleaguesContactAgent = new Agent({
id: "colleague-agent",
name: "Colleagues contact Agent",
model: openai("gpt-4o"),
// Use the injected runtime context
instructions: ({ requestContext }) => {
const aguiContext = requestContext.get('ag-ui')?.context;
const colleaguesContextItem = aguiContext?.find(contextItem => contextItem.description === "The current user's colleagues")
return `
You are a helpful assistant that can help emailing colleagues.
The user's colleagues are: ${JSON.stringify(colleaguesContextItem?.value, null, 2)}
`
},
// ... Everything else used to configure your agent
});Give it a try!#
Ask your agent a question about the context. It should be able to answer!
