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:

1import os
2
3# Install the required libraries
4%pip install --upgrade --quiet pydantic-ai logfire 'logfire[httpx]' nest_asyncio
5
6# Configure the logging to Opik Cloud
7os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = (
8 "https://www.comet.com/opik/api/v1/private/otel"
9)
10os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = (
11 "Authorization=your-api-key,Comet-Workspace=default" # Make sure to replace your API key
12)
13
14# If you are using a self-hosted instance, you can use:
15# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "http://localhost:5173/api/v1/private/otel"

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

1import logfire
2
3logfire.configure(
4 send_to_logfire=False,
5)
6logfire.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

1import nest_asyncio
2import os
3import getpass
4
5if "OPENAI_API_KEY" not in os.environ:
6 os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
7
8nest_asyncio.apply()
1import os
2
3from pydantic_ai import Agent
4
5agent = Agent(
6 "openai:gpt-4o",
7 system_prompt="Be concise, reply with one sentence.",
8)
9
10result = agent.run_sync('Where does "hello world" come from?')
11print(result.data)

pydantic-ai Integration

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