用户期望现代聊天机器人界面能够让他们轻松地与单个聊天消息互动:例如,用户可能希望重新生成消息、撤销消息,或点击喜欢/不喜欢按钮来对生成的消息进行点赞或点踩。
幸运的是,Gradio Chatbot 暴露了三个事件,.retry, .undo, 和 like,让你可以将这些功能构建到你的应用程序中。作为应用程序开发者,你可以将函数附加到这些事件中的任何一个,允许你运行任意的 Python 函数,例如当用户与消息交互时。
在这个演示中,我们将构建一个实现这些事件的用户界面。你可以在这里看到我们部署在Hugging Face空间上的完成演示:
提示: `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_data.value` 访问用户消息的内容
重试事件将以类似的方式工作。我们将使用gr.RetryData来获取前一条用户消息的索引,并从历史记录中删除所有后续消息。然后我们将使用respond函数生成一个新的响应。我们还可以通过gr.RetryData的value属性获取之前的提示。
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)你会看到机器人消息现在有一个“重试”图标 -
提示: 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)就是这样!你现在知道如何为聊天机器人实现重试、撤销和点赞事件了。