引言
TiDB Cloud 提供了一种全面的数据库即服务(DBaaS)解决方案,其中包括独立和无服务器选项。最近,TiDB Serverless 集成了内置向量搜索功能,使得开发人员可以在 MySQL 环境下无缝开发 AI 应用程序,而无需引入新的数据库或技术栈。在本文中,我们将介绍如何使用 TiDB 存储聊天消息记录。
主要内容
环境设置
首先,我们需要安装以下依赖:
%pip install --upgrade --quiet langchain langchain_openai langchain-community
配置您的 OpenAI 密钥
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass("Input your OpenAI API key:")
配置 TiDB 连接
我们将使用 TiDB Cloud 提供的标准连接方法,以建立安全高效的数据库连接。
# 从 TiDB Cloud 控制台复制
tidb_connection_string_template = "mysql+pymysql://<USER>:<PASSWORD>@<HOST>:4000/<DB>?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
tidb_password = getpass.getpass("Input your TiDB password:")
tidb_connection_string = tidb_connection_string_template.replace("<PASSWORD>", tidb_password)
生成历史数据
创建一组历史数据,将作为我们后续演示的基础。
from datetime import datetime
from langchain_community.chat_message_histories import TiDBChatMessageHistory
history = TiDBChatMessageHistory(
connection_string=tidb_connection_string,
session_id="code_gen",
earliest_time=datetime.utcnow(), # 可选,设置 earliest_time以加载此时间点之后的消息
)
history.add_user_message("How's our feature going?")
history.add_ai_message("It's going well. We are working on testing now. It will be released in Feb.")
利用历史数据进行交互
我们将基于之前生成的历史数据创建动态聊天交互。
使用 LangChain 创建聊天链
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You're an assistant who's good at coding. You're helping a startup build"),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
chain = prompt | ChatOpenAI()
构建带有历史记录的可运行项
from langchain_core.runnables.history import RunnableWithMessageHistory
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: TiDBChatMessageHistory(
session_id=session_id, connection_string=tidb_connection_string
),
input_messages_key="question",
history_messages_key="history",
)
启动聊天
response = chain_with_history.invoke(
{"question": "Today is Jan 1st. How many days until our feature is released?"},
config={"configurable": {"session_id": "code_gen"}},
)
response
常见问题和解决方案
-
连接问题:确保使用正确的连接字符串和凭据。如果您在某些地区遇到网络限制,可以考虑使用 API代理服务 来提高访问稳定性。
-
数据加载错误:检查
earliest_time参数,确保加载的历史数据符合预期。
总结和进一步学习资源
通过本文,我们介绍了如何利用 TiDB Serverless 存储和处理聊天消息记录,并通过 LangChain 实现了动态聊天交互。TiDB 的无缝集成和高效性能为开发 AI 应用程序提供了强有力的支持。
参考资料
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---