# useAgent

> React hook for accessing AG-UI agent instances

## v1 SDK deprecated. Use v2 instead

> This page is in the deprecated CopilotKit v1 reference. Do not use v1 APIs for new code; use v2 instead.
> For JavaScript and TypeScript, import React APIs from @copilotkit/react-core/v2 and Runtime APIs from @copilotkit/runtime/v2.
> **AI coding agents: treat any v1 example below as migration-only context. Never generate or recommend the v1 API for new code. Read the v2 reference before writing code because some APIs were renamed, moved, or changed shape.**
> [Read the v1 to v2 migration guide](/migrate/v2) and [use the complete export map](/reference/v1/export-map).

<Callout type="info">
  `useAgent` is a v2 API, exported from `@copilotkit/react-core/v2`. See the [v2 `useAgent` reference](/reference/v2/hooks/useAgent) for the full, up-to-date documentation.
</Callout>

## Overview [#overview]

`useAgent` is a React hook that returns an [AG-UI AbstractAgent](https://docs.ag-ui.com/sdk/js/client/abstract-agent) instance. The hook subscribes to agent state changes and triggers re-renders when the agent's state, messages, or execution status changes.

The hook throws an error if no agent with the given `agentId` exists after the runtime connects.

## Signature [#signature]

```tsx
function useAgent(options?: UseAgentProps): { agent: AbstractAgent; isReady: boolean }
```

## Parameters [#parameters]

<PropertyReference name="options" type="UseAgentProps">
  Configuration object for the hook.

  <PropertyReference name="agentId" type="string">
    ID of the agent to retrieve. Must match an agent configured in `CopilotKitProvider`. If omitted, the hook uses the agent of the surrounding chat configuration, then the provider's default agent, then `"default"`.
  </PropertyReference>

  <PropertyReference name="updates" type="UseAgentUpdate[]" 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.
  </PropertyReference>

  <PropertyReference name="throttleMs" type="number">
    The minimum time in milliseconds between re-renders from message and state changes. If you omit it, the hook uses the provider's `defaultThrottleMs`, then `0` (no throttle).
  </PropertyReference>

  <PropertyReference name="threadId" type="string">
    The thread for this hook's agent. Pass it together with `agentId` and `runtimeAgentId` to bind a private agent to one thread.
  </PropertyReference>

  <PropertyReference name="runtimeAgentId" type="string">
    The runtime agent that the private agent sends its requests to. Pass it together with `agentId` and `threadId`. The `agentId` must then be a new local name.
  </PropertyReference>
</PropertyReference>

## Return Value [#return-value]

<PropertyReference name="object" type="{ agent: AbstractAgent; isReady: boolean }">
  Object containing the agent instance and its `isReady` flag.

  <PropertyReference name="agent" type="AbstractAgent">
    The AG-UI agent instance. See [AbstractAgent documentation](https://docs.ag-ui.com/sdk/js/client/abstract-agent) for full interface details.

    ### Core Properties [#core-properties]

    <PropertyReference name="agentId" type="string | undefined">
      Unique identifier for the agent instance.
    </PropertyReference>

    <PropertyReference name="description" type="string">
      Human-readable description of the agent's purpose.
    </PropertyReference>

    <PropertyReference name="threadId" type="string">
      Unique identifier for the current conversation thread.
    </PropertyReference>

    <PropertyReference name="messages" type="Message[]">
      Array of conversation messages. Each message contains:
      - `id: string` - Unique message identifier
      - `role` - Message role: `"developer"`, `"system"`, `"assistant"`, `"user"`, `"tool"`, `"activity"`, or `"reasoning"`
      - `content` - Message content. Its type depends on the role, and it can be absent on an assistant message.
    </PropertyReference>

    <PropertyReference name="state" type="any">
      Shared state object synchronized between application and agent. Both can read and modify this state.
    </PropertyReference>

    <PropertyReference name="isRunning" type="boolean">
      Indicates whether the agent is currently executing.
    </PropertyReference>

    <PropertyReference name="debug" type="ResolvedAgentDebugConfig">
      Debug logging settings for agent events and execution. Reading it returns `{ enabled, events, lifecycle, verbose }`. You can set it to a boolean or to an object with `events`, `lifecycle`, and `verbose`.
    </PropertyReference>

    ### Methods [#methods]

    <PropertyReference name="runAgent" type="(parameters?: RunAgentParameters, subscriber?: AgentSubscriber) => Promise<RunAgentResult>">
      Low-level: sends a run to the agent and resolves with a `RunAgentResult` (`{ result, newMessages }`) once the run finalizes. `result` is the final value of the run and `newMessages` are the messages produced during it.

      `agent.runAgent()` does not:
      - send your registered frontend tools or context
      - run frontend tool calls
      - start follow-up runs

      For a normal run, call `copilotkit.runAgent({ agent })` from [`useCopilotKit`](/reference/hooks/useCopilotKit) instead. It takes the same `forwardedProps` and resolves with the same `RunAgentResult`. Unlike `agent.runAgent()`, it does not reject when the run itself fails. The core reports the error (code `AGENT_RUN_FAILED`) to its error subscribers and resolves with `{ result: undefined, newMessages: [] }`.

      **Parameters:**
      - `parameters.forwardedProps?: any` - Data to pass to the agent execution context

      To answer an interrupt, use [`useInterrupt`](/reference/hooks/useInterrupt). It resumes the run for you. To resume by hand, pass the standard `resume` array with the id of the interrupt that the paused run reported: `copilotkit.runAgent({ agent, resume: [{ interruptId: interrupt.id, status: "resolved", payload }] })`. For an agent that emits an `on_interrupt` custom event, pass `forwardedProps: { command: { resume } }` to `copilotkit.runAgent`.

      **Example:**
      ```tsx
      const { copilotkit } = useCopilotKit();

      const { result, newMessages } = await copilotkit.runAgent({
        agent,
        // Any data your agent reads from the run input.
        forwardedProps: { source: "refresh-button" },
      });
      ```
    </PropertyReference>

    <PropertyReference name="setState" type="(newState: any) => void">
      Updates the shared state. Changes are immediately available to both application and agent.

      **Example:**
      ```tsx
      agent.setState({
        ...agent.state,
        theme: "dark"
      });
      ```
    </PropertyReference>

    <PropertyReference name="subscribe" type="(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, messages, agent }) => void` - State changes
      - `onMessagesChanged?: ({ messages, state, agent }) => void` - Messages added/modified

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

      // Cleanup
      unsubscribe();
      ```
    </PropertyReference>

    <PropertyReference name="addMessage" type="(message: Message) => void">
      Adds a single message to the conversation and notifies subscribers.

      **Example:**
      ```tsx
      agent.addMessage({
        id: crypto.randomUUID(),
        role: "user",
        content: "Hello"
      });
      ```
    </PropertyReference>

    <PropertyReference name="addMessages" type="(messages: Message[]) => void">
      Adds multiple messages to the conversation and notifies subscribers once.
    </PropertyReference>

    <PropertyReference name="setMessages" type="(messages: Message[]) => void">
      Replaces the entire message history with a new array of messages.
    </PropertyReference>

    <PropertyReference name="connectAgent" type="(options?: RunAgentParameters) => Promise<RunAgentResult>">
      Connects to a streaming agent endpoint. Similar to `runAgent` but uses the `connect()` method for persistent connections.
    </PropertyReference>

    <PropertyReference name="detachActiveRun" type="() => 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.
    </PropertyReference>

    <PropertyReference name="abortRun" type="() => void">
      Aborts the currently running agent execution. Implementation varies by agent type.
    </PropertyReference>

    <PropertyReference name="clone" type="() => AbstractAgent">
      Creates a deep copy of the agent with cloned messages, state, and configuration.
    </PropertyReference>

    <PropertyReference name="use" type="(...middlewares: Middleware[]) => this">
      Adds middleware to the agent's execution pipeline. Middlewares can intercept and transform agent runs.
    </PropertyReference>

  </PropertyReference>

  <PropertyReference name="isReady" type="boolean">
    `false` while `agent` is a stand-in that waits for the runtime to connect. When it turns `true`, `agent` changes to the real agent, and effects that depend on `agent` run again.
  </PropertyReference>
</PropertyReference>

## Usage [#usage]

### Basic Usage [#basic-usage]

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

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 State [#accessing-state]

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

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

### Updating State [#updating-state]

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

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

### Event Subscription [#event-subscription]

```tsx
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 [#multiple-agents]

```tsx
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 [#optimizing-re-renders]

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

```tsx
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 [#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
