> ## 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.

# Pydantic AI quickstart

> Build a Pydantic AI agent that uses Jev as its model. Jev answers each field of the agent's output as a question, with a probability you can act on in code.

Here we build a small [Pydantic AI](https://pydantic.dev/pydantic-ai) agent whose model is
Jev. Many of an agent's steps are decisions: which tool to call, which queue a message goes
to, whether a customer is reporting fraud. An LLM can make those decisions, but it answers
in text and doesn't say how sure it is.

Pydantic AI has a model class for Jev,
[`TypeSafeModel`](https://pydantic.dev/docs/ai/models/typesafe/). You give the agent a
Pydantic model as its output type, and each field becomes one question for Jev. Jev answers
all the questions in one request. `TypeSafeModel` turns each answer into a Python value of
the field's type, and also returns Jev's probabilities and confidence.

The agent triages messages sent to a bank's support team. It asks two
questions about every message: what the message is about, and whether the customer reports
fraud. You end up with a `Triage` output type and a `triage()` function, which returns the
agent's output for one message with Jev's probabilities and confidence. You then decide in
code whether the `fraud` probability is high enough to send the message to the fraud team.

## Setup

> [card] [Run in Colab](https://colab.research.google.com/github/typesafe-ai/typesafe-public-examples/blob/pub-20261203-d36583/integrations/pydantic-ai/quickstart/pydantic_ai_quickstart.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/quickstart/pydantic_ai_quickstart.py)
>
> This page as one .py file, to run locally.

> [card] [Open in playground](https://console.typesafe.ai/playground#share/N4IgJg9gxgrgtgUwHYBcAqCAeKQC4AEIaAFggE4IDkAzvgIb4AsArAHQCc7+ADnQJ6JU+FBHwBBAMIBZAKL4AymgBKMsVICSAOQDi+CEnxw++aijooEglMOLn86-JCSVrFKBADmSAJbUErfAk6Az4IGHwoUigAa3wAd1trbyTqAH4QABpCbjIIOG4UagxsPEJgAB0QEW5vKEqCCpAoMmTybzp6-EaoOjIwak7KgBEEACNk+iQwCIowCZ6+6gIAGwhTLNMIZeQs0dWYhDAssAQoZe8kQ6yIMnxLuNZKrMreAWRCwaIyYOoAM3JqMdvG5rCdxoUssFpq8rLQLnpbmEUI9MvhKnQoO4YKhPgAZTweC4efAXLLcAH6OjLRwIMzeZaAkxmCywyFTeiYsJCPwoFBE6gogC+zxAF1MZBgUD5+gGpUav28CGWYE+1VqTzRIAAjjAEKZvPpPgB1RIk2goUiGPXUOgeBD0UZI1IayoeCBUz5oFq2+0MRDUG12kzvYSiBijYLRGgmGDcbg3awWOhwIUilB8cmfSIQWoISrCzW-b4wFVyypilASqUGpCyhqVBVK0sEBvF0sinV66VIT5DCB6mz22CbRC3CjxsiJ03UPIIfT2pV+fAwPzTC0IYEcrFCG4RXpgZ2o13u5ae71Bv3Wn3BoQiej4CNIKO0aixieJhDJ1Oa9OZ0qVJAwlPEBBUFVEQDoGoADUARrUoQAANwARhAoA)
>
> 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]==2.71.0' nest-asyncio2 ipython 'cooksafe>=0.3.0,<0.4.0'
```

With uv, `uv run pydantic_ai_quickstart.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`; in Colab, add it in the Secrets panel.

The numbers below came from `jev-1.14.0` on 2026-11-25.

```python expandable theme={null}
import json
import os
import urllib.request
from dataclasses import asdict
from pathlib import Path

from cooksafe import JsonCache
import nest_asyncio2
from pydantic import BaseModel, Field
import pydantic_ai
from pydantic_ai import Agent, Choices
from pydantic_ai.models.typesafe import TypeSafeModel

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()

# The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here.
KEYS = ["TYPESAFE_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 key. Pydantic AI still asks for one when it builds the
# agent, so a placeholder stands in when none is set.
os.environ.setdefault("TYPESAFE_API_KEY", "cache-only")

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/quickstart"
)


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():
        urllib.request.urlretrieve(f"{EXAMPLES}/{name}", path)
    return path


CACHE = HERE / "pydantic_ai_quickstart_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)
```

## Write the questions as a type

Pydantic AI builds the Jev request from your types and from the message you pass to the
agent:

| In Pydantic AI | In the Jev request |
| - | - |
| the message passed to the agent | the state |
| each field | one question, whose type comes from the field type |
| the field's name | `instructions.field` |
| the field's `description` | `instructions.question` |
| the class docstring | `instructions.goal`, copied into every question |
| each option's description in `Choices` (or `BoolCriteria` on a `bool`) | the question's criteria |

Pydantic AI sends each question's instructions as a JSON object (see [structured
instructions](https://docs.typesafe.ai/primitives/advanced.md#structured-instructions)). The keys `field`, `question`,
and `goal` are names Pydantic AI chose. They aren't part of the TypeSafe API.

The field type sets the question type:

| Field type | Question type | Value the field gets |
| - | - | - |
| `bool` | Noul | `True` or `False`, from the probability of yes |
| `float` from 0 to 1: `Field(ge=0, le=1)` | Noul | the probability of yes |
| a `Choices` set, or an `Enum` or `Literal` of strings | Choice | the likeliest option |
| `IntEnum` of consecutive whole numbers from 0, with a description for each level | Score | the score rounded to the nearest level |

The state holds the text the questions are about, plus any facts that help answer them.
Pydantic AI builds it from the message you pass to the agent. Put any facts the questions
need, such as a refund policy, in the message. Keep them out of the class docstring and out
of the `instructions` argument to `Agent`, because both are copied into every question.
[State](https://docs.typesafe.ai/concepts/state.md#separate-content-from-questions) has more on keeping content apart
from questions.

```python theme={null}
Topic = Choices(
    {
        "cards": "Debit and credit cards: lost, stolen, blocked, declined, or new.",
        "payments": "Transfers, direct debits, and payments in or out.",
        "account": "Logging in, personal details, statements, and account settings.",
    }
)


class Triage(BaseModel):
    """Triage a message sent to a bank's support team."""

    topic: Topic = Field(description="What is the message about?")
    fraud: float = Field(
        ge=0,
        le=1,
        description="Does the customer report that someone else used their account or card?",
    )
```

Here `topic` is the Choice question and `fraud` is the Noul question, whose value is Jev's
probability of yes.

A `bool` field would also be a Noul question, but Pydantic AI would turn the probability
into `True` or `False` at a threshold of 0.5. You can change that threshold with the
`decision_boolean_threshold` model setting.

A Score question needs an `IntEnum` that mixes in Pydantic AI's `UseEnumMemberDocstrings`,
with a docstring under each level. Version 2.71.0 reads those docstrings from the source
file. A notebook has no source file, so in a notebook the question goes out without the
level descriptions. Put that enum in a `.py` file and import it.

## Run the agent

The `typesafe:` prefix on the model name gives the agent a `TypeSafeModel`, which sends the
request to Jev. `TypeSafeModel` reads your key from `TYPESAFE_API_KEY`. With no key set, it
gets the placeholder from Setup, which is enough to replay the saved answers. Each message
goes to the agent as the user prompt.

To run the agent on one message, call `triage()`. It returns a dictionary with the agent's
output and the response's `provider_details`, which hold Jev's `confidence` and
`probabilities`.

`jev_request()` builds the request Pydantic AI would send Jev, without calling the API. It
runs the agent with `CaptureRequest`, a model class that records the request instead of
sending it.

```python expandable theme={null}
TYPESAFE_MODEL = "jev-1.14.0"  # the page's model; "jev-latest" runs the newest, live
agent = Agent(f"typesafe:{TYPESAFE_MODEL}", output_type=Triage)


class Captured(Exception):
    pass


class CaptureRequest(TypeSafeModel):
    """Pydantic AI's model class for Jev, except it records the request instead of sending it."""

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


def jev_request(message: str):
    """The request Pydantic AI would send Jev for this message, built without calling the API."""
    try:
        agent.run_sync(message, model=CaptureRequest(TYPESAFE_MODEL))
    except Captured as captured:
        return captured.args[0]


def as_json(questions) -> dict:
    return {
        name: {key: value for key, value in asdict(question).items() if value is not None}
        for name, question in questions.items()
    }


@json_cache
def _triage(message: str, questions: str, fields: str, model: str) -> dict:
    result = agent.run_sync(message, model=f"typesafe:{model}")
    return {
        "output": result.output.model_dump(mode="json"),
        "details": result.response.provider_details,
    }


def triage(message: str) -> dict:
    """Run the agent on one message; return its output and Jev's details as plain JSON."""
    questions = json.dumps(as_json(jev_request(message).questions))
    fields = json.dumps({name: repr(field) for name, field in Triage.model_fields.items()})
    return _triage(message, questions, fields, model=TYPESAFE_MODEL)


message = (
    "My card got declined at the supermarket just now, "
    "but there's plenty of money in my account."
)
answer = triage(message)
print(Triage.model_validate(answer["output"]))
print(json.dumps(answer["details"], indent=2))
```

```
topic='cards' fraud=0.04
{
  "confidence": {
    "topic": 1.0
  },
  "probabilities": {
    "topic": {
      "cards": 1.0,
      "payments": 0.0,
      "account": 0.0
    }
  },
  "scores": {}
}
```

`triage()` returns plain JSON, so we validate its output into a `Triage` object to read
each field as a Python value. In `provider_details`:

* The `confidence` key holds a confidence score from 0 to 1 for each Choice question. A
  Noul question has no confidence score. Its probability of yes is the `fraud` value.
* The `probabilities` key holds Jev's probability for every option of each Choice
  question.
* The `scores` key holds the answer to each Score question, so it is empty here.

## Act on the probability in code

Jev's answer for `fraud` is a probability, so you decide in code how high it has to be
before a message goes to the fraud team.

```python theme={null}
message = (
    "There's a 45.99 payment to ACME STREAMING on my statement that I don't recognise. "
    "Can you check what it is?"
)
answer = triage(message)
print(Triage.model_validate(answer["output"]))
```

```
topic='payments' fraud=0.22
```

The `fraud` value is 0.22. That leans no without ruling fraud out. The customer doesn't
recognize the payment, which could be fraud or a subscription they forgot about.

A `bool` field would give you only `True` or `False`, decided by the same threshold for
every `bool` field. With the probability, you set a threshold for this one decision, based
on what a wrong answer costs. Missing fraud costs the bank more than checking a payment
that turns out to be fine, so we send any message with a `fraud` value of 0.3 or more to
the fraud team:

```python theme={null}
FRAUD_THRESHOLD = 0.3

triaged = Triage.model_validate(answer["output"])
if triaged.fraud >= FRAUD_THRESHOLD:
    print("Send to the fraud team")
else:
    print(f"Send to the {triaged.topic} queue")
```

```
Send to the payments queue
```

At 0.22, this message goes to the payments queue. A bank more worried about missing fraud
could set the threshold to 0.15, which would send this message to the fraud team.

Raise the threshold when a wrong yes costs more than a wrong no. Lower it when a wrong no
costs more. You can also have a person check messages whose probability is close to the
threshold. To choose a threshold, try a few on a set of your own messages, each labeled
with the answer you expect.

## Open the request in the playground

To see the request Pydantic AI sends Jev for the last message, call `jev_request()`. Then
pass that request to `make_playground_link()` from `cooksafe` to get a TypeSafe playground
link. In the playground, you can run the request or change its questions.

```python theme={null}
from cooksafe import make_playground_link
from IPython.display import Markdown, display

request = jev_request(message)
questions = as_json(request.questions)
print(json.dumps({"state": request.state, "questions": questions}, indent=2))
link = make_playground_link(request.state, questions)
display(Markdown(f"🔗 [Open in the TypeSafe playground]({link})"))
```

```
{
  "state": "There's a 45.99 payment to ACME STREAMING on my statement that I don't recognise. Can you check what it is?",
  "questions": {
    "topic": {
      "criteria": {
        "cards": "Debit and credit cards: lost, stolen, blocked, declined, or new.",
        "payments": "Transfers, direct debits, and payments in or out.",
        "account": "Logging in, personal details, statements, and account settings."
      },
      "instructions": {
        "field": "topic",
        "question": "What is the message about?",
        "goal": "Triage a message sent to a bank's support team."
      },
      "type": "choice"
    },
    "fraud": {
      "instructions": {
        "field": "fraud",
        "question": "Does the customer report that someone else used their account or card?",
        "goal": "Triage a message sent to a bank's support team."
      },
      "type": "noul"
    }
  }
}
```

[Open in the TypeSafe playground →](https://console.typesafe.ai/playground#share/N4IgJg9gxgrgtgUwHYBcAqCAeKQC4AEIaAFggE4IDkAzvgIb4AsArAHQCc7+ADnQJ6JU+FBHwBBAMIBZAKL4AymgBKMsVICSAOQDi+CEnxw++aijooEglMOLn86-JCSVrFKBADmSAJbUErfAk6Az4IGHwoUigAa3wAd1trbyTqAH4QABpCbjIIOG4UagxsPEJgAB0QEW5vKEqCCpAoMmTybzp6-EaoOjIwak7KgBEEACNk+iQwCIowCZ6+6gIAGwhTLNMIZeQs0dWYhDAssAQoZe8kQ6yIMnxLuNZKrMreAWRCwaIyYOoAM3JqMdvG5rCdxoUssFpq8rLQLnpbmEUI9MvhKnQoO4YKhPgAZTweC4efAXLLcAH6OjLRwIMzeZaAkxmCywyFTeiYsJCPwoFBE6gogC+zxAF1MZBgUD5+gGpUav28CGWYE+1VqTzRIAAjjAEKZvPpPgB1RIk2goUiGPXUOgeBD0UZI1IayoeCBUz5oFq2+0MRDUG12kzvYSiBijYLRGgmGDcbg3awWOhwIUilB8cmfSIQWoISrCzW-b4wFVyypilASqUGpCyhqVBVK0sEBvF0sinV66VIT5DCB6mz22CbRC3CjxsiJ03UPIIfT2pV+fAwPzTC0IYEcrFCG4RXpgZ2o13u5ae71Bv3Wn3BoQiej4CNIKO0aixieJhDJ1Oa9OZ0qVJAwlPEBBUFVEQDoGoADUARrUoQAANwARhAoA)

## Next steps

* [Banking assistant](https://docs.typesafe.ai/cookbooks/pydantic_ai_banking_assistant.md): build a larger agent
  in which Jev picks one of 30 routes, asks the customer a follow-up question when it's
  unsure, and passes money transfers to an LLM.
* The [Pydantic AI TypeSafe docs](https://pydantic.dev/docs/ai/models/typesafe/) cover
  the provider, the model settings, and `FallbackModel`, which switches to another model
  on API errors by default.
* [Primitives](https://docs.typesafe.ai/primitives) and [confidence](https://docs.typesafe.ai/confidence.md) explain Noul, Choice, and
  Score, and how confidence is calculated.


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