Skip to main content
Open In ColabOpen on GitHub

Cassandra

Apache Cassandra® is a NoSQL, row-oriented, highly scalable and highly available database, well suited for storing large amounts of data.

Cassandra is a good choice for storing chat message history because it is easy to scale and can handle a large number of writes.

本笔记本介绍了如何使用 Cassandra 存储聊天消息历史记录。

设置

要运行此笔记本,您需要一个正在运行的 Cassandra 集群,或者在云端运行的一个 DataStax Astra DB 实例(您可以在 datastax.com 免费获取)。有关更多信息,请查看 cassio.org

%pip install --upgrade --quiet  "cassio>=0.1.0 langchain-community"

设置数据库连接参数和密钥

import getpass

database_mode = (input("\n(C)assandra or (A)stra DB? ")).upper()

keyspace_name = input("\nKeyspace name? ")

if database_mode == "A":
ASTRA_DB_APPLICATION_TOKEN = getpass.getpass('\nAstra DB Token ("AstraCS:...") ')
#
ASTRA_DB_SECURE_BUNDLE_PATH = input("Full path to your Secure Connect Bundle? ")
elif database_mode == "C":
CASSANDRA_CONTACT_POINTS = input(
"Contact points? (comma-separated, empty for localhost) "
).strip()

根据是本地还是基于云的 Astra DB,创建相应的数据库连接“Session”对象。

from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster

if database_mode == "C":
if CASSANDRA_CONTACT_POINTS:
cluster = Cluster(
[cp.strip() for cp in CASSANDRA_CONTACT_POINTS.split(",") if cp.strip()]
)
else:
cluster = Cluster()
session = cluster.connect()
elif database_mode == "A":
ASTRA_DB_CLIENT_ID = "token"
cluster = Cluster(
cloud={
"secure_connect_bundle": ASTRA_DB_SECURE_BUNDLE_PATH,
},
auth_provider=PlainTextAuthProvider(
ASTRA_DB_CLIENT_ID,
ASTRA_DB_APPLICATION_TOKEN,
),
)
session = cluster.connect()
else:
raise NotImplementedError

示例

from langchain_community.chat_message_histories import (
CassandraChatMessageHistory,
)

message_history = CassandraChatMessageHistory(
session_id="test-session",
session=session,
keyspace=keyspace_name,
)

message_history.add_user_message("hi!")

message_history.add_ai_message("whats up?")
message_history.messages

引用声明

Apache Cassandra, Cassandra and Apache are either registered trademarks or trademarks of the Apache Software Foundation in the United States and/or other countries.