Agent with Memory

Open in ColabOpen in GitHub

Overview

This tutorial covers how to add an in-memory checkpoint saver to an agent.

An in-memory checkpoint saver enables an agent to store previous interactions, allowing the agent to engage in multi-turn conversations in a coherent manner.

Also in this tutorial, we use ToolNode and tools_condition prebuilt in LangGraph instead of a customized tool node.

Table of Contents

References


Environment Setup

Setting up your environment is the first step. See the Environment Setup guide for more details.

[Note]

langchain-opentutorial is a package of easy-to-use environment setup guidance, useful functions and utilities for tutorials. Check out the langchain-opentutorial for more details.

You can set API keys in a .env file or set them manually.

[Note] If you’re not using the .env file, no worries! Just enter the keys directly in the cell below, and you’re good to go.

Memory Saver

Without a memory to remember the context, an agent cannot engage in multi-turn interactions.

In this tutorial, we use LangGraph's MemorySaver, which stores checkpoints in memory.

By providing a checkpointer during graph compilation and a thread_id when calling a graph, the state is automatically saved after each step. The thread_id acts as a key for continuous graph execution.

Steps to use MemorySaver:

  1. Create a MemorySaver checkpointer.

  1. Define a graph.

  1. Compile the graph with the checkpointer.

  1. Visualize the graph.

png

Configuration with RunnableConfig

Define a RunnableConfig object and set the recursion_limit and thread_id properties.

  • recursion_limit: The maximum number of nodes the graph can visit. Exceeding this limit will trigger a RecursionError.

  • thread_id: An ID to distinguish different sessions.

Modify the thread_id in the RunnableConfig to see if the agent remembers the previous conversation.

Inspecting State Snapshots

A checkpoint (snapshot) stores:

  • the current state values

  • corresponding config

  • The next node to process (empty at the end).

Call get_state(config) to see a graph's state for a certain config.

You can access the configuration with snapshot.config.

You can access the saved states with snapshot.value.

You can use snapshot.next to see which node will be processed next. In this case, snapshot.next is empty since the graph reaches the END node.

Define custom functions to view the complete contents of snapshot and its metadata (snapshot.metadata).

Last updated