OpenInference PydanticAI Instrumentation
The `openinference-instrumentation-pydantic-ai` library provides OpenTelemetry instrumentation for the `pydantic-ai` library. It automatically captures and exports telemetry data (traces, spans) for AI model calls made using `pydantic-ai` models, allowing for observability into AI application workflows. The current version is 0.1.12, and it is part of the larger OpenInference project which has a frequent release cadence, often releasing updates across its various instrumentation packages.
Common errors
-
ModuleNotFoundError: No module named 'pydantic_ai'
cause The `pydantic-ai` library, which this instrumentation targets, is not installed in your environment.fixInstall `pydantic-ai` using `pip install pydantic-ai`. -
ModuleNotFoundError: No module named 'openinference.instrumentation.pydantic_ai'
cause The `openinference-instrumentation-pydantic-ai` library itself is not installed.fixInstall the instrumentation package using `pip install openinference-instrumentation-pydantic-ai`. -
TypeError: 'ABCMeta' object is not subscriptable
cause This error can occur if you have a version conflict between `pydantic` and `pydantic-ai`, or if `pydantic-ai` is installed with an unsupported `pydantic` version. `pydantic-ai` often has strict Pydantic version requirements.fixCheck the `pydantic-ai` package's dependencies for its compatible `pydantic` versions and ensure your environment matches. You might need to reinstall `pydantic-ai` or `pydantic` with specific versions, e.g., `pip install 'pydantic<2.0.0'` if `pydantic-ai` is not Pydantic V2 compatible. -
No traces appear in the console or exporter logs.
cause OpenTelemetry is either not correctly configured, or the `instrument()` method was called too late. The `TracerProvider` and `SpanProcessor` must be set up before `PydanticAIInstrumentor().instrument()` and before any `pydantic-ai` calls are made.fixVerify that `trace.set_tracer_provider()` is called with a configured `TracerProvider` and `SpanProcessor` early in your application's startup. Ensure `PydanticAIInstrumentor().instrument()` is called directly after OpenTelemetry setup.
Warnings
- gotcha OpenTelemetry must be configured (TracerProvider, SpanProcessor, Exporter) before `PydanticAIInstrumentor().instrument()` is called to ensure traces are captured and exported correctly. Failure to do so will result in no telemetry data being emitted.
- breaking The `pydantic-ai` library itself is in early development and can have breaking changes, as indicated by its minor version increments. `openinference-instrumentation-pydantic-ai` explicitly pins `pydantic-ai` to a narrow version range (`>=0.0.17,<0.0.21`). Upgrading `pydantic-ai` outside this range without upgrading the instrumentation package may lead to unexpected behavior or `AttributeError`.
- gotcha Instrumentation might not capture all details if the underlying `pydantic-ai` model uses custom or unsupported LLM providers or complex callbacks that are not directly patched by the instrumentor. The instrumentation primarily targets the core `pydantic-ai` generation methods.
Install
-
pip install openinference-instrumentation-pydantic-ai -
pip install pydantic-ai openai opentelemetry-sdk opentelemetry-exporter-otlp
Imports
- PydanticAIInstrumentor
from openinference.instrumentation.pydantic_ai import PydanticAIInstrumentor
Quickstart
import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter
from openinference.instrumentation.pydantic_ai import PydanticAIInstrumentor
# Configure OpenTelemetry to print traces to the console
resource = Resource.create({"service.name": "my-pydantic-ai-app"})
tracer_provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)
# Instrument pydantic-ai
PydanticAIInstrumentor().instrument()
# Ensure an OpenAI API key is available for pydantic-ai to function
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "sk-YOUR_OPENAI_KEY_HERE")
# Use pydantic-ai
from pydantic import BaseModel
from pydantic_ai import AIModel
class Recipe(AIModel):
ingredients: list[str]
instructions: list[str]
prep_time_minutes: int
def main():
print("\n--- Generating a recipe with PydanticAI ---\n")
with trace.get_tracer(__name__).start_as_current_span("generate_recipe"):
try:
recipe = Recipe.generate("A simple pasta dish for two.")
print(f"Ingredients: {recipe.ingredients}")
print(f"Instructions: {recipe.instructions}")
print(f"Prep time: {recipe.prep_time_minutes} minutes\n")
except Exception as e:
print(f"Error generating recipe: {e}")
print("Please ensure OPENAI_API_KEY is set and valid, and required dependencies are installed.")
if __name__ == "__main__":
main()