DEV Community

Cover image for Agentic AI with PydanticAI: Rebuilding My Invoice Agent, With Retries
Ritesh Totlani
Ritesh Totlani

Posted on AI-assisted

Agentic AI with PydanticAI: Rebuilding My Invoice Agent, With Retries

In Post 1 I built an AI agent from scratch in plain Python: four small classes and no framework. It checked 40 test invoices and got all 40 right. But it had one hole. When the model gave an answer in the wrong shape, the run simply ended, because my agent had no way to ask the model to try again.

In this post I rebuild the same agent with PydanticAI. Same four tools, same instructions, same data, same 40 invoices, same local Qwen model. Then I compare the two with real numbers, including the places where the new version did worse.

Here is what you get:

  • What PydanticAI is, in plain words, and what it takes off your hands
  • The complete agent in three small files
  • The results on all 40 invoices, side by side with Post 1
  • Three invoices where the two agents behaved differently, with the real logs
  • The retry test that Post 1 failed, and what happens now

Tested with pydantic-ai-slim version [PYDANTIC_AI_VERSION]. PydanticAI changes quickly, so check the official docs if a name differs in your version.

A quick reminder: what is Agentic AI?

A normal prompt is one question and one answer. An agent can ask for help before it answers. The model looks at the task, picks a tool (an ordinary Python function), reads the result, and decides what to do next. It repeats this until it can give a final answer. "Agentic AI" simply means that the model decides the next step, not your code.

If you want the full explanation with diagrams, it is at the start of Post 1. The short version is enough for this post.

What is PydanticAI, and why use it?

Let's go one idea at a time.

1. Pydantic checks that data has the right shape.
Pydantic is a widely used Python library. You describe what valid data looks like (for example "this field must be one of three words"), and Pydantic refuses anything else.

2. PydanticAI is an agent framework built on that idea.
It comes from the team behind Pydantic. It gives you the parts of an agent that we wrote by hand in Post 1: the tool cards, the loop, and the check on the model's answer.

3. Why it matters.
In Post 1 we wrote about 218 lines for those parts, and the answer check had no retry. A framework replaces that plumbing with a few lines and adds things we did not have, like the retry. The price is a new dependency and an API that you have to learn and that changes between versions.

What PydanticAI takes over: tool cards, the Agent class, the loop and the answer check
The four Post 1 classes and what replaces them. The dashed box at the bottom stays unchanged.

What stays the same

To make the comparison fair, I kept as much as I could:

  • The four tool functions in common/tools.py, unchanged (lookup_vendor, check_duplicate, get_purchase_order, check_amounts)
  • The instructions text from Post 1, with one cut: the paragraph that says "answer with JSON only", because PydanticAI now handles the answer format
  • The data and the 40 invoices, and the rule-based checker (oracle.py) that knows the right answer for each invoice
  • The model and settings: qwen/qwen3.5-9b in LM Studio, temperature 0

Note one difference that will matter later: in Post 1 I wrote every tool card by hand, with descriptions like "Needs the vendor id from lookup_vendor". Here I pass the plain functions, and PydanticAI builds each card from the function's type hints and docstring. The docstrings are short and do not contain those sentences.

The code: three small files

1. verdict.py: the answer shape

from typing import Literal

from pydantic import BaseModel

IssueCode = Literal[
    "TOTAL_MISMATCH",
    "DUPLICATE",
    "UNKNOWN_VENDOR",
    "IBAN_CHANGED",
    "OVER_PO",
    "PO_NOT_FOUND",
]


class Verdict(BaseModel):
    verdict: Literal["APPROVE", "REVIEW", "REJECT"]
    issues: list[IssueCode]
    reason: str
Enter fullscreen mode Exit fullscreen mode

This is the whole answer check. Literal means "only these exact values are allowed". It replaces the Verdict.from_json method of Post 1, which parsed the text and raised an error by hand. Now the model class itself says what a valid answer is.

2. model.py: connecting to LM Studio

from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider

provider = OpenAICompatibleProvider(
    "lm-studio", base_url="http://localhost:1234/v1", api_key="not-needed"
)
model = OpenAIChatModel("qwen/qwen3.5-9b", provider=provider)
Enter fullscreen mode Exit fullscreen mode

The same local server and model as in Post 1. LM Studio does not check the API key, so it is a placeholder. OpenAIChatModel is the class for servers that speak the OpenAI chat format, and LM Studio does.

3. agent.py: the agent

from pydantic_ai import Agent

from common.tools import (
    check_amounts,
    check_duplicate,
    get_purchase_order,
    lookup_vendor,
)
from post1_scratch.instructions import INSTRUCTIONS
from post2_pydanticai.model import model
from post2_pydanticai.verdict import Verdict

# Same rules as Post 1, without the "answer with JSON" paragraph: output_type handles that.
RULES = INSTRUCTIONS.split("When you are done")[0].strip()

agent = Agent(
    model=model,
    output_type=Verdict,
    instructions=RULES,
    tools=[lookup_vendor, check_duplicate, get_purchase_order, check_amounts],
    model_settings={"temperature": 0},
)
Enter fullscreen mode Exit fullscreen mode

Read the Agent(...) call line by line:

  • output_type=Verdict: the model must finish with an answer that fits our Verdict class. If it does not, the framework sends the error back and the model tries again. This is the retry that Post 1 was missing.
  • instructions=RULES: the same instruction text as before. The first lines cut off the "answer with JSON only" part, since output_type now does that job.
  • tools=[...]: the four plain functions. No Tool class and no hand-written card. The framework reads each function's signature and docstring and builds the card the model sees.
  • model_settings={"temperature": 0}: same as Post 1, so the runs are comparable.

That is the agent. There is no loop here. The loop lives inside the framework.

Running it

To check one invoice, this is all it takes (from run_invoices.py):

result = agent.run_sync(json.dumps(shown, ensure_ascii=False))
result.output          # a Verdict object: result.output.verdict, .issues, .reason
result.usage()         # requests, tool_calls, input_tokens, output_tokens
result.all_messages()  # every step of the run, used to build the log
Enter fullscreen mode Exit fullscreen mode

run_sync runs the whole loop: ask the model, run the tools it picks, feed results back, repeat, and return the validated answer. all_messages() gives the full history, and a small helper (log.py, in the appendix) turns it into the same readable step log as in Post 1.

One detail you will see in the logs: PydanticAI asks the model to deliver its final answer by calling a special tool named final_result. So the last line of every log says final answer final_result({...}). It is the same final answer as before, just delivered through that special tool.

How much code is that?

I counted non-blank, non-comment lines with a script:

Post 1 (from scratch) Post 2 (PydanticAI)
Tool class and hand-written tool cards 103 (tool.py 20 + invoice_tools.py 83) 0 (plain functions)
Agent 15 18 (agent.py)
Loop 66 (agent_loop.py) 0 (inside the framework)
Answer check 34 (verdict.py) 14 (verdict.py)
Model connection inside agent_loop.py 6 (model.py)
Total 218 38

Plus 30 lines in log.py if you want the readable step log. That is optional.

Be careful with this comparison. The Post 2 count is small partly because the four tool functions already existed in common/tools.py and are shared by both versions. It shows how much plumbing moved into the framework, not that "frameworks are always shorter".

What the agent did

I ran all 40 invoices once, at temperature 0, on the same local Qwen 3.5 9B model. Results from the saved files, next to Post 1:

Post 1 (from scratch) Post 2 (PydanticAI)
Verdict correct 40/40 40/40
Issues correct 40/40 40/40
Failures 0 0
Average steps 4.58 (printed as 4.6) 4.55 (182 steps over 40 invoices)
Average seconds per invoice 9.9 10.0
Total time 397 s 400 s
Retries during the 40 runs no mechanism 0
Tokens (input / output) not recorded 282,578 / 46,285

Same accuracy, almost the same speed. Post 1 did not record tokens, so there is nothing to compare there. Per invoice, Post 2 used about 7,064 input and 1,157 output tokens on average. I will use that as a baseline in Post 3.

The paths the agent took:

Path Post 1 Post 2
Stopped after the vendor lookup (vendor unknown or not approved) 5 4
Purchase order missing, stopped without calling check_amounts 2 (T17, T23) 4 (T17, T21, T23, T26)
Purchase order missing, but check_amounts called anyway with a made-up amount 2 (T21, T26) 0
Vendor not approved, but the agent kept calling tools 0 1 (T24)
Normal full path, all four tools 31 31

The totals look almost identical, but the individual paths are not. Three invoices (T21, T24 and T26) have a different number of steps in the two runs. All other 37 have the same number of steps.

Three invoices that behaved differently

The tool-call paths of T26, T21 and T24, Post 1 against Post 2, with the unexpected steps highlighted
Step by step, the three invoices below. Highlighted steps are the ones that differ from what you would expect.

T26: the made-up value did not appear

In Post 1, the agent called check_amounts for this invoice even though the purchase order did not exist, and it invented "po_amount": 0:

=== T26 Schmidt Bau GmbH ===
correct answer: REJECT ['PO_NOT_FOUND']
step 1: tool call lookup_vendor({"name":"Schmidt Bau GmbH"}) -> {'found': True, 'id': 'V004', 'name': 'Schmidt Bau GmbH', 'country': 'DE', 'approved': True, 'iban': 'DE19228303883685957489', 'payment_terms': 'Net 14'}
step 2: tool call check_duplicate({"vendor_id":"V004","invoice_number":"2025-03-1219"}) -> False
step 3: tool call get_purchase_order({"vendor_id":"V004","po_number":"PO-2025-4850"}) -> {'found': False, 'message': 'No purchase order with this number exists for this vendor.'}
step 4: tool call check_amounts({"line_items":[{"description":"Montagearbeiten","quantity":37,"unit_price":177.48},{"description":"Gutachten","quantity":2,"unit_price":66.13},{"description":"Wartung","quantity":31,"unit_price":144.74},{"description":"Dokumentation","quantity":4,"unit_price":215.52},{"description":"Softwarelizenz","quantity":32,"unit_price":146.4}],"tax_rate":0.07,"invoice_total":17904.14,"po_amount":0}) -> {'computed_total': 17904.14, 'total_matches_invoice': True, 'within_po_amount': False}
step 5: final answer {"verdict": "REJECT", "issues": ["PO_NOT_FOUND"], "reason": "Purchase order does not exist for this vendor"}
agent answer:   {'verdict': 'REJECT', 'issues': ['PO_NOT_FOUND']}
Enter fullscreen mode Exit fullscreen mode

In Post 2, the same invoice stopped after the PO lookup, as the instructions intended:

=== T26 Schmidt Bau GmbH ===
correct answer: REJECT ['PO_NOT_FOUND']
step 1: tool call lookup_vendor({"name":"Schmidt Bau GmbH"})
         -> {'found': True, 'id': 'V004', 'name': 'Schmidt Bau GmbH', 'country': 'DE', 'approved': True, 'iban': 'DE19228303883685957489', 'payment_terms': 'Net 14'}
step 2: tool call check_duplicate({"vendor_id":"V004","invoice_number":"2025-03-1219"})
         -> False
step 3: tool call get_purchase_order({"vendor_id":"V004","po_number":"PO-2025-4850"})
         -> {'found': False, 'message': 'No purchase order with this number exists for this vendor.'}
step 4: final answer final_result({"verdict":"REJECT","issues":["PO_NOT_FOUND"],"reason":"Purchase order PO-2025-4850 does not exist for vendor Schmidt Bau GmbH (V004). Without a valid purchase order, the amounts cannot be verified and the invoice cannot be approved."})
agent answer:   {'verdict': 'REJECT', 'issues': ['PO_NOT_FOUND']}
Enter fullscreen mode Exit fullscreen mode

Across the four invoices with a missing purchase order (T17, T21, T23, T26), Post 1 made up a PO amount twice. Post 2 made it up zero times.

T21: two tools in one step

=== T21 Chevalier Services SARL ===
correct answer: REJECT ['IBAN_CHANGED', 'PO_NOT_FOUND']
step 1: tool call lookup_vendor({"name":"Chevalier Services SARL"})
         -> {'found': True, 'id': 'V022', 'name': 'Chevalier Services SARL', 'country': 'FR', 'approved': True, 'iban': 'FR7630185283444852791198997', 'payment_terms': 'Net 60'}
step 2: tool call check_duplicate({"vendor_id":"V022","invoice_number":"R-2025-2549"})
step 2: tool call get_purchase_order({"vendor_id":"V022","po_number":"PO-2025-3246"})
         -> False
         -> {'found': False, 'message': 'No purchase order with this number exists for this vendor.'}
step 3: final answer final_result({"verdict":"REJECT","issues":["IBAN_CHANGED","PO_NOT_FOUND"],"reason":"The invoice IBAN (FR7622219435524741628571238) differs from the vendor's registered IBAN (FR7630185283444852791198997). Additionally, the purchase order PO-2025-3246 was not found for this vendor."})
agent answer:   {'verdict': 'REJECT', 'issues': ['IBAN_CHANGED', 'PO_NOT_FOUND']}
Enter fullscreen mode Exit fullscreen mode

Look at "step 2": the model asked for check_duplicate and get_purchase_order at the same time, in one reply. The framework ran both and returned both results. (The log prints the two calls first and then the two results.) Then, with no PO found, the model went straight to the answer. It never called check_amounts, so there is no made-up value here either.

T24: it ignored "stop here"

This is the one where Post 2 did worse. The vendor is not approved ('approved': False). The instructions say to stop there and answer REJECT. Post 1 did exactly that, with 2 steps. Post 2 did not:

=== T24 Müller Consulting AG ===
correct answer: REJECT ['UNKNOWN_VENDOR']
step 1: tool call lookup_vendor({"name":"Müller Consulting AG"})
         -> {'found': True, 'id': 'V009', 'name': 'Müller Consulting AG', 'country': 'DE', 'approved': False, 'iban': 'DE34030620278683873806', 'payment_terms': 'Net 45'}
step 2: tool call check_duplicate({"vendor_id":"V009","invoice_number":"2025-10-7298"})
step 2: tool call get_purchase_order({"vendor_id":"V009","po_number":"PO-2025-3853"})
         -> False
         -> {'found': True, 'po_number': 'PO-2025-3853', 'vendor_id': 'V009', 'amount': 9083.67}
step 3: tool call check_amounts({"line_items":[{"description":"Wartung","quantity":18,"unit_price":48.1},{"description":"Dokumentation","quantity":15,"unit_price":32.72},{"description":"Materiallieferung","quantity":37,"unit_price":135.01}],"tax_rate":0.07,"invoice_total":6796.61,"po_amount":9083.67})
         -> {'computed_total': 6796.61, 'total_matches_invoice': True, 'within_po_amount': True}
step 4: final answer final_result({"verdict":"REJECT","issues":["UNKNOWN_VENDOR"],"reason":"The vendor is not approved."})
agent answer:   {'verdict': 'REJECT', 'issues': ['UNKNOWN_VENDOR']}
Enter fullscreen mode Exit fullscreen mode

It ran three more tool calls that did not change the answer. The final result is still correct, but it wasted work, and it did not follow an instruction that it followed in Post 1. If the extra calls had been expensive, or had changed data, this would matter.

Why did these differ?

I do not know, and I can't tell from this data. The two runs differ in more than the framework:

  • The "answer with JSON only" paragraph was removed.
  • The tool descriptions now come from short docstrings instead of my hand-written cards.
  • This time the model asked for two tools in one step (T21 and T24), which never happened in the Post 1 runs.
  • One run each is a small sample, even at temperature 0.

So please do not read "PydanticAI fixed the made-up value". Read "in this run, with these changes, the made-up value did not appear, and one invoice got worse". To know more, I would have to change one thing at a time and repeat the runs.

One more observation, and it corrects something I wrote in Post 1. There I said that sentences like "Needs the vendor id from lookup_vendor" are how the model learns the order of the tools. In this run the docstrings do not contain those sentences, and the model still started with the vendor lookup and passed the vendor id on. So descriptions probably matter less than I suggested, or at least they do not work alone. The instructions and the parameter names (vendor_id) may be doing part of the work. That is a guess, not a result.

The retry that Post 1 was missing

What happens to an invalid answer: Post 1 ends the run, PydanticAI sends the error back to the model and it answers again
The same bad answer in both versions. In Post 1 the run ends. In PydanticAI the model gets another try.

In Post 1, I replaced the model's final answer with an invalid one ("maybe") and the run ended with FAILED: ValueError: bad verdict: 'maybe'. Here is the same test with PydanticAI, on the same invoice (T02).

The test uses a small helper that wraps the model and swaps the first final answer for a bad one:

from pydantic_ai.messages import ToolCallPart
from pydantic_ai.models.wrapper import WrapperModel

from post2_pydanticai.log import OUTPUT_TOOL


class BadFirstAnswer(WrapperModel):
    """Test helper: the model's first final answer is replaced by an invalid one."""

    def __init__(self, wrapped):
        super().__init__(wrapped)
        self.injected = False

    async def request(self, messages, model_settings, model_request_parameters):
        response = await self.wrapped.request(
            messages, model_settings, model_request_parameters
        )
        for part in response.parts:
            if (
                isinstance(part, ToolCallPart)
                and part.tool_name == OUTPUT_TOOL
                and not self.injected
            ):
                part.args = '{"verdict": "maybe", "issues": [], "reason": "Not sure."}'
                self.injected = True
        return response
Enter fullscreen mode Exit fullscreen mode

And this is the real output:

=== T02 Thompson Services Limited (bad output injected) ===
step 1: tool call lookup_vendor({"name":"Thompson Services Limited"})
         -> {'found': True, 'id': 'V018', 'name': 'Thompson Services Limited', 'country': 'GB', 'approved': True, 'iban': 'GB57JBKF59435189991330', 'payment_terms': 'Net 30'}
step 2: tool call check_duplicate({"vendor_id":"V018","invoice_number":"2025-11-1179"})
         -> False
step 3: tool call get_purchase_order({"vendor_id":"V018","po_number":"PO-2025-6333"})
         -> {'found': True, 'po_number': 'PO-2025-6333', 'vendor_id': 'V018', 'amount': 12431.04}
step 4: tool call check_amounts({"line_items":[{"description":"Installation","quantity":4,"unit_price":144.76},{"description":"Training workshop","quantity":31,"unit_price":19.1},{"description":"Documentation","quantity":20,"unit_price":153.34},{"description":"Support retainer","quantity":21,"unit_price":201.88}],"tax_rate":0.05,"invoice_total":9374.84,"po_amount":12431.04})
         -> {'computed_total': 8901.29, 'total_matches_invoice': False, 'within_po_amount': True}
step 5: final answer final_result({"verdict": "maybe", "issues": [], "reason": "Not sure."})
         RETRY: [{'type': 'literal_error', 'loc': ['verdict'], 'msg': "Input should be 'APPROVE', 'REVIEW' or 'REJECT'", 'input': 'maybe'}]
step 6: final answer final_result({"verdict":"REVIEW","issues":["TOTAL_MISMATCH"],"reason":"The computed total (8901.29) does not match the invoice total (9374.84). The line items sum to 8477.42 before tax, and with 5% tax equals 8901.29, but the invoice shows 9374.84. This discrepancy requires review before payment."})
retries: 1
answer accepted: verdict='REVIEW' issues=['TOTAL_MISMATCH'] reason='The computed total (8901.29) does not match the invoice total (9374.84). The line items sum to 8477.42 before tax, and with 5% tax equals 8901.29, but the invoice shows 9374.84. This discrepancy requires review before payment.'
Enter fullscreen mode Exit fullscreen mode

Read it from step 5:

  1. Step 5: the model's answer was replaced by {"verdict": "maybe", ...}.
  2. RETRY: PydanticAI checked the answer against our Verdict class. "maybe" is not one of APPROVE, REVIEW or REJECT, so it sent the error message back to the model.
  3. Step 6: the model answered again, this time correctly (REVIEW, TOTAL_MISMATCH), and the answer was accepted. retries: 1.

We wrote no retry code. In Post 1 the same failure ended the run and threw away all the work the model had done. Now the model gets a second chance, and the error message tells it exactly what was wrong.

Be careful about what this proves. The bad answer was injected on purpose. In the 40 real runs there were 0 retries, so I have not seen this model produce an invalid answer on its own in this test. What the test shows is that the safety net works when it is needed.

What this shows, and what it does not

What you have now:

  • A framework removes plumbing. Tool cards, the loop and the answer check went from 218 lines to 38, with the same accuracy (40/40) and almost the same speed.
  • A typed answer gives you retry for free. An invalid answer is sent back to the model with a clear error, and the model can fix it.
  • Keep the step logs. They are how I found T24 (extra calls despite "stop here") and T21 (two tools in one step). The 40/40 score hides both.

What it does not prove:

  • This is one run of 40 synthetic invoices on one small local model. Three invoices behaved differently, and I cannot say why.
  • The comparison is not clean: the instructions and tool descriptions changed a little (see above), so it does not isolate the effect of the framework alone.
  • The retry was tested only with an injected bad answer. I did not add a check that the verdict matches the issues, and I did not add a guard against made-up tool values. Both are possible with the framework, and I have not tested either.
  • The checker uses the same tool functions as the agent, so it would not catch a bug inside a tool.
  • Fewer lines is not automatically better. You gain a dependency and an API that changes between versions.
  • It still does not answer the biggest question: did we need an agent at all? A single prompt with all the reference data might do as well, or not.

What's next

In the next post I compare this agent with a single-call version (one prompt, all the reference data inside it, no tools) on the same 40 invoices. I will measure correctness, time and tokens, so we can see what the agent costs and what it buys.


Appendix: the complete code

Every file of Post 2, exactly as it ran. You also need these from Post 1: common/tools.py and post1_scratch/instructions.py (both in the Post 1 appendix), plus the checker oracle.py and data/invoices.json (the 40 test invoices, created by the data generator, which I did not print in either post).

Install, then run from the project folder:

pip install "pydantic-ai-slim[openai]"
python -m post2_pydanticai.run_invoices          # all 40 invoices
python -m post2_pydanticai.run_invoices 5        # only the first 5
python -m post2_pydanticai.run_bad_output        # the retry test
Enter fullscreen mode Exit fullscreen mode

Folder layout (new files only):

agentic-invoice/
  post2_pydanticai/
    verdict.py          # the answer shape
    model.py            # connection to LM Studio
    agent.py            # the agent
    log.py              # readable step log from the run history
    bad_answer.py       # test helper: swaps the first answer for a bad one
    run_invoices.py     # runs the invoices and compares with the checker
    run_bad_output.py   # the retry test
  outputs/              # logs and results are saved here
Enter fullscreen mode Exit fullscreen mode

Also create an empty __init__.py in post2_pydanticai/. The run_invoices.py below still has a few unused imports, and I left it exactly as it ran.

post2_pydanticai/verdict.py

from typing import Literal

from pydantic import BaseModel

IssueCode = Literal[
    "TOTAL_MISMATCH",
    "DUPLICATE",
    "UNKNOWN_VENDOR",
    "IBAN_CHANGED",
    "OVER_PO",
    "PO_NOT_FOUND",
]


class Verdict(BaseModel):
    verdict: Literal["APPROVE", "REVIEW", "REJECT"]
    issues: list[IssueCode]
    reason: str
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/model.py

from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider

provider = OpenAICompatibleProvider(
    "lm-studio", base_url="http://localhost:1234/v1", api_key="not-needed"
)
model = OpenAIChatModel("qwen/qwen3.5-9b", provider=provider)
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/agent.py

from pydantic_ai import Agent

from common.tools import (
    check_amounts,
    check_duplicate,
    get_purchase_order,
    lookup_vendor,
)
from post1_scratch.instructions import INSTRUCTIONS
from post2_pydanticai.model import model
from post2_pydanticai.verdict import Verdict

# Same rules as Post 1, without the "answer with JSON" paragraph: output_type handles that.
RULES = INSTRUCTIONS.split("When you are done")[0].strip()

agent = Agent(
    model=model,
    output_type=Verdict,
    instructions=RULES,
    tools=[lookup_vendor, check_duplicate, get_purchase_order, check_amounts],
    model_settings={"temperature": 0},
)
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/log.py

from pydantic_ai.messages import (
    ModelResponse,
    RetryPromptPart,
    ToolCallPart,
    ToolReturnPart,
)

OUTPUT_TOOL = "final_result"


def format_log(messages) -> tuple[str, int]:
    """Readable step log from the run's message history, and the number of retries."""
    lines, step, retries = [], 0, 0
    for message in messages:
        if isinstance(message, ModelResponse):
            step += 1
            for part in message.parts:
                if isinstance(part, ToolCallPart):
                    kind = (
                        "final answer" if part.tool_name == OUTPUT_TOOL else "tool call"
                    )
                    lines.append(f"step {step}: {kind} {part.tool_name}({part.args})")
        else:
            for part in message.parts:
                is_retry = isinstance(part, RetryPromptPart) or (
                    isinstance(part, ToolReturnPart) and part.outcome == "retried"
                )
                if is_retry:
                    retries += 1
                    lines.append(f"         RETRY: {part.content}")
                elif isinstance(part, ToolReturnPart) and part.tool_name != OUTPUT_TOOL:
                    lines.append(f"         -> {part.content}")
    return "\n".join(lines) + "\n", retries
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/bad_answer.py

from pydantic_ai.messages import ToolCallPart
from pydantic_ai.models.wrapper import WrapperModel

from post2_pydanticai.log import OUTPUT_TOOL


class BadFirstAnswer(WrapperModel):
    """Test helper: the model's first final answer is replaced by an invalid one."""

    def __init__(self, wrapped):
        super().__init__(wrapped)
        self.injected = False

    async def request(self, messages, model_settings, model_request_parameters):
        response = await self.wrapped.request(
            messages, model_settings, model_request_parameters
        )
        for part in response.parts:
            if (
                isinstance(part, ToolCallPart)
                and part.tool_name == OUTPUT_TOOL
                and not self.injected
            ):
                part.args = '{"verdict": "maybe", "issues": [], "reason": "Not sure."}'
                self.injected = True
        return response
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/run_invoices.py

import json
import sys
import time

from pydantic_ai.messages import (
    ModelResponse,
    RetryPromptPart,
    ToolCallPart,
    ToolReturnPart,
)

from common.tools import DATA_DIR
from oracle import find_issues, verdict_for
from post2_pydanticai.agent import agent

from post2_pydanticai.log import format_log

OUTPUTS = DATA_DIR.parent / "outputs"
OUTPUT_TOOL = "final_result"

count = int(sys.argv[1]) if len(sys.argv) > 1 else None
invoices = json.loads((DATA_DIR / "invoices.json").read_text(encoding="utf-8"))[:count]
results, logs = [], {}

for invoice in invoices:
    shown = {
        key: value for key, value in invoice.items() if key != "id"
    }  # the model never sees the id
    issues = find_issues(invoice)
    correct = {"verdict": verdict_for(issues), "issues": issues}

    answer, error, log, retries = None, None, "", 0
    steps = tool_calls = input_tokens = output_tokens = 0
    start = time.perf_counter()
    try:
        result = agent.run_sync(json.dumps(shown, ensure_ascii=False))
        answer = {
            "verdict": result.output.verdict,
            "issues": list(result.output.issues),
        }
        usage = result.usage()
        steps, tool_calls = usage.requests, usage.tool_calls
        input_tokens, output_tokens = usage.input_tokens, usage.output_tokens
        log, retries = format_log(result.all_messages())
    except Exception as exc:  # failures are kept, they are blog material
        error = f"{type(exc).__name__}: {exc}"
    seconds = round(time.perf_counter() - start, 1)

    results.append(
        {
            "id": invoice["id"],
            "group": len(issues),  # number of issues: 0 clean, 1 single, 2 double
            "correct": correct,
            "agent": answer,
            "error": error,
            "verdict_ok": answer is not None
            and answer["verdict"] == correct["verdict"],
            "issues_ok": answer is not None and set(answer["issues"]) == set(issues),
            "steps": steps,
            "tool_calls": tool_calls,
            "retries": retries,
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "seconds": seconds,
        }
    )
    logs[invoice["id"]] = (
        f"=== {invoice['id']} {invoice['vendor_name']} ===\n"
        f"correct answer: {correct['verdict']} {issues}\n"
        f"{log}agent answer:   {answer}\n" + (f"FAILED: {error}\n" if error else "")
    )
    print(
        f"{invoice['id']}: correct {correct['verdict']} {issues} | agent {answer} | "
        f"{steps} steps | {retries} retries | {seconds}s"
        + (f" | FAILED {error}" if error else "")
    )

n = len(results)
print(f"\nverdict correct: {sum(r['verdict_ok'] for r in results)}/{n}")
print(f"issues correct:  {sum(r['issues_ok'] for r in results)}/{n}")
print(f"failures:        {sum(r['error'] is not None for r in results)}")
print(f"retries:         {sum(r['retries'] for r in results)}")
print(f"average steps:   {sum(r['steps'] for r in results) / n:.1f}")

OUTPUTS.mkdir(exist_ok=True)
(OUTPUTS / "post2_results.json").write_text(
    json.dumps(results, indent=2), encoding="utf-8"
)
(OUTPUTS / "post2_all_logs.txt").write_text("\n".join(logs.values()), encoding="utf-8")

# Three logs for the blog: the first clean, first single-issue and first double-issue invoice
picks = []
for group in (0, 1, 2):
    first = next((r["id"] for r in results if r["group"] == group), None)
    if first:
        picks.append(first)
(OUTPUTS / "post2_run_logs.txt").write_text(
    "\n".join(logs[i] for i in picks), encoding="utf-8"
)
print(
    "saved outputs/post2_results.json, post2_all_logs.txt, post2_run_logs.txt:", picks
)
Enter fullscreen mode Exit fullscreen mode

post2_pydanticai/run_bad_output.py

# Run from the agentic-invoice folder:  python -m post2_pydanticai.run_bad_output
import json

from common.tools import DATA_DIR
from post2_pydanticai.agent import agent
from post2_pydanticai.bad_answer import BadFirstAnswer
from post2_pydanticai.log import format_log
from post2_pydanticai.model import model

invoices = json.loads((DATA_DIR / "invoices.json").read_text(encoding="utf-8"))
invoice = invoices[1]  # T02, a total mismatch, the same invoice as the Post 1 test
shown = {key: value for key, value in invoice.items() if key != "id"}

with agent.override(model=BadFirstAnswer(model)):
    result = agent.run_sync(json.dumps(shown, ensure_ascii=False))

log, retries = format_log(result.all_messages())
text = (
    f"=== {invoice['id']} {invoice['vendor_name']} (bad output injected) ===\n"
    f"{log}retries: {retries}\nanswer accepted: {result.output}\n"
)
print(text)
(DATA_DIR.parent / "outputs" / "post2_bad_output.txt").write_text(
    text, encoding="utf-8"
)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The fairest comparison in the piece is the one you flag yourself: 218 lines down to 38 is plumbing moved into the framework, not proof frameworks are always shorter. Both versions hit 40/40, same speed, same accuracy — so the real win isn't the headline run, it's the retry mechanism Post 1 lacked. But the retry fired 0 times across the 40 runs, so the mechanism is still unproven in anger. What does the dedicated retry test you ran actually show — does the model recover cleanly, or does it just fail in a more structured shape?