# Gradio 快速入门指南 > 📚 专为 HR 智能助手项目编写的 Web 界面开发指南 > 📅 最后更新:2026-03-16 > 👨💻 作者:小小叶 > 🎯 适合人群:Python 开发者,想快速给项目加 Web 界面 --- ## 📖 目录 1. [Gradio 是什么](#1-gradio-是什么) 2. [为什么选择 Gradio](#2-为什么选择-gradio) 3. [快速安装](#3-快速安装) 4. [10 分钟快速开始](#4-10-分钟快速开始) 5. [HR 助手实战](#5-hr-助手实战) 6. [常用组件大全](#6-常用组件大全) 7. [部署上线](#7-部署上线) 8. [最佳实践](#8-最佳实践) 9. [常见问题](#9-常见问题) 10. [参考资料](#10-参考资料) --- ## 1. Gradio 是什么 **Gradio** 是一个开源的 Python 库,用于快速创建机器学习模型的 Web 界面。 ### 核心特点: - ✅ **纯 Python** - 不需要 HTML/CSS/JavaScript - ✅ **快速开发** - 几行代码就能创建界面 - ✅ **美观默认** - 内置现代化 UI 主题 - ✅ **易于分享** - 一键生成可分享链接 - ✅ **高度可定制** - 支持自定义布局和样式 ### 适用场景: - 🎯 AI 模型 Demo 展示 - 🎯 数据可视化工具 - 🎯 内部工具快速开发 - 🎯 教学演示 - 🎯 作品集展示 --- ## 2. 为什么选择 Gradio ### 与其他方案对比: | 方案 | 学习成本 | 开发时间 | 美观度 | 推荐度 | |------|---------|---------|--------|--------| | **Gradio** | ⭐ | 1 小时 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Streamlit** | ⭐⭐ | 2 小时 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Flask + HTML** | ⭐⭐⭐⭐ | 1 天 | ⭐⭐⭐ | ⭐⭐⭐⭐ | | **Vue/React** | ⭐⭐⭐⭐⭐ | 1 周 + | ⭐⭐⭐⭐⭐ | ⭐⭐ | ### Gradio 的优势: 1. **代码量极少** - 50 行代码搞定一个完整界面 2. **零前端知识** - 只需要会 Python 3. **内置组件丰富** - 文本框、按钮、滑块、图表等 4. **自动适配移动端** - 响应式设计 5. **支持实时交互** - 输入后自动更新结果 --- ## 3. 快速安装 ### 基础安装: ```bash pip install gradio ``` ### 指定版本(推荐最新稳定版): ```bash pip install gradio==4.20.0 ``` ### 验证安装: ```bash python -c "import gradio as gr; print(gr.__version__)" ``` ### 国内加速: ```bash pip install gradio -i https://pypi.tuna.tsinghua.edu.cn/simple ``` --- ## 4. 10 分钟快速开始 ### 示例 1:最简单的 Hello World ```python import gradio as gr def greet(name): return "Hello, " + name + "!" demo = gr.Interface(fn=greet, inputs="text", outputs="text") demo.launch() ``` **运行**: ```bash python app.py ``` **访问**:http://localhost:7860 --- ### 示例 2:多个输入输出 ```python import gradio as gr def calculate(a, b, operation): if operation == "加法": return a + b elif operation == "减法": return a - b elif operation == "乘法": return a * b elif operation == "除法": return a / b if b != 0 else "除数不能为 0" demo = gr.Interface( fn=calculate, inputs=[ gr.Number(label="数字 A"), gr.Number(label="数字 B"), gr.Radio(["加法", "减法", "乘法", "除法"], label="运算") ], outputs=gr.Number(label="结果") ) demo.launch() ``` --- ### 示例 3:使用 Blocks 自定义布局 ```python import gradio as gr with gr.Blocks() as demo: gr.Markdown("# 我的应用") with gr.Row(): with gr.Column(): input1 = gr.Textbox(label="输入 1") input2 = gr.Textbox(label="输入 2") btn = gr.Button("处理", variant="primary") with gr.Column(): output = gr.Textbox(label="输出") btn.click(fn=lambda x, y: x + "\n" + y, inputs=[input1, input2], outputs=output) demo.launch() ``` --- ## 5. HR 助手实战 ### 项目结构: ``` hr-assistant/ ├── app.py # Gradio 主程序 ├── src/ │ ├── __init__.py │ ├── rag.py # RAG 检索模块 │ └── llm_client.py # LLM 调用模块 ├── knowledge_base/ # 知识库 └── data/ └── knowledge.db # 向量数据库 ``` --- ### 完整代码(app.py): ```python import gradio as gr from src.rag import RAGRetriever from src.llm_client import LLMClient # ============== 初始化组件 ============== print("🔄 正在加载 RAG 检索器...") retriever = RAGRetriever(db_path="data/knowledge.db") print("🔄 正在加载 LLM 客户端...") llm = LLMClient( api_key="你的 API 密钥", base_url="https://api.moonshot.cn/v1", model="moonshot-v1-8k" ) # ============== 核心功能 ============== def answer_question(question, top_k=3): """ 回答用户问题 Args: question: 用户问题 top_k: 检索的文档数量 Returns: answer: 回答文本 sources: 引用来源列表 """ if not question.strip(): return "⚠️ 请输入问题", [] try: # 1. RAG 检索 print(f"🔍 正在检索:{question}") contexts = retriever.search(question, top_k=top_k) if not contexts: return "❌ 抱歉,没有找到相关的资料。", [] # 2. 组装 Prompt context_text = "\n\n".join([ f"[资料{i+1}]\n{c[0]}" for i, c in enumerate(contexts) ]) prompt = f"""你是 HR 智能助手,基于以下资料回答问题。 如果资料中没有相关信息,请说"抱歉,资料中没有找到相关信息"。 {context_text} 问题:{question} 请用简洁清晰的语言回答:""" # 3. LLM 生成答案 print("🤖 正在生成答案...") answer = llm.generate(prompt) # 4. 准备引用来源 sources = [ { "来源": f"资料{i+1}", "相似度": f"{c[1]:.2f}", "内容": c[0][:200] + "..." } for i, c in enumerate(contexts) ] print("✅ 完成!") return answer, sources except Exception as e: print(f"❌ 错误:{e}") return f"出错了:{str(e)}", [] # ============== 创建界面 ============== with gr.Blocks(title="💼 HR 智能助手", theme=gr.themes.Soft()) as demo: # 标题 gr.Markdown(""" # 💼 HR 智能助手 基于 RAG 的学生手册问答系统 """) # 主布局 with gr.Row(): # 左侧:输入和输出 with gr.Column(scale=3): question_input = gr.Textbox( label="❓ 问题", placeholder="请输入你的问题,例如:宿舍管理规定是什么?", lines=3 ) with gr.Row(): submit_btn = gr.Button("🚀 提交", variant="primary") clear_btn = gr.Button("🗑️ 清空") answer_output = gr.Textbox( label="💬 回答", lines=6, show_copy_button=True ) # 示例问题 gr.Examples( examples=[ "宿舍管理规定是什么?", "考试作弊怎么处理?", "奖学金评定标准?", "请假流程是怎样的?", "毕业要求有哪些?" ], inputs=question_input ) # 右侧:设置和来源 with gr.Column(scale=2): top_k_slider = gr.Slider( minimum=1, maximum=10, value=3, step=1, label="📊 检索文档数量" ) sources_output = gr.JSON(label="📚 参考来源") # 绑定事件 submit_btn.click( fn=answer_question, inputs=[question_input, top_k_slider], outputs=[answer_output, sources_output], api_name="ask" ) clear_btn.click( fn=lambda: ("", ""), inputs=[], outputs=[question_input, answer_output] ) # ============== 启动服务 ============== if __name__ == "__main__": print("\n" + "="*50) print("✅ 服务启动成功!") print("🌐 本地访问:http://localhost:7860") print("🌐 局域网访问:http://你的 IP:7860") print("="*50) print("\n按 Ctrl+C 停止服务\n") demo.launch( server_name="0.0.0.0", # 允许外部访问 server_port=7860 ) ``` --- ### 运行: ```bash cd hr-assistant python app.py ``` ### 访问: 打开浏览器:http://localhost:7860 --- ## 6. 常用组件大全 ### 输入组件: ```python # 文本输入 gr.Textbox(label="姓名", placeholder="请输入...") gr.TextArea(label="内容", lines=5) # 数字输入 gr.Number(label="年龄", value=18) gr.Slider(minimum=0, maximum=100, value=50, label="分数") # 选择输入 gr.Radio(["男", "女"], label="性别") gr.Checkbox(label="同意条款") gr.CheckboxGroup(["A", "B", "C"], label="多选") gr.Dropdown(["选项 1", "选项 2"], label="下拉选择") # 文件输入 gr.File(label="上传文件") gr.Image(label="上传图片") gr.Audio(label="上传音频") ``` --- ### 输出组件: ```python # 文本输出 gr.Textbox(label="结果") gr.Markdown("## 标题\n内容") # 数据输出 gr.JSON(label="数据") gr.DataFrame(label="表格") # 多媒体输出 gr.Image(label="图片") gr.Audio(label="音频") gr.Video(label="视频") gr.Plot(label="图表") ``` --- ### 布局组件: ```python # 行布局 with gr.Row(): gr.Textbox() gr.Textbox() # 列布局 with gr.Column(): gr.Textbox() gr.Button() # 分组 with gr.Group(): gr.Markdown("### 分组标题") gr.Textbox() # 标签页 with gr.Tabs(): with gr.Tab("标签 1"): gr.Textbox() with gr.Tab("标签 2"): gr.Textbox() ``` --- ### 事件处理: ```python # 按钮点击 btn.click(fn=处理函数,inputs=[输入], outputs=[输出]) # 文本变化 textbox.change(fn=处理函数,inputs=[textbox], outputs=[输出]) # 滑块变化 slider.change(fn=处理函数,inputs=[slider], outputs=[输出]) # 文件上传 file.upload(fn=处理函数,inputs=[file], outputs=[输出]) # 多个事件 btn.click(fn=函数 1).then(fn=函数 2) ``` --- ## 7. 部署上线 ### 方案 1:本地运行(开发测试) ```python demo.launch() # 访问:http://localhost:7860 ``` --- ### 方案 2:局域网访问(团队使用) ```python demo.launch(server_name="0.0.0.0", server_port=7860) # 访问:http://你的 IP:7860 ``` --- ### 方案 3:Gradio 分享(临时公网) ```python demo.launch(share=True) # 生成公网链接,72 小时有效 ``` --- ### 方案 4:服务器部署(生产环境) #### 步骤 1:准备服务器 ```bash # 安装 Python 和依赖 pip install gradio # 上传代码 scp app.py user@server:/path/to/project ``` #### 步骤 2:运行服务 ```bash # 后台运行 nohup python app.py > app.log 2>&1 & # 或使用 systemd 服务 sudo systemctl start gradio-app ``` #### 步骤 3:配置 Nginx 反向代理 ```nginx server { listen 80; server_name your-domain.com; location / { proxy_pass http://localhost:7860; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } ``` --- ### 方案 5:Docker 部署 ```dockerfile FROM python:3.10-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 7860 CMD ["python", "app.py"] ``` ```bash # 构建镜像 docker build -t hr-assistant . # 运行容器 docker run -p 7860:7860 hr-assistant ``` --- ## 8. 最佳实践 ### 1. 代码组织 ```python # ✅ 好的结构 app.py # 主程序 src/ rag.py # 业务逻辑 llm.py utils/ config.py # 配置 logger.py # 日志 ``` --- ### 2. 错误处理 ```python # ✅ 好的做法 def answer_question(question): try: # 业务逻辑 return answer, sources except Exception as e: logger.error(f"错误:{e}") return f"出错了:{str(e)}", [] # ❌ 不好的做法 def answer_question(question): # 没有错误处理 return answer, sources ``` --- ### 3. 日志记录 ```python import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) def answer_question(question): logging.info(f"收到问题:{question}") # ... logging.info("回答完成") ``` --- ### 4. 性能优化 ```python # 使用缓存 from functools import lru_cache @lru_cache(maxsize=100) def search_cache(query): return retriever.search(query) # 懒加载 @gr.cache() def load_model(): return load_heavy_model() ``` --- ### 5. 用户体验 ```python # 添加加载提示 with gr.spinner("正在思考中..."): answer = generate_answer() # 添加示例 gr.Examples( examples=["示例 1", "示例 2"], inputs=input_component ) # 添加提示文本 gr.Textbox( placeholder="请输入问题...", info="支持中文和英文" ) ``` --- ## 9. 常见问题 ### Q1: 端口被占用怎么办? ```python # 换一个端口 demo.launch(server_port=7861) ``` --- ### Q2: 如何添加认证? ```python # 简单认证 demo.launch(auth=("username", "password")) # 或多个用户 demo.launch(auth={ "user1": "pass1", "user2": "pass2" }) ``` --- ### Q3: 如何自定义 CSS? ```python demo = gr.Blocks(css=""" .gr-button { background-color: #4CAF50; } .gr-textbox { border: 2px solid #2196F3; } """) ``` --- ### Q4: 如何保存对话历史? ```python import json def chat(question, history): history = history or [] answer = generate_answer(question) history.append((question, answer)) # 保存到文件 with open("history.json", "a") as f: json.dump(history, f) return history, history ``` --- ### Q5: 如何处理大文件上传? ```python gr.File( label="上传文件", file_types=[".pdf", ".md", ".txt"], max_file_size="10MB" ) ``` --- ## 10. 参考资料 ### 官方文档: - [Gradio 官网](https://gradio.app/) - [Gradio 文档](https://gradio.app/docs/) - [Gradio GitHub](https://github.com/gradio-app/gradio) ### 教程: - [Gradio 快速入门](https://gradio.app/guides/quickstart) - [Gradio Blocks 指南](https://gradio.app/guides/using-blocks) - [Gradio 部署指南](https://gradio.app/guides/deploying) ### 示例项目: - [HR 智能助手](本项目的 hr-assistant) - [Gradio 官方示例](https://gradio.app/guides/) --- ## 📝 更新日志 | 日期 | 版本 | 更新内容 | |------|------|---------| | 2026-03-16 | v1.0 | 初始版本 | --- *最后更新:2026-03-16* *维护者:小小叶 🌱*