@videoq-jp/langchainjs-postgres
v0.3.3
Published
Unofficial LangChain.js port of langchain-postgres (Postgres/pgvector integrations for LangChain).
Maintainers
Readme
langchainjs-postgres
The @videoq-jp/langchainjs-postgres package implements core LangChain abstractions using Postgres.
It is an unofficial TypeScript port of
langchain-postgres for LangChain.js.
It is not affiliated with or endorsed by LangChain. For the official LangChain.js
Postgres integration, see @langchain/community.
The package is released under the MIT license.
Feel free to use the abstraction as provided or else modify them / extend them as appropriate for your own application.
Requirements
The package supports the pg (node-postgres) driver,
Node.js >=20 and Postgres with pgvector.
initVectorstoreTable runs CREATE EXTENSION IF NOT EXISTS vector automatically.
Python’s asyncpg and psycopg3 drivers are replaced by pg in this port.
Installation
npm install @videoq-jp/langchainjs-postgres @langchain/core pg [email protected]ESM and CommonJS are supported with TypeScript declarations. Use NodeNext for
strict dependency checking. LangSmith 0.10.10/0.10.11 have incomplete declarations;
the command above selects 0.10.9. Node16 dependency checks require skipLibCheck.
See installation compatibility and pnpm/yarn commands.
Vectorstore
[!WARNING] In the Python package v0.0.14+,
PGVectoris deprecated. Please migrate toPGVectorStorefor improved performance and manageability. This port retains the legacy schema; usemigratePgvectorCollectionto migrate in TypeScript. See the upstream Python migration guide for details on how to migrate fromPGVectortoPGVectorStore.
Documentation
- Quickstart — TypeScript example below
- Python quickstart
- How-to — TypeScript filters, indexes and database-side embeddings
- Python how-to
[!TIP] For developing, debugging, and deploying AI agents and LLM applications, see LangSmith.
Example
import { Document } from "@langchain/core/documents";
import { SyntheticEmbeddings } from "@langchain/core/utils/testing";
import { PGEngine, PGVectorStore } from "@videoq-jp/langchainjs-postgres";
// Replace the connection string with your own Postgres connection string.
const CONNECTION_STRING =
"postgresql://langchain:langchain@localhost:6024/langchain";
const engine = PGEngine.fromConnectionString(CONNECTION_STRING);
// Replace the synthetic test embeddings with your own embedding service.
const VECTOR_SIZE = 768;
const embedding = new SyntheticEmbeddings({ vectorSize: VECTOR_SIZE });
const TABLE_NAME = "my_doc_collection";
await engine.initVectorstoreTable(TABLE_NAME, VECTOR_SIZE);
const store = await PGVectorStore.initialize(engine, embedding, TABLE_NAME);
const docs = [
new Document({ pageContent: "Apples and oranges" }),
new Document({ pageContent: "Cars and airplanes" }),
new Document({ pageContent: "Train" }),
];
await store.addDocuments(docs);
const query = "I'd like a fruit.";
const results = await store.similaritySearch(query);
console.log(results);
await engine.close();[!TIP] All methods in this TypeScript port are asynchronous. Python’s separate
PGVectorStore/AsyncPGVectorStoreclasses are represented by one Promise-basedPGVectorStore, withouta-prefixed method names.
Hybrid Search with PGVectorStore
With PGVectorStore you can use hybrid search for more comprehensive and relevant search results.
import {
HybridSearchConfig,
reciprocalRankFusion,
} from "@videoq-jp/langchainjs-postgres";
// Use the same engine, embedding and TABLE_NAME as in the example above,
// before closing the engine.
const vectorStore = await PGVectorStore.initialize(
engine,
embedding,
TABLE_NAME,
{
hybridSearchConfig: new HybridSearchConfig({
fusionFunction: reciprocalRankFusion,
}),
},
);
await vectorStore.applyHybridSearchIndex();
const hybridDocs = await vectorStore.similaritySearch("products", 5);For a detailed guide on how to use hybrid search, see the TypeScript guide and upstream Python documentation.
ChatMessageHistory
The chat message history abstraction helps to persist chat message history in a postgres table.
PostgresChatMessageHistory is parameterized using a tableName and a sessionId.
The tableName is the name of the table in the database where
the chat messages will be stored.
The sessionId is a unique identifier for the chat session. It can be assigned
by the caller using crypto.randomUUID().
import {
SystemMessage,
AIMessage,
HumanMessage,
} from "@langchain/core/messages";
import { PostgresChatMessageHistory } from "@videoq-jp/langchainjs-postgres";
import { Pool } from "pg";
// Fill in your Postgres connection string.
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
// Create the table schema (only needs to be done once).
const tableName = "chat_history";
await PostgresChatMessageHistory.createTables(pool, tableName);
const sessionId = crypto.randomUUID();
const chatHistory = new PostgresChatMessageHistory({
tableName,
sessionId,
pool,
});
await chatHistory.addMessages([
new SystemMessage("Meow"),
new AIMessage("woof"),
new HumanMessage("bark"),
]);
console.log(await chatHistory.getMessages());
await pool.end();Google Cloud Integrations
The following is upstream guidance for Python packages; these are separate projects, not integrations bundled into this TypeScript package.
Google Cloud provides Vector Store, Chat Message History, and Data Loader integrations for AlloyDB and Cloud SQL for PostgreSQL databases via the following PyPi packages:
Using the Google Cloud integrations provides the following benefits:
- Enhanced Security: Securely connect to Google Cloud databases utilizing IAM for authorization and database authentication without needing to manage SSL certificates, configure firewall rules, or enable authorized networks.
- Simplified and Secure Connections: Connect to Google Cloud databases effortlessly using the instance name instead of complex connection strings. The integrations creates a secure connection pool that can be easily shared across your application using the
engineobject.
| Vector Store | Metadata filtering | Async support | Schema Flexibility | Improved metadata handling | Hybrid Search | | ------------------------- | ------------------ | ------------- | ------------------ | -------------------------- | ------------- | | Google AlloyDB | ✓ | ✓ | ✓ | ✓ | ✗ | | Google Cloud SQL Postgres | ✓ | ✓ | ✓ | ✓ | ✗ |
TypeScript port notes
The TypeScript guide preserves advanced usage, including metadata filters, vector indexes, database-side embeddings and the SQL parameter safety requirements, legacy migration, the complete export map and known gaps. The translator supports only the comparators in LangChain.js’s structured-query IR, and migration batches run sequentially; see known gaps.
See development and integration tests,
automatic releases,
dependency automation and
upstream sync and Python release baseline.
npm uses independent SemVer; the 0.3.2 reference is Python 0.0.19 at
4b72d765c6d663f30db9823f7caac148adac0d58. npm releases use OIDC Trusted Publishing.
The package is now @videoq-jp/langchainjs-postgres; replace previous
@yukiharada1228/langchain-postgres dependencies and imports with this name.
