AI AgentsLangChain
How do you access persistent state inside a tool?
Question 295 of 324 · Updated
On this page
- Direct answer
- 1. Choose the correct persistence boundary
- 2. Configure state, a checkpointer and a store
- 3. Read graph state and update it with Command
- 4. Read a namespaced cross-thread record using runtime.store
- 5. Serialize data, not live dependencies
- 6. Tested Python implementation: durable thread and user records with version checks
- 7. Concurrency and consistency: avoid stale writes and double application
- 8. Recovery when a tool writes both a store and graph state
- 9. Tenant isolation and lifecycle controls
- 10. Production test plan and common mistakes
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In modern LangChain, a tool can receive an injected ToolRuntime object and use runtime.state to read the current graph state and runtime.store to access an explicitly configured store. Graph state becomes resumable when the agent has a suitable checkpointer and the host invokes it using an authorized thread identifier. A store supports data shared across threads through application-defined namespaces. To update graph state from a tool, return a supported LangGraph Command with an explicit state update rather than mutating the runtime state dictionary.
A store write and a graph-state update are different operations. They do not automatically form one atomic transaction. In-memory backends demonstrate the interfaces but do not survive a process restart.
The generic checkpointing lessons (#55, #56 and #151) explain recovery principles. The LangChain runtime context and dependency injection lessons (#290 and #294) explain trusted invocation dependencies. This lesson focuses on reading state and store records from tools, returning state updates and preserving persistence boundaries. Memory retrieval strategies, history trimming, memory consolidation and the full LangGraph persistence architecture receive separate lessons.
1. Choose the correct persistence boundary#
Imagine a fictional parcel-quotation assistant. Within one support conversation it remembers the latest verified quote reference. Across separate conversations, a customer may have an explicitly saved preference for brief responses.
| Facility | Appropriate contents | Lifetime | How a tool accesses it |
|---|---|---|---|
| Runtime context | Authenticated principal, approved scoped service | Invocation; reconstruct on resume | runtime.context |
| Graph state | Current messages, quote reference, progress and evidence | Thread or run; optionally checkpointed | runtime.state |
| Checkpointer | Serialized graph state and execution recovery information | Depends on backend and retention | Managed by the graph runtime |
| Store | Namespaced preferences or approved durable records | Can span multiple threads; backend dependent | runtime.store |
| External domain database | Authoritative invoices, payments or business records | Domain-specific durability | Authorized service dependency |
The checkpointer and store are complementary, not interchangeable. Checkpointing the graph does not automatically save a cross-thread preference. Writing to a store does not necessarily advance the graph checkpoint. Even a configured persistent store does not automatically place every record in the model's context window.
This is an architectural view rather than an exact representation of internal SDK execution or checkpoint order.
2. Configure state, a checkpointer and a store#
The following examples illustrate common modern LangChain/LangGraph interfaces. LangChain, langchain_core and langgraph were absent from the local environment. All framework snippets are unexecuted and version-dependent. Verify the installed release, provider integration, supported state schema and persistence backends before use.
PYTHONfrom dataclasses import dataclass from typing import NotRequired from langchain.agents import AgentState, create_agent from langchain.tools import tool, ToolRuntime from langgraph.checkpoint.memory import InMemorySaver from langgraph.store.memory import InMemoryStore @dataclass(frozen=True) class SupportContext: tenant_id: str user_id: str class SupportState(AgentState): quote_ref: NotRequired[str] @tool def read_quote_reference(runtime: ToolRuntime[SupportContext]) -> str: """Read the current conversation's saved quote reference.""" return runtime.state.get("quote_ref") or "No quote reference recorded."
The custom state schema extends AgentState so the graph can track the optional quote_ref field in addition to its normal message state. The runtime parameter is injected rather than generated by the model. The tool's return value is a read-only observation, not a state update.
The next section adds a state-update tool, and section 4 adds a store-read tool. An agent can then be configured as follows, after those functions have been defined:
PYTHONcheckpointer = InMemorySaver() store = InMemoryStore() agent = create_agent( model="openai:gpt-4o-mini", tools=[read_quote_reference, record_demo_quote, read_preference], state_schema=SupportState, context_schema=SupportContext, checkpointer=checkpointer, store=store, system_prompt="Report verified fictional quote references only.", ) ctx = SupportContext(tenant_id="demo-a", user_id="demo-user") config = {"configurable": {"thread_id": "authorized-demo-thread-1"}} # The host must authenticate the caller and authorize the thread first. result = agent.invoke( {"messages": [{"role": "user", "content": "Record the fictional quote Q-17."}]}, config=config, context=ctx, )
The model ID is illustrative, not a guarantee of current access. The thread ID and identity values are synthetic. In a real service, authorize thread ownership before passing the identifier to the graph, and validate that the caller can access every business resource referenced by the thread.
A subsequent invocation with the same authorized thread ID and checkpointer can continue from checkpointed state according to the installed runtime's invocation semantics. A different thread normally has its own execution state. Both threads may access the same user-level store namespace if the host has authorized that access.
InMemorySaver and InMemoryStore are useful for development. They retain data in process memory; they are not durable across application restart, nor automatically shared between independent workers. Production deployments need a supported durable backend, explicit connection management, retention, backups and access controls.
3. Read graph state and update it with Command#
Treat runtime.state as the state available to the current tool invocation. A tool can read specific fields, but changing a dictionary in place is not a supported substitute for a graph transition. Direct mutation can bypass reducers, conflict detection, checkpointing and other graph execution semantics.
Use a Command in supported tool execution paths to propose a state update. When a tool call has been made by the model, include a correlated ToolMessage when the runtime requires a tool response in the messages state.
PYTHONfrom langgraph.types import Command from langchain_core.messages import ToolMessage @tool def record_demo_quote( quote_ref: str, runtime: ToolRuntime[SupportContext], ) -> Command: """Record a verified fictional quote reference in this conversation.""" # Synthetic fixture only; real quotes require a scoped lookup. if quote_ref != "Q-17": return Command(update={ "messages": [ToolMessage( content="Quote unavailable.", tool_call_id=runtime.tool_call_id, )], }) return Command(update={ "quote_ref": quote_ref, "messages": [ToolMessage( content="Recorded fictional quote Q-17.", tool_call_id=runtime.tool_call_id, )], })
The Command declares that the graph should update quote_ref and append or merge the tool observation using its configured state semantics. The tool-call ID associates the result with the model's proposed call. The example is intended for actual tool-node execution with an available correlation ID, not for a bare Python invocation with a fabricated runtime.
The quote_ref state field uses ordinary replacement semantics in this example. If two parallel tools attempt to update the same field at the same graph step, the runtime may reject conflicting writes unless appropriate reducers or coordination are configured. Do not assume last-write-wins behavior. For an append-only field, a correctly designed reducer might merge independent updates, but a reducer is not automatically an authorization check or a database transaction.
The fictional fixture only permits Q-17. A production tool must independently verify that a quote exists and is visible to the authenticated principal before recording it. A string in checkpointed state is not proof that the underlying record remains valid or accessible.
Checkpoint timing and durability modes depend on the configured runtime. The diagram does not imply that every Command is synchronously flushed before the next model request.
4. Read a namespaced cross-thread record using runtime.store#
A store holds records under namespaces and keys. Use a stable application-owned namespace that includes the authorized tenant and subject where the record is private. A user-level preference namespace can be shared by that user's different authorized threads.
PYTHON@tool def read_preference(runtime: ToolRuntime[SupportContext]) -> str: """Read the caller's explicitly saved response-format preference.""" ctx = runtime.context if not isinstance(ctx, SupportContext) or not ctx.tenant_id or not ctx.user_id: raise PermissionError("invalid context") if runtime.store is None: return "Preference store unavailable." namespace = ("preferences", ctx.tenant_id, ctx.user_id) item = runtime.store.get(namespace, "response_format") if item is None: return "No response-format preference recorded." value = item.value if not isinstance(value, dict) or value.get("format") not in ("brief", "detailed"): return "Preference unavailable." return value["format"]
The namespace is constructed from trusted context, not from model-supplied tenant or user values. The store result is validated before returning only the small permitted preference. Missing or malformed records do not silently produce a privileged default.
For this demo, an authorized host can seed a preference using the configured store's put interface:
PYTHON# Illustrative trusted-host operation, after authorization and user choice. store.put( ("preferences", ctx.tenant_id, ctx.user_id), "response_format", {"format": "brief"}, )
A tool that writes preferences can also use the supported store interface, but it must validate the proposed value, check whether the operation is permitted, and respect user consent and retention requirements. A preference-setting tool should not be given arbitrary namespace access.
The exact get/put signatures, item representation, async APIs, indexing and retention capabilities depend on the installed store implementation. These SDK examples are not local execution results.
A namespace is a logical address, not an access-control mechanism. If the underlying store lets any authorized service read any namespace, an application bug can still leak another tenant's data. Enforce access through scoped service policies, backend controls where available and negative integration tests.
The repeated user identifier X is intentional: identifiers may be unique only within a tenant. Include all required isolation dimensions in the namespace.
5. Serialize data, not live dependencies#
Checkpointed state and store values should consist of supported serializable representations. The actual graph serializer may support more types than JSON; use a deliberately narrow representation for application-owned fields to keep recovery portable and reviewable.
| Good persistence candidate | Poor persistence candidate |
|---|---|
| Stable quote reference | Open database connection |
| Validated workflow status | Live HTTP client or coroutine |
| Schema version and bounded evidence | Raw credential or bearer token |
| Approved preference value | Entire request object or unrestricted runtime context |
| Durable operation reference | Temporary process-local object identity |
A live dependency belongs in runtime context and should be reconstructed after interruption or process restart. A checkpoint should not grant permanent access to a resource that was authorized in the past. Recheck permissions before exposing or acting on restored references.
Version custom state and store records. For example, a preference record might carry schema_version=1 and format="brief". A migration can validate older records and translate them to a newer supported format. Reject incompatible or corrupted values rather than guessing at their meaning. Avoid unsafe deserialization of untrusted objects.
Do not store private information just because persistence is available. Enforce retention, encryption and deletion according to the application's policy, including copies held in checkpoints, stores, backups and diagnostic traces.
6. Tested Python implementation: durable thread and user records with version checks#
The following runnable teaching example uses Python's standard-library sqlite3 module and a temporary SQLite file. It illustrates the application's persistence invariants independently of LangChain. It is not an implementation of LangGraph's checkpoint protocol, tool Command semantics or store API.
The host supplies a synthetic Scope containing an authenticated tenant, owner and authorized thread. Thread records are keyed by thread ID. User-level records are keyed by a fixed preference key. A conditional update checks the expected version so an older read cannot silently overwrite a newer committed value.
PYTHONimport json import sqlite3 from dataclasses import dataclass from pathlib import Path from tempfile import TemporaryDirectory @dataclass(frozen=True) class Scope: tenant: str user: str thread: str # selected by an authorized host, not the model class Conflict(Exception): pass class Records: def __init__(self, path): self.db = sqlite3.connect(path) self.db.execute('''CREATE TABLE IF NOT EXISTS records ( tenant TEXT NOT NULL, owner TEXT NOT NULL, kind TEXT NOT NULL, key TEXT NOT NULL, version INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (tenant, owner, kind, key))''') self.db.commit() def read(self, scope, kind): key = scope.thread if kind == 'thread' else 'preferences' row = self.db.execute('''SELECT version, value FROM records WHERE tenant=? AND owner=? AND kind=? AND key=?''', (scope.tenant, scope.user, kind, key)).fetchone() return (row[0], json.loads(row[1])) if row else (0, None) def save(self, scope, kind, expected, value): if kind not in ('thread', 'user'): raise ValueError('unknown record kind') key = scope.thread if kind == 'thread' else 'preferences' payload = json.dumps(value, allow_nan=False) with self.db: if expected == 0: cur = self.db.execute('''INSERT INTO records VALUES (?, ?, ?, ?, 1, ?) ON CONFLICT DO NOTHING''', (scope.tenant, scope.user, kind, key, payload)) else: cur = self.db.execute('''UPDATE records SET version=version+1, value=? WHERE tenant=? AND owner=? AND kind=? AND key=? AND version=?''', (payload, scope.tenant, scope.user, kind, key, expected)) if cur.rowcount != 1: raise Conflict('stale record version') return expected + 1 with TemporaryDirectory() as tmp: path = Path(tmp) / 'records.db' a = Scope('a', 'u1', 't1') a2 = Scope('a', 'u1', 't2') b = Scope('b', 'u1', 't1') other = Scope('a', 'u2', 't1') r = Records(path) assert r.read(a, 'thread') == (0, None) assert r.save(a, 'thread', 0, {'stage':'quoted'}) == 1 assert r.save(a, 'user', 0, {'format':'brief'}) == 1 assert r.read(a2, 'thread') == (0, None) assert r.read(a2, 'user') == (1, {'format':'brief'}) assert r.read(b, 'user') == r.read(b, 'thread') == (0, None) assert r.read(other, 'user') == r.read(other, 'thread') == (0, None) r.db.close() r = Records(path) assert r.read(a, 'thread') == (1, {'stage':'quoted'}) s = Records(path) old, _ = s.read(a, 'thread') assert r.save(a, 'thread', old, {'stage':'verified'}) == 2 try: s.save(a, 'thread', old, {'stage':'stale'}) except Conflict: pass else: raise AssertionError('stale write accepted') assert s.read(a, 'thread') == (2, {'stage':'verified'}) try: r.save(a, 'user', 1, {'bad':object()}) except TypeError: pass else: raise AssertionError('nonserializable data accepted') assert r.read(a, 'user') == (1, {'format':'brief'}) s.db.close() r.db.close() print('13 checks passed')
Actual local execution on Python 3.13.5 and SQLite 3.46.1:
13 checks passed| Test group | Observed behavior |
|---|---|
| Initial read and insert | Missing record, then committed version 1 |
| Separate thread | New thread does not inherit old thread state |
| Cross-thread preference | Same tenant and user can read the saved preference |
| Tenant isolation | Tenant B with identical user/thread IDs sees no records from tenant A |
| Subject isolation | Another user in tenant A sees no private records |
| Reopen database | Previously committed thread record survives connection close and reopen |
| Stale update | Second connection cannot overwrite version 2 with stale version 1 |
| Serialization failure | Unsupported object raises TypeError and previous committed value remains |
The test demonstrates ordinary committed-file persistence across reopening, not survival of arbitrary power loss or distributed failover. The two database connections simulate a sequential stale-read conflict; they do not benchmark simultaneous concurrent transactions. SQLite locking, transaction isolation and busy handling must be considered for real concurrent workloads.
The Scope is a synthetic trusted input. Constructing it does not authenticate a real user. read and save are deliberately narrow teaching methods; production code should validate all kinds, values, versions and identifiers, enforce thread ownership, and wrap connection cleanup in robust resource-management code. This implementation assumes cooperating authorized callers and does not implement a full production permission system, migration framework or schema validation for stored values.
7. Concurrency and consistency: avoid stale writes and double application#
Suppose two tool invocations read a preference record at version 7. One saves a new value and advances it to version 8. The second attempts an update based on version 7.
Without coordination, the later writer may accidentally replace the first writer's result. With compare-and-set semantics, the second write fails because its expected version no longer matches. The application can reload the current value and decide whether a fresh update is still appropriate.
This is a recommended application-level consistency strategy, not a claim that runtime.store.put exposes compare-and-set in every LangGraph backend. Where the store lacks a conditional-write interface, use an authorized service with transactions or another appropriate coordination mechanism. Do not implement read-modify-write using two separate calls and assume atomicity.
For graph state, use supported reducers, explicit ordering or a single writer per field when updates conflict. For thread-level concurrency, choose a policy for simultaneous invocations on the same thread: reject overlap, queue work or use a deployment-specific supported conflict strategy. Two workers must not each assume exclusive ownership of a workflow.
An additive reducer is not necessarily safe to replay. If a repeated operation increments a counter twice, the final state can become incorrect. Use durable operation identifiers and deduplication when needed. A tool-call ID can help correlate results but may change when a model regenerates a call; it is not automatically a stable business idempotency key.
8. Recovery when a tool writes both a store and graph state#
Consider a tool that stores an approved preference and returns a Command updating the thread's progress. A failure can occur after the store write commits but before the state checkpoint is durably saved. On resume, the graph may repeat work while the cross-thread record already exists.
| Observed situation | Safe recovery |
|---|---|
| Store update committed, checkpoint missing | Read authoritative record and reconcile before reapplying |
| Checkpoint records intent, store update missing | Verify current authorization and retry only under a safe policy |
| Both present | Confirm matching operation identity and expected result |
| Both uncertain | Investigate durable evidence; avoid claiming success |
| State refers to revoked or deleted resource | Reauthorize and invalidate stale reference |
Do not treat the store and checkpoint as one transaction unless the actual implementation explicitly provides that guarantee. For a critical write, persist an operation record or use a transactional outbox in the authoritative domain system where appropriate. Make retries idempotent and reconcile uncertain outcomes.
A possible design uses a stable approved operation ID and a domain record with pending, applied and verified statuses. The tool reads the authoritative result before repeating an operation. The graph checkpoint records a reference to that operation rather than becoming the sole proof that a payment, email or other external action occurred.
A checkpoint restore does not undo a store write or external transaction. Replaying a graph from an earlier point should be performed in a controlled environment or with side effects safely disabled/reconciled.
9. Tenant isolation and lifecycle controls#
Before invoking an agent with a thread ID, authenticate the caller and resolve whether that thread is accessible. A guessed thread identifier must not grant access to its state. Use a trusted thread registry and enforce access at the persistence boundary. Do not accept a namespace directly from model-generated arguments for private data.
Separate:
- The model's task arguments, such as a quote reference.
- Trusted runtime context, including the current principal.
- Authorized thread identifiers selected by the host.
- Namespaces and keys derived by application policy.
- Business records accessed through scoped services.
Treat restored messages and store content as data rather than trusted instructions. An old stored message may contain prompt injection or invalid authorization claims. Validate relevant records, freshness and permissions before using them. Keep credentials out of state and store values.
For async execution, use supported asynchronous store and checkpointer methods where available, with compatible clients and appropriate connection ownership. A synchronous store call inside an async tool may block an event loop. Test actual behavior in the installed runtime and backend rather than assuming the wrapper makes blocking operations nonblocking.
10. Production test plan and common mistakes#
Start with deterministic unit tests for state-update logic, namespace construction, serialization and authorization. Then run actual SDK integration tests in a controlled environment.
| Test | Acceptance condition |
|---|---|
| First tool invocation | Reads expected initial state and returns a supported Command |
| State update | Correct field and correlated tool observation survive the graph transition |
| Same-thread continuation | Authorized thread restores expected checkpointed state |
| New-thread invocation | Does not inherit unrelated thread state |
| Store read | Retrieves only approved cross-thread record |
| Missing store | Controlled unavailable response |
| Cross-tenant access | No unauthorized thread or namespace data returned |
| Concurrent update | Conflict handled explicitly, without lost updates |
| Restart and resume | Durable backend restores state and dependencies are reconstructed |
| Failure between writes | Reconciliation avoids duplicated side effects |
| Serialization and schema upgrade | Invalid or incompatible record rejected or migrated safely |
Use in-memory backends for fast unit tests and real durable backends for persistence integration tests. Test storage outages, malformed records, missing context, retention, concurrent writes and failure injection at the actual commit boundaries. For observability, record safe thread or operation aliases, checkpoint and record versions, conflict categories, recovery outcomes and latency. Avoid dumping private state or credentials into traces.
Common mistakes include assuming an in-memory backend survives restart, using a raw thread ID as authorization, mutating runtime.state directly, omitting the required ToolMessage for a Command response, confusing cross-thread store records with checkpointed state, persisting live clients, and treating separate writes as atomic. Each is preventable through explicit contracts and integration tests.
Interview-ready answer#
I inject ToolRuntime into the tool and read runtime.state for current thread state or runtime.store for configured namespaced cross-thread records. I configure a checkpointer and use an authorized thread ID for resumable graph state. To update graph state I return a supported Command with the required correlated tool observation, respecting state schemas and reducers rather than mutating state directly. I derive store namespaces from trusted identity, persist serializable values, enforce current permissions, coordinate concurrent updates and reconcile failures across store writes and checkpoints. In-memory backends are for demonstrations; durable backends and real recovery tests are required in production.
Official documentation research leads and verification status#
- LangChain tools
- LangChain runtime
- LangChain short-term memory
- LangChain long-term memory
- LangGraph persistence
- LangChain API reference
- Python sqlite3 documentation
- Python JSON documentation
Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. Local Python 3.13.5 and SQLite 3.46.1 executed the standalone persistence example successfully with 13 checks. LangChain, langchain_core and langgraph were absent, so SDK examples, actual state/Command/store integration and provider behavior were not executed or version-verified. All records are synthetic and the test used a temporary local database. Mermaid diagrams are stored in triple-backtick fences; live rendering and public website display were not verified.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain runtimedocs.langchain.com
- 3.LangChain short-term memorydocs.langchain.com
- 4.LangChain long-term memorydocs.langchain.com
- 5.LangGraph persistencedocs.langchain.com
- 6.LangChain API referencereference.langchain.com
- 7.Python sqlite3 documentationdocs.python.org
- 8.Python JSON documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps