当前位置: 首页 > news >正文

详细介绍:小杰-大模型(twelve)——大模型部署与应用——gradipo-实现UI界面

对话机器人gradio

gradio 介绍

Gradio 是一个简单易用的 Python 库,能够帮助开发者快速搭建用户友好的 Web 应用,特别适合用于机器学习模型的展示。本课程将使用 Gradio 来搭建一个可以与 FastAPI 后端交互的对话机器人。

Gradio 组件讲解

首先介绍 Gradio 的核心组件,包括:

  • Gradio Blocks:用于组织界面布局的容器。
  • Slider:用于调整生成参数,如 temperature 和 top_p。
  • Textbox:用户输入对话的地方。
  • Button:发送用户输入或清空历史记录。
  • Chatbot:用于显示对话历史的组件。

安装gradio

pip install gradio==5.25.2 -i https://pypi.tuna.tsinghua.edu.cn/simple

导入依赖库

import gradio as gr
import requests

定义后端 API 的 URL

backend_url = "http://127.0.0.1:6606/chat"

定义与后端交互的函数

  • prompt:用户的输入。
  • sys_prompt:系统提示语(可用于引导模型行为)。
  • history:保存对话历史记录的变量。
  • temperature:用于控制生成的多样性,数值越高,生成的文本越随机。
  • top_p:用于控制采样的多样性。
  • max_tokens:最大生成文本的长度。
  • stream:是否启用流式输出。
def chat_with_backend(prompt, sys_prompt, history, history_len, temperature, top_p, max_tokens, stream):# 构建请求数据data = {"query": prompt,"sys_prompt": sys_prompt,"history_len": history_len,"history": history,"temperature": temperature,"top_p": top_p,"max_tokens": max_tokens,}# 发送请求到 FastAPI 后端try:response = requests.post(backend_url, json=data, stream=True)if response.status_code == 200:chunks = ""if stream:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):if chunk:chunks += chunkchat_history_display = [(entry["role"], entry["content"]) for entry in history]chat_history_display.append(("user", prompt))chat_history_display.append(("assistant", chunks))# # 体验流式输出# sleep(0.1)yield chat_history_display, gr.update(value='')else:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):chunks += chunkchat_history_display = [(entry["role"], entry["content"]) for entry in history]chat_history_display.append(("user", prompt))chat_history_display.append(("assistant", chunks))yield chat_history_display, gr.update(value='')history.append({"role": "user", "content": prompt})history.append({"role": "assistant", "content": chunks})else:return "请求失败,请检查后台服务器是否正常运行。"except Exception as e:return f"发生错误:{e}"

清空对话历史

此函数用于清空当前的对话历史记录。

def clear_history(history):history.clear()return "", ""

autodl vllm方式

使用 Gradio 搭建前端界面

gr.Blocks()表示页面的容器,gr.Row()表示一行,两个gr.Row()表示分成了两行,在第二行
使用gr.Column分成了两列,scale用来控制两列的占比。第二列中又被分为两行,第一行显示聊天记录(聊天窗)
,第二行用来显示输入框等组件。clear_button和submit_button分别是两个按钮组件,用于清空历史和发送。
点击clear_button将运行clear_history函数,输入参数是history,输出是chatbot, prompt(清空聊天窗和输入框),
点击submit_button将运行chat_with_backend函数,输入参数是prompt, sys_prompt, history, history_len, temperature, top_p, max_tokens, stream,
输出是chatbot, prompt(更新聊天窗,清空输入框)。
history = gr.State([])记录对话状态。

import  gradio as gr
import  requests
# 定义后台的fastapi的URL
backend_url = "http://127.0.0.1:6067/chat"
def chat_with_backend(prompt, history, sys_prompt, history_len, temperature, top_p, max_tokens, stream):# history:["role": "user", "metadata":{'title':None},"content":"xxxx"],去掉metadata字段history_none_meatdata = [{"role": h.get("role"), "content": h.get("content")} for h in history]# 构建请求的数据data = {"query": prompt,"sys_prompt": sys_prompt,"history": history_none_meatdata,"history_len": history_len,"temperature": temperature,"top_p": top_p,"max_tokens": max_tokens}response = requests.post(backend_url, json=data, stream=True)if response.status_code == 200:chunks = ""if stream:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):chunks += chunkyield chunkselse:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):chunks += chunkyield chunks
# 使用gr.Blocks创建一个块,并设置可以填充高度和宽度
with gr.Blocks(fill_width=True,fill_height=True) as demo:# 创建一个标签页with gr.Tab(" 聊天机器人"):#添加标题gr.Markdown("##  聊天机器人")# 创建一个行布局with gr.Row():# 创一个左侧的列布局with gr.Column(scale=1,variant="panel") as sidebar_left:sys_prompt=gr.Textbox(label="系统提示词", value="You are a helpful assistant")history_len=gr.Slider(minimum=1,maximum=10,value=1, label="保留历史对话的数量")temperature=gr.Slider(minimum=0.01, maximum=2.0, value=0.5, step=0.01, label="temperature")top_p = gr.Slider(minimum=0.01, maximum=1.0, value=0.5, step=0.01, label="top_p")max_tokens = gr.Slider(minimum=512, maximum=4096, value=1024, step=8, label="max_tokens")stream = gr.Checkbox(label="stream", value=True)#创建右侧的布局,设置比例为20with gr.Column(scale=10) as main:# 创建聊天机器人的聊天界面,高度为500pxchatbot=gr.Chatbot(type="messages",height=500)# 创建chatinterface, 用于处理聊天的逻辑gr.ChatInterface(fn=chat_with_backend,type='messages',chatbot=chatbot,additional_inputs=[sys_prompt,history_len,temperature,top_p,max_tokens,stream])
demo.launch()

启动聊天

FastAPI端

from fastapi import FastAPI, Body
# pip install opeai==1.93.0
from openai import AsyncOpenAI
from typing import List
from fastapi.responses import StreamingResponse
# 初始化FastAPI应用
app = FastAPI()
# 初始化openai的客户端
api_key = "EMPTY"
base_url = "http://127.0.0.1:10222/v1"
aclient = AsyncOpenAI(api_key=api_key, base_url=base_url)
# 初始化对话列表
messages = []
# 定义路由,实现接口对接
@app.post("/chat")
async def chat(query: str = Body(..., description="用户输入"),sys_prompt: str = Body("你是一个有用的助手。", description="系统提示词"),history: List = Body([], description="历史对话"),history_len: int = Body(1, description="保留历史对话的轮数"),temperature: float = Body(0.5, description="LLM采样温度"),top_p: float = Body(0.5, description="LLM采样概率"),max_tokens: int = Body(None, description="LLM最大token数量")
):global messages# 控制历史记录长度if history_len > 0:history = history[-2 * history_len:]# 清空消息列表messages.clear()messages.append({"role": "system", "content": sys_prompt})# 在message中添加历史记录messages.extend(history)# 在message中添加用户的promptmessages.append({"role": "user", "content": query})# 发送请求response = await aclient.chat.completions.create(model="Qwen2___5-0___5B-Instruct",messages=messages,max_tokens=max_tokens,temperature=temperature,top_p=top_p,stream=True)# 响应流式输出并返回async def generate_response():async for chunk in response:chunk_msg = chunk.choices[0].delta.contentif chunk_msg:yield chunk_msg# 流式的响应fastapi的客户端return StreamingResponse(generate_response(), media_type="text/plain")
if __name__ == "__main__":import uvicornuvicorn.run(app, host="127.0.0.1", port=6066, log_level="info")

启动vllm

python -m vllm.entrypoints.openai.api_server --port 10222 --model /root/models/Qwen/Qwen2___5-0___5B-Instruct --served-model-name Qwen2___5-0___5B-Instruct

启动fastapi

python chatbot_fastapi.py

启动webui

python chatbot_gradio.py

本地的

前端程序+fastapi+ollama大模型

前端界面程序

import  gradio as gr
import  requests
# 定义后台的fastapi的URL
backend_url = "http://127.0.0.1:6067/chat"
def chat_with_backend(prompt, history, sys_prompt, history_len, temperature, top_p, max_tokens, stream):# history:["role": "user", "metadata":{'title':None},"content":"xxxx"],去掉metadata字段history_none_meatdata = [{"role": h.get("role"), "content": h.get("content")} for h in history]# 构建请求的数据data = {"query": prompt,"sys_prompt": sys_prompt,"history": history_none_meatdata,"history_len": history_len,"temperature": temperature,"top_p": top_p,"max_tokens": max_tokens}response = requests.post(backend_url, json=data, stream=True)if response.status_code == 200:chunks = ""if stream:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):chunks += chunkyield chunkselse:for chunk in response.iter_content(chunk_size=None, decode_unicode=True):chunks += chunkyield chunks
# 使用gr.Blocks创建一个块,并设置可以填充高度和宽度
with gr.Blocks(fill_width=True,fill_height=True) as demo:# 创建一个标签页with gr.Tab(" 聊天机器人"):#添加标题gr.Markdown("##  聊天机器人")# 创建一个行布局with gr.Row():# 创一个左侧的列布局with gr.Column(scale=1,variant="panel") as sidebar_left:sys_prompt=gr.Textbox(label="系统提示词", value="You are a helpful assistant")history_len=gr.Slider(minimum=1,maximum=10,value=1, label="保留历史对话的数量")temperature=gr.Slider(minimum=0.01, maximum=2.0, value=0.5, step=0.01, label="temperature")top_p = gr.Slider(minimum=0.01, maximum=1.0, value=0.5, step=0.01, label="top_p")max_tokens = gr.Slider(minimum=512, maximum=4096, value=1024, step=8, label="max_tokens")stream = gr.Checkbox(label="stream", value=True)#创建右侧的布局,设置比例为20with gr.Column(scale=10) as main:# 创建聊天机器人的聊天界面,高度为500pxchatbot=gr.Chatbot(type="messages",height=500)# 创建chatinterface, 用于处理聊天的逻辑gr.ChatInterface(fn=chat_with_backend,type='messages',chatbot=chatbot,additional_inputs=[sys_prompt,history_len,temperature,top_p,max_tokens,stream])
demo.launch()
fastapi+ollama大模型
from fastapi import FastAPI, Body
# pip install opeai==1.93.0
from openai import AsyncOpenAI
from typing import List
from fastapi.responses import StreamingResponse
# 初始化FastAPI应用
app = FastAPI()
# 初始化openai的客户端
api_key = "EMPTY"
base_url = "http://127.0.0.1:11434/v1"
aclient = AsyncOpenAI(api_key=api_key, base_url=base_url)
# 初始化对话列表
messages = []
# 定义路由,实现接口对接
@app.post("/chat")
async def chat(query: str = Body(..., description="用户输入"),sys_prompt: str = Body("你是一个有用的助手。", description="系统提示词"),history: List = Body([], description="历史对话"),history_len: int = Body(1, description="保留历史对话的轮数"),temperature: float = Body(0.5, description="LLM采样温度"),top_p: float = Body(0.5, description="LLM采样概率"),max_tokens: int = Body(None, description="LLM最大token数量")
):global messages# 控制历史记录长度if history_len > 0:history = history[-2 * history_len:]# 清空消息列表messages.clear()messages.append({"role": "system", "content": sys_prompt})# 在message中添加历史记录messages.extend(history)# 在message中添加用户的promptmessages.append({"role": "user", "content": query})# 发送请求response = await aclient.chat.completions.create(model="qwen2.5:0.5b",messages=messages,max_tokens=max_tokens,temperature=temperature,top_p=top_p,stream=True)# 响应流式输出并返回async def generate_response():async for chunk in response:chunk_msg = chunk.choices[0].delta.contentif chunk_msg:yield chunk_msg# 流式的响应fastapi的客户端return StreamingResponse(generate_response(), media_type="text/plain")
if __name__ == "__main__":import uvicornuvicorn.run(app, host="127.0.0.1", port=6067, log_level="info")

ollama启动本地大模型

ollama serve

http://icebutterfly214.com/news/83774/

相关文章:

  • 详细介绍:轻量级云原生体验:在OpenEuler 25.09上快速部署单节点K3s
  • 挖矿病毒分析
  • 模块会根据自学习到的权重对各输入进行加权组合,再经过卷积、BN和激活函数等进一步处理,形成新的融合特征图,是BiFPN内部的核心机制
  • 2025年贵州装修公司如何选?这份深度评测报告给你答案
  • lambda函数的特性
  • 祝贺朱雀三号首飞成功入轨!国产时序数据库 IoTDB 助力火箭试验
  • 53(12.5)
  • Spring两大特性 AOP和IOC
  • 2025年专业新闻发稿公司推荐:高性价比平台评估与深度解析
  • 2025年12月广东佛山琉璃瓦/青瓦源头厂家深度解析:如何选择靠谱供应商避坑指南
  • 2025年目前最好的微动开关供货商有哪些,汽车微动开关/新能源微动开关/大电流微动开关/小型微动开关/家电微动开关供货商怎么选择
  • ToDesk 360帧超高清远程控制,开启游戏与应用中心抢先体验!
  • 2025汽车脚垫五大品牌权威推荐:深度测评指南,卡骐盾TPE
  • Rufus 下载安装教程(2025 最新版):最简单的U盘启动盘制作指南 | 超详细步骤
  • pbootcms文章插入图片取消最大只有1000宽度
  • 2025年深圳夹爪供应商哪家好?品牌选择指南
  • html 和css基础常用的标签和样式(2)-css - 实践
  • 计算粗心马虎纠正初中数学辅导精选:从根源培养严谨习惯,有效减少不必要的失分
  • 普通莫队板子
  • 2025年N2氮气发泡罐批发厂家权威推荐榜单:鞋底中底发泡罐/体育器材发泡罐/高压发泡罐源头厂家精选
  • AI真的太好用啦!Aspire Dashboard集成GitHub Copilot。
  • 2025年度不锈钢衣柜加盟TOP5权威推荐:甄选代理项目抢占
  • 最大似然优化与交叉熵(CE)多高斯混合估计算法的应用
  • 2025年下半年江苏徐州工业吊扇厂家综合推荐榜单
  • 助力科研|EnergyPlus-MCP与vscode的联动
  • 2025年苏州地区咖啡培训优质中心推荐,靠谱的咖啡培训学校全
  • Lasso算法在数据挖掘中的深入解析与MATLAB实现
  • 高性价比家政服务公司推荐,广州喜相缘家政实力上榜
  • 从结构化到多模态,AI 时代如何利用多模态数据智能中台激活业务价值?
  • 2025 年陶瓷喷涂源头厂家最新推荐榜,聚焦技术实力与市场口碑深度解析涡轮叶片陶瓷喷涂/半导体腔体陶瓷喷涂/锅炉管道耐高温陶瓷喷涂/阀门陶瓷喷涂公司推荐