> ## Documentation Index
> Fetch the complete documentation index at: https://docs.typesafe.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Banking assistant

> Route banking requests with Jev in a Pydantic AI agent. When Jev's probability for its pick is low, the app asks the customer and offers the routes Jev rated likeliest.

A customer writes "i want assistance with my utility bill". They could want to pay it, or
to see what they owe. A bank's assistant has to give each request a route: the one thing
the app should do with it. Most requests are clear: "what's my balance" has one route. An
app that guesses on the unclear ones does the wrong thing some of the time, and an app that
asks about every request is slow to use.

Here we build a banking assistant as a [Pydantic AI](https://pydantic.dev/pydantic-ai)
agent. Jev picks the route and returns a probability for every route. Jev is the agent's
model, through Pydantic AI's
[`TypeSafeModel`](https://pydantic.dev/docs/ai/models/typesafe/). When the probability of
Jev's pick is 0.8 or more, the app acts on it. When it is lower, Pydantic AI raises
`UnsureRoute`, and the app asks the customer to choose among the routes to which Jev gave a
probability of 0.1 or more.

On 600 labeled requests from [CLINC150](https://github.com/clinc/oos-eval) (Larson et al.,
CC BY 3.0), the app asked the customer on 35, about 1 in 17. Jev's pick matched the label
on 20 of those 35, and the routes the app offered included the label's route on 34.

| | ends correctly | acted without asking (% matching the label) | asked the customer (% offering the label's route) | routes offered per ask |
| - | - | - | - | - |
| **The app: asks when Jev's pick is under 0.8** | **98.3%** | 94% (98.4%) | 6% (97%) | 2.3 |
| Acting on Jev's pick every time | 96.0% | 100% (96.0%) | – | – |

A request "ends correctly" if the app acts on the label's route, or asks and offers it.

You end up with `respond()`, which takes one customer request and returns what the app does
next: the route to act on, or the routes to offer.

```mermaid actions={true} theme={null}
  %%{init: {"fontFamily": "Inter, sans-serif", "flowchart": {"rankSpacing": 35, "wrappingWidth": 300, "subGraphTitleMargin": {"top": 8, "bottom": 76}}}}%%
flowchart TB
    %% Branch colors (styles.css): node classes and green_/blue_ edge ids.
    REQ["customer request"]
    subgraph R1["Jev call 1<br/>route question"]
        PICK["<b>Choice:</b> which route?<br/><i>options: the output<br/>functions and tools</i>"]
    end
    GATE{"pick ≥<br/>threshold?"}
    subgraph R2["Jev call 2<br/>argument question<br/><i>skipped if the route<br/>has no argument</i>"]
        FILL["<b>Choice:</b> the argument<br/><i>e.g. which bill?</i>"]
    end
    REQ -->|"request + route question"| R1
    R1 -->|"pick + a probability<br/>per route"| GATE
    GATE blue_ask@-->|"no:<br/>UnsureRoute"| ASK["app asks the customer which of<br/>Jev's likeliest routes they meant<br/><i>the reply goes back to Jev as the next turn</i>"]
    GATE -->|"yes"| R2
    GATE blue_amount@-->|"yes: transfer<br/>(Jev can't fill the amount)"| AMOUNT["app asks the customer<br/>for the amount"]
    R2 blue_confirm@-->|"action"| CONFIRM["confirm button"]
    R2 green_answer@-->|"information"| ANSWER["answer written<br/>by code from<br/>account data"]
    class ANSWER neonGreen
    class ASK,CONFIRM,AMOUNT neonBlue
```

## Setup

> [card] [Run in Colab](https://colab.research.google.com/github/typesafe-ai/typesafe-public-examples/blob/pub-20261203-d36583/integrations/pydantic-ai/banking_assistant/pydantic_ai_banking_assistant.ipynb)
>
> Runs as published without an API key.

> [card] [Python file](https://github.com/typesafe-ai/typesafe-public-examples/blob/pub-20261203-d36583/integrations/pydantic-ai/banking_assistant/pydantic_ai_banking_assistant.py)
>
> This page as one .py file, to run locally.

> [card] [Open in playground](https://console.typesafe.ai/playground#share/N4IgJg9gxgrgtgUwHYBcAqCAeKQC4AEIA7gBYCGKA5AM74okL5gyNgWMBmEATvnAJ74oEOFDLUU+AEYBLADZyQAGkIAHbiNUpqGbHkLAAOiA0wUCYwSMgo3GebtlL+a1LJyySKBf3GMCugYhGAkRBF4SCCI+GCgSPggkBEEZWhkkQIQZXjckAGt8MihhGFQAOmMVYxRuT2oilBlE6mdjABlUyXpGbgRvVHx0sBkANxlmdzpapHqoRub8RMzg0MRuGkLiiFKUCuV8Y2pVZGGkAHMAfRJOnn5WkABleDgyO2pGSOi4WPjulZQwhFxPgjsgUCoePhSBRMoJQQNEhCRuFCvhjnYIGA9lUTNtGud7gBxUaMP65PIbUz4s74JDwKQori8P6wVbhDZFErlSoHEDpBwICQXWrme7+OTLVkAtbLfnhQWSEWkhjZaSeAqc7YDBCvGbY3manYXKRyaB5BBge4AUUwqg86ShJEELJC0vZtENA1S0lNUHNYBUvv9i14HA0AC9kCpPGB8J86BB8KUTWbBrsecZZAoLswfAQ-AgAi62bxSMhUVmJd7c-rM-I5Mb3J5vGLCxLi26IlEYnFYYsiIwlmRpPXazZesMUBc5DI4PZW0WglLAZKJ-Z8DO5+CQ6uLeuJPXCiMyPIyCaEBCMt1VbY95IxNwsRmQHOkBdVGR+IhUAv20vXSufzUC8CgKmin7fl0DCCGIGQvOaiwZMOt6TkIryxpCw6VmOZDqL+koATKfwAIIAAoAEoqH8cq9BI+BKkI5DcGcFqIZkN5rve6FjlgqjZBQTRvmwoq+CA4oESWjrltevAPrGvHZIKY5yTmfQzkklqiTadonhkpDOv+JYbHJULAmAanpKxMLDqoMDcHE4gIGOvREOh1CNh4Xh5ry4kdiu8YvEggguehaIQPytDdII5DIs5FoIAgcDCggrmPi0Wm2vaGTxn5MqwfR8WJTu8KxjJBWpbGqjhag1BjjRSACYk7gXBwCXpfmYlthJnaOjCrWCuxsmhQ5zEDUyaJ2Q57welIGhkBhvAOhA3SyXZvReDISnPr0OneJBFwqcwIqCfhuUovGprnKiSTRJCO0eHtYJoY+dBkOakWJq8dixc+uF2jIYjzG+EgUCEp2GT1Za9INQicc9sZ-TOgOCSCKAxrVz4ofYFzUMIvTg4wy5ESqq3cOt95w7jPBOc+s7qBAyIHZxON495xjEsi3UrvNYzeGxtSpOkNJlVjkhU70Y7mVA6lsyAAAiFlJGFM7mHI-BlPgaBBL0ACOLB0d6SDLYUUh4lzawbHAiTJCo5KbFy2gqHJtCQpWtX4DaZBwHagoEDUZDInIKjUJEqh8ecVFBAOFAMNwwcge27h5GOYYJZGFyeig9wAGK9Agkbm+6ar5PbWpi4mRv0ELaEZAy4HjPgYYiGmY7+zMrXcPcACyDOMFbSSCAyKADtJEOAhyWw7Bj+zGB+-DGvW9ykZ+iGDhwhfrLQbu0lEY48OZ3AHQwfrtbyADyj4osON3SBAEAFBA68fuijF9HktDjWdm+lzsY7h0fngWL3AAMLkHOMqRgpEACSAA5NiX9jKhUwpPbkM8TAICqtwKcYYyAwE0h1ciGCeCSGHDgvBMA5BPUhKUXowgzhIFSKxEaLEIS8GoCEY4cxWJkIDPAseFsPQoPTGgnaxDpwQCFHJe4hDMFQUJoRIuJlTR0UhKEShSEkCxhTH6Fuz42AvBYmAA66FpEYIeowZCoV6AwmrF7MghjbYaHNBkSERsNyJBYqWHg780ROmoADdwatlLM03NjBy4D7jEWoAUcaw5rhnFjjuU0A5ZJw1CZIJYCDaCi3hmOG6xjHyRLDmrRumFaQpVhneXJxgAC+OJ0gSG4LEIGp9rB6wVCdUSAB1a4vZH6ZHeEwCAA0q7ZMCaU7gAB+Z8bg-RnFMJo+4ABNbYhRoZ-HEP4kGXokJonCNQJqEoODpGbBYsOTtEhJC4aVRMWTi4aiEdQJ2cNnaFE0SOBQHpJCkABgwZEOR1QenecIb2nhNqRWgkmd4GsAAG5hsAwsGLQaEcj-grgAFauhBCeMAABufAMLrihG4PwRFkQ5BgAhYwHU3AZwohQHZGYKgZDr08OrWpOIUD8GOPcOI4UWwgBqTU-YIBcIyAAGr7MEvoEAIwACMgqgA)
>
> Edit one request and run it live. Needs a TypeSafe account.

Requires Python 3.11 or later.

```bash theme={null}
pip install 'pydantic-ai-slim[typesafe,openai]==2.71.0' nest-asyncio2 matplotlib ipython 'cooksafe>=0.3.0,<0.4.0'
```

With uv, `uv run pydantic_ai_banking_assistant.py` installs the dependencies for you.

The code replays saved answers, so it runs as published without an API key. To change a
request, set `TYPESAFE_API_KEY` and `OPENAI_API_KEY`; in Colab, add them in the Secrets
panel. The script downloads
[`samples.json`](https://github.com/typesafe-ai/typesafe-public-examples/blob/pub-20261203-d36583/integrations/pydantic-ai/banking_assistant/samples.json)
from the typesafe-public-examples repository if it isn't already on disk. The file holds
CLINC150 requests, used under CC BY 3.0. The attribution and a list of our changes are in
[`DATA_LICENSE.md`](https://github.com/typesafe-ai/typesafe-public-examples/blob/pub-20261203-d36583/integrations/pydantic-ai/banking_assistant/DATA_LICENSE.md).

A live run makes about 600 agent runs on Jev, and three on gpt-5.5, which reads a
transfer's amount. The latencies shown are the ones recorded when the answers were saved.

The results below are from `jev-1.14.0` and gpt-5.5, run on 2026-11-25.

```python expandable theme={null}
import hashlib
import inspect
import json
import os
import statistics
import urllib.request
from dataclasses import asdict
from pathlib import Path
from time import perf_counter
from typing import Annotated, get_type_hints

import matplotlib.pyplot as plt
from cooksafe import JsonCache, make_playground_link
from IPython.display import Markdown, display
import nest_asyncio2
import pydantic_ai
from pydantic_ai import Agent, Choices, DeferredToolRequests, ModelResponse, Tool
from pydantic_ai.messages import ModelRequest, TextPart, UserPromptPart
from pydantic_ai.models.decision import (
    DecisionModelSettings,
    UnfillableRoute,
    UnsureRoute,
)
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIResponsesModel
from pydantic_ai.models.typesafe import TypeSafeModel
from pydantic_ai.providers.openai import OpenAIProvider
from pydantic_ai.providers.typesafe import TypeSafeProvider

pydantic_ai.BANNER_ENABLED = False  # no first-run Logfire banner
# A notebook is already running an event loop, and `run_sync` can't start a second one
# inside it. `nest_asyncio2.apply()` lets `run_sync` start one anyway. A plain script doesn't
# need the call.
nest_asyncio2.apply()

TYPESAFE_MODEL = "jev-1.14.0"  # the page's model; "jev-latest" runs the newest, live
LLM_MODEL = "gpt-5.5"  # reads a transfer's amount
# When the probability of Jev's pick is under this, the app asks the customer instead of
# acting.
ROUTE_THRESHOLD = 0.8
# When the app asks, it offers the routes to which Jev gave at least this probability.
OFFER_FLOOR = 0.1

# The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here.
KEYS = ["TYPESAFE_API_KEY", "OPENAI_API_KEY"]
try:
    from google.colab import userdata
except ImportError:  # not in Colab
    userdata = None
for key in KEYS:
    if userdata is not None and key not in os.environ:
        try:
            os.environ[key] = userdata.get(key)
        except (userdata.SecretNotFoundError, userdata.NotebookAccessError):
            pass  # not saved, or this notebook may not read it


# Replaying saved answers needs no keys, so both clients fall back to a placeholder.
def jev_model(name: str) -> TypeSafeModel:
    key = os.environ.get("TYPESAFE_API_KEY", "cache-only")
    return TypeSafeModel(name, provider=TypeSafeProvider(api_key=key))


def llm_model(name: str) -> OpenAIResponsesModel:
    key = os.environ.get("OPENAI_API_KEY", "cache-only")
    return OpenAIResponsesModel(name, provider=OpenAIProvider(api_key=key))


HERE = Path(__file__).resolve().parent if "__file__" in globals() else Path.cwd()

EXAMPLES = (
    "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261203-d36583/"
    "integrations/pydantic-ai/banking_assistant"
)


def download(name: str) -> Path:
    """Fetch one of this cookbook's files from typesafe-public-examples unless it is on disk."""
    path = HERE / name
    if not path.exists():
        path.parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(f"{EXAMPLES}/{name}", path)
    return path


CACHE = HERE / "pydantic_ai_banking_assistant_cache.json"
# True fills CACHE with the published answers, so the run makes no requests. To run
# live, set it to False and delete CACHE; a CACHE already on disk is never overwritten.
DOWNLOAD_CACHE = True
if DOWNLOAD_CACHE:
    download(CACHE.name)
json_cache = JsonCache(CACHE, indent=None)

CHART_PALETTES = {
    "light": {
        "surface": "#ffffff", "ink": "#0b0b0b", "ink2": "#52514e", "muted": "#898781",
        "grid": "#e1e0d9", "axis": "#c3c2b7", "blue": "#2a78d6",
    },
    "dark": {
        "surface": "#0d0a0f", "ink": "#fafafa", "ink2": "#d4d4d8", "muted": "#a1a1aa",
        "grid": "#2e2e33", "axis": "#52525b", "blue": "#5b9be8",
    },
}


def show_chart(draw) -> None:
    """Display the chart draw(palette) makes. The docs build sets COOKSAFE_RENDER and also
    gets a dark copy."""
    for theme in ("light", "dark") if os.environ.get("COOKSAFE_RENDER") else ("light",):
        fig = draw(CHART_PALETTES[theme])
        display(fig, metadata={"theme": theme})
        plt.close(fig)
```

## Load a labeled sample

The requests come from [CLINC150](https://github.com/clinc/oos-eval). Each one is a short
request to an assistant, labeled with its intent: what the person wanted, such as
`balance`. There are 150 intents across 10 domains, such as banking and travel, plus
requests labeled out of scope because they fit none of the intents. The app handles the 30
intents in the banking and credit-card domains. Requests from the other eight domains, and
the out-of-scope ones, should go to the `decline` route.

`samples.json` holds 600 requests drawn at random, with a fixed seed, from the CLINC150
test set: 15 for each of the 30 intents, 75 from other domains, and 75 out of scope.

The requests are short and casual, and a few intents overlap, so some requests fit two
routes: `transactions` and `spending_history`, `new_card` and `replacement_card_duration`,
`credit_limit` and `balance`.

```python theme={null}
SAMPLES = json.loads(download("samples.json").read_text())
# CLINC labels a request that fits none of its intents `out_of_scope`; the app's route for it
# is `decline`.
REQUESTS = [r | {"label": "decline" if r["gold"] == "out_of_scope" else r["gold"]}
            for r in SAMPLES["requests"]]
to_decline = sum(r["label"] == "decline" for r in REQUESTS)
print(f"{len(REQUESTS)} requests, {to_decline} to decline")
print()
for row in REQUESTS[:4]:
    print(f"{row['label']:<26}{row['text']}")
```

```
600 requests, 150 to decline

bill_balance              what are my total bills this month
international_fees        will it cost me anything to use my card in turin
decline                   how do you spell "montpelier
pin_change                access my checking account and update my pin to 1234
```

## Write each route as a function

Write each kind of request the app supports as a Python function. Each function is one
route. Pydantic AI builds each route's name, description, and argument types from the
function's signature and docstring. It then sends Jev one Choice question with every route
as an option. A second call to Jev sends one Choice question for each argument of the
picked route. To decide, Jev sees the request and any earlier turns, the agent's
instructions, and the route descriptions.

Each route is an output function or a tool:

* **Output functions.** Calling one ends the run, and its return value is the reply. They
  cover the 20 information requests and `decline`. Jev picks one and fills its arguments.
  The function then writes the answer from the customer's data, so no model writes any
  text.
* **Tools with `requires_approval=True`**, for the 10 actions. When Jev picks one, the run
  ends with a `DeferredToolRequests` object, which holds the tool call waiting for
  approval. The app shows a confirm button, and nothing runs until the customer taps it.

One tool, `transfer`, has an argument Jev can't fill. Its `amount: float | None` can be any
number, so there's no set of options for Jev to choose from. When Jev picks `transfer`,
Pydantic AI raises an `UnfillableRoute` exception. The app catches it and asks the customer
for the amount.

The account, card, and bill arguments are `Choices` built at run time from the customer's
data, so Jev picks from this customer's own accounts instead of a list fixed in the code.
The action functions return placeholder strings, and some output functions return fixed
example text.

```python expandable theme={null}
INSTRUCTIONS = (
    "You are the assistant in a personal finance app, connected to the customer's bank "
    "accounts, credit cards and bills at whichever banks and companies they use. `text` is "
    "what the customer just said; `history` holds the earlier turns, if any."
)

# The customer's data (mock).
ACCOUNTS = {
    "checking": {"about": "Everyday checking account, ending 4821", "balance": 2310.55,
                 "rate": 0.01, "routing": "123456789"},
    "savings": {"about": "Savings account, ending 9930", "balance": 12840.00,
                "rate": 3.75, "routing": "123456789"},
}
CARDS = {
    "visa": {"about": "Visa credit card, ending 1234", "limit": 8000, "owed": 1240.10,
             "apr": 22.9, "min": 35, "expires": "09/2028", "points": 18450, "fx_fee": 3},
    "mastercard": {"about": "Mastercard credit card, ending 5678", "limit": 3000,
                   "owed": 310.00, "apr": 19.9, "min": 25, "expires": "02/2027",
                   "points": 2210, "fx_fee": 0},
}
BILLS = {
    "electricity": {"about": "Electricity bill", "due": "Oct 14", "amount": 84.20},
    "phone": {"about": "Phone bill", "due": "Oct 20", "amount": 45.00},
    "internet": {"about": "Internet bill", "due": "Oct 22", "amount": 60.00},
    "water": {"about": "Water bill", "due": "Oct 28", "amount": 31.75},
}

# The options come from the customer's data, so they're Choices built at run time.
Account = Choices({k: v["about"] for k, v in ACCOUNTS.items()})
Card = Choices({k: v["about"] for k, v in CARDS.items()})
Bill = Choices({k: v["about"] for k, v in BILLS.items()})


def reply(route: str, text: str, args: dict | None = None) -> dict:
    """What the app shows: an answer an output function builds from the customer's data."""
    return {"route": route, "text": text, "args": args or {}}


def money(x: float) -> str:
    return f"${x:,.2f}"


def each(name: str | None, table: dict) -> list[str]:
    """The one item the customer named, or all of them when they didn't say."""
    return [name] if name else list(table)


# An information request: an output function. Jev picks it and fills `account`; the function
# writes the answer.
def balance(account: Annotated[str, Account] | None = None) -> dict:
    """Tell the customer how much money is in their bank account.

    Args:
        account: Which account is the customer asking about?
    """
    lines = [f"{ACCOUNTS[a]['about']}: {money(ACCOUNTS[a]['balance'])}"
             for a in each(account, ACCOUNTS)]
    return reply("balance", "\n".join(lines), {"account": account})


def bill_due(bill: Annotated[str, Bill] | None = None) -> dict:
    """Tell the customer when a bill is due.

    Args:
        bill: Which bill is the customer asking about?
    """
    lines = [f"{BILLS[b]['about']}: due {BILLS[b]['due']}" for b in each(bill, BILLS)]
    return reply("bill_due", "\n".join(lines), {"bill": bill})


# Requests the app doesn't handle get a route too, so Jev always has a fitting option.
def decline() -> dict:
    """Decline politely. The request is not about the customer's money, bank accounts, cards or bills. Examples: travel, shopping, the weather, small talk."""
    return reply("decline", "Sorry, I can only help with your accounts, cards and bills.")


# An action: a tool that needs the customer's confirmation. Nothing runs until they confirm.
def report_lost_card(card: Annotated[str, Card] | None = None) -> str:
    """Report the customer's card lost or stolen and block it.

    Args:
        card: Which card was lost or stolen?
    """
    return "reported"


# `amount` can be any number, so Jev can pick this route but can't fill `amount`.
def transfer(
    from_account: Annotated[str, Account] | None = None,
    to_account: Annotated[str, Account] | None = None,
    amount: float | None = None,
) -> str:
    """Move money between the customer's accounts.

    Args:
        from_account: Which account does the money come from?
        to_account: Which account does the money go to?
        amount: How much money, in dollars? Leave empty if the customer gave no amount.
    """
    return "transferred"
```

The other 26 routes follow the same patterns. The lists `ANSWERS` and `ACTIONS` hold every
route, in the order Jev sees them. Each saved answer is stored under a key that
includes `WORDING`, a short hash of the instructions, the customer data, and the route
names, parameter names, and docstrings. Edit any of those and the saved answers no longer
match, so the run needs new answers from the models.

```python expandable theme={null}
def transactions(account: Annotated[str, Account] | None = None) -> dict:
    """List the recent individual transactions on the customer's account.

    Args:
        account: Which account is the customer asking about?
    """
    return reply("transactions", "Your last 5 transactions: ...", {"account": account})


def spending_history(account: Annotated[str, Account] | None = None) -> dict:
    """Summarise how much the customer has spent, or what they spent on, over a period.

    Args:
        account: Which account is the customer asking about?
    """
    return reply("spending_history", "You spent $1,284.90 this month: ...", {"account": account})


def routing(account: Annotated[str, Account] | None = None) -> dict:
    """Give the bank's routing number for the customer's account.

    Args:
        account: Which account is the customer asking about?
    """
    a = account or "checking"
    return reply("routing", f"Routing number: {ACCOUNTS[a]['routing']}", {"account": account})


def interest_rate(account: Annotated[str, Account] | None = None) -> dict:
    """Tell the customer the interest rate their bank account earns.

    Args:
        account: Which account is the customer asking about?
    """
    lines = [f"{ACCOUNTS[a]['about']}: {ACCOUNTS[a]['rate']}% APY"
             for a in each(account, ACCOUNTS)]
    return reply("interest_rate", "\n".join(lines), {"account": account})


def account_blocked(account: Annotated[str, Account] | None = None) -> dict:
    """Explain why the customer's account is blocked, locked or frozen, and how to unblock it.

    Args:
        account: Which account is the customer asking about?
    """
    return reply("account_blocked", "None of your accounts is blocked right now.",
                 {"account": account})


def bill_balance(bill: Annotated[str, Bill] | None = None) -> dict:
    """Tell the customer how much they owe on a bill.

    Args:
        bill: Which bill is the customer asking about?
    """
    lines = [f"{BILLS[b]['about']}: {money(BILLS[b]['amount'])}" for b in each(bill, BILLS)]
    return reply("bill_balance", "\n".join(lines), {"bill": bill})


def credit_limit(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer the credit limit, or the credit still available, on their credit card.

    Args:
        card: Which card is the customer asking about?
    """
    lines = [f"{CARDS[c]['about']}: limit {money(CARDS[c]['limit'])}, "
             f"available {money(CARDS[c]['limit'] - CARDS[c]['owed'])}"
             for c in each(card, CARDS)]
    return reply("credit_limit", "\n".join(lines), {"card": card})


def min_payment(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer the smallest payment they can make on a credit card or a bill.

    Args:
        card: Which card is the customer asking about, if it's a card?
    """
    lines = [f"{CARDS[c]['about']}: minimum {money(CARDS[c]['min'])}" for c in each(card, CARDS)]
    return reply("min_payment", "\n".join(lines), {"card": card})


def apr(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer the APR, the interest rate charged on their credit card.

    Args:
        card: Which card is the customer asking about?
    """
    lines = [f"{CARDS[c]['about']}: {CARDS[c]['apr']}% APR" for c in each(card, CARDS)]
    return reply("apr", "\n".join(lines), {"card": card})


def expiration_date(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer when their card expires.

    Args:
        card: Which card is the customer asking about?
    """
    lines = [f"{CARDS[c]['about']}: expires {CARDS[c]['expires']}" for c in each(card, CARDS)]
    return reply("expiration_date", "\n".join(lines), {"card": card})


def card_declined(card: Annotated[str, Card] | None = None) -> dict:
    """Explain why the customer's card was declined at a purchase.

    Args:
        card: Which card is the customer asking about?
    """
    return reply("card_declined", "Your last declined payment was flagged as unusual; ...",
                 {"card": card})


def rewards_balance(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer how many reward points they have.

    Args:
        card: Which card is the customer asking about?
    """
    lines = [f"{CARDS[c]['about']}: {CARDS[c]['points']:,} points" for c in each(card, CARDS)]
    return reply("rewards_balance", "\n".join(lines), {"card": card})


def redeem_rewards(card: Annotated[str, Card] | None = None) -> dict:
    """Explain how the customer can redeem or spend their reward points.

    Args:
        card: Which card is the customer asking about?
    """
    return reply("redeem_rewards", "You can redeem points for statement credit or travel: ...",
                 {"card": card})


def international_fees(card: Annotated[str, Card] | None = None) -> dict:
    """Tell the customer what fees their card charges for purchases abroad or in other currencies.

    Args:
        card: Which card is the customer asking about?
    """
    lines = [f"{CARDS[c]['about']}: {CARDS[c]['fx_fee']}% foreign transaction fee"
             for c in each(card, CARDS)]
    return reply("international_fees", "\n".join(lines), {"card": card})


def replacement_card_duration() -> dict:
    """Tell the customer how long a new or replacement card takes to arrive."""
    return reply("replacement_card_duration", "A replacement card arrives in 5–7 business days.")


def application_status() -> dict:
    """Tell the customer where their credit card application stands."""
    return reply("application_status", "Your application is being reviewed; ...")


def credit_score() -> dict:
    """Tell the customer their current credit score."""
    return reply("credit_score", "Your credit score is 742 (updated Oct 1).")


def improve_credit_score() -> dict:
    """Give the customer advice on raising their credit score."""
    return reply("improve_credit_score", "Pay on time, keep utilisation under 30%, ...")


def freeze_account(account: Annotated[str, Account] | None = None) -> str:
    """Freeze the customer's bank account so nothing can be paid from it.

    Args:
        account: Which account should be frozen?
    """
    return "frozen"


def pay_bill(bill: Annotated[str, Bill] | None = None) -> str:
    """Pay one of the customer's bills now.

    Args:
        bill: Which bill should be paid?
    """
    return "paid"


def order_checks(account: Annotated[str, Account] | None = None) -> str:
    """Order a new book of paper checks for the customer's account.

    Args:
        account: Which account are the checks for?
    """
    return "ordered"


def pin_change() -> str:
    """Change the PIN on the customer's card or account."""
    return "changed"


def report_fraud() -> str:
    """Report a fraudulent or unrecognised charge, or suspected fraud, on the customer's account."""
    return "reported"


def damaged_card(card: Annotated[str, Card] | None = None) -> str:
    """Replace a card that is damaged, broken or no longer works physically.

    Args:
        card: Which card is damaged?
    """
    return "replacement ordered"


def credit_limit_change(card: Annotated[str, Card] | None = None) -> str:
    """Ask for a higher or lower credit limit on the customer's credit card.

    Args:
        card: Which card should the limit change on?
    """
    return "requested"


def new_card() -> str:
    """Apply for a new credit card."""
    return "applied"


ANSWERS = [balance, transactions, spending_history, routing, interest_rate, account_blocked,
           bill_due, bill_balance, credit_limit, min_payment, apr, expiration_date,
           card_declined, rewards_balance, redeem_rewards, international_fees,
           replacement_card_duration, application_status, credit_score, improve_credit_score,
           decline]
ACTIONS = [freeze_account, transfer, pay_bill, order_checks, pin_change, report_fraud,
           report_lost_card, damaged_card, credit_limit_change, new_card]
# Resolve type hints here, in case this runs where annotations are kept as strings.
for route in ANSWERS + ACTIONS:
    route.__annotations__ = get_type_hints(route, include_extras=True)

# A change to a route's name, parameter names or docstring, the instructions or the customer's
# data changes this hash, so replay fails until new answers are saved.
WORDING = hashlib.sha256(json.dumps([
    INSTRUCTIONS, ACCOUNTS, CARDS, BILLS,
    [[f.__name__, list(inspect.signature(f).parameters), inspect.getdoc(f)] for f in ANSWERS + ACTIONS],
]).encode()).hexdigest()[:8]
print(f"{len(ANSWERS)} output functions, {len(ACTIONS)} actions, wording {WORDING}")
```

```
21 output functions, 10 actions, wording b8eaec10
```

## Build the agent

The agent's model is Jev. Its output types are the output functions plus
`DeferredToolRequests`, which a run returns when it stops at an action. Its tools are the
actions, each with `requires_approval=True`.

Run the agent with `decision_route_threshold=ROUTE_THRESHOLD`. When the probability of
Jev's pick is under the threshold, Pydantic AI raises `UnsureRoute` before it fills any
argument. The exception carries Jev's probability for every route. The app offers the
customer the routes at `OFFER_FLOOR` or more, and never fewer than two or more than four.

`respond()` takes one customer request and returns a record of what the app does next:
answer, show a confirm button, or ask which route. The record also holds Jev's pick, the
pick's arguments, how long the run took, and every nonzero route probability, read from
`result.response.provider_details['route']['probabilities']`.

A run stops after the first call to Jev when the pick is under the threshold or is
`transfer`.

```python expandable theme={null}
def build_agent(model, settings: DecisionModelSettings | None = None) -> Agent:
    return Agent(
        model,
        output_type=[*ANSWERS, DeferredToolRequests],
        tools=[Tool(action, requires_approval=True) for action in ACTIONS],
        instructions=INSTRUCTIONS,
        model_settings=settings,
    )


def as_record(output) -> dict:
    """What the run ended with: an action to confirm, or an output function's answer."""
    if isinstance(output, DeferredToolRequests):
        call = output.approvals[0]
        return {"kind": "confirm", "route": call.tool_name, "args": call.args_as_dict()}
    return {"kind": "answer", "route": output["route"], "args": output["args"],
            "text": output["text"]}


def nonzero(probabilities: dict) -> dict:
    return {route: p for route, p in probabilities.items() if p > 0}


@json_cache
def route_request(wording: str, text: str, *, history=(), route_threshold=None,
                  typesafe_model=None) -> dict:
    """Run one request through the agent, on the Jev model `typesafe_model` names. `history`
    holds earlier (customer, app) turns. With `route_threshold`, Pydantic AI raises
    `UnsureRoute` when the probability of Jev's pick is under it."""
    settings = (DecisionModelSettings(decision_route_threshold=route_threshold)
                if route_threshold is not None else None)
    messages = []
    for said, replied in history:
        messages += [ModelRequest(parts=[UserPromptPart(content=said)]),
                     ModelResponse(parts=[TextPart(content=replied)])]
    start = perf_counter()
    try:
        agent = build_agent(jev_model(typesafe_model))
        result = agent.run_sync(text, message_history=messages or None, model_settings=settings)
    except UnsureRoute as unsure:  # under the threshold: the app asks instead of acting
        probabilities = nonzero(unsure.probabilities)
        return {"kind": "ask", "route": max(probabilities, key=probabilities.get), "args": {},
                "route_probability": unsure.probability, "route_probabilities": probabilities,
                "seconds": round(perf_counter() - start, 2)}
    except UnfillableRoute as unfillable:  # `transfer`: Jev picked it but can't fill `amount`
        # This exception carries the probability of the pick and no others.
        return {"kind": "confirm", "route": unfillable.route, "args": {},
                "route_probability": unfillable.probability,
                "route_probabilities": {unfillable.route: unfillable.probability},
                "seconds": round(perf_counter() - start, 2)}
    record = as_record(result.output) | {"seconds": round(perf_counter() - start, 2)}
    route = result.response.provider_details["route"]
    record["route_probability"] = route["probabilities"][route["choice"]]
    record["route_probabilities"] = nonzero(route["probabilities"])
    return record


def offered(probabilities: dict) -> list[str]:
    """The routes the app offers when it asks: those at `OFFER_FLOOR` or more, likeliest
    first. Never fewer than two, if two have a nonzero probability, and never more than four."""
    ranked = sorted(probabilities, key=probabilities.get, reverse=True)
    at_floor = [route for route in ranked if probabilities[route] >= OFFER_FLOOR]
    return ranked[:max(2, min(len(at_floor), 4))]


def respond(text: str, history=()) -> dict:
    """What the app does with one customer request. `history` holds earlier (customer, app)
    turns."""
    earlier = {"history": history} if history else {}
    record = route_request(WORDING, text, typesafe_model=TYPESAFE_MODEL,
                           route_threshold=ROUTE_THRESHOLD, **earlier)
    if record["kind"] == "ask":
        record = record | {"offered": offered(record["route_probabilities"])}
    return record
```

The app turns each record into what the customer sees. When Jev is unsure, the app builds
its question from `ASK`, a dict with a short phrase per route. Jev never sees the dict, but
the question built from it goes into the history on the customer's next turn.

```python expandable theme={null}
ASK = {
    "balance": "check an account balance", "transactions": "see recent transactions",
    "spending_history": "see what you've spent", "routing": "get your routing number",
    "interest_rate": "see an account's interest rate",
    "account_blocked": "find out why an account is blocked",
    "bill_due": "see when a bill is due", "bill_balance": "see what you owe on a bill",
    "credit_limit": "see a card's credit limit", "min_payment": "see a minimum payment",
    "apr": "see a card's APR", "expiration_date": "see when a card expires",
    "card_declined": "find out why a card was declined",
    "rewards_balance": "see your reward points", "redeem_rewards": "redeem reward points",
    "international_fees": "see fees for using a card abroad",
    "replacement_card_duration": "see how long a new card takes",
    "application_status": "check a card application", "credit_score": "see your credit score",
    "improve_credit_score": "get tips to raise your credit score",
    "freeze_account": "freeze an account", "transfer": "move money", "pay_bill": "pay a bill",
    "order_checks": "order checks", "pin_change": "change a PIN", "report_fraud": "report fraud",
    "report_lost_card": "report a lost or stolen card", "damaged_card": "replace a damaged card",
    "credit_limit_change": "change a credit limit", "new_card": "apply for a new card",
}


def clarifying_question(routes: list[str]) -> str:
    named = [ASK[route] for route in routes if route != "decline"]
    if not named:
        return "What would you like to do?"
    if len(named) < len(routes) or len(named) == 1:  # `decline` was one of the routes offered
        return f"Did you want to {', '.join(named)}, or something else?"
    return f"Did you want to {', '.join(named[:-1])}{',' if len(named) > 2 else ''} or {named[-1]}?"


def app_reply(record: dict) -> str:
    args = {k: v for k, v in record["args"].items() if v is not None}
    if record["kind"] == "ask":
        return clarifying_question(record["offered"])
    if record["kind"] == "confirm" and record["route"] == "transfer" and "amount" not in args:
        return "How much would you like to move?"
    if record["kind"] == "confirm":
        return f"Confirm: {ASK[record['route']]} {args or ''}  [Confirm] [Cancel]"
    return record["text"]


def show(text: str, record: dict) -> None:
    args = {k: v for k, v in record["args"].items() if v is not None}
    print(f"> {text}")
    print(f"  {record['kind']}: {record['route']} {args or ''}  [{record['seconds']} s]")
    probs = record["route_probabilities"]
    top = sorted(probs, key=probs.get, reverse=True)[:4]
    print("  route probabilities: " + ", ".join(f"{r} {probs[r]:.2f}" for r in top))
    print("  app: " + app_reply(record).replace("\n", "\n       "))
    print()
```

## Route a clear request

```python theme={null}
show("what's the due date for my comcast bill", respond("what's the due date for my comcast bill"))
```

```
> what's the due date for my comcast bill
  answer: bill_due {'bill': 'internet'}  [0.2 s]
  route probabilities: bill_due 1.00
  app: Internet bill: due Oct 22
```

Jev picked `bill_due` and filled `bill` with `internet`. None of the customer's bills
mentions Comcast, but Comcast is an internet provider, so `internet` is the option that
fits. The output function then wrote the answer from the bill data. The probability of the
pick is 1.00, above the 0.8 threshold, so the app acted.

## Ask the customer when Jev is unsure

Some requests could fit more than one route. A request about a utility bill:

```python theme={null}
first = "i want assistance with my utility bill"
asked = respond(first)
show(first, asked)

follow_up = "pay it please"
show(follow_up, respond(follow_up, history=((first, app_reply(asked)),)))
```

```
> i want assistance with my utility bill
  ask: bill_balance   [0.22 s]
  route probabilities: bill_balance 0.62, pay_bill 0.25, bill_due 0.11, decline 0.02
  app: Did you want to see what you owe on a bill, pay a bill, or see when a bill is due?

> pay it please
  confirm: pay_bill   [0.19 s]
  route probabilities: pay_bill 1.00
  app: Confirm: pay a bill   [Confirm] [Cancel]
```

Jev's pick was `bill_balance` at 0.62, under the threshold, so Pydantic AI raised
`UnsureRoute` and nothing ran. Three routes are at 0.1 or more: `bill_balance`, `pay_bill`
at 0.25, and `bill_due` at 0.11. The app offered those three.

The app sends the customer's reply to the agent as the next turn, with the earlier turn in
`message_history`, so Jev sees what the app asked. Jev then picked `pay_bill` at 1.00, and
the run stopped at the confirm button. The customer didn't say which bill, so `bill` is
empty and the app can ask which bill before it shows the button.

## Check that low-probability picks are wrong more often

Asking only helps if Jev's low-probability picks are the ones it gets wrong. Run the 600
labeled requests, group Jev's picks into bands by probability, and check how often the
picks in each band match the label.

```python expandable theme={null}
# Run one at a time: in worker threads, `run_sync` would share one TypeSafe client across
# event loops.
RECORDS = [respond(row["text"]) for row in REQUESTS]
BANDS = [(0.0, 0.5), (0.5, 0.7), (0.7, 0.9), (0.9, 0.99), (0.99, 1.01)]


def calibration() -> list[tuple[int, float]]:
    """(picks, share that match the label) per probability band."""
    out = []
    for lo, hi in BANDS:
        picks = [(r, row) for r, row in zip(RECORDS, REQUESTS)
                 if lo <= r["route_probability"] < hi]
        out.append((len(picks), sum(r["route"] == row["label"] for r, row in picks) / len(picks)))
    return out


def style(ax, p: dict) -> None:
    ax.set_facecolor(p["surface"])
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    for side in ("left", "bottom"):
        ax.spines[side].set_color(p["axis"])
    ax.tick_params(colors=p["muted"], labelcolor=p["ink2"])
    ax.grid(axis="y", color=p["grid"], linewidth=0.8)
    ax.set_axisbelow(True)


def calibration_chart(p: dict):
    fig, ax = plt.subplots(figsize=(8, 4.2), facecolor=p["surface"])
    style(ax, p)
    labels = ["< 0.5", "0.5–0.7", "0.7–0.9", "0.9–0.99", "≥ 0.99"]
    bands = calibration()
    ax.bar(range(len(BANDS)), [share for _, share in bands], width=0.6, color=p["blue"])
    for x, (n, share) in enumerate(bands):
        ax.text(x, share + 0.02, f"{share:.0%}\nn={n}", ha="center", va="bottom",
                fontsize=9, color=p["ink2"])
    ax.set_xticks(range(len(BANDS)), labels)
    ax.set_ylim(0, 1.22)
    ax.set_yticks([0, 0.25, 0.5, 0.75, 1], ["0%", "25%", "50%", "75%", "100%"])
    ax.set_xlabel("probability of Jev's pick", color=p["ink2"])
    ax.set_ylabel("picks matching the label", color=p["ink2"])
    ax.set_title("Picks with a higher probability match the label more often",
                 color=p["ink"], loc="left", pad=12)
    fig.tight_layout()
    return fig


show_chart(calibration_chart)
```

![output](https://mintcdn.com/ts-docs/4Bw2bMmeLzpKyiId/cookbooks/pydantic_ai_banking_assistant/pydantic_ai_banking_assistant.executed.1.png?fit=max\&auto=format\&n=4Bw2bMmeLzpKyiId\&q=85\&s=d743d9d518db0523cca535c02830f431)

The share of picks that match the label rises with the probability, from 20% under 0.5 to
99% at 0.99 or more. About 80% of picks are at 0.99 or more. The bands under 0.9 hold few
picks, so their shares are rough.

We ask when the probability of the pick is under 0.8, and offer the routes at 0.1 or more.
To choose your own values, try a few on labeled requests of your own, and compare how often
the app asks with how often it acts on, or offers, the label's route.

## Count how the 600 requests end

A request ends correctly if the app acts on the label's route, or asks and offers it.
Compare that with acting on Jev's pick every time:

```python expandable theme={null}
def ends_correctly(record: dict, label: str) -> bool:
    """The app acted on the label's route, or asked and offered it."""
    if record["kind"] == "ask":
        return label in record["offered"]
    return record["route"] == label


pairs = list(zip(RECORDS, REQUESTS))
asked_pairs = [(r, row) for r, row in pairs if r["kind"] == "ask"]
acted_pairs = [(r, row) for r, row in pairs if r["kind"] != "ask"]


def share(hits, group) -> float:
    return sum(hits) / len(group)


ended = share((ends_correctly(r, row["label"]) for r, row in pairs), pairs)
acted_match = share((r["route"] == row["label"] for r, row in acted_pairs), acted_pairs)
asked_offered = share((row["label"] in r["offered"] for r, row in asked_pairs), asked_pairs)
always_act = share((r["route"] == row["label"] for r, row in pairs), pairs)
routes_per_ask = sum(len(r["offered"]) for r, _ in asked_pairs) / len(asked_pairs)
display(Markdown("\n".join([
    "| | ends correctly | acted without asking (% matching the label) | asked the customer "
    "(% offering the label's route) | routes offered per ask |",
    "|---|---|---|---|---|",
    f"| The app: asks when Jev's pick is under {ROUTE_THRESHOLD:g} | {ended:.1%} | "
    f"{len(acted_pairs) / len(pairs):.0%} ({acted_match:.1%}) | "
    f"{len(asked_pairs) / len(pairs):.0%} ({asked_offered:.0%}) | {routes_per_ask:.1f} |",
    f"| Acting on Jev's pick every time | {always_act:.1%} | 100% ({always_act:.1%}) | – | – |",
])))

pick_match = sum(r["route"] == row["label"] for r, row in asked_pairs)
offered_match = sum(row["label"] in r["offered"] for r, row in asked_pairs)
two_match = sum(
    row["label"] in sorted(r["route_probabilities"], key=r["route_probabilities"].get)[-2:]
    for r, row in asked_pairs
)
print(f"The app asked on {len(asked_pairs)} of {len(pairs)} requests. On those {len(asked_pairs)}:")
print(f"  Jev's pick matches the label on {pick_match}")
print(f"  the routes offered include the label's route on {offered_match}")
print(f"  Jev's two likeliest routes include it on {two_match}")
seconds = sorted(r["seconds"] for r in RECORDS)
print(f"Time per request: median {statistics.median(seconds):.2f} s, "
      f"90% within {seconds[int(0.9 * (len(seconds) - 1))]:.2f} s")
```

```
The app asked on 35 of 600 requests. On those 35:
  Jev's pick matches the label on 20
  the routes offered include the label's route on 34
  Jev's two likeliest routes include it on 31
Time per request: median 0.16 s, 90% within 0.24 s
```

| | ends correctly | acted without asking (% matching the label) | asked the customer (% offering the label's route) | routes offered per ask |
| - | - | - | - | - |
| The app: asks when Jev's pick is under 0.8 | 98.3% | 94% (98.4%) | 6% (97%) | 2.3 |
| Acting on Jev's pick every time | 96.0% | 100% (96.0%) | – | – |

The app ended 98.3% of the requests correctly, against 96.0% for acting on Jev's pick every
time. It acted without asking on 94% of the requests, and Jev's pick matched the label on
98.4% of those. A request took a median of 0.16 seconds.

The app asked on 35 requests. Jev's pick matched the label on 20 of them, 57%, against
98.4% of the rest. The routes the app offered included the label's route on 34 of the 35,
at 2.3 routes per ask. Offering only Jev's two likeliest routes would have included it on
31\.

## Confirm actions before they run

When Jev picks an action, the run stops before Pydantic AI calls the tool:

```python theme={null}
show("i lost my card and need to report it", respond("i lost my card and need to report it"))
```

```
> i lost my card and need to report it
  confirm: report_lost_card   [0.25 s]
  route probabilities: report_lost_card 1.00
  app: Confirm: report a lost or stolen card   [Confirm] [Cancel]
```

The run returned `DeferredToolRequests` instead of an answer. Jev picked
`report_lost_card`, and `requires_approval=True` stopped the tool before it ran. The
customer has two cards and didn't say which, so `card` is `None`. Ask for the card before
approving the call, because approval doesn't check that the customer gave enough
information.

To run the tool once the customer confirms, keep the `AgentRunResult` and resume with
`agent.run_sync(message_history=result.all_messages(), deferred_tool_results=results)`.
Here `results` is a `DeferredToolResults` whose `approvals` maps each pending tool call ID
to `True`, or to `ToolApproved(override_args=...)` for corrected arguments.

## Read a transfer's amount with an LLM

Jev answers by choosing from options, so it can't fill an argument that could be any
number. When Jev picks `transfer`, Pydantic AI raises `UnfillableRoute` before it fills any
argument:

```python theme={null}
show("i need $360 transfered from savings to checking account",
     respond("i need $360 transfered from savings to checking account"))
```

```
> i need $360 transfered from savings to checking account
  confirm: transfer   [0.1 s]
  route probabilities: transfer 1.00
  app: How much would you like to move?
```

The customer gave the accounts and the amount, and the app has none of them, so it has to
ask. To have an LLM read them instead, put the LLM behind Jev in a `FallbackModel`. With
`fallback_on=UnfillableRoute`, Pydantic AI calls gpt-5.5 only when Jev picks a route with
an argument Jev can't fill:

```python theme={null}
@json_cache
def route_with_llm(wording: str, text: str, *, typesafe_model: str, llm: str) -> dict:
    """Run one request through an agent whose model falls back from Jev to an LLM."""
    model = FallbackModel(jev_model(typesafe_model), llm_model(llm), fallback_on=UnfillableRoute)
    start = perf_counter()
    result = build_agent(model).run_sync(text)
    answered_by = ["Jev" if m.model_name.startswith("jev") else llm
                   for m in result.new_messages() if isinstance(m, ModelResponse)]
    return as_record(result.output) | {"answered_by": answered_by,
                                       "seconds": round(perf_counter() - start, 2)}


for text in ["i need $360 transfered from savings to checking account",
             "i need to make a transfer of my money",
             "how much money can i transfer today"]:
    record = route_with_llm(WORDING, text, typesafe_model=TYPESAFE_MODEL, llm=LLM_MODEL)
    args = {k: v for k, v in record["args"].items() if v is not None}
    print(f"> {text}")
    print(f"  {record['kind']}: {record['route']} {args or ''}  "
          f"[{' + '.join(record['answered_by'])}, {record['seconds']} s]")
    print("  app: " + app_reply(record).replace("\n", "\n       "))
    print()
```

```
> i need $360 transfered from savings to checking account
  confirm: transfer {'from_account': 'savings', 'to_account': 'checking', 'amount': 360}  [gpt-5.5, 2.24 s]
  app: Confirm: move money {'from_account': 'savings', 'to_account': 'checking', 'amount': 360}  [Confirm] [Cancel]

> i need to make a transfer of my money
  confirm: transfer   [gpt-5.5, 1.98 s]
  app: How much would you like to move?

> how much money can i transfer today
  answer: balance   [gpt-5.5, 3.3 s]
  app: Everyday checking account, ending 4821: $2,310.55
       Savings account, ending 9930: $12,840.00
```

With gpt-5.5 behind Jev, the first request ends at a confirm button with the accounts and
the amount filled in: gpt-5.5 read 360, from savings to checking. The second names no
amount, so gpt-5.5 left `amount` empty and the app asks for it. Each of the three took two
to three seconds. A request that never reaches gpt-5.5 takes about 0.2.

`FallbackModel` hands gpt-5.5 the customer's request and every route, so gpt-5.5 can
overrule Jev's pick. Pydantic AI called gpt-5.5 for the third request, so Jev had picked
`transfer`. gpt-5.5 picked `balance`.

To send the requests Jev is unsure about to gpt-5.5 too, instead of asking the customer,
set `fallback_on=DecisionHandOff`, which covers both `UnfillableRoute` and `UnsureRoute`.

## Open the request in the playground

To see what Pydantic AI sends Jev, give the agent a model that captures the call instead of
sending it. Here we capture the route question for the Comcast request, with all 31 routes
and their descriptions, and turn it into a playground link.

```python theme={null}
class Captured(Exception):
    pass


class CaptureRequest(TypeSafeModel):
    """Pydantic AI's `TypeSafeModel`, except it captures the call instead of sending it."""

    async def decide(self, request, model_settings):
        raise Captured(request)


try:
    capture = CaptureRequest(TYPESAFE_MODEL, provider=TypeSafeProvider(api_key="cache-only"))
    build_agent(capture).run_sync("what's the due date for my comcast bill")
except Captured as captured:
    request = captured.args[0]


def as_json(question) -> dict:
    return {k: v for k, v in asdict(question).items() if v is not None}


questions = {name: as_json(q) for name, q in request.questions.items()}
print(f"questions in the first call: {', '.join(questions)}; "
      f"options in 'route': {len(questions['route']['criteria'])}")
playground_link = make_playground_link(request.state, questions)
display(Markdown(f"🔗 [Open in the TypeSafe playground]({playground_link})"))
```

```
questions in the first call: route; options in 'route': 31
```

[Open in the TypeSafe playground →](https://console.typesafe.ai/playground#share/N4IgJg9gxgrgtgUwHYBcAqCAeKQC4AEIA7gBYCGKA5AM74okL5gyNgWMBmEATvnAJ74oEOFDLUU+AEYBLADZyQAGkIAHbiNUpqGbHkLAAOiA0wUCYwSMgo3GebtlL+a1LJyySKBf3GMCugYhGAkRBF4SCCI+GCgSPggkBEEZWhkkQIQZXjckAGt8MihhGFQAOmMVYxRuT2oilBlE6mdjABlUyXpGbgRvVHx0sBkANxlmdzpapHqoRub8RMzg0MRuGkLiiFKUCuV8Y2pVZGGkAHMAfRJOnn5WkABleDgyO2pGSOi4WPjulZQwhFxPgjsgUCoePhSBRMoJQQNEhCRuFCvhjnYIGA9lUTNtGud7gBxUaMP65PIbUz4s74JDwKQori8P6wVbhDZFErlSoHEDpBwICQXWrme7+OTLVkAtbLfnhQWSEWkhjZaSeAqc7YDBCvGbY3manYXKRyaB5BBge4AUUwqg86ShJEELJC0vZtENA1S0lNUHNYBUvv9i14HA0AC9kCpPGB8J86BB8KUTWbBrsecZZAoLswfAQ-AgAi62bxSMhUVmJd7c-rM-I5Mb3J5vGLCxLi26IlEYnFYYsiIwlmRpPXazZesMUBc5DI4PZW0WglLAZKJ-Z8DO5+CQ6uLeuJPXCiMyPIyCaEBCMt1VbY95IxNwsRmQHOkBdVGR+IhUAv20vXSufzUC8CgKmin7fl0DCCGIGQvOaiwZMOt6TkIryxpCw6VmOZDqL+koATKfwAIIAAoAEoqH8cq9BI+BKkI5DcGcFqIZkN5rve6FjlgqjZBQTRvmwoq+CA4oESWjrltevAPrGvHZIKY5yTmfQzkklqiTadonhkpDOv+JYbHJULAmAanpKxMLDqoMDcHE4gIGOvREOh1CNh4Xh5ry4kdiu8YvEggguehaIQPytDdII5DIs5FoIAgcDCggrmPi0Wm2vaGTxn5MqwfR8WJTu8KxjJBWpbGqjhag1BjjRSACYk7gXBwCXpfmYlthJnaOjCrWCuxsmhQ5zEDUyaJ2Q57welIGhkBhvAOhA3SyXZvReDISnPr0OneJBFwqcwIqCfhuUovGprnKiSTRJCO0eHtYJoY+dBkOakWJq8dixc+uF2jIYjzG+EgUCEp2GT1Za9INQicc9sZ-TOgOCSCKAxrVz4ofYFzUMIvTg4wy5ESqq3cOt95w7jPBOc+s7qBAyIHZxON495xjEsi3UrvNYzeGxtSpOkNJlVjkhU70Y7mVA6lsyAAAiFlJGFM7mHI-BlPgaBBL0ACOLB0d6SDLYUUh4lzawbHAiTJCo5KbFy2gqHJtCQpWtX4DaZBwHagoEDUZDInIKjUJEqh8ecVFBAOFAMNwwcge27h5GOYYJZGFyeig9wAGK9Agkbm+6ar5PbWpi4mRv0ELaEZAy4HjPgYYiGmY7+zMrXcPcACyDOMFbSSCAyKADtJEOAhyWw7Bj+zGB+-DGvW9ykZ+iGDhwhfrLQbu0lEY48OZ3AHQwfrtbyADyj4osON3SBAEAFBA68fuijF9HktDjWdm+lzsY7h0fngWL3AAMLkHOMqRgpEACSAA5NiX9jKhUwpPbkM8TAICqtwKcYYyAwE0h1ciGCeCSGHDgvBMA5BPUhKUXowgzhIFSKxEaLEIS8GoCEY4cxWJkIDPAseFsPQoPTGgnaxDpwQCFHJe4hDMFQUJoRIuJlTR0UhKEShSEkCxhTH6Fuz42AvBYmAA66FpEYIeowZCoV6AwmrF7MghjbYaHNBkSERsNyJBYqWHg780ROmoADdwatlLM03NjBy4D7jEWoAUcaw5rhnFjjuU0A5ZJw1CZIJYCDaCi3hmOG6xjHyRLDmrRumFaQpVhneXJxgAC+OJ0gSG4LEIGp9rB6wVCdUSAB1a4vZH6ZHeEwCAA0q7ZMCaU7gAB+Z8bg-RnFMJo+4ABNbYhRoZ-HEP4kGXokJonCNQJqEoODpGbBYsOTtEhJC4aVRMWTi4aiEdQJ2cNnaFE0SOBQHpJCkABgwZEOR1QenecIb2nhNqRWgkmd4GsAAG5hsAwsGLQaEcj-grgAFauhBCeMAABufAMLrihG4PwRFkQ5BgAhYwHU3AZwohQHZGYKgZDr08OrWpOIUD8GOPcOI4UWwgBqTU-YIBcIyAAGr7MEvoEAIwACMgqgA)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.