mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-31 04:09:49 +02:00
269 lines
11 KiB
Plaintext
269 lines
11 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "4499eb16-bca8-4a60-9a3a-2f34ae3f7078",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain import hub\n",
|
|
"from langchain.agents import create_openai_functions_agent\n",
|
|
"from langchain_openai.chat_models import ChatOpenAI\n",
|
|
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
|
"\n",
|
|
"tools = [TavilySearchResults(max_results=1)]\n",
|
|
"\n",
|
|
"# Get the prompt to use - you can modify this!\n",
|
|
"prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
|
|
"\n",
|
|
"# Choose the LLM that will drive the agent\n",
|
|
"llm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", streaming=True)\n",
|
|
"\n",
|
|
"# Construct the OpenAI Functions agent\n",
|
|
"agent_runnable = create_openai_functions_agent(llm, tools, prompt)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "c941fb10-dbe5-4d6a-ab7d-133d01c33cc4",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import TypedDict, Annotated, List, Union\n",
|
|
"from langchain_core.agents import AgentAction, AgentFinish\n",
|
|
"from langchain_core.messages import BaseMessage\n",
|
|
"import operator\n",
|
|
"\n",
|
|
"\n",
|
|
"class AgentState(TypedDict):\n",
|
|
" # The input string\n",
|
|
" input: str\n",
|
|
" # The list of previous messages in the conversation\n",
|
|
" chat_history: list[BaseMessage]\n",
|
|
" # The outcome of a given call to the agent\n",
|
|
" # Needs `None` as a valid type, since this is what this will start as\n",
|
|
" agent_outcome: Union[AgentAction, AgentFinish, None]\n",
|
|
" # List of actions and corresponding observations\n",
|
|
" # Here we annotate this with `operator.add` to indicate that operations to\n",
|
|
" # this state should be ADDED to the existing values (not overwrite it)\n",
|
|
" intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "d61a970d-edf4-4eef-9678-28bab7c72331",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain_core.agents import AgentFinish\n",
|
|
"from langgraph.prebuilt.tool_executor import ToolExecutor\n",
|
|
"\n",
|
|
"# This a helper class we have that is useful for running tools\n",
|
|
"# It takes in an agent action and calls that tool and returns the result\n",
|
|
"tool_executor = ToolExecutor(tools)\n",
|
|
"\n",
|
|
"# Define the agent\n",
|
|
"def run_agent(data):\n",
|
|
" agent_outcome = agent_runnable.invoke(data)\n",
|
|
" return {\"agent_outcome\": agent_outcome}\n",
|
|
"\n",
|
|
"# Define the function to execute tools\n",
|
|
"def execute_tools(data):\n",
|
|
" # Get the most recent agent_outcome - this is the key added in the `agent` above\n",
|
|
" agent_action = data['agent_outcome']\n",
|
|
" output = tool_executor.invoke(agent_action)\n",
|
|
" return {\"intermediate_steps\": [(agent_action, str(output))]}\n",
|
|
"\n",
|
|
"# Define logic that will be used to determine which conditional edge to go down\n",
|
|
"def should_continue(data):\n",
|
|
" # If the agent outcome is an AgentFinish, then we return `exit` string\n",
|
|
" # This will be used when setting up the graph to define the flow\n",
|
|
" if isinstance(data['agent_outcome'], AgentFinish):\n",
|
|
" return \"end\"\n",
|
|
" # Otherwise, an AgentAction is returned\n",
|
|
" # Here we return `continue` string\n",
|
|
" # This will be used when setting up the graph to define the flow\n",
|
|
" else:\n",
|
|
" return \"continue\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "4883e47a-0a15-429c-bf31-1e8afe982a77",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"'tavily_search_results_json'"
|
|
]
|
|
},
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"tools[0].name"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "fb16db55-ff1a-4e16-94c1-dcb8b2a8f0ba",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langchain_core.agents import AgentActionMessageLog\n",
|
|
"\n",
|
|
"def first_agent(inputs):\n",
|
|
" action = AgentActionMessageLog(\n",
|
|
" # We force call this tool\n",
|
|
" tool=\"tavily_search_results_json\",\n",
|
|
" # We just pass in the `input` key to this tool\n",
|
|
" tool_input=inputs[\"input\"],\n",
|
|
" log=\"\",\n",
|
|
" message_log=[]\n",
|
|
" )\n",
|
|
" return {\"agent_outcome\": action}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "c4054dde-4618-49b7-998a-daa0c1d6d6c0",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from langgraph.graph import END, StateGraph\n",
|
|
"\n",
|
|
"# Define a new graph\n",
|
|
"workflow = StateGraph(AgentState)\n",
|
|
"\n",
|
|
"# Define the two nodes we will cycle between\n",
|
|
"workflow.add_node(\"agent\", run_agent)\n",
|
|
"workflow.add_node(\"action\", execute_tools)\n",
|
|
"workflow.add_node(\"first_agent\", first_agent)\n",
|
|
"\n",
|
|
"# Set the entrypoint as `agent`\n",
|
|
"# This means that this node is the first one called\n",
|
|
"workflow.set_entry_point(\"first_agent\")\n",
|
|
"\n",
|
|
"# We now add a conditional edge\n",
|
|
"workflow.add_conditional_edges(\n",
|
|
" # First, we define the start node. We use `agent`.\n",
|
|
" # This means these are the edges taken after the `agent` node is called.\n",
|
|
" \"agent\",\n",
|
|
" # Next, we pass in the function that will determine which node is called next.\n",
|
|
" should_continue,\n",
|
|
" # Finally we pass in a mapping.\n",
|
|
" # The keys are strings, and the values are other nodes.\n",
|
|
" # END is a special node marking that the graph should finish.\n",
|
|
" # What will happen is we will call `should_continue`, and then the output of that\n",
|
|
" # will be matched against the keys in this mapping.\n",
|
|
" # Based on which one it matches, that node will then be called.\n",
|
|
" {\n",
|
|
" # If `tools`, then we call the tool node.\n",
|
|
" \"continue\": \"action\",\n",
|
|
" # Otherwise we finish.\n",
|
|
" \"end\": END\n",
|
|
" }\n",
|
|
")\n",
|
|
"\n",
|
|
"# We now add a normal edge from `tools` to `agent`.\n",
|
|
"# This means that after `tools` is called, `agent` node is called next.\n",
|
|
"workflow.add_edge('action', 'agent')\n",
|
|
"\n",
|
|
"workflow.add_edge('first_agent', 'action')\n",
|
|
"\n",
|
|
"# Finally, we compile it!\n",
|
|
"# This compiles it into a LangChain Runnable,\n",
|
|
"# meaning you can use it as you would any other runnable\n",
|
|
"chain = workflow.compile()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"id": "214ae46e-c297-465d-86db-2b0312ed3530",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Output from node 'first_agent':\n",
|
|
"---\n",
|
|
"{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[])}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"Output from node 'action':\n",
|
|
"---\n",
|
|
"{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[]), \"[{'url': 'https://weatherspark.com/h/m/557/2024/1/Historical-Weather-in-January-2024-in-San-Francisco-California-United-States', 'content': 'January 2024 Weather History in San Francisco California, United States Daily Precipitation in January 2024 in San Francisco Observed Weather in January 2024 in San Francisco San Francisco Temperature History January 2024 Hourly Temperature in January 2024 in San Francisco Hours of Daylight and Twilight in January 2024 in San FranciscoJanuary 2024 Weather History in San Francisco California, United States. The data for this report comes from the San Francisco International Airport. ... frigid 15°F freezing 32°F very cold 45°F cold 55°F cool 65°F comfortable 75°F warm 85°F hot 95°F sweltering. The hourly reported temperature, color coded into bands. ...'}]\")]}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"Output from node 'agent':\n",
|
|
"---\n",
|
|
"{'agent_outcome': AgentFinish(return_values={'output': \"I'm sorry, but I couldn't find the current weather in San Francisco. If you'd like, I can try another source to get the current weather for you.\"}, log=\"I'm sorry, but I couldn't find the current weather in San Francisco. If you'd like, I can try another source to get the current weather for you.\")}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"Output from node '__end__':\n",
|
|
"---\n",
|
|
"{'input': 'what is the weather in sf', 'chat_history': [], 'agent_outcome': AgentFinish(return_values={'output': \"I'm sorry, but I couldn't find the current weather in San Francisco. If you'd like, I can try another source to get the current weather for you.\"}, log=\"I'm sorry, but I couldn't find the current weather in San Francisco. If you'd like, I can try another source to get the current weather for you.\"), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[]), \"[{'url': 'https://weatherspark.com/h/m/557/2024/1/Historical-Weather-in-January-2024-in-San-Francisco-California-United-States', 'content': 'January 2024 Weather History in San Francisco California, United States Daily Precipitation in January 2024 in San Francisco Observed Weather in January 2024 in San Francisco San Francisco Temperature History January 2024 Hourly Temperature in January 2024 in San Francisco Hours of Daylight and Twilight in January 2024 in San FranciscoJanuary 2024 Weather History in San Francisco California, United States. The data for this report comes from the San Francisco International Airport. ... frigid 15°F freezing 32°F very cold 45°F cold 55°F cool 65°F comfortable 75°F warm 85°F hot 95°F sweltering. The hourly reported temperature, color coded into bands. ...'}]\")]}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"for output in chain.stream(\n",
|
|
" {\"input\": \"what is the weather in sf\", \"chat_history\": []}\n",
|
|
"):\n",
|
|
" # stream() yields dictionaries with output keyed by node name\n",
|
|
" for key, value in output.items():\n",
|
|
" print(f\"Output from node '{key}':\")\n",
|
|
" print(\"---\")\n",
|
|
" print(value)\n",
|
|
" print(\"\\n---\\n\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "2eb662bc-de7d-4a57-a3e8-2f00dcf4ff8b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3 (ipykernel)",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.11.1"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|