0
0
LangChainframework~5 mins

Checkpointing and persistence in LangChain

Choose your learning style9 modes available
Introduction

Checkpointing and persistence help save your work so you can continue later without losing progress.

When running long tasks that might stop unexpectedly.
When you want to save intermediate results to avoid repeating work.
When you want to keep a record of your chatbot conversations.
When you want to reload a previous state of your application quickly.
Syntax
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()

# Save conversation state
memory.save_context({'input': 'Hello'}, {'output': 'Hi there!'})

# Load conversation state
history = memory.load_memory_variables({})

save_context stores the input and output of a conversation step.

load_memory_variables retrieves the saved conversation history.

Examples
This example saves a simple greeting and then prints the saved conversation.
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.save_context({'input': 'Hi'}, {'output': 'Hello!'})
history = memory.load_memory_variables({})
print(history)
Here, we use a custom key chat_history to store and retrieve the conversation.
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history")

memory.save_context({'input': 'How are you?'}, {'output': 'I am fine, thanks!'})
chat = memory.load_memory_variables({})
print(chat['chat_history'])
Sample Program

This program saves two conversation exchanges and then prints the full conversation history stored in memory.

LangChain
from langchain.memory import ConversationBufferMemory

# Create memory to store conversation
memory = ConversationBufferMemory()

# Simulate saving conversation steps
memory.save_context({'input': 'Hello, LangChain!'}, {'output': 'Hi! How can I help you?'})
memory.save_context({'input': 'What is checkpointing?'}, {'output': 'It saves your progress so you don\'t lose data.'})

# Load and print conversation history
history = memory.load_memory_variables({})
print(history['history'])
OutputSuccess
Important Notes

Checkpointing helps avoid losing data if your program stops unexpectedly.

Persistence means saving data to disk or database so it lasts beyond program runs.

LangChain memory classes make it easy to save and load conversation states.

Summary

Checkpointing saves your work so you can continue later.

Persistence keeps data safe beyond one program run.

LangChain provides memory tools to manage conversation history easily.