Interactive components

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

Human in the Loop: Interrupts

Waking up the demo

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?

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

Install the CrewAI AG-UI package

pip install ag-ui-crewai litellm

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.
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)

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.

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:

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.

On the frontend, register an interrupt renderer with useInterrupt. When the agent pauses, your component mounts inline in the chat, captures the user's choice, and resumes the run with that input. The excerpt imports the demo's TimePickerCard, its fallback slots, and its suggestions. Use your own picker component in their place.

page.tsx
import {
  CopilotKit,
  CopilotChat,
  useInterrupt,
} from "@copilotkit/react-core/v2";
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";

type SchedulingPayload = {
  topic?: string;
  attendee?: string;
  slots?: TimeSlot[];
};

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();
  useInterrupt({
    agentId: "gen-ui-interrupt",
    renderInChat: true,
    render: ({ event, interrupt, resolve }) => {
      const metadata = interrupt?.metadata as
        | { crewai?: { output?: SchedulingPayload } }
        | undefined;
      const raw = event.value ?? {};
      const fallback = (typeof raw === "string" ? JSON.parse(raw) : raw) as
        | SchedulingPayload
        | { metadata?: { crewai?: { output?: SchedulingPayload } } };
      const payload: SchedulingPayload =
        metadata?.crewai?.output ??
        ("metadata" in fallback
          ? fallback.metadata?.crewai?.output
          : (fallback as SchedulingPayload)) ??
        {};
      const slots =
        payload.slots && payload.slots.length > 0
          ? payload.slots
          : generateFallbackSlots();
      return (
        <TimePickerCard
          topic={payload.topic ?? "a call"}
          attendee={payload.attendee}
          slots={slots}
          onSubmit={(result) => setTimeout(() => resolve(result), 500)}
        />
      );
    },
  });

  return (
    <CopilotChat agentId="gen-ui-interrupt" className="h-full rounded-2xl" />
  );
}

On the backend, the agent pauses the run with its framework's interrupt primitive and waits for the user's answer before it continues.

interrupt_flow.py
class InterruptState(CopilotKitState):
    pending_tool_call_id: str | None = None
    meeting: dict[str, Any] = Field(default_factory=dict)


class InterruptFlow(Flow[InterruptState]):
    """Pause after schedule_meeting and continue from a spec resume entry."""

    @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]:
        response = await copilotkit_stream(
            await acompletion(
                allowed_openai_params=["reasoning_effort"],
                reasoning_effort="none",
                model="openai/gpt-6-luna",
                messages=[
                    {"role": "system", "content": SYSTEM_PROMPT},
                    *self.state.messages,
                ],
                tools=[SCHEDULE_MEETING_TOOL],
                tool_choice={
                    "type": "function",
                    "function": {"name": "schedule_meeting"},
                },
                parallel_tool_calls=False,
                stream=True,
            )
        )
        message = response.choices[0].message
        self.state.messages.append(message)
        tool_calls = message.get("tool_calls") or []
        schedule_call = next(
            (
                call
                for call in tool_calls
                if call.get("function", {}).get("name") == "schedule_meeting"
            ),
            None,
        )
        if schedule_call is None:
            return {
                "topic": "Meeting",
                "attendee": None,
                "slots": candidate_slots(),
            }

        try:
            arguments = json.loads(
                schedule_call.get("function", {}).get("arguments") or "{}"
            )
        except (TypeError, json.JSONDecodeError):
            arguments = {}
        self.state.pending_tool_call_id = schedule_call.get("id")
        slots = arguments.get("slots")
        return {
            "topic": arguments.get("topic") or "Meeting",
            "attendee": arguments.get("attendee"),
            "slots": slots if isinstance(slots, list) and slots else candidate_slots(),
        }

    @listen("request_schedule")
    async def confirm_schedule(self, result: HumanFeedbackResult) -> None:
        feedback_text = result.feedback or ""
        try:
            feedback = json.loads(feedback_text or "{}")
        except (TypeError, json.JSONDecodeError):
            feedback = {}
        if not isinstance(feedback, dict):
            feedback = {}
        output = result.output if isinstance(result.output, dict) else {}
        # The AG-UI CrewAI provider resumes a cancelled protocol interrupt
        # with an empty feedback string. Submitted choices are JSON objects,
        # so an empty payload is the package's authoritative cancel signal.
        cancelled = not feedback_text.strip() or bool(feedback.get("cancelled"))
        self.state.meeting = {
            "topic": output.get("topic") or "Meeting",
            "attendee": output.get("attendee"),
            "time": None if cancelled else feedback.get("chosen_time"),
            "label": None if cancelled else feedback.get("chosen_label"),
            "cancelled": cancelled,
        }

        if self.state.pending_tool_call_id:
            result_content = json.dumps(self.state.meeting)
            self.state.messages.append(
                {
                    "role": "tool",
                    "tool_call_id": self.state.pending_tool_call_id,
                    "content": result_content,
                }
            )
            await copilotkit_emit_tool_result(
                self.state.pending_tool_call_id, result_content
            )
        response = await copilotkit_stream(
            await acompletion(
                allowed_openai_params=["reasoning_effort"],
                reasoning_effort="none",
                model="openai/gpt-6-luna",
                messages=[
                    {
                        "role": "system",
                        "content": (
                            f"{SYSTEM_PROMPT}\nScheduling outcome: "
                            f"{json.dumps(self.state.meeting)}"
                        ),
                    },
                    *self.state.messages,
                ],
                tools=[SCHEDULE_MEETING_TOOL],
                parallel_tool_calls=False,
                stream=True,
            )
        )
        self.state.messages.append(response.choices[0].message)

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.

How is this guide?