Overview
useAgent is a React hook that returns an AG-UI AbstractAgent instance. The hook subscribes to agent state changes and triggers re-renders when the agent's state, messages, or execution status changes.
Throws error if no agent is configured with the specified agentId.
Signature
function useAgent(options?: UseAgentProps): { agent: AbstractAgent };
Parameters
Configuration object for the hook.
ID of the agent to retrieve. Must match an agent configured in
CopilotKitProvider.
Controls which agent changes trigger component re-renders. Options:
UseAgentUpdate.OnMessagesChanged- Re-render when messages changeUseAgentUpdate.OnStateChanged- Re-render when state changesUseAgentUpdate.OnRunStatusChanged- Re-render when execution status changes
Pass an empty array [] to prevent automatic re-renders.
Return Value
Object containing the agent instance.
The AG-UI agent instance. See AbstractAgent documentation for full interface details.
Core Properties
Unique identifier for the agent instance.
Human-readable description of the agent's purpose.
Unique identifier for the current conversation thread.
Array of conversation messages. Each message contains:
id: string- Unique message identifierrole: "user" | "assistant" | "system"- Message rolecontent: string- Message content
Shared state object synchronized between application and agent. Both can read and modify this state.
Indicates whether the agent is currently executing.
Methods
Manually triggers agent execution.
Parameters:
options.forwardedProps?: any- Data to pass to the agent execution context
Example:
await agent.runAgent({
forwardedProps: {
command: { resume: "user response" }
}
});
Updates the shared state. Changes are immediately available to both application and agent.
Example:
agent.setState({
...agent.state,
theme: "dark"
});
Subscribes to agent events. Returns cleanup function.
Subscriber Events:
onCustomEvent?: ({ event: { name: string, value: any } }) => void- Custom eventsonRunStartedEvent?: () => void- Agent execution startsonRunFinalized?: () => void- Agent execution completesonStateChanged?: (state: any) => void- State changesonMessagesChanged?: (messages: Message[]) => void- Messages added/modified
Adds a single message to the conversation and notifies subscribers.
Adds multiple messages to the conversation and notifies subscribers once.
Replaces the entire message history with a new array of messages.
Aborts the currently running agent execution.
Creates a deep copy of the agent with cloned messages, state, and configuration.
Usage
Basic Usage
function AgentStatus() {
const { agent } = useAgent();
return (
<div>
<div>Agent: {agent.agentId}</div>
<div>Messages: {agent.messages.length}</div>
<div>Running: {agent.isRunning ? "Yes" : "No"}</div>
</div>
);
}
Accessing and Updating State
function StateController() {
const { agent } = useAgent();
return (
<div>
<pre>{JSON.stringify(agent.state, null, 2)}</pre>
<button onClick={() => agent.setState({ ...agent.state, count: 1 })}>
Update State
</button>
</div>
);
}
Event Subscription
function EventListener() {
const { agent } = useAgent();
useEffect(() => {
const { unsubscribe } = agent.subscribe({
onRunStartedEvent: () => console.log("Started"),
onRunFinalized: () => console.log("Finished"),
});
return unsubscribe;
}, []);
return null;
}
Multiple Agents
function MultiAgentView() {
const { agent: primary } = useAgent({ agentId: "primary" });
const { agent: support } = useAgent({ agentId: "support" });
return (
<div>
<div>Primary: {primary.messages.length} messages</div>
<div>Support: {support.messages.length} messages</div>
</div>
);
}
Optimizing Re-renders
// Only re-render when messages change
function MessageCount() {
const { agent } = useAgent({
updates: [UseAgentUpdate.OnMessagesChanged],
});
return <div>Messages: {agent.messages.length}</div>;
}
Behavior
- Automatic Re-renders: Component re-renders when agent state, messages, or execution status changes (configurable via
updatesparameter) - Error Handling: Throws error if no agent exists with specified
agentId - State Synchronization: State updates via
setState()are immediately available to both app and agent - Event Subscriptions: Subscribe/unsubscribe pattern for lifecycle and custom events
Related
- AG-UI AbstractAgent - Full agent interface documentation