Pydantic AI¶
ActionCapability turns registered actions into typed Pydantic AI tools. The
model can propose a command and see a safe preview, but it cannot create
financial authority or bypass the runtime.
The extra admits pydantic-ai-slim>=2.33.0,<3; the integration tests run
against the version in uv.lock, 2.61.0 since 27/10/2026. It installs no
provider SDK. The complete example below uses FunctionModel, so it runs
offline without an API key.
Run the example¶
Output:
The refund was submitted for verification.
The refund was authoritatively verified.
executor calls: 1
Complete agent¶
This file imports the production-shaped refund reference application used by the quickstart. Both files are executable from the source distribution.
"""A complete Pydantic AI agent with a confirm-first refund tool.
Run with:
uv run --extra pydantic-ai python -m examples.docs.pydantic_ai_agent
The FunctionModel keeps this example offline and deterministic. Replace it with
your provider model when integrating the same capability in an application.
"""
from __future__ import annotations
import asyncio
from contextlib import asynccontextmanager
from dataclasses import dataclass
from decimal import Decimal
from typing import TYPE_CHECKING
from pydantic_ai import Agent, DeferredToolRequests
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, ToolCallPart
from pydantic_ai.models import override_allow_model_requests
from pydantic_ai.models.function import AgentInfo, FunctionModel
from examples.refund.app import (
PROPOSING_AGENT,
REQUESTER,
TENANT,
RefundApplication,
RefundDependencies,
build_refund_application,
)
from examples.refund.domain import (
PaymentOrder,
RefundCommand,
RefundPreview,
RefundResult,
RefundSnapshot,
)
from threvo_actions import EvidenceConsumer, Money, OperationOutcome
from threvo_actions.integrations.pydantic_ai import (
ActionAgentContext,
ActionCapability,
DeferredActionRequest,
ScopedActionToolBinding,
)
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from contextlib import AbstractAsyncContextManager
@dataclass(frozen=True)
class AgentDependencies:
tenant_reference: str
demo: RefundApplication
@asynccontextmanager
async def _action_dependencies(
deps: AgentDependencies,
) -> AsyncIterator[RefundDependencies]:
if deps.tenant_reference != deps.demo.host.tenant_reference:
raise PermissionError("tenant is not authenticated for this action")
yield deps.demo.dependencies_for_operation()
def action_dependencies(
deps: AgentDependencies,
) -> AbstractAsyncContextManager[RefundDependencies]:
return _action_dependencies(deps)
def action_context(deps: RefundDependencies) -> ActionAgentContext:
# In a web application, build this from the authenticated server session.
return ActionAgentContext(
tenant_reference=deps.host.tenant_reference,
requesting_principal=REQUESTER,
proposing_agent=PROPOSING_AGENT,
evidence_consumer=EvidenceConsumer(reference="consumer:user:requester"),
)
def offline_model() -> FunctionModel:
calls = 0
def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
nonlocal calls
del messages
calls += 1
if calls == 1:
return ModelResponse(
parts=[
ToolCallPart(
"refund",
{
"intent_reference": "intent:refund:42",
"order_reference": "ORD-42",
"amount": {"amount": "30.00", "currency": "EUR"},
},
tool_call_id="refund-call:1",
)
]
)
if [tool.name for tool in info.function_tools] != ["refund"]:
raise RuntimeError("the refund tool was not registered")
return ModelResponse(parts=[TextPart("The refund was submitted for verification.")])
return FunctionModel(respond)
def seed_demo(demo: RefundApplication) -> None:
demo.ledger.add(
PaymentOrder(
order_reference="ORD-42",
payment_reference="payment:private:42",
customer_contact="private@example.test",
captured=Money(amount=Decimal("100.00"), currency="EUR"),
refunded=Money(amount=Decimal("20.00"), currency="EUR"),
)
)
async def main() -> None:
demo = build_refund_application()
seed_demo(demo)
proposal_reference: str | None = None
async def establish_authority(
request: DeferredActionRequest,
*,
deps: AgentDependencies,
) -> bool:
nonlocal proposal_reference
# A real handler authenticates the confirmer and applies separation of
# duties before recording evidence. Framework approval alone is not enough.
proposal_reference = request.proposal_reference
await deps.demo.approve(request.proposal_reference)
return True
refund: ScopedActionToolBinding[
AgentDependencies,
RefundDependencies,
RefundCommand,
RefundSnapshot,
RefundPreview,
RefundResult,
] = ScopedActionToolBinding(
application=demo.actions,
action=demo.refund,
dependency_scope=action_dependencies,
context_resolver=action_context,
name="refund",
description="Prepare a refund and show a safe preview before execution.",
)
actions = ActionCapability[AgentDependencies](
bindings=[refund],
inline_authority_handler=establish_authority,
)
agent = Agent(
offline_model(),
deps_type=AgentDependencies,
output_type=[str, DeferredToolRequests],
capabilities=[actions],
)
with override_allow_model_requests(False):
result = await agent.run(
"Refund order ORD-42",
deps=AgentDependencies(tenant_reference=TENANT, demo=demo),
)
print(result.output)
if proposal_reference is None:
raise RuntimeError("the action did not produce a proposal reference")
demo.clock.advance(demo.specification.verification_delay)
verified = await demo.reconcile(proposal_reference)
if verified.outcome is not OperationOutcome.VERIFIED:
raise RuntimeError("the authoritative verifier did not confirm the refund")
print("The refund was authoritatively verified.")
print(f"executor calls: {demo.host.executor_calls}")
if __name__ == "__main__":
asyncio.run(main())
What the integration does¶
ScopedActionToolBindingexposes onlyRefundCommandas the model-visible schema and enters a fresh host-owned dependency scope for every call. Tenant, requester, evidence consumer, authority, private state, executor, and verifier are not tool arguments.- The first tool call prepares a proposal and raises Pydantic AI's deferred approval request with safe metadata.
- The host authority handler authenticates and authorizes the confirmer, then
records bound
AuthorityEvidencein the action runtime. - Pydantic AI resumes the tool call in a later dependency scope. The capability resolves trusted context again, binds the registered action, and executes the durable proposal. No prior bound runtime is reusable.
- If execution is immediately due for verification, the capability performs
one reconciliation attempt and returns a display-safe
ActionToolResult. - When verification is delayed or still uncertain, the host schedules a later
reconciliation and reports completion only after a
verifiedoutcome.
ScopedActionToolBinding is also the content-safe boundary around trusted host
composition. Dependency entry, context resolution, recipe binding, and binding
cleanup failures are never forwarded to the model. An optional
binding_failure_handler receives the original exception and traceback under
host logging policy. The tool returns binding_unavailable when composition
never completed, or operation_outcome_unknown when scope cleanup failed after
an operation ran. Models must not retry either outcome; the host owns diagnosis
and reconciliation.
The capability supplies the same fail-closed outcome rules as model-visible
instructions, rather than relying on application prompt authors to reproduce
them. invalid_continuation stops the flow until the host supplies a fresh
continuation. preparation_denied is retried only after trusted host context
changes. prepared_not_visible remains hidden and is not continued from model
context. verification_pending and failed_unknown require host
reconciliation, never a blind resend. Only verified proves completion.
If preparation succeeds but the current evidence consumer cannot read the new
proposal, the tool returns prepared_not_visible without a proposal reference,
lifecycle status, or preview. This is distinct from preparation_denied: the
proposal is durable and remains subject to the host's expiry, retention, and
operator-reconciliation policies, but it is not exposed to the model.
The agent is ordinary Pydantic AI:
agent = Agent(
"openai:gpt-5.2",
deps_type=AgentDependencies,
output_type=[str, DeferredToolRequests],
capabilities=[actions],
)
Replace the offline FunctionModel with your provider and set its credentials
as Pydantic AI documents. The action control flow stays the same.
Keep an existing confirmation flow¶
Brownfield applications often already have model tools and a durable approval
record. ExistingToolActionBinding is the smaller first layer for that case.
It keeps the existing function and confirmation UI, validates at composition
time that the model cannot supply tenant, proposal, snapshot, or authority
fields, and marks the tool requires_approval=True.
from threvo_actions.integrations.pydantic_ai import (
ExistingToolActionBinding,
build_existing_tool_action_toolset,
)
toolset = build_existing_tool_action_toolset(
bindings=(
ExistingToolActionBinding(
name="change_supplier_bank_account",
action_type=SUPPLIER_BANK_CHANGE,
),
),
executors={"change_supplier_bank_account": change_supplier_bank_account},
)
The executor still prepares and continues the durable action through the
runtime. Pydantic AI approval is a suspension and routing signal; it is never
converted into AuthorityEvidence. Applications ready for library-owned
proposal continuation can move one layer deeper to ActionToolBinding, then to
ScopedActionToolBinding for per-call resources, and finally to direct runtime
composition when they need every port.
Deferred approval across requests¶
Inline authority is convenient for a trusted server flow, but a real approval often spans HTTP requests or users. In that case:
The repository includes a second complete program for this flow:
It prints the same verified result as the inline example, but execution pauses until the host records authority. The flow is:
- run the agent and persist
prepared.all_messages()according to your chat retention policy; - render the proposal using trusted server data;
- record bound authority after the authenticated decision;
- call
actions.build_continuation_results(...); and - invoke
agent.run(...)with the prior messages and deferred results.
"""A Pydantic AI approval that pauses and resumes across requests.
Run with:
uv run --extra pydantic-ai python -m examples.docs.pydantic_ai_deferred
The FunctionModel keeps this example offline and deterministic. In production,
persist the returned message history and record authority in an authenticated
approval endpoint before resuming the agent.
"""
from __future__ import annotations
import asyncio
from pydantic_ai import Agent, DeferredToolRequests
from pydantic_ai.models import override_allow_model_requests
from examples.docs.pydantic_ai_agent import (
AgentDependencies,
action_context,
action_dependencies,
offline_model,
seed_demo,
)
from examples.refund.app import TENANT, build_refund_application
from threvo_actions import OperationOutcome
from threvo_actions.integrations.pydantic_ai import ActionCapability, ScopedActionToolBinding
async def main() -> None:
demo = build_refund_application()
seed_demo(demo)
dependencies = AgentDependencies(tenant_reference=TENANT, demo=demo)
actions = ActionCapability[AgentDependencies](
bindings=[
ScopedActionToolBinding(
application=demo.actions,
action=demo.refund,
dependency_scope=action_dependencies,
context_resolver=action_context,
name="refund",
description="Prepare a refund and show a safe preview before execution.",
)
],
)
agent = Agent(
offline_model(),
deps_type=AgentDependencies,
output_type=[str, DeferredToolRequests],
capabilities=[actions],
)
with override_allow_model_requests(False):
prepared = await agent.run("Refund order ORD-42", deps=dependencies)
if not isinstance(prepared.output, DeferredToolRequests):
raise RuntimeError("the action did not request authority")
call_id = "refund-call:1"
metadata = prepared.output.metadata.get(call_id)
if not isinstance(metadata, dict):
raise RuntimeError("the authority request has no continuation metadata")
proposal_reference = metadata.get("proposal_reference")
if not isinstance(proposal_reference, str):
raise RuntimeError("the authority request has no proposal reference")
# This line belongs in an authenticated approval endpoint. The host must
# authorize the confirmer and enforce separation of duties before recording.
await demo.approve(proposal_reference)
continuation = actions.build_continuation_results(
prepared.output,
decisions={call_id: True},
)
with override_allow_model_requests(False):
completed = await agent.run(
"Continue after server authority was recorded",
deps=dependencies,
message_history=prepared.all_messages(),
deferred_tool_results=continuation,
)
print(completed.output)
demo.clock.advance(demo.specification.verification_delay)
verified = await demo.reconcile(proposal_reference)
if verified.outcome is not OperationOutcome.VERIFIED:
raise RuntimeError("the authoritative verifier did not confirm the refund")
print("The refund was authoritatively verified.")
print(f"executor calls: {demo.host.executor_calls}")
if __name__ == "__main__":
asyncio.run(main())
ToolApproved only permits framework continuation. Returning True from an
inline handler without calling record_authority() still leaves the proposal
authority_pending and the executor is not called.
Trust rules¶
- Build
ActionAgentContextfrom authenticated dependencies, never model arguments. - Encode
Decimalcommand fields as JSON strings. Numeric JSON values for those fields are rejected before preparation because a Pythonfloatmay already have lost precision. - Treat deferred metadata and message history as untrusted routing input.
- Do not use
ToolApproved.override_argsto change a prepared action. - Render previews and results from the stored proposal, not model prose.
- Treat only
verifiedas authoritative completion. - Schedule later reconciliation through the same registered action and fresh
host dependency scope when the capability returns
verification_pending. - Raise
ApprovalRequiredonly after the prepare scope exits successfully so a host transaction can commit. Operation exceptions and cancellation leave through the exceptional scope path. Composition failures are reported only through the host-controlled diagnostic hook and a stable safe tool outcome.
Existing applications may continue to use ActionToolBinding with a fixed
expert runtime. Registering an ActionRecipe never exposes a tool by itself;
tool exposure remains an explicit integration decision.
For operator and support agents, ActionRecoveryToolBinding exposes the same
authorized read_recovery projection as direct callers. It accepts a proposal
reference, resolves ReadContext from trusted dependencies, and returns safe
conditions and recommended steps. Those steps remain advice; the tool cannot
approve, execute, reconcile, acknowledge a case, or supply success evidence.
The Stripe reference app enables this extra tool only through its explicit
agent_recovery_enabled setting.
Human decisions that span requests should use the
authenticated approval-channel recipe. Pydantic AI's
framework approval remains continuation control and never replaces the host's
server-bound AuthorityEvidence.
See the Pydantic AI API reference for every integration type.