Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firebase Checkpoint Saver #694

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"devDependencies": {
"@langchain/anthropic": "^0.3.5",
"@langchain/community": "^0.3.9",
"@langchain/core": "^0.3.16",
"@langchain/core": "^0.3.19",
"@langchain/groq": "^0.1.2",
"@langchain/langgraph": "workspace:*",
"@langchain/mistralai": "^0.1.1",
Expand Down
6 changes: 6 additions & 0 deletions libs/checkpoint-firebase/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# ------------------LangSmith tracing------------------
LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
LANGCHAIN_API_KEY=
LANGCHAIN_PROJECT=
# -----------------------------------------------------
69 changes: 69 additions & 0 deletions libs/checkpoint-firebase/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
module.exports = {
extends: [
"airbnb-base",
"eslint:recommended",
"prettier",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: 12,
parser: "@typescript-eslint/parser",
project: "./tsconfig.json",
sourceType: "module",
},
plugins: ["@typescript-eslint", "no-instanceof", "eslint-plugin-jest"],
ignorePatterns: [
".eslintrc.cjs",
"scripts",
"node_modules",
"dist",
"dist-cjs",
"*.js",
"*.cjs",
"*.d.ts",
],
rules: {
"no-process-env": 2,
"no-instanceof/no-instanceof": 2,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-shadow": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-use-before-define": ["error", "nofunc"],
"@typescript-eslint/no-unused-vars": ["warn", { args: "none" }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
"arrow-body-style": 0,
camelcase: 0,
"class-methods-use-this": 0,
"import/extensions": [2, "ignorePackages"],
"import/no-extraneous-dependencies": [
"error",
{ devDependencies: ["**/*.test.ts"] },
],
"import/no-unresolved": 0,
"import/prefer-default-export": 0,
'jest/no-focused-tests': 'error',
"keyword-spacing": "error",
"max-classes-per-file": 0,
"max-len": 0,
"no-await-in-loop": 0,
"no-bitwise": 0,
"no-console": 0,
"no-empty-function": 0,
"no-restricted-syntax": 0,
"no-shadow": 0,
"no-continue": 0,
"no-void": 0,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-useless-constructor": 0,
"no-return-await": 0,
"consistent-return": 0,
"no-else-return": 0,
"func-names": 0,
"no-lonely-if": 0,
"prefer-rest-params": 0,
"new-cap": ["error", { properties: false, capIsNew: false }],
},
};
7 changes: 7 additions & 0 deletions libs/checkpoint-firebase/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
index.cjs
index.js
index.d.ts
index.d.cts
node_modules
dist
.yarn
19 changes: 19 additions & 0 deletions libs/checkpoint-firebase/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"htmlWhitespaceSensitivity": "css",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf"
}
13 changes: 13 additions & 0 deletions libs/checkpoint-firebase/.release-it.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"github": {
"release": true,
"autoGenerate": true,
"tokenRef": "GITHUB_TOKEN_RELEASE"
},
"npm": {
"publish": true,
"versionArgs": [
"--workspaces-update=false"
]
}
}
21 changes: 21 additions & 0 deletions libs/checkpoint-firebase/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2024 LangChain

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
109 changes: 109 additions & 0 deletions libs/checkpoint-firebase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# @langchain/langgraph-checkpoint-firebase

Implementation of a [LangGraph.js](https://github.com/langchain-ai/langgraphjs) CheckpointSaver that uses a FireBase instance.

The `FirebaseSaver` class is an implementation of the `BaseCheckpointSaver` interface that uses Firebase Realtime Database for persistence. It is part of the `@langchain/langgraph-checkpoint` library and provides scalable, real-time management of checkpoints in LangGraph.js.

---

## Features

- **Firebase Persistence**: Leverages Firebase's real-time capabilities to store checkpoints and metadata.
- **Thread Management**: Isolates states using thread-based checkpointing for multi-tenant or parallel use cases.
- **Pending Writes**: Handles intermediate writes for partially executed graph nodes.
- **Real-Time Updates**: Takes advantage of Firebase's dynamic data updates for live applications.

---

## Installation

### Prerequisites
- Firebase Realtime Database instance
- Node.js with TypeScript

### Install Dependencies
```bash
npm install @langchain/langgraph-checkpoint firebase

### Usage

```ts
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import { FirebaseSaver } from "@langchain/langgraph-checkpoint-firebase";

const writeConfig = {
configurable: {
thread_id: "1",
checkpoint_ns: ""
}
};
const readConfig = {
configurable: {
thread_id: "1"
}
};

const writeConfig = {
configurable: {
thread_id: "1",
checkpoint_ns: ""
}
};
const readConfig = {
configurable: {
thread_id: "1"
}
};

const firebaseConfig = {
apiKey: "REPLACE-WITH-YOUR-API-KEY",
authDomain: "REPLACE-WITH-YOUR-localhost",
projectId: "REPLACE-WITH-YOUR-TEST-PROJECT",
databaseURL: process.env.FIREBASEURL || "http://localhost:9000", // Use emulator URL
};
process.env.FIREBASE_URL = process.env.FIREBASEURL || "http://localhost:9000"
const app = initializeApp(firebaseConfig);

database = getDatabase(app);

const checkpoint = {
v: 1,
ts: "2024-07-31T20:14:19.804150+00:00",
id: "1ef4f797-8335-6428-8001-8a1503f9b875",
channel_values: {
my_key: "meow",
node: "node"
},
channel_versions: {
__start__: 2,
my_key: 3,
start:node: 3,
node: 3
},
versions_seen: {
__input__: {},
__start__: {
__start__: 1
},
node: {
start:node: 2
}
},
pending_sends: [],
}

// store checkpoint
await checkpointer.put(writeConfig, checkpoint, {}, {});

// load checkpoint
await checkpointer.get(readConfig);

// list checkpoints
for await (const checkpoint of checkpointer.list(readConfig)) {
console.log(checkpoint);
}

await client.close();
```

20 changes: 20 additions & 0 deletions libs/checkpoint-firebase/jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest/presets/default-esm",
testEnvironment: "./jest.env.cjs",
modulePathIgnorePatterns: ["dist/"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.tsx?$": ["@swc/jest"],
},
transformIgnorePatterns: [
"/node_modules/",
"\\.pnp\\.[^\\/]+$",
"./scripts/jest-setup-after-env.js",
],
setupFiles: ["dotenv/config"],
testTimeout: 20_000,
passWithNoTests: true,
};
12 changes: 12 additions & 0 deletions libs/checkpoint-firebase/jest.env.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { TestEnvironment } = require("jest-environment-node");

class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment {
constructor(config, context) {
// Make `instanceof Float32Array` return true in tests
// to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549
super(config, context);
this.global.Float32Array = Float32Array;
}
}

module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
21 changes: 21 additions & 0 deletions libs/checkpoint-firebase/langchain.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";

/**
* @param {string} relativePath
* @returns {string}
*/
function abs(relativePath) {
return resolve(dirname(fileURLToPath(import.meta.url)), relativePath);
}

export const config = {
internals: [/node\:/, /@langchain\/core\//, /async_hooks/],
entrypoints: {
index: "index"
},
tsConfigPath: resolve("./tsconfig.json"),
cjsSource: "./dist-cjs",
cjsDestination: "./dist",
abs,
};
Loading