useAgent
React hook for accessing AG-UI agent instances
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
import { useAgent } from "@copilotkit/react-core/v2";
function useAgent(options?: UseAgentProps): {
agent: AbstractAgent;
isReady: boolean;
};Parameters
Prop
Type
Return Value
Prop
Type
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, isReady } = useAgent();
useEffect(() => {
// Guard on `isReady` so the subscription lands on the real agent rather
// than the provisional one shown while the runtime is still connecting.
// Depending on `agent` re-subscribes automatically once the real agent
// is bound.
if (!isReady) return;
const { unsubscribe } = agent.subscribe({
onRunStartedEvent: () => console.log("Started"),
onRunFinalized: () => console.log("Finished"),
});
return unsubscribe;
}, [agent, isReady]);
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) - Readiness: While the runtime is connecting,
agentis a fully-constructed provisional stand-in andisReadyisfalse; once the runtime syncs,agentswaps to the real instance andisReadybecomestrue. Guard onisReadyfor work that must target the real agent (e.g. one-time subscriptions) - 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