### Run Tests Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md Installs dependencies and runs project tests using pnpm. ```bash pnpm i pnpm run test ``` -------------------------------- ### Install langgraph-checkpoint-mongodb Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md Installs the langgraph-checkpoint-mongodb package using pnpm or npm. ```bash pnpm add langgraph-checkpoint-mongodb # or: npm i langgraph-checkpoint-mongodb ``` -------------------------------- ### Complete LangGraph Integration Example with MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Full example demonstrating how to integrate MongoCheckpointSaver with a LangGraph application for persistent, resumable agent conversations. This includes setting up a singleton pattern for checkpointer management and handling connection lifecycle. It requires MongoDB connection details and LangGraph dependencies. ```typescript import { MongoClient } from 'mongodb' import type { BaseCheckpointSaver } from '@langchain/langgraph' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' // Singleton pattern for checkpointer management let saver: BaseCheckpointSaver | null = null let client: MongoClient | null = null export async function getCheckpointer(): Promise { if (saver) return saver const uri = process.env.MONGODB_URI! const dbName = process.env.MONGODB_DB || 'langgraph' client = await MongoClient.connect(uri) saver = new MongoCheckpointSaver(client, dbName) return saver } export async function closeCheckpointer(): Promise { if (client) { await client.close() client = null saver = null } } // Usage with LangGraph (pseudocode) async function runAgent() { const checkpointer = await getCheckpointer() // Create your LangGraph with the checkpointer // const graph = createGraph({ checkpointer }) // Run with a thread ID for persistence // const result = await graph.invoke(input, { // configurable: { // thread_id: 'user-123', // checkpoint_ns: 'default' // } // }) } // Cleanup on shutdown process.on('SIGTERM', async () => { await closeCheckpointer() process.exit(0) }) ``` -------------------------------- ### Initialize MongoCheckpointSaver (JavaScript CJS) Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md A minimal example of initializing MongoCheckpointSaver in JavaScript (CJS). It connects to MongoDB and creates a saver instance. ```javascript const { MongoClient } = require('mongodb') const { MongoCheckpointSaver } = require('langgraph-checkpoint-mongodb') (async () => { const client = await MongoClient.connect(process.env.MONGODB_URI) const saver = new MongoCheckpointSaver(client, process.env.MONGODB_DB) // use saver })() ``` -------------------------------- ### Build Project Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md Builds the project using the pnpm run build command. ```bash pnpm run build ``` -------------------------------- ### Initialize MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Instantiates the MongoDB checkpointer. Supports basic connection strings or custom serialization (serde) for advanced data handling. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' // Basic usage without custom serde const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'my_langgraph_db') // With custom JSON serde for explicit serialization control const jsonSerde = { async dumpsTyped(value: unknown): Promise<[string, Uint8Array]> { const buf = Buffer.from(JSON.stringify(value)) return ['json', new Uint8Array(buf)] }, async loadsTyped(_type: string, bytes: Uint8Array): Promise { const str = Buffer.from(bytes).toString('utf-8') return JSON.parse(str) }, } const saverWithSerde = new MongoCheckpointSaver(client, 'my_langgraph_db', jsonSerde) ``` -------------------------------- ### Initialize MongoCheckpointSaver with Custom Serde (TypeScript ESM) Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md Shows how to use MongoCheckpointSaver with a custom serde for efficient typed storage in TypeScript (ESM). It defines `dumpsTyped` and `loadsTyped` functions. ```javascript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const serde = { async dumpsTyped(v) { const buf = Buffer.from(JSON.stringify(v)) return ['json', new Uint8Array(buf)] as const }, async loadsTyped(_t, b) { return JSON.parse(Buffer.from(b).toString('utf8')) }, } const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, process.env.MONGODB_DB!, serde) // provide `saver` to your LangGraph app ``` -------------------------------- ### Initialize MongoCheckpointSaver (TypeScript ESM) Source: https://github.com/lablnet/langgraph-checkpoint-mongodb/blob/main/README.md Demonstrates simple usage of MongoCheckpointSaver in TypeScript (ESM) without a custom serde. It connects to MongoDB and initializes the saver. ```typescript import { MongoClient } from 'mongodb' import type { BaseCheckpointSaver } from '@langchain/langgraph' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' let saver: BaseCheckpointSaver | null = null export async function getCheckpointer(): Promise { if (saver) return saver const dbName = process.env.MONGODB_DB! const uri = process.env.MONGODB_URI! const client = await MongoClient.connect(uri) saver = new MongoCheckpointSaver(client, dbName) return saver } export async function closeCheckpointer() { if (!saver) return // if you kept a client reference, close it here saver = null } ``` -------------------------------- ### List Checkpoints with Pagination and Filtering using MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Provides an asynchronous iterator to list checkpoints for a thread, sorted by timestamp. Supports pagination via `limit`, filtering by `before` a specific checkpoint, and custom query filters. Useful for historical analysis or state restoration. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) const config = { configurable: { thread_id: 'conversation-789', checkpoint_ns: 'chat' } } console.log('All checkpoints:') for await (const item of saver.list(config)) { console.log(` - ${item.checkpoint.id} at ${item.checkpoint.ts}`) } console.log(' First 5 checkpoints:') for await (const item of saver.list(config, { limit: 5 })) { console.log(` - ${item.checkpoint.id}`) } const beforeConfig = { configurable: { thread_id: 'conversation-789', checkpoint_ns: 'chat', checkpoint_id: 'cp-5' } } console.log(' Checkpoints before cp-5:') for await (const item of saver.list(config, { before: beforeConfig, limit: 3 })) { console.log(` - ${item.checkpoint.id}`) } ``` -------------------------------- ### Method: put Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Stores a checkpoint snapshot in MongoDB. This method persists the current state of the graph, allowing the agent to resume from this specific point later. ```APIDOC ## POST /put ### Description Stores a checkpoint snapshot in MongoDB. Returns a RunnableConfig that references the exact checkpoint, allowing LangGraph to resume from this state. ### Method POST ### Parameters #### Request Body - **config** (object) - Required - Contains thread_id and checkpoint_ns. - **checkpoint** (object) - Required - The checkpoint object matching LangGraph's Checkpoint interface. - **metadata** (object) - Required - Metadata associated with the checkpoint. - **newVersions** (object) - Required - Channel versions for the checkpoint. ### Request Example { "config": { "configurable": { "thread_id": "user-123", "checkpoint_ns": "default" } }, "checkpoint": { "id": "cp-001", "ts": "2023-10-27T10:00:00Z" }, "metadata": { "source": "input" }, "newVersions": { "messages": 1 } } ### Response #### Success Response (200) - **RunnableConfig** (object) - The configuration object updated with the checkpoint_id. #### Response Example { "configurable": { "thread_id": "user-123", "checkpoint_ns": "default", "checkpoint_id": "cp-001" } } ``` -------------------------------- ### Retrieve Full Checkpoint Tuple with MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Retrieves a complete checkpoint tuple, including the checkpoint, metadata, pending writes, and configuration. This is essential for restoring agent state in LangGraph. The method handles deserialization and returns all relevant data for a given thread and namespace. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) const config = { configurable: { thread_id: 'agent-session-456', checkpoint_ns: 'workflow' } } const tuple = await saver.getTuple(config) if (tuple) { console.log('Checkpoint:', tuple.checkpoint.id) console.log('Config:', tuple.config.configurable) console.log('Metadata:', tuple.metadata) console.log('Pending writes count:', tuple.pendingWrites?.length) tuple.pendingWrites?.forEach(([taskId, channel, value]) => { console.log(` Task ${taskId} -> ${channel}:`, value) }) } ``` -------------------------------- ### Store Checkpoint with put() Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Persists a checkpoint snapshot to MongoDB. Returns a configuration object containing the checkpoint ID for future state resumption. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) const config = { configurable: { thread_id: 'user-session-123', checkpoint_ns: 'default' } } const checkpoint = { v: 1, id: 'checkpoint-001', ts: new Date().toISOString(), channel_values: { messages: ['Hello', 'World'] }, channel_versions: { messages: 1 }, versions_seen: {}, pending_sends: [] } const metadata = { source: 'input', step: 0, parents: {} } const newVersions = { messages: 1 } const savedConfig = await saver.put(config, checkpoint, metadata, newVersions) console.log('Saved checkpoint ID:', savedConfig.configurable?.checkpoint_id) ``` -------------------------------- ### Retrieve Latest Checkpoint with MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Fetches the most recent checkpoint for a specified thread and namespace using MongoCheckpointSaver. It deserializes the checkpoint using the configured serde. Returns undefined if no checkpoint is found. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) const config = { configurable: { thread_id: 'user-session-123', checkpoint_ns: 'default' } } const checkpoint = await saver.get(config) if (checkpoint) { console.log('Checkpoint ID:', checkpoint.id) console.log('Timestamp:', checkpoint.ts) console.log('Channel values:', checkpoint.channel_values) } else { console.log('No checkpoint found for this thread') } ``` -------------------------------- ### Method: putWrites Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Stores pending writes associated with a specific checkpoint. These are serialized channel updates that have not yet been committed to a full checkpoint. ```APIDOC ## POST /putWrites ### Description Stores pending writes associated with a checkpoint. Each write is stored with its channel name, task ID, and serialized value. ### Method POST ### Parameters #### Request Body - **config** (object) - Required - The config object containing the checkpoint reference. - **writes** (array) - Required - Array of [channel_name, value] tuples. - **taskId** (string) - Required - The unique ID of the task performing the write. ### Request Example { "config": { "configurable": { "checkpoint_id": "cp-001" } }, "writes": [["messages", { "role": "user" }]], "taskId": "task-abc-123" } ### Response #### Success Response (200) - **void** - Returns nothing upon successful storage. #### Response Example { "status": "success" } ``` -------------------------------- ### Store Pending Writes with putWrites() Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Saves pending channel updates associated with a specific checkpoint. This is used to track state changes that have not yet been finalized in a checkpoint. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) const config = { configurable: { thread_id: 'agent-session-456', checkpoint_ns: 'workflow' } } const checkpoint = { v: 1, id: 'cp-workflow-1', ts: new Date().toISOString(), channel_values: {}, channel_versions: {}, versions_seen: {}, pending_sends: [] } const savedConfig = await saver.put(config, checkpoint, { source: 'input', step: 0, parents: {} }, {}) const writes = [ ['messages', { role: 'user', content: 'What is the weather?' }], ['tool_calls', { name: 'get_weather', args: { location: 'NYC' } }] ] await saver.putWrites(savedConfig, writes, 'task-abc-123') console.log('Pending writes stored successfully') ``` -------------------------------- ### Clear All Checkpoints with MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Wipes all checkpoints, writes, and versions from the MongoDB database. This operation should be used with caution as it removes all stored state for all threads. It requires a MongoClient instance and a MongoCheckpointSaver configured with a database name and optionally a serde object. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) // Clear all data (use with caution!) await saver.clearAll() console.log('All checkpoint data cleared') ``` -------------------------------- ### Delete Thread Data with MongoCheckpointSaver Source: https://context7.com/lablnet/langgraph-checkpoint-mongodb/llms.txt Removes all checkpoints, writes, and version data associated with a specific thread ID and namespace. This method is useful for cleaning up old conversations or resetting an agent's state entirely. It confirms deletion by attempting to retrieve a checkpoint afterward. ```typescript import { MongoClient } from 'mongodb' import { MongoCheckpointSaver } from 'langgraph-checkpoint-mongodb' const client = await MongoClient.connect(process.env.MONGODB_URI!) const saver = new MongoCheckpointSaver(client, 'langgraph_db', jsonSerde) await saver.deleteThread('user-session-123', 'default') console.log('Thread data deleted') const config = { configurable: { thread_id: 'user-session-123', checkpoint_ns: 'default' } } const checkpoint = await saver.get(config) console.log('Checkpoint after deletion:', checkpoint) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.