Pydantic AI: act in your users' accounts
Give a Pydantic AI agent a tool that calls an Anlyon action for one of your users, defer the run while that user approves in your app, and resume it with the receipt grade.
Pydantic AI runs your agent. It does not hold your users’ GitHub or Gmail tokens, count what the agent does per user, or ask the right person before a risky write. A tool that calls a provider itself needs that user’s token in your agent’s process, and a Pydantic AI approval is answered by your own code, not by the provider call.
With Anlyon, the agent’s tool calls an action by name. Your server binds the tool to one user through the run’s dependencies, Anlyon adds that user’s token at dispatch, checks their limit, parks the call until they approve it in your app, and returns a receipt. The agent never sees a token, and the tool has no user field the model could change.
This guide builds a support agent that opens GitHub issues in each user’s own account:
- The model calls the
open_issuetool. Anlyon parks the call for the user’s approval, the tool raisesCallDeferred, and the run ends withDeferredToolRequests. - The user approves in your app. Approving runs the parked call.
- Your server reads the invocation by id and resumes the run with the result. The model reports the receipt grade.
Before you start
Run the quickstart first, or do its steps 1 and 4 in your environment. You then have:
- The action
open-issue. It opens one issue with the calling user’s own GitHub connection,{{connection:github}}, counts oneissuesper call and reads the issue back. - An approval policy with
decidedBy: "end_user": every call waits for the user it acts for. - An impact limit of 5 issues a day per user (
scope: "end_user"). - An app key,
ANLYON_APP_KEY, from the Standard preset plusend-users:writeandend-users:approvals, with Require an end user on.
The agent’s tool needs actions:invoke, and your resume step actions:read. Your server’s approval routes need end-users:approvals, and its connect routes end-users:write. Nothing here needs the GitHub token, approvals:decide or policies:write.
Install the packages:
pip install pydantic-ai anlyon
Use any model Pydantic AI supports with tool calling. This guide uses "openai:gpt-5-mini".
Check the key at startup
The agent is async, so this guide uses AsyncClient:
import os
from anlyon import AsyncClient
anlyon = AsyncClient(api_key=os.environ["ANLYON_APP_KEY"])
async def check_key() -> None:
# Fail fast on a wrong key: missing what the app needs, or holding what it must not.
await anlyon.auth.require_scopes(
["actions:read", "actions:invoke", "end-users:write", "end-users:approvals"],
forbidden=["approvals:decide", "policies:write", "impact-limits:write", "secrets:write"],
)
require_scopes() raises ScopeCheckError with missing and forbidden. It never changes the key.
Define the agent and its tool
The bound client travels in the run’s dependencies. Your server builds it with anlyon.for_user(end_user_id) from your session, so the tool acts for that user and the model has no way to name another.
The tool raises CallDeferred when Anlyon parks the call. That ends the run with DeferredToolRequests, and the invocation id goes with it as metadata. The idempotency key is made from the tool call’s id, so a tool that runs twice for one call never opens two issues.
# assistant.py
import json
import os
from dataclasses import dataclass
from anlyon import AsyncClient, EndUserConnectionRequiredError
from anlyon.integrations.action_tools import connect_required_result
from pydantic_ai import Agent, CallDeferred, DeferredToolRequests, RunContext
anlyon = AsyncClient(api_key=os.environ["ANLYON_APP_KEY"])
@dataclass
class Deps:
end_user_id: str
user: AsyncClient # anlyon.for_user(end_user_id), built by your server
NOTES = {
"succeeded": "Done.",
"running": "Still running. Do not call it again.",
"unknown": "The outcome is unknown. Do not call it again.",
"failed": "It did not happen. Tell the user why.",
"denied": "The user declined. Do not call it again.",
"expired": "Nobody approved it in time. Do not call it again.",
}
def outcome(invocation: dict) -> str:
"""What the model reads back: status, receipt grade and what to do next."""
status = invocation["status"]
return json.dumps({
"status": status,
"grade": invocation.get("grade"),
"invocationId": invocation["id"],
"error": invocation.get("error"),
"note": NOTES.get(status, ""),
})
support = Agent(
"openai:gpt-5-mini",
deps_type=Deps,
output_type=[str, DeferredToolRequests],
instructions=(
"You help the user track bugs. To open a GitHub issue, call open_issue once. "
"If a tool says the user must connect an account, tell them to use the Connect button. "
"Never call a tool again to get around a decision or an unknown outcome."
),
)
@support.tool
async def open_issue(ctx: RunContext[Deps], title: str, body: str) -> str:
"""Open one GitHub issue in the user's own account. The user approves each issue."""
try:
invocation = (await ctx.deps.user.actions.invoke(
"open-issue",
{"title": title, "body": body},
# One tool call, one invocation, even if the tool runs again.
idempotency_key=f"pydantic-ai:{ctx.deps.end_user_id}:{ctx.tool_call_id}",
)).data
except EndUserConnectionRequiredError as error:
# Not connected: nothing was sent. The model relays the message.
return json.dumps(connect_required_result(error))
if invocation["pendingApproval"]:
raise CallDeferred(metadata={
"invocation_id": invocation["id"],
"approval_id": invocation["approvalId"],
})
return outcome(invocation)
Do not also mark the tool requires_approval=True. That asks for a second yes in your own code, and it does not decide the Anlyon approval.
Run the agent for a user
Your route takes the user from its own session, never from the request body or the model. When the run is deferred, store the conversation on your server:
from pydantic_ai import ConversationTypeAdapter, DeferredToolRequests
from assistant import Deps, anlyon, support
async def chat(session_user_id: str, text: str) -> dict:
deps = Deps(session_user_id, anlyon.for_user(session_user_id))
result = await support.run(text, deps=deps)
if isinstance(result.output, DeferredToolRequests):
# Paused: keep the conversation with the user's chat, and show their approval in your app.
save_conversation(session_user_id, ConversationTypeAdapter.dump_json(result.conversation))
waiting = [m["approval_id"] for m in result.output.metadata.values()]
return {"waiting": waiting}
return {"reply": result.output}
save_conversation and load_conversation (below) are your own storage, keyed by the user from your session. When the user asks to open an issue, the run ends and the call is parked in Anlyon. Nothing has reached GitHub:
{ "waiting": ["apr_01JABCDEF"] }
Let the user approve, then resume
Show the user their pending approval: the exact title and body the agent wants to send. When they decide, your server relays it and resumes the run. Approving runs the parked call with the request exactly as the user saw it.
from pydantic_ai import ConversationTypeAdapter
from assistant import Deps, anlyon, outcome, support
async def pending_approvals(session_user_id: str) -> list[dict]:
# This user's approvals only. Another user's answers 404.
return (await anlyon.end_users.approvals.list(session_user_id, status="pending")).data
async def decide(session_user_id: str, approval_id: str, approve: bool) -> str | None:
await anlyon.end_users.approvals.decide(
session_user_id, approval_id, decision="approve" if approve else "deny"
)
return await resume(session_user_id)
async def resume(session_user_id: str) -> str | None:
conversation = ConversationTypeAdapter.validate_json(load_conversation(session_user_id))
requests = conversation.deferred_tool_requests
user = anlyon.for_user(session_user_id)
answers = {}
for call in requests.calls:
invocation_id = requests.metadata[call.tool_call_id]["invocation_id"]
invocation = (await user.actions.invocation(invocation_id)).data
if invocation["status"] in ("pending_approval", "running"):
return None # not finished yet: try again later
answers[call.tool_call_id] = outcome(invocation)
result = await support.run(
conversation=conversation,
deferred_tool_results=requests.build_results(calls=answers),
deps=Deps(session_user_id, user),
)
return result.output
On resume, the model reads the outcome and replies. For open-issue the tool result is:
{ "status": "succeeded", "grade": "confirmed", "invocationId": "inv_01JABCDEF", "error": null, "note": "Done." }
confirmed means Anlyon read the issue back from GitHub and its title matched.
resume returns None while a call is still running. Call it again later. The approval does not have to be decided while anyone waits: it stays pending for 24 hours by default (your workspace defaults can change the window), and the stored conversation keeps the invocation id. To learn about decisions without polling, subscribe to approval events with a webhook and call resume from there.
Connect a user who has not connected GitHub
When the user has no GitHub connection, the action is not sent, and the tool returns:
{
"status": "connect_required",
"integration": "github",
"connectUrl": "https://...",
"message": "The user has not connected github yet, so nothing was done. Ask them to connect it, then try again."
}
reconnect_required means the provider revoked the connection. Render connectUrl as a Connect GitHub button: it works once, for 10 minutes. It is null when the environment has no default redirect URL; then make a link yourself and confirm the connection in your callback:
from anlyon import parse_connect_redirect
link = (await anlyon.end_users.create_connect_link(
end_user_id=session_user_id,
integration="github",
redirect_url="https://app.example.com/connections/callback",
)).data # send the browser to link["url"]
# In the callback route, with the user from your session:
result = parse_connect_redirect(callback_url)
if result and result.status == "pending_confirmation" and result.flow_id:
await anlyon.end_users.confirm_connection(session_user_id, result.flow_id)
See Workspace connections and end-user connections.
Read the result
| Status | Grade | What your app should do |
|---|---|---|
pending_approval |
pending or null |
Keep the conversation stored. The user decides in your app. |
running |
pending |
Read the same invocation later, then resume. |
succeeded |
confirmed or acknowledged |
Resume with it. confirmed: a read-back matched the request. |
failed |
failed or refused |
Resume with error. refused means Anlyon refused it at dispatch, for example on the user’s daily limit. Nothing was sent. |
unknown |
unknown |
No usable response. Anlyon does not send it again. Tell the model not to call the tool again. |
denied / expired |
denied |
Resume with it. Do not resubmit to get around the decision. |
Handle errors
| Error | What it means | What to do |
|---|---|---|
EndUserConnectionRequiredError |
The user has no working connection. | Handled in the tool: the model gets connect_required. |
EndUserRequiredError (400 END_USER_REQUIRED) |
A call was made without for_user(). |
Always build Deps with anlyon.for_user(session_user_id). |
NotFoundError when resuming |
The invocation belongs to another user, or the id is wrong. | Resume only the conversation you stored for the user in your session. |
ScopeCheckError |
The key is wrong for the app. | Use a key with the scopes above. |
AnlyonError with code AUTHORIZATION_ERROR (403) |
The key lacks a scope a call needs. | Add it when you create the key. |
RateLimitError, NetworkError, TimeoutError |
Raised after the SDK’s own retries. | Run the turn again. The idempotency key answers a repeated tool call from the first record. |
See the Python SDK for every error.
Pydantic AI approvals and Anlyon approvals together
A Pydantic AI tool with requires_approval=True, or one that raises ApprovalRequired, also ends the run with DeferredToolRequests. Your code answers it with DeferredToolResults. That answer is made in your process, and it does not approve the Anlyon call.
The Anlyon approval is the decision on the real call: it goes to the user it acts for, it is bound to the exact request, and only end_users.approvals.decide can make it. Nothing the model or a stored conversation says can make it.
A Pydantic AI tool that calls a provider with its own token does not go through Anlyon, so no limit, approval or receipt applies to it. For a call you cannot move to an action yet, approvals.gate() waits for a decision and then runs your own function with your own credential.
Related
- Python SDK: the client the tool uses.
- Approvals: who decides, and how a policy routes a call.
- Receipts and grades and Idempotency and retries.
- Pydantic AI’s deferred tools.

