深圳市升华建设有限公司网站,简单旅游网站模板下载,视频外链平台,淘宝网站建设的特点大模型WebUI#xff1a;Gradio全解11——Chatbots#xff1a;融合大模型的聊天机器人#xff08;2#xff09; 前言本篇摘要11. Chatbot#xff1a;融合大模型的多模态聊天机器人11.2 使用流行的LLM库和API11.2.1 Llama Index11.2.2 LangChain11.2.3 OpenAI1. 基本用法2. … 大模型WebUIGradio全解11——Chatbots融合大模型的聊天机器人2 前言本篇摘要11. Chatbot融合大模型的多模态聊天机器人11.2 使用流行的LLM库和API11.2.1 Llama Index11.2.2 LangChain11.2.3 OpenAI1. 基本用法2. 语音聊天3. Twilio凭据4. 自定义Interface 11.2.4 Hugging Face transformers11.2.5 SambaNova11.2.6 Hyperbolic11.2.7 Anthropic Claude 参考文献 前言
本系列文章主要介绍WEB界面工具Gradio。Gradio是Hugging Face发布的简易webui开发框架它基于FastAPI和svelte便于开发多功能界面和部署人工智能模型是当前热门的非常易于开发和展示机器学习大语言模型LLM及扩散模型DM的UI框架。本系列文章分为前置概念和实战演练两部分。前置概念先介绍Gradio的详细技术架构、历史、应用场景、与其他框架Gradio/NiceGui/StreamLit/Dash/PyWebIO的区别然后详细介绍了著名的资源网站Hugging Face因为Gradio演示中经常用到Hugging Face的models及某些场景需要部署在spaces这里包括三类资源models/datasets/spaces的使用、六类工具库transformers/diffusers/datasets/PEFT/accelerate/optimum实战。实战演练部分先讲解了多种不同的安装、运行和部署方式安装包括Linux/Win/Mac三类系统安装运行包括普通方式和热重载方式部署包括本地部署、HuggingFace托管、FastAPI挂载和Gradio-Lite浏览器集成然后按照先整体再细节的逻辑讲解Gradio的多种高级特性包括三种Gradio Clientspython/javascript/curl、Gradio Tools、Gradio的模块架构和环境变量等方便读者对Gradio整体把握最后深入细节也是本系列文章的核心先实践基础功能Interface、Blocks和Additional Features再详解高级功能Chatbots、Data Science And Plots和Streaming。本系列文章讲解细致涵盖Gradio大部分组件和功能代码均可运行并附有大量运行截图方便读者理解Gradio一定会成为每个技术人员实现奇思妙想的最称手工具。
本系列文章目录如下
《Gradio全解1——Gradio简介》《Gradio全解1——Gradio的安装与运行》《Gradio全解2——剖析Hugging Face详解三类资源models/datasets/spaces》《Gradio全解3——剖析Hugging Face实战六类工具库transformers/diffusers/datasets/PEFT/accelerate/optimum》《Gradio全解4——Gradio的31种部署方式实践》《Gradio全解4——浏览器集成Gradio-Lite》《Gradio全解5——Gradio Clientpython客户端》《Gradio全解5——Gradio Clientjavascript客户端》《Gradio全解5——Gradio Clientcurl客户端》《Gradio全解6——Gradio Tools将Gradio用于LLM Agents》《Gradio全解7——Gradio库的模块架构和环境变量》《Gradio全解8——Interface高级抽象界面类上》《Gradio全解8——Interface高级抽象界面类下》《Gradio全解9——Blocks底层区块类上》《Gradio全解9——Blocks底层区块类下》《Gradio全解10——Additional Features补充特性上》《Gradio全解10——Additional Features补充特性下》《Gradio全解11——Chatbot融合大模型的多模态聊天机器人上》《Gradio全解11——Chatbot融合大模型的多模态聊天机器人下》《Gradio全解系列12——Data Science And Plots数据科学与绘图》《Gradio全解13——Streaming数据流上》《Gradio全解13——Streaming数据流下》
本篇摘要
本篇介绍如何使用Gradio创建聊天机器人主要内容包括gr.ChatInterface快速创建Chatbot、与流行LLM库及API结合、使用Agents和Tools智能代理工具、使用Blocks创建Chatbot、Chatbot的特殊Events、通过Gradio应用创建Discord Bot/Slack Bot/Website Widget。
11. Chatbot融合大模型的多模态聊天机器人
本章介绍如何使用Gradio创建聊天机器人。聊天机器人是大型语言模型LLMs的一个流行应用通过Gradio我们可以轻松构建LLM演示并与其它用户分享或者自己使用直观的聊天机器人界面进行开发尝试。本章主要内容包括gr.ChatInterface快速创建Chatbot、与流行LLM库及API结合、使用Agents和Tools智能代理工具、使用Blocks创建Chatbot、Chatbot的特殊Events、通过Gradio应用创建Discord Bot/Slack Bot/Website Widget。
11.2 使用流行的LLM库和API
在本节中我们将通过几个示例展示如何将gr.ChatInterface与流行的LLM库和API提供商一起使用将涵盖以下库和API提供商
Llama IndexLangChainOpenAIHugging Face transformersSambaNovaHyperbolicAnthropic’s Claude
大部分LLM库和提供商都存在社区维护的集成库这使得启动Gradio应用程序更加容易。我们将在下面的适当部分中引用这些库下面逐一介绍它们的用法。
11.2.1 Llama Index
让我们从在OpenAI上使用llama-index开始构建一个RAG聊天机器人。该机器人可以在任意文本或 PDF文件上运行并且可以在不到30行代码中演示和分享它。此示例需要OpenAI密钥请继续阅读以获取免费的开源等效方案代码如下
# This is a simple RAG chatbot built on top of Llama Index and Gradio. It allows you to upload any text or PDF files and ask questions about them!
# Before running this, make sure you have exported your OpenAI API key as an environment variable:
# export OPENAI_API_KEYyour-openai-api-keyfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReader
import gradio as grdef answer(message, history):files []for msg in history:if msg[role] user and isinstance(msg[content], tuple):files.append(msg[content][0])for file in message[files]:files.append(file)documents SimpleDirectoryReader(input_filesfiles).load_data()index VectorStoreIndex.from_documents(documents)query_engine index.as_query_engine()return str(query_engine.query(message[text]))demo gr.ChatInterface(answer,typemessages,titleLlama Index RAG Chatbot,descriptionUpload any text or pdf files and ask questions about them!,textboxgr.MultimodalTextbox(file_types[.pdf, .txt]),multimodalTrue
)demo.launch()运行界面如下 注意
需要安装包llama_index受限于未知原因有些代码作者难以运行出结果请读者将重点放在理解代码下同如果未设置OPENAI_API_KEY提交文档后会在后台报错Original error:No API key found for OpenAI。OPENAI_API_KEY获取地址https://platform.openai.com/account/api-keys使用OPENAI、Google或Microsoft注册账号登录后创建某组织可随意填写并跳过邀请成员后即可获得。然后在运行环境中键入命令export OPENAI_API_KEY“your-openai-api-key”如果设置后还遇到401认证错误可能是因为OpenAI API客户端无法从环境变量中获取API令牌。此时可以将其保存到Python会话中或者在代码界面运行
import os
os.environ[OPENAI_API_KEY] 11.2.2 LangChain
以下是一个在OpenAI上使用langchain构建通用聊天机器人的示例。与之前一样此示例需要OpenAI 密钥。
# This is a simple general-purpose chatbot built on top of LangChain and Gradio.
# Before running this, make sure you have exported your OpenAI API key as an environment variable:
# export OPENAI_API_KEYyour-openai-api-keyfrom langchain_openai import ChatOpenAI
from langchain.schema import AIMessage, HumanMessage
import gradio as grmodel ChatOpenAI(modelgpt-4o-mini)def predict(message, history):history_langchain_format []for msg in history:if msg[role] user:history_langchain_format.append(HumanMessage(contentmsg[content]))elif msg[role] assistant:history_langchain_format.append(AIMessage(contentmsg[content]))history_langchain_format.append(HumanMessage(contentmessage))gpt_response model.invoke(history_langchain_format)return gpt_response.contentdemo gr.ChatInterface(predict,typemessages
)demo.launch()运行界面如下 提示本例需安装langchain_openai和langchain。另外对于快速原型设计社区维护的langchain-gradio仓库使得在LangChain上构建聊天机器人变得更加容易。
11.2.3 OpenAI
当然我们也可以直接使用openai库但对于快速原型设计openai-gradio库使得在OpenAI模型上构建聊天机器人更加容易。openai-gradio是一个 Python包它使开发者能够非常轻松地创建由OpenAI API驱动的机器学习应用程序。
1. 基本用法
使用以下命令安装openai-gradio
pip install openai-gradio同样需要设置OPENAI_API_KEY然后就可以通过几行代码完成聊天机器人程序
import gradio as gr
import openai_gradiogr.load(namegpt-4-turbo,srcopenai_gradio.registry,
).launch()运行后就可以看到连接到OpenAI模型的Gradio界面 底层原理openai-gradio Python库有两个依赖项openai和gradio它定义了一个“注册”函数 openai_gradio.registry该函数接收一个模型名称并返回一个Gradio应用。
2. 语音聊天
OpenAI-Gradio还支持语音聊天功能。我们可以通过以下两种方式启用该功能
使用实时模型
import gradio as gr
import openai_gradiogr.load(namegpt-4o-realtime-preview-2024-10-01,srcopenai_gradio.registry
).launch()显式地使用任意实时模型
import gradio as gr
import openai_gradiogr.load(namegpt-4o-mini-realtime-preview-2024-12-17,srcopenai_gradio.registry,enable_voiceTrue
).launch()这将创建一个基于WebRTC的界面允许与AI模型进行实时语音对话。
3. Twilio凭据
为了实现语音聊天功能除了OPENAI_API_KEY还需要Twilio凭据WebRTC语音聊天所需
export TWILIO_ACCOUNT_SIDyour Twilio account SID
export TWILIO_AUTH_TOKENyour Twilio auth token我们可以通过以下方式获取Twilio的凭证
在 Twilio 上创建一个免费账户地址https://www.twilio.com/en-us在 Twilio 控制台中获取 Account SID 和 Auth Token。 如果没有Twilio凭证语音聊天功能仍然可以工作但在某些网络环境中可能会遇到连接问题。
4. 自定义Interface
一旦我们可以通过OpenAI端点创建一个Gradio用户界面就可以通过设置自己的输入和输出组件或任何其他gr.Interface参数来自定义它。演示代码如下
import gradio as gr
import openai_gradiogr.load(namegpt-4-turbo,srcopenai_gradio.registry,titleOpenAI-Gradio Integration,descriptionChat with GPT-4-turbo model.,examples[Explain quantum gravity to a 5-year old., How many R are there in the word Strawberry?]
).launch()运行截图如下 或者将加载的Interface组合到更大的Gradio Web用户界面中例如
import gradio as gr
import openai_gradiowith gr.Blocks() as demo:with gr.Tab(GPT-4-turbo):gr.load(gpt-4-turbo, srcopenai_gradio.registry)with gr.Tab(GPT-3.5-turbo):gr.load(gpt-3.5-turbo, srcopenai_gradio.registry)demo.launch()OpenAI支持的所有聊天API模型都与该集成兼容。有关可用模型及其详细信息的完整列表请参阅 OpenAI模型文档https://platform.openai.com/docs/models。
11.2.4 Hugging Face transformers
在许多情况下我们可能希望在本地运行聊天机器人。以下是使用Hugging Face transformers库和 SmolLM2-135M-Instruct模型的等效示例
from transformers import AutoModelForCausalLM, AutoTokenizer
import gradio as grcheckpoint HuggingFaceTB/SmolLM2-135M-Instruct
device cpu # cuda or cpu
tokenizer AutoTokenizer.from_pretrained(checkpoint)
model AutoModelForCausalLM.from_pretrained(checkpoint).to(device)def predict(message, history):history.append({role: user, content: message})input_text tokenizer.apply_chat_template(history, tokenizeFalse)inputs tokenizer.encode(input_text, return_tensorspt).to(device) outputs model.generate(inputs, max_new_tokens100, temperature0.2, top_p0.9, do_sampleTrue)decoded tokenizer.decode(outputs[0])response decoded.split(|im_start|assistant\n)[-1].split(|im_end|)[0]return responsedemo gr.ChatInterface(predict, typemessages)demo.launch()运行截图如下
11.2.5 SambaNova
SambaNova Cloud API提供了对全精度开源模型例如Llama系列的访问权限。以下是一个围绕SambaNova API构建Gradio应用的示例注意这里需要设置SAMBANOVA_API_KEY申请地址https://sambanova.ai/
# This is a simple general-purpose chatbot built on top of SambaNova API.
# Before running this, make sure you have exported your SambaNova API key as an environment variable:
# export SAMBANOVA_API_KEYyour-sambanova-api-keyimport os
import gradio as gr
from openai import OpenAIapi_key os.getenv(SAMBANOVA_API_KEY)client OpenAI(base_urlhttps://api.sambanova.ai/v1/,api_keyapi_key,
)def predict(message, history):history.append({role: user, content: message})stream client.chat.completions.create(messageshistory, modelMeta-Llama-3.1-70B-Instruct-8k, streamTrue)chunks []for chunk in stream:chunks.append(chunk.choices[0].delta.content or )yield .join(chunks)demo gr.ChatInterface(predict, typemessages)demo.launch()提示对于快速原型设计sambanova-gradio库使得在SambaNova模型上构建聊天机器人变得更加容易。
11.2.6 Hyperbolic
Hyperbolic AI API提供了对许多开源模型例如Llama系列的访问权限。以下是一个通过SambaNova API构建Gradio应用的示例这里同样需要设置HYPERBOLIC_API_KEY
# This is a simple general-purpose chatbot built on top of Hyperbolic API.
# Before running this, make sure you have exported your Hyperbolic API key as an environment variable:
# export HYPERBOLIC_API_KEYyour-hyperbolic-api-keyimport os
import gradio as gr
from openai import OpenAIapi_key os.getenv(HYPERBOLIC_API_KEY)client OpenAI(base_urlhttps://api.hyperbolic.xyz/v1/,api_keyapi_key,
)def predict(message, history):history.append({role: user, content: message})stream client.chat.completions.create(messageshistory, modelgpt-4o-mini, streamTrue)chunks []for chunk in stream:chunks.append(chunk.choices[0].delta.content or )yield .join(chunks)demo gr.ChatInterface(predict, typemessages)demo.launch()提示对于快速原型设计hyperbolic-gradio库使得在Hyperbolic模型上构建聊天机器人变得更加容易。
11.2.7 Anthropic Claude
Anthropic的Claude模型也可以通过API使用。以下是一个基于Anthropic API构建的简单20个问题风格的游戏示例
# This is a simple 20 questions-style game built on top of the Anthropic API.
# Before running this, make sure you have exported your Anthropic API key as an environment variable:
# export ANTHROPIC_API_KEYyour-anthropic-api-keyimport anthropic
import gradio as grclient anthropic.Anthropic()def predict(message, history):keys_to_keep [role, content]history [{k: d[k] for k in keys_to_keep if k in d} for d in history]history.append({role: user, content: message})if len(history) 20:history.append({role: user, content: DONE})output client.messages.create(messageshistory, modelclaude-3-5-sonnet-20241022,max_tokens1000,systemYou are guessing an object that the user is thinking of. You can ask 10 yes/no questions. Keep asking questions until the user says DONE)return {role: assistant,content: output.content[0].text, options: [{value: Yes}, {value: No}]}placeholder
centerh110 Questions/h1brThink of a person, place, or thing. Ill ask you 10 yes/no questions to try and guess it.
/center
demo gr.ChatInterface(predict,examples[Start!],chatbotgr.Chatbot(placeholderplaceholder),typemessages
)demo.launch()参考文献
Gradio - guides - Additional Featuresopenai-gradio