Pydantic AI — Integration Guide
Step-by-step developer guide for instrumenting a Pydantic AI application.
Pydantic AI Integration Guide (Developer)
This is the complete, step-by-step guide for a developer instrumenting
a real Pydantic AI application with ADG.
It reflects the adapter as actually validated against a real,
independently-authored open-source application (ggozad/oterm) — not
just this project's own hand-built demos — see "Real-world validation"
below for what that means in practice and why it matters to you.
For the conceptual question "which of my own objects/calls should become a Trace vs. an Activity vs. an Artifact vs. a Resource?" — see the Ontology Mapping Decision Guide first. This guide assumes you already know the answer and shows the Pydantic-AI-specific mechanics of acting on it.
1. The one-line integration
Pydantic AI's own documented observability mechanism is
OpenTelemetry itself: "Pydantic AI emits OpenTelemetry traces of every
run, model request and tool call," following the
OpenTelemetry Semantic Conventions for Generative AI systems.
This adapter attaches an OTel SpanProcessor to observe exactly that
— no wrapping of your Agent/Runner calls, no subclassing, no
changes to your agent's own tools/output-validators:
from adg.adapters.pydantic_ai import instrument_tracing
instrument_tracing()
result = agent.run_sync(user_input)
instrument_tracing():
- Installs (or reuses, see "Composable path" below) a real
opentelemetry.sdk.trace.TracerProvider. - Attaches an
ADGSpanProcessorto it, wired with ADG's default transport (console by default; your Facet platform contact can help configure REST/production transport). - Calls Pydantic AI's own
Agent.instrument_all()— the framework's own public API for turning on its OTel emission, not an ADG internal.
Composable path (you already run OpenTelemetry/Logfire)
from adg.adapters.pydantic_ai import instrument_tracing
instrument_tracing(tracer_provider=my_existing_provider)
This only adds ADGSpanProcessor to your existing provider —
composing with, never replacing, whatever other processors/exporters
you already have attached (e.g. Pydantic Logfire, a Jaeger/Tempo
exporter). Pass instrument_all=False if you've already called
Agent.instrument_all(...)/logfire.instrument_pydantic_ai()
yourself with your own InstrumentationSettings — ADGSpanProcessor
observes whatever spans Pydantic AI emits regardless of who turned on
instrumentation or with what settings.
Lower-level path (full manual control)
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.trace import set_tracer_provider
from pydantic_ai import Agent
from adg.adapters.pydantic_ai import ADGSpanProcessor
provider = TracerProvider()
provider.add_span_processor(ADGSpanProcessor())
set_tracer_provider(provider)
Agent.instrument_all()
Customizing what gets captured
All the same optional parameters every other ADG adapter supports are
available on instrument_tracing(...):
from pathlib import Path
from adg.adapters.pydantic_ai import instrument_tracing
from adg.artifact_types import load_artifact_type_mapping
artifact_type_mapping = load_artifact_type_mapping(
Path(__file__).parent / "artifact_types.toml"
)
instrument_tracing(artifact_type_mapper=artifact_type_mapping)
See the Artifact Type Mapping guide for the
full artifact_types.toml format — this classifies your agent's own
outcome Artifacts (e.g. "this tool's return value is a DECISION")
without ADG ever guessing at your business semantics itself.
No zero-code mode (yet)
Unlike LangGraph, Semantic Kernel, and the Direct LLM API, Pydantic AI
has no zero-code sitecustomize patch today — there is no
pydantic_ai-specific entry in adg.zero_code._PATCHERS. Setting
ADG_ZERO_CODE_FRAMEWORKS=pydantic_ai is a no-op today (it would log
an "unknown framework" warning and do nothing). Code-level
instrumentation (§1 above, one call to instrument_tracing()) is the
only supported integration path today. This is on our roadmap if
your customer specifically needs zero-code.
2. How Pydantic AI's OTel spans map onto the ontology
This is the only adapter in this codebase (besides any future
sibling built on the same shared core) that observes a framework via
its own standards-based OpenTelemetry emission rather than a
framework-proprietary callback protocol (LangGraph/LangChain/Semantic
Kernel's own dict-state-diffing, or the OpenAI Agents SDK's own typed
SpanData). The framework-agnostic ingestion engine —
adg.adapters.otel_genai — dispatches on the published
gen_ai.operation.name OTel attribute (an industry-standard fact, not
a Pydantic-AI-specific guess) — see that package's own module
docstring for the full rationale and §4 below for why this reuse
matters.
OTel span (gen_ai.operation.name / span name) |
Ontology entity | Notes |
|---|---|---|
The outermost invoke_agent <name> span (or legacy "agent run", see §3) |
Trace | One per agent.run()/run_sync() call. |
| Every span Pydantic AI emits, nested or not | Activity | invoke_agent, chat (one per model request, including retries), execute_tool (one per tool call) — nesting via OTel parent-child span relationships becomes Lineage CONTAINS. |
chat (a model request) |
Artifact (the completion, if populated) + Resource ("llm"-typed, with usage metadata) |
One chat span per model round-trip — a retried output-validator call (§4) produces a second nested chat span in the same Trace, not a second Trace. |
execute_tool <name> (or legacy "running tool", see §3) |
Artifact (the tool's return value, named after the tool) + Resource ("tool"-typed) |
Proven against a real custom tool during real-world validation (oterm's _add tool — see §5). |
| An error recorded on any span during the run | TraceFailed (instead of TraceCompleted) |
Including pydantic_ai.exceptions.UnexpectedModelBehavior from an exhausted output-validator retry budget — see §4. |
3. One documented compatibility concern: two attribute shapes across Pydantic AI's own release history
Pydantic AI's own instrumentation has shipped two different attribute shapes across its release history (confirmed directly, against real installs of both):
- Releases requiring
pydantic>=2.12(1.65.0+, including the current 2.x line): the modern OTel GenAI semantic-convention shape this adapter is primarily written against —gen_ai.operation.nameon every span,gen_ai.tool.call.resultfor tool output. - Releases still on
pydantic>=2.10(up to and including 1.64.x — the floor this project's ownpyproject.tomlpins): only thechatspan carriesgen_ai.operation.name; the root run span's name is either the legacy literal"agent run"or (withInstrumentationSettings(version=3|4)) the modern"invoke_agent <name>", but never carries the operation attribute itself either way. Tool calls are similarly named either the legacy"running tool"or the modern"execute_tool <name>", wrapped in an extra"running tools"container span with no 2.x equivalent, and the result may live undertool_responserather thangen_ai.tool.call.result.
The adapter's own _normalize_attrs shim handles
both shapes transparently, normalizing the older one onto the newer
one's attribute names once, rather than teaching the shared
adg.adapters.otel_genai extractors two dialects. You do not need
to know or care which shape your installed pydantic-ai-slim version
emits — instrument_tracing() handles both identically.
4. Guardrails: the output-validator mechanism
Pydantic AI's first-class guardrail primitive is
@agent.output_validator, raising pydantic_ai.ModelRetry to reject
an output and force a retry (as opposed to the OpenAI Agents SDK's
separate input_guardrail/output_guardrail span type — Pydantic AI
has no equivalent dedicated span type of its own):
from pydantic_ai import Agent, ModelRetry
agent = Agent("openai:gpt-4o", output_type=str)
@agent.output_validator
def no_speculation(output: str) -> str:
if "i think" in output.lower():
raise ModelRetry("Speculative language is not allowed; cite a source.")
return output
Confirmed directly via OTel span inspection (based on investigation documented against our own internal test applications):
- A retry produces no distinct Artifact of its own — only a
second nested
chatspan inside the sameinvoke_agentTrace (the validator's rejection message is appended to the root span's ownpydantic_ai.all_messagesattribute, not surfaced as a separate ontology entity). - Exhausting the retry budget (
retries=1by default) raises a genuinepydantic_ai.exceptions.UnexpectedModelBehavior, which sets the root span's OTel status toERROR— captured correctly asTraceFailedby the adapter's existing, generic error handling (inherited unchanged fromadg.adapters.otel_genai), with zero adapter changes required to support this.
If you want a visible Artifact per guardrail verdict (the way the
OpenAI Agents SDK's dedicated "guardrail" span type gives you
automatically), do your own check inside a plain tool instead (see
our own internal test applications' check_no_pii for a worked,
real-Presidio-backed example) — a tool call's return value is
always captured as its own Artifact (§2's table).
5. Real-world validation: what this adapter was actually proven against
Beyond this project's own two hand-built internal test applications, the adapter was validated against a real, independently-authored open-source application:
ggozad/oterm ("the terminal
client for LLMs," MIT license, 2.4k★, published on PyPI as oterm) —
its real oterm.agent.get_agent() entry point constructs a genuine
pydantic_ai.Agent with real provider resolution (Ollama/
OpenAI-compatible/Grok), profile merging, and capability fitting. This
was validated via a pip-install-based demo (not vendored — oterm
publishes its own PyPI package, same posture as LangChain's
gpt_researcher_integration).
get_agent()'s real, unmodified code was run with a real custom tool
and Pydantic AI's own documented Agent.run_sync(prompt, model=scripted_model) override parameter (a cleaner, zero-monkeypatch
way to substitute a deterministic scripted model than the OpenAI
Agents SDK's own cs_agents_integration validation needed) — through
ADGSpanProcessor — capturing a fully correct event shape (1 Trace,
3 Activities, 3 Artifacts, 3 Resources, 6 Lineage).
Result: zero changes to the adapter were needed.
A genuinely useful side finding: both oterm and a second
candidate real-world target investigated (ggozad/haiku.rag) require
pydantic-ai-slim>=2.59.0 — a much newer release than this project's
own 1.60.0 floor. Running oterm's real code against that newer
release through this adapter (in an isolated environment) empirically
confirms forward compatibility with Pydantic AI's 2.x line requires
zero further adapter changes — the _normalize_attrs shim (§3)
already anticipated and handles exactly this attribute-shape
difference.
6. Where to go next
- The Ontology Mapping Decision Guide — how to decide ontology boundaries for anything Pydantic AI's own instrumentation doesn't already structure for you.
- The Artifact Type Mapping guide — classifying your agent's own outcome Artifacts.
- The Field Mapping guide — vocabulary normalization (mapping your own field names onto canonical projection fields).
- Your Facet platform contact — production transport, monitoring, and scaling for Pydantic-AI-sourced traces.
- The framework-agnostic OTel GenAI semantic-convention core this adapter specializes — the same core any future OTel-GenAI-semconv-emitting framework adapter (AWS Strands Agents, LiteLLM — this is on our roadmap) will reuse unmodified.