HITLGuides

Pydantic AI

Gate Pydantic AI tools with a toolset; approvals use Pydantic AI's deferred tools and resume from the message history.

Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.

Python only.

Install from the registry (to run the repo's own examples, clone it as in the README):

pip install "viewport-hitl[pydantic-ai]"    # pydantic-ai-slim >= 2.74

The example uses a FunctionModel, so it runs with no key.

Wrap the tools in a toolset

hitl.pydantic_ai.toolset(gate, tools, scope=...) takes functions, Pydantic AI tools, @gate functions or a whole toolset (an MCP server, a FunctionToolset). Give the agent output_type=[..., DeferredToolRequests] so a pending approval ends the run instead of failing it.

scope is required (a conversation or user id, or a function of the call), unless an action hook sets the actor or tenant: tool call ids come from the model's client, so an approval is only ever redeemed inside the scope it was asked in. Without either, toolset() raises hitl.scope_required.

examples/python/pydantic-ai/main.py (excerpt)
gate = hitl.Gate(
    {
        "approvers": {"finance": {"channel": "desk", "members": ["desk:dana"]}},
        "rules": {
            "refunds": {"allow": "issue_refund"},
            "large-refunds": {
                "ask": "issue_refund",
                "when": {"args": {"amount": {"gt": 50}}},
                "approver": "finance",
                "reason": "Refunds over $50 need finance",
            },
        },
    },
    channels=[desk],
    clock=FakeClock("2026-11-25T10:00:00Z"),
)


def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    refunded.append({"order_id": order_id, "amount": amount})
    return f"Refunded ${amount:g} on {order_id}"


# Tool call ids come from the model's client, so approvals are scoped to the conversation (or user) they belong to.
tools = hitl.pydantic_ai.toolset(gate, [issue_refund], scope="conversation-42")
agent = Agent(
    FunctionModel(scripted),
    toolsets=[tools],
    output_type=[str, DeferredToolRequests],  # a pending approval ends the run instead of failing it
)

Per call: allowed calls run; policy denials are tool failures the model sees, never a person's problem; asks raise Pydantic AI's ApprovalRequired, so the run ends with DeferredToolRequests.

examples/python/pydantic-ai/main.py (excerpt)
first = await agent.run("Refund A-1002, it arrived broken")
assert isinstance(first.output, DeferredToolRequests)  # the run ended: an approval is pending

Resume

hitl.pydantic_ai.results(gate, requests, toolset=tools) builds DeferredToolResults from the gate's store, with the toolset's scope and action hook: ToolApproved() for granted calls, ToolDenied(message) for refused ones, nothing for calls still pending (wait=True waits instead). The next run redeems each approval right before the function runs.

examples/python/pydantic-ai/main.py (excerpt)
# Later, after finance approved (Slack, the CLI, or gate.respond):
await gate.respond(desk.requests[0].approval_id, hitl.approve(by="desk:dana"))

decided = await hitl.pydantic_ai.results(gate, first.output, toolset=tools)  # decisions from the gate's store
done = await agent.run(message_history=first.all_messages(), deferred_tool_results=decided)
print(f"agent: {done.output}")  # agent: Refund sent.

DeferredToolResults come from the caller, so they are never trusted as decisions. An approver's edits are applied from the store; override_args are accepted only when they are exactly the approved arguments or the approver's edit.

On this page