技术背景介绍
TiDB是一种灵活的数据库管理系统,近年来广受欢迎。TiDB Cloud作为其DBaaS(Database-as-a-Service)的解决方案,提供了专用和无服务器选项。现在,TiDB Serverless通过内置的向量搜索增强了MySQL环境,使得在不增加额外技术栈的情况下,可以无缝开发AI应用。
在这篇文章中,我们将探索如何使用TiDB来存储聊天消息历史,并利用其强大的功能进行数据检索和交互。
核心原理解析
TiDB Serverless集成了向量搜索功能,使得以低延迟进行海量数据操作成为可能。我们将利用该特性,结合LangChain库来管理和处理聊天消息历史。通过建立稳定高效的数据库连接,这些消息历史可以在后续的对话中动态检索和利用。
代码实现演示
环境准备
首先,安装必要的依赖库:
%pip install --upgrade --quiet langchain langchain_openai langchain-community
配置OpenAI API密钥
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(),
)
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."
)
# 查看历史消息
print(history.messages)
基于历史数据的对话
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"}},
)
print(response)
检查历史数据
history.reload_cache()
print(history.messages)
应用场景分析
通过TiDB的向量搜索和LangChain的结合,我们能够方便地在各种AI应用中记录和检索对话历史。这在客服聊天机器人、交互式助手等场景中尤为实用。
实践建议
在实践中,建议定期检查和优化数据库连接的配置,确保会话数据的安全和高效管理。在构建复杂应用时,灵活使用TiDB的向量搜索功能可以大大提高应用性能和用户体验。
如果遇到问题欢迎在评论区交流。
—END—

939



被折叠的 条评论
为什么被折叠?



