SYSTEM NOTICE

Auto translation by AI. Be sure, accuracy, nuances and authorial intent may not be fully reflected.
見出し画像

[No.152] Python × PydanticAI Practical Pack — Typed Agent Output

To solve the problem where Python AI output often becomes a nightmare of dict conversion and JSON parsing, PydanticAI fixes structured output using Agent + BaseModel. With Agent(deps_type, output_type), DI via @agent.tool and RunContext, result.output is the Pydantic object itself.
You can write it with the same DI feel as FastAPI.
Saving the SupportResponse template to your Snippets is the move for this week.



What this article includes

PydanticAI positioning — structured output without JSON parsing

SupportResponse template — for BaseModel + Agent copy-pasting

@agent.tool + RunContext DI memo — deps_type configuration

Failure fallback check — for validation errors

7-day Typed Agent Checklist — with completion definitions


What you can take away from this article

After pip install pydantic-ai, passing output_type=BaseModel subclass to the Agent makes result.output a typed object. Use deps_type for dependency injection, and @agent.tool with RunContext for FastAPI-style DI. This is the shortest route to avoiding JSON parsing hell.

One move to try this week: Save the SupportResponse template to your Snippets.


PydanticAI — structured output with Agent + BaseModel

According to the official Pydantic AI docs (ai.pydantic.dev / pydantic.dev), structured output is achieved with Agent + Pydantic models. It uses FastAPI-style DI. Python 3.10+. Agent(deps_type, output_type), DI via @agent.tool and RunContext. result.output is the Pydantic object itself.

For example, if a customer support bot returns responses and escalation requirements as JSON strings every time, leading to parsing failures, fixing it with output_type=SupportResponse as a BaseModel allows the SDK to handle validation. If you have FastAPI experience, the flow of placing DB sessions or configuration objects into deps_type and referencing them via RunContext within @agent.tool will feel familiar. Please treat the official Pydantic docs as the primary source of truth.

SDK key points (based on official Pydantic)

  • Requirement: Python 3.10+

  • Installation: pip install pydantic-ai

  • Definition: Agent(deps_type, output_type)

  • Tools: @agent.tool + RunContext

  • Output: result.output is a Pydantic object

  • Feel: Same DI as FastAPI


No JSON parsing required — 3 elements of a typed Agent

3 elements of a typed Agent

  1. output_type — Fix output schema with BaseModel subclass

  2. deps_type — Inject dependencies (DB clients, etc.) by type

  3. @agent.tool — Access deps via RunContext

  • Impact 1 — Python engineers: Fix LLM output dict conversion to structures

  • Impact 2 — FastAPI users: Use the same DI feel

  • Impact 3 — Production Agents: Early detection of validation failures

Common misconceptions and rebuttals

Misconception 1: "Pydantic v2 is all you need" → Rebuttal: PydanticAI includes the Agent loop and tool DI.

Misconception 2: "dict is enough for output" → Rebuttal: Fixing result.output to a BaseModel eliminates the need for parsing.

Misconception 3: "deps can be global" → Rebuttal: deps_type + RunContext is the official pattern.


SupportResponse template — BaseModel + Agent

This is a skeleton to fill in and save as snippets (label format).

SupportResponse template

  • Installation: pip install pydantic-ai

  • Import: Agent, RunContext (refer to official docs), BaseModel from pydantic

  • Output model SupportResponse:

    • reply: str — Response text for the user

    • needs_escalation: bool — Whether human escalation is required

    • category: str — Inquiry classification (e.g., billing / technical)

  • Dependencies Deps (optional):

    • deps_type name: Deps

    • Field example: user_id: str

  • Agent definition:

    • agent = Agent(model='(model name)', deps_type=Deps, output_type=SupportResponse, system_prompt='(1 line)')

  • @agent.tool example:

    • Function name: fetch_user_context

    • Arguments: ctx: RunContext[Deps]

    • Body: Reference ctx.deps.user_id (single-line processing)

  • Execution:

    • result = agent.run_sync('(user query 1 line)', deps=Deps(user_id='(id)'))

    • Retrieve: result.output.reply, result.output.needs_escalation

  • Expectation: result.output is of type SupportResponse, no manual JSON parsing

Definition of completion: result.output.category can be retrieved as a str in a single run_sync call.


Validation failure check — single fallback

Fallback check

  • Symptom: ValidationError / output type mismatch

  • Check 1: Is output_type a BaseModel subclass?

  • Check 2: Did you specify the output field names in the system_prompt?

  • Check 3: Is the model name in the official supported list?

  • Fallback: Add 1 line of JSON example to the prompt → run again

  • Log: Note the 1 line of failed input and the 1 line of corrected output

  • Production: Human escalation after 3 failures — needs_escalation=True fixed

Definition of completion: Intentionally tested the fallback procedure once with one ambiguous input.


7-day Typed Agent Checklist — Extended from SupportResponse

Day 1 — install

  • pip install pydantic-ai, verify Python 3.10+

  • Definition of completion: import successful

Day 2 — BaseModel

  • Define SupportResponse with 3 fields

  • Definition of completion: model is in one file

Day 3 — Minimal Agent

  • One Agent with output_type=SupportResponse, run without tools

  • Definition of completion: result.output can retrieve 3 fields

Day 4 — deps + tool

  • Add deps_type and one @agent.tool

  • Definition of completion: successful reference of deps via RunContext

Day 5 — Snippets

  • Save SupportResponse template as Snippets

  • Definition of completion: registered in editor

Day 6 — Fallback

  • Run a check once when validation fails

  • Definition of completion: one line of fallback notes

Day 7 — README

  • 3 lines in README explaining execution steps and output type

  • Definition of Done: Include pip install and output_type in the README

✅ Today, I will define and save only the three fields of SupportResponse.


Usage by Persona

Python Engineer: Replace existing dict-parsing Agents with fixed output_type. Start with SupportResponse.

FastAPI Developer: Align deps_type with DB sessions, etc., and use RunContext DI with @agent.tool.

Contract Engineer: Submit the SupportResponse template as a "structured output specification" for clients.


References

Pydantic AI official. Structured output with Agent + Pydantic models. FastAPI-style DI. Python 3.10+.


Disclaimer

This article is a secondary explanation based on official Pydantic information. Please treat the official docs as the source of truth for API shapes and supported models. Modify templates according to project confidentiality and contracts. This is for entertainment and summary purposes; use in production is at your own risk.

Edo Tech Kawaraban — Survival Strategy in the AI Era

いいなと思ったら応援しよう!