Files
langgraph/examples/plan-and-execute/plan-and-execute.ipynb
T

20 KiB

Plan-and-Execute

This notebook shows how to create a "plan-and-execute" style agent. This is heavily inspired by the Plan-and-Solve paper as well as the Baby-AGI project.

The core idea is to first come up with a multi-step plan, and then go through that plan one item at a time. After accomplishing a particular task, you can then revisit the plan and modify as appropriate.

This compares to a typical ReAct style agent where you think one step at a time. The advantages of this "plan-and-execute" style agent are:

  1. Explicit long term planning (which even really strong LLMs can struggle with)
  2. Ability to use smaller/weaker models for the execution step, only using larger/better models for the planning step

Setup

First, we need to install the packages required.

In [1]:
!pip install --quiet -U langchain langchain_openai tavily-python
[notice] A new release of pip is available: 23.3.2 -> 24.0
[notice] To update, run: python3.11 -m pip install --upgrade pip

Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)

In [ ]:
import os
import getpass

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API Key:")

Optionally, we can set API key for LangSmith tracing, which will give us best-in-class observability.

In [ ]:
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass("LangSmith API Key:")
In [37]:
import os
os.environ["LANGCHAIN_PROJECT"] = "brex"

Define Tools

We will first define the tools we want to use. For this simple example, we will use a built-in search tool via Tavily. However, it is really easy to create your own tools - see documentation here on how to do that.

In [38]:
from langchain_community.tools.tavily_search import TavilySearchResults

tools = [TavilySearchResults(max_results=3)]

Define our Execution Agent

Now we will create the execution agent we want to use to execute tasks. Note that for this example, we will be using the same execution agent for each task, but this doesn't HAVE to be the case.

In [39]:
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain_openai import ChatOpenAI
# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")
# Choose the LLM that will drive the agent
llm = ChatOpenAI(model="gpt-4-turbo-preview")
# Construct the OpenAI Functions agent
agent_runnable = create_openai_functions_agent(llm, tools, prompt)
In [40]:
from langgraph.prebuilt import create_agent_executor
In [41]:
agent_executor = create_agent_executor(agent_runnable, tools)
In [42]:
agent_executor.invoke({"input": "who is the winnner of the us open", "chat_history": []})
Out [42]:
{'input': 'who is the winnner of the us open',
 'chat_history': [],
 'agent_outcome': AgentFinish(return_values={'output': 'The winners of the US Open in 2023 are:\n\n- For tennis, Coco Gauff won her first Grand Slam title at the US Open 2023 with a comeback victory against Aryna Sabalenka. [Source](https://sports.yahoo.com/us-open-2023-coco-gauff-wins-1st-grand-slam-title-with-wild-comeback-vs-aryna-sabalenka-222431287.html)\n\n- In golf, Wyndham Clark won the 2023 US Open, marking his first major championship victory. The tournament took place at the Los Angeles Country Club. [Source](https://www.nbclosangeles.com/news/sports/golf/wyndham-clark-wins-2023-us-open-for-first-major-championship/3172672/)'}, log='The winners of the US Open in 2023 are:\n\n- For tennis, Coco Gauff won her first Grand Slam title at the US Open 2023 with a comeback victory against Aryna Sabalenka. [Source](https://sports.yahoo.com/us-open-2023-coco-gauff-wins-1st-grand-slam-title-with-wild-comeback-vs-aryna-sabalenka-222431287.html)\n\n- In golf, Wyndham Clark won the 2023 US Open, marking his first major championship victory. The tournament took place at the Los Angeles Country Club. [Source](https://www.nbclosangeles.com/news/sports/golf/wyndham-clark-wins-2023-us-open-for-first-major-championship/3172672/)'),
 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'US Open winner 2023'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'US Open winner 2023'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"US Open winner 2023"}', 'name': 'tavily_search_results_json'}})]),
   '[{\'url\': \'https://sports.yahoo.com/us-open-2023-coco-gauff-wins-1st-grand-slam-title-with-wild-comeback-vs-aryna-sabalenka-222431287.html\', \'content\': \'— US Open Tennis (@usopen) September 9, 2023  — US Open Tennis (@usopen) September 9, 2023  US Open 2023: Coco Gauff wins 1st Grand Slam title with wild comeback vs. Aryna Sabalenka  What a backhand winner from Coco Gauff! pic.twitter.com/JhDcFpsJ4E — US Open Tennis (@usopen) September 9, 2023— US Open Tennis (@usopen) September 9, 2023 Gauff got the momentum change the crowd was looking for early in the second set, breaking Sabalenka to go up 3-1 and holding serve from there to take ...\'}, {\'url\': \'https://www.nbclosangeles.com/news/sports/golf/wyndham-clark-wins-2023-us-open-for-first-major-championship/3172672/\', \'content\': "Wyndham Clark wins 2023 US Open for first major championship  2023 US Open features a record purse. Here\'s how much the winning golfer will make  Clark on Sunday claimed the 2023 US Open title at the Los Angeles Country Club, making it his first major championship  US Open champion in 2011 and a four-time total major winner -- who recorded a nine-under.Clark on Sunday claimed the 2023 US Open title at the Los Angeles Country Club, making it his first major championship triumph. The 29-year-old finished the tournament going 10-under, just edging ..."}, {\'url\': \'https://www.sportingnews.com/us/golf/news/us-open-2023-live-scores-results-leaderboard/jbmxrpro5jc37drgq8e2lehn\', \'content\': \'MORE: Watch the 2023 U.S. Open live with Fubo (free trial) U.S. Open leaderboard 2023  Edition Who won the U.S. Open in 2023? Complete scores, results, highlights from Los Angeles Country Club  The golf world headed to the City of Angels — Los Angeles — for the 2023 U.S. Open.  MORE:\\xa0How much prize money does the U.S. Open winner make?Nick Brinkerhoff 06-19-2023 • 23 min read (Getty Images) The golf world headed to the City of Angels — Los Angeles — for the 2023 U.S. Open. And the tournament got its Hollywood ending....\'}]')]}

Define the State

Let's now start by defining the state the track for this agent.

First, we will need to track the current plan. Let's represent that as a list of strings.

Next, we should track previously executed steps. Let's represent that as a list of tuples (these tuples will contain the step and then the result)

Finally, we need to have some state to represent the final response as well as the original input.

In [43]:
from langchain_core.pydantic_v1 import BaseModel, Field
from typing import List, Tuple, Annotated, TypedDict
import operator


class PlanExecute(TypedDict):

    input: str 
    plan: List[str]
    past_steps: Annotated[List[Tuple], operator.add]
    response: str

Planning Step

Let's now think about creating the planning step. This will use function calling to create a plan.

In [44]:
from langchain_core.pydantic_v1 import BaseModel


class Plan(BaseModel):
    """Plan to follow in future"""
    steps: List[str] = Field(description="different steps to follow, should be in sorted order")
In [45]:
from langchain.chains.openai_functions import create_structured_output_runnable
from langchain_core.prompts import ChatPromptTemplate

planner_prompt = ChatPromptTemplate.from_template("""For the given objective, come up with a simple step by step plan. \
This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps. \
The result of the final step should be the final answer. Make sure that each step has all the information needed - do not skip steps.

{objective}""")
planner = create_structured_output_runnable(Plan, ChatOpenAI(model="gpt-4-turbo-preview", temperature=0), planner_prompt)
In [46]:
planner.invoke({'objective': 'what is the hometown of the current Australia open winner?'})
Out [46]:
Plan(steps=['Identify the current year.', 'Search for the Australia Open winner of the current year.', 'Find the hometown of the identified winner.'])

Re-Plan Step

Now, let's create a step that re-does the plan based on the result of the previous step.

In [47]:
from langchain.chains.openai_functions import create_openai_fn_runnable
class Response(BaseModel):
    """Response to user."""
    response: str

replanner_prompt = ChatPromptTemplate.from_template("""For the given objective, come up with a simple step by step plan. \
This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps. \
The result of the final step should be the final answer. Make sure that each step has all the information needed - do not skip steps.

Your objective was this:
{input}

Your original plan was this:
{plan}

You have currently done the follow steps:
{past_steps}

Update your plan accordingly. If no more steps are needed and you can return to the user, then respond with that. Otherwise, fill out the plan. Only add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.""")


replanner = create_openai_fn_runnable([Plan, Response], ChatOpenAI(model="gpt-4-turbo-preview", temperature=0), replanner_prompt)

Create the Graph

We can now create the graph!

In [48]:
async def execute_step(state: PlanExecute):
    task = state['plan'][0]
    agent_response = await agent_executor.ainvoke({"input": task, "chat_history": []})
    return {"past_steps": (task, agent_response['agent_outcome'].return_values['output'])}

async def plan_step(state: PlanExecute):
    plan = await planner.ainvoke({"objective": state["input"]})
    return {"plan": plan.steps}

async def replan_step(state: PlanExecute):
    output = await replanner.ainvoke(state)
    if isinstance(output, Response):
        return {"response": output.response}
    else:
        return {"plan": output.steps}

def should_end(state: PlanExecute):
    if state['response']:
        return True
    else:
        return False
In [49]:
from langgraph.graph import StateGraph, END

workflow = StateGraph(PlanExecute)

# Add the plan node
workflow.add_node("planner", plan_step)

# Add the execution step
workflow.add_node("agent", execute_step)

# Add a replan node
workflow.add_node("replan", replan_step)

workflow.set_entry_point("planner")

# From plan we go to agent
workflow.add_edge('planner', 'agent')

# From agent, we replan
workflow.add_edge("agent", "replan")

workflow.add_conditional_edges(
    "replan",
    # Next, we pass in the function that will determine which node is called next.
    should_end,
    {
        # If `tools`, then we call the tool node.
        True: END,
        False: "agent",
    }
)

# Finally, we compile it!
# This compiles it into a LangChain Runnable,
# meaning you can use it as you would any other runnable
app = workflow.compile()
In [50]:
from langchain_core.messages import HumanMessage
config = {"recursion_limit": 50}
inputs = {"input": "what is the hometown of the 2024 Australia open winner?"}
async for event in app.astream(inputs, config=config):
    for k, v in event.items():
        if k != "__end__":
            print(v)
{'plan': ['Identify the winner of the 2024 Australia Open.', "Research the winner's biography to find their place of birth or hometown.", 'Confirm the hometown of the 2024 Australia Open winner.']}
{'past_steps': ('Identify the winner of the 2024 Australia Open.', "The winners of the 2024 Australian Open were Jannik Sinner in the men's singles category and Aryna Sabalenka in the women's singles category.")}
{'plan': ["Research Jannik Sinner's biography to find his place of birth or hometown.", "Research Aryna Sabalenka's biography to find her place of birth or hometown.", 'Confirm the hometown of Jannik Sinner.', 'Confirm the hometown of Aryna Sabalenka.']}
{'past_steps': ("Research Jannik Sinner's biography to find his place of birth or hometown.", 'Jannik Sinner was born in Innichen, Italy. This town is also known as San Candido, which is mentioned as his hometown.')}
{'plan': ["Research Aryna Sabalenka's biography to find her place of birth or hometown.", 'Confirm the hometown of Aryna Sabalenka.']}
{'past_steps': ("Research Aryna Sabalenka's biography to find her place of birth or hometown.", 'Aryna Sabalenka was born in Minsk, the capital of Belarus.')}
{'response': 'The hometown of the 2024 Australia Open winners are Innichen (San Candido), Italy for Jannik Sinner and Minsk, Belarus for Aryna Sabalenka. No further steps are needed.'}
In [ ]:
In [ ]: