From 2b38a4ee5547b20e56a57a9215b6367441905da0 Mon Sep 17 00:00:00 2001 From: Vadym Barda Date: Tue, 24 Sep 2024 11:39:04 -0400 Subject: [PATCH] docs[patch]: update chatbot tools how-to (#26816) --- docs/docs/how_to/chatbots_tools.ipynb | 223 +++++++++----------------- 1 file changed, 80 insertions(+), 143 deletions(-) diff --git a/docs/docs/how_to/chatbots_tools.ipynb b/docs/docs/how_to/chatbots_tools.ipynb index 95125b15bb0..22457d4da02 100644 --- a/docs/docs/how_to/chatbots_tools.ipynb +++ b/docs/docs/how_to/chatbots_tools.ipynb @@ -18,25 +18,46 @@ "\n", "This section will cover how to create conversational agents: chatbots that can interact with other systems and APIs using tools.\n", "\n", + ":::{.callout-note}\n", + "\n", + "This how-to guide previously built a chatbot using [RunnableWithMessageHistory](https://python.langchain.com/api_reference/core/runnables/langchain_core.runnables.history.RunnableWithMessageHistory.html). You can access this version of the tutorial in the [v0.2 docs](https://python.langchain.com/v0.2/docs/how_to/chatbots_tools/).\n", + "\n", + "The LangGraph implementation offers a number of advantages over `RunnableWithMessageHistory`, including the ability to persist arbitrary components of an application's state (instead of only messages).\n", + "\n", + ":::\n", + "\n", "## Setup\n", "\n", - "For this guide, we'll be using a [tool calling agent](/docs/how_to/agent_executor) with a single tool for searching the web. The default will be powered by [Tavily](/docs/integrations/tools/tavily_search), but you can switch it out for any similar tool. The rest of this section will assume you're using Tavily.\n", + "For this guide, we'll be using a [tool calling agent](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/#tool-calling-agent) with a single tool for searching the web. The default will be powered by [Tavily](/docs/integrations/tools/tavily_search), but you can switch it out for any similar tool. The rest of this section will assume you're using Tavily.\n", "\n", "You'll need to [sign up for an account](https://tavily.com/) on the Tavily website, and install the following packages:" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "OpenAI API Key: ········\n", + "Tavily API Key: ········\n" + ] + } + ], "source": [ - "%pip install --upgrade --quiet langchain-community langchain-openai tavily-python\n", + "%pip install --upgrade --quiet langchain-community langchain-openai tavily-python langgraph\n", "\n", - "# Set env var OPENAI_API_KEY or load from a .env file:\n", - "import dotenv\n", + "import getpass\n", + "import os\n", "\n", - "dotenv.load_dotenv()" + "if not os.environ.get(\"OPENAI_API_KEY\"):\n", + " os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\n", + "\n", + "if not os.environ.get(\"TAVILY_API_KEY\"):\n", + " os.environ[\"TAVILY_API_KEY\"] = getpass.getpass(\"Tavily API Key:\")" ] }, { @@ -70,14 +91,14 @@ "\n", "# Choose the LLM that will drive the agent\n", "# Only certain models support this\n", - "chat = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0)" + "model = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "To make our agent conversational, we must also choose a prompt with a placeholder for our chat history. Here's an example:" + "To make our agent conversational, we can also specify a prompt. Here's an example:" ] }, { @@ -86,18 +107,9 @@ "metadata": {}, "outputs": [], "source": [ - "from langchain_core.prompts import ChatPromptTemplate\n", - "\n", - "# Adapted from https://smith.langchain.com/hub/jacob/tool-calling-agent\n", - "prompt = ChatPromptTemplate.from_messages(\n", - " [\n", - " (\n", - " \"system\",\n", - " \"You are a helpful assistant. You may not need to use tools for every query - the user may just want to chat!\",\n", - " ),\n", - " (\"placeholder\", \"{messages}\"),\n", - " (\"placeholder\", \"{agent_scratchpad}\"),\n", - " ]\n", + "prompt = (\n", + " \"You are a helpful assistant. \"\n", + " \"You may not need to use tools for every query - the user may just want to chat!\"\n", ")" ] }, @@ -105,7 +117,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Great! Now let's assemble our agent:" + "Great! Now let's assemble our agent using LangGraph's prebuilt [create_react_agent](https://langchain-ai.github.io/langgraph/reference/prebuilt/#create_react_agent), which allows you to create a [tool-calling agent](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/#tool-calling-agent):" ] }, { @@ -114,11 +126,12 @@ "metadata": {}, "outputs": [], "source": [ - "from langchain.agents import AgentExecutor, create_tool_calling_agent\n", + "from langgraph.prebuilt import create_react_agent\n", "\n", - "agent = create_tool_calling_agent(chat, tools, prompt)\n", - "\n", - "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)" + "# state_modifier allows you to preprocess the inputs to the model inside ReAct agent\n", + "# in this case, since we're passing a prompt string, we'll just always add a SystemMessage\n", + "# with this prompt string before any other messages sent to the model\n", + "agent = create_react_agent(model, tools, state_modifier=prompt)" ] }, { @@ -135,23 +148,11 @@ "execution_count": 5, "metadata": {}, "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", - "\u001b[32;1m\u001b[1;3mHello Nemo! It's great to meet you. How can I assist you today?\u001b[0m\n", - "\n", - "\u001b[1m> Finished chain.\u001b[0m\n" - ] - }, { "data": { "text/plain": [ - "{'messages': [HumanMessage(content=\"I'm Nemo!\")],\n", - " 'output': \"Hello Nemo! It's great to meet you. How can I assist you today?\"}" + "{'messages': [HumanMessage(content=\"I'm Nemo!\", additional_kwargs={}, response_metadata={}, id='39e715c7-bd1c-426f-8e14-c05586b3d221'),\n", + " AIMessage(content='Hi Nemo! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 107, 'total_tokens': 118, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-6937c944-d702-40bb-9a9f-4141ddde9f78-0', usage_metadata={'input_tokens': 107, 'output_tokens': 11, 'total_tokens': 118})]}" ] }, "execution_count": 5, @@ -162,7 +163,7 @@ "source": [ "from langchain_core.messages import HumanMessage\n", "\n", - "agent_executor.invoke({\"messages\": [HumanMessage(content=\"I'm Nemo!\")]})" + "agent.invoke({\"messages\": [HumanMessage(content=\"I'm Nemo!\")]})" ] }, { @@ -177,29 +178,13 @@ "execution_count": 6, "metadata": {}, "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", - "\u001b[32;1m\u001b[1;3m\n", - "Invoking: `tavily_search_results_json` with `{'query': 'current conservation status of the Great Barrier Reef'}`\n", - "\n", - "\n", - "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.abc.net.au/news/2022-08-04/great-barrier-reef-report-says-coral-recovering-after-bleaching/101296186', 'content': 'Great Barrier Reef hit with widespread and severe bleaching event\\n\\'Devastating\\': Over 90pc of reefs on Great Barrier Reef suffered bleaching over summer, report reveals\\nTop Stories\\nJailed Russian opposition leader Alexei Navalny is dead, says prison service\\nTaylor Swift puts an Aussie twist on a classic as she packs the MCG for the biggest show of her career — as it happened\\nMelbourne comes alive with Swifties, as even those without tickets turn up to soak in the atmosphere\\nAustralian Border Force investigates after arrival of more than 20 men by boat north of Broome\\nOpenAI launches video model that can instantly create short clips from text prompts\\nAntoinette Lattouf loses bid to force ABC to produce emails calling for her dismissal\\nCategory one cyclone makes landfall in Gulf of Carpentaria off NT-Queensland border\\nWhy the RBA may be forced to cut before the Fed\\nBrisbane records \\'wettest day since 2022\\', as woman dies in floodwaters near Mount Isa\\n$45m Sydney beachside home once owned by late radio star is demolished less than a year after sale\\nAnnabel Sutherland\\'s historic double century puts Australia within reach of Test victory over South Africa\\nAlmighty defensive effort delivers Indigenous victory in NRL All Stars clash\\nLisa Wilkinson feared she would have to sell home to pay legal costs of Bruce Lehrmann\\'s defamation case, court documents reveal\\nSupermarkets as you know them are disappearing from our cities\\nNRL issues Broncos\\' Reynolds, Carrigan with breach notices after public scrap\\nPopular Now\\nJailed Russian opposition leader Alexei Navalny is dead, says prison service\\nTaylor Swift puts an Aussie twist on a classic as she packs the MCG for the biggest show of her career — as it happened\\n$45m Sydney beachside home once owned by late radio star is demolished less than a year after sale\\nAustralian Border Force investigates after arrival of more than 20 men by boat north of Broome\\nDealer sentenced for injecting children as young as 12 with methylamphetamine\\nMelbourne comes alive with Swifties, as even those without tickets turn up to soak in the atmosphere\\nTop Stories\\nJailed Russian opposition leader Alexei Navalny is dead, says prison service\\nTaylor Swift puts an Aussie twist on a classic as she packs the MCG for the biggest show of her career — as it happened\\nMelbourne comes alive with Swifties, as even those without tickets turn up to soak in the atmosphere\\nAustralian Border Force investigates after arrival of more than 20 men by boat north of Broome\\nOpenAI launches video model that can instantly create short clips from text prompts\\nJust In\\nJailed Russian opposition leader Alexei Navalny is dead, says prison service\\nMelbourne comes alive with Swifties, as even those without tickets turn up to soak in the atmosphere\\nTraveller alert after one-year-old in Adelaide reported with measles\\nAntoinette Lattouf loses bid to force ABC to produce emails calling for her dismissal\\nFooter\\nWe acknowledge Aboriginal and Torres Strait Islander peoples as the First Australians and Traditional Custodians of the lands where we live, learn, and work.\\n Increased coral cover could come at a cost\\nThe rapid growth in coral cover appears to have come at the expense of the diversity of coral on the reef, with most of the increases accounted for by fast-growing branching coral called Acropora.\\n Documents obtained by the ABC under Freedom of Information laws revealed the Morrison government had forced AIMS to rush the report\\'s release and orchestrated a \"leak\" of the material to select media outlets ahead of the reef being considered for inclusion on the World Heritage In Danger list.\\n The reef\\'s status and potential inclusion on the In Danger list were due to be discussed at the 45th session of the World Heritage Committee in Russia in June this year, but the meeting was indefinitely postponed due to the war in Ukraine.\\n More from ABC\\nEditorial Policies\\nGreat Barrier Reef coral cover at record levels after mass-bleaching events, report shows\\nGreat Barrier Reef coral cover at record levels after mass-bleaching events, report shows\\nRecord coral cover is being seen across much of the Great Barrier Reef as it recovers from past storms and mass-bleaching events.'}]\u001b[0m\u001b[32;1m\u001b[1;3mThe Great Barrier Reef is currently showing signs of recovery, with record coral cover being seen across much of the reef. This recovery comes after past storms and mass-bleaching events. However, the rapid growth in coral cover appears to have come at the expense of the diversity of coral on the reef, with most of the increases accounted for by fast-growing branching coral called Acropora. There were discussions about the reef's potential inclusion on the World Heritage In Danger list, but the meeting to consider this was indefinitely postponed due to the war in Ukraine.\n", - "\n", - "You can read more about it in this article: [Great Barrier Reef hit with widespread and severe bleaching event](https://www.abc.net.au/news/2022-08-04/great-barrier-reef-report-says-coral-recovering-after-bleaching/101296186)\u001b[0m\n", - "\n", - "\u001b[1m> Finished chain.\u001b[0m\n" - ] - }, { "data": { "text/plain": [ - "{'messages': [HumanMessage(content='What is the current conservation status of the Great Barrier Reef?')],\n", - " 'output': \"The Great Barrier Reef is currently showing signs of recovery, with record coral cover being seen across much of the reef. This recovery comes after past storms and mass-bleaching events. However, the rapid growth in coral cover appears to have come at the expense of the diversity of coral on the reef, with most of the increases accounted for by fast-growing branching coral called Acropora. There were discussions about the reef's potential inclusion on the World Heritage In Danger list, but the meeting to consider this was indefinitely postponed due to the war in Ukraine.\\n\\nYou can read more about it in this article: [Great Barrier Reef hit with widespread and severe bleaching event](https://www.abc.net.au/news/2022-08-04/great-barrier-reef-report-says-coral-recovering-after-bleaching/101296186)\"}" + "{'messages': [HumanMessage(content='What is the current conservation status of the Great Barrier Reef?', additional_kwargs={}, response_metadata={}, id='a74cc581-8ad5-4401-b3a5-f028d69e4b21'),\n", + " AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_aKOItwvAb4DHQCwaasKphGHq', 'function': {'arguments': '{\"query\":\"current conservation status of the Great Barrier Reef 2023\"}', 'name': 'tavily_search_results_json'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 28, 'prompt_tokens': 116, 'total_tokens': 144, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-267ff8a8-d866-4ae5-9534-ad87ebbdc954-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'current conservation status of the Great Barrier Reef 2023'}, 'id': 'call_aKOItwvAb4DHQCwaasKphGHq', 'type': 'tool_call'}], usage_metadata={'input_tokens': 116, 'output_tokens': 28, 'total_tokens': 144}),\n", + " ToolMessage(content='[{\"url\": \"https://www.aims.gov.au/monitoring-great-barrier-reef/gbr-condition-summary-2023-24\", \"content\": \"This report summarises the condition of coral reefs in the Northern, Central and Southern\\xa0Great Barrier Reef (GBR) from the Long-Term Monitoring Program (LTMP) surveys of 94 reefs conducted between August\\xa02023 and June 2024 (reported as ‘2024’). Over the past 38 years of monitoring by the Australian Institute of Marine Science (AIMS), hard coral cover on reefs of the GBR has decreased and increased in response to cycles of disturbance and recovery. It is relatively rare for GBR reefs to have 75% to 100% hard coral cover and AIMS defines >30% – 50% hard coral cover as a high value, based on historical surveys across the GBR.\"}]', name='tavily_search_results_json', id='05b3fab7-9ac8-42bb-9612-ff2a896dbb67', tool_call_id='call_aKOItwvAb4DHQCwaasKphGHq', artifact={'query': 'current conservation status of the Great Barrier Reef 2023', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Annual Summary Report of Coral Reef Condition 2023/24', 'url': 'https://www.aims.gov.au/monitoring-great-barrier-reef/gbr-condition-summary-2023-24', 'content': 'This report summarises the condition of coral reefs in the Northern, Central and Southern\\xa0Great Barrier Reef (GBR) from the Long-Term Monitoring Program (LTMP) surveys of 94 reefs conducted between August\\xa02023 and June 2024 (reported as ‘2024’). Over the past 38 years of monitoring by the Australian Institute of Marine Science (AIMS), hard coral cover on reefs of the GBR has decreased and increased in response to cycles of disturbance and recovery. It is relatively rare for GBR reefs to have 75% to 100% hard coral cover and AIMS defines >30% – 50% hard coral cover as a high value, based on historical surveys across the GBR.', 'score': 0.95991266, 'raw_content': None}], 'response_time': 4.22}),\n", + " AIMessage(content='The current conservation status of the Great Barrier Reef (GBR) indicates ongoing challenges and fluctuations in coral health. According to a report from the Australian Institute of Marine Science (AIMS), the condition of coral reefs in the GBR has been monitored over the years, showing cycles of disturbance and recovery. \\n\\nAs of the latest surveys conducted between August 2023 and June 2024, hard coral cover on the GBR has experienced both decreases and increases. AIMS defines a hard coral cover of over 30% to 50% as high value, but it is relatively rare for GBR reefs to achieve 75% to 100% hard coral cover.\\n\\nFor more detailed information, you can refer to the [AIMS report](https://www.aims.gov.au/monitoring-great-barrier-reef/gbr-condition-summary-2023-24).', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 174, 'prompt_tokens': 337, 'total_tokens': 511, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-bec32925-0dba-445d-8b55-87358ef482bb-0', usage_metadata={'input_tokens': 337, 'output_tokens': 174, 'total_tokens': 511})]}" ] }, "execution_count": 6, @@ -208,7 +193,7 @@ } ], "source": [ - "agent_executor.invoke(\n", + "agent.invoke(\n", " {\n", " \"messages\": [\n", " HumanMessage(\n", @@ -233,25 +218,13 @@ "execution_count": 7, "metadata": {}, "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", - "\u001b[32;1m\u001b[1;3mYour name is Nemo!\u001b[0m\n", - "\n", - "\u001b[1m> Finished chain.\u001b[0m\n" - ] - }, { "data": { "text/plain": [ - "{'messages': [HumanMessage(content=\"I'm Nemo!\"),\n", - " AIMessage(content='Hello Nemo! How can I assist you today?'),\n", - " HumanMessage(content='What is my name?')],\n", - " 'output': 'Your name is Nemo!'}" + "{'messages': [HumanMessage(content=\"I'm Nemo!\", additional_kwargs={}, response_metadata={}, id='2c8e58bf-ad20-45a4-940b-84393c6b3a03'),\n", + " AIMessage(content='Hello Nemo! How can I assist you today?', additional_kwargs={}, response_metadata={}, id='5e014114-7e9d-42c3-b63e-a662b3a49bef'),\n", + " HumanMessage(content='What is my name?', additional_kwargs={}, response_metadata={}, id='d92be4e1-6497-4037-9a9a-83d3e7b760d5'),\n", + " AIMessage(content='Your name is Nemo!', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 130, 'total_tokens': 136, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-17db96f8-8dbd-4f25-a80d-e4e872967641-0', usage_metadata={'input_tokens': 130, 'output_tokens': 6, 'total_tokens': 136})]}" ] }, "execution_count": 7, @@ -262,7 +235,7 @@ "source": [ "from langchain_core.messages import AIMessage, HumanMessage\n", "\n", - "agent_executor.invoke(\n", + "agent.invoke(\n", " {\n", " \"messages\": [\n", " HumanMessage(content=\"I'm Nemo!\"),\n", @@ -277,7 +250,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If preferred, you can also wrap the agent executor in a [`RunnableWithMessageHistory`](/docs/how_to/message_history/) class to internally manage history messages. Let's redeclare it this way:" + "If preferred, you can also add memory to the LangGraph agent to manage the history of messages. Let's redeclare it this way:" ] }, { @@ -286,63 +259,35 @@ "metadata": {}, "outputs": [], "source": [ - "agent = create_tool_calling_agent(chat, tools, prompt)\n", + "from langgraph.checkpoint.memory import MemorySaver\n", "\n", - "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Then, because our agent executor has multiple outputs, we also have to set the `output_messages_key` property when initializing the wrapper:" + "# highlight-start\n", + "memory = MemorySaver()\n", + "agent = create_react_agent(model, tools, state_modifier=prompt, checkpointer=memory)\n", + "# highlight-end" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 9, "metadata": {}, "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", - "\u001b[32;1m\u001b[1;3mHi Nemo! It's great to meet you. How can I assist you today?\u001b[0m\n", - "\n", - "\u001b[1m> Finished chain.\u001b[0m\n" - ] - }, { "data": { "text/plain": [ - "{'messages': [HumanMessage(content=\"I'm Nemo!\")],\n", - " 'output': \"Hi Nemo! It's great to meet you. How can I assist you today?\"}" + "{'messages': [HumanMessage(content=\"I'm Nemo!\", additional_kwargs={}, response_metadata={}, id='117b2cfc-c6cc-449c-bba9-26fc545d0afa'),\n", + " AIMessage(content='Hi Nemo! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 107, 'total_tokens': 118, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-ba16cc0b-fba1-4ec5-9d99-e010c3b702d0-0', usage_metadata={'input_tokens': 107, 'output_tokens': 11, 'total_tokens': 118})]}" ] }, - "execution_count": 11, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "from langchain_community.chat_message_histories import ChatMessageHistory\n", - "from langchain_core.runnables.history import RunnableWithMessageHistory\n", - "\n", - "demo_ephemeral_chat_history_for_chain = ChatMessageHistory()\n", - "\n", - "conversational_agent_executor = RunnableWithMessageHistory(\n", - " agent_executor,\n", - " lambda session_id: demo_ephemeral_chat_history_for_chain,\n", - " input_messages_key=\"messages\",\n", - " output_messages_key=\"output\",\n", - ")\n", - "\n", - "conversational_agent_executor.invoke(\n", + "agent.invoke(\n", " {\"messages\": [HumanMessage(\"I'm Nemo!\")]},\n", - " {\"configurable\": {\"session_id\": \"unused\"}},\n", + " config={\"configurable\": {\"thread_id\": \"1\"}},\n", ")" ] }, @@ -355,39 +300,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", - "\u001b[32;1m\u001b[1;3mYour name is Nemo! How can I assist you today, Nemo?\u001b[0m\n", - "\n", - "\u001b[1m> Finished chain.\u001b[0m\n" - ] - }, { "data": { "text/plain": [ - "{'messages': [HumanMessage(content=\"I'm Nemo!\"),\n", - " AIMessage(content=\"Hi Nemo! It's great to meet you. How can I assist you today?\"),\n", - " HumanMessage(content='What is my name?')],\n", - " 'output': 'Your name is Nemo! How can I assist you today, Nemo?'}" + "{'messages': [HumanMessage(content=\"I'm Nemo!\", additional_kwargs={}, response_metadata={}, id='117b2cfc-c6cc-449c-bba9-26fc545d0afa'),\n", + " AIMessage(content='Hi Nemo! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 107, 'total_tokens': 118, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-ba16cc0b-fba1-4ec5-9d99-e010c3b702d0-0', usage_metadata={'input_tokens': 107, 'output_tokens': 11, 'total_tokens': 118}),\n", + " HumanMessage(content='What is my name?', additional_kwargs={}, response_metadata={}, id='53ac8d34-99bb-43a7-9103-80e26b7ee6cc'),\n", + " AIMessage(content='Your name is Nemo!', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 130, 'total_tokens': 136, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_1bb46167f9', 'finish_reason': 'stop', 'logprobs': None}, id='run-b3f224a5-902a-4973-84ff-9b683615b0e2-0', usage_metadata={'input_tokens': 130, 'output_tokens': 6, 'total_tokens': 136})]}" ] }, - "execution_count": 11, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "conversational_agent_executor.invoke(\n", + "agent.invoke(\n", " {\"messages\": [HumanMessage(\"What is my name?\")]},\n", - " {\"configurable\": {\"session_id\": \"unused\"}},\n", + " config={\"configurable\": {\"thread_id\": \"1\"}},\n", ")" ] }, @@ -395,11 +328,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This [LangSmith trace](https://smith.langchain.com/public/1a9f712a-7918-4661-b3ff-d979bcc2af42/r) shows what's going on under the hood.\n", + "This [LangSmith trace](https://smith.langchain.com/public/9e6b000d-08aa-4c5a-ac83-2fdf549523cb/r) shows what's going on under the hood.\n", "\n", "## Further reading\n", "\n", - "Other types agents can also support conversational responses too - for more, check out the [agents section](/docs/tutorials/agents).\n", + "For more on how to build agents, check these [LangGraph](https://langchain-ai.github.io/langgraph/) guides:\n", + "\n", + "* [agents conceptual guide](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/)\n", + "* [agents tutorials](https://langchain-ai.github.io/langgraph/tutorials/multi_agent/multi-agent-collaboration/)\n", + "* [create_react_agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent/)\n", "\n", "For more on tool usage, you can also check out [this use case section](/docs/how_to#tools)." ] @@ -421,9 +358,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.5" + "version": "3.12.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 }