GuidesCookbooksObservability for Pydantic AI with Langfuse Integration
This is a Jupyter notebook

Integrate Langfuse with Pydantic AI

This notebook provides a step-by-step guide on integrating Langfuse with Pydantic AI to achieve observability and debugging for your LLM applications.

About PydanticAI: PydanticAI is a Python agent framework designed to simplify the development of production-grade generative AI applications. It brings the same type-safety, ergonomic API design, and developer experience found in FastAPI to the world of GenAI app development.

What is Langfuse? Langfuse is an open-source LLM engineering platform. It offers tracing and monitoring capabilities for AI applications. Langfuse helps developers debug, analyze, and optimize their AI systems by providing detailed insights and integrating with a wide array of tools and Pydantic AIs through native integrations, OpenTelemetry, and dedicated SDKs.

Getting Started

Let’s walk through a practical example of using Pydantic AI and integrating it with Langfuse for comprehensive tracing.

Step 1: Install Dependencies

⚠️

Note: This notebook utilizes the Langfuse OTel Python SDK v3. For users of Python SDK v2, please refer to our legacy Pydantic AI integration guide.

%pip install langfuse pydantic-ai -U

Step 2: Configure Langfuse SDK

Next, set up your Langfuse API keys. You can get these keys by signing up for a free Langfuse Cloud account or by self-hosting Langfuse. These environment variables are essential for the Langfuse client to authenticate and send data to your Langfuse project.

import os
 
# Get keys for your project from the project settings page: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." 
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." 
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region
 
# Your OpenAI key
os.environ["OPENAI_API_KEY"] = "sk-proj-..." 

With the environment variables set, we can now initialize the Langfuse client. get_client() initializes the Langfuse client using the credentials provided in the environment variables.

from langfuse import get_client
 
langfuse = get_client()
 
# Verify connection
if langfuse.auth_check():
    print("Langfuse client is authenticated and ready!")
else:
    print("Authentication failed. Please check your credentials and host.")
 

Step 3: Initialize Pydantic AI Instrumentation

Now, we initialize the Pydantic AI Instrumentation. This automatically captures Pydantic AI operations and exports OpenTelemetry (OTel) spans to Langfuse.

from pydantic_ai.agent import Agent
 
# Initialize Pydantic AI instrumentation
Agent.instrument_all()

Step 4: Basic Pydantic AI Application

Finally, run your Pydantic AI agent and generate trace data that will be sent to Langfuse. In the example below, the agent is executed with a dependency value (the winning square) and natural language input. The output from the tool function is then printed.

Make sure to pass instrument=True while configuring the Agent.

from pydantic_ai import Agent, RunContext
 
roulette_agent = Agent(
    'openai:gpt-4o',
    deps_type=int,
    result_type=bool,
    system_prompt=(
        'Use the `roulette_wheel` function to see if the '
        'customer has won based on the number they provide.'
    ),
    instrument=True
)
 
@roulette_agent.tool
async def roulette_wheel(ctx: RunContext[int], square: int) -> str:
    """check if the square is a winner"""
    return 'winner' if square == ctx.deps else 'loser'
# Run the agent - using await since we're in a Jupyter notebook
success_number = 18
result = await roulette_agent.run('Put my money on square eighteen', deps=success_number)
print(result.output)

Step 5: View Traces in Langfuse

After executing the application, navigate to your Langfuse Trace Table. You will find detailed traces of the application’s execution, providing insights into the LLM calls, retrieval operations, inputs, outputs, and performance metrics.

Example Trace in Langfuse

Example Trace in Langfuse

Add Additional Attributes

Langfuse allows you to pass additional attributes to your spans. These can include user_id, tags, session_id, and custom metadata. Enriching traces with these details is important for analysis, debugging, and monitoring of your application’s behavior across different users or sessions.

The following code demonstrates how to start a custom span with langfuse.start_as_current_span and then update the trace associated with this span using span.update_trace().

→ Learn more about Updating Trace and Span Attributes.

# Create a simple question-answering agent
qa_agent = Agent(
    'openai:gpt-4o',
    system_prompt='You are a helpful assistant that answers questions clearly and concisely.',
    instrument=True
)
 
with langfuse.start_as_current_span(
    name="pydantic-ai-qa-trace",
    ) as span:
    
    # Run your application here
    question = "What is Langfuse?"
    response = await qa_agent.run(question)
    print(response.output)
 
    # Pass additional attributes to the span
    span.update_trace(
        input=question,
        output=response.output,
        user_id="user_123",
        session_id="session_abc",
        tags=["dev", "pydantic-ai"],
        metadata={"email": "[email protected]"},
        version="1.0.0"
        )
 
# Flush events in short-lived applications
langfuse.flush()
 

Score Traces and Spans

Langfuse lets you ingest custom scores for individual spans or entire traces. This scoring workflow enables you to implement custom quality checks at runtime or facilitate human-in-the-loop evaluation processes.

In the example below, we demonstrate how to score a specific span for relevance (a numeric score) and the overall trace for feedback (a categorical score). This helps in systematically assessing and improving your application.

→ Learn more about Custom Scores in Langfuse.

with langfuse.start_as_current_span(
    name="pydantic-ai-scored-trace",
    ) as span:
    
    # Run your application here
    question = "What is Langfuse?"
    response = await qa_agent.run(question)
    print(response.output)
    
    # Score this specific span
    span.score(name="relevance", value=0.9, data_type="NUMERIC")
 
    # Score the overall trace
    span.score_trace(name="feedback", value="positive", data_type="CATEGORICAL")
 
# Flush events in short-lived applications
langfuse.flush()
 

Manage Prompts with Langfuse

Langfuse Prompt Management allows you to collaboratively create, version, and deploy prompts. You can manage prompts either through the Langfuse SDK or directly within the Langfuse UI. These managed prompts can then be fetched into your application at runtime.

The code below illustrates fetching a prompt named answer-question from Langfuse, compiling it with an input variable (country), and then using this compiled prompt in the application.

→ Get started with Langfuse Prompt Management.

🔗

Note: Linking the Langfuse Prompt and the Generation is currently not possible. This is on our roadmap and we are tracking this here.

# Fetch the prompt from langfuse
langfuse_prompt = langfuse.get_prompt(name="answer-question")
 
# Compile the prompt with the input
compiled_prompt = langfuse_prompt.compile(country = "France")
 
# Run your application
with langfuse.start_as_current_span(
    name="pydantic-ai-prompt-trace",
    ) as span:
    
    # Run your application here with the compiled prompt
    response = await qa_agent.run(compiled_prompt)
    print(response.output)
 
# Flush events in short-lived applications
langfuse.flush()

Dataset Experiments

Offline evaluation using datasets is a critical part of the LLM development lifecycle. Langfuse supports this through Dataset Experiments. The typical workflow involves:

  1. Benchmark Dataset: Defining a dataset with input prompts and their corresponding expected outputs.
  2. Application Run: Running your LLM application against each item in the dataset.
  3. Evaluation: Comparing the generated outputs against the expected results or using other scoring mechanisms (e.g., model-based evaluation) to assess performance.

The following example demonstrates how to use a pre-existing dataset containing countries and their capitals to run an experiment.

→ Learn more about Langfuse Dataset Experiments.

from langfuse import get_client
 
langfuse = get_client()
 
# Fetch an existing dataset
dataset = langfuse.get_dataset(name="capital_cities_11")
for item in dataset.items:
    print(f"Input: {item.input['country']}, Expected Output: {item.expected_output}")
 

Next, we iterate through each item in the dataset, run our Pydantic AI application (your_application) with the item’s input, and log the results as a run associated with that dataset item in Langfuse. This allows for structured evaluation and comparison of different application versions or prompt configurations.

The item.run() context manager is used to create a new trace for each dataset item processed in the experiment. Optionally you can score the dataset runs.

from langfuse import get_client
 
langfuse = get_client()
dataset_name = "capital_cities_11"
current_run_name = "capital_cities_run-pydantic-ai_01" # Identifies this specific evaluation run
current_run_metadata={"model_provider": "OpenAI", "temperature_setting": 0.7}
current_run_description="Evaluation run for Q&A model on June 4th"
 
# Define your application function using Pydantic AI agent
async def your_application(question):
    with langfuse.start_as_current_span(name="pydantic-ai-trace") as span:
 
        response = await qa_agent.run(question)
        print(response.output)
 
        # Update the trace with the input and output
        span.update_trace(
            input=question,
            output=response.output,
        )
 
        return response.output
 
dataset = langfuse.get_dataset(name=dataset_name) # Fetch your pre-populated dataset
 
for item in dataset.items:
    print(f"Running evaluation for item: {item.id} (Input: {item.input['country']})")
 
    # Use the item.run() context manager
    with item.run(
        run_name=current_run_name,
        run_metadata=current_run_metadata,
        run_description=current_run_description
    ) as root_span: 
        # All subsequent langfuse operations within this block are part of this trace.
        generated_answer = await your_application(
            question="What is the capital of " + item.input["country"] + "? Just answer with the name of the city.",
        )
 
        # Optionally, score the result against the expected output
        if item.expected_output and generated_answer == item.expected_output:
            root_span.score_trace(name="exact_match", value=1.0)
        else:
            root_span.score_trace(name="exact_match", value=0.0)
 
print(f"\nFinished processing dataset '{dataset_name}' for run '{current_run_name}'.")
 

Explore More Langfuse Features

Langfuse offers more features to enhance your LLM development and observability workflow:

Was this page helpful?