[使用TiDB Serverless存储和检索AI聊天记录的实用指南]

89 阅读2分钟
# 使用TiDB Serverless存储和检索AI聊天记录的实用指南

## 引言

随着AI技术的不断发展,越来越多的开发者开始将AI集成到他们的应用中。TiDB Cloud 提供了TiDB Serverless,这是一种灵活的数据库解决方案,特别适合存储和管理AI生成的聊天记录。本文将介绍如何使用TiDB Serverless存储聊天记录,并利用它的内置向量搜索功能来提高查找效率。

## 主要内容

### TiDB Serverless简介

TiDB Serverless是TiDB Cloud的一部分,提供了一种易于使用的Database-as-a-Service (DBaaS)解决方案。通过其内置的向量搜索功能,开发者无需新的技术栈即可将AI应用程序无缝集成到MySQL环境中。

### 安装依赖

首先,我们需要安装一些必要的库:

```shell
%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的连接。以下是标准的方法:

# 使用API代理服务提高访问稳定性
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(),
)

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.content)

常见问题和解决方案

网络限制

在某些地区,由于网络限制,访问TiDB Cloud可能不太稳定。此时,考虑使用API代理服务确保连接的稳定性。

连接错误

确保提供正确的连接字符串格式和有效的凭据,以避免连接错误。

总结和进一步学习资源

通过TiDB Serverless,开发者可以轻松地存储和检索AI生成的聊天记录,从而简化AI应用的开发过程。欲了解更多信息,请参考以下资源:

参考资料

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

---END---