CockroachDBChatMessageHistory stores chat conversation history in CockroachDB’s distributed SQL database.
The code lives in the integration package: langchain-cockroachdb.
Overview
CockroachDBChatMessageHistory provides:
- Distributed storage: Chat history automatically replicated across nodes
- Strong consistency: SERIALIZABLE transactions prevent message ordering issues
- High availability: Automatic failover with no data loss
- Session isolation: Each conversation has a unique session ID
- PostgreSQL compatibility: Easy migration from PostgreSQL-based systems
Setup
Install
pip install -qU langchain-cockroachdb
Connection string
# CockroachDB Cloud
CONNECTION_STRING = "cockroachdb://user:password@host:26257/database?sslmode=verify-full"
# Local insecure cluster
CONNECTION_STRING = "cockroachdb://root@localhost:26257/defaultdb?sslmode=disable"
Initialization
Create the message history table
import asyncio
from langchain_cockroachdb import CockroachDBChatMessageHistory
# Create table (only needs to be done once)
async def setup():
chat_history = CockroachDBChatMessageHistory(
session_id="setup",
connection_string=CONNECTION_STRING,
table_name="chat_history",
)
await chat_history._acreate_table_if_not_exists()
asyncio.run(setup())
Optional: Specify a schema name by using schema parameter (default: “public”)
Initialize for a session
Create a chat history instance for a specific conversation:
import uuid
session_id = str(uuid.uuid4()) # Unique ID for this conversation
chat_history = CockroachDBChatMessageHistory(
session_id=session_id,
connection_string=CONNECTION_STRING,
table_name="chat_history",
)
Usage
Add messages
from langchain.messages import HumanMessage, AIMessage
# Add messages to the conversation
await chat_history.aadd_message(HumanMessage(content="Hello! What is CockroachDB?"))
await chat_history.aadd_message(AIMessage(content="CockroachDB is a distributed SQL database..."))
Add multiple messages at once
messages = [
HumanMessage(content="What are vector indexes?"),
AIMessage(content="Vector indexes enable fast similarity search..."),
HumanMessage(content="How do they work?"),
AIMessage(content="They use approximate nearest neighbor algorithms..."),
]
await chat_history.aadd_messages(messages)
Retrieve messages
Get all messages for the session:
messages = await chat_history.aget_messages()
for msg in messages:
if isinstance(msg, HumanMessage):
print(f"User: {msg.content}")
elif isinstance(msg, AIMessage):
print(f"AI: {msg.content}")
Clear conversation history
Delete all messages for the session:
await chat_history.aclear()
Sync interface
Use the synchronous API:
# Sync usage
chat_history_sync = CockroachDBChatMessageHistory(
session_id=session_id,
connection_string=CONNECTION_STRING,
table_name="chat_history",
)
# Sync operations
chat_history_sync.add_message(HumanMessage(content="Hello!"))
messages = chat_history_sync.messages
chat_history_sync.clear()
API reference
For detailed documentation:
Additional resources