Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

write me an ai agent example using openai-agents-python library. Make it so the first…

  1. User

    write me an ai agent example using openai-agents-python library. Make it so the first call creates a masterplan after which the plan then gets executed

  2. Gemini Assistant

    Okay, this is a fantastic request that highlights a common pattern in more complex AI agents: planning before execution.

    We'll create an OpenAIAgent that, on its first run for a given goal, uses a special tool to store a master plan. On subsequent runs for the same goal, it will detect the stored plan and proceed to execute it using other functional tools.

    Key Concepts:

    1. OpenAIAgent: LlamaIndex's agent that leverages OpenAI's function calling capabilities.
    2. Tools: Functions wrapped for the agent to call. We'll have:
      • store_plan: To save the master plan generated by the agent.
      • search_web (simulated): An example execution tool.
      • summarize_info (simulated): Another example execution tool.
    3. State Management: A simple in-memory variable to hold the master plan. In a real application, this would be a database, file, or more robust state management system.
    4. Phased Execution: The agent's run method will have two distinct phases: planning and execution, controlled by the presence of a stored plan.

    Setup

    First, ensure you have the necessary libraries installed and your OpenAI API key set up.

    pip install llama-index llama-index-llms-openai llama-index-agent-openai
    

    Set your API key:

    export OPENAI_API_KEY="YOUR_API_KEY"
    

    Python Code

    import logging
    from typing import List, Dict, Any
    
    from llama_index.llms.openai import OpenAI
    from llama_index.agent.openai import OpenAIAgent
    from llama_index.core.tools import FunctionTool
    from llama_index.core.llms import ChatMessage, MessageRole
    
    # Configure logging for better visibility
    logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
    
    # --- 1. Global State for Master Plan (Simple in-memory storage) ---
    # In a real app, this would be persisted (e.g., database, file, Redis)
    _stored_master_plan: str = None
    _current_goal: str = None # To track which goal the plan belongs to
    
    # --- 2. Define Tools for the Agent ---
    
    def store_plan(plan_text: str, goal: str) -> str:
        """
        Stores the master plan generated by the agent for a specific goal.
        This tool should be called by the agent after it formulates a plan.
        """
        global _stored_master_plan, _current_goal
        _stored_master_plan = plan_text
        _current_goal = goal
        logging.info(f"Master plan for goal '{goal}' stored:\n{plan_text}")
        return f"Master plan for goal '{goal}' successfully stored."
    
    def retrieve_plan() -> str:
        """
        Retrieves the currently stored master plan.
        """
        global _stored_master_plan
        return _stored_master_plan if _stored_master_plan else "No master plan stored."
    
    def search_web(query: str) -> str:
        """
        Simulates searching the web for information based on a query.
        """
        logging.info(f"Simulating web search for: '{query}'")
        # Replace with actual web search API (e.g., Google Search API, SerpApi)
        if "weather in San Francisco" in query.lower():
            return "The current weather in San Francisco is partly cloudy, 65°F (18°C), with a gentle breeze."
        elif "population of New York City" in query.lower():
            return "The estimated population of New York City in 2023 is around 8.5 million."
        elif "capital of France" in query.lower():
            return "The capital of France is Paris."
        else:
            return f"Simulated web search result for '{query}': Relevant information found."
    
    def summarize_info(text: str) -> str:
        """
        Simulates summarizing a given piece of text.
        """
        logging.info(f"Simulating summarization for text: '{text[:100]}...'")
        # In a real scenario, this would use a more advanced text summarization model
        return f"Summary: The key points from the provided text are: {text[:50]}... (full text was longer)."
    
    # Create FunctionTool instances
    store_plan_tool = FunctionTool.from_defaults(fn=store_plan)
    retrieve_plan_tool = FunctionTool.from_defaults(fn=retrieve_plan)
    search_web_tool = FunctionTool.from_defaults(fn=search_web)
    summarize_info_tool = FunctionTool.from_defaults(fn=summarize_info)
    
    # --- 3. Define the MasterPlanAgent Class ---
    
    class MasterPlanAgent:
        def __init__(self, llm: OpenAI):
            self.llm = llm
            # The agent will use different system prompts and potentially tool subsets
            # based on whether it's planning or executing.
            # For simplicity, we'll give both "phases" access to all tools here,
            # but their system prompts will guide their behavior.
    
            self.planning_agent_instance = OpenAIAgent.from_tools(
                tools=[store_plan_tool, search_web_tool, summarize_info_tool], # Planning agent needs to know about execution tools to plan for them
                llm=llm,
                verbose=True,
                system_prompt=(
                    "You are a sophisticated planning agent. Your primary objective is to break down complex goals into detailed, step-by-step master plans. "
                    "Each step should be actionable and clearly state which tool (if any) would be used. "
                    "Once you have formulated a complete plan, you MUST use the `store_plan` tool to save it. "
                    "Do NOT attempt to execute any part of the plan yourself; simply create and store the plan."
                )
            )
    
            self.execution_agent_instance = OpenAIAgent.from_tools(
                tools=[search_web_tool, summarize_info_tool, retrieve_plan_tool], # Execution agent needs execution tools and optionally retrieve_plan
                llm=llm,
                verbose=True,
                system_prompt=(
                    "You are a dedicated execution agent. Your task is to meticulously follow a pre-defined master plan. "
                    "Execute each step using the available tools (`search_web`, `summarize_info`). "
                    "Report on your progress after each significant step and provide a comprehensive final outcome based on the plan. "
                    "Do not deviate from the plan or generate new plans."
                )
            )
    
        def run(self, goal: str) -> str:
            global _stored_master_plan, _current_goal
    
            if _stored_master_plan is None or _current_goal != goal:
                # --- PHASE 1: Master Plan Creation ---
                logging.info(f"\n--- Initiating Master Plan Creation for goal: '{goal}' ---")
                logging.info("The agent will now create a plan and store it.")
    
                # The agent is prompted to create a plan and use the store_plan tool
                response = self.planning_agent_instance.chat(
                    f"Your new mission is: '{goal}'. Create a very detailed, step-by-step master plan. "
                    "Think about what information is needed, what tools to use for each step. "
                    "Once the plan is complete, call the `store_plan` tool with the full plan text and the original goal. "
                    "Example plan format: '1. Step one (Tool: search_web). 2. Step two (Tool: summarize_info).' etc. "
                )
                
                if _stored_master_plan and _current_goal == goal:
                    logging.info(f"\nMaster plan for '{goal}' successfully created and stored.")
                    return f"Master plan for '{goal}' created. Please run the agent again with the same goal to begin execution."
                else:
                    logging.error(f"\nFailed to create and store master plan for '{goal}'. Agent response:\n{response.response}")
                    _stored_master_plan = None # Ensure consistent state
                    _current_goal = None
                    return f"Failed to create master plan. Please try again. Agent's final thought: {response.response}"
            else:
                # --- PHASE 2: Master Plan Execution ---
                logging.info(f"\n--- Initiating Master Plan Execution for goal: '{goal}' ---")
                logging.info(f"Using stored plan:\n{_stored_master_plan}")
    
                # The agent is prompted to execute the stored plan
                # We explicitly pass the plan so the agent doesn't need to 'retrieve_plan' itself,
                # though it could if the prompt encouraged it.
                response = self.execution_agent_instance.chat(
                    f"You have the following master plan to execute for the goal '{goal}':\n\n"
                    f"'{_stored_master_plan}'\n\n"
                    "Execute this plan step-by-step using your tools. Report on your progress and provide a final summary of the outcome."
                )
                
                logging.info("\n--- Master Plan Execution Complete ---")
                # Reset plan state after execution for the next new goal
                _stored_master_plan = None
                _current_goal = None
                return f"Execution complete for goal '{goal}'. Final Outcome:\n{response.response}"
    
    # --- 4. Example Usage ---
    
    if __name__ == "__main__":
        llm = OpenAI(model="gpt-4o", temperature=0.1) # Using a capable model like gpt-4o or gpt-4 is recommended
    
        agent_orchestrator = MasterPlanAgent(llm=llm)
    
        my_goal_1 = "Find out the current weather in San Francisco and suggest what kind of activities would be good based on it."
        
        print("\n--- FIRST CALL: Creating Master Plan ---")
        result_1 = agent_orchestrator.run(my_goal_1)
        print(f"\nFirst Call Result:\n{result_1}")
        
        # Simulate waiting or a separate invocation
        print("\n\n--- SECOND CALL: Executing Master Plan ---")
        print(" (Simulating a separate run for the same goal) ")
        result_2 = agent_orchestrator.run(my_goal_1)
        print(f"\nSecond Call Result (Execution):\n{result_2}")
    
        print("\n\n--- THIRD CALL: NEW GOAL (Will create new plan) ---")
        my_goal_2 = "Discover the population of New York City and provide a short summary of recent demographic trends (simulated)."
        result_3 = agent_orchestrator.run(my_goal_2)
        print(f"\nThird Call Result:\n{result_3}")
    
        print("\n\n--- FOURTH CALL: Executing NEW GOAL ---")
        print(" (Simulating a separate run for the new goal) ")
        result_4 = agent_orchestrator.run(my_goal_2)
        print(f"\nFourth Call Result (Execution):\n{result_4}")
    

    How to Run and Observe:

    1. Save: Save the code as a Python file (e.g., master_agent.py).
    2. Run: Execute it from your terminal: python master_agent.py

    Expected Output Structure (Simplified):

    You will see detailed INFO logs from the agent (due to verbose=True) showing its thought process and tool calls.

    First Call Output:

    • You'll see --- Initiating Master Plan Creation ---
    • The agent will think, break down the goal, and eventually call the store_plan tool.
    • You'll see INFO: Master plan for goal '...' stored:\n[The detailed plan]
    • The final printed result will indicate that the plan was created and you need to run again for execution.

    Second Call Output (Same Goal):

    • You'll see --- Initiating Master Plan Execution ---
    • It will print the Using stored plan: message.
    • The agent will then proceed to execute the plan step-by-step, calling search_web and summarize_info as dictated by its stored plan and its prompt.
    • The final printed result will be the outcome of the execution.

    Third Call Output (New Goal):

    • It will revert to the --- Initiating Master Plan Creation --- phase because _stored_master_plan is now None (reset after the previous execution) or the _current_goal does not match.
    • A new plan will be created and stored for my_goal_2.

    Fourth Call Output (New Goal Execution):

    • It will enter the --- Initiating Master Plan Execution --- phase for my_goal_2.
    • It will execute the newly stored plan.

    This example clearly demonstrates how to build a phased AI agent using llama_index and OpenAIAgent, where the first interaction focuses on strategic planning, and subsequent interactions on tactical execution of that plan.