Back to Opik

Using Opik with DSPy

apps/opik-documentation/documentation/docs/cookbook/dspy.ipynb

2.0.22-6605-merge-20652.0 KB
Original Source

Using Opik with DSPy

DSPy is the framework for programming—rather than prompting—language models.

In this guide, we will showcase how to integrate Opik with DSPy so that all the DSPy calls are logged as traces in Opik.

Creating an account on Comet.com

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

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

python
%pip install --upgrade opik dspy
python
import opik

opik.configure(use_local=False)
python
import os
import getpass

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

Logging traces

In order to log traces to Opik, you will need to set the opik callback:

python
import dspy
from opik.integrations.dspy.callback import OpikCallback

lm = dspy.LM("openai/gpt-4o-mini")

project_name = "DSPY"
opik_callback = OpikCallback(project_name=project_name, log_graph=True)

dspy.configure(lm=lm, callbacks=[opik_callback])
python
cot = dspy.ChainOfThought("question -> answer")
cot(question="What is the meaning of life?")

The trace is now logged to the Opik platform:

If you set log_graph to True in the OpikCallback, then each module graph is also displayed in the "Agent graph" tab: