Couchbase
Couchbase is an award-winning distributed NoSQL cloud database that delivers unmatched versatility, performance, scalability, and financial value for all of your cloud, mobile, AI, and edge computing applications. Couchbase embraces AI with coding assistance for developers and vector search for their applications.
本笔记本介绍了如何使用 CouchbaseChatMessageHistory 类将聊天消息历史存储在 Couchbase 集群中
设置 Couchbase 集群
要运行此演示,您需要一个 Couchbase 集群。
您可以同时使用 Couchbase Capella 和您自行管理的 Couchbase Server。
安装依赖项
CouchbaseChatMessageHistory 位于 langchain-couchbase 包内。
%pip install --upgrade --quiet langchain-couchbase
Note: you may need to restart the kernel to use updated packages.
创建 Couchbase 连接对象
我们首先创建到 Couchbase 集群的连接,然后将集群对象传递给向量存储。
在这里,我们使用用户名和密码进行连接。您也可以使用集群支持的任何其他方式进行连接。
有关连接到 Couchbase 集群的更多信息,请查看 Python SDK 文档。
COUCHBASE_CONNECTION_STRING = (
"couchbase://localhost" # or "couchbases://localhost" if using TLS
)
DB_USERNAME = "Administrator"
DB_PASSWORD = "Password"
from datetime import timedelta
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions
auth = PasswordAuthenticator(DB_USERNAME, DB_PASSWORD)
options = ClusterOptions(auth)
cluster = Cluster(COUCHBASE_CONNECTION_STRING, options)
# Wait until the cluster is ready for use.
cluster.wait_until_ready(timedelta(seconds=5))
我们将设置 Couchbase 集群中用于存储消息历史的存储桶、作用域和集合的名称。
请注意,在使用它们存储消息历史之前,存储桶、作用域和集合需要已经存在。
BUCKET_NAME = "langchain-testing"
SCOPE_NAME = "_default"
COLLECTION_NAME = "conversational_cache"
使用
为了存储消息,你需要以下内容:
- Couchbase 集群对象:与 Couchbase 集群的有效连接
- bucket_name: 存储聊天消息历史的集群中的存储桶
- scope_name:存储消息历史的桶中的作用域
- collection_name:用于存储消息历史的范围内的集合
- session_id:会话的唯一标识符
可选地,您可以配置以下内容:
- session_id_key: 存储聊天消息文档中
session_id的字段 - message_key: 存储聊天消息内容的字段在聊天消息文档中。
- create_index: 用于指定是否需要在集合上创建索引。默认情况下,在文档的
message_key和session_id_key上创建索引 - ttl: 用于指定文档在存储中自动删除前的存活时间,范围为
timedelta到无限。
from langchain_couchbase.chat_message_histories import CouchbaseChatMessageHistory
message_history = CouchbaseChatMessageHistory(
cluster=cluster,
bucket_name=BUCKET_NAME,
scope_name=SCOPE_NAME,
collection_name=COLLECTION_NAME,
session_id="test-session",
)
message_history.add_user_message("hi!")
message_history.add_ai_message("how are you doing?")
message_history.messages
[HumanMessage(content='hi!'), AIMessage(content='how are you doing?')]
为聊天消息指定生存时间(TTL)
在初始化聊天消息历史存储时,通过指定一个 ttl 参数,存储的消息可以在指定时间后自动删除。
from langchain_couchbase.chat_message_histories import CouchbaseChatMessageHistory
message_history = CouchbaseChatMessageHistory(
cluster=cluster,
bucket_name=BUCKET_NAME,
scope_name=SCOPE_NAME,
collection_name=COLLECTION_NAME,
session_id="test-session",
ttl=timedelta(hours=24),
)
链式调用
聊天消息历史类可以与LCEL 可运行对象一起使用
import getpass
import os
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = getpass.getpass()
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
# Create the LCEL runnable
chain = prompt | ChatOpenAI()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: CouchbaseChatMessageHistory(
cluster=cluster,
bucket_name=BUCKET_NAME,
scope_name=SCOPE_NAME,
collection_name=COLLECTION_NAME,
session_id=session_id,
),
input_messages_key="question",
history_messages_key="history",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "testing"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
AIMessage(content='Hello, Bob! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 22, 'total_tokens': 33}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-62e54e3d-db70-429d-9ee0-e5e8eb2489a1-0', usage_metadata={'input_tokens': 22, 'output_tokens': 11, 'total_tokens': 33})
chain_with_history.invoke({"question": "Whats my name"}, config=config)
AIMessage(content='Your name is Bob.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 5, 'prompt_tokens': 44, 'total_tokens': 49}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-d84a570a-45f3-4931-814a-078761170bca-0', usage_metadata={'input_tokens': 44, 'output_tokens': 5, 'total_tokens': 49})