@ -30,36 +30,12 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.memory import ChatMessageHistory"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4404d509",
"metadata": {},
"outputs": [],
"source": [
"history = ChatMessageHistory()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "78c1a67b",
"metadata": {},
"outputs": [],
"source": [
"history.add_user_message(\"hi!\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "525ce606",
"metadata": {},
"outputs": [],
"source": [
"from langchain.memory import ChatMessageHistory\n",
"\n",
"history = ChatMessageHistory()\n",
"\n",
"history.add_user_message(\"hi!\")\n",
"\n",
"history.add_ai_message(\"whats up?\")"
]
},
@ -331,6 +307,99 @@
"conversation.predict(input=\"Tell me about yourself.\")"
]
},
{
"cell_type": "markdown",
"id": "fb68bb9e",
"metadata": {},
"source": [
"## Saving Message History\n",
"\n",
"You may often to save messages, and then load them to use again. This can be done easily by first converting the messages to normal python dictionaries, saving those (as json or something) and then loading those. Here is an example of doing that."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "b5acbc4b",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"from langchain.memory import ChatMessageHistory\n",
"from langchain.schema import messages_from_dict, messages_to_dict\n",
"\n",
"history = ChatMessageHistory()\n",
"\n",
"history.add_user_message(\"hi!\")\n",
"\n",
"history.add_ai_message(\"whats up?\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7812ee21",
"metadata": {},
"outputs": [],
"source": [
"dicts = messages_to_dict(history.messages)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "3ed6e6a0",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'type': 'human', 'data': {'content': 'hi!', 'additional_kwargs': {}}},\n",
" {'type': 'ai', 'data': {'content': 'whats up?', 'additional_kwargs': {}}}]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dicts"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cdf4ebd2",
"metadata": {},
"outputs": [],
"source": [
"new_messages = messages_from_dict(dicts)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "9724e24b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[HumanMessage(content='hi!', additional_kwargs={}),\n",
" AIMessage(content='whats up?', additional_kwargs={})]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"new_messages"
]
},
{
"cell_type": "markdown",
"id": "7826c210",