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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d31df93e",
   "metadata": {},
   "source": [
    "# Getting Started\n",
    "\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 convenience 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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "87235cf1",
   "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?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "be030822",
   "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": [
    "history.messages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c0328fb",
   "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a382b160",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "a280d337",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = ConversationBufferMemory()\n",
    "memory.chat_memory.add_user_message(\"hi!\")\n",
    "memory.chat_memory.add_ai_message(\"whats up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1b739c0a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'Human: hi!\\nAI: whats up?'}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "989e9425",
   "metadata": {},
   "source": [
    "We can also get the history as a list of messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "798ceb1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = ConversationBufferMemory(return_messages=True)\n",
    "memory.chat_memory.add_user_message(\"hi!\")\n",
    "memory.chat_memory.add_ai_message(\"whats up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "698688fd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': [HumanMessage(content='hi!', additional_kwargs={}),\n",
       "  AIMessage(content='whats up?', additional_kwargs={})]}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d051c1da",
   "metadata": {},
   "source": [
    "## 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)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "54301321",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.llms import OpenAI\n",
    "from langchain.chains import ConversationChain\n",
    "\n",
    "\n",
    "llm = OpenAI(temperature=0)\n",
    "conversation = ConversationChain(\n",
    "    llm=llm, \n",
    "    verbose=True, \n",
    "    memory=ConversationBufferMemory()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ae046bff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "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",
      "\n",
      "Current conversation:\n",
      "\n",
      "Human: Hi there!\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\" Hi there! It's nice to meet you. How can I help you today?\""
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"Hi there!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d8e2a6ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "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",
      "\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",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\" That's great! It's always nice to have a conversation with someone new. What would you like to talk about?\""
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"I'm doing well! Just having a conversation with an AI.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "15eda316",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "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",
      "\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",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "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.\""
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"Tell me about yourself.\")"
   ]
  },
  {
   "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",
   "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,
   "id": "3dd37d93",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}