@videoq-jp/langchainjs-postgres 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yuki Harada
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,334 @@
1
- # Temporary Holding Version
1
+ # langchainjs-postgres
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/%40videoq-jp%2Flangchainjs-postgres.svg)](https://www.npmjs.com/package/@videoq-jp/langchainjs-postgres)
4
+ [![CI](https://github.com/videoq-jp/langchainjs-postgres/actions/workflows/ci.yml/badge.svg)](https://github.com/videoq-jp/langchainjs-postgres/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ An **unofficial** [LangChain.js](https://github.com/langchain-ai/langchainjs) port of
8
+ [`langchain-postgres`](https://github.com/langchain-ai/langchain-postgres) — implementations
9
+ of core LangChain abstractions using Postgres / [pgvector](https://github.com/pgvector/pgvector),
10
+ hand-translated from Python to TypeScript.
11
+
12
+ > [!NOTE]
13
+ > Not affiliated with or endorsed by LangChain. If you want the official, first-party Postgres
14
+ > integration for LangChain.js, see
15
+ > [`@langchain/community`](https://www.npmjs.com/package/@langchain/community).
16
+
17
+ The package is released under the MIT license. Feel free to use the abstractions as provided,
18
+ or modify / extend them as appropriate for your own application.
19
+
20
+ ## Requirements
21
+
22
+ - Node.js >= 20
23
+ - Postgres with the [`pgvector`](https://github.com/pgvector/pgvector) extension available
24
+ (`CREATE EXTENSION IF NOT EXISTS vector` is run automatically by `initVectorstoreTable`)
25
+ - [`pg`](https://www.npmjs.com/package/pg) (`node-postgres`) as the driver
26
+
27
+ ## Installation
28
+
29
+ You can use npm, pnpm, or yarn to install `langchainjs-postgres`:
30
+
31
+ `npm install @videoq-jp/langchainjs-postgres @langchain/core pg langsmith@0.10.9`
32
+
33
+ `pnpm add @videoq-jp/langchainjs-postgres @langchain/core pg langsmith@0.10.9`
34
+
35
+ `yarn add @videoq-jp/langchainjs-postgres @langchain/core pg langsmith@0.10.9`
36
+
37
+ Both ESM (`import`) and CommonJS (`require`) are supported, including their respective
38
+ TypeScript declarations with `Node16` and `NodeNext` module resolution.
39
+
40
+ LangSmith 0.10.10 and 0.10.11 ship incomplete `NullableHeaders` declarations. The package's
41
+ peer dependency excludes these releases; the commands above select 0.10.9 so strict
42
+ TypeScript consumers using `NodeNext` do not need `skipLibCheck`. When upgrading an existing project,
43
+ update its LangSmith dependency and lockfile as well. Revisit this constraint once an
44
+ upstream fix passes the package compatibility checks.
45
+
46
+ For `Node16` resolution, upstream LangChain/js-tiktoken and LangSmith declarations still
47
+ produce TS1479 when checking dependencies. Use `NodeNext` for full dependency checking,
48
+ or set `skipLibCheck: true` with `Node16`; consumer imports are checked in both modes.
49
+
50
+ ## Vectorstore
51
+
52
+ > [!WARNING]
53
+ > `PGVector` is a straight port of upstream's deprecated collection/embedding-table schema.
54
+ > Prefer `PGVectorStore` below for new projects — it's faster and easier to manage. See
55
+ > [Legacy `PGVector`](#legacy-pgvector) for migrating an existing schema.
56
+
57
+ ### Documentation
58
+
59
+ - [Example](#example) — minimal quickstart below
60
+ - [Integration tests](tests/integration) — runnable examples against a real Postgres +
61
+ pgvector instance
62
+
63
+ > [!TIP]
64
+ > For developing, debugging, and deploying AI agents and LLM applications, see
65
+ > [LangSmith](https://docs.langchain.com/langsmith/home).
66
+
67
+ ### Example
68
+
69
+ ```typescript
70
+ import { PGEngine, PGVectorStore } from "@videoq-jp/langchainjs-postgres";
71
+ import { OpenAIEmbeddings } from "@langchain/openai";
72
+ import { Document } from "@langchain/core/documents";
73
+
74
+ const engine = PGEngine.fromConnectionString(process.env.DATABASE_URL!);
75
+
76
+ await engine.initVectorstoreTable("documents", 1536, {
77
+ metadataColumns: [{ name: "category", dataType: "TEXT" }],
78
+ });
79
+
80
+ const vectorStore = await PGVectorStore.initialize(
81
+ engine,
82
+ new OpenAIEmbeddings(),
83
+ "documents",
84
+ {
85
+ metadataColumns: ["category"],
86
+ },
87
+ );
88
+
89
+ await vectorStore.addDocuments([
90
+ new Document({
91
+ pageContent: "pgvector stores embeddings in Postgres.",
92
+ metadata: { category: "docs" },
93
+ }),
94
+ ]);
95
+
96
+ const results = await vectorStore.similaritySearch(
97
+ "How are embeddings stored?",
98
+ 4,
99
+ {
100
+ category: "docs",
101
+ },
102
+ );
103
+
104
+ await engine.close();
105
+ ```
106
+
107
+ > [!TIP]
108
+ > Since JavaScript has no sync/async split, the Python package's separate `PGVectorStore` /
109
+ > `AsyncPGVectorStore` classes are collapsed into a single, always-async `PGVectorStore` —
110
+ > every method here works the way any other LangChain.js vector store does
111
+ > (`similaritySearch`, `addDocuments`, `delete`, ...), no `a`-prefixed method names.
112
+
113
+ ### Metadata filters
114
+
115
+ `similaritySearch`, `similaritySearchWithScore`, `delete`, and `get` all accept a Mongo-style
116
+ filter object:
117
+
118
+ ```typescript
119
+ await vectorStore.similaritySearch("query", 4, {
120
+ $and: [{ category: "docs" }, { "author.age": { $gt: 30 } }],
121
+ });
122
+ ```
123
+
124
+ Supported operators: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$between`,
125
+ `$exists`, `$like`, `$ilike`, `$and`, `$or`, `$not`.
126
+
127
+ ### Hybrid Search with `PGVectorStore`
128
+
129
+ With `PGVectorStore` you can use hybrid (dense + sparse/full-text) search for more
130
+ comprehensive and relevant search results.
131
+
132
+ ```typescript
133
+ import {
134
+ HybridSearchConfig,
135
+ reciprocalRankFusion,
136
+ } from "@videoq-jp/langchainjs-postgres";
137
+
138
+ const vectorStore = await PGVectorStore.initialize(
139
+ engine,
140
+ embeddings,
141
+ "documents",
142
+ {
143
+ hybridSearchConfig: new HybridSearchConfig({
144
+ fusionFunction: reciprocalRankFusion,
145
+ }),
146
+ },
147
+ );
148
+
149
+ await vectorStore.applyHybridSearchIndex();
150
+ const hybridDocs = await vectorStore.similaritySearch("products", 5);
151
+ ```
152
+
153
+ ### Vector indexes
154
+
155
+ ```typescript
156
+ import { HNSWIndex } from "@videoq-jp/langchainjs-postgres";
157
+
158
+ await vectorStore.applyVectorIndex(
159
+ new HNSWIndex({ m: 16, efConstruction: 64 }),
160
+ );
161
+ ```
162
+
163
+ ### Database-side embeddings
164
+
165
+ Embedding providers can implement `embedQueryInlineTemplate(placeholder)` to compute
166
+ embeddings inside Postgres. It returns a trusted SQL expression using the supplied `$n`
167
+ placeholder; document and query text are passed separately as native `pg` parameters.
168
+ The query embedding expression is evaluated at most once per similarity search and reused
169
+ for ranking and scoring.
170
+ The SQL embedding function must already be available in your database. For example:
171
+
172
+ ```typescript
173
+ import type { PGVectorStoreEmbeddings } from "@videoq-jp/langchainjs-postgres";
174
+
175
+ const dbEmbeddings: PGVectorStoreEmbeddings = {
176
+ embedDocuments: (texts) => embeddings.embedDocuments(texts),
177
+ embedQuery: (text) => embeddings.embedQuery(text),
178
+ embedQueryInlineTemplate: (placeholder) =>
179
+ `embedding('model_id', ${placeholder})::vector`,
180
+ };
181
+
182
+ const store = await PGVectorStore.initialize(engine, dbEmbeddings, "documents");
183
+ ```
184
+
185
+ `addDocuments`, `addTexts`, and text similarity searches use the inline hook instead of
186
+ calling the provider's client embedding methods. Explicit, non-empty vectors are used as
187
+ provided. Maximal marginal relevance search still uses `embedQuery` for its client-side
188
+ reranking step, matching upstream.
189
+
190
+ The legacy `embedQueryInline(text)` hook is no longer called because interpolating raw text
191
+ into SQL can allow SQL injection. Initialization (including `fromTexts` and `fromDocuments`)
192
+ rejects providers that expose this hook without a callable `embedQueryInlineTemplate`.
193
+ Upgrade your embedding provider or implement the template hook as shown above, using the
194
+ supplied placeholder rather than quoting or interpolating document/query text. Providers
195
+ with both hooks use only the template hook; ordinary `embedDocuments`/`embedQuery` providers
196
+ continue to work. These camelCase hook names correspond to upstream's
197
+ `embed_query_inline_template` and `embed_query_inline` methods.
198
+
199
+ ### Legacy `PGVector`
200
+
201
+ For parity with the original `langchain_pg_collection` / `langchain_pg_embedding` schema:
202
+
203
+ ```typescript
204
+ import { PGVector } from "@videoq-jp/langchainjs-postgres";
205
+
206
+ const store = await PGVector.initialize(engine, embeddings, {
207
+ collectionName: "my-collection",
208
+ });
209
+ ```
210
+
211
+ Use `migratePgvectorCollection(engine, "my-collection", newStore)` to move data from a legacy
212
+ collection into a `PGVectorStore` table.
213
+
214
+ ## ChatMessageHistory
215
+
216
+ The chat message history abstraction helps persist chat message history in a Postgres table.
217
+
218
+ `PostgresChatMessageHistory` is parameterized using a `tableName` and a `sessionId`.
219
+
220
+ The `tableName` is the name of the table in the database where the chat messages will be
221
+ stored.
222
+
223
+ The `sessionId` is a unique identifier for the chat session. It can be assigned by the caller
224
+ using `crypto.randomUUID()`.
225
+
226
+ ```typescript
227
+ import { Pool } from "pg";
228
+ import { PostgresChatMessageHistory } from "@videoq-jp/langchainjs-postgres";
229
+
230
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
231
+
232
+ // Create the table schema (only needs to be done once)
233
+ await PostgresChatMessageHistory.createTables(pool, "chat_history");
234
+
235
+ const history = new PostgresChatMessageHistory({
236
+ tableName: "chat_history",
237
+ sessionId: crypto.randomUUID(),
238
+ pool,
239
+ });
240
+
241
+ await history.addUserMessage("Hello!");
242
+ console.log(await history.getMessages());
243
+ ```
244
+
245
+ ## What's included
246
+
247
+ | Export | Ported from (Python) | Purpose |
248
+ | ------------------------------------------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------- |
249
+ | `PGEngine` | `langchain_postgres.v2.engine.PGEngine` | Connection pool + table setup (`initVectorstoreTable`) |
250
+ | `PGVectorStore` | `langchain_postgres.v2.async_vectorstore.AsyncPGVectorStore` | Modern, per-table vector store (metadata filters, hybrid search, indexes) |
251
+ | `PostgresChatMessageHistory` | `langchain_postgres.chat_message_histories.PostgresChatMessageHistory` | Chat history backed by a simple `(session_id, message)` table |
252
+ | `PGVector` | `langchain_postgres.vectorstores.PGVector` | Legacy collection/embedding-table vector store |
253
+ | `PGVectorTranslator` | `langchain_postgres.translator.PGVectorTranslator` | Self-query retriever filter translator |
254
+ | `HNSWIndex`, `IVFFlatIndex`, `ExactNearestNeighbor`, ... | `langchain_postgres.v2.indexes` | Vector index management |
255
+ | `HybridSearchConfig`, `weightedSumRanking`, `reciprocalRankFusion` | `langchain_postgres.v2.hybrid_search_config` | Dense + sparse (full-text) hybrid search |
256
+ | `migratePgvectorCollection`, `listPgvectorCollectionNames` | `langchain_postgres.utils.pgvector_migrator` | Migrate data from the legacy `PGVector` schema to `PGVectorStore` |
257
+
258
+ ### Known gaps vs. upstream
259
+
260
+ - The self-query translator only supports the comparators `@langchain/core`'s structured-query
261
+ IR defines (`eq`/`ne`/`lt`/`gt`/`lte`/`gte`); Python's IR additionally has `in`/`nin`/`contain`/`like`.
262
+ - `migratePgvectorCollection` inserts batch-by-batch sequentially instead of with bounded
263
+ concurrency.
264
+
265
+ These (and any newly-introduced upstream behavior) are tracked via the upstream-sync workflow
266
+ described below.
267
+
268
+ ## Development
269
+
270
+ Use Node.js 24.11 or later in the 24.x line for development, matching the package build CI.
271
+ tsup 9 requires Node.js `^22.18.0 || ^24.11.0 || >=26.0.0` to build the package.
272
+
273
+ ```bash
274
+ npm install
275
+ npm run build # tsup -> dist/
276
+ npm test # vitest (unit tests against a mocked pg.Pool, no DB required)
277
+ npm run typecheck
278
+ npm run lint
279
+ npm run test:package # fresh npm pack install, ESM/CJS loading and strict TS 5.9/6 checks
280
+ ```
281
+
282
+ ### Integration tests
283
+
284
+ `tests/integration/` runs the same code paths against a real Postgres + pgvector instance
285
+ (no mocking). It requires `DATABASE_URL` and is not part of `npm test`:
286
+
287
+ ```bash
288
+ docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres pgvector/pgvector:pg17
289
+ DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres npm run test:integration
290
+ ```
291
+
292
+ CI runs this automatically against a `pgvector/pgvector:pg17` service container.
293
+
294
+ With `DATABASE_URL` set, `npm run test:package` also checks the installed tarball's vector
295
+ CRUD, search, filters, indexes, legacy UUID generation, and chat persistence. CI runs
296
+ these checks on Node.js 20.0.0 and the latest Node.js 20, 22, 24, and 26 releases. Build
297
+ tools run on Node.js 24; `PACKAGE_NODE_VERSION=20.0.0 npm run test:package` selects a
298
+ different runtime for the installed package. This command requires network access to
299
+ resolve fresh consumer dependencies and the requested Node.js runtime.
300
+
301
+ ## Automatic releases
302
+
303
+ After changes are squash-merged into `main` and CI passes, releases are automatic:
304
+ version selection, release PR creation and merging, changelog, GitHub Release, and npm
305
+ publication using Trusted Publishing. Use Conventional Commit PR titles (`fix:`, `feat:`,
306
+ `fix!:`, etc.); CI validates the format. See the [release policy](.github/releases.md)
307
+ for version rules, timing, and recovery.
308
+
309
+ ## Dependency update automation
310
+
311
+ Dependabot patch updates can auto-merge after every CI job passes. Failed updates
312
+ receive instructions for requesting a repair through Codex's GitHub integration
313
+ using your ChatGPT subscription; no OpenAI API key or always-on PC is needed.
314
+ See the [setup guide](.github/dependency-automation.md) for enabling auto-merge and
315
+ connecting Codex. A person starts each repair by commenting on the PR.
316
+
317
+ ## Staying in sync with upstream
318
+
319
+ This package tracks [`langchain-ai/langchain-postgres`](https://github.com/langchain-ai/langchain-postgres)
320
+ (Python) as a git submodule at [`upstream/langchain-postgres`](upstream/langchain-postgres),
321
+ pinned to the commit this port was last synced against. Since porting Python to TypeScript
322
+ can't be automated, a daily [GitHub Actions workflow](.github/workflows/upstream-sync.yml)
323
+ compares the pinned commit against upstream's latest commit and, when
324
+ `langchain_postgres/` has changed, opens (or refreshes) a tracking issue labeled `upstream`
325
+ summarizing what moved. You can also run the check manually:
326
+
327
+ ```bash
328
+ git submodule update --init --recursive
329
+ npm run diff:upstream
330
+ ```
331
+
332
+ ## Package scope migration
333
+
334
+ The package name is now `@videoq-jp/langchainjs-postgres`. Replace previous `@yukiharada1228/langchain-postgres` dependencies and imports with the new name. The source remains in `videoq-jp/langchainjs-postgres`.