Registry / llm-agents / langchain-postgres

langchain-postgres

JSON →
library0.0.17pypypi✓ verified 22d ago

langchain-postgres is an integration package that connects LangChain abstractions with PostgreSQL, leveraging its robust features for vector stores, chat message history, and LangGraph checkpoint saving. It is currently at version 0.0.17 and receives regular updates. The package supports asyncpg and psycopg3 drivers, enabling efficient and scalable interactions with PostgreSQL databases.

pip install -U langchain-postgres
INSTALL
IMPORT
SIG · LANGCHAIN-POSTGRES
L
langchain-postgres
llm-agentspythonv0.0.17
Install
12.0s avg
Import
3214ms
Disk
199MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.0.17 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 3.340s · 191.9MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 12.0s · import 3.088s · 199MB
199MB installed
● package 199MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PGEngine
from langchain_postgres import PGEngine
PGVectorStore
from langchain_postgres import PGVectorStore
PostgresChatMessageHistory
from langchain_postgres.chat_message_histories import PostgresChatMessageHistory
PostgresSaver
from langgraph.checkpoint.postgres import PostgresSaver
from langchain_postgres import PostgresSaver
PostgresSaver for LangGraph checkpoints is located in `langgraph.checkpoint.postgres`, not directly in `langchain_postgres`.
PGVector
from langchain_postgres.vectorstores import PGVector
from langchain_postgres import PGVector
As of v0.0.14+, `PGVector` is deprecated. Migrate to `PGVectorStore` for improved performance and manageability.

This quickstart demonstrates how to set up `PGEngine` for connecting to PostgreSQL, initialize a `PGVectorStore` for document embedding and similarity search, and use `PostgresChatMessageHistory` for persisting chat messages. It uses `DeterministicFakeEmbedding` for demonstration purposes; in a real application, you would replace this with an actual embedding model. Remember to set your `POSTGRES_CONNECTION_STRING` environment variable.

import os from langchain_core.documents import Document from langchain_core.embeddings import DeterministicFakeEmbedding from langchain_postgres import PGEngine, PGVectorStore # Replace with your PostgreSQL connection string CONNECTION_STRING = os.environ.get('POSTGRES_CONNECTION_STRING', 'postgresql+psycopg://langchain:langchain@localhost:6024/langchain') # Initialize PGEngine engine = PGEngine.from_connection_string(url=CONNECTION_STRING) # Define vector size and embedding service VECTOR_SIZE = 768 # Adjust based on your embedding model embedding = DeterministicFakeEmbedding(size=VECTOR_SIZE) TABLE_NAME = "my_doc_collection" # Initialize the vector store table (if it doesn't exist) engine.init_vectorstore_table( table_name=TABLE_NAME, vector_size=VECTOR_SIZE, ) # Create a synchronous PGVectorStore instance store = PGVectorStore.create_sync( engine=engine, table_name=TABLE_NAME, embedding_service=embedding, ) # Add documents docs = [ Document(page_content="Apples and oranges"), Document(page_content="Cars and airplanes"), Document(page_content="Dogs and cats"), ] store.add_documents(docs) # Perform a similarity search query = "fruits" results = store.similarity_search(query, k=1) print(f"Similarity search for '{query}': {results[0].page_content}") # Example for Chat Message History from langchain_postgres.chat_message_histories import PostgresChatMessageHistory import uuid session_id = str(uuid.uuid4()) chat_history = PostgresChatMessageHistory(session_id=session_id, table_name="chat_messages", connection=engine.get_connection()) chat_history.add_user_message("Hello LangChain Postgres!") chat_history.add_ai_message("Hi there!") print(f"Chat history for session {session_id}: {chat_history.messages}")
Debug
Known issues
breakingIn versions 0.0.14 and higher, the `PGVector` class has been deprecated. Users should migrate to `PGVectorStore` for improved performance and manageability.
fix
Replace `PGVector` imports and instantiations with `PGVectorStore`. Refer to the official migration guide for detailed steps.
affects: >=0.0.14
gotchaWhen using `PostgresSaver` (from `langgraph.checkpoint.postgres`) with manually created PostgreSQL connections, it is crucial to include `autocommit=True` and `row_factory=dict_row` in the connection parameters. Failure to do so can lead to `TypeError` exceptions due to incorrect row access (tuple vs. dictionary) and unpersisted table creations after `.setup()` calls.
fix
Ensure your connection string or connection object creation includes `autocommit=True` and `row_factory=dict_row` (e.g., `from psycopg.rows import dict_row`). For production, consider `ConnectionPool` from `psycopg_pool` to manage connections.
affects: All
breakingThe connection string format has changed for `langchain-postgres` to explicitly work with `psycopg3`. Update connection strings from `postgresql+psycopg2://...` to `postgresql+psycopg://...`.
fix
Modify your PostgreSQL connection strings to use `postgresql+psycopg://` as the scheme instead of `postgresql+psycopg2://`.
affects: All
gotchaFor `PostgresSaver`, when the database is first used, the `.setup()` method must be called to create the required tables. Operations will fail if tables are not initialized.
fix
Always call `checkpointer.setup()` on your `PostgresSaver` instance when setting it up for the first time or when ensuring table existence.
affects: All
gotchaLangChain applications, especially those using checkpoints in production deployments, can suffer from 'too many clients already' errors if the PostgreSQL connection limit is exceeded. This is often due to a high number of runs, large checkpoint sizes, or unmanaged connection pools.
fix
Optimize connection pool settings (e.g., `ASYNCPG_POOL_MAX_SIZE`, `ASYNCPG_POOL_MIN_SIZE`), increase PostgreSQL `max_connections`, implement connection retry logic, and consider using a connection pooler like PgBouncer.
affects: All
Upgrade
Version history
0.0.17latest on PyPI · released Feb 17, 2026
Audit
Dependencies
langchain-corerequiredCore LangChain abstractions are utilized by this integration package.
psycopgoptionalDefault PostgreSQL driver (Psycopg 3) for synchronous operations.
asyncpgoptionalAsynchronous PostgreSQL driver.
sqlalchemyrequiredUsed for database abstraction and connection management.
psycopg-pooloptionalConnection pooling for psycopg.
pgvectorrequiredPostgreSQL extension for vector similarity search, integral to PGVectorStore.
numpyrequiredNumerical operations, potentially for embedding handling.
Agent activity
57 hits · last 30 days
node
50
OpenAI (training)
1
Resources