LangChain PostgreSQL Integration

0.0.17 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →