├── .gitignore ├── README.md ├── health_and_wellness_agent ├── README.md ├── health_and_wellness_agent.py └── requirements.txt ├── menu ├── README.md ├── menu.py ├── requirements.txt └── streamlit_app.py └── real_estate_agent ├── README.md ├── real_estate_agent.py ├── real_estate_streamlit.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | /.pnp 4 | .pnp.js 5 | yarn.lock 6 | package-lock.json 7 | 8 | # Testing 9 | /coverage 10 | 11 | # Production 12 | /build 13 | /dist 14 | .next/ 15 | out/ 16 | 17 | # Environment variables 18 | .env 19 | .env.local 20 | .env.development.local 21 | .env.test.local 22 | .env.production.local 23 | 24 | # Logs 25 | *.log 26 | npm-debug.log* 27 | yarn-debug.log* 28 | yarn-error.log* 29 | 30 | # IDEs and editors 31 | .idea/ 32 | .vscode/ 33 | *.swp 34 | *.swo 35 | .DS_Store 36 | 37 | # Images 38 | *.jpg 39 | *.jpeg 40 | *.png 41 | *.gif 42 | *.ico 43 | *.svg 44 | *.webp 45 | *.bmp 46 | *.tiff 47 | 48 | # Python 49 | __pycache__/ 50 | *.py[cod] 51 | *$py.class 52 | *.so 53 | .Python 54 | build/ 55 | develop-eggs/ 56 | dist/ 57 | downloads/ 58 | eggs/ 59 | .eggs/ 60 | lib/ 61 | lib64/ 62 | parts/ 63 | sdist/ 64 | var/ 65 | wheels/ 66 | *.egg-info/ 67 | .installed.cfg 68 | *.egg 69 | 70 | # Cache 71 | .cache/ 72 | .eslintcache 73 | 74 | # Misc 75 | .DS_Store 76 | *.pem 77 | .vercel -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Agents SDK Examples 2 | 3 | A curated collection of example projects built using the [Agents SDK by OpenAI](https://openai.github.io/openai-agents-python/tracing/) and AgentOpsAI. This repository demonstrates various ways to create and implement AI agents for different use cases and applications. 4 | 5 | ## 🌟 About AgentOpsAI 6 | 7 | [AgentOpsAI](https://agentops.ai) is an observability platform for AI agents, helping developers monitor, debug, and optimize their agents' performance. The platform provides: 8 | - Real-time monitoring of agent behavior and decisions 9 | - Comprehensive logging and tracing capabilities 10 | - Performance metrics and analytics 11 | - Debug tools for understanding agent actions 12 | - Insights to improve agent reliability and effectiveness 13 | 14 | ## 🤖 What's Inside 15 | 16 | This repository contains multiple example projects showcasing how to build different types of agents using the AgentOpsAI Agents SDK. Each project is self-contained and demonstrates specific capabilities and use cases. 17 | 18 | ### Example Projects 19 | 20 | Each project in this repository: 21 | - Is built using the Agents SDK and AgentOpsAI 22 | - Contains its own documentation and setup instructions 23 | - Demonstrates specific agent capabilities 24 | - Includes complete source code and implementation details 25 | 26 | ## 🎯 Purpose 27 | 28 | The main goals of this repository are to: 29 | - Provide practical examples of building agents with Agents SDK and AgentOpsAI 30 | - Demonstrate best practices for agent implementation 31 | - Help developers understand different use cases for AI agents 32 | - Serve as a learning resource for getting started with AgentOpsAI 33 | 34 | ## 📁 Repository Structure 35 | 36 | Each example project is located in its own directory with: 37 | - Source code 38 | - Project-specific README 39 | - Setup instructions 40 | - Dependencies and requirements 41 | 42 | ## 🚀 Getting Started 43 | 44 | To explore any example: 45 | 1. Navigate to the specific project directory 46 | 2. Follow the project's README for setup and running instructions 47 | 3. Experiment with the code and customize it for your needs 48 | 49 | ## 🤝 Contributing 50 | 51 | We welcome contributions! If you have an interesting agent implementation you'd like to share: 52 | 1. Fork the repository 53 | 2. Add your example project 54 | 3. Submit a pull request 55 | 56 | ## 📝 License 57 | 58 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 59 | -------------------------------------------------------------------------------- /health_and_wellness_agent/README.md: -------------------------------------------------------------------------------- 1 | # Health and Wellness Agent 2 | 3 | An AI agent that provides personalized health and wellness recommendations using AgentOps for observability. 4 | 5 | ## Installation 6 | 7 | ### Using uv (Recommended - Faster) 8 | 1. Install uv if you haven't already: 9 | ```bash 10 | pip install uv 11 | ``` 12 | 13 | 2. Create and activate virtual environment: 14 | ```bash 15 | uv venv 16 | source .venv/bin/activate # On Windows: .venv\Scripts\activate 17 | ``` 18 | 19 | 3. Install dependencies: 20 | ```bash 21 | uv pip install -r requirements.txt 22 | ``` 23 | 24 | ### Using pip (Alternative) 25 | 1. Create a virtual environment: 26 | ```bash 27 | python -m venv venv 28 | source venv/bin/activate # On Windows: venv\Scripts\activate 29 | ``` 30 | 31 | 2. Install dependencies: 32 | ```bash 33 | pip install -r requirements.txt 34 | ``` 35 | 36 | ### Environment Setup 37 | Create a `.env` file in the project root: 38 | ```bash 39 | OPENAI_API_KEY=your_openai_api_key 40 | AGENTOPS_API_KEY=your_agentops_api_key 41 | ``` 42 | 43 | ## Usage 44 | 45 | Run the agent: 46 | ```bash 47 | python health_agent.py 48 | ``` 49 | 50 | ## Monitoring 51 | View your agent's performance in the [AgentOps Dashboard](https://app.agentops.ai). -------------------------------------------------------------------------------- /health_and_wellness_agent/health_and_wellness_agent.py: -------------------------------------------------------------------------------- 1 | from agents import Agent, Runner, function_tool 2 | from agents import WebSearchTool 3 | import asyncio 4 | from typing import List, Dict, Optional 5 | from pydantic import BaseModel, Field 6 | import os 7 | from dotenv import load_dotenv 8 | import agentops 9 | from openai import OpenAI 10 | 11 | # Load environment variables from .env file 12 | load_dotenv() 13 | 14 | # Get API key from environment variables 15 | OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") 16 | AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") 17 | 18 | # Initialize AgentOps - this is all you need for automatic instrumentation 19 | agentops.init(AGENTOPS_API_KEY) 20 | # Initialize the OpenAI client 21 | client = OpenAI() 22 | web_search = WebSearchTool() 23 | 24 | # Define Pydantic models for structured outputs 25 | 26 | class NutritionInfo(BaseModel): 27 | foods: List[str] = Field(..., description="List of foods identified in the meal") 28 | total_calories: Optional[int] = Field(None, description="Estimated total calories") 29 | recommendations: Optional[List[str]] = Field(None, description="Nutritional recommendations") 30 | 31 | class WorkoutPlan(BaseModel): 32 | exercises: List[str] = Field(..., description="List of recommended exercises") 33 | duration: str = Field(..., description="Recommended workout duration") 34 | intensity: str = Field(..., description="Recommended intensity level") 35 | 36 | class BMIResult(BaseModel): 37 | bmi: Optional[float] = Field(None, description="Calculated BMI value") 38 | category: Optional[str] = Field(None, description="BMI category") 39 | advice: Optional[str] = Field(None, description="Health advice based on BMI") 40 | 41 | class SleepRecommendation(BaseModel): 42 | bedtime: Optional[str] = Field(None, description="Recommended bedtime") 43 | tips: Optional[List[str]] = Field(None, description="Sleep hygiene tips") 44 | 45 | 46 | # Create specialized agents 47 | 48 | nutrition_agent = Agent( 49 | name="nutrition_agent", 50 | instructions="""You are a nutrition specialist. 51 | 52 | When asked about food or meals, use the web_search tool to find nutritional information. 53 | Return the information in a clear, structured format. 54 | 55 | Always include: 56 | - Identified foods 57 | - Estimated calories (when possible) 58 | - Nutritional recommendations 59 | 60 | After providing your recommendations, ask ONE specific follow-up question to learn more about the user's 61 | dietary preferences, restrictions, or habits. This will help you provide more personalized nutrition advice. 62 | """, 63 | tools=[web_search] 64 | ) 65 | 66 | workout_agent = Agent( 67 | name="workout_agent", 68 | instructions="""You are a fitness trainer. 69 | 70 | When asked about workouts or exercises, use the web_search tool to find appropriate workout plans. 71 | Consider the user's fitness level, available equipment, and goals. 72 | 73 | Always include: 74 | - List of recommended exercises 75 | - Recommended duration 76 | - Intensity level 77 | 78 | After providing your workout recommendations, ask ONE specific follow-up question to learn more about the 79 | user's fitness level, available equipment, or exercise preferences. This will help you tailor future workout suggestions. 80 | """, 81 | tools=[web_search] 82 | ) 83 | 84 | bmi_agent = Agent( 85 | name="bmi_agent", 86 | instructions="""You are a BMI calculator and advisor. 87 | 88 | Calculate BMI using the formula: weight(kg) / height(m)². 89 | Provide the BMI category and appropriate health advice. 90 | Use web_search to find additional information if needed. 91 | 92 | After providing BMI information, ask ONE specific follow-up question about the user's health goals or 93 | current lifestyle to help provide more personalized health recommendations. 94 | """, 95 | tools=[web_search] 96 | ) 97 | 98 | sleep_agent = Agent( 99 | name="sleep_agent", 100 | instructions="""You are a sleep specialist. 101 | 102 | Provide sleep recommendations based on the user's wake-up time and sleep needs. 103 | Use web_search to find sleep hygiene tips and other relevant information. 104 | 105 | After providing sleep advice, ask ONE specific follow-up question about the user's current sleep habits, 106 | bedtime routine, or sleep environment to help provide more tailored recommendations. 107 | """, 108 | tools=[web_search] 109 | ) 110 | 111 | # Create the main health coach agent with handoffs to specialized agents 112 | health_coach = Agent( 113 | name="health_coach", 114 | instructions="""You are a helpful health and wellness coach. 115 | 116 | Your job is to help users improve their physical health, nutrition, sleep, and overall wellness. 117 | 118 | For nutrition questions, hand off to the nutrition_agent. 119 | For workout questions, hand off to the workout_agent. 120 | For BMI calculations, hand off to the bmi_agent. 121 | For sleep recommendations, hand off to the sleep_agent. 122 | 123 | For general health questions, use web_search to find relevant information. 124 | 125 | IMPORTANT: Always personalize your advice. After answering a user's question, ask ONE specific follow-up 126 | question to learn more about their personal situation, preferences, or health metrics. This will help you 127 | provide more tailored recommendations in future interactions. 128 | 129 | Examples of good follow-up questions: 130 | - "What foods do you typically enjoy for breakfast?" 131 | - "How much time can you realistically dedicate to exercise each day?" 132 | - "Do you have any dietary restrictions I should be aware of?" 133 | - "What time do you usually wake up in the morning?" 134 | 135 | Be supportive, encouraging, and non-judgmental. Focus on sustainable habits rather than quick fixes. 136 | """, 137 | tools=[web_search], 138 | handoffs=[nutrition_agent, workout_agent, bmi_agent, sleep_agent] 139 | ) 140 | 141 | # Modify the main function to include AgentOps tracking 142 | async def main(): 143 | print("Welcome to the Health and Wellness Coach!") 144 | print("I can help you with workouts, nutrition, sleep, and general wellness advice.") 145 | print("Type 'exit' at any time to end the conversation.\n") 146 | 147 | query = input("How can I help with your health and wellness goals today? ") 148 | 149 | while query.lower() != 'exit': 150 | try: 151 | # Run the agent - AgentOps will automatically track this 152 | result = await Runner.run(health_coach, query) 153 | 154 | # Print the response to the user 155 | print(f"\nHealth Coach: {result.final_output}\n") 156 | 157 | except Exception as e: 158 | print(f"\nAn error occurred: {str(e)}\n") 159 | 160 | # Get the next query 161 | query = input("You: ") 162 | 163 | if __name__ == "__main__": 164 | asyncio.run(main()) 165 | -------------------------------------------------------------------------------- /health_and_wellness_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | openai>=1.3.0 2 | python-dotenv>=1.0.0 3 | agentops>=0.1.0 4 | streamlit>=1.29.0 -------------------------------------------------------------------------------- /menu/README.md: -------------------------------------------------------------------------------- 1 | # Restaurant Finder Assistant 2 | 3 | An AI-powered restaurant recommendation system that considers dietary restrictions, allergies, and current operating hours. 4 | 5 | ## Features 6 | - Real-time restaurant availability checking 7 | - Dietary restrictions and allergy considerations 8 | - Location-aware recommendations 9 | 10 | ## Installation 11 | 12 | ### Basic Installation (CLI only) 13 | ```bash 14 | # Clone the repository 15 | git clone 16 | cd menu 17 | 18 | # Create and activate virtual environment 19 | python -m venv .venv 20 | source .venv/bin/activate # On Windows: .venv\Scripts\activate 21 | 22 | # Install basic requirements 23 | pip install -r requirements.txt 24 | ``` 25 | 26 | ### Full Installation (including Web Interface) 27 | ```bash 28 | # Follow basic installation steps, then: 29 | pip install -r requirements-web.txt 30 | ``` 31 | 32 | ## Configuration 33 | 34 | 1. Create a `.env` file in the project root: 35 | ```env 36 | OPENAI_API_KEY=your_openai_api_key 37 | AGENTOPS_API_KEY=your_agentops_api_key 38 | ``` 39 | 40 | 2. Make sure your environment variables are set: 41 | ```bash 42 | # On Unix/macOS 43 | export OPENAI_API_KEY="your_openai_api_key" 44 | export AGENTOPS_API_KEY="your_agentops_api_key" 45 | 46 | # On Windows (PowerShell) 47 | $env:OPENAI_API_KEY="your_openai_api_key" 48 | $env:AGENTOPS_API_KEY="your_agentops_api_key" 49 | ``` 50 | 51 | ## Usage 52 | 53 | ### CLI Interface 54 | Run the assistant in your terminal: 55 | ```bash 56 | python main.py 57 | ``` 58 | 59 | You'll be prompted to: 60 | 1. Enter your timezone 61 | 2. List any food allergies 62 | 3. Specify dietary restrictions 63 | 4. Provide your location 64 | 5. Enter your restaurant preferences 65 | 66 | ### Web Interface (Optional) 67 | Run the Streamlit web app: 68 | ```bash 69 | streamlit run streamlit_app.py 70 | ``` 71 | 72 | The web interface provides: 73 | - User-friendly form inputs 74 | - Real-time updates 75 | - Interactive search 76 | - Recommendation history 77 | - Visual presentation of results 78 | -------------------------------------------------------------------------------- /menu/menu.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import pytz 3 | from datetime import datetime 4 | 5 | # Add these lines at the top of the file to make the agent importable 6 | __all__ = ['restaurant_agent', 'Runner'] 7 | 8 | from agents import Agent, Runner, WebSearchTool 9 | import os 10 | from dotenv import load_dotenv 11 | import agentops 12 | 13 | # Load environment variables and initialize 14 | load_dotenv() 15 | AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") 16 | agentops.init(AGENTOPS_API_KEY) 17 | 18 | # Initialize the OpenAI client 19 | web_search = WebSearchTool() 20 | 21 | # Create specialized agents for different aspects of restaurant search 22 | restaurant_search_agent = Agent( 23 | name="restaurant_search_agent", 24 | instructions="""You are a restaurant search specialist. 25 | 26 | CRITICAL: When searching for restaurants, you MUST: 27 | 1. Check the current day and time provided in each query 28 | 2. Verify the restaurant is CURRENTLY OPEN before recommending 29 | 3. Include the closing time for each recommended restaurant 30 | 4. Only recommend restaurants that are confirmed to be open 31 | 5. NEVER recommend permanently closed restaurants 32 | 6. Verify the restaurant's current operational status through recent reviews or their website 33 | 34 | VERIFICATION STEPS FOR EACH RESTAURANT: 35 | 1. Check if the business is permanently closed 36 | 2. Verify recent activity (reviews, social media, website updates) 37 | 3. Confirm current operating status through official sources 38 | 4. Double-check current day's operating hours 39 | 5. Only proceed with recommendation if all verifications pass 40 | 41 | When asked about restaurants, use the web_search tool to find current open restaurants 42 | that match the user's dietary restrictions and allergies. 43 | Return the information in a clear, structured format. 44 | 45 | Always include: 46 | - Restaurant name 47 | - CURRENT OPERATING STATUS (Must be open now) 48 | - Today's closing time 49 | - Last verified date/source (e.g., "Verified open via website 2024-03-XX") 50 | - Address 51 | - Type of cuisine 52 | - Price range 53 | - Menu highlights that match dietary restrictions 54 | - URL to the restaurant's website or menu 55 | - Current rating/reviews with recent dates 56 | 57 | Pay special attention to: 58 | - Recent reviews or social media posts confirming operation 59 | - Special holiday hours or temporary closures 60 | - Allergy information and cross-contamination policies 61 | - Dietary accommodation options (vegan, gluten-free, etc.) 62 | - Kitchen closing times (if different from restaurant hours) 63 | 64 | If you're unsure about a restaurant's current operational status, DO NOT recommend it. 65 | 66 | After providing verified open restaurant options, ask ONE specific follow-up question about their 67 | dining preferences or restrictions to provide better recommendations. 68 | """, 69 | tools=[web_search], 70 | ) 71 | 72 | dietary_agent = Agent( 73 | name="dietary_agent", 74 | instructions="""You are a dietary requirements specialist. 75 | 76 | Help users identify restaurants that can safely accommodate their: 77 | - Food allergies 78 | - Dietary restrictions (vegan, vegetarian, kosher, halal, etc.) 79 | - Special dietary needs 80 | 81 | Use web_search to find: 82 | - Restaurant allergy policies 83 | - Cross-contamination prevention practices 84 | - Special menu options 85 | - Kitchen practices for dietary accommodations 86 | 87 | After providing information, ask ONE specific follow-up question about their 88 | dietary needs to ensure all restrictions are properly addressed. 89 | """, 90 | tools=[web_search] 91 | ) 92 | 93 | location_agent = Agent( 94 | name="location_agent", 95 | instructions="""You are a location and accessibility specialist. 96 | 97 | When asked about restaurant locations, use web_search to find: 98 | - Current traffic conditions 99 | - Parking availability 100 | - Public transportation options 101 | - Accessibility features 102 | - Nearby landmarks or points of reference 103 | 104 | Always verify: 105 | - Current operating status 106 | - Special hours or closures 107 | - Delivery/takeout options 108 | 109 | After providing location information, ask ONE follow-up question about their 110 | transportation preferences or accessibility needs. 111 | """, 112 | tools=[web_search] 113 | ) 114 | 115 | # Main restaurant recommendation agent 116 | restaurant_agent = Agent( 117 | name="restaurant_agent", 118 | instructions="""You are a comprehensive restaurant recommendation assistant that helps users 119 | find suitable dining options considering their allergies, dietary restrictions, and location. 120 | 121 | IMPORTANT: Only use web search or hand off to specialized agents when specific current information is needed: 122 | 1. For specific restaurant searches and current openings -> hand off to restaurant_search_agent 123 | 2. For detailed dietary and allergy accommodation info -> hand off to dietary_agent 124 | 3. For location-specific details and accessibility -> hand off to location_agent 125 | 126 | For general dining questions or follow-up questions about previous responses, 127 | use your existing knowledge to respond without web searches. 128 | 129 | Always maintain a focus on food safety for users with allergies and dietary restrictions. 130 | After answering a query, ask ONE specific follow-up question to better understand their needs. 131 | 132 | Be transparent about when you're using current data vs general knowledge. 133 | """, 134 | tools=[web_search], 135 | handoffs=[restaurant_search_agent, dietary_agent, location_agent] 136 | ) 137 | 138 | async def main(): 139 | print("Welcome to the Restaurant Recommendation Assistant!") 140 | print("I can help you find restaurants that accommodate your dietary needs and allergies.") 141 | print("Type 'exit' at any time to end the conversation.\n") 142 | 143 | # Get user's timezone 144 | timezone = input("What's your timezone (e.g., US/Pacific, US/Eastern)?: ") 145 | try: 146 | tz = pytz.timezone(timezone) 147 | except pytz.exceptions.UnknownTimeZoneError: 148 | print("Invalid timezone. Defaulting to UTC.") 149 | tz = pytz.UTC 150 | 151 | conversation_inputs = [{ 152 | "role": "system", 153 | "content": """You are a restaurant recommendation assistant. Help users find safe dining options 154 | that accommodate their allergies and dietary restrictions. Use web search for current restaurant 155 | information and operating hours. Only recommend restaurants that are currently open.""" 156 | }] 157 | 158 | # Gather essential information 159 | print("\nTo help you better, I need to know a few things:") 160 | allergies = input("Please list any food allergies you have: ") 161 | dietary_restrictions = input("Any dietary restrictions (vegetarian, vegan, etc.)?: ") 162 | location = input("What's your location (city/neighborhood)?: ") 163 | 164 | query = input("\nWhat kind of restaurant are you looking for? ") 165 | 166 | while query.lower() != 'exit': 167 | try: 168 | # Get current time in user's timezone 169 | current_time = datetime.now(tz) 170 | current_day = current_time.strftime('%A') 171 | current_time_str = current_time.strftime('%I:%M %p') 172 | 173 | # Create user profile 174 | user_profile = f""" 175 | Current Time: {current_time_str} 176 | Current Day: {current_day} 177 | Location: {location} 178 | Timezone: {timezone} 179 | Allergies: {allergies} 180 | Dietary Restrictions: {dietary_restrictions} 181 | """ 182 | 183 | enhanced_query = f"""User Profile:\n{user_profile}\n\nQuery: {query}""" 184 | 185 | new_input = conversation_inputs + [{"role": "user", "content": enhanced_query}] 186 | result = await Runner.run(restaurant_agent, new_input) 187 | 188 | conversation_inputs = result.to_input_list() 189 | print(f"\nRestaurant Assistant: {result.final_output}\n") 190 | 191 | except Exception as e: 192 | print(f"\nAn error occurred: {str(e)}\n") 193 | 194 | query = input("You: ") 195 | 196 | if __name__ == "__main__": 197 | asyncio.run(main()) -------------------------------------------------------------------------------- /menu/requirements.txt: -------------------------------------------------------------------------------- 1 | # Core requirements 2 | python-dotenv>=0.19.0 3 | agentops>=0.1.0 4 | pytz>=2024.1 5 | agents-sdk # replace with actual version when public 6 | 7 | # Optional - Web Interface 8 | streamlit>=1.32.0 # Optional - only needed for web interface 9 | 10 | asyncio -------------------------------------------------------------------------------- /menu/streamlit_app.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from datetime import datetime 3 | import pytz 4 | from menu import restaurant_agent, Runner 5 | import asyncio 6 | import uuid 7 | 8 | st.set_page_config( 9 | page_title="Restaurant Finder", 10 | page_icon="🍽️", 11 | layout="wide", 12 | initial_sidebar_state="expanded" 13 | ) 14 | 15 | # Initialize session state 16 | if 'conversation_inputs' not in st.session_state: 17 | st.session_state.conversation_inputs = [{ 18 | "role": "system", 19 | "content": """You are a restaurant recommendation assistant. Help users find safe dining options 20 | that accommodate their allergies and dietary restrictions. Use web search for current restaurant 21 | information and operating hours. Only recommend restaurants that are currently open.""" 22 | }] 23 | 24 | if 'thread_id' not in st.session_state: 25 | st.session_state.thread_id = str(uuid.uuid4()) 26 | 27 | # Sidebar for user profile 28 | st.sidebar.title("Your Profile") 29 | 30 | # Timezone selection 31 | timezone = st.sidebar.selectbox( 32 | "Select your timezone", 33 | options=pytz.common_timezones, 34 | index=pytz.common_timezones.index('US/Pacific') 35 | ) 36 | 37 | # User information 38 | location = st.sidebar.text_input("Your location (city/neighborhood)") 39 | allergies = st.sidebar.text_area("Food allergies (if any)") 40 | dietary_restrictions = st.sidebar.text_area("Dietary restrictions (e.g., vegetarian, vegan)") 41 | 42 | # Main content 43 | st.title("🍽️ Smart Restaurant Finder") 44 | st.markdown(""" 45 | Find restaurants that match your dietary needs and are open right now! 46 | """) 47 | 48 | # Current time display 49 | try: 50 | tz = pytz.timezone(timezone) 51 | current_time = datetime.now(tz) 52 | current_day = current_time.strftime('%A') 53 | current_time_str = current_time.strftime('%I:%M %p') 54 | st.info(f"Current time in {timezone}: {current_time_str} on {current_day}") 55 | except Exception as e: 56 | st.error(f"Error with timezone: {str(e)}") 57 | tz = pytz.UTC 58 | 59 | # Query input 60 | query = st.text_input("What kind of restaurant are you looking for?") 61 | 62 | # Search button 63 | if st.button("Search Restaurants", type="primary"): 64 | if not location: 65 | st.warning("⚠️ Please enter your location in the sidebar first!") 66 | else: 67 | try: 68 | # Get current time in user's timezone 69 | current_time = datetime.now(tz) 70 | current_day = current_time.strftime('%A') 71 | current_time_str = current_time.strftime('%I:%M %p') 72 | 73 | # Create user profile 74 | user_profile = f""" 75 | Current Time: {current_time_str} 76 | Current Day: {current_day} 77 | Location: {location} 78 | Timezone: {timezone} 79 | Allergies: {allergies} 80 | Dietary Restrictions: {dietary_restrictions} 81 | """ 82 | 83 | enhanced_query = f"""User Profile:\n{user_profile}\n\nQuery: {query}""" 84 | 85 | with st.spinner('🔍 Searching for the perfect restaurants...'): 86 | async def search_restaurants(): 87 | new_input = st.session_state.conversation_inputs + [{"role": "user", "content": enhanced_query}] 88 | result = await Runner.run(restaurant_agent, new_input) 89 | st.session_state.conversation_inputs = result.to_input_list() 90 | return result 91 | 92 | # Run the async function 93 | result = asyncio.run(search_restaurants()) 94 | 95 | st.markdown(''' 96 |
97 |

Restaurant Recommendations

98 |
99 | ''', unsafe_allow_html=True) 100 | st.markdown(result.final_output) 101 | 102 | except Exception as e: 103 | st.error(f"An error occurred: {str(e)}") 104 | 105 | # Footer 106 | st.markdown("---") 107 | st.markdown(""" 108 | 💡 **Tips:** 109 | - Be specific about your cuisine preferences 110 | - Include any dietary restrictions in the sidebar 111 | - Make sure your location is accurate 112 | """) -------------------------------------------------------------------------------- /real_estate_agent/README.md: -------------------------------------------------------------------------------- 1 | # Real Estate Agent 2 | 3 | An AI agent that helps with real estate analysis and recommendations using AgentOps for observability. 4 | 5 | ## Installation 6 | 7 | ### Using uv (Recommended - Faster) 8 | 1. Install uv if you haven't already: 9 | ```bash 10 | pip install uv 11 | ``` 12 | 13 | 2. Create and activate virtual environment: 14 | ```bash 15 | uv venv 16 | source .venv/bin/activate # On Windows: .venv\Scripts\activate 17 | ``` 18 | 19 | 3. Install dependencies: 20 | ```bash 21 | uv pip install -r requirements.txt 22 | ``` 23 | 24 | ### Using pip (Alternative) 25 | 1. Create a virtual environment: 26 | ```bash 27 | python -m venv venv 28 | source venv/bin/activate # On Windows: venv\Scripts\activate 29 | ``` 30 | 31 | 2. Install dependencies: 32 | ```bash 33 | pip install -r requirements.txt 34 | ``` 35 | 36 | ### Environment Setup 37 | Create a `.env` file in the project root: 38 | ```bash 39 | OPENAI_API_KEY=your_openai_api_key 40 | AGENTOPS_API_KEY=your_agentops_api_key 41 | ``` 42 | 43 | ## Usage 44 | 45 | Run the agent: 46 | ```bash 47 | python real_estate_agent.py 48 | ``` 49 | 50 | ### Optional: Web Interface 51 | Run the Streamlit app: 52 | ```bash 53 | streamlit run streamlit_app.py 54 | ``` 55 | 56 | ## Monitoring 57 | View your agent's performance in the [AgentOps Dashboard](https://app.agentops.ai). -------------------------------------------------------------------------------- /real_estate_agent/real_estate_agent.py: -------------------------------------------------------------------------------- 1 | from agents import Agent, Runner, WebSearchTool 2 | import os 3 | from dotenv import load_dotenv 4 | import agentops 5 | import asyncio # we use this in the main function to run the agent 6 | 7 | # Set the OPENAI_API_KEY environment variable on your terminal 8 | # export OPENAI_API_KEY="..." 9 | 10 | # Load AGENTOPS_API_KEY environment variable from .env file 11 | load_dotenv() 12 | 13 | # Get AGENTOPS_API key from environment variables 14 | AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") 15 | 16 | # Initialize AgentOps - this is all you need for automatic instrumentation 17 | agentops.init(AGENTOPS_API_KEY) 18 | 19 | # Initialize the OpenAI client 20 | web_search = WebSearchTool() 21 | 22 | # Create specialized agents 23 | property_search_agent = Agent( 24 | name="property_search_agent", 25 | instructions="""You are a real estate property search specialist. 26 | 27 | When asked about properties or homes for sale, use the web_search tool to find current listings. 28 | Return the information in a clear, structured format. 29 | 30 | Always include if available: 31 | - Property address 32 | - Listing price 33 | - Number of bedrooms and bathrooms 34 | - Square footage 35 | - Property type 36 | - URL to the actual listing (must be real URLs from your web search, never use example.com or placeholder URLs) 37 | - URL to the actual listing, not the example URL 38 | 39 | After providing property listings, ask ONE specific follow-up question to learn more about the user's 40 | preferences, budget constraints, or must-have features. This will help you provide more targeted property recommendations. 41 | """, 42 | tools=[web_search], 43 | ) 44 | 45 | mortgage_agent = Agent( 46 | name="mortgage_agent", 47 | instructions="""You are a mortgage specialist. 48 | 49 | When asked about mortgages, financing, or home loans, use the web_search tool to find current rates and information. 50 | Consider the user's budget, down payment capabilities, and financial goals. 51 | 52 | Always include when possible: 53 | - Loan amount options 54 | - Current interest rates 55 | - Estimated monthly payments 56 | - Recommended down payment 57 | 58 | After providing mortgage information, ask ONE specific follow-up question to learn more about the 59 | user's financial situation, credit score range, or long-term housing plans. This will help you provide more accurate mortgage advice. 60 | """, 61 | tools=[web_search] 62 | ) 63 | 64 | neighborhood_agent = Agent( 65 | name="neighborhood_agent", 66 | instructions="""You are a neighborhood information specialist. 67 | 68 | When asked about neighborhoods or locations, use the web_search tool to find relevant information. 69 | Provide details about schools, amenities, safety, and transportation options. 70 | 71 | Always include when possible: 72 | - School ratings and districts 73 | - Local amenities (parks, shopping, restaurants) 74 | - Crime statistics and safety information 75 | - Public transportation options and walkability 76 | 77 | After providing neighborhood information, ask ONE specific follow-up question to understand if the user 78 | has specific concerns about the area or particular amenities they're looking for. This will help you provide more relevant information. 79 | """, 80 | tools=[web_search] 81 | ) 82 | 83 | # Create the main real estate agent that coordinates the specialized agents using handoffs 84 | real_estate_agent = Agent( 85 | name="real_estate_agent", 86 | instructions="""You are a comprehensive real estate assistant that helps users find properties, 87 | understand mortgage options, and learn about neighborhoods. 88 | 89 | Based on the user's query: 90 | 1. If they're asking about specific properties or home listings, hand off to the property_search_agent 91 | 2. If they're asking about mortgages, financing, or affordability, hand off to the mortgage_agent 92 | 3. If they're asking about neighborhoods, schools, or local amenities, hand off to the neighborhood_agent 93 | 94 | For general real estate questions, use web_search to find relevant information. 95 | 96 | Provide helpful, accurate information and maintain a professional, friendly tone. 97 | If the user's request spans multiple categories, prioritize addressing their primary concern first, 98 | then offer to help with related aspects. 99 | 100 | IMPORTANT: Always personalize your advice. After answering a user's question, ask ONE specific follow-up 101 | question to learn more about their personal situation, preferences, or requirements. This will help you 102 | provide more tailored recommendations in future interactions. 103 | 104 | Examples of good follow-up questions: 105 | - "What's your budget range for a new home?" 106 | - "Are there specific neighborhoods you're interested in?" 107 | - "How many bedrooms and bathrooms are you looking for?" 108 | - "Are you planning to buy with a conventional mortgage or exploring other options?" 109 | 110 | Always be transparent about the information sources and any limitations in the data provided. 111 | """, 112 | tools=[web_search], 113 | handoffs=[property_search_agent, mortgage_agent, neighborhood_agent] 114 | ) 115 | 116 | async def main(): 117 | print("Welcome to the Real Estate Assistant!") 118 | print("I can help you find properties, understand mortgage options, and learn about neighborhoods.") 119 | print("Type 'exit' at any time to end the conversation.\n") 120 | 121 | query = input("What real estate information are you looking for? ") 122 | 123 | while query.lower() != 'exit': 124 | try: 125 | # Run the agent - AgentOps will automatically track this 126 | result = await Runner.run(real_estate_agent, query) 127 | 128 | # Print the response to the user 129 | print(f"\nReal Estate Assistant: {result.final_output}\n") 130 | 131 | except Exception as e: 132 | print(f"\nAn error occurred: {str(e)}\n") 133 | 134 | # Get the next query 135 | query = input("You: ") 136 | 137 | if __name__ == "__main__": 138 | asyncio.run(main()) -------------------------------------------------------------------------------- /real_estate_agent/real_estate_streamlit.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | import asyncio 3 | from real_estate_agent import real_estate_agent, Runner 4 | 5 | # Set page configuration 6 | st.set_page_config( 7 | page_title="Real Estate Assistant", 8 | page_icon="🔑", 9 | layout="centered" 10 | ) 11 | 12 | # Initialize session state for chat history 13 | if "messages" not in st.session_state: 14 | st.session_state.messages = [ 15 | {"role": "assistant", "content": "Welcome to the Real Estate Assistant! I can help you find properties, understand mortgage options, and learn about neighborhoods. How can I help you today?"} 16 | ] 17 | 18 | # Page header 19 | st.title("🏠 Real Estate Assistant") 20 | st.markdown("Find properties, understand mortgages, and explore neighborhoods") 21 | 22 | # Display chat messages 23 | for message in st.session_state.messages: 24 | if message["role"] == "assistant": 25 | with st.chat_message(message["role"], avatar="🔑"): 26 | st.markdown(message["content"]) 27 | else: 28 | with st.chat_message(message["role"], avatar="👤"): 29 | st.markdown(message["content"]) 30 | 31 | # Function to process user input 32 | async def process_query(query): 33 | try: 34 | result = await Runner.run(real_estate_agent, query) 35 | return result.final_output 36 | except Exception as e: 37 | return f"An error occurred: {str(e)}" 38 | 39 | # Chat input 40 | if prompt := st.chat_input("What real estate information are you looking for?"): 41 | # Add user message to chat history 42 | st.session_state.messages.append({"role": "user", "content": prompt}) 43 | 44 | # Display user message 45 | with st.chat_message("user", avatar="👤"): 46 | st.markdown(prompt) 47 | 48 | # Display assistant response 49 | with st.chat_message("assistant", avatar="🔑"): 50 | message_placeholder = st.empty() 51 | message_placeholder.markdown("Thinking...") 52 | 53 | # Process the query 54 | response = asyncio.run(process_query(prompt)) 55 | 56 | # Update the placeholder with the response 57 | message_placeholder.markdown(response) 58 | 59 | # Add assistant response to chat history 60 | st.session_state.messages.append({"role": "assistant", "content": response}) -------------------------------------------------------------------------------- /real_estate_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | openai>=1.3.0 2 | python-dotenv>=1.0.0 3 | agentops>=0.1.0 4 | streamlit>=1.29.0 --------------------------------------------------------------------------------