Gradio 月活用户突破 100 万!

阅读更多
Gradio logo
  1. 聊天机器人
  2. 聊天机器人特定事件

聊天机器人特定事件

用户期望现代聊天机器人 UI 能够让他们轻松地与单个聊天消息互动:例如,用户可能想要重试消息生成、撤消消息,或者点击喜欢/不喜欢按钮来赞成或反对生成的消息。

值得庆幸的是,Gradio Chatbot 公开了几个事件,例如 .retry.undo.like.clear,让你可以将此功能构建到你的应用程序中。 作为应用程序开发者,你可以将函数附加到任何这些事件,从而允许你在用户与消息互动时运行任意 Python 函数,例如。

在本演示中,我们将构建一个实现这些事件的 UI。你可以在 Hugging Face Spaces 上查看我们完成的演示:

提示: `gr.ChatInterface` 自动使用 `retry` 和 `.undo` 事件,因此最好从那里开始,以便快速获得一个功能齐全的应用程序。

用户界面

首先,我们将构建 UI,而不处理这些事件,并从那里开始构建。我们将使用 Hugging Face InferenceClient 以便开始,而无需设置任何 API 密钥。

这是我们的应用程序的第一个草稿的样子:

from huggingface_hub import InferenceClient
import gradio as gr

client = InferenceClient()

def respond(
    prompt: str,
    history,
):
    if not history:
        history = [{"role": "system", "content": "You are a friendly chatbot"}]
    history.append({"role": "user", "content": prompt})

    yield history

    response = {"role": "assistant", "content": ""}
    for message in client.chat_completion(
        history,
        temperature=0.95,
        top_p=0.9,
        max_tokens=512,
        stream=True,
        model="HuggingFaceH4/zephyr-7b-beta"
    ):
        response["content"] += message.choices[0].delta.content or ""

        yield history + [response]


with gr.Blocks() as demo:
    gr.Markdown("# Chat with Hugging Face Zephyr 7b 🤗")
    chatbot = gr.Chatbot(
        label="Agent",
        type="messages",
        avatar_images=(
            None,
            "https://em-content.zobj.net/source/twitter/376/hugging-face_1f917.png",
        ),
    )
    prompt = gr.Textbox(max_lines=1, label="Chat Message")
    prompt.submit(respond, [prompt, chatbot], [chatbot])
    prompt.submit(lambda: "", None, [prompt])


if __name__ == "__main__":
    demo.launch()

撤销事件

我们的撤销事件将使用户之前的消息填充文本框,并删除所有后续的助手回复。

为了知道最后一条用户消息的索引,我们可以将 gr.UndoData 传递给我们的事件处理函数,如下所示:

``python def handle_undo(history, undo_data: gr.UndoData): return history[:undo_data.index], history[undo_data.index]['content']


We then pass this function to the `undo` event!

```python
    chatbot.undo(handle_undo, chatbot, [chatbot, prompt])

你会注意到,现在每个机器人响应都会有一个“撤销图标”,你可以使用它来撤销响应 -

undo_event

提示: 你还可以使用 `undo_data.value` 访问用户消息的内容

重试事件

重试事件的工作方式类似。我们将使用 gr.RetryData 获取上一个用户消息的索引,并从历史记录中删除所有后续消息。然后我们将使用 respond 函数生成新的响应。我们还可以通过 gr.RetryDatavalue 属性获取之前的提示。

def handle_retry(history, retry_data: gr.RetryData):
    new_history = history[:retry_data.index]
    previous_prompt = history[retry_data.index]['content']
    yield from respond(previous_prompt, new_history)

...

chatbot.retry(handle_retry, chatbot, chatbot)

你会看到,现在机器人消息有了“重试”图标 -

retry_event

提示: Hugging Face 推理 API 会缓存响应,因此在本演示中,重试按钮不会生成新的响应。

点赞事件

现在您应该已经看到了这种模式!为了让用户点赞消息,我们将向我们的聊天机器人添加一个 .like 事件。我们将传递给它一个接受 gr.LikeData 对象的函数。在本例中,我们只打印被点赞或不喜欢的消息。

def handle_like(data: gr.LikeData):
    if data.liked:
        print("You upvoted this response: ", data.value)
    else:
        print("You downvoted this response: ", data.value)

...

chatbot.like(vote, None, None)

编辑事件

编辑监听器也是同样的想法!使用 gr.Chatbot(editable=True),您可以捕获用户编辑。gr.EditData 对象告诉我们被编辑消息的索引和消息的新文本。下面,我们使用此对象来编辑历史记录,并删除任何后续消息。

def handle_edit(history, edit_data: gr.EditData):
    new_history = history[:edit_data.index]
    new_history[-1]['content'] = edit_data.value
    return new_history

...

chatbot.edit(handle_edit, chatbot, chatbot)

清除事件

作为奖励,我们还将介绍 .clear() 事件,当用户单击清除图标以清除所有消息时,将触发该事件。作为开发人员,您可以附加在单击此图标时应发生的其他事件,例如处理清除额外的聊天机器人状态

from uuid import uuid4
import gradio as gr


def clear():
    print("Cleared uuid")
    return uuid4()


def chat_fn(user_input, history, uuid):
    return f"{user_input} with uuid {uuid}"


with gr.Blocks() as demo:
    uuid_state = gr.State(
        uuid4
    )
    chatbot = gr.Chatbot(type="messages")
    chatbot.clear(clear, outputs=[uuid_state])

    gr.ChatInterface(
        chat_fn,
        additional_inputs=[uuid_state],
        chatbot=chatbot,
        type="messages"
    )

demo.launch()

在此示例中,当通过垃圾箱图标清除聊天记录时,绑定到 chatbot.clear 事件的 clear 函数会将新的 UUID 返回到我们的会话状态。这可以在 chat_fn 函数中看到,该函数引用了保存在我们会议状态中的 UUID。

此示例还表明,您可以通过传入自定义 gr.Chatbot 对象将这些事件与 gr.ChatInterface 一起使用。

结论

就是这样!现在您知道如何为 Chatbot 实现重试、撤消、点赞和清除事件了。