기본 콘텐츠로 건너뛰기

Pydantic AI Tutorial: Typed Agents and Structured Output

Summary: Pydantic AI is an open-source (MIT) Python agent framework that treats structured output as a first-class type: you pass a Pydantic model as output_type, and result.output comes back validated. This tutorial covers install on Python 3.11+, a first typed agent, tools plus dependency injection, and when to add Pydantic Logfire observability. Plan prices below are only for Logfire's hosted Personal / Team / Growth tiers from the official pricing page — the framework itself has no license fee.

What Pydantic AI is (and is not)

Pydantic AI is the agent framework from the same team behind Pydantic Validation. The docs describe it as a typed, extensible agent loop: swap models with a provider:model string, attach tools, and get structured results that match a Python type. It is not a hosted chatbot product. You run agents in your own process — scripts, APIs, durable workers, or a CLI — and you bring your own model provider credentials (or route through Pydantic AI Gateway).

An Agent is the main unit of work. Conceptually it holds instructions, optional function tools, an optional structured output type, a dependency type constraint, a default model, and optional capabilities. Agents are designed for reuse the way a small FastAPI app is: define one, call run / run_sync many times. Multi-agent patterns (delegation through tools, handoffs, graphs) exist, but you do not need them for a first working extractor.

Official docs live at pydantic.dev/docs/ai (the older ai.pydantic.dev host redirects there). Package name on PyPI is pydantic-ai; current release checked for this post was 2.66.0 under the MIT license.

Install Pydantic AI

Requirements from the install guide: Python 3.11+. Prefer a fresh virtual environment.

Step 1: Create a venv (optional but recommended)

python3 -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate

Step 2: Install the full package

pip install pydantic-ai
# or
uv add pydantic-ai

The full wheel installs the pydantic_ai package plus libraries needed for OpenAI, Anthropic, and Google models, and pulls in CLI, MCP, Evals, Web UI, and Logfire integration extras. To keep a slim environment, use pydantic-ai-slim with only the extras you need, for example pip install "pydantic-ai-slim[openai]" or "pydantic-ai-slim[openai,google,logfire]".

Step 3: Set a provider API key

Pick a model from the Models overview and export the matching environment variable (for OpenAI-style providers that is typically OPENAI_API_KEY). If the provider is missing a key, Pydantic AI raises a clear UserError naming the variable. For unit tests with no network, the docs support Agent('test') via the built-in test model.

Step 4: Confirm import

python -c "from pydantic_ai import Agent; print(Agent)"

Optional examples package: pip install "pydantic-ai[examples]". Optional observability wizard mentioned in the install page: uvx logfire-cli wizard --task pydantic-ai (free Logfire tier; GitHub signup; no credit card).

Your first typed agent with structured output

"Output" in Pydantic AI is the final value from a run — plain text, structured data, an image, or the result of an output function. Structured data is where the framework shines: pass output_type=YourModel and the agent loop forces the model to return data that validates as that type. By default this uses tool calling; you can switch to native or prompted modes when a provider needs it.

Here is the olympics-style example from the Output docs (model id is whatever the docs currently show — always swap to a model you can call):

from pydantic import BaseModel
from pydantic_ai import Agent

class CityLocation(BaseModel):
    city: str
    country: str

agent = Agent('google:gemini-3.8-flash', output_type=CityLocation)
result = agent.run_sync('Where were the olympics held in 2012?')
print(result.output)
# CityLocation(city='London', country='United Kingdom')
print(result.usage)

result.output is a real CityLocation instance, not a JSON string you parse by hand. result.usage exposes token and cost fields when the provider reports them. If validation fails, the framework can retry within the output retry budget (default one retry) before raising.

Ways to run an agent

  • agent.run(...) — async, returns a completed run result.
  • agent.run_sync(...) — sync wrapper for scripts and notebooks.
  • agent.run_stream(...) / run_stream_sync(...) — stream text or structured partials.
  • agent.run_stream_events(...) — async iterator over stream events.
  • agent.iter(...) — step through the underlying graph nodes.

For day-one scripts, run_sync is enough. Inside async tools or nested agent calls, use await agent.run(...) instead of nesting run_sync (that raises a UserError to avoid deadlocks).

Important rename if you follow older blog posts: V1's result_type= became output_type= in V2. A TypeError: unexpected keyword argument 'result_type' means you are on V2 APIs with V1 sample code — change the keyword and read the migration map.

Add a tool and inject dependencies

Tools are ordinary Python functions registered with @agent.tool. Type hints become the argument schema; the docstring becomes the tool description the model sees. Arguments are validated before your function runs.

A compact pattern from the overview (sentiment + a review-fetch tool):

from typing import Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext

class Sentiment(BaseModel):
    label: Literal['positive', 'negative', 'neutral']
    score: float = Field(ge=-1, le=1)

agent = Agent('openai:gpt-6.1-sol', output_type=Sentiment)

@agent.tool
def recent_reviews(ctx: RunContext, product: str) -> list[str]:
    """Fetch recent review snippets for a product."""
    return ['The new release fixed everything I complained about!']

result = agent.run_sync('How are people feeling about the Extract app?')
print(result.output)

Dependencies keep secrets and shared clients out of globals. Declare a type with deps_type=... on the Agent, pass an instance as deps=... on run/run_sync, and read it from RunContext as the first parameter of tools or dynamic instructions. A dataclass holding an API key plus an httpx.AsyncClient is the pattern the Dependencies docs use. In tests, override deps (and models) with Agent.override so you never hit a live LLM.

The roulette-wheel example in the Agents guide shows the same idea with deps_type=int and output_type=bool: the tool compares the player's square to ctx.deps, and the run returns a boolean. That is enough to prove type-safe injection without standing up a database.

When to turn on Logfire (and when not to)

Pydantic AI emits OpenTelemetry spans for agent runs, model requests, and tool calls. Pydantic Logfire is the team's hosted (and optionally self-hosted Enterprise) backend for those traces. Instrumentation is optional: if logfire is installed, configured, and logfire.instrument_pydantic_ai() is called, traces go out; otherwise overhead stays near zero.

Use Logfire (or any OTel backend) when you need to answer: why was this run slow, expensive, or wrong? The troubleshooting guide's first advice for non-crashing misbehaviour is to inspect what the model actually saw — instructions, tool schemas, messages, and retries. Logfire makes that a clickable trace; without a backend you can still call result.all_messages() or wrap failures in capture_run_messages().

Minimal hand setup from the Logfire integration page:

uvx logfire-cli auth
uvx logfire-cli init
# then in code:
import logfire
from pydantic_ai import Agent

logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent('openai:gpt-6.1-sol', name='hello_world_agent',
              instructions='Be concise, reply with one sentence.')
print(agent.run_sync('Where does "hello world" come from?').output)

Skip Logfire when you are only practicing with Agent('test'), or when your org already ships OTel elsewhere — the same spans work with other backends. Pydantic AI Gateway (one key, spend limits, failover) is a separate optional layer managed through Logfire; you do not need Gateway to use the open-source Agent API.

Logfire Personal vs Team vs Growth

The open-source pydantic-ai package is free under MIT. The comparison below is only for Pydantic's hosted Logfire / AI observability plans as shown on pydantic.dev/pricing on 2026-11-06. Every listed plan includes a $20/mo usage credit covering 10 million spans, logs, or metrics. Personal hard-caps at that included amount ($0 bill). Team and Growth bill overage at $2 per million additional records, and you can set a price cap.

Capability Personal Team Growth
Base cost Free, forever (no credit card) $49/mo $249/mo
Included telemetry 10M records/mo, hard-capped at $0 10M included, then $2/M 10M included, then $2/M
Seats & guests 1 seat + 2 read-only guests 5 seats included ($25/extra seat) + 10 read-only guests Unlimited seats and guests
Projects & retention 3 projects · 30-day retention 5 projects Unlimited projects · up to 90-day retention
AI extras Monitor agents/services/hosts; AI Gateway BYOK (up to 3 credentials) Adds AI output evaluations + human review; Gateway BYOK (up to 3) Everything in Team; unlimited BYOK; priority support + boilerplate BAA

Enterprise is custom (cloud, dedicated, or self-hosted) and is outside this table. Personal is enough for local debugging of Pydantic AI agents; move to Team when several people need write access or you need paid overage instead of an ingest pause.

Editor's note

Who this is for: Python developers who already use Pydantic models and want agents that return typed objects, not free-form chat. Especially useful for extraction, classification, and tool-using workflows you will unit-test.

Who this is not for: people looking for a no-code agent builder, or teams that only need a single chat completion without tools or schemas. Also skip Logfire pricing worry if you only need the OSS library.

Gotchas from the official troubleshooting docs:

  • Missing API key → set the env var named in the UserError, or pass api_key= to the provider.
  • result_type= TypeError → rename to output_type= (V2).
  • Tool exceeded max retries (UnexpectedModelBehavior) → improve the tool docstring / field descriptions, or raise retries on the tool; inspect messages with capture_run_messages().
  • Nested run_sync inside a sync tool → make the tool async and await agent.run(...).
  • RuntimeError: Event loop is closed → recreate the agent/model (and HTTP client) after a loop is closed; do not reuse a model bound to a dead connection pool.

FAQ

Is Pydantic AI free?
The open-source framework on PyPI is MIT-licensed and free to use. You still pay your LLM provider for tokens. Pydantic Logfire's Personal plan is free with a hard 10M records/month cap; Team and Growth are paid hosted plans.

Do I have to use Logfire to use Pydantic AI?
No. Logfire integration is optional. Spans are plain OpenTelemetry, so any OTel backend works. Many tutorials never call logfire.configure().

How is this different from CrewAI?
CrewAI focuses on multi-agent crews and flows as product units. Pydantic AI centers on a typed Python Agent with Pydantic output_type, dependency injection, and first-party OTel. You can combine ideas, but the APIs and project layout are different — start from each project's own docs rather than translating one-to-one.

Related posts on lightmind24

Start with pip install pydantic-ai, one Pydantic model as output_type, and a single run_sync call — then add tools, deps, and traces only when the first typed result is green.

Last verified: 2026-11-06
Sources: Pydantic AI overview, Installation, Agents, Output, Dependencies, Function tools, Logfire integration, Troubleshooting, Pricing, MIT LICENSE, PyPI pydantic-ai 2.66.0.

Image credit: screenshots of public pydantic.dev docs and pricing pages captured for this post; official Logfire weather-agent trace image from Pydantic AI docs (pydantic.dev/docs/ai/img/). Includes no AI-generated image.

Uploaded Image Uploaded Image Uploaded Image Uploaded Image

댓글

이 블로그의 인기 게시물

브루(Vrew) 요금제 정리: 무료 200크레딧으로 어디까지 쓸 수 있나

요약: 영상 자막 편집기 브루(Vrew)는 2026년 4월 22일부터 기능별 사용량 대신 '통합 크레딧' 하나로 요금을 매겨요. 무료 플랜은 매달 200크레딧이 들어오는데, 음성 분석(자동 자막)만 쓰면 최대 200분 분량이라 짧은 영상 몇 편은 충분하지만, 영상 초반의 Vrew 마크를 지우려면 유료 플랜이 필요해요. 이 글은 브루 공식 가격 페이지와 고객센터 공지를 2026년 10월 23일에 다시 확인해, 크레딧 계산법과 플랜 고르는 기준을 정리했어요. 목차 브루 요금 구조: 통합 크레딧이란 1크레딧으로 할 수 있는 일 무료 플랜으로 되는 것과 안 되는 것 유료 플랜 4종 비교표 월 구독·연 구독·기간 이용권, 무엇이 이득일까 상황별 추천: 학생·직장인·유튜버 크레딧이 모자랄 때: 사용 기록 지우개 업그레이드·환불 전에 알아둘 규칙 운영자 메모, 자주 묻는 질문 1. 브루 요금 구조: 통합 크레딧이란 예전 브루는 플랜마다 음성 분석 몇 분, AI 목소리 몇 자, 번역 몇 자처럼 기능별 한도를 따로 줬어요. 그런데 보이저엑스(브루 운영사)가 실제 이용 데이터를 보니 한두 가지 기능만 집중해서 쓰는 사람이 훨씬 많았다고 해요. 그래서 2026년 4월 22일 업데이트부터는 플랜마다 정해진 크레딧을 받고, 어떤 기능에 쓸지는 내가 정하는 방식으로 바뀌었어요. 플랜별 매달 지급량은 Free 200 · Light 2,000 · Standard 10,000 · Business 12,000크레딧 이에요. 공식 공지에 따르면 무료 사용자는 매달 1일에, 유료 사용자는 매월 결제일에 충전되고, 남은 크레딧은 다음 달로 넘어가지 않아요. 바뀐 뒤 무엇이 좋아졌나 공지에 나온 예시가 이해하기 쉬워요. Standard 플랜에서 AI 목소리만 쓰면 예전에는 최대 50만 자였지만, 지금은 1만 크레딧을 모두 AI 목소리에 몰아 쓸 수 있어 최대 100만 자가 돼요. 반대로 여러 기능을 골고루 쓰는 사람은 크레딧이 기능끼리 ...

에이닷 전화 vs 익시오: 통화 녹음·AI 요약, 내 통신사·폰에 맞는 앱 고르기

요약: 통화 녹음과 AI 요약을 쓰고 싶다면 먼저 내 통신사와 휴대폰 종류부터 확인해야 해요. LG유플러스 고객은 무료 앱 익시오, SKT 고객은 에이닷 전화가 가장 기능이 많고, 다른 통신사의 아이폰 사용자는 iOS에 들어 있는 기본 통화 녹음·전사 기능이 현실적인 선택이에요. 이 글은 2026-10-30에 SKT·LG유플러스·Apple 공식 페이지와 도움말을 직접 확인해 세 가지를 비교했어요. 왜 '앱 기능'보다 '내 조건'을 먼저 봐야 할까요 통화 요약 앱 비교 글을 보면 기능 목록부터 나열하는 경우가 많아요. 그런데 실제로 써 보려는 사람에게 가장 먼저 걸리는 건 기능이 아니라 이용 조건 이에요. 익시오는 LG유플러스 고객 전용이고, 에이닷 전화는 누구나 설치할 수 있지만 통역콜·baro 같은 기능은 SKT 고객에게만 열려 있어요. 아이폰은 운영체제 구조상 앱이 통화를 마음대로 녹음하기 어려워서, 통신사 앱이 안 되면 iOS 기본 기능에 기대야 해요. 그래서 이 글은 "어떤 앱이 제일 좋은가"보다 "내 통신사·내 폰에서 무엇을 쓸 수 있나" 순서로 정리했어요. 기능 차이는 그다음이에요. 한눈에 비교: 에이닷 전화 vs 익시오 vs 아이폰 기본 통화 녹음 구분 에이닷 전화 (SKT) 익시오 ixi-O (LG유플러스) 아이폰 기본 통화 녹음 (Apple) 누가 쓸 수 있나 통신사 구분 없이 앱 설치 가능. 단, 통역콜·baro·그룹통화 발신 등은 SKT 고객 전용 U+ 모바일 고객. 타 통신사, 만 14세 미만, 선불요금제 고객은 제한 (공식 사이트 FAQ상 알뜰폰 중 KB리브엠은 예외) 지원 국가·언어의 iPhone 사용자. 1명과 통화할 때만 녹음 가능 지원 OS·기기 Android 10 이상, iOS 16 이상 iOS 17 이상 iPhone 12 이상 / Android...

타입캐스트 vs 클로바더빙: 수익 나는 채널에 쓸 때 무료·유료 조건 비교

요약 타입캐스트와 클로바더빙은 둘 다 글만 입력하면 한국어 AI 목소리를 만들어 주는 서비스지만, 무료로 쓸 수 있는 범위가 꽤 다릅니다. 클로바더빙 무료는 매달 15,000자까지 쓸 수 있는 대신 수익이 생기는 채널에는 쓸 수 없고, 타입캐스트 무료는 처음에 주는 약 5분 분량의 다운로드로 끝나는 체험판에 가깝습니다. 광고 수익이 붙은 유튜브나 쇼핑몰 영상에 넣을 목소리라면 처음부터 유료 플랜 조건을 보고 고르는 편이 안전합니다. 왜 이 두 서비스를 같이 비교하나 쇼츠 내레이션, 수업 자료 더빙, 상품 소개 영상처럼 "내 목소리 대신 AI 목소리"가 필요할 때 한국 사용자들이 가장 많이 찾는 곳이 네오사피엔스의 타입캐스트 와 네이버의 클로바더빙 입니다. 기능 소개만 보면 비슷해 보이지만, 실제로 문제가 되는 건 음질보다 "이 목소리를 내 채널에 써도 되나" 입니다. 그래서 이 글은 기능 나열보다 무료 사용 범위, 출처 표기 의무, 유료 플랜 가격과 다운로드 한도를 중심으로 정리했습니다. 모든 수치는 2026년 10월 25일에 두 서비스의 공식 요금 페이지와 고객센터 도움말에서 직접 다시 확인한 내용입니다. 한눈에 보는 비교표 항목 타입캐스트 무료 타입캐스트 베이직 클로바더빙 Free 클로바더빙 Standard 월 요금 0원 9,900원 (연간 결제 시 10% 할인) 0원 19,900원 (네이버 클라우드 플랫폼에서 결제) 무료·포함 사용량 음성 생성·재생 무제한, 다운로드는 최초 3,000크레딧(약 5분) 1회 지급 월 30,000크레딧(약 60분) 월 15,000자, 다운로드 월 20회, 프로젝트 누적 5개 (매월 1일 갱신) 월 30,000자, 다운로드 월 40회, 프로젝트 누적 20개 쓸 수 있...