Back to Opik

Using Opik with Pydantic AI

apps/opik-documentation/documentation/docs/cookbook/pydantic-ai.ipynb

2.0.24-52622.5 KB
Original Source

Using Opik with Pydantic AI

Opik integrates with Pydantic AI to provide a simple way to log your agent calls.

Creating an account on Comet.com

Comet provides a hosted version of the Opik platform, simply create an account and grab you API Key.

You can also run the Opik platform locally, see the installation guide for more information.

Setting up the logging

Pydantic AI uses the logfire library to log traces to Opik. Before logging our agent calls, we will configure the integration by installing the required libraries and setting the correct environment variables:

python
import os

# Install the required libraries
%pip install --upgrade --quiet pydantic-ai logfire 'logfire[httpx]' nest_asyncio

# Configure the logging to Opik Cloud
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = (
    "https://www.comet.com/opik/api/v1/private/otel"
)
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = (
    "Authorization=your-api-key,Comet-Workspace=default"  # Make sure to replace your API key
)

# If you are using a self-hosted instance, you can use:
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "http://localhost:5173/api/v1/private/otel"

Now that everything is configured correctly, we can enable the logging:

python
import logfire

logfire.configure(
    send_to_logfire=False,
)
logfire.instrument_httpx(capture_all=True)

Logging your first trace

Before we log our first trace, we are going to configure the environment and ensure the code runs in a Notebook

python
import nest_asyncio
import os
import getpass

if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")

nest_asyncio.apply()
python
import os

from pydantic_ai import Agent

agent = Agent(
    "openai:gpt-4o",
    system_prompt="Be concise, reply with one sentence.",
)

result = agent.run_sync('Where does "hello world" come from?')
print(result.data)

Note: This screenshot was taken for a more complex agent but you should see a very trace.