# Tutorial: build and test a typed support agent with Pydantic AI 2.71, step by step

This hands-on tutorial builds a small customer-support agent with Pydantic AI 2.71 and tests it completely offline. You will inject dependencies, write tools that correct the model, return a validated Pydantic object, cap runaway loops and write pytest tests that fail if anything tries to call a real model.

Many agent bugs are not model bugs. A tool receives an argument it cannot handle, the final answer is missing a field, a loop never ends, or one customer sees another customer's data. These are ordinary software defects, and they can be caught with ordinary unit tests, if the framework lets you swap the model for something deterministic.

Pydantic AI is built around that idea. Agents are typed: dependencies, tool arguments and outputs are Pydantic models or type-annotated Python, and the library ships two test models, `TestModel` and `FunctionModel`, plus a switch that blocks real model calls during tests. This tutorial builds a typed order-support agent in six steps and tests it without a network connection or an API key. Every command and output below was run against `pydantic-ai-slim` 2.71.0. If you are new to agents, read [the agent loop step by step](/articles/agent-loop-step-by-step-trace) first; the loop described there is the one Pydantic AI runs.

## What happened

### Pydantic AI ships four minor releases in eight days (12 to 19 November 2026)

Pydantic AI 2.68.0 was published on 12 November 2026, followed by 2.69.0 on 17 November, 2.70.0 later the same day (UTC) and 2.71.0 on 19 November. This tutorial pins 2.71.0. At this pace, small API changes do happen; one appears in this tutorial, where `result.usage` is now a property and calling it as a method raises a `PydanticAIDeprecationWarning`.

### The testing guide recommends three habits

The Pydantic AI testing documentation recommends three practices that this tutorial follows: use `TestModel` or `FunctionModel` instead of a real model, use `Agent.override` to replace the model inside application code, and set `ALLOW_MODEL_REQUESTS = False` globally so that tests cannot call a real model by accident. It also states plainly that `TestModel` "is not magic": it generates data from the tool schemas with procedural code, and for anything more specific you should use `FunctionModel`.

## Step 1: install and define the agent

Install the slim package, which has no provider dependencies, and pytest:

```bash
pip install "pydantic-ai-slim==2.71.0" pytest
export PYDANTIC_AI_NO_BANNER=1        # hides the start-up banner in 2.71
```

The agent has three typed parts: `Deps` (what tools need at run time), `Reply` (what the agent must return) and the tools.

```python
# support_agent.py
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext, ModelRetry

@dataclass
class Deps:                               # everything the tools need, injected per run
    orders: dict[str, dict]
    customer_id: str

class Reply(BaseModel):                   # the typed result the agent must return
    order_id: str
    status: str
    refund_eligible: bool
    message: str = Field(description="One short sentence for the customer")

agent = Agent(
    None,                                 # model chosen at run time, or set e.g. "provider:model-id"
    deps_type=Deps,
    output_type=Reply,
    instructions="You answer order questions. Always look the order up before answering.",
    retries=2,
)

@agent.tool
def get_order(ctx: RunContext[Deps], order_id: str) -> dict:
    """Look up one of the current customer's orders."""
    order = ctx.deps.orders.get(order_id)
    if order is None or order["customer_id"] != ctx.deps.customer_id:
        raise ModelRetry(f"Order {order_id} not found for this customer. Ask for the order id or check digits.")
    return {"status": order["status"], "days_since_delivery": order.get("days_since_delivery")}

@agent.tool_plain
def refund_window_days() -> int:
    """Number of days after delivery in which refunds are allowed."""
    return 30

DEPS = Deps(orders={"1042": {"customer_id": "c7", "status": "delivered", "days_since_delivery": 3},
                    "2077": {"customer_id": "c9", "status": "in transit"}}, customer_id="c7")
```

What each piece does:

- **`deps_type=Deps`** declares a dependency object. Each run receives a concrete `Deps`, and tools read it through `ctx.deps`. This is how you pass a database connection or the current user without global variables, and it makes tests easy: pass fake data.
- **`output_type=Reply`** makes the agent return a validated `Reply` object, not free text. Under the hood Pydantic AI offers the model an output tool (named `final_result`), and the arguments must validate against the schema. See [structured outputs](/tools/structured-outputs).
- **`@agent.tool`** registers a tool that receives the run context. Its docstring becomes the tool description and its type hints become the argument schema, which is [function calling](/tools/function-calling) generated from Python.
- **`@agent.tool_plain`** registers a tool that needs no context.
- **`ModelRetry`** is the key safety feature. Raising it sends the message back to the model as feedback so it can try again, up to `retries` times. Note that the ownership check is in code: a customer can never read another customer's order, whatever the model asks for.

## Step 2: understand why TestModel needs care

`TestModel` by default calls every tool with arguments generated from the schema, then returns output that fits the output type. For `get_order`, it generated `order_id="a"`. The tool rejected it with `ModelRetry`, `TestModel` tried the same argument again, and the run failed with `UnexpectedModelBehavior: Tool 'get_order' exceeded max retries count of 2`.

That is not a bug in either side. It shows that `TestModel` exercises wiring and schemas, not behaviour. Tools that validate their input will reject its dummy values. The fix is to tell it which tools to call and what output to return.

## Step 3: a smoke test with TestModel

```python
# step_testmodel.py
from pydantic_ai.models.test import TestModel
from support_agent import agent, DEPS

m = TestModel(call_tools=["refund_window_days"],          # only call tools that accept any input
              custom_output_args={"order_id": "1042", "status": "delivered", "refund_eligible": True,
                                  "message": "Your order was delivered and can be refunded."})
result = agent.run_sync("Where is my order 1042?", deps=DEPS, model=m)
print(repr(result.output))
params = m.last_model_request_parameters
print("tools offered:", [t.name for t in params.function_tools], "| output tool:", params.output_tools[0].name)
print("usage:", result.usage)
```

```text
Reply(order_id='1042', status='delivered', refund_eligible=True, message='Your order was delivered and can be refunded.')
tools offered: ['get_order', 'refund_window_days'] | output tool: final_result
usage: RunUsage(input_tokens=111, output_tokens=22, requests=2, tool_calls=1)
```

This confirms three things in milliseconds: the output validates as a `Reply`, both tools are registered and offered to the model, and the structured output goes through a tool called `final_result`. `last_model_request_parameters` is a handy assertion target: if someone renames or removes a tool, a test on it fails. The token counts here are estimates produced by the test model, not real usage.

## Step 4: script exact behaviour with FunctionModel

`FunctionModel` wraps a Python function that receives the message history and returns the next model response. That lets you script a precise scenario. Here the "model" first makes a typo (the letter O instead of a zero), reads the retry hint, corrects the order id, and finally returns the typed output.

```python
# scripted_model.py
from pydantic_ai.messages import ModelResponse, ToolCallPart, ToolReturnPart
from pydantic_ai.models.function import AgentInfo

def scripted(messages, info: AgentInfo) -> ModelResponse:
    returns = [p for m in messages if m.kind == "request" for p in m.parts if isinstance(p, ToolReturnPart)]
    if not returns:                                    # 1st call: a typo, letter O instead of zero
        return ModelResponse(parts=[ToolCallPart("get_order", {"order_id": "1O42"})])
    if "not found" in str(returns[-1].content):        # 2nd call: read the retry hint and fix the id
        return ModelResponse(parts=[ToolCallPart("get_order", {"order_id": "1042"})])
    order = returns[-1].content                        # 3rd call: produce the typed output
    return ModelResponse(parts=[ToolCallPart(info.output_tools[0].name, {
        "order_id": "1042", "status": order["status"], "refund_eligible": order["days_since_delivery"] <= 30,
        "message": f"Order 1042 is {order['status']} and still within the refund window."})])
```

```python
# step_functionmodel.py
from pydantic_ai import capture_run_messages
from pydantic_ai.models.function import FunctionModel
from scripted_model import scripted
from support_agent import agent, DEPS

with capture_run_messages() as messages:
    result = agent.run_sync("Where is my order 1O42?", deps=DEPS, model=FunctionModel(scripted))
for i, msg in enumerate(messages):
    for p in msg.parts:
        detail = getattr(p, "args", None) or str(getattr(p, "content", ""))[:70]
        print(f"{i} {msg.kind:8} {type(p).__name__:15} {getattr(p, 'tool_name', '') or '':13} {detail}")
print(result.output)
print("requests:", result.usage.requests)
```

```text
0 request  UserPromptPart                Where is my order 1O42?
1 response ToolCallPart    get_order     {'order_id': '1O42'}
2 request  ToolReturnPart  get_order     Order 1O42 not found for this customer. Ask for the order id or check
3 response ToolCallPart    get_order     {'order_id': '1042'}
4 request  ToolReturnPart  get_order     {'status': 'delivered', 'days_since_delivery': 3}
5 response ToolCallPart    final_result  {'order_id': '1042', 'status': 'delivered', 'refund_eligible': True, 'message': 'Order 1042 is delivered and still within the refund window.'}
6 request  ToolReturnPart  final_result  Final result processed.
order_id='1042' status='delivered' refund_eligible=True message='Order 1042 is delivered and still within the refund window.'
requests: 3
```

Notice what the transcript does not contain: no prose from the model before the structured output, and no extra confirmation turn. With a typed output, the run ends as soon as `final_result` validates, which keeps request counts low. If the arguments had failed validation, for example a missing `message` field, Pydantic AI sends the validation error back to the model and lets it try again; a quick check with a script that omitted `message` on the first attempt finished correctly on the second. The `retries` argument accepts either an integer or an `AgentRetries` mapping with separate `tools` and `output` budgets, so set it with both tool errors and output errors in mind.

Read the transcript line by line. Message 1 is the bad call. Message 2 is the `ModelRetry` text delivered back as tool feedback. Message 3 is the corrected call. Message 5 is the structured output, sent as a call to `final_result`. Three model requests in total. `capture_run_messages` records all of this even when a run fails, which makes it the first thing to print when a test breaks. The [ReAct tool-calling simulation](/ai-simulations/react-tool-calling) animates the same request and response cycle.

## Step 5: cap the loop with usage limits

A model that keeps calling tools costs money and time. `UsageLimits` puts a hard ceiling on a run:

```python
# step_limits.py
from pydantic_ai import UsageLimits, UsageLimitExceeded
from pydantic_ai.models.function import FunctionModel
from scripted_model import scripted
from support_agent import agent, DEPS

try:
    agent.run_sync("Where is my order 1O42?", deps=DEPS, model=FunctionModel(scripted),
                   usage_limits=UsageLimits(request_limit=2))
except UsageLimitExceeded as e:
    print("stopped:", e)
```

```text
stopped: The next request would exceed the request_limit of 2. Consider raising the limit, or see the docs on usage limits for budget-aware patterns: https://pydantic.dev/docs/ai/core-concepts/agent/#usage-limits
```

The same scenario needs three requests, so a limit of two stops it before the third call is made. In production, set request and token limits from the distribution of real runs, for example a little above the 99th percentile, and treat a `UsageLimitExceeded` as an alert rather than a normal answer. The [agent loop token cost simulation](/ai-simulations/agent-loop-token-cost) shows why each extra request costs more than the last, and [cost and latency budgets](/tools/cost-and-latency-budgets) covers how to set them.

## Step 6: turn the scenarios into pytest tests

```python
# test_support_agent.py   Run: pytest -q
import pytest
from pydantic_ai import models
from pydantic_ai.models.function import FunctionModel
from pydantic_ai.models.test import TestModel
from support_agent import agent, DEPS, Deps
from scripted_model import scripted

models.ALLOW_MODEL_REQUESTS = False          # any accidental real model call raises an error

def test_typo_is_corrected_and_output_is_typed():
    with agent.override(model=FunctionModel(scripted)):
        result = agent.run_sync("Where is my order 1O42?", deps=DEPS)
    assert result.output.order_id == "1042" and result.output.refund_eligible

def test_other_customers_orders_are_hidden():
    other = Deps(orders=DEPS.orders, customer_id="c9")       # c9 must not see order 1042
    with agent.override(model=FunctionModel(scripted)):
        with pytest.raises(Exception, match="exceeded max retries"):
            agent.run_sync("Where is my order 1042?", deps=other)

def test_schema_smoke():
    m = TestModel(call_tools=[], custom_output_args={"order_id": "1", "status": "x", "refund_eligible": False, "message": "m"})
    with agent.override(model=m):
        agent.run_sync("hi", deps=DEPS)
    assert {t.name for t in m.last_model_request_parameters.function_tools} == {"get_order", "refund_window_days"}
```

```text
3 passed in 0.49s
```

The three tests cover three kinds of risk. The first checks behaviour: a recoverable mistake is corrected and the output is typed. The second checks a security property: when customer `c9` asks for order 1042, the tool refuses every time, the retries run out and the run fails instead of leaking data. The third checks the contract: the tool set the model sees. `agent.override` swaps the model without changing application code, so the same pattern works when the agent is buried inside a web handler.

## Step 7: going live with a real model

Moving to a real model changes one line and adds two habits. The line: give the agent a model, either in the constructor in place of `None` or per run with `model=`, using a provider-prefixed model id string, and set that provider's API key in the environment. Nothing else in `support_agent.py` changes, which is the payoff of keeping tools, dependencies and output types independent of the model.

The first habit is observability. `Agent.instrument_all()` turns on OpenTelemetry instrumentation for every agent, so each run, model request and tool call becomes a span that any OpenTelemetry backend can store. Pydantic's own Logfire is one option; Langfuse or Phoenix work as well because they accept OpenTelemetry data. Without traces, the retry in step 4 would be invisible in production: the user would get a correct answer, and you would never learn that the model needed two attempts.

The second habit is explicit limits. `UsageLimits` has a default `request_limit` of 50 in 2.71, which is generous for a support agent that normally needs three requests. It also accepts `tool_calls_limit`, `input_tokens_limit`, `output_tokens_limit`, `total_tokens_limit` and a `cost_limit`. Set the ones that match your budget per run, and keep them in configuration so operators can tighten them without a code change.

## Common mistakes and how the tests catch them

- **Checking permissions in the prompt.** "Only show the customer their own orders" in the instructions is a request, not a rule. The second test only passes because the ownership check lives in `get_order`.
- **Returning free text.** Without `output_type`, callers end up parsing prose with regular expressions. A typed `Reply` fails loudly when a field is missing, and the model gets a retry with the validation error.
- **Vague retry messages.** `ModelRetry("error")` gives the model nothing to work with. The message in step 1 says what went wrong and what to check, which is why the scripted correction is realistic.
- **Tests that silently call a real model.** A forgotten API key in a CI environment can turn a unit test into a slow, flaky, paid integration test. `ALLOW_MODEL_REQUESTS = False` makes that impossible.
- **Asserting on exact wording.** Tests that compare the customer message word for word break with every prompt change. Assert on typed fields such as `order_id` and `refund_eligible`, and leave wording to evaluations.

## What it means in practice

Offline tests like these run in under a second, so they belong in every pull request. They will not tell you whether a real model chooses well; for that you need evaluation runs against the real model, repeated several times, as covered on the [evals page](/tools/evals). The two layers complement each other: unit tests lock down wiring, permissions, schemas and limits, and evaluations measure judgement.

This tutorial used `run_sync` for readability. In a web service you would call the async `run`, stream partial output with `run_stream`, or step through the graph node by node with `iter` when you need fine control, for example to log each decision or stop early. All of them accept the same `deps`, `usage_limits` and `model` arguments, so the tests above still apply.

Pydantic AI suits teams that already use Pydantic for validation and want the agent to feel like typed Python rather than a separate runtime. If you need graph-shaped workflows with checkpoints and human interrupts as first-class features, a graph framework may fit better; the testing habits in this tutorial carry over either way.

The design choices that made testing easy are worth copying in any framework. Dependencies are injected, not global. Permission checks live in tools, not prompts. Output is a schema, not prose. Limits are explicit. A test model can be swapped in from outside. For framework comparisons, see [Pydantic AI](/tools/pydantic-ai) and our [frameworks overview](/articles/agentic-ai-frameworks-langchain-langgraph-and-every-alternative).

## What to do now

1. **Type the output.** Give your agent an `output_type` so callers get validated objects instead of text to parse.
2. **Inject dependencies.** Pass databases, clients and the current user through `deps`, never through globals or prompts.
3. **Enforce permissions in tools.** Check ownership in code and raise `ModelRetry` with a helpful message when input is wrong.
4. **Block real calls in tests.** Set `models.ALLOW_MODEL_REQUESTS = False` in your test setup.
5. **Use TestModel for contracts.** Assert on tool names and output schemas with `last_model_request_parameters`.
6. **Use FunctionModel for scenarios.** Script typos, refusals and edge cases that a real model produces only occasionally.
7. **Set usage limits.** Add `UsageLimits` to every production run and alert when they trigger.
8. **Pin the version.** Pydantic AI released four minor versions in eight days; pin and upgrade deliberately.

## Risks and open questions

**Scripted models can drift from reality.** A `FunctionModel` script encodes your guess about model behaviour. Refresh scenarios from real traces so tests stay realistic.

**Retries hide problems.** A tool that often triggers `ModelRetry` adds latency and cost even when runs succeed. Track retry counts in traces.

**Typed output is not correct output.** Validation guarantees the shape of the answer, not its truth. `refund_eligible=True` still needs to match policy, which is what evaluations check.

**Fast release cadence.** Frequent minor versions bring new features but also deprecations, like the `usage` property change seen here.

**Watch next:** how Pydantic AI's newer capabilities and native tools interact with `TestModel`, which its documentation says cannot emulate provider-executed native tools, and how test patterns evolve for durable, long-running agents.

## Frequently asked questions

### What is the difference between TestModel and FunctionModel?

`TestModel` generates tool arguments and output from schemas with simple procedural code, which is ideal for checking wiring and contracts. `FunctionModel` runs your own Python function to decide each response, which lets you script precise scenarios such as typos, retries and refusals.

### Why did TestModel fail when it called every tool?

It called `get_order` with a generated `order_id` of "a", which the tool correctly rejected with `ModelRetry`. After the retry limit of two, the run failed. Limiting `call_tools` or using `FunctionModel` solves this.

### How does ModelRetry help an agent?

It turns a tool failure into feedback. The message is sent back to the model, which can correct its call; in the demo the model fixed "1O42" to "1042" on the next request. If the model keeps failing, the retry limit ends the run with an error.

### Can tests accidentally call a paid model?

Not if you set `models.ALLOW_MODEL_REQUESTS = False`. Any attempt to use a non-test model then raises an error, which the Pydantic AI testing guide recommends doing globally in test setups.

### How do I move from the scripted model to a real one?

Pass a model when creating the agent, or at run time with `model=`, for example a provider-prefixed model id string, and set the provider's API key. The tools, dependencies, output type and limits stay the same, and the offline tests keep running unchanged through `agent.override`.

## Summary

This tutorial built a typed order-support agent with Pydantic AI 2.71: injected dependencies, two tools, a permission check that raises `ModelRetry`, and a `Reply` model as validated output. `TestModel` checked the contract in milliseconds once it was told which tools to call. `FunctionModel` scripted a full scenario in which the model fixed a typo after a retry hint and returned typed output in three requests. `UsageLimits` stopped the same run at two requests, and three pytest tests, with real model calls blocked, passed in under half a second. Keep these offline tests in every pull request and pair them with evaluations against the real model.

## Sources

- [Pydantic AI Docs: Unit testing](https://pydantic.dev/docs/ai/guides/testing)
- [GitHub: pydantic-ai testing guide source](https://github.com/pydantic/pydantic-ai/blob/main/docs/testing.md)
- [Pydantic AI Docs: TestModel API](https://pydantic.dev/docs/ai/models/test)
- [Pydantic AI Docs: FunctionModel API](https://pydantic.dev/docs/ai/models/function)
- [PyPI: pydantic-ai](https://pypi.org/project/pydantic-ai/)
- [PyPI: pydantic-ai-slim](https://pypi.org/project/pydantic-ai-slim/)
