from pydantic import BaseModel from agents import Agent, Runner, function_tool from typing import List HOW_MANY_SEARCHES = 1 INSTRUCTIONS = f"""You are a helpful research assistant. Given a query and user's answers to three questions, come up with a set of web searches to perform to best answer the query. Use the user's answers to refine and make the search more sophisticated. Output {HOW_MANY_SEARCHES} terms to query for. You have access to a question generation function that you can use to generate relevant questions. Use this function to generate three sequential questions that build upon each other: 1. First question should focus on understanding the main aspects of interest 2. Second question should use the first answer to narrow down the focus 3. Third question should use both previous answers to ask about specific requirements After getting all three answers, use them to create a sophisticated search plan. IMPORTANT: Your response MUST be a valid JSON object with a 'searches' array containing objects with 'query' and 'reason' fields. Example format: {{ "searches": [ {{ "query": "search term", "reason": "reason for this search" }} ] }} The response MUST: 1. Be a valid JSON object 2. Have a 'searches' array as the top-level key 3. Each item in 'searches' must have both 'query' and 'reason' fields 4. The 'searches' array must contain exactly {HOW_MANY_SEARCHES} items 5. Do not include any other fields or formatting DO NOT include any other fields or formatting. The response must be a valid JSON object that matches the WebSearchPlan model exactly.""" QUESTION_GENERATION_INSTRUCTIONS = f"""You are a research assistant that helps refine research topics through focused questions. Given a research topic and any previous answers, generate ONE specific question that will help narrow down and focus the research. The input will be provided as a dictionary with: - query: The main research topic - previous_answers: A list of previous answers (may be empty) For the first question (when previous_answers is empty): - Focus on understanding the main aspects of interest - Make it broad enough to guide the direction of follow-up questions For the second question (when there is one previous answer): - Use the answer to the first question to narrow down the focus - Ask about specific details or preferences For the third question (when there are two previous answers): - Use both previous answers to ask about specific requirements or constraints - Make it highly specific to the user's needs Return your response as a single question string, without any additional formatting or explanation.""" class WebSearchItem(BaseModel): reason: str "Your reasoning for why this search is important to the query." query: str "The search term to use for the web search." class WebSearchPlan(BaseModel): searches: list[WebSearchItem] """A list of web searches to perform to best answer the query.""" class UserContext(BaseModel): main_query: str answer1: str answer2: str answer3: str def format_search_plan(plan: WebSearchPlan) -> str: result = "Search Plan:\n\n" for i, search in enumerate(plan.searches, 1): result += f"{i}. Query: {search.query}\n" result += f" Reason: {search.reason}\n\n" return result # Create the question generator agent question_generator = Agent( name="QuestionGenerator", description=QUESTION_GENERATION_INSTRUCTIONS, model="gpt-4" ) # Create the planner agent first planner_agent = Agent( name="PlannerAgent", description=INSTRUCTIONS, model="gpt-4", output_type=WebSearchPlan ) # Create the question generation function async def generate_question(query: str, previous_answers: List[str] = None) -> str: """Generate a question based on the query and previous answers.""" try: context = { "query": query, "previous_answers": previous_answers or [] } result = await Runner.run(question_generator, context) if "error" in result: raise Exception(result["error"]) if "final_output" not in result: raise Exception("No final output in response") return result["final_output"] except Exception as e: print(f"Error in generate_question: {str(e)}") raise # Create a function to handle the planning @function_tool( name="plan_searches", description="Plan web searches based on a research query and context." ) async def plan_searches(query: str) -> WebSearchPlan: """Plan web searches based on a research query and context.""" try: # Create a default search plan if something goes wrong default_plan = WebSearchPlan( searches=[ WebSearchItem( query=query, reason="Default search based on original query" ) ] ) # Run the planner agent result = await Runner.run(planner_agent, {"query": query}) if "error" in result: print(f"Error in planner agent: {result['error']}") return default_plan if "final_output" not in result or result["final_output"] is None: print("No final output from planner agent") return default_plan # Try to parse the result as a WebSearchPlan try: if isinstance(result["final_output"], str): return WebSearchPlan.model_validate_json(result["final_output"]) return result["final_output"] except Exception as e: print(f"Error parsing search plan: {str(e)}") return default_plan except Exception as e: print(f"Error in plan_searches: {str(e)}") return default_plan # Add the plan_searches function as a tool to the planner agent planner_agent.tools = [plan_searches]