Skip to main content
Open In ColabOpen on GitHub

TiDB

TiDB Cloud 是一个全面的数据库即服务 (DBaaS) 解决方案,提供专享和无服务器选项。TiDB Serverless 正在将内置的向量搜索集成到 MySQL 生态系统中。通过此增强功能,您无需新的数据库或额外的技术栈,即可使用 TiDB Serverless 轻松开发 AI 应用。请在此处创建免费的 TiDB Serverless 集群并开始使用向量搜索功能:https://pingcap.com/ai。

本笔记本将介绍如何使用 TiDB 存储聊天消息历史。

设置

首先,我们将安装以下依赖:

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

配置你的 OpenAI 密钥

import getpass
import os

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

最后,我们将配置与 TiDB 的连接。在本笔记本中,我们将遵循 TiDB Cloud 提供的标准连接方法来建立一个安全且高效的数据库连接。

# copy from tidb cloud console
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(), # Optional to set earliest_time to load messages after this time point.
)

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
[HumanMessage(content="How's our feature going?"),
AIMessage(content="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"}},
)
response
AIMessage(content='There are 31 days in January, so there are 30 days until our feature is released in February.')

检查历史数据

history.reload_cache()
history.messages
[HumanMessage(content="How's our feature going?"),
AIMessage(content="It's going well. We are working on testing now. It will be released in Feb."),
HumanMessage(content='Today is Jan 1st. How many days until our feature is released?'),
AIMessage(content='There are 31 days in January, so there are 30 days until our feature is released in February.')]