{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa9f9110-ea74-43af-aa72-6b45518abd6e", "metadata": {}, "outputs": [], "source": [ "from langchain import hub\n", "from langchain_openai import ChatOpenAI\n", "from langchain_community.tools.tavily_search import TavilySearchResults\n", "from langgraph.prebuilt.messages_executor import create_messages_executor\n", "from langchain_core.messages import HumanMessage" ] }, { "cell_type": "code", "execution_count": 2, "id": "0f005b2d-ddc0-4d60-8af9-9eb3dbeb45b7", "metadata": {}, "outputs": [], "source": [ "tools = [TavilySearchResults(max_results=1)]\n", "model = ChatOpenAI()" ] }, { "cell_type": "code", "execution_count": 3, "id": "02831581-f1ba-4701-ba33-f0f68468907d", "metadata": {}, "outputs": [], "source": [ "from langchain.tools.render import format_tool_to_openai_function" ] }, { "cell_type": "code", "execution_count": 4, "id": "a5c0ca12-4922-461c-b740-62ff99f8ae56", "metadata": {}, "outputs": [], "source": [ "model = model.bind_functions([format_tool_to_openai_function(t) for t in tools])" ] }, { "cell_type": "code", "execution_count": 5, "id": "57547622-ddd8-4179-aa4a-e1b69ca4523c", "metadata": {}, "outputs": [], "source": [ "from langgraph.prebuilt.tool_executor import ToolExecutor\n", "tool_executor = ToolExecutor(tools)" ] }, { "cell_type": "code", "execution_count": 6, "id": "96141ebd-32af-4c9d-a0b0-f46482b8bb88", "metadata": {}, "outputs": [], "source": [ "from typing import TypedDict, Annotated, Sequence\n", "import operator\n", "from langchain_core.messages import BaseMessage\n", "# We create the AgentState that we will pass around\n", "# This simply involves a list of messages\n", "# We want steps to return messages to append to the list\n", "# So we annotate the messages attribute with operator.add\n", "class AgentState(TypedDict):\n", " messages: Annotated[Sequence[BaseMessage], operator.add]" ] }, { "cell_type": "code", "execution_count": 20, "id": "f422dc99-672e-414f-88b3-1a6dd21b6882", "metadata": {}, "outputs": [], "source": [ "from langchain_core.agents import AgentAction\n", "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", " messages = state['messages']\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", " return \"end\"\n", " # Otherwise if there is, we continue\n", " else:\n", " return \"continue\"\n", "\n", "# Define the function that calls the model\n", "def call_model(state):\n", " messages = state['messages']\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}\n", "\n", "# Define the function to execute tools\n", "def call_tool(state):\n", " messages = state['messages']\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an AgentAction from the function_call\n", " action = AgentAction(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", " log=\"\",\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", " # We use the response to create a FunctionMessage\n", " function_message = FunctionMessage(content=str(response), name=action.tool)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [function_message]}\n", "\n" ] }, { "cell_type": "code", "execution_count": 21, "id": "1133ec83-7af9-4444-9f88-c793fbdce214", "metadata": {}, "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", "# Define the two nodes we will cycle between\n", "workflow.add_node(\"agent\", call_model)\n", "workflow.add_node(\"action\", call_tool)\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", "app = workflow.compile()" ] }, { "cell_type": "code", "execution_count": 22, "id": "289c648f-bfc6-464f-8df9-50be8b1b9e48", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'messages': [AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\\n \"query\": \"weather in San Francisco\"\\n}', 'name': 'tavily_search_results_json'}})]}\n", "----\n", "{'messages': [FunctionMessage(content=\"[{'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 Francisco80 deg, E Cloud Cover Mostly Cloudy 18,000 ft Mostly Clear 4,000 ft Partly Cloudy 15,000 ft Raw: KSFO 121956Z 08006KT 10SM FEW040 SCT150 BKN180 11/07 A3028 RMK AO2 SLP254 T01110067 This report shows the past weather for San Francisco, providing a weather history for January 2024.'}]\", name='tavily_search_results_json')]}\n", "----\n", "{'messages': [AIMessage(content='The weather in San Francisco is currently not available. However, you can check the weather history for January 2024 in San Francisco on [weatherspark.com](https://weatherspark.com/h/m/557/2024/1/Historical-Weather-in-January-2024-in-San-Francisco-California-United-States).')]}\n", "----\n", "{'messages': [HumanMessage(content='what is the weather in sf'), AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\\n \"query\": \"weather in San Francisco\"\\n}', 'name': 'tavily_search_results_json'}}), FunctionMessage(content=\"[{'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 Francisco80 deg, E Cloud Cover Mostly Cloudy 18,000 ft Mostly Clear 4,000 ft Partly Cloudy 15,000 ft Raw: KSFO 121956Z 08006KT 10SM FEW040 SCT150 BKN180 11/07 A3028 RMK AO2 SLP254 T01110067 This report shows the past weather for San Francisco, providing a weather history for January 2024.'}]\", name='tavily_search_results_json'), AIMessage(content='The weather in San Francisco is currently not available. However, you can check the weather history for January 2024 in San Francisco on [weatherspark.com](https://weatherspark.com/h/m/557/2024/1/Historical-Weather-in-January-2024-in-San-Francisco-California-United-States).')]}\n", "----\n" ] } ], "source": [ "inputs = {\"messages\": [HumanMessage(content=\"what is the weather in sf\")]}\n", "for s in app.stream(inputs):\n", " print(list(s.values())[0])\n", " print(\"----\")" ] }, { "cell_type": "code", "execution_count": null, "id": "4cd4b39f-831a-4818-bf56-99cf301b0555", "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 }