# Interactive components

> Create approval flows where the agent pauses and waits for human input.

<!-- interactive demo: gen-ui-interrupt -->

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

Interactive generative UI creates flows where the agent pauses execution and waits for user input before continuing. This enables approval workflows, confirmation dialogs, and any scenario where human judgment is needed mid-execution.

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

Use interactive generative UI when you need:

- Approval/rejection flows (e.g. "Run this command?")
- User decisions that the agent should know about
- Confirmation dialogs with structured responses
- Any flow where the agent pauses for human judgment

## How it works in code [#how-it-works-in-code]

<Steps>
  <Step>
    ### Nothing to wire for `useHumanInTheLoop`

    A tool registered with `useHumanInTheLoop` is a frontend tool. The AG-UI
    endpoint forwards its definition to the agent with each run, and the chat
    client sees it alongside the agent's own tools. The agent declares
    nothing for it:

    ```python title="agent/src/agent.py"
    from agent_framework import Agent
    from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
    from fastapi import FastAPI

    # Frontend tools registered with useHumanInTheLoop are automatically available
    agent = Agent(
        name="sample_agent",
        instructions="You are a helpful assistant.",
        client=chat_client,
    )

    app = FastAPI(title="AG-UI Server (Python)")
    add_agent_framework_fastapi_endpoint(app=app, agent=agent, path="/")
    ```

  </Step>
</Steps>

This framework registers `schedule_meeting` as a frontend tool with
`useHumanInTheLoop`. The agent calls the tool, and the chat renders the picker.
The tool call resolves when the picker calls `respond(...)`, after the user
chooses a slot or cancels.

```typescript title="src/app/demos/gen-ui-interrupt/page.tsx"
import {
  CopilotKit,
  CopilotChat,
  useHumanInTheLoop,
} from "@copilotkit/react-core/v2";
import { z } from "zod";
import type { TimeSlot } from "./_components/time-picker-card";
import { TimePickerCard } from "./_components/time-picker-card";
import { generateFallbackSlots } from "../_shared/interrupt-fallback-slots";
import { useGenUiInterruptSuggestions } from "./suggestions";

export default function GenUiInterruptDemo() {
  return (
    <CopilotKit runtimeUrl="/api/copilotkit" agent="gen-ui-interrupt">
      <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() {
  useGenUiInterruptSuggestions();

  // MS Agent Framework has no `interrupt()` primitive, so the LangGraph
  // showcase's `useInterrupt({ renderInChat: true })` hook is silently dead
  // here — it listens for AG-UI `interrupt` events that the MAF backend
  // never emits, leaving the chat stuck on the "[Scheduling...]" tool-call
  // placeholder.
  //
  // `interrupt_agent.py` instead exposes `schedule_meeting` as a tool the
  // model is instructed to call; the frontend registers a matching
  // `useHumanInTheLoop` here, renders the picker inline, and resolves the
  // call via `respond(...)`. UX matches LGP's interrupt-rendered card; the
  // mechanism differs.
  useHumanInTheLoop({
    agentId: "gen-ui-interrupt",
    name: "schedule_meeting",
    description:
      "Ask the user to pick a meeting time. The picker renders inline in " +
      "the chat; the chosen slot is returned to the agent so it can confirm.",
    parameters: z.object({
      topic: z
        .string()
        .describe("What the meeting is about (e.g. 'Intro with sales')"),
      attendee: z
        .string()
        .optional()
        .describe("Who the meeting is with (e.g. 'Alice')"),
    }),
    render: ({ args, respond }: any) => {
      // `TimePickerCard` here is the gen-ui-interrupt-specific variant
      // (under `_components/`) that gates buttons on its own internal
      // `picked`/`cancelled` state — it doesn't take a `status` prop like
      // the hitl-in-chat version. That's fine: the buttons stay clickable
      // until the user makes a choice and `respond(...)` resolves the
      // tool call.
      const topic = (args?.topic as string | undefined) ?? "a call";
      const attendee = args?.attendee as string | undefined;
      const slots = generateFallbackSlots();
      return (
        <TimePickerCard
          topic={topic}
          attendee={attendee}
          slots={slots}
          onSubmit={(result) => respond?.(result)}
        />
      );
    },
  });
```

```python title="src/agents/interrupt_agent.py"
SYSTEM_PROMPT = dedent(
    """
    You are a scheduling assistant. Whenever the user asks you to book a call
    or schedule a meeting, you MUST call the `schedule_meeting` tool. Pass a
    short `topic` describing the purpose of the meeting and, if known, an
    `attendee` describing who the meeting is with.

    The `schedule_meeting` tool is implemented on the client: it surfaces a
    time-picker UI to the user and returns the user's selection. After the
    tool returns, briefly confirm whether the meeting was scheduled and at
    what time, or note that the user cancelled. Do NOT ask for approval
    yourself — always call the tool and let the picker handle the decision.

    Keep responses short and friendly. After you finish executing tools,
    always send a brief final assistant message summarizing what happened so
    the message persists.
    """.strip()
)


def create_interrupt_agent(chat_client: BaseChatClient) -> AgentFrameworkAgent:
    """Instantiate the scheduling-only agent used by the interrupt-adapted demos."""
    base_agent = Agent(
        client=chat_client,
        name="scheduling_agent",
        instructions=SYSTEM_PROMPT,
        # No backend tools. `schedule_meeting` is registered on the frontend
        # via `useFrontendTool` and dispatched through the CopilotKit runtime.
        # When the agent calls `schedule_meeting`, the request is routed to
        # the frontend handler, which returns a Promise that only resolves
        # once the user picks a slot — equivalent to `interrupt()` in the
        # LangGraph reference.
        tools=[],
    )

    return AgentFrameworkAgent(
        agent=base_agent,
        name="CopilotKitMicrosoftAgentFrameworkInterruptAgent",
        description=(
            "Scheduling assistant for the interrupt-adapted demos. Delegates "
            "the time-picker interaction to a frontend tool."
        ),
        require_confirmation=False,
    )

```

Ask the agent to book a call, for example `Book an intro call with the sales
team to discuss pricing`. The time picker appears in the chat. Pick a slot,
and the agent confirms the booked time.

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