AgentOps Logo
Back to Blog

Build your first agent using OpenAI's Agents SDK and AgentOpsAI

Build your first agent with less than 50 lines of code!

6 min read
Build your first agent using OpenAI's Agents SDK and AgentOpsAI

In this tutorial, we'll walk through creating a simple and easy health and wellness coach agent using OpenAI's Agents SDK and AgentOps for monitoring. By the end, you'll have a fully functional AI assistant that can provide personalized advice on nutrition, fitness, sleep, and general wellness.We're creating a health and wellness coach that:

  • Answers questions about nutrition, workouts, BMI calculations, and sleep
  • Uses specialized sub-agents for different health domains
  • Searches the web for information when needed
  • Tracks interactions with AgentOps for monitoring and improvement

Prerequisites

  • Python 3.8+
  • OpenAI API key - Create your OpenAI key here
  • AgentOps API key - Create your AgentOps API key here

Step 1: Setting Up Your Environment

First, let's set up our project and install the necessary dependencies:

bash
Copy
# Create a virtual environment using uv (you can also use pip) 
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate 
# Install required packages 
pip install openai openai-agents pydantic python-dotenv agentops

Create a .env file in your project directory to store your API keys:

bash
Copy
OPENAI_API_KEY=your_openai_api_key
AGENTOPS_API_KEY=your_agentops_api_key

What's happening here?

  • We're creating a dedicated folder for our project
  • A virtual environment isolates our project's dependencies from other Python projects
  • We're installing the libraries we need:
    • openai: To access OpenAI's API
    • openai-agents: OpenAI's Agents SDK
    • pydantic: For data validation and settings management
    • python-dotenv: To load environment variables from a .env file
    • agentops: For monitoring and tracking our agent's performance

Step 2: Use OpenAI Agent SDK’s inbuilt web_search tool

Next, we'll make use of Agent SDK's in-built web search tool to search the web:

python
Copy
web_search=WebSearchTool()

What's happening here?

  • We're leveraging OpenAI's built-in web search capability
  • The function makes an API call to OpenAI with the web search tool enabled
  • It extracts the search results from the response and formats them for the agent to use
  • This approach eliminates the need for separate search API keys and implementations

Step 3: Creating Specialized Agents

Now, let's create specialized agents for different health domains:

python
Copy
from agents import Agent, Runner, WebSearchTool


nutrition_agent = Agent(  
  name="nutrition_agent",  
  instructions="""You are a nutrition specialist.   When asked about food or meals, use the web_search tool to find nutritional information.  Return the information in a clear, structured format.   Always include:  - Identified foods  - Estimated calories (when possible)  - Nutritional recommendations   After providing your recommendations, ask ONE specific follow-up question to learn more about the user's  dietary preferences, restrictions, or habits. This will help you provide more personalized nutrition advice.  """,  
  tools=[web_search]
) 


workout_agent = Agent(
  name="workout_agent",
  instructions="""You are a fitness trainer.   When asked about workouts or exercises, use the web_search tool to find appropriate workout plans.  Consider the user's fitness level, available equipment, and goals.   Always include:  - List of recommended exercises  - Recommended duration  - Intensity level   After providing your workout recommendations, ask ONE specific follow-up question to learn more about the  user's fitness level, available equipment, or exercise preferences. This will help you tailor future workout suggestions.  """,
  tools=[web_search] 
) 


bmi_agent = Agent(
  name="bmi_agent",  
  instructions="""You are a BMI calculator and advisor.   Calculate BMI using the formula: weight(kg) / height(m)².  Provide the BMI category and appropriate health advice.  Use web_search to find additional information if needed.   After providing BMI information, ask ONE specific follow-up question about the user's health goals or  current lifestyle to help provide more personalized health recommendations.  """,  
  tools=[web_search] 
) 


sleep_agent = Agent(
  name="sleep_agent",  
  instructions="""You are a sleep specialist.   Provide sleep recommendations based on the user's wake-up time and sleep needs.  Use web_search to find sleep hygiene tips and other relevant information.   After providing sleep advice, ask ONE specific follow-up question about the user's current sleep habits,  bedtime routine, or sleep environment to help provide more tailored recommendations.  """,  
  tools=[web_search] 
)

What's happening here?

  • We're creating four specialized agents, each with expertise in a specific health domain
  • Each agent is an instance of the Agent class from the Agents SDK
  • The name parameter gives each agent a unique identifier for reference
  • The instructions parameter provides detailed guidance on how the agent should behave
  • Each agent has access to the web_search tool we defined earlier
  • The instructions include specific formatting requirements for responses
  • Each agent is instructed to ask a follow-up question to personalize future interactions
  • This specialized approach allows for more detailed and accurate responses in each domain

Step 4: Creating the Main Health Coach Agent

Now, let's create our main health coach agent that can hand off to specialized agents:

python
Copy
health_coach = Agent(  
  name="health_coach",  
  instructions="""You are a helpful health and wellness coach.   Your job is to help users improve their physical health, nutrition, sleep, and overall wellness.   For nutrition questions, hand off to the nutrition_agent.  For workout questions, hand off to the workout_agent.  For BMI calculations, hand off to the bmi_agent.  For sleep recommendations, hand off to the sleep_agent.   For general health questions, use web_search to find relevant information.   IMPORTANT: Always personalize your advice. After answering a user's question, ask ONE specific follow-up  question to learn more about their personal situation, preferences, or health metrics. This will help you  provide more tailored recommendations in future interactions.   Examples of good follow-up questions:  - "What foods do you typically enjoy for breakfast?"  - "How much time can you realistically dedicate to exercise each day?"  - "Do you have any dietary restrictions I should be aware of?"  - "What time do you usually wake up in the morning?"   Be supportive, encouraging, and non-judgmental. Focus on sustainable habits rather than quick fixes.  """,
  tools=[web_search],  
  handoffs=[nutrition_agent, workout_agent, bmi_agent, sleep_agent] 
)

What's happening here?

  • We're creating a main coordinator agent that serves as the primary interface for users
  • This agent can handle general health questions using the web_search tool
  • The handoffs parameter lists the specialized agents this main agent can delegate to
  • When a user asks about a specific domain (nutrition, workouts, BMI, sleep), the main agent will hand off to the appropriate specialized agent
  • This creates a hierarchical structure where the main agent acts as a router
  • The instructions emphasize personalization and follow-up questions
  • The agent is guided to be supportive and focus on sustainable habits
  • This approach combines the benefits of specialized knowledge with a unified user experience

Step 5: Integrating AgentOps for Monitoring

Let's add AgentOps to track and monitor our agent's performance:

python
Copy
import os from dotenv 

import load_dotenv 

import agentops 


# Load environment variables from .env file load_dotenv() 
# Get API key from environment variables 
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") 

# Initialize AgentOps - this is all you need for automatic instrumentation 
agentops.init(api_key=AGENTOPS_API_KEY, default_tags=["wellness_coach"])

What's happening here?

  • We're setting up AgentOps to monitor and track our agent's performance
  • load_dotenv() loads environment variables from a .env file, including API keys
  • os.getenv() retrieves the AgentOps API key from the environment variables
  • agentops.init() initializes AgentOps with our API key and default tags
  • The tag "wellness_coach" helps categorize this agent in the AgentOps dashboard

Step 6: Creating the Main Function

Finally, let's create a main function to run our agent:

python
Copy
import asyncio from agents 
import Runner 

async def main():  
print("Welcome to the Health and Wellness Coach!")  
print("I can help you with workouts, nutrition, sleep, and general wellness advice.")  
print("Type 'exit' at any time to end the conversation.\n")     
query = input("How can I help with your health and wellness goals today? ") 

while query.lower() != 'exit': 
  try:  
        # Run the agent - AgentOps will automatically track this  
        result = await Runner.run(health_coach, query)             
        # Print the response to the user  
        print(f"\nHealth Coach: {result.final_output}\n")      
        
  except Exception as e:  
        print(f"\nAn error occurred: {str(e)}\n")         
        # Get the next query  query = input("You: ") 

if __name__ == "__main__":  asyncio.run(main())

What's happening here?

  • We're creating an asynchronous function called main() to run our agent
  • Asynchronous functions use async and await to handle operations that might take time
  • We display a welcome message to orient the user
  • We use a while loop to maintain a conversation until the user types 'exit'
  • Runner.run() executes our agent with the user's query and returns the result
  • input() gets text input from the user for the next query
  • asyncio.run(main()) runs our asynchronous main function

Running Your Health & Wellness Coach

Once you've built your health and wellness coach using the OpenAI Agents SDK and AgentOps, you'll need to know how to run it. Here are the steps to get your agent up and running:

Step 1: Save your code

Save all your code in a file named health_and_wellness_agent.py.

Step 2: Run the script

Open your terminal or command prompt, navigate to the directory containing your script, and run:

python health_and_wellness_agent.py

Step 3: Interact with your agent

Once the script is running, you'll see a welcome message and a prompt asking how the agent can help with your health and wellness goals. Type your questions or requests, and the agent will respond.

Example interaction:

bash
Copy
Welcome to the Health and Wellness Coach! I can help you with workouts, nutrition, sleep, and general wellness advice. Type 'exit' at any time to end the conversation. 
How can I help with your health and wellness goals today? I want to improve my sleep quality 
Health Coach: Based on your interest in improving sleep quality, here are some recommendations... 
You: What foods should I avoid before bedtime?
Health Coach: When it comes to foods to avoid before bedtime... 
You: exit

Key Features and Benefits

  • Specialized Agents: By creating domain-specific agents, we can provide more accurate and detailed responses for different health topics.
  • Handoffs: The main agent can delegate to specialized agents when appropriate, ensuring the user gets the best possible advice.
  • Follow-up Questions: Each agent is instructed to ask a follow-up question, making the interaction more conversational and personalized.
  • AgentOps Integration: By tracking interactions with AgentOps, we can monitor performance, identify areas for improvement, and detect issues.
  • Structured Outputs: Using Pydantic models ensures our agent returns consistent, well-formatted information.

Conclusion

Congratulations! You've built a sophisticated health and wellness coach using OpenAI's Agents SDK and AgentOps. This agent can provide personalized advice on nutrition, fitness, sleep, and general wellness, and it's designed to learn more about the user through follow-up questions.

The combination of specialized agents, web search capabilities, and AgentOps monitoring makes this a powerful and flexible solution that can be extended and improved over time.To take this further, you could:

  • Add more specialized agents for other health domains
  • Implement real web search functionality
  • Connect to health-tracking APIs or databases
  • Enhance the user interface with more interactive elements

Happy coding, and here's to building more helpful and intelligent agents!

We use cookies

We use cookies to ensure you get the best experience on our website. For more information on how we use cookies, please see our cookie policy.

By clicking "Accept", you agree to our use of cookies.
Learn more.