{
 "cells": [
  {
   "cell_type": "raw",
   "id": "17546ebb",
   "metadata": {},
   "source": [
    "---\n",
    "sidebar_position: 4\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4c03f40-1328-412d-8a48-1db0cd481b77",
   "metadata": {},
   "source": [
    "# Build an Agent with AgentExecutor (Legacy)\n",
    "\n",
    ":::{.callout-important}\n",
    "This section will cover building with the legacy LangChain AgentExecutor. These are fine for getting started, but past a certain point, you will likely want flexibility and control that they do not offer. For working with more advanced agents, we'd recommend checking out [LangGraph Agents](/docs/concepts/#langgraph) or the [migration guide](/docs/how_to/migrate_agent/)\n",
    ":::\n",
    "\n",
    "By themselves, language models can't take actions - they just output text.\n",
    "A big use case for LangChain is creating **agents**.\n",
    "Agents are systems that use an LLM as a reasoning engine to determine which actions to take and what the inputs to those actions should be.\n",
    "The results of those actions can then be fed back into the agent and it determines whether more actions are needed, or whether it is okay to finish.\n",
    "\n",
    "In this tutorial, we will build an agent that can interact with multiple different tools: one being a local database, the other being a search engine. You will be able to ask this agent questions, watch it call tools, and have conversations with it.\n",
    "\n",
    "## Concepts\n",
    "\n",
    "Concepts we will cover are:\n",
    "- Using [language models](/docs/concepts/#chat-models), in particular their tool calling ability\n",
    "- Creating a [Retriever](/docs/concepts/#retrievers) to expose specific information to our agent\n",
    "- Using a Search [Tool](/docs/concepts/#tools) to look up things online\n",
    "- [`Chat History`](/docs/concepts/#chat-history), which allows a chatbot to \"remember\" past interactions and take them into account when responding to follow-up questions. \n",
    "- Debugging and tracing your application using [LangSmith](/docs/concepts/#langsmith)\n",
    "\n",
    "## Setup\n",
    "\n",
    "### Jupyter Notebook\n",
    "\n",
    "This guide (and most of the other guides in the documentation) uses [Jupyter notebooks](https://jupyter.org/) and assumes the reader is as well. Jupyter notebooks are perfect for learning how to work with LLM systems because oftentimes things can go wrong (unexpected output, API down, etc) and going through guides in an interactive environment is a great way to better understand them.\n",
    "\n",
    "This and other tutorials are perhaps most conveniently run in a Jupyter notebook. See [here](https://jupyter.org/install) for instructions on how to install.\n",
    "\n",
    "### Installation\n",
    "\n",
    "To install LangChain run:\n",
    "\n",
    "```{=mdx}\n",
    "import Tabs from '@theme/Tabs';\n",
    "import TabItem from '@theme/TabItem';\n",
    "import CodeBlock from \"@theme/CodeBlock\";\n",
    "\n",
    "<Tabs>\n",
    "  <TabItem value=\"pip\" label=\"Pip\" default>\n",
    "    <CodeBlock language=\"bash\">pip install langchain</CodeBlock>\n",
    "  </TabItem>\n",
    "  <TabItem value=\"conda\" label=\"Conda\">\n",
    "    <CodeBlock language=\"bash\">conda install langchain -c conda-forge</CodeBlock>\n",
    "  </TabItem>\n",
    "</Tabs>\n",
    "\n",
    "```\n",
    "\n",
    "\n",
    "For more details, see our [Installation guide](/docs/how_to/installation).\n",
    "\n",
    "### LangSmith\n",
    "\n",
    "Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls.\n",
    "As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent.\n",
    "The best way to do this is with [LangSmith](https://smith.langchain.com).\n",
    "\n",
    "After you sign up at the link above, make sure to set your environment variables to start logging traces:\n",
    "\n",
    "```shell\n",
    "export LANGCHAIN_TRACING_V2=\"true\"\n",
    "export LANGCHAIN_API_KEY=\"...\"\n",
    "```\n",
    "\n",
    "Or, if in a notebook, you can set them with:\n",
    "\n",
    "```python\n",
    "import getpass\n",
    "import os\n",
    "\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass()\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c335d1bf",
   "metadata": {},
   "source": [
    "## Define tools\n",
    "\n",
    "We first need to create the tools we want to use. We will use two tools: [Tavily](/docs/integrations/tools/tavily_search) (to search online) and then a retriever over a local index we will create\n",
    "\n",
    "### [Tavily](/docs/integrations/tools/tavily_search)\n",
    "\n",
    "We have a built-in tool in LangChain to easily use Tavily search engine as tool.\n",
    "Note that this requires an API key - they have a free tier, but if you don't have one or don't want to create one, you can always ignore this step.\n",
    "\n",
    "Once you create your API key, you will need to export that as:\n",
    "\n",
    "```bash\n",
    "export TAVILY_API_KEY=\"...\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "482ce13d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.tools.tavily_search import TavilySearchResults"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9cc86c0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "search = TavilySearchResults(max_results=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e593bbf6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'url': 'https://www.weatherapi.com/',\n",
       "  'content': \"{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1714000492, 'localtime': '2024-04-24 16:14'}, 'current': {'last_updated_epoch': 1713999600, 'last_updated': '2024-04-24 16:00', 'temp_c': 15.6, 'temp_f': 60.1, 'is_day': 1, 'condition': {'text': 'Overcast', 'icon': '//cdn.weatherapi.com/weather/64x64/day/122.png', 'code': 1009}, 'wind_mph': 10.5, 'wind_kph': 16.9, 'wind_degree': 330, 'wind_dir': 'NNW', 'pressure_mb': 1018.0, 'pressure_in': 30.06, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 72, 'cloud': 100, 'feelslike_c': 15.6, 'feelslike_f': 60.1, 'vis_km': 16.0, 'vis_miles': 9.0, 'uv': 5.0, 'gust_mph': 14.8, 'gust_kph': 23.8}}\"},\n",
       " {'url': 'https://www.weathertab.com/en/c/e/04/united-states/california/san-francisco/',\n",
       "  'content': 'San Francisco Weather Forecast for Apr 2024 - Risk of Rain Graph. Rain Risk Graph: Monthly Overview. Bar heights indicate rain risk percentages. Yellow bars mark low-risk days, while black and grey bars signal higher risks. Grey-yellow bars act as buffers, advising to keep at least one day clear from the riskier grey and black days, guiding ...'}]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "search.invoke(\"what is the weather in SF\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8097977",
   "metadata": {},
   "source": [
    "### Retriever\n",
    "\n",
    "We will also create a retriever over some data of our own. For a deeper explanation of each step here, see [this tutorial](/docs/tutorials/rag)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9c9ce713",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "loader = WebBaseLoader(\"https://docs.smith.langchain.com/overview\")\n",
    "docs = loader.load()\n",
    "documents = RecursiveCharacterTextSplitter(\n",
    "    chunk_size=1000, chunk_overlap=200\n",
    ").split_documents(docs)\n",
    "vector = FAISS.from_documents(documents, OpenAIEmbeddings())\n",
    "retriever = vector.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dae53ec6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='# The data to predict and grade over    evaluators=[exact_match], # The evaluators to score the results    experiment_prefix=\"sample-experiment\", # The name of the experiment    metadata={      \"version\": \"1.0.0\",      \"revision_id\": \"beta\"    },)import { Client, Run, Example } from \\'langsmith\\';import { runOnDataset } from \\'langchain/smith\\';import { EvaluationResult } from \\'langsmith/evaluation\\';const client = new Client();// Define dataset: these are your test casesconst datasetName = \"Sample Dataset\";const dataset = await client.createDataset(datasetName, {    description: \"A sample dataset in LangSmith.\"});await client.createExamples({    inputs: [        { postfix: \"to LangSmith\" },        { postfix: \"to Evaluations in LangSmith\" },    ],    outputs: [        { output: \"Welcome to LangSmith\" },        { output: \"Welcome to Evaluations in LangSmith\" },    ],    datasetId: dataset.id,});// Define your evaluatorconst exactMatch = async ({ run, example }: { run: Run; example?:', metadata={'source': 'https://docs.smith.langchain.com/overview', 'title': 'Getting started with LangSmith | \\uf8ffü¶úÔ∏è\\uf8ffüõ†Ô∏è LangSmith', 'description': 'Introduction', 'language': 'en'})"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retriever.invoke(\"how to upload a dataset\")[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04aeca39",
   "metadata": {},
   "source": [
    "Now that we have populated our index that we will do doing retrieval over, we can easily turn it into a tool (the format needed for an agent to properly use it)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "117594b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.tools.retriever import create_retriever_tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7280b031",
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever_tool = create_retriever_tool(\n",
    "    retriever,\n",
    "    \"langsmith_search\",\n",
    "    \"Search for information about LangSmith. For any questions about LangSmith, you must use this tool!\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3b47c1d",
   "metadata": {},
   "source": [
    "### Tools\n",
    "\n",
    "Now that we have created both, we can create a list of tools that we will use downstream."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b8e8e710",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [search, retriever_tool]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e00068b0",
   "metadata": {},
   "source": [
    "## Using Language Models\n",
    "\n",
    "Next, let's learn how to use a language model by to call tools. LangChain supports many different language models that you can use interchangably - select the one you want to use below!\n",
    "\n",
    "```{=mdx}\n",
    "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
    "\n",
    "<ChatModelTabs openaiParams={`model=\"gpt-4\"`} />\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "69185491",
   "metadata": {},
   "outputs": [],
   "source": [
    "# | output: false\n",
    "# | echo: false\n",
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "model = ChatOpenAI(model=\"gpt-4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "642ed8bf",
   "metadata": {},
   "source": [
    "You can call the language model by passing in a list of messages. By default, the response is a `content` string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c96c960b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello! How can I assist you today?'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "response = model.invoke([HumanMessage(content=\"hi!\")])\n",
    "response.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47bf8210",
   "metadata": {},
   "source": [
    "We can now see what it is like to enable this model to do tool calling. In order to enable that we use `.bind_tools` to give the language model knowledge of these tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ba692a74",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_with_tools = model.bind_tools(tools)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd920b69",
   "metadata": {},
   "source": [
    "We can now call the model. Let's first call it with a normal message, and see how it responds. We can look at both the `content` field as well as the `tool_calls` field."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b6a7e925",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ContentString: Hello! How can I assist you today?\n",
      "ToolCalls: []\n"
     ]
    }
   ],
   "source": [
    "response = model_with_tools.invoke([HumanMessage(content=\"Hi!\")])\n",
    "\n",
    "print(f\"ContentString: {response.content}\")\n",
    "print(f\"ToolCalls: {response.tool_calls}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8c81e76",
   "metadata": {},
   "source": [
    "Now, let's try calling it with some input that would expect a tool to be called."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "688b465d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ContentString: \n",
      "ToolCalls: [{'name': 'tavily_search_results_json', 'args': {'query': 'current weather in San Francisco'}, 'id': 'call_4HteVahXkRAkWjp6dGXryKZX'}]\n"
     ]
    }
   ],
   "source": [
    "response = model_with_tools.invoke([HumanMessage(content=\"What's the weather in SF?\")])\n",
    "\n",
    "print(f\"ContentString: {response.content}\")\n",
    "print(f\"ToolCalls: {response.tool_calls}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83c4bcd3",
   "metadata": {},
   "source": [
    "We can see that there's now no content, but there is a tool call! It wants us to call the Tavily Search tool.\n",
    "\n",
    "This isn't calling that tool yet - it's just telling us to. In order to actually calll it, we'll want to create our agent."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40ccec80",
   "metadata": {},
   "source": [
    "## Create the agent\n",
    "\n",
    "Now that we have defined the tools and the LLM, we can create the agent. We will be using a tool calling agent - for more information on this type of agent, as well as other options, see [this guide](/docs/concepts/#agent_types/).\n",
    "\n",
    "We can first choose the prompt we want to use to guide the agent.\n",
    "\n",
    "If you want to see the contents of this prompt and have access to LangSmith, you can go to:\n",
    "\n",
    "[https://smith.langchain.com/hub/hwchase17/openai-functions-agent](https://smith.langchain.com/hub/hwchase17/openai-functions-agent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "af83d3e3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')),\n",
       " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
       " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')),\n",
       " MessagesPlaceholder(variable_name='agent_scratchpad')]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
    "prompt.messages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8014c9d",
   "metadata": {},
   "source": [
    "Now, we can initalize the agent with the LLM, the prompt, and the tools. The agent is responsible for taking in input and deciding what actions to take. Crucially, the Agent does not execute those actions - that is done by the AgentExecutor (next step). For more information about how to think about these components, see our [conceptual guide](/docs/concepts/#agents).\n",
    "\n",
    "Note that we are passing in the `model`, not `model_with_tools`. That is because `create_tool_calling_agent` will call `.bind_tools` for us under the hood."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "89cf72b4-6046-4b47-8f27-5522d8cb8036",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import create_tool_calling_agent\n",
    "\n",
    "agent = create_tool_calling_agent(model, tools, prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a58c9f8",
   "metadata": {},
   "source": [
    "Finally, we combine the agent (the brains) with the tools inside the AgentExecutor (which will repeatedly call the agent and execute tools)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "ce33904a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import AgentExecutor\n",
    "\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4df0e06",
   "metadata": {},
   "source": [
    "## Run the agent\n",
    "\n",
    "We can now run the agent on a few queries! Note that for now, these are all **stateless** queries (it won't remember previous interactions).\n",
    "\n",
    "First up, let's how it responds when there's no need to call a tool:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "114ba50d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': 'hi!', 'output': 'Hello! How can I assist you today?'}"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"hi!\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71493a42",
   "metadata": {},
   "source": [
    "In order to see exactly what is happening under the hood (and to make sure it's not calling a tool) we can take a look at the [LangSmith trace](https://smith.langchain.com/public/8441812b-94ce-4832-93ec-e1114214553a/r)\n",
    "\n",
    "Let's now try it out on an example where it should be invoking the retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "3fa4780a",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': 'how can langsmith help with testing?',\n",
       " 'output': 'LangSmith is a platform that aids in building production-grade Language Learning Model (LLM) applications. It can assist with testing in several ways:\\n\\n1. **Monitoring and Evaluation**: LangSmith allows close monitoring and evaluation of your application. This helps you to ensure the quality of your application and deploy it with confidence.\\n\\n2. **Tracing**: LangSmith has tracing capabilities that can be beneficial for debugging and understanding the behavior of your application.\\n\\n3. **Evaluation Capabilities**: LangSmith has built-in tools for evaluating the performance of your LLM. \\n\\n4. **Prompt Hub**: This is a prompt management tool built into LangSmith that can help in testing different prompts and their responses.\\n\\nPlease note that to use LangSmith, you would need to install it and create an API key. The platform offers Python and Typescript SDKs for utilization. It works independently and does not require the use of LangChain.'}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"how can langsmith help with testing?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2d94242",
   "metadata": {},
   "source": [
    "Let's take a look at the [LangSmith trace](https://smith.langchain.com/public/762153f6-14d4-4c98-8659-82650f860c62/r) to make sure it's actually calling that.\n",
    "\n",
    "Now let's try one where it needs to call the search tool:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "77c2f769",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': 'whats the weather in sf?',\n",
       " 'output': 'The current weather in San Francisco is partly cloudy with a temperature of 16.1°C (61.0°F). The wind is coming from the WNW at a speed of 10.5 mph. The humidity is at 67%. [source](https://www.weatherapi.com/)'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"whats the weather in sf?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c174f838",
   "metadata": {},
   "source": [
    "We can check out the [LangSmith trace](https://smith.langchain.com/public/36df5b1a-9a0b-4185-bae2-964e1d53c665/r) to make sure it's calling the search tool effectively."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "022cbc8a",
   "metadata": {},
   "source": [
    "## Adding in memory\n",
    "\n",
    "As mentioned earlier, this agent is stateless. This means it does not remember previous interactions. To give it memory we need to pass in previous `chat_history`. Note: it needs to be called `chat_history` because of the prompt we are using. If we use a different prompt, we could change the variable name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c4073e35",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': 'hi! my name is bob',\n",
       " 'chat_history': [],\n",
       " 'output': 'Hello Bob! How can I assist you today?'}"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Here we pass in an empty list of messages for chat_history because it is the first message in the chat\n",
    "agent_executor.invoke({\"input\": \"hi! my name is bob\", \"chat_history\": []})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "9dc5ed68",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "550e0c6e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'chat_history': [HumanMessage(content='hi! my name is bob'),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'input': \"what's my name?\",\n",
       " 'output': 'Your name is Bob. How can I assist you further?'}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"chat_history\": [\n",
    "            HumanMessage(content=\"hi! my name is bob\"),\n",
    "            AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        ],\n",
    "        \"input\": \"what's my name?\",\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07b3bcf2",
   "metadata": {},
   "source": [
    "If we want to keep track of these messages automatically, we can wrap this in a RunnableWithMessageHistory. For more information on how to use this, see [this guide](/docs/how_to/message_history). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "8edd96e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "from langchain_core.chat_history import BaseChatMessageHistory\n",
    "from langchain_core.runnables.history import RunnableWithMessageHistory\n",
    "\n",
    "store = {}\n",
    "\n",
    "\n",
    "def get_session_history(session_id: str) -> BaseChatMessageHistory:\n",
    "    if session_id not in store:\n",
    "        store[session_id] = ChatMessageHistory()\n",
    "    return store[session_id]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c450d6a5",
   "metadata": {},
   "source": [
    "Because we have multiple inputs, we need to specify two things:\n",
    "\n",
    "- `input_messages_key`: The input key to use to add to the conversation history.\n",
    "- `history_messages_key`: The key to add the loaded messages into."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "828d1e95",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_with_chat_history = RunnableWithMessageHistory(\n",
    "    agent_executor,\n",
    "    get_session_history,\n",
    "    input_messages_key=\"input\",\n",
    "    history_messages_key=\"chat_history\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "1f5932b6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': \"hi! I'm bob\",\n",
       " 'chat_history': [],\n",
       " 'output': 'Hello Bob! How can I assist you today?'}"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_with_chat_history.invoke(\n",
    "    {\"input\": \"hi! I'm bob\"},\n",
    "    config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "ae627966",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name?\",\n",
       " 'chat_history': [HumanMessage(content=\"hi! I'm bob\"),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'output': 'Your name is Bob.'}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_with_chat_history.invoke(\n",
    "    {\"input\": \"what's my name?\"},\n",
    "    config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6de2798e",
   "metadata": {},
   "source": [
    "Example LangSmith trace: https://smith.langchain.com/public/98c8d162-60ae-4493-aa9f-992d87bd0429/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c029798f",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "That's a wrap! In this quick start we covered how to create a simple agent. Agents are a complex topic, and there's lot to learn! \n",
    "\n",
    ":::{.callout-important}\n",
    "This section covered building with LangChain Agents. LangChain Agents are fine for getting started, but past a certain point you will likely want flexibility and control that they do not offer. For working with more advanced agents, we'd reccommend checking out [LangGraph](/docs/concepts/#langgraph)\n",
    ":::\n",
    "\n",
    "If you want to continue using LangChain agents, some good advanced guides are:\n",
    "\n",
    "- [How to use LangGraph's built-in versions of `AgentExecutor`](/docs/how_to/migrate_agent)\n",
    "- [How to create a custom agent](https://python.langchain.com/v0.1/docs/modules/agents/how_to/custom_agent/)\n",
    "- [How to stream responses from an agent](https://python.langchain.com/v0.1/docs/modules/agents/how_to/streaming/)\n",
    "- [How to return structured output from an agent](https://python.langchain.com/v0.1/docs/modules/agents/how_to/agent_structured/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3ec3244",
   "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
}
