mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
20 KiB
20 KiB
In [1]:
!pip install --quiet -U langchain langchain_openai tavily-python[1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m A new release of pip is available: [0m[31;49m23.3.2[0m[39;49m -> [0m[32;49m24.0[0m [1m[[0m[34;49mnotice[0m[1;39;49m][0m[39;49m To update, run: [0m[32;49mpython3.11 -m pip install --upgrade pip[0m
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:")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"In [38]:
from langchain_community.tools.tavily_search import TavilySearchResults
tools = [TavilySearchResults(max_results=3)]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_executorIn [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....\'}]')]}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: strIn [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.'])
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)
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 FalseIn [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 [ ]: