OpenInference PydanticAI Instrumentation

0.1.12 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument `pydantic-ai` calls using `OpenInferencePydanticAIInstrumentor`. It sets up a console exporter for OpenTelemetry, instruments `pydantic-ai`, and then uses a simple `AIModel` to generate a recipe. Ensure `OPENAI_API_KEY` is set in your environment or replace the placeholder. You'll need `pydantic-ai`, `openai`, `opentelemetry-sdk`, and `opentelemetry-exporter-otlp` installed for this to run.

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()

view raw JSON →