A2UI Launched: Full CopilotKit support at launch!

A2UI Launched: CopilotKit has partnered with Google to deliver full support in both CopilotKit and AG-UI!

Check it out
LogoLogo
  • Overview
  • Integrations
  • API Reference
  • Copilot Cloud
Slanted end borderSlanted end border
Slanted start borderSlanted start border
  • API Reference
  • UI Components
  • CopilotTextarea
  • CopilotKit
  • Hooks
  • useAgent
  • useDefaultTool
  • useFrontendTool
  • useRenderToolCall
  • useHumanInTheLoop
  • useCopilotReadable
  • useCopilotAdditionalInstructions
  • useCopilotChat
  • useCopilotChatHeadless_c
  • useCopilotChatSuggestions
  • useCoAgent
  • useCoAgentStateRender
  • useLangGraphInterrupt
  • useCopilotAction
  • Classes
  • CopilotRuntime
  • CopilotTask
  • SDKs

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

function useAgent(options?: UseAgentOptions): { agent: AbstractAgent }

Parameters

optionsUseAgentOptions

Configuration object for the hook.

agentIdstring
Default: ""default""

ID of the agent to retrieve. Must match an agent configured in CopilotKitProvider.

updatesUseAgentUpdate[]
Default: "[OnMessagesChanged, OnStateChanged, OnRunStatusChanged]"

Controls which agent changes trigger component re-renders. Options:

  • UseAgentUpdate.OnMessagesChanged - Re-render when messages change
  • UseAgentUpdate.OnStateChanged - Re-render when state changes
  • UseAgentUpdate.OnRunStatusChanged - Re-render when execution status changes

Pass an empty array [] to prevent automatic re-renders.

Return Value

object{ agent: AbstractAgent }

Object containing the agent instance.

agentAbstractAgent

The AG-UI agent instance. See AbstractAgent documentation for full interface details.

Core Properties

agentIdstring | undefined

Unique identifier for the agent instance.

descriptionstring

Human-readable description of the agent's purpose.

threadIdstring

Unique identifier for the current conversation thread.

messagesMessage[]

Array of conversation messages. Each message contains:

  • id: string - Unique message identifier
  • role: "user" | "assistant" | "system" - Message role
  • content: string - Message content
stateany

Shared state object synchronized between application and agent. Both can read and modify this state.

isRunningboolean

Indicates whether the agent is currently executing.

debugboolean

Enables debug logging for agent events and execution.

Methods

runAgent(options?: RunAgentOptions) => Promise<void>

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" }
  }
});
setState(newState: any) => void

Updates the shared state. Changes are immediately available to both application and agent.

Example:

agent.setState({
  ...agent.state,
  theme: "dark"
});
subscribe(subscriber: AgentSubscriber) => { unsubscribe: () => void }

Subscribes to agent events. Returns cleanup function.

Subscriber Events:

  • onCustomEvent?: ({ event: { name: string, value: any } }) => void - Custom events (e.g., LangGraph interrupts)
  • onRunStartedEvent?: () => void - Agent execution starts
  • onRunFinalized?: () => void - Agent execution completes
  • onStateChanged?: (state: any) => void - State changes
  • onMessagesChanged?: (messages: Message[]) => void - Messages added/modified

Example:

const { unsubscribe } = agent.subscribe({
  onCustomEvent: ({ event }) => {
    console.log(event.name, event.value);
  }
});

// Cleanup
unsubscribe();
addMessage(message: Message) => void

Adds a single message to the conversation and notifies subscribers.

Example:

agent.addMessage({
  id: crypto.randomUUID(),
  role: "user",
  content: "Hello"
});
addMessages(messages: Message[]) => void

Adds multiple messages to the conversation and notifies subscribers once.

setMessages(messages: Message[]) => void

Replaces the entire message history with a new array of messages.

connectAgent(options?: RunAgentParameters) => Promise<RunAgentResult>

Connects to a streaming agent endpoint. Similar to runAgent but uses the connect() method for persistent connections.

detachActiveRun() => Promise<void>

Detaches from the currently active agent run without aborting it. The run continues in the background but stops updating the local agent state.

abortRun() => void

Aborts the currently running agent execution. Implementation varies by agent type.

clone() => AbstractAgent

Creates a deep copy of the agent with cloned messages, state, and configuration.

use(...middlewares: Middleware[]) => this

Adds middleware to the agent's execution pipeline. Middlewares can intercept and transform agent runs.

Usage

Basic Usage

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

function AgentStatus() {
  const { agent } = useAgent();

  return (
    <div>
      <div>Agent: {agent.id}</div>
      <div>Messages: {agent.messages.length}</div>
      <div>Running: {agent.isRunning ? "Yes" : "No"}</div>
    </div>
  );
}

Accessing State

function StateDisplay() {
  const { agent } = useAgent();

  return <pre>{JSON.stringify(agent.state, null, 2)}</pre>;
}

Updating State

function StateController() {
  const { agent } = useAgent();

  return (
    <button onClick={() => agent.setState({ ...agent.state, count: 1 })}>
      Increment
    </button>
  );
}

Event Subscription

import { useEffect } from "react";
import { useAgent } from "@copilotkit/react-core/v2";
import type { AgentSubscriber } from "@ag-ui/client";

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}</div>
      <div>Support: {support.messages.length}</div>
    </div>
  );
}

Optimizing Re-renders

Control when your component re-renders using the updates parameter:

import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";

// Only re-render when messages change
function MessageCount() {
  const { agent } = useAgent({
    updates: [UseAgentUpdate.OnMessagesChanged]
  });

  return <div>Messages: {agent.messages.length}</div>;
}

// Manually manage subscriptions (no automatic re-renders)
function ManualSubscription() {
  const { agent } = useAgent({ updates: [] });

  useEffect(() => {
    const { unsubscribe } = agent.subscribe({
      onMessagesChanged: () => {
        // Handle changes manually
      }
    });
    return unsubscribe;
  }, [agent]);

  return <div>Manual mode</div>;
}

Behavior

  • Automatic Re-renders: Component re-renders when agent state, messages, or execution status changes (configurable via updates parameter)
  • 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
PREV
CopilotKit
Slanted end borderSlanted end border
Slanted start borderSlanted start border
NEXT
useDefaultTool

On this page

Overview
Signature
Parameters
Return Value
Core Properties
Methods
Usage
Basic Usage
Accessing State
Updating State
Event Subscription
Multiple Agents
Optimizing Re-renders
Behavior
Related