💻用 Python 为您的 LLM 创建一个 Web 界面

社区文章 发布于 2024 年 1 月 23 日

在本教程中,我们将创建一个简单的聊天机器人 Web 界面,并使用一个名为 Taipy 的开源 Python 库对其进行部署。

Render of the app

这里我们将使用 HuggingFace 的 API 和 google/flan-t5-xxl。本教程可以很容易地适应其他 LLM。

步骤 1:安装依赖

创建一个名为 requirements.txt 的文件,内容如下

taipy==3.0.0

在终端中使用 pip 安装依赖

pip install -r requirements.txt

步骤 2:导入

创建一个名为 main.py 的文件,并包含以下导入语句

import requests
from taipy.gui import Gui, State, notify

步骤 3:初始化变量

在 main.py 文件中初始化以下变量

context = "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.\n\nHuman: Hello, who are you?\nAI: I am an AI created by Google. How can I help you today? "
conversation = {
    "Conversation": ["Who are you?", "Hi! I am FLAN-T5 XXL. How can I help you today?"]
}
current_user_message = ""
  • context 是对话的初始上下文,LLM 将使用它来理解预期行为。
  • conversation 是一个字典,将存储要显示的对话历史记录
  • current_user_message 是用户当前正在键入的消息

步骤 4:创建一个生成响应的函数

如果您想使用不同的 LLM,则此步骤需要进行调整。

使用您的访问令牌初始化 HuggingFace 变量。您可以在此处找到您的访问令牌。

API_URL = "https://api-inference.huggingface.co/models/google/flan-t5-xxl"
headers = {"Authorization": "Bearer [YOUR ACCESS TOKEN]"}

创建一个函数,该函数将用户消息字符串 prompt 作为输入,并返回 LLM 的响应字符串。

def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

def request(state: State, prompt: str) -> str:
    """
    Send a prompt to the HuggingFace API and return the response.

    Args:
        - state: The current state of the app.
        - prompt: The prompt to send to the API.

    Returns:
        The response from the API.
    """
    
    output = query(
        {
            "inputs": prompt,
        }
    )
    print(output)
    return output[0]["generated_text"]

步骤 5:创建一个将新消息添加到对话中的函数

创建一个当用户发送消息时触发的函数。此函数会将用户消息添加到上下文,将其发送到 API,获取响应,并将响应添加到上下文和显示的对话中。

def send_message(state: State) -> None:
    """
    Send the user's message to the API and update the conversation.

    Args:
        - state: The current state of the app.
    """
    # Add the user's message to the context
    state.context += f"Human: \n {state.current_user_message}\n\n AI:"
    # Send the user's message to the API and get the response
    answer = request(state, state.context).replace("\n", "")
    # Add the response to the context for future messages
    state.context += answer
    # Update the conversation
    conv = state.conversation._dict.copy()
    conv["Conversation"] += [state.current_user_message, answer]
    state.conversation = conv
    # Clear the input field
    state.current_user_message = ""

步骤 6:创建用户界面

在 Taipy 中,定义页面的一种方法是使用 Markdown 字符串。这里我们使用一个表格来显示 conversation 字典,并使用一个输入框以便用户可以输入他们的消息。当用户按下回车键时,send_message 函数将被触发。

page = """
<|{conversation}|table|show_all|width=100%|>
<|{current_user_message}|input|label=Write your message here...|on_action=send_message|class_name=fullwidth|>
"""

步骤 7:运行应用程序

最后,我们运行应用程序

if __name__ == "__main__":
    Gui(page).run(dark_mode=True, title="Taipy Chat")

结果如下

Render of the app

步骤 8:样式设计

此应用程序的样式是 Taipy 的默认 Stylekit。我们将进行一些更改,使其看起来更像一个聊天应用程序。

首先在 main.css 文件中,创建用于不同显示用户和 AI 消息的样式

.gpt_message td {
    margin-left: 30px;
    margin-bottom: 20px;
    margin-top: 20px;
    position: relative;
    display: inline-block;
    padding: 20px;
    background-color: #ff462b;
    border-radius: 20px;
    max-width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    font-size: large;
}

.user_message td {
    margin-right: 30px;
    margin-bottom: 20px;
    margin-top: 20px;
    position: relative;
    display: inline-block;
    padding: 20px;
    background-color: #140a1e;
    border-radius: 20px;
    max-width: 80%;
    float: right;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    font-size: large;
}

现在我们需要告诉 Taipy 将这些样式应用于表格中的行。我们首先创建一个函数,该函数将为每一行返回正确的类名

def style_conv(state: State, idx: int, row: int) -> str:
    """
    Apply a style to the conversation table depending on the message's author.

    Args:
        - state: The current state of the app.
        - idx: The index of the message in the table.
        - row: The row of the message in the table.

    Returns:
        The style to apply to the message.
    """
    if idx is None:
        return None
    elif idx % 2 == 0:
        return "user_message"
    else:
        return "gpt_message"

然后,我们通过添加 style 属性将此函数应用于表格

<|{conversation}|table|show_all|style=style_conv|>

瞧!

The styled application

步骤 9:更多功能

我添加了通知、一个带有清除对话按钮的侧边栏以及一个历史对话记录。我不会在这里详细介绍如何实现这些功能,但您可以在 GitHub 仓库中找到完整的代码

步骤 10:将应用程序部署到 Taipy Cloud

现在我们将应用程序部署到 Taipy Cloud,以便任何人都可以通过链接访问它。

首先,我们需要将 API 密钥存储在环境变量中。将步骤 4 中定义 headers 的行替换为

import os
headers = {"Authorization": f"Bearer {os.environ['HUGGINGFACE_API_KEY']}"}

现在,应用程序将从环境变量中查找我们的 API 密钥,而不是将其硬编码在代码中。

我们现在可以将应用程序部署到 Taipy Cloud

  1. 连接到Taipy Cloud并登录
  2. 单击“添加机器”并填写字段
  3. 选择创建的机器并单击“添加应用程序”
  4. main.pymain.cssrequirements.txt 文件压缩,并将 zip 文件上传到“应用程序文件”字段。填写其他字段
  5. 在“环境变量”选项卡中,创建一个名为 HUGGINGFACE_API_KEY 的新环境变量,并将您的 API 密钥粘贴为值,如下图所示
  6. 按“部署应用程序”

Environment Variables Tab

一段时间后,您的应用程序应该会运行,并且可以通过显示的链接访问!

Taipy Cloud Interface

The final application

社区

注册登录 发表评论