AI Hints
Home›LangGraph Tutorial›Memory in Graphs
LangGraph · Lesson 76 of 120

The Store in Nodes

Read and write.

⏱ 2 min read▶ Video at 1:21:33🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

To use the store inside a graph, pass it to compile. Then any node can reach it, through a runtime argument. The runtime also carries the context, like which customer is talking.

The Store in Nodes
From the video: The Store in Nodes
  • Pass the store to compile
  • Nodes reach it
  • Through the runtime

Save in one node, read in another

The context class holds the user ID. The save node writes the customer's favourite genre to the store, under their namespace. The greet node reads it back. Both get the store from runtime dot store. We compile with the store, and pass the context when invoking. Run it. The greeting uses the genre saved by the first node.

store_nodes.pypython
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore

@dataclass
class Ctx:
    user_id: str
class State(TypedDict):
    genre: str
    greeting: str
def save(s, runtime: Runtime[Ctx]):
    runtime.store.put(("prefs", runtime.context.user_id), "genre", {"value": s["genre"]})
def greet(s, runtime: Runtime[Ctx]):
    genre = runtime.store.get(("prefs", runtime.context.user_id), "genre").value["value"]
    return {"greeting": f"Welcome back! New {genre} books are in."}
b = StateGraph(State, context_schema=Ctx); b.add_sequence([save, greet]); b.add_edge(START, "save")
print(b.compile(store=InMemoryStore()).invoke({"genre": "fantasy"}, context=Ctx("sam"))["greeting"])
Output
Welcome back! New fantasy books are in.

Runtime

A node can take a second argument, the runtime. Runtime dot store is the store passed to compile. Runtime dot context is the context passed to invoke. Context is the safe place for the user ID, because the model can never change it.

keyvalue
runtime.storefrom compile
runtime.contextfrom invoke
User IDin context
Safemodel can't change it

Summary

Compile with a store, and nodes reach it through runtime dot store, with the user from runtime dot context. Next, remembering preferences across conversations.

Key takeaways
  • compile(store=...)
  • runtime.store
  • runtime.context
Next up: Remembering Preferences — across threads