教你5分钟内使用Hugging Face和 Gradio 构建 AI 聊天机器人
这个简短的教程将使用Microsoft DialoGPT模型,拥抱面部空间和Gradio干扰构建一个简单的聊天机器人。您将能够使用类似的技术在 5 分钟内开发和自定义您自己的应用程序。
在线工具推荐:3D数字孪生场景编辑器 - GLTF/GLB材质纹理编辑器 - 3D模型在线转换 - Three.js AI自动纹理开发包 - YOLO 虚幻合成数据生成器 - 三维模型预览图生成器
1. 创建新空间
- 转到 hf.co 并创建一个免费帐户。之后,单击右上角的显示图像,然后选择“新空间”选项。
- 在表单中填写应用程序名称、许可证、空间硬件和可见性。
- 按“创建空间”以初始化应用程序。
- 您可以克隆存储库并从本地系统推送文件,或者使用浏览器在拥抱脸上创建和编辑文件。
图片来自AI ChatBot
2.创建聊天机器人应用程序文件
我们将单击“文件”选项卡>+添加文件>创建新文件。
创建 Gradio 接口。你可以复制我的代码。
我已经加载了“microsoft/dialopGPT-large”标记器和模型,并创建了一个“预测”函数来获取响应和创建历史记录。
from transformers import AutoModelForCausalLM, AutoTokenizer
import gradio as gr
import torch
title = "🤖AI ChatBot"
description = "A State-of-the-Art Large-scale Pretrained Response generation model (DialoGPT)"
examples = [["How are you?"]]
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-large")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-large")
def predict(input, history=[]):
# tokenize the new input sentence
new_user_input_ids = tokenizer.encode(
input + tokenizer.eos_token, return_tensors="pt"
)
# append the new user input tokens to the chat history
bot_input_ids = torch.cat([torch.LongTensor(history), new_user_input_ids], dim=-1)
# generate a response
history = model.generate(
bot_input_ids, max_length=4000, pad_token_id=tokenizer.eos_token_id
).tolist()
# convert the tokens to text, and then split the responses into lines
response = tokenizer.decode(history[0]).split("<|endoftext|>")
# print('decoded_response-->>'+str(response))
response = [
(response[i], response[i + 1]) for i in range(0, len(response) - 1, 2)
] # convert to tuples of list
# print('response-->>'+str(response))
return response, history
gr.Interface(
fn=predict,
title=title,
description=description,
examples=examples,
inputs=["text", "state"],
outputs=["chatbot", "state"],
theme="finlaymacklon/boxy_violet",
).launch()
此外,我还为我的应用程序提供了一个自定义主题:boxy_violet。您可以浏览Gradio主题库,根据您的口味选择主题。
3. 创建需求文件
现在,我们需要创建一个“需求.txt”文件并添加所需的 Python 包。
transformers
torch
之后,您的应用程序将开始构建,并在几分钟内下载模型并加载模型推理。
4. Gradio 演示
Gradio应用程序看起来很棒。我们只需要为每个不同的模型架构师创建一个“预测”函数,以获得响应并维护历史记录。
您现在可以在kingabzpro / AI-ChatBot上与应用程序聊天和互动,或使用 https://kingabzpro-ai-chatbot.hf.space 将您的应用程序嵌入您的网站。
你还在困惑吗?在 Spaces 上查找数百个聊天机器人应用程序,以获得灵感并了解模型推理。
例如,如果您有一个在“LLaMA-7B”上微调的模式。搜索模型并向下滚动以查看模型的各种实现。
结论
总之,本博客提供了一个快速简便的教程,介绍如何在短短 5 分钟内使用 Hugging Face 和 Gradio 创建 AI 聊天机器人。通过分步说明和可自定义的选项,任何人都可以轻松创建他们的聊天机器人。
这很有趣,我希望你学到了一些东西。请在评论部分分享您的Gradio演示。如果您正在寻找更简单的解决方案,请查看OpenChat:在几分钟内构建自定义聊天机器人的免费和简单平台。
由3D建模学习工作室 整理翻译,转载请注明出处!