Observability for OpenAI Agents with Opik

OpenAI released an agentic framework aptly named Agents. What sets this framework apart from others is that it provides a rich set of core building blocks:

  1. Models: Support for all OpenAI Models
  2. Tools: Similar function calling functionality than the one available when using the OpenAI models directly
  3. Knowledge and Memory: Seamless integration with OpenAI’s vector store and Embeddings Anthropic
  4. Guardrails: Run Guardrails checks in parallel to your agent execution which allows for secure execution without slowing down the total agent execution.

Opik’s integration with Agents is just one line of code and allows you to analyse and debug the agent execution flow in our Open-Source platform.

Account Setup

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.

Getting Started

Installation

First, ensure you have both opik and openai-agents packages installed:

$pip install opik openai-agents

Configuring Opik

Configure the Opik Python SDK for your deployment type. See the Python SDK Configuration guide for detailed instructions on:

  • CLI configuration: opik configure
  • Code configuration: opik.configure()
  • Self-hosted vs Cloud vs Enterprise setup
  • Configuration files and environment variables

Configuring OpenAI Agents

In order to use OpenAI Agents, you will need to configure your OpenAI API key. You can find or create your API keys in these pages:

You can set them as environment variables:

$export OPENAI_API_KEY="YOUR_API_KEY"

Or set them programmatically:

1import os
2import getpass
3
4if "OPENAI_API_KEY" not in os.environ:
5 os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")

Enabling logging to Opik

To enable logging to Opik, simply add the following two lines of code to your existing OpenAI Agents code:

1import os
2from agents import Agent, Runner
3from agents import set_trace_processors
4from opik.integrations.openai.agents import OpikTracingProcessor
5
6# Set project name for better organization
7os.environ["OPIK_PROJECT_NAME"] = "openai-agents-demo"
8
9set_trace_processors(processors=[OpikTracingProcessor()])
10
11agent = Agent(name="Assistant", instructions="You are a helpful assistant")
12
13result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
14print(result.final_output)

The Opik integration will automatically track both the token usage and overall cost of each LLM call that is being made. You can also view this information aggregated for the entire agent execution.

Advanced Example: Agents with Function Tools

For more complex use cases, you can create agents with custom function tools and use the @track decorator for multi-step workflows:

1from agents import Agent, Runner, function_tool
2from opik import track
3
4@function_tool
5def calculate_average(numbers: list[float]) -> float:
6 return sum(numbers) / len(numbers)
7
8@function_tool
9def get_recommendation(topic: str, user_level: str) -> str:
10 recommendations = {
11 "python": {
12 "beginner": "Start with Python.org's tutorial, then try Python Crash Course book. Practice with simple scripts and built-in functions.",
13 "intermediate": "Explore frameworks like Flask/Django, learn about decorators, context managers, and dive into Python's data structures.",
14 "advanced": "Study Python internals, contribute to open source, learn about metaclasses, and explore performance optimization."
15 },
16 "machine learning": {
17 "beginner": "Start with Andrew Ng's Coursera course, learn basic statistics, and try scikit-learn with simple datasets.",
18 "intermediate": "Dive into deep learning with TensorFlow/PyTorch, study different algorithms, and work on real projects.",
19 "advanced": "Research latest papers, implement algorithms from scratch, and contribute to ML frameworks."
20 }
21 }
22
23 topic_lower = topic.lower()
24 level_lower = user_level.lower()
25
26 if topic_lower in recommendations and level_lower in recommendations[topic_lower]:
27 return recommendations[topic_lower][level_lower]
28 else:
29 return f"For {topic} at {user_level} level: Focus on fundamentals, practice regularly, and build projects to apply your knowledge."
30
31def create_advanced_agent():
32 """Create an advanced agent with tools and comprehensive instructions."""
33 instructions = """
34 You are an expert programming tutor and learning advisor. You have access to tools that help you:
35 1. Calculate averages for performance metrics, grades, or other numerical data
36 2. Provide personalized learning recommendations based on topics and user experience levels
37
38 Your role:
39 - Help users learn programming concepts effectively
40 - Provide clear, beginner-friendly explanations when needed
41 - Use your tools when appropriate to give concrete help
42 - Offer structured learning paths and resources
43 - Be encouraging and supportive
44
45 When users ask about:
46 - Programming languages: Use get_recommendation to provide tailored advice
47 - Performance or scores: Use calculate_average if numbers are involved
48 - Learning paths: Combine your knowledge with tool-based recommendations
49
50 Always explain your reasoning and make your responses educational.
51 """
52
53 return Agent(
54 name="AdvancedProgrammingTutor",
55 instructions=instructions,
56 model="gpt-4o-mini",
57 tools=[calculate_average, get_recommendation]
58 )
59
60# Create and use the advanced agent
61advanced_agent = create_advanced_agent()
62
63# Example queries
64queries = [
65 "I'm new to Python programming. Can you tell me about it?",
66 "I got these test scores: 85, 92, 78, 96, 88. What's my average and how am I doing?",
67 "I know some Python basics but want to learn machine learning. What should I do next?",
68]
69
70for i, query in enumerate(queries, 1):
71 print(f"\n📝 Query {i}: {query}")
72 result = Runner.run_sync(advanced_agent, query)
73 print(f"🤖 Response: {result.final_output}")
74 print("=" * 80)

Logging threads

When you are running multi-turn conversations with OpenAI Agents using OpenAI Agents trace API, Opik integration automatically use the trace group_id as the Thread ID so you can easily review conversation inside Opik. Here is an example below:

1async def main():
2 agent = Agent(name="Assistant", instructions="Reply very concisely.")
3
4 thread_id = str(uuid.uuid4())
5
6 with trace(workflow_name="Conversation", group_id=thread_id):
7 # First turn
8 result = await Runner.run(agent, "What city is the Golden Gate Bridge in?")
9 print(result.final_output)
10 # San Francisco
11
12 # Second turn
13 new_input = result.to_input_list() + [{"role": "user", "content": "What state is it in?"}]
14 result = await Runner.run(agent, new_input)
15 print(result.final_output)
16 # California

Further improvements

OpenAI Agents is still a relatively new framework and we are working on a couple of improvements:

  1. Improved rendering of the inputs and outputs for the LLM calls as part of our Pretty Mode functionality
  2. Improving the naming conventions for spans
  3. Adding the agent execution input and output at a trace level

If there are any additional improvements you would like us to make, feel free to open an issue on our GitHub repository.