langchain-polardb-pg
LangChain integration for Alibaba Cloud PolarDB for PostgreSQL — providing in-database embeddings, vector store, and model management powered by the polar_ai extension.
Features
- In-Database Embeddings — compute text embeddings directly inside PolarDB, eliminating external API calls and network round-trips.
- Dual Embedding Modes — automatically selects the optimal path based on your cluster edition:
ai_text_embeddingmode (Standard edition): inline embedding in a single SQL statementcall_modelmode (Enterprise edition + AI node): embedding viaai_callmodel
- Vector Store — full-featured similarity search, MMR, filtering, built on community
langchain-postgres. - Model Management — register, configure, and manage AI models through Python APIs.
- Auto-Discovery —
from_instance()resolves cluster endpoints and capabilities via Alibaba Cloud OpenAPI.
Installation
pip install langchain-polardb-pg
With cloud auto-discovery support (recommended):
pip install langchain-polardb-pg[cloud]
Quick Start
from langchain_polardb_pg import PolarDBPGEngine, PolarDBPGEmbeddings, PolarDBPGVector
# 1. Connect to your PolarDB instance
engine = PolarDBPGEngine.from_instance(
cluster_id="pc-xxxxx",
database="mydb",
user="user",
password="password",
access_key_id="your-ak",
access_key_secret="your-sk",
)
# 2. Create in-database embeddings (no external API needed!)
embeddings = PolarDBPGEmbeddings.create_sync(engine)
# 3. Initialize vector store table
vector_size = len(embeddings.embed_query("dimension probe"))
engine.init_vectorstore_table("my_docs", vector_size=vector_size)
# 4. Create vector store
store = PolarDBPGVector.create_sync(engine, embeddings, table_name="my_docs")
# 5. Add documents & search
store.add_texts(["PolarDB is a cloud-native database", "LangChain is an AI framework"])
results = store.similarity_search("cloud database", k=2)
Embedding Modes
| Mode | Edition | How it works | Vector Dim |
|---|---|---|---|
ai_text_embedding |
Standard (Beijing) | Inline SQL — embedding computed inside INSERT/SELECT | 1536 |
call_model |
Enterprise + AI Node | Two-step — ai_callmodel then INSERT/SELECT |
1024 |
The mode is auto-resolved from your cluster attributes. You can also specify it explicitly:
from langchain_polardb_pg.embeddings import EmbeddingMode
embeddings = PolarDBPGEmbeddings.create_sync(engine, mode=EmbeddingMode.AI_TEXT_EMBEDDING)
Components
PolarDBPGEngine
Extends the community PGEngine with:
from_instance()— auto-discover endpoints via Alibaba Cloud OpenAPIcluster_attribute— cached cluster metadata (region, edition, AI capabilities)get_ai_api_key()— unified AI key retrieval (from cluster or environment)
PolarDBPGEmbeddings
Implements LangChain Embeddings interface:
embed_query(text)/embed_documents(texts)— standard embedding APIsembed_query_inline(text)— returns a SQL expression for inline embedding (ai_text_embedding mode only)
PolarDBPGVector
Inherits all capabilities from community PGVectorStore:
add_documents()/add_texts()— with in-database embeddingsimilarity_search()/similarity_search_with_score()max_marginal_relevance_search()— diversity-aware retrievaldelete()— by IDs or metadata filter
PolarDBPGModelManager
Model lifecycle management:
create_model()/alter_model()/drop_model()set_model_token()/call_model()list_models()/get_model()
Connection Methods
# Method 1: Auto-discovery (recommended)
engine = PolarDBPGEngine.from_instance(
cluster_id="pc-xxxxx",
database="mydb", user="user", password="pass",
access_key_id="ak", access_key_secret="sk",
)
# Method 2: Direct connection string
engine = PolarDBPGEngine.from_connection_string(
"postgresql+asyncpg://user:pass@host:5432/mydb"
)
# Method 3: From existing SQLAlchemy engine
engine = PolarDBPGEngine.from_engine(existing_async_engine)
Environment Variables
from_instance() can read Alibaba Cloud credentials from environment
variables when they are not passed explicitly:
export ALIBABA_CLOUD_ACCESS_KEY_ID="your-ak"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-sk"
export POLARDB_REGION="cn-hangzhou" # optional
The integration tests and examples use these variables:
export POLARDB_CLUSTER_ID="pc-xxxxx"
export POLARDB_DATABASE="ai_test"
export POLARDB_USER="your_user"
export POLARDB_PASSWORD="your_password"
export POLARDB_NETWORK_TYPE="Public" # or "Private"
export ALIBABA_CLOUD_ACCESS_KEY_ID="your-ak"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-sk"
export DASHSCOPE_API_KEY="your-dashscope-key" # optional for ai_text_embedding mode
Requirements
- Python >= 3.9
- PolarDB for PostgreSQL with the
polar_aiextension - A reachable PolarDB endpoint for the selected network type (
PublicorPrivate) - Alibaba Cloud OpenAPI credentials when using
from_instance()auto-discovery - Dependencies:
langchain-postgres,langchain-core,sqlalchemy[asyncio],asyncpg
Development
Install local development dependencies:
python -m pip install -U pip
python -m pip install -e ".[dev,cloud]"
Run unit tests:
make test
Run LangChain standard vector store integration tests with a live PolarDB instance:
make integration-test
Build and validate distribution metadata:
make build
make check-dist
License
Release files for langchain-polardb-pg 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| langchain_polardb_pg-0.1.1.tar.gz | 31.5 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| langchain_polardb_pg-0.1.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 66.7 kB
Release files / langchain_polardb_pg-0.1.1.tar.gz
| Download URL | langchain_polardb_pg-0.1.1.tar.gz |
|---|---|
| Size | 31.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
af34b30b468a0d2bc5e0713d78773c5c3231d383408ed7fa0ae0e14a1a81b2f8
|
|
BLAKE2b-256 checksum How to use checksums |
a903935b59133f3edef299b72b21b55ed7832f48f34f1752b3e5bb86856fad79
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 13, 2026.
Transparency logRelease files / langchain_polardb_pg-0.1.1-py3-none-any.whl
| Download URL | langchain_polardb_pg-0.1.1-py3-none-any.whl |
|---|---|
| Size | 35.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7654f8bcaeb3bdddcb43a58bd379c664f9463b6f2ffdfbabf1f3171e5b695d6e
|
|
BLAKE2b-256 checksum How to use checksums |
a083747d5308ef8f34710405cd24bfaab6795c87f02fe71272194528e07f9887
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 13, 2026.
Transparency log