langchain/docs/modules/memory/getting_started.ipynb

442 lines
12 KiB
Plaintext
Raw Normal View History

2022-12-27 14:17:01 +00:00
{
"cells": [
{
"cell_type": "markdown",
"id": "d31df93e",
"metadata": {},
"source": [
"# Getting Started\n",
2022-12-27 14:17:01 +00:00
"\n",
"This notebook walks through how LangChain thinks about memory. \n",
"\n",
"Memory involves keeping a concept of state around throughout a user's interactions with an language model. A user's interactions with a language model are captured in the concept of ChatMessages, so this boils down to ingesting, capturing, transforming and extracting knowledge from a sequence of chat messages. There are many different ways to do this, each of which exists as its own memory type.\n",
"\n",
"In general, for each type of memory there are two ways to understanding using memory. These are the standalone functions which extract information from a sequence of messages, and then there is the way you can use this type of memory in a chain. \n",
"\n",
"Memory can return multiple pieces of information (for example, the most recent N messages and a summary of all previous messages). The returned information can either be a string or a list of messages.\n",
"\n",
"In this notebook, we will walk through the simplest form of memory: \"buffer\" memory, which just involves keeping a buffer of all prior messages. We will show how to use the modular utility functions here, then show how it can be used in a chain (both returning a string as well as a list of messages).\n",
"\n",
"## ChatMessageHistory\n",
"One of the core utility classes underpinning most (if not all) memory modules is the `ChatMessageHistory` class. This is a super lightweight wrapper which exposes convienence methods for saving Human messages, AI messages, and then fetching them all. \n",
"\n",
"You may want to use this class directly if you are managing memory outside of a chain."
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 1,
2023-03-07 17:02:40 +00:00
"id": "87235cf1",
2022-12-27 14:17:01 +00:00
"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?\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 5,
2023-03-07 17:02:40 +00:00
"id": "be030822",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[HumanMessage(content='hi!', additional_kwargs={}),\n",
" AIMessage(content='whats up?', additional_kwargs={})]"
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 5,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"history.messages"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "markdown",
2023-03-07 17:02:40 +00:00
"id": "2c0328fb",
2022-12-27 14:17:01 +00:00
"metadata": {},
"source": [
"## ConversationBufferMemory\n",
"\n",
"We now show how to use this simple concept in a chain. We first showcase `ConversationBufferMemory` which is just a wrapper around ChatMessageHistory that extracts the messages in a variable.\n",
"\n",
"We can first extract it as a string."
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 7,
2023-03-07 17:02:40 +00:00
"id": "a382b160",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [],
2022-12-27 14:17:01 +00:00
"source": [
"from langchain.memory import ConversationBufferMemory"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 10,
2023-03-07 17:02:40 +00:00
"id": "a280d337",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [],
"source": [
"memory = ConversationBufferMemory()\n",
"memory.chat_memory.add_user_message(\"hi!\")\n",
"memory.chat_memory.add_ai_message(\"whats up?\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 12,
2023-03-07 17:02:40 +00:00
"id": "1b739c0a",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'history': 'Human: hi!\\nAI: whats up?'}"
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 12,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"memory.load_memory_variables({})"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "markdown",
2023-03-07 17:02:40 +00:00
"id": "989e9425",
2022-12-27 14:17:01 +00:00
"metadata": {},
"source": [
"We can also get the history as a list of messages"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 13,
2023-03-07 17:02:40 +00:00
"id": "798ceb1c",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [],
2022-12-27 14:17:01 +00:00
"source": [
"memory = ConversationBufferMemory(return_messages=True)\n",
"memory.chat_memory.add_user_message(\"hi!\")\n",
"memory.chat_memory.add_ai_message(\"whats up?\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 14,
2023-03-07 17:02:40 +00:00
"id": "698688fd",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'history': [HumanMessage(content='hi!', additional_kwargs={}),\n",
" AIMessage(content='whats up?', additional_kwargs={})]}"
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 14,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"memory.load_memory_variables({})"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "markdown",
"id": "d051c1da",
2022-12-27 14:17:01 +00:00
"metadata": {},
"source": [
2023-03-07 17:02:40 +00:00
"## Using in a chain\n",
"Finally, let's take a look at using this in a chain (setting `verbose=True` so we can see the prompt)."
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "54301321",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [],
2022-12-27 14:17:01 +00:00
"source": [
"from langchain.llms import OpenAI\n",
"from langchain.chains import ConversationChain\n",
"\n",
"\n",
"llm = OpenAI(temperature=0)\n",
"conversation = ConversationChain(\n",
2022-12-27 14:17:01 +00:00
" llm=llm, \n",
" verbose=True, \n",
" memory=ConversationBufferMemory()\n",
")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "ae046bff",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
2022-12-27 14:17:01 +00:00
"Prompt after formatting:\n",
"\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
2022-12-27 14:17:01 +00:00
"\n",
"Current conversation:\n",
"\n",
"Human: Hi there!\n",
"AI:\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
2022-12-27 14:17:01 +00:00
]
},
{
"data": {
"text/plain": [
"\" Hi there! It's nice to meet you. How can I help you today?\""
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 16,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.predict(input=\"Hi there!\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "d8e2a6ff",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
2022-12-27 14:17:01 +00:00
"Prompt after formatting:\n",
"\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
2022-12-27 14:17:01 +00:00
"\n",
"Current conversation:\n",
"Human: Hi there!\n",
"AI: Hi there! It's nice to meet you. How can I help you today?\n",
"Human: I'm doing well! Just having a conversation with an AI.\n",
"AI:\u001b[0m\n",
2022-12-27 14:17:01 +00:00
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
2022-12-27 14:17:01 +00:00
]
},
{
"data": {
"text/plain": [
"\" That's great! It's always nice to have a conversation with someone new. What would you like to talk about?\""
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 17,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.predict(input=\"I'm doing well! Just having a conversation with an AI.\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "15eda316",
2022-12-27 14:17:01 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
2022-12-27 14:17:01 +00:00
"Prompt after formatting:\n",
"\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
2022-12-27 14:17:01 +00:00
"\n",
"Current conversation:\n",
"Human: Hi there!\n",
"AI: Hi there! It's nice to meet you. How can I help you today?\n",
"Human: I'm doing well! Just having a conversation with an AI.\n",
"AI: That's great! It's always nice to have a conversation with someone new. What would you like to talk about?\n",
"Human: Tell me about yourself.\n",
"AI:\u001b[0m\n",
2022-12-27 14:17:01 +00:00
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
2022-12-27 14:17:01 +00:00
]
},
{
"data": {
"text/plain": [
"\" Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers.\""
2022-12-27 14:17:01 +00:00
]
},
"execution_count": 18,
2022-12-27 14:17:01 +00:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.predict(input=\"Tell me about yourself.\")"
2022-12-27 14:17:01 +00:00
]
},
{
"cell_type": "markdown",
"id": "fb68bb9e",
"metadata": {},
"source": [
"## Saving Message History\n",
"\n",
"You may often have 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",
2023-03-07 17:02:40 +00:00
"id": "7826c210",
"metadata": {},
"source": [
"And that's it for the getting started! There are plenty of different types of memory, check out our examples to see them all"
]
},
{
"cell_type": "code",
"execution_count": null,
2023-03-07 17:02:40 +00:00
"id": "3dd37d93",
"metadata": {},
"outputs": [],
2022-12-27 14:17:01 +00:00
"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.9.1"
2022-12-27 14:17:01 +00:00
}
},
"nbformat": 4,
"nbformat_minor": 5
}