LangChain Graph Checkpoint Example
Table of Contents
1. Introduction
This document demonstrates how to use checkpoints in LangChain graphs. Checkpoints allow you to save the state of a graph at a specific point in time and resume execution from that point later. This is useful for debugging, human-in-the-loop interactions, and resuming long-running graphs.
2. Setup
2.1. Install necessary packages
pip install langchain | grep langchain
2.2. Import necessary modules
from langchain.graphs import Graph
from langchain.chains import LLMChain
from langchain.llms import OpenAI
3. Define the Graph
3.1. Create a simple graph with two nodes
graph = Graph()
# Add a node that generates text
graph.add_node(
LLMChain(llm=OpenAI(temperature=0), prompt="What is the capital of France?"),
"generate_text",
)
# Add a node that summarizes the text
graph.add_node(
LLMChain(llm=OpenAI(temperature=0), prompt="Summarize the following text: {text}"),
"summarize_text",
)
# Connect the nodes
graph.add_edge("generate_text", "summarize_text", "text")
4. Run the Graph with Checkpoints
4.1. Execute the graph with the checkpoint parameter
# Run the graph with checkpoints enabled
result = graph.execute(
inputs={},
checkpoint="my_checkpoint.json", # Save checkpoint to this file
)
print(result)
5. Resume the Graph from a Checkpoint
5.1. Load the checkpoint and resume execution
# Load the graph from the checkpoint
graph = Graph.from_checkpoint("my_checkpoint.json")
# Resume execution from the checkpoint
result = graph.execute(inputs={})
print(result)
6. Conclusion
This example demonstrates how to use checkpoints in LangChain graphs. This feature manages the state of your graphs and makes them more reliable.