# Pausing the Agent for Input

> Pause an agent run, hand control to a custom Vue component, and resume with the user's answer.

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

Some agent steps need a person's answer before the run can continue, such as approving a payment or picking a meeting time. `useInterrupt` pauses the run, shows your Vue component, and resumes the run with the answer. How the pause works depends on your agent framework.

LangGraph ships a first-class [`interrupt()`](https://docs.langchain.com/oss/python/langgraph/interrupts) primitive that lets a running node suspend itself and hand control to the client. The run is frozen server-side until the client resolves the interrupt with a payload, at which point the node resumes as if `interrupt()` had returned that payload.

CopilotKit's `useInterrupt` is the frontend half of that contract: it subscribes to the paused run, exposes reactive interrupt state, and resumes the agent with the user's answer.

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

Reach for `useInterrupt` when the pause is a **graph-enforced checkpoint** where the code path _must_ stop and wait for a human, not an LLM-initiated tool call. Typical cases:

- A sensitive action (payments, irreversible writes) must be approved
- A required piece of state isn't known and can only be collected from the user
- The agent explicitly reaches an approval node in a longer workflow
- You want the server-side contract to be `interrupt(...)` and resume with a payload

For LLM-initiated pauses where the model decides on the fly to ask the user, prefer [`useHumanInTheLoop`](../human-in-the-loop).

## The backend: `interrupt()` inside a tool [#the-backend-interrupt-inside-a-tool]

<Steps>
  <Step>
    ### Install the CrewAI AG-UI package

    ```bash
    pip install ag-ui-crewai litellm
    ```

  </Step>
  <Step>
    ### Give `useHumanInTheLoop` tools to the model

    A Flow makes its own model call, so it must pass the tools itself:

    - Type the Flow on `CopilotKitState`. A tool registered with
      `useHumanInTheLoop` arrives in `self.state.copilotkit.actions`.
    - Pass the actions as `tools`, inside `copilotkit_stream`, so the tool call
      reaches the browser as it streams.
    - The run ends when the model calls the tool. After the user answers,
      CopilotKit runs the Flow again with the answer as the last message, with
      `role: "tool"`. Read it in the `@start()` step to decide what happens
      next.

    ```python title="agent.py"
    from typing import Any, cast

    from crewai.flow.flow import Flow, listen, start
    from litellm import acompletion

    from ag_ui_crewai import CopilotKitState, copilotkit_stream


    class AgentState(CopilotKitState):
        pass


    class SampleAgentFlow(Flow[AgentState]):
        @start()
        async def check_for_user_feedback(self):
            if not self.state.messages:
                return

            last_message = cast(Any, self.state.messages[-1])

            # The result of the useHumanInTheLoop tool (SEND or CANCEL)
            if last_message["role"] == "tool":
                if last_message.get("content") == "SEND":
                    self.state.messages.append({
                        "role": "assistant",
                        "content": "✅ Great! Sending your essay via email.",
                    })
                    return

                if last_message.get("content") == "CANCEL":
                    self.state.messages.append({
                        "role": "assistant",
                        "content": "❌ Okay, we can improve the draft. What would you like to change?",
                    })
                    return

        @listen(check_for_user_feedback)
        async def chat(self):
            system_message = {
                "role": "system",
                "content": (
                    "You write essays. Use your tools to write an essay; "
                    "don't just write it in plain text."
                ),
            }

            response = await copilotkit_stream(
                await acompletion(
                    reasoning_effort="none",
                    allowed_openai_params=["reasoning_effort"],
                    model="openai/gpt-6-luna",
                    messages=[system_message, *self.state.messages],
                    tools=self.state.copilotkit.actions,
                    stream=True,
                )
            )

            self.state.messages.append(response.choices[0].message)
    ```

  </Step>
  <Step>
    ### Pause the Flow for `useInterrupt`

    To pause at a fixed step in your code instead, decorate the step with
    CrewAI's `@human_feedback` and the AG-UI feedback provider. The step's
    return value is the interrupt payload. The listening step receives the
    user's answer as a `HumanFeedbackResult`.

    ```python title="src/agents/interrupt_flow.py"
    import json
    from typing import Any

    from crewai.flow import Flow, HumanFeedbackResult, human_feedback, listen, start

    from ag_ui_crewai import CopilotKitState, agui_feedback_provider


    class InterruptFlow(Flow[CopilotKitState]):
        @start()
        @human_feedback(
            message="Choose a meeting time or cancel the request.",
            llm=None,
            provider=agui_feedback_provider,
        )
        async def request_schedule(self) -> dict[str, Any]:
            # ... call the model, then return what the picker needs:
            return {"topic": topic, "attendee": attendee, "slots": slots}

        @listen("request_schedule")
        async def confirm_schedule(self, result: HumanFeedbackResult) -> None:
            feedback_text = result.feedback or ""
            # A cancelled interrupt resumes with an empty feedback string.
            cancelled = not feedback_text.strip()
            feedback = {} if cancelled else json.loads(feedback_text)
    ```

    Register the endpoint so it emits standard AG-UI interrupts:

    ```python title="src/agent_server.py"
    add_crewai_flow_fastapi_endpoint(
        app,
        interrupt_flow,
        "/interrupt",
        emit_interrupt_outcome=True,
        enable_legacy_on_interrupt_event=False,
    )
    ```

    For a Conversational Flow, pass these
    two flags in addition to `conversational=True`. On the frontend, read the
    payload from `interrupt.metadata.crewai.output`. See
    `src/agents/interrupt_flow.py` for the full Flow.

  </Step>
</Steps>

The agent can expose a `schedule_meeting` tool that issues an interrupt with the meeting context. The run stops until the client resolves the interrupt. The resolve payload becomes the return value of `interrupt()`. The tool turns that value into a result for the model.

Two things to note:

- The payload, for example `{ "topic": topic, "attendee": attendee }`, is what the Vue frontend receives as `event.value`. The LangGraph adapter sends it as a JSON string, so parse it before you read fields. Keep it a plain, serializable object containing the pause-time context the UI needs.
- The return-side contract, such as `{ chosen_label, chosen_time }` or `{ cancelled: true }`, is entirely yours. The client can send any serializable resolve payload; the tool gives it meaning and must validate it before a side effect.

## The frontend: `useInterrupt` and the chat slot [#the-frontend-useinterrupt-and-the-chat-slot]

Register `useInterrupt` in a descendant component. With the default `renderInChat: true`, the composable publishes the pending interrupt to `CopilotChat`; render it through the `#interrupt` scoped slot and call `resolve(...)` to resume:

```vue title="src/components/MeetingChat.vue"
<script setup lang="ts">
import { CopilotChat, useInterrupt } from "@copilotkit/vue/v2";

type MeetingPayload = { topic?: string; attendee?: string };

// The LangGraph adapter sends the interrupt value as a JSON string.
function readValue(value: unknown): MeetingPayload {
  if (typeof value !== "string") return (value ?? {}) as MeetingPayload;
  try {
    return JSON.parse(value) as MeetingPayload;
  } catch {
    return {};
  }
}

useInterrupt({
  agentId: "gen-ui-interrupt",
});
</script>

<template>
  <CopilotChat agent-id="gen-ui-interrupt">
    <template #interrupt="{ event, resolve }">
      <section>
        <p>Pick a time for {{ readValue(event.value).topic ?? "a call" }}</p>
        <button
          @click="resolve({ chosen_label: 'Tomorrow', chosen_time: '2026-09-01T09:00:00Z' })"
        >
          Tomorrow at 09:00
        </button>
        <button @click="resolve({ cancelled: true })">Cancel</button>
      </section>
    </template>
  </CopilotChat>
</template>
```

Whatever you pass to `resolve` is round-tripped back to the agent as the return value of the matching interrupt.

Ask the agent to book a call. The picker appears in the chat. Click **Tomorrow at 09:00**, and the agent confirms the booked time.

### Key props [#key-props]

- **`agentId`**: must match a runtime-registered agent. If omitted, the composable uses the agent of the surrounding chat configuration, then `"default"`. A mismatch means the interrupt never appears.
- **`renderInChat`**: when `true`, `slotProps` are published to the chat's `#interrupt` slot. Set it to `false` when your own component renders the returned refs elsewhere. See [Headless interrupts](/vue/human-in-the-loop/headless).
- **`handler`**: optionally preprocesses the interrupt, can resolve it early, and exposes its return value as `result`.
- **`enabled`**: filters interrupt shapes before they are surfaced.

The Vue `#interrupt` slot receives `{ event, result, resolve }`. For the complete standard-interrupt surface (including `interrupt`, `interrupts`, and `cancel`), use the composable's returned `slotProps` with `renderInChat: false`.

## Multiple interrupts? Add a type and gate with `enabled` [#multiple-interrupts-add-a-type-and-gate-with-enabled]

If your graph issues more than one kind of interrupt, tag each payload with a `type` field and install one `useInterrupt` per shape, each gated by `enabled`:

```ts
// The LangGraph adapter sends the interrupt value as a JSON string.
function readValue(value: unknown): Record<string, unknown> {
  if (typeof value !== "string") return (value ?? {}) as Record<string, unknown>;
  try {
    return JSON.parse(value) as Record<string, unknown>;
  } catch {
    return {};
  }
}

useInterrupt({
  agentId: "gen-ui-interrupt",
  enabled: (event) => readValue(event.value).type === "ask",
});

useInterrupt({
  agentId: "gen-ui-interrupt",
  enabled: (event) => readValue(event.value).type === "approval",
});
```

## Preprocess with `handler` [#preprocess-with-handler]

For cases where the interrupt can sometimes be resolved _without_ user input, pass a `handler` that runs before the UI is rendered. The handler can call `resolve(...)` itself to resume the agent early, or return a value exposed as `result`:

```ts
const { slotProps } = useInterrupt({
  agentId: "gen-ui-interrupt",
  renderInChat: false,
  handler: async ({ event, resolve }) => {
    const department = await lookupUserDepartment();
    // readValue is the helper from the previous sample.
    const required = readValue(event.value).accessDepartment;

    if (required === department || department === "admin") {
      await resolve({ code: "AUTH_BY_DEPARTMENT" });
      return;
    }

    return { department };
  },
});
```

## AG-UI standard interrupt flow vs. legacy [#ag-ui-standard-interrupt-flow-vs-legacy]

This section is a reference for developers who write interrupt UI for their own agent. The [Vue `useInterrupt` reference](/reference/vue/hooks/useInterrupt) lists every option. `useInterrupt` handles two kinds of interrupt, and your agent framework decides which kind it sends.

### Standard flow (`RUN_FINISHED` with `outcome.type === "interrupt"`) [#standard-flow-run_finished-with-outcometype--interrupt]

When the agent backend conforms to the AG-UI protocol, it signals an interrupt by emitting a `RUN_FINISHED` event whose outcome carries the interrupts array:

```text
outcome.type === "interrupt"
outcome.interrupts  // Interrupt[]
```

The composable detects this on `onRunFinishedEvent` and exposes the interrupts after `onRunFinalized` fires. `slotProps.value` contains:

- **`interrupt`**: the primary `Interrupt` (`interrupts[0]`), with shape `{ id, reason, message?, toolCallId?, responseSchema?, expiresAt?, metadata? }`.
- **`interrupts`**: the full open set.
- **`resolve(payload?, interruptId?)`**: records a resolved response for the targeted interrupt. The run resumes once every open interrupt has a response.
- **`cancel(interruptId?)`**: records a cancelled response for the targeted interrupt. The same accumulate-then-submit logic applies.

### Legacy flow (`on_interrupt` custom event) [#legacy-flow-on_interrupt-custom-event]

Agents can emit a custom `on_interrupt` event. The LangGraph adapter does this by default. The composable exposes its payload in `event.value`, with `interrupt` set to `null` and `interrupts` to `[]`. Calling `resolve(payload)` resumes via `forwardedProps.command`. `cancel()` dismisses the interrupt without resuming because the custom-event flow has no cancel response.

### Priority [#priority]

If both signals appear on the same run, the standard flow wins.

### Approve / Cancel example [#approve--cancel-example]

```vue title="src/components/ApprovalPanel.vue"
<script setup lang="ts">
import { useInterrupt } from "@copilotkit/vue/v2";

const { slotProps } = useInterrupt({ renderInChat: false });
</script>

<template>
  <section v-if="slotProps">
    <p>{{ slotProps.interrupt?.message ?? "Approve this action?" }}</p>
    <button @click="slotProps.resolve({ approved: true })">Approve</button>
    <button @click="slotProps.cancel()">Cancel</button>
  </section>
</template>
```

Both methods return the `RunAgentResult` once the run restarts, or `void` while waiting for responses to other open interrupts.

### Multi-interrupt behavior [#multi-interrupt-behavior]

Some agents issue more than one interrupt in a single run. Each interrupt has its own `id`; address them individually:

```vue
<template>
  <ul v-if="slotProps">
    <li v-for="item in slotProps.interrupts" :key="item.id">
      {{ item.message }}
      <button @click="slotProps.resolve({ ok: true }, item.id)">Approve</button>
      <button @click="slotProps.cancel(item.id)">Cancel</button>
    </li>
  </ul>
</template>
```

The agent run resumes only after **every** open interrupt has been addressed. If you omit `interruptId`, the primary interrupt is targeted; Vue warns when several are open.

### `responseSchema`: surface only, no client-side validation [#responseschema-surface-only-no-client-side-validation]

The `Interrupt` type exposes a `responseSchema` JSON Schema that the agent can use to describe the expected payload. `useInterrupt` surfaces it on `interrupt.responseSchema` for your UI to read, but it does **not** validate `resolve` payloads against it. Validation is the agent's responsibility on resume.

## Provider setup [#provider-setup]

The component calling `useInterrupt` must be a descendant of `CopilotKitProvider`:

```vue title="src/App.vue"
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue/v2";
import MeetingChat from "./components/MeetingChat.vue";
</script>

<template>
  <CopilotKitProvider runtime-url="/api/copilotkit">
    <MeetingChat />
  </CopilotKitProvider>
</template>
```
