Back to Opik

Using Opik with OpenAI Agents

apps/opik-documentation/documentation/docs/cookbook/openai-agents.ipynb

2.0.24-52625.8 KB
Original Source

Using Opik with OpenAI Agents

Opik integrates with OpenAI Agents to provide a simple way to log traces and analyse for all OpenAI LLM calls. This works for all OpenAI models, including if you are using the streaming API.

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 openai-agents
python
import opik

opik.configure(use_local=False)

Preparing our environment

First, we will set up our OpenAI API keys.

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, we need to wrap our OpenAI calls with the track_openai function:

python
from agents import Agent, Runner
from agents import set_trace_processors
from opik.integrations.openai.agents import OpikTracingProcessor

os.environ["OPIK_PROJECT_NAME"] = "openai-agents-demo"

set_trace_processors(processors=[OpikTracingProcessor()])
python
# Create and run your agent
agent = Agent(
    name="Creative Assistant", 
    instructions="You are a creative writing assistant that helps users with poetry and creative content.",
    model="gpt-4o-mini"
)

# Use async Runner.run() instead of run_sync() in Jupyter notebooks
result = await Runner.run(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

Using it with the track decorator

If you have multiple steps in your LLM pipeline, you can use the track decorator to log the traces for each step. If OpenAI is called within one of these steps, the LLM call with be associated with that corresponding step:

python
from agents import Agent, Runner, function_tool
from opik import track

@function_tool
def calculate_average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

@function_tool  
def get_recommendation(topic: str, user_level: str) -> str:
    recommendations = {
        "python": {
            "beginner": "Start with Python.org's tutorial, then try Python Crash Course book. Practice with simple scripts and built-in functions.",
            "intermediate": "Explore frameworks like Flask/Django, learn about decorators, context managers, and dive into Python's data structures.",
            "advanced": "Study Python internals, contribute to open source, learn about metaclasses, and explore performance optimization."
        },
        "machine learning": {
            "beginner": "Start with Andrew Ng's Coursera course, learn basic statistics, and try scikit-learn with simple datasets.",
            "intermediate": "Dive into deep learning with TensorFlow/PyTorch, study different algorithms, and work on real projects.",
            "advanced": "Research latest papers, implement algorithms from scratch, and contribute to ML frameworks."
        }
    }
    
    topic_lower = topic.lower()
    level_lower = user_level.lower()
    
    if topic_lower in recommendations and level_lower in recommendations[topic_lower]:
        return recommendations[topic_lower][level_lower]
    else:
        return f"For {topic} at {user_level} level: Focus on fundamentals, practice regularly, and build projects to apply your knowledge."

def create_advanced_agent():
    """Create an advanced agent with tools and comprehensive instructions."""
    instructions = """
    You are an expert programming tutor and learning advisor. You have access to tools that help you:
    1. Calculate averages for performance metrics, grades, or other numerical data
    2. Provide personalized learning recommendations based on topics and user experience levels
    
    Your role:
    - Help users learn programming concepts effectively
    - Provide clear, beginner-friendly explanations when needed
    - Use your tools when appropriate to give concrete help
    - Offer structured learning paths and resources
    - Be encouraging and supportive
    
    When users ask about:
    - Programming languages: Use get_recommendation to provide tailored advice
    - Performance or scores: Use calculate_average if numbers are involved
    - Learning paths: Combine your knowledge with tool-based recommendations
    
    Always explain your reasoning and make your responses educational.
    """
    
    return Agent(
        name="AdvancedProgrammingTutor",
        instructions=instructions,
        model="gpt-4o-mini",
        tools=[calculate_average, get_recommendation]
    )

advanced_agent = create_advanced_agent()

advanced_queries = [
    "I'm new to Python programming. Can you tell me about it?",
    "I got these test scores: 85, 92, 78, 96, 88. What's my average and how am I doing?",
    "I know some Python basics but want to learn machine learning. What should I do next?",
    "Can you help me calculate the average of these response times: 1.2, 0.8, 1.5, 0.9, 1.1 seconds? And tell me if that's good performance?"
]

for i, query in enumerate(advanced_queries, 1):
    print(f"\nšŸ“ Query {i}: {query}")
    result = await Runner.run(advanced_agent, query)
    print(f"šŸ¤– Response: {result.final_output}")
    print("=" * 80)

The trace can now be viewed in the UI: