Skip to main content

langchain-azure-cosmosdb

Azure CosmosDB NoSQL integrations for LangChain and LangGraph.

Installation

pip install langchain-azure-cosmosdb

Integrations

Integration Sync Async Description
Vector Store AzureCosmosDBNoSqlVectorSearch AsyncAzureCosmosDBNoSqlVectorSearch Vector, full-text, hybrid, and weighted hybrid search
Vector Store (MongoDB compatibility) AzureDocumentDBVectorSearch N/A Vector search for Azure DocumentDB clusters with MongoDB compatibility
Semantic Cache AzureCosmosDBNoSqlSemanticCache AsyncAzureCosmosDBNoSqlSemanticCache LLM response caching backed by CosmosDB
Chat History CosmosDBChatMessageHistory AsyncCosmosDBChatMessageHistory Persistent chat message history
LangGraph Checkpointer CosmosDBSaverSync CosmosDBSaver LangGraph graph state persistence
LangGraph Cache CosmosDBCacheSync CosmosDBCache LangGraph node-level result caching
LangGraph Store CosmosDBStore AsyncCosmosDBStore LangGraph long-term memory with optional vector search

Usage

Vector Store

Before configuring the policies in this example, review the Azure Cosmos DB vector search documentation and the workload-specific vector index selection guidance to choose policies for your workload.

from azure.cosmos import CosmosClient, PartitionKey
from langchain_azure_cosmosdb import AzureCosmosDBNoSqlVectorSearch

cosmos_client = CosmosClient("<endpoint>", "<key>")
request_charges = []

vectorstore = AzureCosmosDBNoSqlVectorSearch(
    cosmos_client=cosmos_client,
    embedding=embedding,
    vector_embedding_policy={
        "vectorEmbeddings": [
            {
                "path": "/embedding",
                "dataType": "float32",
                "distanceFunction": "cosine",
                "dimensions": 1536,
            }
        ]
    },
    indexing_policy={
        "indexingMode": "consistent",
        "includedPaths": [{"path": "/*"}],
        "excludedPaths": [{"path": '/"_etag"/?'}],
        "vectorIndexes": [{"path": "/embedding", "type": "diskANN"}],
    },
    cosmos_container_properties={"partition_key": PartitionKey(path="/id")},
    cosmos_database_properties={"id": "my-database"},
    vector_search_fields={"text_field": "text", "embedding_field": "embedding"},
    database_name="my-database",
    container_name="my-container",
    request_charge_callback=request_charges.append,
)

# Add documents
vectorstore.add_texts(["Azure CosmosDB is a multi-model database."])

# Search
results = vectorstore.similarity_search("What is CosmosDB?", k=3)
if request_charges:
    print(request_charges[-1].request_charge)

The optional request_charge_callback receives one CosmosDBRequestCharge after each successful logical query. Its request_charge is the sum of all Cosmos DB query pages and request_count is the number of page requests that reported a charge. The same callback contract applies to the async vector store. Insert, delete, point-read, and batch charges are not currently reported.

Vector Store (Azure DocumentDB with MongoDB compatibility)

from pymongo import MongoClient
from langchain_azure_cosmosdb import AzureDocumentDBVectorSearch

mongo_client = MongoClient("<connection-string>")
collection = mongo_client["my-database"]["my-collection"]

vectorstore = AzureDocumentDBVectorSearch(
    collection=collection,
    embedding=embedding,
    index_name="vectorSearchIndex",
)

vectorstore.add_texts(["Azure DocumentDB supports MongoDB-compatible vector search."])
results = vectorstore.similarity_search("What does DocumentDB support?", k=3)

Semantic Cache

from azure.cosmos import CosmosClient, PartitionKey
from langchain_core.globals import set_llm_cache
from langchain_azure_cosmosdb import AzureCosmosDBNoSqlSemanticCache

cosmos_client = CosmosClient("<endpoint>", "<key>")

cache = AzureCosmosDBNoSqlSemanticCache(
    cosmos_client=cosmos_client,
    embedding=embedding,
    vector_embedding_policy=vector_embedding_policy,
    indexing_policy=indexing_policy,
    cosmos_container_properties={"partition_key": PartitionKey(path="/id")},
    cosmos_database_properties={"id": "cache-db"},
    vector_search_fields={"text_field": "text", "embedding_field": "embedding"},
    database_name="cache-db",
    container_name="cache-container",
)

set_llm_cache(cache)

# First call hits LLM, second call returns cached result
response = llm.invoke("What is CosmosDB?")

Chat Message History

from langchain_azure_cosmosdb import CosmosDBChatMessageHistory

history = CosmosDBChatMessageHistory(
    cosmos_endpoint="<endpoint>",
    credential="<key>",  # or a TokenCredential for AAD
    cosmos_database="chat-db",
    cosmos_container="chat-container",
    session_id="session-001",
    user_id="user-alice",
    ttl=3600,  # optional: messages expire after 1 hour
)
history.prepare_cosmos()

history.add_user_message("Hello!")
history.add_ai_message("Hi there!")
print(history.messages)

LangGraph Checkpointer

Sync

from langchain_azure_cosmosdb import CosmosDBSaverSync

# Sync — uses COSMOSDB_ENDPOINT / COSMOSDB_KEY env vars or explicit params
checkpointer = CosmosDBSaverSync(
    database_name="langgraph-db",
    container_name="checkpoints",
    endpoint="<endpoint>",
    key="<key>",
)

graph = workflow.compile(checkpointer=checkpointer)
result = graph.invoke(input, config={"configurable": {"thread_id": "1"}})

Async

from langchain_azure_cosmosdb import CosmosDBSaver

# Async — use as a context manager
async with CosmosDBSaver.from_conn_info(
    endpoint="<endpoint>",
    key="<key>",
    database_name="langgraph-db",
    container_name="checkpoints",
) as checkpointer:
    graph = workflow.compile(checkpointer=checkpointer)
    result = await graph.ainvoke(input, config={"configurable": {"thread_id": "1"}})

LangGraph Cache

Sync

from langchain_azure_cosmosdb import CosmosDBCacheSync

cache = CosmosDBCacheSync(
    database_name="langgraph-db",
    container_name="cache",
    endpoint="<endpoint>",
    key="<key>",
)

graph = workflow.compile(cache=cache)

Async

from langchain_azure_cosmosdb import CosmosDBCache

async with CosmosDBCache.from_conn_info(
    endpoint="<endpoint>",
    key="<key>",
    database_name="langgraph-db",
    container_name="cache",
) as cache:
    graph = workflow.compile(cache=cache)
    result = await graph.ainvoke(input, config={"configurable": {"thread_id": "1"}})

LangGraph Store (Long-Term Memory)

Sync

from langchain_azure_cosmosdb import CosmosDBStore

store = CosmosDBStore.from_endpoint(
    endpoint="<endpoint>",
    credential="<key>",
    database_name="langgraph-db",
    container_name="store",
    index={
        "dims": 1536,
        "embed": embedding,
        "fields": ["text"],
    },
)
store.setup()

# Store items under namespaces
store.put(("users", "alice", "preferences"), "coffee", {"text": "Dark roast"})
item = store.get(("users", "alice", "preferences"), "coffee")

# Semantic search
results = store.search(("users",), query="beverage preferences", limit=3)

Async

from langchain_azure_cosmosdb import AsyncCosmosDBStore

async with AsyncCosmosDBStore.from_endpoint(
    endpoint="<endpoint>",
    credential="<key>",
    database_name="langgraph-db",
    container_name="store",
    index={
        "dims": 1536,
        "embed": embedding,
        "fields": ["text"],
    },
) as store:
    await store.setup()

    await store.aput(
        ("users", "alice", "preferences"), "coffee", {"text": "Dark roast"}
    )
    item = await store.aget(("users", "alice", "preferences"), "coffee")

    results = await store.asearch(("users",), query="beverage preferences", limit=3)

Authentication

All integrations support both access key and Microsoft Entra ID (AAD / Managed Identity) authentication:

# Access key
from azure.cosmos import CosmosClient

client = CosmosClient("<endpoint>", "<key>")

# AAD / Managed Identity
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential

client = CosmosClient("<endpoint>", credential=DefaultAzureCredential())

The LangGraph integrations that manage their own client — CosmosDBSaverSync / CosmosDBSaver, CosmosDBCacheSync / CosmosDBCache, and CosmosDBStore / AsyncCosmosDBStore — fall back to DefaultAzureCredential automatically when no key is provided. The semantic cache (AzureCosmosDBNoSqlSemanticCache) and vectorstore require you to pass a CosmosClient explicitly.

Samples

See the samples/cosmosdb-nosql/ directory for runnable end-to-end examples of every integration.

Host a persistent LangGraph agent on Azure

Start with the async checkpointer example for per-thread graph state, or the async store example for long-term memory. Hosting with ResponsesHostServer or InvocationsHostServer requires the async CosmosDBSaver for Cosmos DB checkpoints: both hosts use async graph calls, which are not supported by CosmosDBSaverSync.

Compile your graph with checkpointer=checkpointer (and store=store if needed), then await ResponsesHostServer(graph).run_async() or InvocationsHostServer(graph).run_async() inside the async context manager scope. Keep database clients and async context managers open for the host's lifetime. Follow the LangGraph hosting guide for deployment, and ensure the deployed agent can authenticate to Cosmos DB as well as its Foundry project.

Alternatively, Foundry-hosted agents using container protocol 2.0.0 can persist graph checkpoints with FoundryCheckpointSaver backed by Foundry State Store, without a Cosmos DB checkpointer. The same saver uses local files during local development; see its linked guide for the state directory and restart requirements.

Changelog

1.1.0

  • We introduced bulk delta-channel history loading for synchronous and asynchronous LangGraph checkpointers, replacing per-ancestor reads with two bulk queries while preserving history reconstruction behavior. [NEW] #840
  • We raised the minimum supported dependency versions to langgraph-checkpoint>=4.1.0,<5.0.0, langgraph>=1.0.0, langchain-core>=1.3.3,<2.0, azure-identity>=1.15.0, and numpy>=1.26.2. Existing environments must upgrade these dependencies to install this release. #840 #1316
  • We removed the precautionary NumPy upper bound to allow newer compatible releases. #1222

1.0.1

We raised the minimum supported Python version from 3.10 to 3.11 in accordance with the repository's Python support policy. Users running Python 3.10 must upgrade their runtime to install this release. #1021

  • We introduced the AzureDocumentDBVectorSearch integration and compatibility aliases for MongoDB-compatible vector search, including a fix for the deprecated import path. [NEW] #870 #871
  • We added optional request-charge callbacks for synchronous and asynchronous vector queries. [NEW] #876
  • We fixed DocumentDB vector search handling for single-pass iterables and ensured caller-provided oversampling is forwarded to vector queries. #1028

1.0.0

Initial release of langchain-azure-cosmosdb — a standalone package consolidating all Azure CosmosDB NoSQL integrations for LangChain and LangGraph.

LangChain Integrations:

  • AzureCosmosDBNoSqlVectorSearch / AsyncAzureCosmosDBNoSqlVectorSearch — Vector, full-text, hybrid, and weighted hybrid search
  • AzureCosmosDBNoSqlSemanticCache / AsyncAzureCosmosDBNoSqlSemanticCache — LLM semantic response caching
  • CosmosDBChatMessageHistory / AsyncCosmosDBChatMessageHistory — Persistent chat message history with TTL support

LangGraph Integrations:

  • CosmosDBSaverSync / CosmosDBSaver — Graph state checkpointing
  • CosmosDBCacheSync / CosmosDBCache — Node-level result caching
  • CosmosDBStore / AsyncCosmosDBStore — Long-term memory store with optional vector search

Highlights:

  • Full sync and async support for all integrations
  • Microsoft Entra ID (AAD / Managed Identity) authentication across all integrations
  • User agent tracking for all CosmosDB client instances

Metadata

Release files for langchain-azure-cosmosdb 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-azure-cosmosdb 1.1.0
File Size Uploaded Provenance Actions
langchain_azure_cosmosdb-1.1.0.tar.gz 72.1 kB Without provenance Details for langchain_azure_cosmosdb-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for langchain-azure-cosmosdb 1.1.0
File Interpreter ABI Platform Actions
langchain_azure_cosmosdb-1.1.0-py3-none-any.whl Python 3 none any Details for langchain_azure_cosmosdb-1.1.0-py3-none-any.whl

Total release size: 155.0 kB

Release files / langchain_azure_cosmosdb-1.1.0.tar.gz

Download URL langchain_azure_cosmosdb-1.1.0.tar.gz
Size 72.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0f7414e7c5fd954abc40bd07640cb942d970589f43fde90dfc8b022e75fabfc5
BLAKE2b-256 checksum
How to use checksums
56b5afb11134f1582b0993015c349514f567ab8a0d4b870c6295f304436d97dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / langchain_azure_cosmosdb-1.1.0-py3-none-any.whl

Download URL langchain_azure_cosmosdb-1.1.0-py3-none-any.whl
Size 82.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ad464c7c9f611cdc2b960d21cc2c2551144f1123375de7f00ee7422eb5341c7b
BLAKE2b-256 checksum
How to use checksums
21b4f74f669ee9906443e3a93aa2b7abd34df6dbb67e7dcc5edd01c2e1087d18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Security for langchain-azure-cosmosdb 1.1.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page