mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-30 19:59:40 +02:00
227 lines
11 KiB
Plaintext
227 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",
|
|
" inputs = data.copy()\n",
|
|
" if len(inputs['intermediate_steps']) > 5:\n",
|
|
" inputs['intermediate_steps'] = inputs['intermediate_steps'][-5:]\n",
|
|
" agent_outcome = agent_runnable.invoke(inputs)\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": "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",
|
|
"\n",
|
|
"# Set the entrypoint as `agent`\n",
|
|
"# This means that this node is the first one called\n",
|
|
"workflow.set_entry_point(\"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",
|
|
"# 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": 5,
|
|
"id": "214ae46e-c297-465d-86db-2b0312ed3530",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Output from node 'agent':\n",
|
|
"---\n",
|
|
"{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})])}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"Output from node 'action':\n",
|
|
"---\n",
|
|
"{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})]), \"[{'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 FranciscoThis report shows the past weather for San Francisco, providing a weather history for January 2024. It features all historical weather data series we have available, including the San Francisco temperature history for January 2024. You can drill down from year to month and even day level reports by clicking on the graphs.'}]\")]}\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"Output from node 'agent':\n",
|
|
"---\n",
|
|
"{'agent_outcome': AgentFinish(return_values={'output': \"I'm sorry, I couldn't find the current weather for San Francisco. If you'd like, I can search for the current weather using a different method.\"}, log=\"I'm sorry, I couldn't find the current weather for San Francisco. If you'd like, I can search for the current weather using a different method.\")}\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, I couldn't find the current weather for San Francisco. If you'd like, I can search for the current weather using a different method.\"}, log=\"I'm sorry, I couldn't find the current weather for San Francisco. If you'd like, I can search for the current weather using a different method.\"), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})]), \"[{'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 FranciscoThis report shows the past weather for San Francisco, providing a weather history for January 2024. It features all historical weather data series we have available, including the San Francisco temperature history for January 2024. You can drill down from year to month and even day level reports by clicking on the graphs.'}]\")]}\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
|
|
}
|