{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f725852e-71ef-4615-8cac-011a516fbe72",
   "metadata": {},
   "source": [
    "# Agent Executor From Scratch\n",
    "\n",
    "In this notebook we will create an agent with a search tool. However, at the start we will force the agent to call the search tool (and then let it do whatever it wants after). This is useful when you want to force agents to call particular tools, but still want flexibility of what happens after that.\n",
    "\n",
    "This examples builds off the base agent executor. It is highly recommended you learn about that executor before going through this notebook. You can find documentation for that example [here](./base.ipynb).\n",
    "\n",
    "Any modifications of that example are called below with **MODIFICATION**, so if you are looking for the differences you can just search for that."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6821de30-6eeb-4f70-b0a7-e05d3187b14b",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First we need to install the packages required"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "694cfc4c-22a7-495d-930d-56b21d850ff9",
   "metadata": {},
   "outputs": [],
   "source": ["%%capture --no-stderr\n%pip install --quiet -U langgraph langchain langchain_openai tavily-python"]
  },
  {
   "cell_type": "markdown",
   "id": "dc039752-6d34-4ad4-aa31-9a10f4d4d597",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30c06a84-291a-4f58-9d31-53d3b56a3def",
   "metadata": {},
   "outputs": [],
   "source": ["import getpass\nimport os\n\nos.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\nos.environ[\"TAVILY_API_KEY\"] = getpass.getpass(\"Tavily API Key:\")"]
  },
  {
   "cell_type": "markdown",
   "id": "5e7f4767-54fb-4b6e-bd9a-3d433df924fb",
   "metadata": {},
   "source": [
    "Optionally, we can set API key for [LangSmith tracing](https://smith.langchain.com/), which will give us best-in-class observability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8fb285a-7e6e-46fc-a273-43ab1a676189",
   "metadata": {},
   "outputs": [],
   "source": ["os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\nos.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass(\"LangSmith API Key:\")"]
  },
  {
   "cell_type": "markdown",
   "id": "5dace4a9-7c9e-4da2-bf7b-e58d0d05581e",
   "metadata": {},
   "source": [
    "## Create the LangChain agent\n",
    "\n",
    "First, we will create the LangChain agent. For more information on LangChain agents, see [this documentation](https://python.langchain.com/v0.2/docs/concepts/#agents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4499eb16-bca8-4a60-9a3a-2f34ae3f7078",
   "metadata": {},
   "outputs": [],
   "source": ["from langchain import hub\nfrom langchain.agents import create_openai_functions_agent\nfrom langchain_community.tools.tavily_search import TavilySearchResults\nfrom langchain_openai.chat_models import ChatOpenAI\n\ntools = [TavilySearchResults(max_results=1)]\n\n# Get the prompt to use - you can modify this!\nprompt = hub.pull(\"hwchase17/openai-functions-agent\")\n\n# Choose the LLM that will drive the agent\nllm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", streaming=True)\n\n# Construct the OpenAI Functions agent\nagent_runnable = create_openai_functions_agent(llm, tools, prompt)"]
  },
  {
   "cell_type": "markdown",
   "id": "972e58b3-fe3c-449d-b3c4-8fa2217afd07",
   "metadata": {},
   "source": [
    "## Define the graph state\n",
    "\n",
    "We now define the graph state. The state for the traditional LangChain agent has a few attributes:\n",
    "\n",
    "1. `input`: This is the input string representing the main ask from the user, passed in as input.\n",
    "2. `chat_history`: This is any previous conversation messages, also passed in as input.\n",
    "3. `intermediate_steps`: This is list of actions and corresponding observations that the agent takes over time. This is updated each iteration of the agent.\n",
    "4. `agent_outcome`: This is the response from the agent, either an AgentAction or AgentFinish. The AgentExecutor should finish when this is an AgentFinish, otherwise it should call the requested tools.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c941fb10-dbe5-4d6a-ab7d-133d01c33cc4",
   "metadata": {},
   "outputs": [],
   "source": ["import operator\nfrom typing import Annotated, TypedDict, Union\n\nfrom langchain_core.agents import AgentAction, AgentFinish\nfrom langchain_core.messages import BaseMessage\n\n\nclass 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]"]
  },
  {
   "cell_type": "markdown",
   "id": "cd27b281-cc9a-49c9-be78-8b98a7d905c4",
   "metadata": {},
   "source": [
    "## Define the nodes\n",
    "\n",
    "We now need to define a few different nodes in our graph.\n",
    "In `langgraph`, a node can be either a function or a [runnable](https://python.langchain.com/v0.2/docs/concepts/#langchain-expression-language-lcel).\n",
    "There are two main nodes we need for this:\n",
    "\n",
    "1. The agent: responsible for deciding what (if any) actions to take.\n",
    "2. A function to invoke tools: if the agent decides to take an action, this node will then execute that action.\n",
    "\n",
    "We will also need to define some edges.\n",
    "Some of these edges may be conditional.\n",
    "The reason they are conditional is that based on the output of a node, one of several paths may be taken.\n",
    "The path that is taken is not known until that node is run (the LLM decides).\n",
    "\n",
    "1. Conditional Edge: after the agent is called, we should either:\n",
    "   a. If the agent said to take an action, then the function to invoke tools should be called\n",
    "   b. If the agent said that it was finished, then it should finish\n",
    "2. Normal Edge: after the tools are invoked, it should always go back to the agent to decide what to do next\n",
    "\n",
    "Let's define the nodes, as well as a function to decide how what conditional edge to take."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d61a970d-edf4-4eef-9678-28bab7c72331",
   "metadata": {},
   "outputs": [],
   "source": ["from langchain_core.agents import AgentFinish\n\nfrom 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\ntool_executor = ToolExecutor(tools)\n\n\n# Define the agent\ndef run_agent(data):\n    agent_outcome = agent_runnable.invoke(data)\n    return {\"agent_outcome\": agent_outcome}\n\n\n# Define the function to execute tools\ndef 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\n# Define logic that will be used to determine which conditional edge to go down\ndef 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": "markdown",
   "id": "02437e83-5485-4827-87e6-7ad1d02cf9be",
   "metadata": {},
   "source": [
    "**MODIFICATION**\n",
    "\n",
    "Here we create a node that returns an AgentAction that just calls the Tavily search with the input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2ed8463e-73e5-417d-9fab-be6bcee87835",
   "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": "df25d899-2338-4f31-a8bf-0582a2eec325",
   "metadata": {},
   "outputs": [],
   "source": ["from langchain_core.agents import AgentActionMessageLog\n\n\ndef 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": "markdown",
   "id": "c0b211f4-0c5c-4792-b18d-cd70907c71e7",
   "metadata": {},
   "source": [
    "## Define the graph\n",
    "\n",
    "We can now put it all together and define the graph!\n",
    "\n",
    "**MODIFICATION**\n",
    "\n",
    "We now add a new `first_agent` node which we set as the entrypoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c4054dde-4618-49b7-998a-daa0c1d6d6c0",
   "metadata": {},
   "outputs": [],
   "source": ["from langgraph.graph import END, StateGraph, START\n\n# Define a new graph\nworkflow = StateGraph(AgentState)\n\n# Define the two nodes we will cycle between\nworkflow.add_node(\"agent\", run_agent)\nworkflow.add_node(\"action\", execute_tools)\nworkflow.add_node(\"first_agent\", first_agent)\n\n# Set the entrypoint as `agent`\n# This means that this node is the first one called\nworkflow.add_edge(START, \"first_agent\")\n\n# We now add a conditional edge\nworkflow.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.\nworkflow.add_edge(\"action\", \"agent\")\n\n# After the first agent, we want to take an action\nworkflow.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\napp = workflow.compile()"]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "214ae46e-c297-465d-86db-2b0312ed3530",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[])}\n",
      "----\n",
      "{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[]), \"[{'url': 'https://www.whereandwhen.net/when/north-america/california/san-francisco-ca/january/', 'content': 'Best time to go to San Francisco? Weather in San Francisco in january 2024  How was the weather last january? Here is the day by day recorded weather in San Francisco in january 2023:  Seasonal average climate and temperature of San Francisco in january  The climate of San Francisco in january is tolerableWeather in San Francisco in january 2024. The weather in San Francisco in january comes from statistical data on the past years. You can view the weather statistics the entire month, but also by using the tabs for the beginning, the middle and the end of the month. ... 15-01-2023 50°F to 52°F. 16-01-2023 45°F to 52°F. 17-01-2023 45°F to ...'}]\")]}\n",
      "----\n",
      "{'agent_outcome': AgentFinish(return_values={'output': 'The weather in San Francisco in January is typically tolerable, with temperatures ranging from 45°F to 52°F. If you need more specific and up-to-date information about the current weather in San Francisco, I can look it up for you.'}, log='The weather in San Francisco in January is typically tolerable, with temperatures ranging from 45°F to 52°F. If you need more specific and up-to-date information about the current weather in San Francisco, I can look it up for you.')}\n",
      "----\n",
      "{'input': 'what is the weather in sf', 'chat_history': [], 'agent_outcome': AgentFinish(return_values={'output': 'The weather in San Francisco in January is typically tolerable, with temperatures ranging from 45°F to 52°F. If you need more specific and up-to-date information about the current weather in San Francisco, I can look it up for you.'}, log='The weather in San Francisco in January is typically tolerable, with temperatures ranging from 45°F to 52°F. If you need more specific and up-to-date information about the current weather in San Francisco, I can look it up for you.'), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input='what is the weather in sf', log='', message_log=[]), \"[{'url': 'https://www.whereandwhen.net/when/north-america/california/san-francisco-ca/january/', 'content': 'Best time to go to San Francisco? Weather in San Francisco in january 2024  How was the weather last january? Here is the day by day recorded weather in San Francisco in january 2023:  Seasonal average climate and temperature of San Francisco in january  The climate of San Francisco in january is tolerableWeather in San Francisco in january 2024. The weather in San Francisco in january comes from statistical data on the past years. You can view the weather statistics the entire month, but also by using the tabs for the beginning, the middle and the end of the month. ... 15-01-2023 50°F to 52°F. 16-01-2023 45°F to 52°F. 17-01-2023 45°F to ...'}]\")]}\n",
      "----\n"
     ]
    }
   ],
   "source": ["inputs = {\"input\": \"what is the weather in sf\", \"chat_history\": []}\nfor s in app.stream(inputs):\n    print(list(s.values())[0])\n    print(\"----\")"]
  },
  {
   "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
}
