Skip to content

Documentation navigation

Interrupts & Human-in-the-Loop

Pause an agent for human input mid-run and resume the session safely.

#Interrupts and follow-up questions

The SDK has two related human-input surfaces:

  • @depends_on_interrupt(...) supplies a specific tool argument at execution time.
  • agent.allow_followup_questions(...) or swarm.allow_followup_questions(...) lets the runtime ask typed clarification questions during one invocation.

Both surfaces keep the input handler local. Only serializable prompt and policy metadata crosses the wire.

#Tool-argument interrupts

Python
from typing import Literal

from maivn import Agent, default_terminal_interrupt, depends_on_interrupt

agent = Agent(name='deployer', api_key='your-api-key')


@agent.toolify(description='Deploy after a human chooses the environment')
@depends_on_interrupt(
    arg_name='environment',
    input_handler=default_terminal_interrupt,
    prompt='Environment (staging/production):',
)
def deploy(environment: Literal['staging', 'production']) -> dict[str, str]:
    return {'environment': environment}

depends_on_interrupt accepts arg_name, input_handler, optional prompt, optional input_type, and optional choices. A Literal[...] annotation infers a choice prompt. bool infers boolean, int and float infer number, and other annotations use text. Those are the four input types.

The default handler reads one terminal line. A custom handler has the shape Callable[[str], object] and may close over UI or request state. It always receives one positional argument, the prompt, and it may be async. When you omit prompt, the handler receives '<arg_name>: '.

Python
def collect_from_ui(prompt: str) -> str:
    publish_prompt(prompt)
    return wait_for_answer()

The decorated argument must be a real function parameter. The dependency is transported with the tool schema, and the SDK submits the returned answer before local tool execution continues.

#Tool approval

New in maivn 2.5.0. Per-tool approval is opt-in: if you omit approval_policy, a privileged tool stays refused, as it was before 2.5.0.

Privileged tool approval is opt-in through approval_policy='ask' and an approval_handler in the tool's registration metadata. The SDK calls the local handler with a fixed boolean question, then submits its answer through the tool-argument interrupt flow using the reserved argument __tool_approval__. Approval permits one call. Denial or timeout returns tool_authorization_required.

The handler is an ordinary input handler, so the rules above apply: one prompt argument, optionally async. Its prompt is always "Approve this privileged tool invocation?". A handler that also declares tool_name, arguments or call_id, or accepts **kwargs, receives them as keywords: the arguments as the model sent them, with private values shown as placeholders, in a read-only copy. The approval applies only to the call with exactly those arguments.

See Approval for privileged tools for a complete runnable example, the full list of policy values, and what a refusal looks like.

#Runtime-authored follow-up questions

Follow-ups are opt-in per invocation through a chainable builder. There is no persistent enabled switch.

Python
from maivn import Agent, FollowupQuestion

agent = Agent(name='planner', api_key='your-api-key')


def answer_followup(
    question: FollowupQuestion,
    response_schema: dict[str, object],
) -> object:
    print(question.question)
    for option in question.options:
        print(option.label, '-', option.description)
    return 'US East'


response = agent.allow_followup_questions(
    input_handler=answer_followup,
    max_questions=3,
    max_questions_per_thread=10,
    response_schema={'type': 'string'},
    timeout=60,
).invoke('Plan the deployment.', thread_id='thread-42')

The builder takes these keyword-only arguments:

ArgumentDefaultMeaning
input_handlerdefault_terminal_followupA FollowupInputHandler; see below
max_questions3Questions allowed in this run
max_questions_per_thread10Questions allowed across the thread
response_schemaNoneJSON Schema dict or Pydantic model class for the answer. Omit it and the model proposes the answer format.
timeoutNoneWhole seconds to wait for an answer. Omit it and the deployment's human-wait timeout applies. The server rejects a value above 604800 (seven days).

A paused run ends without an answer when its wait times out (followup_question_timed_out, or interrupt_timed_out for a tool input), when it is cancelled, or when it has been paused for seven days. An answer that arrives after seven days is refused. The first hourly check after the seven days ends the run, with the reason checkpoint_retention_limit_reached, and it cannot be resumed.

An answer, and any free-text reason given for cancelling or for an approval decision, is stored with its checkpoint while the run is active and deleted from it when the run ends, however it ends. The stored run then keeps only who answered and when. The answer also reaches your run as part of the conversation: a tool result in the run's history, kept and shielded like any message you send. On the SDK invoke path that tool result is scanned for private values like any other tool result.

The limits and timeout must be positive, or ValueError is raised. The builder wraps these values in FollowupQuestionsConfig, a frozen dataclass you can also build yourself.

The same builder supports invoke, ainvoke, stream, and astream and preserves the normal invocation keyword surface. When an agent_followup checkpoint arrives, the builder calls the handler, submits its typed answer through the current client, and continues the same stream and thread.

#Input handlers

FollowupInputHandler is the alias Callable[[FollowupQuestion, dict[str, Any]], object]. The handler receives the question and the effective response schema, and returns the answer.

  • Return a value that matches the schema. Returning None submits a JSON null; it does not skip the question.
  • Raising EOFError leaves the checkpoint unanswered, so the stream keeps waiting until the server times out, the run is cancelled, or another client answers. Set timeout to bound that wait.

The public question models are FollowupQuestion and FollowupOption, both frozen.

FollowupQuestion fieldNotes
checkpoint_id, thread_id, session_idNon-empty strings
headerOptional, up to 64 characters
questionUp to 2048 characters
explanationOptional, up to 1024 characters
optionsUp to three FollowupOption values
multi_select, requiredBooleans, defaulting to False and True

A FollowupOption has a label (up to 80 characters), a description (up to 240) and an optional value.

default_terminal_followup prints the question, with any header and explanation, plus the numbered options, then reads one line. It converts boolean, object, array/multi-select, option-number, and free-text answers according to the supplied response schema. An option number resolves to that option's value. When options are shown and the schema does not fix the allowed values, it adds a line inviting a free-text answer. Install no extra dependency for this plain terminal path.

#Model-authored tool prompts

Use the exported AgentGenerated singleton as the prompt when the runtime, rather than application copy, should author a tool interrupt question:

Python
from maivn import AgentGenerated, default_terminal_interrupt, depends_on_interrupt


@agent.toolify(description='Collect a deployment note')
@depends_on_interrupt(
    arg_name='note',
    input_handler=default_terminal_interrupt,
    prompt=AgentGenerated,
)
def collect_note(note: str) -> str:
    return note

#Manual client submission

Applications that manage the event loop themselves can submit a typed answer with Client.submit_interrupt_response(thread_id, interrupt_id, answer=..., responded_by=..., surface='sdk'). Use asubmit_interrupt_response in async code. In the next release, this also answers the boolean tool-argument checkpoint used by approval_policy='ask'.

Legacy thread tool_approval checkpoints use the separate submit_approval and asubmit_approval methods, which take decision=ApprovalDecision(approved=..., decided_by=..., reason=None).

For stream shapes, see Events. For private values collected during a turn, see Private Data. Privacy controls reduce exposure but do not certify the deployment.