Coco
Build agents

Human in the loop

Pause a tool call with interrupt() until a person decides, inspect the pending request, resume with Command, and use HumanInTheLoopMiddleware.

Pause a tool call until a person decides, and resume.

interrupt() saves the graph to the checkpointer and surfaces its payload to the caller. Invoking the graph again with Command(resume=...) on the same thread_id continues it, and interrupt() returns the resume value. Any node, tool, or middleware can call it, and a pause needs a checkpointer.

Prerequisites: The framework, installed as in the Quickstart, with OPENAI_API_KEY set.


Pause from middleware

This middleware pauses before one tool and acts on the person's decision:

from coco.agents import create_agent
from coco.agents.middleware import wrap_tool_call
from coco_core.messages import ToolMessage
from coco_core.tools import tool
from coco_graph.checkpoint.memory import InMemorySaver
from coco_graph.types import Command, interrupt


@tool
def delete_database_record(record_id: str) -> str:
    """Permanently delete a record from the database."""
    return f"Record {record_id} deleted."


@wrap_tool_call
def require_human_approval(request, handler):
    if request.tool_call["name"] == "delete_database_record":
        decision = interrupt(
            {
                "action": request.tool_call["name"],
                "args": request.tool_call["args"],
                "question": "Approve permanent deletion?",
            }
        )
        if not decision.get("approved"):
            return ToolMessage(
                content=f"Deletion rejected by operator: {decision.get('reason', 'No reason given')}",
                tool_call_id=request.tool_call["id"],
                name=request.tool_call["name"],
                status="error",
            )
    return handler(request)


agent = create_agent(
    model="openai:gpt-4o",
    tools=[delete_database_record],
    middleware=[require_human_approval],
    checkpointer=InMemorySaver(),
)

config = {"configurable": {"thread_id": "approval-thread-1"}}

# Step 1: Run until the agent pauses at interrupt()
initial = agent.invoke(
    {"messages": [{"role": "user", "content": "Delete record REC-999."}]},
    config=config,
)

# Inspect the pending interrupt payload on the graph state
state = agent.get_state(config)
print("Paused for approval:", state.tasks[0].interrupts[0].value)

# Step 2: Resume execution with the operator's decision
resumed = agent.invoke(
    Command(resume={"approved": True}),
    config=config,
)
print(resumed["messages"][-1].content)

It prints Paused for approval: {'action': 'delete_database_record', 'args': {'record_id': 'REC-999'}, 'question': 'Approve permanent deletion?'}, then the model's answer once the record is deleted. Resume with {"approved": False, "reason": "..."} and the tool never runs; the model reads the rejection instead.

Good to know: On resume, the graph runs the interrupted node again from its start, so code before interrupt() runs twice. Keep side effects after it.

Use HumanInTheLoopMiddleware

HumanInTheLoopMiddleware pauses before the tools you name, so you write no pause code. A person answers each call with approve, edit to change the arguments, or reject to send feedback to the model.

from coco.agents import create_agent
from coco.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig
from coco_graph.checkpoint.memory import InMemorySaver
from coco_graph.types import Command

hitl = HumanInTheLoopMiddleware(
    interrupt_on={
        "send_wire_transfer": InterruptOnConfig(
            allowed_decisions=["approve", "edit", "reject"],
            description="Wire transfers require treasury sign-off.",
        ),
        "read_balance": False,  # Never interrupt on read-only tools
    }
)

agent = create_agent(
    model="openai:gpt-4o",
    tools=[send_wire_transfer, read_balance],
    middleware=[hitl],
    checkpointer=InMemorySaver(),
)

config = {"configurable": {"thread_id": "treasury-1"}}

# 1. Invoke until interrupt
agent.invoke(
    {"messages": [{"role": "user", "content": "Wire $5,000 to vendor VEN-9."}]},
    config=config,
)

# 2. Resume with approval (or edit/reject)
agent.invoke(
    Command(resume={"decisions": [{"type": "approve"}]}),
    config=config,
)

send_wire_transfer and read_balance stand for your own @tool functions.

Good to know: CocoGuard pauses the same way when Coco escalates a call, but the person decides through Coco. See Where Coco attaches.


On this page