# HITL Overview

> Allow your agent and users to collaborate on complex tasks.

<!-- interactive demo: hitl-in-chat -->

<Callout type="info" title="See this in Inspector">
  Open Inspector on localhost. Go to **Inspect**, then **Frontend Tools**.
  Your tool and its schema are listed.

  More detail: [Inspector](/ag2/inspector).
</Callout>

## What is this? [#what-is-this]

Human-in-the-loop (HITL) lets an agent pause mid-run to collect input,
confirmation, or a choice from the user, then resume with that answer
folded back into its reasoning. It's what turns an autonomous workflow
into a collaborative one: the agent keeps its context, the user keeps
the steering wheel.

<video
  src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/human-in-the-loop-example.mp4"
  className="rounded-lg shadow-xl"
  loop
  playsInline
  controls
  autoPlay
  muted
/>

## When should I use this? [#when-should-i-use-this]

Use HITL when you need:

- **Quality control**: a human gate at high-stakes decision points.
- **Missing input**: the agent needs a value only the user knows, such as a meeting time.
- **Risky actions**: the agent must get a yes before it sends, pays, or deletes.
- **Expert input**: the user supplies domain knowledge the model lacks.

## Two patterns for HITL in CopilotKit [#two-patterns-for-hitl-in-copilotkit]

CopilotKit ships two complementary ways to pause an agent turn and ask
the human something. They look similar from the outside (the chat
pauses, a custom component appears, the user answers, the run resumes)
but they're wired differently on the backend, and each has its own niche.

| Pattern | Who decides to pause? | Backend surface |
| --- | --- | --- |
| `useHumanInTheLoop` | The **LLM**, by calling a registered client-side tool | A frontend-only tool description (Zod schema + `render`) |
| `useInterrupt` | Your **agent code**, at a step that must stop for a person | An interrupt your agent emits, for example LangGraph `interrupt()` or Mastra `suspend()` |

**Pick `useHumanInTheLoop`** when the pause is an _agent-initiated_
decision (the model chose to ask the user) and you want the picker UI
inlined into the normal tool-call flow.

**Pick `useInterrupt`** when the pause is a checkpoint in your agent code:
the code path always requires a human answer, and the server-side contract is
an interrupt. On the Built-in Agent, interrupts are temporarily unavailable, so
use `useHumanInTheLoop` there.

<Steps>
  <Step>
    ### `useHumanInTheLoop`: no frontend-tool code on the agent

    `AGUIStream` turns every tool the client declares into a client-side tool,
    so a tool you register with `useHumanInTheLoop` reaches the model through
    the AG-UI request. Do not declare it on the AG2 agent. Name it in the
    agent's `prompt` so the model calls it.

    To keep the user's answer, have a backend tool write it to
    `context.variables`. When a tool changes the variables, `AGUIStream` sends
    a `STATE_SNAPSHOT` at the end of the run:

    ```python title="agent.py"
    from typing import Annotated

    from fastapi import FastAPI, Header
    from fastapi.responses import StreamingResponse
    from pydantic import Field

    from ag2 import Agent, Context, tool
    from ag2.ag_ui import AGUIStream, RunAgentInput
    from ag2.config import OpenAIResponsesConfig

    @tool
    def store_user_choice(
        choice: Annotated[str, Field(description="The option selected by the user")],
        context: Context,
    ) -> str:
        """Store the latest user choice in shared state."""
        context.variables["hitl"] = {"latest_choice": choice}
        return f"Stored choice: {choice}"

    agent = Agent(
        name="assistant",
        prompt=(
            "When you need the user to choose, call the frontend tool `offerOptions`. "
            "After it returns, call `store_user_choice` with the selected value."
        ),
        config=OpenAIResponsesConfig(model="gpt-6-luna"),
        tools=[store_user_choice],
    )

    stream = AGUIStream(agent)
    app = FastAPI()

    @app.post("/chat")
    async def run_agent(
        message: RunAgentInput,
        accept: str | None = Header(None),
    ) -> StreamingResponse:
        return StreamingResponse(
            stream.dispatch(message, accept=accept),
            media_type=accept or "text/event-stream",
        )
    ```

  </Step>
  <Step>
    ### Approve a tool call with interrupts

    AG2 can also pause a run on the **backend**. A tool wrapped in
    `ApprovalRequired` is held until the user approves or rejects the call.
    AG2 sends the held call to the client as an AG-UI interrupt, and
    CopilotKit's `useInterrupt` renders it.

    ```python title="tools.py"
    from typing import Annotated

    from pydantic import Field

    from ag2 import Context, tool
    from ag2.middleware.builtin.tools.approval import ApprovalRequired

    @tool(
        description="Save a city to the user's favorites. The user confirms before anything is saved.",
        middleware=[
            ApprovalRequired("Save this city to your favorites?\n{tool_arguments}", allow_always=False)
        ],
    )
    async def save_favorite_city(
        context: Context,
        city: Annotated[str, Field(description="The city name to save, e.g. 'Lisbon'")],
    ) -> list[str]:
        favorites = list(context.variables.get("favorites", []))
        if city not in favorites:
            favorites.append(city)
        context.variables["favorites"] = favorites
        return favorites
    ```

    Serve the agent with `AGUIStream` as usual. Do not set a `hitl_hook` on
    the agent. With one, AG2 asks in-process and no interrupt reaches the
    browser.

    The run ends with an interrupt of reason `tool_call`. The backend reads the
    answer as a boolean, so `resolve(true)` approves the call and
    `resolve(false)` refuses it. A refusal does not fail the run: the model is
    told the call was refused and carries on.

    ```tsx title="page.tsx"
    import { useInterrupt } from "@copilotkit/react-core/v2";

    export function Page() {
      useInterrupt({
        render: ({ interrupt, resolve }) => (
          <div>
            <p>{interrupt?.message ?? "The assistant needs your confirmation."}</p>
            <button onClick={() => resolve(true)}>Approve</button>
            <button onClick={() => resolve(false)}>Reject</button>
          </div>
        ),
      });

      // ...
    }
    ```

    Ask `Save Lisbon to my favorites`. The approval card appears in the chat.
    Approve it, and the city shows up in the shared state.

    <Callout type="warn">
      `useInterrupt().resolve()` and `.cancel()` send no `metadata` in the
      resume entry. That is enough for a gated tool call like the one above,
      but not for an AG2 server built with `require_resume_proof=True`, which
      needs the interrupt's `metadata` copied into the resume entry. See
      <a href="https://docs.ag2.ai/docs/user-guide/ag-ui/overview#asking-the-human-a-question" target="_blank">Asking the human a question</a>
      in the AG2 docs.
    </Callout>

    A held turn lives in the AG2 process that served the run, so the resuming
    run must reach that same process. See
    <a href="https://docs.ag2.ai/docs/user-guide/ag-ui/overview#deployment-a-held-turn-lives-in-one-process" target="_blank">the AG2 deployment notes</a>
    before you run several replicas.

  </Step>
</Steps>

## Pattern 1: `useHumanInTheLoop` (tool-based) [#pattern-1-usehumanintheloop-tool-based]

Register a HITL tool in your React app with `useHumanInTheLoop`.
When the LLM calls that tool, CopilotKit routes the call through your
`render` function, which shows a custom component and calls `respond`
with the user's answer. The agent sees the answer as the tool result and
continues from there.

```typescript title="src/app/demos/hitl-in-chat/page.tsx"
import React from "react";
import {
  CopilotKit,
  CopilotChat,
  useHumanInTheLoop,
  useConfigureSuggestions,
} from "@copilotkit/react-core/v2";
import { z } from "zod";
import { TimePickerCard, TimeSlot } from "./time-picker-card";

const DEFAULT_SLOTS: TimeSlot[] = [
  { label: "Tomorrow 10:00 AM", iso: "2026-04-19T10:00:00-07:00" },
  { label: "Tomorrow 2:00 PM", iso: "2026-04-19T14:00:00-07:00" },
  { label: "Monday 9:00 AM", iso: "2026-04-21T09:00:00-07:00" },
  { label: "Monday 3:30 PM", iso: "2026-04-21T15:30:00-07:00" },
];

export default function HitlInChatDemo() {
  return (
    <CopilotKit runtimeUrl="/api/copilotkit" agent="hitl-in-chat">
      <div className="flex justify-center items-center h-screen w-full">
        <div className="h-full w-full max-w-4xl">
          <Chat />
        </div>
      </div>
    </CopilotKit>
  );
}

function Chat() {
  useConfigureSuggestions({
    suggestions: [
      {
        title: "Book a call with sales",
        message:
          "Please book an intro call with the sales team to discuss pricing.",
      },
      {
        title: "Schedule a 1:1 with Alice",
        message: "Schedule a 1:1 with Alice next week to review Q2 goals.",
      },
    ],
    available: "always",
  });

  useHumanInTheLoop({
    agentId: "hitl-in-chat",
    name: "book_call",
    description:
      "Ask the user to pick a time slot for a call. The picker UI presents fixed candidate slots; the user's choice is returned to the agent.",
    parameters: z.object({
      topic: z
        .string()
        .describe("What the call is about (e.g. 'Intro with sales')"),
      attendee: z
        .string()
        .describe("Who the call is with (e.g. 'Alice from Sales')"),
    }),
    render: ({ args, status, respond }: any) => (
      <TimePickerCard
        topic={args?.topic ?? "a call"}
        attendee={args?.attendee}
        slots={DEFAULT_SLOTS}
        status={status}
        onSubmit={(result) => respond?.(result)}
      />
    ),
  });
```

The sample imports `TimePickerCard` from its own file. The card renders the
slots and calls `onSubmit` with the user's choice. These are its props:

```typescript title="src/app/demos/hitl-in-chat/time-picker-card.tsx"
export interface TimePickerCardProps {
  topic: string;
  attendee?: string;
  slots: TimeSlot[];
  status: TimePickerStatus;
  onSubmit: (
    result: { chosen_time: string; chosen_label: string } | { cancelled: true },
  ) => void;
}
```

Each slot button calls `onSubmit({ chosen_time: s.iso, chosen_label: s.label })`.
The "None of these work" button calls `onSubmit({ cancelled: true })`. The full
file is in the Code view of the demo at the top of this page.

The picker UI is fed a static list of candidate slots. This is just
data the demo page owns, so you can swap in real availability, a
calendar API, or anything else:

```typescript title="src/app/demos/hitl-in-chat/page.tsx"
import React from "react";
import {
  CopilotKit,
  CopilotChat,
  useHumanInTheLoop,
  useConfigureSuggestions,
} from "@copilotkit/react-core/v2";
import { z } from "zod";
import { TimePickerCard, TimeSlot } from "./time-picker-card";

const DEFAULT_SLOTS: TimeSlot[] = [
  { label: "Tomorrow 10:00 AM", iso: "2026-04-19T10:00:00-07:00" },
  { label: "Tomorrow 2:00 PM", iso: "2026-04-19T14:00:00-07:00" },
  { label: "Monday 9:00 AM", iso: "2026-04-21T09:00:00-07:00" },
  { label: "Monday 3:30 PM", iso: "2026-04-21T15:30:00-07:00" },
];
```

## Pattern 2: `useInterrupt` (agent-paused) [#pattern-2-useinterrupt-agent-paused]

With an interrupt, your agent code enforces the pause, for example with
LangGraph's `interrupt()`:

1. A node calls `interrupt({...})`, and the run stops.
2. The client receives the payload and renders your UI.
3. The user answers, and the run resumes with the answer.

CopilotKit's `useInterrupt` hook is the render contract.

See the [`useInterrupt` deep dive](/human-in-the-loop/useInterrupt) for
the full walkthrough, including the backend tool and render-prop wiring.

## Going headless [#going-headless]

Both patterns above ship with a `render` prop. CopilotKit handles the
"when to show the picker" logic for you. If you want to drive
interrupt resolution from a custom UI that lives anywhere in the tree
(not necessarily inside a chat), see the
[headless interrupts guide](/human-in-the-loop/headless). It shows
how to compose `useAgent`, `agent.subscribe`, and `copilotkit.runAgent`
to build your own `useInterrupt` equivalent.

<IntegrationGrid path="human-in-the-loop" />
