# 利用 Azure OpenAI 部署你自己的知识库聊天机器人

## 概述

[AutoFlow](https://github.com/pingcap/autoflow) 是一款基于 Graph RAG 的对话式知识库聊天助手，由 TiDB 向量存储和 LlamaIndex 构建而成，开源且可免费使用。

+ 在本实验中，你将学习如何：
  + 将你自己的知识（Word/PDF/TXT/Markdown 等格式）导入知识库。
  + 使用聊天机器人在知识库中搜索信息。
  + 连接到为你预配的 TiDB Cloud Serverless 集群并在其上运行查询。该集群同时作为向量存储和图数据库。
  + 向 [这样](https://tidb.ai) 部署你自己的知识库聊天机器人。

  ![70%](https://lab-static.pingcap.com/quick-demo/taa-example-does-tidb-support-fk.jpeg)

### 实验时长

+ 本实验预计大约需要 1 小时完成。

### 任务

+ 使用 [pingcap/autoflow](https://github.com/pingcap/autoflow) 代码库部署知识库应用程序。
+ 配置你的知识库应用程序。
+ 与人工智能聊天机器人进行随机聊天，查看它是否能利用知识库中的信息回答你的问题。

> [!TIP]
> 点击 **开始** 启动实验环境。
> 环境准备就绪后，点击底部工具栏中的 **前进** 进入 **模块 1**。
> 然后，按照实验指南的步骤连接到实践环境并开始你的任务。

## 模块 1：准备运行时环境并初始化 AutoFlow 服务

### 步骤 1. 登录应用服务器虚拟机

+ 点击这里 - [终端 1](ssh://monitor1-ssh#1) 打开一个新的终端，连接到为你的实践实验分配的虚拟机。

+ 登录后显示的信息如下：

  ```output
  ubuntu@ip-10-90-1-154:~$ 
  ```

### 步骤 2. 安装 Docker、Docker Compose、MySQL 客户端等必要软件包

+ 卸载旧版本的 Docker 和 Docker Compose。

   ```bash
   for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done
   ```

   ```output
   Reading package lists... Done
   Building dependency tree... Done
   Reading state information... Done
   .
   .
   .
   Reading state information... Done
   Package 'runc' is not installed, so not removed
   0 upgraded, 0 newly installed, 0 to remove and 30 not upgraded.
   ```

+ 添加 Docker 的官方 GPG 密钥。

   ```bash
   sudo apt-get update -y
   sudo apt-get install ca-certificates curl -y
   sudo install -m 0755 -d /etc/apt/keyrings
   sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
   sudo chmod a+r /etc/apt/keyrings/docker.asc
   ```

   ```output
   Hit:1 http://us-west-2.ec2.archive.ubuntu.com/ubuntu noble InRelease
   Get:2 http://us-west-2.ec2.archive.ubuntu.com/ubuntu noble-updates InRelease [126 kB]
   .
   .
   .
   Get:15 http://us-west-2.ec2.archive.ubuntu.com/ubuntu noble-updates/main Translation-en [151 kB]
   Fetched 30.6 MB in 5s (6133 kB/s)               
   Reading package lists... Done
   Reading package lists... Done
   Building dependency tree... Done
   Reading state information... Done
   ca-certificates is already the newest version (20240203).
   ca-certificates set to manually installed.
   curl is already the newest version (8.5.0-2ubuntu10.4).
   curl set to manually installed.
   0 upgraded, 0 newly installed, 0 to remove and 33 not upgraded.
   ```

+ 将存储库添加到 `apt` 源。

   ```bash
   echo \
     "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
     $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
     sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
   sudo apt-get update -y
   ```

   ```output
   Reading package lists... Done
   .
   .
   .                      
   Get:6 https://download.docker.com/linux/ubuntu noble/stable amd64 Packages [15.3 kB]
   Fetched 64.2 kB in 1s (79.9 kB/s)   
   Reading package lists... Done
   ```
  
+ 安装 Docker 软件包。

   ```bash
   sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
   ```

   ```output
   Reading package lists... Done
   Building dependency tree... Done
   Reading state information... Done
   .
   .
   .
   No VM guests are running outdated hypervisor (qemu) binaries on this host.
   ```

+ 通过运行 `hello-world` 镜像验证 Docker 是否正确安装。

   ```bash
   sudo docker run hello-world
   ```

   ```output
   Unable to find image 'hello-world:latest' locally
   latest: Pulling from library/hello-world
   c1ec31eb5944: Pull complete 
   Digest: sha256:d211f485f2dd1dee407a80973c8f129f00d54604d2c90732e8e320e5038a0348
   Status: Downloaded newer image for hello-world:latest

   Hello from Docker!
   .
   .
   .
   To try something more ambitious, you can run an Ubuntu container with:
    $ docker run -it ubuntu bash

   Share images, automate workflows, and more with a free Docker ID:
    https://hub.docker.com/

   For more examples and ideas, visit:
    https://docs.docker.com/get-started/
   ```

+ 安装 MySQL 客户端。

   ```bash
   sudo apt-get install -y mysql-client-core-8.0
   ```
   ```output
   Reading package lists... Done
   Building dependency tree... Done
   Reading state information... Done
   The following NEW packages will be installed:
     mysql-client-core-8.0
   0 upgraded, 1 newly installed, 0 to remove and 33 not upgraded.
   Need to get 2794 kB of archives.
   After this operation, 61.6 MB of additional disk space will be used.
   Get:1 http://us-west-2.ec2.archive.ubuntu.com/ubuntu noble-updates/main amd64 mysql-client-core-8.0 amd64 8.0.39-0ubuntu0.24.04.2 [2794 kB]
   Fetched 2794 kB in 0s (34.7 MB/s)
   Selecting previously unselected package mysql-client-core-8.0.
   (Reading database ... 68102 files and directories currently installed.)
   Preparing to unpack .../mysql-client-core-8.0_8.0.39-0ubuntu0.24.04.2_amd64.deb ...
   Unpacking mysql-client-core-8.0 (8.0.39-0ubuntu0.24.04.2) ...
   Setting up mysql-client-core-8.0 (8.0.39-0ubuntu0.24.04.2) ...
   Processing triggers for man-db (2.12.0-4build2) ...
   Scanning processes...
   Scanning linux images...

   Running kernel seems to be up-to-date.

   No services need to be restarted.

   No containers need to be restarted.

   No user sessions are running outdated binaries.

   No VM guests are running outdated hypervisor (qemu) binaries on this host.
   ```

### 步骤 3. 克隆并配置 AutoFlow

+ 克隆 pingcap/autoflow 代码库，并导航到 `autoflow` 目录。

   ```bash
   git clone https://github.com/pingcap/autoflow;
   cd autoflow;
   git fetch origin v0.4.1;
   git checkout v0.4.1;
   git switch --detach d2300a3a9f43c8d3545d057c2943c9ecbf4b6b8a;
   ```

   ```output
   Cloning into 'autoflow'...
   remote: Enumerating objects: 12041, done.
   remote: Counting objects: 100% (538/538), done.
   remote: Compressing objects: 100% (264/264), done.
   remote: Total 12041 (delta 312), reused 446 (delta 268), pack-reused 11503 (from 1)
   Receiving objects: 100% (12041/12041), 4.33 MiB | 22.07 MiB/s, done.
   Resolving deltas: 100% (7431/7431), done.
   ```

+ 使用以下值更新 `.env` 文件：

   ```bash
   cat > .env <<'EOF'
   ENVIRONMENT=production

   SECRET_KEY="some_secret_key_that_is_at_least_32_characters_long"

   TIDB_HOST=serverless_host
   TIDB_PORT=serverless_port
   TIDB_USER='serverless_username'
   TIDB_PASSWORD='serverless_password'
   TIDB_DATABASE=tidbai_test
   TIDB_SSL=true

   EMBEDDING_DIMS=1536
   EMBEDDING_MAX_TOKENS=8191
   EOF
   cat .env
   ```

   ```output
   ENVIRONMENT=production

   SECRET_KEY="some_secret_key_that_is_at_least_32_characters_long"

   TIDB_HOST=serverless_host
   TIDB_PORT=serverless_port
   TIDB_USER='serverless_username'
   TIDB_PASSWORD='serverless_password'
   TIDB_DATABASE=tidbai_test
   TIDB_SSL=true

   EMBEDDING_DIMS=1536
   EMBEDDING_MAX_TOKENS=8191
   ```

### 步骤 4. 确保你的数据库已清理并为后续步骤做好准备

+ 使用以下命令连接到 TiDB Cloud Serverless 集群。

   ```bash
   mysql \
      --comments -u 'serverless_username' -p'serverless_password' \
      -h serverless_host -P serverless_port \
      --ssl-mode=VERIFY_IDENTITY --ssl-ca=/etc/ssl/certs/ca-certificates.crt
   ```
   ```output
   mysql: [Warning] Using a password on the command line interface can be insecure.
   Welcome to the MySQL monitor.  Commands end with ; or \g.
   Your MySQL connection id is 2168969
   Server version: 5.7.28-TiDB-Serverless TiDB Server (Apache License 2.0) Community Edition, MySQL 5.7 compatible

   Copyright (c) 2000, 2024, Oracle and/or its affiliates.

   Oracle is a registered trademark of Oracle Corporation and/or its
   affiliates. Other names may be trademarks of their respective
   owners.

   Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

   mysql>
   ```

+ 删除现有数据库并创建一个新数据库。

   ```bash
   DROP DATABASE IF EXISTS tidbai_test;
   CREATE DATABASE tidbai_test;
   EXIT;
   ```
   ```output
   mysql> DROP DATABASE IF EXISTS tidbai_test;
   Query OK, 0 rows affected (0.00 sec)

   mysql> CREATE DATABASE tidbai_test;
   Query OK, 0 rows affected (0.12 sec)

   mysql> EXIT;
   Bye
   ```

### 步骤 5. 创建 schema

+ 运行 data migration 以创建表并设置初始管理员用户 <span style="color: Red">请注意输出中红色行生成的管理员密码。</span>

   ```bash
   sudo docker compose run backend /bin/sh -c "alembic upgrade head";
   sudo docker compose run backend /bin/sh -c "python bootstrap.py";
   ```

   ```output
   [+] Creating 1/0
   ✔ Container tidb-ai-redis-1  Running                                                                                                                                   0.0s
   INFO  [alembic.runtime.migration] Context impl MySQLImpl.
   INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
   INFO  [alembic.runtime.migration] Running upgrade  -> 2fc10c21bf88, empty message
   INFO  [alembic.runtime.migration] Running upgrade 2fc10c21bf88 -> 94b198e20946, empty message
   INFO  [alembic.runtime.migration] Running upgrade 94b198e20946 -> 04d4f05116ed, empty message
   INFO  [alembic.runtime.migration] Running upgrade 04d4f05116ed -> 197bc8be72d1, empty message
   INFO  [alembic.runtime.migration] Running upgrade 197bc8be72d1 -> ac6e4d58580d, empty message
   INFO  [alembic.runtime.migration] Running upgrade ac6e4d58580d -> a8c79553c9f6, empty message
   INFO  [alembic.runtime.migration] Running upgrade a8c79553c9f6 -> bd17a4ebccc5, empty message
   INFO  [alembic.runtime.migration] Running upgrade bd17a4ebccc5 -> e32f1e546eec, empty message
   INFO  [alembic.runtime.migration] Running upgrade e32f1e546eec -> 04d81be446c3, empty message
   INFO  [alembic.runtime.migration] Running upgrade 04d81be446c3 -> 041fbef26e3a, empty message
   INFO  [alembic.runtime.migration] Running upgrade 041fbef26e3a -> 10f36e8a25c4, empty message
   INFO  [alembic.runtime.migration] Running upgrade 10f36e8a25c4 -> 00534dc350db, empty message
   INFO  [alembic.runtime.migration] Running upgrade 00534dc350db -> eb0b85608c0a, empty message
   INFO  [alembic.runtime.migration] Running upgrade eb0b85608c0a -> dfee070b8abd, empty message
   WARN[0000] Found orphan containers ([tidb-ai-backend-run-d4d35b6b5909]) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
   [+] Creating 1/0
   ✔ Container tidb-ai-redis-1  Running                                                                                                                                   0.0s
   Bootstrapping the application...
   /usr/local/lib/python3.11/site-packages/pydantic/_internal/_config.py:341: UserWarning: Valid config keys have changed in V2:
   * 'orm_mode' has been renamed to 'from_attributes'
    warnings.warn(message, UserWarning)
   User 019309f5-2a8f-7e9d-b848-cc81312e598a has registered.

   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   [IMPORTANT] Admin user created with email: admin@example.com and password: <your admin password will be displayed here>
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

   None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
   Default chat engine created.
   Bootstrapping completed.
   ```

### 步骤 6. 通过运行以下 `docker compose` 命令启动知识库应用程序

   ```bash
   sudo docker compose up -d
   ```

   ```output
   [+] Running 43/33
   ✔ backend Pulled                    51.9s
   ✔ background Pulled                 51.9s
   ✔ redis Pulled                       6.5s
   ✔ frontend Pulled                   36.8s

   [+] Running 5/5
   ✔ Network tidb-ai_default         Created              0.3s
   ✔ Container tidb-ai-redis-1       Started             35.0s
   ✔ Container tidb-ai-backend-1     Started              0.7s
   ✔ Container tidb-ai-background-1  Started              0.7s
   ✔ Container tidb-ai-frontend-1    Started              0.9s
   ```

## 模块 2：配置 Azure OpenAI

+ 在本模块中，我们将介绍如何在 Azure OpenAI 服务中配置 Azure OpenAI 服务、嵌入模型和大语言模型。
+ 更多详细信息，请参考：

  + [Azure OpenAI documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference)
  + [Create and deploy an Azure OpenAI Service resource](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource?pivots=web-portal)

### 步骤 1. 创建 Azure OpenAI 服务

+ 第一步，我们将创建一个 Azure OpenAI 服务。首先要登录 [Azure portal](https://portal.azure.com/#home)。如果这是你首次登录，你将看到以下页面。

  ![Azure Empty Portal](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-empty-portal.jpg)

+ 点击 <kbd>Azure AI services</kbd> 按钮。
+ 在 Azure OpenAI 账户部分点击 <kbd>Create</kbd> 按钮。

  ![Azure AI Services](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-ai-services.jpg)

+ 按照说明创建一个 Azure OpenAI 服务。

> **注意**:
>
> + Azure OpenAI 模型受限于 Azure OpenAI 服务所在的区域。例如，如果你在 `Southeast Asia` 区域创建一个 Azure OpenAI 服务，很可能无法创建 Azure OpenAI 模型。
> + 请在 `Network` 部分选择 "All networks, including the internet, can access this resource." 选项。这样 Azure OpenAI 服务就能从互联网访问。
> + Azure OpenAI 服务可免费使用，更多详细信息请参考 [Azure OpenAI pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/) 。

+ Azure OpenAI 服务创建完成后，你将看到以下页面。

  ![Azure Created Portal](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-created-portal.jpg)

+ 一旦我们创建了 Azure OpenAI 服务，就可以部署一个嵌入模型。请注意，Azure OpenAI 服务或多或少像一个容器，所以你需要在 Azure OpenAI 服务中部署嵌入模型和大语言模型。

### 步骤 2. 部署嵌入模型

+ 在这一步，我们将在 Azure OpenAI 服务中部署一个嵌入模型。我们需要进入一个单独的页面 [Azure AI Foundry](https://ai.azure.com/resource/deployments) 来部署嵌入模型。

  ![Azure AI Foundry](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-ai-foundry-deployment.jpg)

+ 点击 <kbd>Deploy model</kbd> ，然后点击 <kbd>Deploy base model</kbd> 按钮。
+ 选择 `text-embedding-3-small` 模型。
+ 点击 <kbd>Confirm</kbd> 按钮。
+ 在弹出窗口中点击 <kbd>Deploy</kbd> 按钮。

  ![Azure AI Foundry Embedding Model Deployment](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-ai-foundry-embedding-deploy.jpg)

+ 恭喜！你已成功在 Azure OpenAI 服务中部署了一个嵌入模型。

### 步骤 3. 部署大语言模型

+ 在这一步，我们将在 Azure OpenAI 服务中部署一个大语言模型。我们将像部署嵌入模型一样，在 Azure AI Foundry 中部署 `gpt-4o` 模型。
+ 点击页面左侧的 <kbd>Deployments</kbd> 选项卡，回到 **Model deployments** 页面。
+ 点击 <kbd>Deploy model</kbd> ，然后点击 <kbd>Deploy base model</kbd> 按钮。
+ 选择 `gpt-4o` 模型。
+ 点击 <kbd>Confirm</kbd> 按钮。
+ 在弹出窗口中点击 <kbd>Deploy</kbd> 按钮。
+ 恭喜！你已成功在 Azure OpenAI 服务中部署了一个大语言模型。

### 步骤 4. 收集参数

+ 现在，我们需要收集 Azure OpenAI 服务、嵌入模型和大语言模型的参数，以便稍后在 AutoFlow 应用程序中使用。
+ 点击 `text-embedding-3-small` 模型，你将看到 `text-embedding-3-small` 模型页面。

  ![Azure AI Foundry Parameters Collecting - Embedding Model](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-ai-foundry-embedding-collection.jpg)

+ 点击 `gpt-4o` 模型，你将看到 `gpt-4o` 模型页面。

  ![Azure AI Foundry Parameters Collecting - Large Language Model](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/azure-ai-foundry-llm-collection.jpg)

+ 现在，我们已经收集了 Azure OpenAI 服务、嵌入模型和大语言模型的参数。稍后我们将在 AutoFlow 应用程序中使用这些参数。

  + Azure OpenAI Endpoint
  + Azure OpenAI API Key
  + Embedding API Version
  + LLM API Version
  + LLM Deployment Name

## 模块 3：配置并填充知识库

### 步骤 1. 配置 LLM

+ 通过在浏览器中访问 [http://monitor1_address:3000](http://monitor1_address:3000) 来访问并配置知识库应用程序，你将看到以下页面。

+ 使用默认管理员用户 `admin@example.com` 和你在 <span style="color: Red">模块1, 步骤 5 </span>中获得的密码登录。

  ![60%](https://lab-static.pingcap.com/quick-demo/taa-app-credentials.jpeg)

+ 点击 <kbd>Models</kbd> ，然后点击 <kbd>LLMs</kbd> 选项卡，接着点击 <kbd>New LLM</kbd> 按钮。
+ 输入以下信息，然后如下图所示点击 <kbd>Create LLM</kbd> 按钮。请用你在 <span style="color: Red">模块 2，步骤 4</span> 中收集的参数替换占位符：

  + Name: my-azure-openai-llm
  + Provider: Azure OpenAI
  + Model: gpt-4o
  + Azure OpenAI API Key: ${Azure OpenAI API Key}
  + Is Default LLM: Yes
  + Advanced Settings:

    ```json
    {
      "azure_endpoint": "${Azure OpenAI Endpoint}",
      "api_version": "${LLM API Version}",
      "engine": "${LLM Deployment Name}"
    }
    ```

  ![Autoflow LLM Creation](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-config-llm.jpg)

### 步骤 2. 配置嵌入模型

+ 点击 <kbd>Models</kbd> ，然后点击 <kbd>Embedding Models</kbd> 选项卡，接着点击 <kbd>New Embedding Model</kbd> 按钮。
+ 输入以下信息，然后如下图所示点击 <kbd>Create Embedding Model</kbd> 按钮。请用你在 <span style="color: Red">模块 2，步骤 4</span>中收集的参数替换占位符：

  + Name: my-azure-openai-embedding
  + Provider: Azure OpenAI
  + Model: text-embedding-3-small
  + Azure OpenAI API Key: ${Azure OpenAI API Key}
  + Vector Dimensions: 1536
  + Advanced Settings:

    ```json
    {
      "azure_endpoint": "${Azure OpenAI Endpoint}",
      "api_version": "${Embedding API Version}"
    }
    ```

  ![Autoflow Embedding Model Creation](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-config-embedding.jpg)

### 步骤 3. 填充知识库

+ 点击 <kbd>Knowledge Base</kbd> 选项卡，然后点击 <kbd>New Knowledge Base</kbd> 按钮。
+ 输入以下信息，然后点击 <kbd>Create</kbd> 按钮：

  + Name: tidb overview
  + Description: tidb overview
  + LLM: my-azure-openai-llm
  + Embedding Model: my-azure-openai-embedding
  + Knowledge Graph Index: Yes

  ![Autoflow Knowledge Base Creation](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-config-kb.jpg)

### 步骤 4. 创建数据源

+ 在 Knowledge Base 页面，点击 <kbd>Data Sources</kbd> 选项卡，然后点击  <kbd>Web Pages</kbd> 按钮。
+ 在 Page URL 下点击 <kbd>New Item</kbd> 按钮，输入以下信息，然后点击 <kbd>Create</kbd> 按钮：

  + Page URL: https://docs.pingcap.com/tidb/stable/overview
  + Datasource Name: tidb overview

  ![Autoflow Data Source Creation](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-config-data-source.jpg)

### 步骤 5. 观察索引进度

+ 点击 <kbd>Index Progress</kbd> 选项卡，导航到索引进度状态页面，检查索引任务的进度。

+ 你快完成了！现在应用程序正在后台运行一个任务，从你提供的 URL 下载内容。
    + 如果圆圈颜色为蓝色，表示内容正在下载。
    + 如果圆圈颜色为绿色，表示内容已成功下载并导入（索引），这意味着你可以开始与AI聊天机器人聊天了。

  ![Built Index](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-built-index.jpg)

### 步骤 6. 配置默认聊天引擎

+ 现在，我们已经有了一个知识库，以及一个 LLM, and 和一个嵌入模型，我们可以配置聊天引擎来与 AI 聊天机器人聊天。
+ 点击 <kbd>Chat Engines</kbd> 选项卡，然后点击 <kbd>default</kbd> 聊天引擎。
+ 点击 <kbd>Retrieval</kbd> 项卡，然后选择你刚刚创建的知识库，接着点击 <kbd>Save</kbd> 按钮。

  ![Autoflow Default Chat Engine Configuration](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-chat-engine-config.jpg)

### 步骤 7. 使用你刚刚构建的聊天机器人

+ 在浏览器中打开 [http://monitor1_address:3000](http://monitor1_address:3000)  ，或者点击 <kbd>Home</kbd> 开始与人工智能聊天机器人聊天！只需提问： "What is TiDB?":

+ 开心地与你自己的人工智能聊天机器人聊天吧！

  ![Autoflow Chat Start](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-chat-start.jpg)

  ![Autoflow Chat Done](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/autoflow-chat-done.jpg)

## 模块 4：真实场景

在真实情境中，材料通常更为复杂。让我们展示来自 autoflow 客户的真实案例。

> **免责声明**：
>
> 以下问题基于 autoflow 的某真实客户，但我们进行了精炼以移除敏感信息并使其不可识别。同时，对于需要导入的材料，我们是自己制作的，并非客户的真实材料。

### 第一步：确定问题的范围

这是一家来自快餐行业的客户，他们希望为员工构建一个知识库，以便查阅标准操作程序 (SOP)、食谱、食品储存指南和其他知识。

因此，来自客户的一些典型问题有：

+ 我可以要求客户支付小费吗？
+ 如何制作“海陆双拼”？
+ 生三文鱼何时应丢弃？

### 第二步：下载材料

为了回答这些问题，我们需要将材料导入知识库。这是一个虚假的食品行业材料库，你可以从[仓库的发布页面](https://github.com/Icemap/fake-food-industry-material/releases)下载到本地计算机。

![dataset release page](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/dataset-release-page.jpg)

你可以下载 zip 文件或 tar.gz 文件，然后将其解压到本地计算机。

解压的结果是一个名为 `fake-food-industry-material-<version>` 的文件夹，文件夹结构如下：

```output
.
├── recipes
│   ├── chicken_nuggets.md
│   ├── chicken_sandwich.md
│   ├── classic_hamburger.md
│   ├── crispy_fried_chicken.md
│   ├── fish_and_chips.md
│   ├── french_fries.md
│   ├── hot_dogs.md
│   ├── milkshakes.md
│   ├── onion_rings.md
│   ├── pizza.md
│   ├── soft_serve_ice_cream.md
│   └── surf_and_turf.md
├── sop.md
└── storage_guidelines
    ├── bread_products.md
    ├── dry_goods.md
    ├── frozen_foods.md
    └── prepared_foods.md
```

### 第三步：将材料导入知识库

+ 点击<kbd>Knowledge Base</kbd>标签，然后点击<kbd>New Knowledge Base</kbd>按钮。
+ 输入以下信息，然后点击<kbd>Create</kbd>按钮：

  + 名称：食品行业知识库
  + 知识图谱索引：是

  ![food industry knowledge base](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-kb.jpg)

+ 知识库创建完成后，点击<kbd>Data Sources</kbd>标签，然后点击<kbd>Files</kbd>按钮。
+ 点击<kbd>Select files...</kbd>按钮，然后选择你在<span style="color: Red">模块 4，步骤 2</span>中下载的 `fake-food-industry-material-<version>` 文件夹。

  ![food industry data source](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-data-source.jpg)

+ 填写数据源名称为 `Food Industry Data Source`，然后点击<kbd>Create</kbd>按钮。
+ 数据源创建完成后，点击<kbd>Index Progress</kbd>标签以检查索引进度。
+ 等待索引进度完成。

  ![food industry index complete](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-index-complete.jpg)

### 第四步：使用食品行业知识库创建聊天引擎

+ 点击<kbd>Chat Engines</kbd>标签，然后点击<kbd>New Chat Engine</kbd>按钮。
+ 在名称部分输入`Food Industry Chat Engine`，然后点击<kbd>Retrieval</kbd>标签，在知识库部分选择`Food Industry Knowledge Base`，然后点击<kbd>Create Chat Engine</kbd>按钮。

  ![food industry chat engine](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-chat-engine.jpg)

### 第五步：使用聊天机器人回答问题

+ 点击<kbd>Home</kbd>标签，然后点击<kbd>Select Chat Engine</kbd>按钮。
+ 然后选择`Food Industry Chat Engine`。

  ![food industry chat engine select](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-chat-engine-select.jpg)

+ 输入我们在<span style="color: Red">模块 4，步骤 1</span>中提到的问题，并开始与聊天机器人对话。

+ 问题：我可以要求客户支付小费吗？

  ![food industry conversation 1](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-conversation-1.jpg)

+ 问题：如何制作“海陆双拼”？

  ![food industry conversation 2](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-conversation-2.jpg)

+ 问题：生三文鱼何时应丢弃？

  ![food industry conversation 3](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-403/food-industry-conversation-3.jpg)

现在，你可以处理来自客户的真实问题了。

## 结论

在本实验中，你学习了如何像 [https://tidb.ai](https://tidb.ai)那样部署你自己的知识库聊天机器人，你可以将自己的知识导入知识库，并使用聊天机器人在知识库中搜索信息。

如果你想在工作环境中使用这个人工智能聊天机器人，可以在自己的服务器上部署，你需要：

+ 从 [pingcap/autoflow](https://github.com/pingcap/autoflow) 获取源代码。
+ 从 [https://tidbcloud.com](https://tidbcloud.com) 获取你自己的 TiDB Cloud Serverless 集群。
+ 获取你自己的 [Azure OpenAI Service](https://azure.microsoft.com/en-us/products/ai-services).