# Set project name for better organization
os.environ["OPIK_PROJECT_NAME"] = "openai-agents-demo"

set_trace_processors(processors=[OpikTracingProcessor()])

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)
```

<Tip>
  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.
</Tip>

## Example: Agents with Function Tools

<Frame>
  <img src="https://files.buildwithfern.com/https://opik.docs.buildwithfern.com/docs/opik/2026-01-30T17:33:07.444Z/img/tracing/openai_agents_trace.png" alt="OpenAI Agents trace in Opik" />
</Frame>

You can create agents with custom function tools. The `OpikTracingProcessor` automatically captures all tool calls as well:

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

set_trace_processors(processors=[OpikTracingProcessor()])

@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]
    )