The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
core[patch]: fix runnable history and add docs (#22283)
Harrison Chaseee3236926510
diff --git a/docs/docs/how_to/message_history.ipynb b/docs/docs/how_to/message_history.ipynbindex dd343fc266..fbc88b00b2 100644--- a/docs/docs/how_to/message_history.ipynb+++ b/docs/docs/how_to/message_history.ipynb@@ -2,7 +2,7 @@"cells": [{"cell_type": "markdown",- "id": "6a4becbd-238e-4c1d-a02d-08e61fbc3763",+ "id": "f47033eb","metadata": {},"source": ["# How to add message history\n",@@ -18,420 +18,465 @@"\n",":::\n","\n",- "Passing conversation state into and out a chain is vital when building a chatbot. The [`RunnableWithMessageHistory`](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.history.RunnableWithMessageHistory.html#langchain_core.runnables.history.RunnableWithMessageHistory) class lets us add message history to certain types of chains. It wraps another Runnable and manages the chat message history for it.\n",+ "Passing conversation state into and out a chain is vital when building a chatbot. The [`RunnableWithMessageHistory`](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.history.RunnableWithMessageHistory.html#langchain_core.runnables.history.RunnableWithMessageHistory) class lets us add message history to certain types of chains. It wraps another Runnable and manages the chat message history for it. Specifically, it loads previous messages in the conversation BEFORE passing it to the Runnable, and it saves the generated response as a message AFTER calling the runnable. This class also enables multiple conversations by saving each conversation with a `session_id` - it then expects a `session_id` to be passed in the config when calling the runnable, and uses that to look up the relevant conversation history.\n","\n",- "Specifically, it can be used for any Runnable that takes as input one of:\n",+ "\n","\n",- "* a sequence of [`BaseMessages`](/docs/concepts/#message-types)\n",- "* a dict with a key that takes a sequence of `BaseMessages`\n",- "* a dict with a key that takes the latest message(s) as a string or sequence of `BaseMessages`, and a separate key that takes historical messages\n",+ "In practice this looks something like:\n","\n",- "And returns as output one of\n",+ "```python\n",+ "from langchain_core.runnables.history import RunnableWithMessageHistory\n","\n",- "* a string that can be treated as the contents of an `AIMessage`\n",- "* a sequence of `BaseMessage`\n",- "* a dict with a key that contains a sequence of `BaseMessage`\n","\n",- "Let's take a look at some examples to see how it works. First we construct a runnable (which here accepts a dict as input and returns a message as output):\n",+ "with_message_history = RunnableWithMessageHistory(\n",+ " # The underlying runnable\n",+ " runnable, \n",+ " # A function that takes in a session id and returns a memory object\n",+ " get_session_history, \n",+ " # Other parameters that may be needed to align the inputs/outputs\n",+ " # of the Runnable with the memory object\n",+ " ... \n",+ ")\n","\n",- "```{=mdx}\n",- "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",+ "with_message_history.invoke(\n",+ " # The same input as before\n",+ " {\"ability\": \"math\", \"input\": \"What does cosine mean?\"},\n",+ " # Configuration specifying the `session_id`,\n",+ " # which controls which conversation to load\n",+ " config={\"configurable\": {\"session_id\": \"abc123\"}},\n",+ ")\n",+ "```\n","\n",- "<ChatModelTabs\n",- " customVarName=\"llm\"\n",- "/>\n",- "```"+ "\n",+ "In order to properly set this up there are two main things to consider:\n",+ "\n",+ "1. How to store and load messages? (this is `get_session_history` in the example above)\n",+ "2. What is the underlying Runnable you are wrapping and what are its inputs/outputs? (this is `runnable` in the example above, as well any additional parameters you pass to `RunnableWithMessageHistory` to align the inputs/outputs)\n",+ "\n",+ "Let's walk through these pieces (and more) below."]},{- "cell_type": "code",- "execution_count": 1,- "id": "6489f585",+ "cell_type": "markdown",+ "id": "734123cb","metadata": {},- "outputs": [],"source": [- "# | output: false\n",- "# | echo: false\n",+ "## How to store and load messages\n","\n",- "%pip install -qU langchain langchain_anthropic\n",+ "A key part of this is storing and loading messages.\n",+ "When constructing `RunnableWithMessageHistory` you need to pass in a `get_session_history` function.\n",+ "This function should take in a `session_id` and return a `BaseChatMessageHistory` object.\n","\n",- "import os\n",- "from getpass import getpass\n",+ "**What is `session_id`?** \n","\n",- "from langchain_anthropic import ChatAnthropic\n",+ "`session_id` is an identifier for the session (conversation) thread that these input messages correspond to. This allows you to maintain several conversations/threads with the same chain at the same time.\n","\n",- "os.environ[\"ANTHROPIC_API_KEY\"] = getpass()\n",+ "**What is `BaseChatMessageHistory`?** \n","\n",- "model = ChatAnthropic(model=\"claude-3-haiku-20240307\", temperature=0)"+ "`BaseChatMessageHistory` is a class that can load and save message objects. It will be called by `RunnableWithMessageHistory` to do exactly that. These classes are usually initialized with a session id.\n",+ "\n",+ "Let's create a `get_session_history` object to use for this example. To keep things simple, we will use a simple SQLiteMessage"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "e8210560",+ "metadata": {},+ "outputs": [],+ "source": [+ "! rm memory.db"]},{"cell_type": "code","execution_count": 2,- "id": "2ed413b4-33a1-48ee-89b0-2d4917ec101a",+ "id": "27f36241","metadata": {},"outputs": [],"source": [- "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",+ "from langchain_community.chat_message_histories import SQLChatMessageHistory\n","\n",- "prompt = ChatPromptTemplate.from_messages(\n",- " [\n",- " (\n",- " \"system\",\n",- " \"You're an assistant who's good at {ability}. Respond in 20 words or fewer\",\n",- " ),\n",- " MessagesPlaceholder(variable_name=\"history\"),\n",- " (\"human\", \"{input}\"),\n",- " ]\n",- ")\n",- "runnable = prompt | model"+ "\n",+ "def get_session_history(session_id):\n",+ " return SQLChatMessageHistory(session_id, \"sqlite:///memory.db\")"]},{"cell_type": "markdown",- "id": "9fd175e1-c7b8-4929-a57e-3331865fe7aa",+ "id": "c200cb3a","metadata": {},"source": [- "To manage the message history, we will need:\n",- "1. This runnable;\n",- "2. A callable that returns an instance of `BaseChatMessageHistory`.\n",+ "Check out the [memory integrations](https://integrations.langchain.com/memory) page for implementations of chat message histories using other providers (Redis, Postgres, etc)."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "a531da5e",+ "metadata": {},+ "source": [+ "## What is the runnable you are trying wrap?\n",+ "\n",+ "`RunnableWithMessageHistory` can only wrap certain types of Runnables. Specifically, it can be used for any Runnable that takes as input one of:\n",+ "\n",+ "* a sequence of [`BaseMessages`](/docs/concepts/#message-types)\n",+ "* a dict with a key that takes a sequence of `BaseMessages`\n",+ "* a dict with a key that takes the latest message(s) as a string or sequence of `BaseMessages`, and a separate key that takes historical messages\n",+ "\n",+ "And returns as output one of\n",+ "\n",+ "* a string that can be treated as the contents of an `AIMessage`\n",+ "* a sequence of `BaseMessage`\n",+ "* a dict with a key that contains a sequence of `BaseMessage`\n","\n",- "Check out the [memory integrations](https://integrations.langchain.com/memory) page for implementations of chat message histories using Redis and other providers. Here we demonstrate using an in-memory `ChatMessageHistory` as well as more persistent storage using `RedisChatMessageHistory`."+ "Let's take a look at some examples to see how it works. "]},{"cell_type": "markdown",- "id": "3d83adad-9672-496d-9f25-5747e7b8c8bb",+ "id": "6a4becbd-238e-4c1d-a02d-08e61fbc3763","metadata": {},"source": [- "## In-memory\n",+ "### Setup\n","\n",- "Below we show a simple example in which the chat history lives in memory, in this case via a global Python dict.\n",+ "First we construct a runnable (which here accepts a dict as input and returns a message as output):\n","\n",- "We construct a callable `get_session_history` that references this dict to return an instance of `ChatMessageHistory`. The arguments to the callable can be specified by passing a configuration to the `RunnableWithMessageHistory` at runtime. By default, the configuration parameter is expected to be a single string `session_id`. This can be adjusted via the `history_factory_config` kwarg.\n",+ "```{=mdx}\n",+ "import ChatModelTabs from \"@theme/ChatModelTabs\";\n","\n",- "Using the single-parameter default:"+ "<ChatModelTabs\n",+ " customVarName=\"llm\"\n",+ "/>\n",+ "```"]},{"cell_type": "code","execution_count": 3,- "id": "54348d02-d8ee-440c-bbf9-41bc0fbbc46c",+ "id": "6489f585","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",+ "# | output: false\n",+ "# | echo: false\n","\n",+ "# %pip install -qU langchain langchain_anthropic\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]\n",+ "# import os\n",+ "# from getpass import getpass\n","\n",+ "# os.environ[\"ANTHROPIC_API_KEY\"] = getpass()\n",+ "from langchain_anthropic import ChatAnthropic\n","\n",- "with_message_history = RunnableWithMessageHistory(\n",- " runnable,\n",- " get_session_history,\n",- " input_messages_key=\"input\",\n",- " history_messages_key=\"history\",\n",- ")"+ "model = ChatAnthropic(model=\"claude-3-haiku-20240307\", temperature=0)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "2ed413b4-33a1-48ee-89b0-2d4917ec101a",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain_core.messages import HumanMessage\n",+ "from langchain_core.runnables.history import RunnableWithMessageHistory"]},{"cell_type": "markdown",- "id": "01acb505-3fd3-4ab4-9f04-5ea07e81542e",+ "id": "e8816b01","metadata": {},"source": [- ":::info\n",- "\n",- "Note that we've specified `input_messages_key` (the key to be treated as the latest input message) and `history_messages_key` (the key to add historical messages to).\n",+ "### Messages input, message(s) output\n","\n",- ":::"+ "The simplest form is just adding memory to a ChatModel.\n",+ "ChatModels accept a list of messages as input and output a message.\n",+ "This makes it very easy to use `RunnableWithMessageHistory` - no additional configuration is needed!"]},{- "cell_type": "markdown",- "id": "35222c30",+ "cell_type": "code",+ "execution_count": 5,+ "id": "0521d551","metadata": {},+ "outputs": [],"source": [- "When invoking this new runnable, we specify the corresponding chat history via a configuration parameter:"+ "runnable_with_history = RunnableWithMessageHistory(\n",+ " model,\n",+ " get_session_history,\n",+ ")"]},{"cell_type": "code",- "execution_count": 4,- "id": "01384412-f08e-4634-9edb-3f46f475b582",+ "execution_count": 6,+ "id": "d5142e1a","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='Cosine is a trigonometric function that represents the ratio of the adjacent side to the hypotenuse of a right triangle.', response_metadata={'id': 'msg_01DH8iRBELVbF3sqM8U5sk8A', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 32, 'output_tokens': 31}}, id='run-e07fc012-a4f6-4e47-8ef8-250f296eba5b-0')"+ "AIMessage(content=\"It's nice to meet you, Bob! I'm Claude, an AI assistant created by Anthropic. How can I help you today?\", response_metadata={'id': 'msg_01UHCCMiZz9yNYjt41xUJrtk', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 32}}, id='run-55f6a451-606b-4e04-9e39-e03b81035c1f-0', usage_metadata={'input_tokens': 12, 'output_tokens': 32, 'total_tokens': 44})"]},- "execution_count": 4,+ "execution_count": 6,"metadata": {},"output_type": "execute_result"}],"source": [- "with_message_history.invoke(\n",- " {\"ability\": \"math\", \"input\": \"What does cosine mean?\"},\n",- " config={\"configurable\": {\"session_id\": \"abc123\"}},\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"hi - im bob!\")],\n",+ " config={\"configurable\": {\"session_id\": \"1\"}},\n",")"]},{"cell_type": "code",- "execution_count": 5,- "id": "954688a2-9a3f-47ee-a9e8-fa0c83e69477",+ "execution_count": 7,+ "id": "768e0c12","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='The inverse of the cosine function is called the arccosine or inverse cosine.', response_metadata={'id': 'msg_015TeeRQBvTvc7XG1JxYqZyq', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 72, 'output_tokens': 22}}, id='run-32ae22ea-3b2f-4d38-8c8a-cb8702e2f3e7-0')"+ "AIMessage(content='I\\'m afraid I don\\'t actually know your name - you introduced yourself as Bob, but I don\\'t have any other information about your identity. As an AI assistant, I don\\'t have a way to independently verify people\\'s names or identities. I\\'m happy to continue our conversation, but I\\'ll just refer to you as \"Bob\" since that\\'s the name you provided.', response_metadata={'id': 'msg_018L96tAxiexMKsHBQz22CcE', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 52, 'output_tokens': 80}}, id='run-7399ddb5-bb06-444b-bfb2-2f65674105dd-0', usage_metadata={'input_tokens': 52, 'output_tokens': 80, 'total_tokens': 132})"]},- "execution_count": 5,+ "execution_count": 7,"metadata": {},"output_type": "execute_result"}],"source": [- "# Remembers\n",- "with_message_history.invoke(\n",- " {\"ability\": \"math\", \"input\": \"What is its inverse called?\"},\n",- " config={\"configurable\": {\"session_id\": \"abc123\"}},\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"whats my name?\")],\n",+ " config={\"configurable\": {\"session_id\": \"1\"}},\n",")"]},{"cell_type": "markdown",- "id": "e0c651e5",+ "id": "9d942227","metadata": {},"source": [":::info\n","\n",- "Note that in this case the context is preserved via the chat history for the provided `session_id`, so the model knows that \"it\" refers to \"cosine\" in this case.\n",+ "Note that in this case the context is preserved via the chat history for the provided `session_id`, so the model knows the users name.\n","\n",- ":::"- ]- },- {- "cell_type": "markdown",- "id": "a44f8d5f",- "metadata": {},- "source": [- "Now let's try a different `session_id`"+ ":::\n",+ "\n",+ "We can now try this with a new session id and see that it does not remember."]},{"cell_type": "code",- "execution_count": 6,- "id": "39350d7c-2641-4744-bc2a-fd6a57c4ea90",+ "execution_count": 14,+ "id": "addddd03","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='The inverse of a function is the function that undoes the original function.', response_metadata={'id': 'msg_01M8WbHWg2sjWTz3m3NKqZuF', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 32, 'output_tokens': 18}}, id='run-b64c73d6-03ee-4b0a-85e0-34beb45408d4-0')"+ "AIMessage(content=\"I'm afraid I don't actually know your name. As an AI assistant, I don't have personal information about you unless you provide it to me directly.\", response_metadata={'id': 'msg_01LhbWu7mSKTvKAx7iQpMPzd', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 35}}, id='run-cf86cad2-21f2-4525-afc8-09bfd1e8af70-0', usage_metadata={'input_tokens': 12, 'output_tokens': 35, 'total_tokens': 47})"]},- "execution_count": 6,+ "execution_count": 14,"metadata": {},"output_type": "execute_result"}],"source": [- "# New session_id --> does not remember.\n",- "with_message_history.invoke(\n",- " {\"ability\": \"math\", \"input\": \"What is its inverse called?\"},\n",- " config={\"configurable\": {\"session_id\": \"def234\"}},\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"whats my name?\")],\n",+ " config={\"configurable\": {\"session_id\": \"1a\"}},\n",")"]},{"cell_type": "markdown",- "id": "5416e195",+ "id": "8b26a0c0","metadata": {},"source": [- "When we pass a different `session_id`, we start a new chat history, so the model does not know what \"it\" refers to."+ ":::info \n",+ "\n",+ "When we pass a different `session_id`, we start a new chat history, so the model does not know what the user's name is. \n",+ "\n",+ ":::"]},{"cell_type": "markdown",- "id": "a6710e65",+ "id": "e5bb5c7c","metadata": {},"source": [- "### Customization"+ "### Dictionary input, message(s) output\n",+ "\n",+ "Besides just wrapping a raw model, the next step up is wrapping a prompt + LLM. This now changes the input to be a **dictionary** (because the input to a prompt is a dictionary). This adds two bits of complication.\n",+ "\n",+ "First: a dictionary can have multiple keys, but we only want to save ONE as input. In order to do this, we now now need to specify a key to save as the input.\n",+ "\n",+ "Second: once we load the messages, we need to know how to save them to the dictionary. That equates to know which key in the dictionary to save them in. Therefore, we need to specify a key to save the loaded messages in.\n",+ "\n",+ "Putting it all together, that ends up looking something like:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "id": "34edd990",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",+ "\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\n",+ " \"system\",\n",+ " \"You're an assistant who speaks in {language}. Respond in 20 words or fewer\",\n",+ " ),\n",+ " MessagesPlaceholder(variable_name=\"history\"),\n",+ " (\"human\", \"{input}\"),\n",+ " ]\n",+ ")\n",+ "\n",+ "runnable = prompt | model\n",+ "\n",+ "runnable_with_history = RunnableWithMessageHistory(\n",+ " runnable,\n",+ " get_session_history,\n",+ " input_messages_key=\"input\",\n",+ " history_messages_key=\"history\",\n",+ ")"]},{"cell_type": "markdown",- "id": "d29497be-3366-408d-bbb9-d4a8bf4ef37c",+ "id": "c0baa075","metadata": {},"source": [- "The configuration parameters by which we track message histories can be customized by passing in a list of ``ConfigurableFieldSpec`` objects to the ``history_factory_config`` parameter. Below, we use two parameters: a `user_id` and `conversation_id`."+ ":::info\n",+ "\n",+ "Note that we've specified `input_messages_key` (the key to be treated as the latest input message) and `history_messages_key` (the key to add historical messages to).\n",+ "\n",+ ":::"]},{"cell_type": "code",- "execution_count": 7,- "id": "1c89daee-deff-4fdf-86a3-178f7d8ef536",+ "execution_count": 16,+ "id": "5877544f","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content=\"Why can't a bicycle stand up on its own? It's two-tired!\", response_metadata={'id': 'msg_011qHi8pvbNkKhRb9XYRm2kc', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 30, 'output_tokens': 20}}, id='run-5d1d5b5a-ccec-4c2c-b11a-f1953dbe85a3-0')"+ "AIMessage(content='Ciao Bob! È un piacere conoscerti. Come stai oggi?', response_metadata={'id': 'msg_0121ADUEe4G1hMC6zbqFWofr', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 29, 'output_tokens': 23}}, id='run-246a70df-aad6-43d6-a7e8-166d96e0d67e-0', usage_metadata={'input_tokens': 29, 'output_tokens': 23, 'total_tokens': 52})"]},- "execution_count": 7,+ "execution_count": 16,"metadata": {},"output_type": "execute_result"}],"source": [- "from langchain_core.runnables import ConfigurableFieldSpec\n",- "\n",- "store = {}\n",- "\n",- "\n",- "def get_session_history(user_id: str, conversation_id: str) -> BaseChatMessageHistory:\n",- " if (user_id, conversation_id) not in store:\n",- " store[(user_id, conversation_id)] = ChatMessageHistory()\n",- " return store[(user_id, conversation_id)]\n",- "\n",- "\n",- "with_message_history = RunnableWithMessageHistory(\n",- " runnable,\n",- " get_session_history,\n",- " input_messages_key=\"input\",\n",- " history_messages_key=\"history\",\n",- " history_factory_config=[\n",- " ConfigurableFieldSpec(\n",- " id=\"user_id\",\n",- " annotation=str,\n",- " name=\"User ID\",\n",- " description=\"Unique identifier for the user.\",\n",- " default=\"\",\n",- " is_shared=True,\n",- " ),\n",- " ConfigurableFieldSpec(\n",- " id=\"conversation_id\",\n",- " annotation=str,\n",- " name=\"Conversation ID\",\n",- " description=\"Unique identifier for the conversation.\",\n",- " default=\"\",\n",- " is_shared=True,\n",- " ),\n",- " ],\n",- ")\n",- "\n",- "with_message_history.invoke(\n",- " {\"ability\": \"jokes\", \"input\": \"Tell me a joke\"},\n",- " config={\"configurable\": {\"user_id\": \"123\", \"conversation_id\": \"1\"}},\n",+ "runnable_with_history.invoke(\n",+ " {\"language\": \"italian\", \"input\": \"hi im bob!\"},\n",+ " config={\"configurable\": {\"session_id\": \"2\"}},\n",")"]},{"cell_type": "code",- "execution_count": 8,- "id": "4f282883",+ "execution_count": 17,+ "id": "8605c2b1","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='The joke was about a bicycle not being able to stand up on its own because it\\'s \"two-tired\" (too tired).', response_metadata={'id': 'msg_01LbrkfidZgseBMxxRjQXJQH', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 59, 'output_tokens': 30}}, id='run-8b2ca810-77d7-44b8-b27b-677e0062b19a-0')"+ "AIMessage(content='Bob, il tuo nome è Bob.', response_metadata={'id': 'msg_01EDUZG6nRLGeti9KhFN5cek', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 60, 'output_tokens': 12}}, id='run-294b4a72-81bc-4c43-b199-3aafdff87cb3-0', usage_metadata={'input_tokens': 60, 'output_tokens': 12, 'total_tokens': 72})"]},- "execution_count": 8,+ "execution_count": 17,"metadata": {},"output_type": "execute_result"}],"source": [- "# remembers\n",- "with_message_history.invoke(\n",- " {\"ability\": \"jokes\", \"input\": \"What was the joke about?\"},\n",- " config={\"configurable\": {\"user_id\": \"123\", \"conversation_id\": \"1\"}},\n",+ "runnable_with_history.invoke(\n",+ " {\"language\": \"italian\", \"input\": \"whats my name?\"},\n",+ " config={\"configurable\": {\"session_id\": \"2\"}},\n",")"]},+ {+ "cell_type": "markdown",+ "id": "3ab7c09f",+ "metadata": {},+ "source": [+ ":::info\n",+ "\n",+ "Note that in this case the context is preserved via the chat history for the provided `session_id`, so the model knows the users name.\n",+ "\n",+ ":::\n",+ "\n",+ "We can now try this with a new session id and see that it does not remember."+ ]+ },{"cell_type": "code",- "execution_count": 9,- "id": "fc122c18",+ "execution_count": 19,+ "id": "c7ddad6b","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content=\"I'm afraid I don't have enough context to provide a relevant joke. As an AI assistant, I don't actually have pre-programmed jokes. I'd be happy to try generating a humorous response if you provide more details about the context.\", response_metadata={'id': 'msg_01PgSp46hNJnKyNfNKPDauQ9', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 32, 'output_tokens': 54}}, id='run-ed202892-27e4-4da9-a26d-e0dc16b10940-0')"+ "AIMessage(content='Mi dispiace, non so il tuo nome. Come posso aiutarti?', response_metadata={'id': 'msg_01Lyd9FAGQJTxxAZoFi3sQpQ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 30, 'output_tokens': 23}}, id='run-19a82197-3b1c-4b5f-a68d-f91f4a2ba523-0', usage_metadata={'input_tokens': 30, 'output_tokens': 23, 'total_tokens': 53})"]},- "execution_count": 9,+ "execution_count": 19,"metadata": {},"output_type": "execute_result"}],"source": [- "# New user_id --> does not remember\n",- "with_message_history.invoke(\n",- " {\"ability\": \"jokes\", \"input\": \"What was the joke about?\"},\n",- " config={\"configurable\": {\"user_id\": \"456\", \"conversation_id\": \"1\"}},\n",+ "runnable_with_history.invoke(\n",+ " {\"language\": \"italian\", \"input\": \"whats my name?\"},\n",+ " config={\"configurable\": {\"session_id\": \"2a\"}},\n",")"]},{"cell_type": "markdown",- "id": "3ce37565",- "metadata": {},- "source": [- "Note that in this case the context was preserved for the same `user_id`, but once we changed it, the new chat history was started, even though the `conversation_id` was the same."- ]- },- {- "cell_type": "markdown",- "id": "18f1a459-3f88-4ee6-8542-76a907070dd6",+ "id": "a05e6c12","metadata": {},"source": [- "### Examples with runnables of different signatures\n",+ ":::info \n","\n",- "The above runnable takes a dict as input and returns a BaseMessage. Below we show some alternatives."+ "When we pass a different `session_id`, we start a new chat history, so the model does not know what the user's name is. \n",+ "\n",+ ":::"]},{"cell_type": "markdown",- "id": "48eae1bf-b59d-4a61-8e62-b6dbf667e866",+ "id": "717440a9","metadata": {},"source": [- "#### Messages input, dict output"+ "### Messages input, dict output\n",+ "\n",+ "This format is useful when you are using a model to generate one key in a dictionary."]},{"cell_type": "code",- "execution_count": 10,- "id": "17733d4f-3a32-4055-9d44-5d58b9446a26",+ "execution_count": 20,+ "id": "80b8efb0","metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'output_message': AIMessage(content='Simone de Beauvoir was a prominent French existentialist philosopher who had some key beliefs about free will:\\n\\n1. Radical Freedom: De Beauvoir believed that humans have radical freedom - the ability to choose and define themselves through their actions. She rejected determinism and believed that we are not simply products of our biology, upbringing, or social circumstances.\\n\\n2. Ambiguity of the Human Condition: However, de Beauvoir also recognized the ambiguity of the human condition. While we have radical freedom, we are also situated beings constrained by our facticity (our given circumstances and limitations). This creates a tension and anguish in the human experience.\\n\\n3. Responsibility and Bad Faith: With radical freedom comes great responsibility. De Beauvoir criticized \"bad faith\" - the denial or avoidance of this responsibility by making excuses or pretending we lack free will. She believed we must courageously embrace our freedom and the burdens it entails.\\n\\n4. Ethical Engagement: For de Beauvoir, freedom is not just an abstract philosophical concept, but something that must be exercised through ethical engagement with the world and others. Our choices and actions have moral implications that we must grapple with.\\n\\nOverall, de Beauvoir\\'s perspective on free will was grounded in existentialist principles - the belief that we are fundamentally free, yet this freedom is fraught with difficulty and responsibility. Her views emphasized the centrality of human agency and the ethical dimensions of our choices.', response_metadata={'id': 'msg_01QFXHx74GSzcMWnWc8YxYSJ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 20, 'output_tokens': 324}}, id='run-752513bc-2b4f-4cad-87f0-b96fee6ebe43-0')}"- ]- },- "execution_count": 10,- "metadata": {},- "output_type": "execute_result"- }- ],+ "outputs": [],"source": ["from langchain_core.messages import HumanMessage\n","from langchain_core.runnables import RunnableParallel\n",@@ -439,317 +484,387 @@"chain = RunnableParallel({\"output_message\": model})\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]\n",- "\n",- "\n",- "with_message_history = RunnableWithMessageHistory(\n",+ "runnable_with_history = RunnableWithMessageHistory(\n"," chain,\n"," get_session_history,\n"," output_messages_key=\"output_message\",\n",- ")\n",- "\n",- "with_message_history.invoke(\n",- " [HumanMessage(content=\"What did Simone de Beauvoir believe about free will\")],\n",- " config={\"configurable\": {\"session_id\": \"baz\"}},\n",")"]},+ {+ "cell_type": "markdown",+ "id": "9040c535",+ "metadata": {},+ "source": [+ ":::info\n",+ "\n",+ "Note that we've specified `output_messages_key` (the key to be treated as the output to save).\n",+ "\n",+ ":::"+ ]+ },{"cell_type": "code",- "execution_count": 11,- "id": "efb57ef5-91f9-426b-84b9-b77f071a9dd7",+ "execution_count": 21,+ "id": "8b26a209","metadata": {},"outputs": [{"data": {"text/plain": [- "{'output_message': AIMessage(content='Simone de Beauvoir\\'s views on free will were quite similar to those of her long-time partner and fellow existentialist philosopher, Jean-Paul Sartre. There are some key parallels and differences:\\n\\nSimilarities:\\n\\n1. Radical Freedom: Both de Beauvoir and Sartre believed that humans have radical, unconditioned freedom to choose and define themselves.\\n\\n2. Rejection of Determinism: They both rejected deterministic views that see humans as products of their circumstances or nature.\\n\\n3. Emphasis on Responsibility: They agreed that with radical freedom comes great responsibility for one\\'s choices and actions.\\n\\n4. Critique of \"Bad Faith\": Both philosophers criticized the tendency of people to deny or avoid their freedom through self-deception and making excuses.\\n\\nDifferences:\\n\\n1. Gendered Perspectives: While Sartre developed a more gender-neutral existentialist philosophy, de Beauvoir brought a distinctly feminist lens, exploring the unique challenges and experiences of women\\'s freedom.\\n\\n2. Ethical Engagement: De Beauvoir placed more emphasis on the importance of ethical engagement with the world and others, whereas Sartre\\'s focus was more individualistic.\\n\\n3. Ambiguity of the Human Condition: De Beauvoir was more attuned to the ambiguity and tensions inherent in the human condition, whereas Sartre\\'s views were sometimes seen as more absolutist.\\n\\n4. Influence of Phenomenology: De Beauvoir was more influenced by the phenomenological tradition, which shaped her understanding of embodied, situated freedom.\\n\\nOverall, while Sartre and de Beauvoir shared a core existentialist framework, de Beauvoir\\'s unique feminist perspective and emphasis on ethical engagement with others distinguished her views on free will and the human condition.', response_metadata={'id': 'msg_01BEANW4VX6cUWYjkv3CanLz', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 355, 'output_tokens': 388}}, id='run-e786ab3a-1a42-45f3-94a3-f0c591430df3-0')}"+ "{'output_message': AIMessage(content=\"It's nice to meet you, Bob! I'm Claude, an AI assistant created by Anthropic. How can I help you today?\", response_metadata={'id': 'msg_01WWJSyUyGGKuBqTs3h18ZMM', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 32}}, id='run-0f50cb43-a734-447c-b535-07c615a0984c-0', usage_metadata={'input_tokens': 12, 'output_tokens': 32, 'total_tokens': 44})}"]},- "execution_count": 11,+ "execution_count": 21,"metadata": {},"output_type": "execute_result"}],"source": [- "with_message_history.invoke(\n",- " [HumanMessage(content=\"How did this compare to Sartre\")],\n",- " config={\"configurable\": {\"session_id\": \"baz\"}},\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"hi - im bob!\")],\n",+ " config={\"configurable\": {\"session_id\": \"3\"}},\n",")"]},- {- "cell_type": "markdown",- "id": "a39eac5f-a9d8-4729-be06-5e7faf0c424d",- "metadata": {},- "source": [- "#### Messages input, messages output"- ]- },{"cell_type": "code",- "execution_count": 12,- "id": "e45bcd95-e31f-4a9a-967a-78f96e8da881",+ "execution_count": 22,+ "id": "743edcf8","metadata": {},"outputs": [{"data": {"text/plain": [- "RunnableWithMessageHistory(bound=RunnableBinding(bound=RunnableBinding(bound=RunnableLambda(_enter_history), config={'run_name': 'load_history'})\n",- "| RunnableBinding(bound=ChatAnthropic(model='claude-3-haiku-20240307', temperature=0.0, anthropic_api_url='https://api.anthropic.com', anthropic_api_key=SecretStr('**********'), _client=<anthropic.Anthropic object at 0x105682720>, _async_client=<anthropic.AsyncAnthropic object at 0x106a08fe0>), config_factories=[<function Runnable.with_listeners.<locals>.<lambda> at 0x106aeef20>]), config={'run_name': 'RunnableWithMessageHistory'}), get_session_history=<function get_session_history at 0x106aee520>, history_factory_config=[ConfigurableFieldSpec(id='session_id', annotation=<class 'str'>, name='Session ID', description='Unique identifier for a session.', default='', is_shared=True, dependencies=None)])"+ "{'output_message': AIMessage(content='I\\'m afraid I don\\'t actually know your name - you introduced yourself as Bob, but I don\\'t have any other information about your identity. As an AI assistant, I don\\'t have a way to independently verify people\\'s names or identities. I\\'m happy to continue our conversation, but I\\'ll just refer to you as \"Bob\" since that\\'s the name you provided.', response_metadata={'id': 'msg_01TEGrhfLXTwo36rC7svdTy4', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 52, 'output_tokens': 80}}, id='run-178e8f3f-da21-430d-9edc-ef07797a5e2d-0', usage_metadata={'input_tokens': 52, 'output_tokens': 80, 'total_tokens': 132})}"]},- "execution_count": 12,+ "execution_count": 22,"metadata": {},"output_type": "execute_result"}],"source": [- "RunnableWithMessageHistory(\n",- " model,\n",- " get_session_history,\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"whats my name?\")],\n",+ " config={\"configurable\": {\"session_id\": \"3\"}},\n",")"]},{"cell_type": "markdown",- "id": "04daa921-a2d1-40f9-8cd1-ae4e9a4163a7",+ "id": "81efb7f1","metadata": {},"source": [- "#### Dict with single key for all messages input, messages output"+ ":::info\n",+ "\n",+ "Note that in this case the context is preserved via the chat history for the provided `session_id`, so the model knows the users name.\n",+ "\n",+ ":::\n",+ "\n",+ "We can now try this with a new session id and see that it does not remember."]},{"cell_type": "code",- "execution_count": 13,- "id": "27157f15-9fb0-4167-9870-f4d7f234b3cb",+ "execution_count": 23,+ "id": "b8b04907","metadata": {},"outputs": [{"data": {"text/plain": [- "RunnableWithMessageHistory(bound=RunnableBinding(bound=RunnableBinding(bound=RunnableAssign(mapper={\n",- " input_messages: RunnableBinding(bound=RunnableLambda(_enter_history), config={'run_name': 'load_history'})\n",- "}), config={'run_name': 'insert_history'})\n",- "| RunnableBinding(bound=RunnableLambda(itemgetter('input_messages'))\n",- " | ChatAnthropic(model='claude-3-haiku-20240307', temperature=0.0, anthropic_api_url='https://api.anthropic.com', anthropic_api_key=SecretStr('**********'), _client=<anthropic.Anthropic object at 0x105682720>, _async_client=<anthropic.AsyncAnthropic object at 0x106a08fe0>), config_factories=[<function Runnable.with_listeners.<locals>.<lambda> at 0x106aef560>]), config={'run_name': 'RunnableWithMessageHistory'}), get_session_history=<function get_session_history at 0x106aee520>, input_messages_key='input_messages', history_factory_config=[ConfigurableFieldSpec(id='session_id', annotation=<class 'str'>, name='Session ID', description='Unique identifier for a session.', default='', is_shared=True, dependencies=None)])"+ "{'output_message': AIMessage(content=\"I'm afraid I don't actually know your name. As an AI assistant, I don't have personal information about you unless you provide it to me directly.\", response_metadata={'id': 'msg_0118ZBudDXAC9P6smf91NhCX', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 35}}, id='run-deb14a3a-0336-42b4-8ace-ad1e52ca5910-0', usage_metadata={'input_tokens': 12, 'output_tokens': 35, 'total_tokens': 47})}"]},- "execution_count": 13,+ "execution_count": 23,"metadata": {},"output_type": "execute_result"}],"source": [- "from operator import itemgetter\n",- "\n",- "RunnableWithMessageHistory(\n",- " itemgetter(\"input_messages\") | model,\n",- " get_session_history,\n",- " input_messages_key=\"input_messages\",\n",+ "runnable_with_history.invoke(\n",+ " [HumanMessage(content=\"whats my name?\")],\n",+ " config={\"configurable\": {\"session_id\": \"3a\"}},\n",")"]},{"cell_type": "markdown",- "id": "418ca7af-9ed9-478c-8bca-cba0de2ca61e",+ "id": "6716a068","metadata": {},"source": [- "## Persistent storage"+ ":::info \n",+ "\n",+ "When we pass a different `session_id`, we start a new chat history, so the model does not know what the user's name is. \n",+ "\n",+ ":::"]},{"cell_type": "markdown",- "id": "76799a13-d99a-4c4f-91f2-db699e40b8df",+ "id": "ec4187d0","metadata": {},"source": [- "In many cases it is preferable to persist conversation histories. `RunnableWithMessageHistory` is agnostic as to how the `get_session_history` callable retrieves its chat message histories. See [here](https://github.com/langchain-ai/langserve/blob/main/examples/chat_with_persistence_and_user/server.py) for an example using a local filesystem. Below we demonstrate how one could use Redis. Check out the [memory integrations](https://integrations.langchain.com/memory) page for implementations of chat message histories using other providers."+ "### Dict with single key for all messages input, messages output\n",+ "\n",+ "This is a specific case of \"Dictionary input, message(s) output\". In this situation, because there is only a single key we don't need to specify as much - we only need to specify the `input_messages_key`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 24,+ "id": "7530c4ed",+ "metadata": {},+ "outputs": [],+ "source": [+ "from operator import itemgetter\n",+ "\n",+ "runnable_with_history = RunnableWithMessageHistory(\n",+ " itemgetter(\"input_messages\") | model,\n",+ " get_session_history,\n",+ " input_messages_key=\"input_messages\",\n",+ ")"]},{"cell_type": "markdown",- "id": "6bca45e5-35d9-4603-9ca9-6ac0ce0e35cd",+ "id": "def75152","metadata": {},"source": [- "### Setup\n",+ ":::info\n","\n",- "We'll need to install Redis if it's not installed already:"+ "Note that we've specified `input_messages_key` (the key to be treated as the latest input message).\n",+ "\n",+ ":::"]},{"cell_type": "code",- "execution_count": 14,- "id": "477d04b3-c2b6-4ba5-962f-492c0d625cd5",+ "execution_count": 25,+ "id": "659bc1bf","metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/plain": [+ "AIMessage(content=\"It's nice to meet you, Bob! I'm Claude, an AI assistant created by Anthropic. How can I help you today?\", response_metadata={'id': 'msg_01UdD5wz1J5xwoz5D94onaQC', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 32}}, id='run-91bee6eb-0814-4557-ad71-fef9b0270358-0', usage_metadata={'input_tokens': 12, 'output_tokens': 32, 'total_tokens': 44})"+ ]+ },+ "execution_count": 25,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],"source": [- "%pip install --upgrade --quiet redis"+ "runnable_with_history.invoke(\n",+ " {\"input_messages\": [HumanMessage(content=\"hi - im bob!\")]},\n",+ " config={\"configurable\": {\"session_id\": \"4\"}},\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 26,+ "id": "6da2835e",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "AIMessage(content='I\\'m afraid I don\\'t actually know your name - you introduced yourself as Bob, but I don\\'t have any other information about your identity. As an AI assistant, I don\\'t have a way to independently verify people\\'s names or identities. I\\'m happy to continue our conversation, but I\\'ll just refer to you as \"Bob\" since that\\'s the name you provided.', response_metadata={'id': 'msg_012WUygxBKXcVJPeTW14LNrc', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 52, 'output_tokens': 80}}, id='run-fcbaaa1a-8c33-4eec-b0b0-5b800a47bddd-0', usage_metadata={'input_tokens': 52, 'output_tokens': 80, 'total_tokens': 132})"+ ]+ },+ "execution_count": 26,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "runnable_with_history.invoke(\n",+ " {\"input_messages\": [HumanMessage(content=\"whats my name?\")]},\n",+ " config={\"configurable\": {\"session_id\": \"4\"}},\n",+ ")"]},{"cell_type": "markdown",- "id": "6a0ec9e0-7b1c-4c6f-b570-e61d520b47c6",+ "id": "d4c7a6f2","metadata": {},"source": [- "Start a local Redis Stack server if we don't have an existing Redis deployment to connect to:\n",- "```bash\n",- "docker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack:latest\n",- "```"+ ":::info\n",+ "\n",+ "Note that in this case the context is preserved via the chat history for the provided `session_id`, so the model knows the users name.\n",+ "\n",+ ":::\n",+ "\n",+ "We can now try this with a new session id and see that it does not remember."]},{"cell_type": "code",- "execution_count": 15,- "id": "cd6a250e-17fe-4368-a39d-1fe6b2cbde68",+ "execution_count": 27,+ "id": "6cf6abd6","metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/plain": [+ "AIMessage(content=\"I'm afraid I don't actually know your name. As an AI assistant, I don't have personal information about you unless you provide it to me directly.\", response_metadata={'id': 'msg_017xW3Ki5y4UBYzCU9Mf1pgM', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 12, 'output_tokens': 35}}, id='run-d2f372f7-3679-4a5c-9331-a55b820ec03e-0', usage_metadata={'input_tokens': 12, 'output_tokens': 35, 'total_tokens': 47})"+ ]+ },+ "execution_count": 27,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],"source": [- "REDIS_URL = \"redis://localhost:6379/0\""+ "runnable_with_history.invoke(\n",+ " {\"input_messages\": [HumanMessage(content=\"whats my name?\")]},\n",+ " config={\"configurable\": {\"session_id\": \"4a\"}},\n",+ ")"]},{"cell_type": "markdown",- "id": "36f43b87-655c-4f64-aa7b-bd8c1955d8e5",+ "id": "9839a6d1","metadata": {},"source": [- "### [LangSmith](https://docs.smith.langchain.com)\n",+ ":::info \n","\n",- "LangSmith is especially useful for something like message history injection, where it can be hard to otherwise understand what the inputs are to various parts of the chain.\n",+ "When we pass a different `session_id`, we start a new chat history, so the model does not know what the user's name is. \n","\n",- "Note that LangSmith is not needed, but it is helpful.\n",- "If you do want to use LangSmith, after you sign up at the link above, make sure to uncoment the below and set your environment variables to start logging traces:"+ ":::"]},{- "cell_type": "code",- "execution_count": 16,- "id": "2afc1556-8da1-4499-ba11-983b66c58b18",+ "cell_type": "markdown",+ "id": "a6710e65","metadata": {},- "outputs": [],"source": [- "# os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",- "# os.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass()"+ "## Customization"]},{"cell_type": "markdown",- "id": "f9d81796-ce61-484c-89e2-6c567d5e54ef",+ "id": "d29497be-3366-408d-bbb9-d4a8bf4ef37c","metadata": {},"source": [- "Updating the message history implementation just requires us to define a new callable, this time returning an instance of `RedisChatMessageHistory`:"+ "The configuration parameters by which we track message histories can be customized by passing in a list of ``ConfigurableFieldSpec`` objects to the ``history_factory_config`` parameter. Below, we use two parameters: a `user_id` and `conversation_id`."]},{"cell_type": "code",- "execution_count": 17,- "id": "ca7c64d8-e138-4ef8-9734-f82076c47d80",+ "execution_count": 30,+ "id": "1c89daee-deff-4fdf-86a3-178f7d8ef536","metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/plain": [+ "AIMessage(content='Ciao Bob! È un piacere conoscerti. Come stai oggi?', response_metadata={'id': 'msg_016RJebCoiAgWaNcbv9wrMNW', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 29, 'output_tokens': 23}}, id='run-40425414-8f72-47d4-bf1d-a84175d8b3f8-0', usage_metadata={'input_tokens': 29, 'output_tokens': 23, 'total_tokens': 52})"+ ]+ },+ "execution_count": 30,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],"source": [- "from langchain_community.chat_message_histories import RedisChatMessageHistory\n",+ "from langchain_core.runnables import ConfigurableFieldSpec\n","\n","\n",- "def get_message_history(session_id: str) -> RedisChatMessageHistory:\n",- " return RedisChatMessageHistory(session_id, url=REDIS_URL)\n",+ "def get_session_history(user_id: str, conversation_id: str):\n",+ " return SQLChatMessageHistory(f\"{user_id}--{conversation_id}\", \"sqlite:///memory.db\")\n","\n","\n","with_message_history = RunnableWithMessageHistory(\n"," runnable,\n",- " get_message_history,\n",+ " get_session_history,\n"," input_messages_key=\"input\",\n"," history_messages_key=\"history\",\n",+ " history_factory_config=[\n",+ " ConfigurableFieldSpec(\n",+ " id=\"user_id\",\n",+ " annotation=str,\n",+ " name=\"User ID\",\n",+ " description=\"Unique identifier for the user.\",\n",+ " default=\"\",\n",+ " is_shared=True,\n",+ " ),\n",+ " ConfigurableFieldSpec(\n",+ " id=\"conversation_id\",\n",+ " annotation=str,\n",+ " name=\"Conversation ID\",\n",+ " description=\"Unique identifier for the conversation.\",\n",+ " default=\"\",\n",+ " is_shared=True,\n",+ " ),\n",+ " ],\n",+ ")\n",+ "\n",+ "with_message_history.invoke(\n",+ " {\"language\": \"italian\", \"input\": \"hi im bob!\"},\n",+ " config={\"configurable\": {\"user_id\": \"123\", \"conversation_id\": \"1\"}},\n",")"]},- {- "cell_type": "markdown",- "id": "37eefdec-9901-4650-b64c-d3c097ed5f4d",- "metadata": {},- "source": [- "We can invoke as before:"- ]- },{"cell_type": "code",- "execution_count": 18,- "id": "a85bcc22-ca4c-4ad5-9440-f94be7318f3e",+ "execution_count": 32,+ "id": "4f282883","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='Cosine is a trigonometric function that represents the ratio of the adjacent side to the hypotenuse of a right triangle.', response_metadata={'id': 'msg_01DwU2BD8KPLoXeZ6bZPqxxJ', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 164, 'output_tokens': 31}}, id='run-c2a443c4-79b1-4b07-bb42-5e9112e5bbfc-0')"+ "AIMessage(content='Bob, il tuo nome è Bob.', response_metadata={'id': 'msg_01Kktiy3auFDKESY54KtTWPX', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 60, 'output_tokens': 12}}, id='run-c7768420-3f30-43f5-8834-74b1979630dd-0', usage_metadata={'input_tokens': 60, 'output_tokens': 12, 'total_tokens': 72})"]},- "execution_count": 18,+ "execution_count": 32,"metadata": {},"output_type": "execute_result"}],"source": [+ "# remembers\n","with_message_history.invoke(\n",- " {\"ability\": \"math\", \"input\": \"What does cosine mean?\"},\n",- " config={\"configurable\": {\"session_id\": \"foobar\"}},\n",+ " {\"language\": \"italian\", \"input\": \"whats my name?\"},\n",+ " config={\"configurable\": {\"user_id\": \"123\", \"conversation_id\": \"1\"}},\n",")"]},{"cell_type": "code",- "execution_count": 19,- "id": "ab29abd3-751f-41ce-a1b0-53f6b565e79d",+ "execution_count": 33,+ "id": "fc122c18","metadata": {},"outputs": [{"data": {"text/plain": [- "AIMessage(content='The inverse of cosine is called arccosine or inverse cosine.', response_metadata={'id': 'msg_01XYH5iCUokxV1UDhUa8xzna', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 202, 'output_tokens': 19}}, id='run-97dda3a2-01e3-42e5-8241-f948e7535ffc-0')"+ "AIMessage(content='Mi dispiace, non so il tuo nome. Come posso aiutarti?', response_metadata={'id': 'msg_0178FpbpPNioB7kqvyHk7rjD', 'model': 'claude-3-haiku-20240307', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 30, 'output_tokens': 23}}, id='run-df1f1768-aab6-4aec-8bba-e33fc9e90b8d-0', usage_metadata={'input_tokens': 30, 'output_tokens': 23, 'total_tokens': 53})"]},- "execution_count": 19,+ "execution_count": 33,"metadata": {},"output_type": "execute_result"}],"source": [+ "# New user_id --> does not remember\n","with_message_history.invoke(\n",- " {\"ability\": \"math\", \"input\": \"What's its inverse\"},\n",- " config={\"configurable\": {\"session_id\": \"foobar\"}},\n",+ " {\"language\": \"italian\", \"input\": \"whats my name?\"},\n",+ " config={\"configurable\": {\"user_id\": \"456\", \"conversation_id\": \"1\"}},\n",")"]},{"cell_type": "markdown",- "id": "da3d1feb-b4bb-4624-961c-7db2e1180df7",- "metadata": {},- "source": [- ":::tip\n",- "\n",- "[Langsmith trace](https://smith.langchain.com/public/bd73e122-6ec1-48b2-82df-e6483dc9cb63/r)\n",- "\n",- ":::"- ]- },- {- "cell_type": "markdown",- "id": "61d5115e-64a1-4ad5-b676-8afd4ef6093e",- "metadata": {},- "source": [- "Looking at the Langsmith trace for the second call, we can see that when constructing the prompt, a \"history\" variable has been injected which is a list of two messages (our first input and first output)."- ]- },- {- "cell_type": "markdown",- "id": "fd510b68",+ "id": "3ce37565","metadata": {},"source": [- "## Next steps\n",- "\n",- "You have now learned one way to manage message history for a runnable.\n",- "\n",- "To learn more, see the other how-to guides on runnables in this section."+ "Note that in this case the context was preserved for the same `user_id`, but once we changed it, the new chat history was started, even though the `conversation_id` was the same."]}],@@ -769,7 +884,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.12.3"+ "version": "3.10.1"}},"nbformat": 4,diff --git a/docs/static/img/message_history.png b/docs/static/img/message_history.pngnew file mode 100644index 0000000000..31f7664d28Binary files /dev/null and b/docs/static/img/message_history.png differdiff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.pyindex 3ff6df09d7..fdc40e5583 100644--- a/libs/core/langchain_core/runnables/history.py+++ b/libs/core/langchain_core/runnables/history.py@@ -372,6 +372,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):) -> List[BaseMessage]:from langchain_core.messages import BaseMessage+ # If dictionary, try to pluck the single key representing messagesif isinstance(input_val, dict):if self.input_messages_key:key = self.input_messages_key@@ -381,13 +382,25 @@ class RunnableWithMessageHistory(RunnableBindingBase):key = "input"input_val = input_val[key]+ # If value is a string, convert to a human messageif isinstance(input_val, str):from langchain_core.messages import HumanMessagereturn [HumanMessage(content=input_val)]+ # If value is a single message, convert to a listelif isinstance(input_val, BaseMessage):return [input_val]+ # If value is a list or tuple...elif isinstance(input_val, (list, tuple)):+ # Handle empty case+ if len(input_val) == 0:+ return list(input_val)+ # If is a list of list, then return the first value+ # This occurs for chat models - since we batch inputs+ if isinstance(input_val[0], list):+ if len(input_val) != 1:+ raise ValueError()+ return input_val[0]return list(input_val)else:raise ValueError(@@ -400,6 +413,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):) -> List[BaseMessage]:from langchain_core.messages import BaseMessage+ # If dictionary, try to pluck the single key representing messagesif isinstance(output_val, dict):if self.output_messages_key:key = self.output_messages_key@@ -418,6 +432,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):from langchain_core.messages import AIMessagereturn [AIMessage(content=output_val)]+ # If value is a single message, convert to a listelif isinstance(output_val, BaseMessage):return [output_val]elif isinstance(output_val, (list, tuple)):@@ -431,7 +446,10 @@ class RunnableWithMessageHistory(RunnableBindingBase):if not self.history_messages_key:# return all messages- messages += self._get_input_messages(input)+ input_val = (+ input if not self.input_messages_key else input[self.input_messages_key]+ )+ messages += self._get_input_messages(input_val)return messagesasync def _aenter_history(@@ -454,7 +472,6 @@ class RunnableWithMessageHistory(RunnableBindingBase):# Get the input messagesinputs = load(run.inputs)input_messages = self._get_input_messages(inputs)-# If historic messages were prepended to the input messages, remove them to# avoid adding duplicate messages to history.if not self.history_messages_key:diff --git a/libs/core/langchain_core/tracers/base.py b/libs/core/langchain_core/tracers/base.pyindex c7373556c5..8f553e52f2 100644--- a/libs/core/langchain_core/tracers/base.py+++ b/libs/core/langchain_core/tracers/base.py@@ -48,7 +48,9 @@ class BaseTracer(BaseCallbackHandler, ABC):def __init__(self,*,- _schema_format: Literal["original", "streaming_events"] = "original",+ _schema_format: Literal[+ "original", "streaming_events", "original+chat"+ ] = "original",**kwargs: Any,) -> None:"""Initialize the tracer.@@ -63,6 +65,8 @@ class BaseTracer(BaseCallbackHandler, ABC):for internal usage. It will likely change in the future, orbe deprecated entirely in favor of a dedicated async tracerfor streaming events.+ - 'original+chat' is a format that is the same as 'original'+ except it does NOT raise an attribute error on_chat_model_startkwargs: Additional keyword arguments that will be passed tothe super class."""@@ -163,7 +167,7 @@ class BaseTracer(BaseCallbackHandler, ABC):**kwargs: Any,) -> Run:"""Start a trace for an LLM run."""- if self._schema_format != "streaming_events":+ if self._schema_format not in ("streaming_events", "original+chat"):# Please keep this un-implemented for backwards compatibility.# When it's unimplemented old tracers that use the "original" format# fallback on the on_llm_start method implementation if they@@ -360,7 +364,7 @@ class BaseTracer(BaseCallbackHandler, ABC):def _get_chain_inputs(self, inputs: Any) -> Any:"""Get the inputs for a chain run."""- if self._schema_format == "original":+ if self._schema_format in ("original", "original+chat"):return inputs if isinstance(inputs, dict) else {"input": inputs}elif self._schema_format == "streaming_events":return {@@ -371,7 +375,7 @@ class BaseTracer(BaseCallbackHandler, ABC):def _get_chain_outputs(self, outputs: Any) -> Any:"""Get the outputs for a chain run."""- if self._schema_format == "original":+ if self._schema_format in ("original", "original+chat"):return outputs if isinstance(outputs, dict) else {"output": outputs}elif self._schema_format == "streaming_events":return {@@ -436,7 +440,7 @@ class BaseTracer(BaseCallbackHandler, ABC):if metadata:kwargs.update({"metadata": metadata})- if self._schema_format == "original":+ if self._schema_format in ("original", "original+chat"):inputs = {"input": input_str}elif self._schema_format == "streaming_events":inputs = {"input": inputs}diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.pyindex 8b1f2da9f5..4f15675523 100644--- a/libs/core/langchain_core/tracers/log_stream.py+++ b/libs/core/langchain_core/tracers/log_stream.py@@ -482,7 +482,7 @@ def _get_standardized_inputs(def _get_standardized_outputs(- run: Run, schema_format: Literal["original", "streaming_events"]+ run: Run, schema_format: Literal["original", "streaming_events", "original+chat"]) -> Optional[Any]:"""Extract standardized output from a run.diff --git a/libs/core/langchain_core/tracers/root_listeners.py b/libs/core/langchain_core/tracers/root_listeners.pyindex 7db7407d26..4b33a2fe53 100644--- a/libs/core/langchain_core/tracers/root_listeners.py+++ b/libs/core/langchain_core/tracers/root_listeners.py@@ -22,7 +22,7 @@ class RootListenersTracer(BaseTracer):on_end: Optional[Listener],on_error: Optional[Listener],) -> None:- super().__init__()+ super().__init__(_schema_format="original+chat")self.config = configself._arg_on_start = on_startdiff --git a/libs/core/tests/unit_tests/fake/memory.py b/libs/core/tests/unit_tests/fake/memory.pyindex 43dd53dc5e..d8431fa859 100644--- a/libs/core/tests/unit_tests/fake/memory.py+++ b/libs/core/tests/unit_tests/fake/memory.py@@ -17,6 +17,8 @@ class ChatMessageHistory(BaseChatMessageHistory, BaseModel):def add_message(self, message: BaseMessage) -> None:"""Add a self-created message to the store"""+ if not isinstance(message, BaseMessage):+ raise ValueErrorself.messages.append(message)def clear(self) -> None: