教程|Hugging Face Spaces 免费部署 AI Demo:3 分钟上线
本教程演示如何在 Hugging Face Spaces 上免费部署 AI Demo。
Spaces 是什么
- CPU 基础:免费
- GPU T4:免费 2 小时/天
- GPU A10G:$0.6/小时
- 支持 Gradio / Streamlit / Docker
第 1 步:写 app.py
import gradio as gr
from transformers import pipeline
generator = pipeline("text-generation", model="Qwen/Qwen2.5-7B-Instruct")
def respond(message, history):
messages = []
for h in history[-5:]:
messages.append({"role": "user", "content": h[0]})
if h[1]:
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": message})
output = generator(messages, max_new_tokens=512)
return output[0]["generated_text"][-1]["content"]
demo = gr.ChatInterface(respond, title="Qwen 2.5 聊天")
demo.launch()
第 2 步:写 README.md
---
title: Qwen 2.5 Chat
emoji: 🤖
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: 5.0.0
app_file: app.py
pinned: false
license: mit
---
第 3 步:推到 HF Space
# 1. 在 huggingface.co/new-space 创建 Space
# 2. 克隆
git clone https://huggingface.co/spaces/yourname/qwen-chat
cd qwen-chat
cp ../app.py . && cp ../README.md .
git add . && git commit -m "init"
git push
# 5-10 分钟后 Space 自动 build
第 4 步:升级到 GPU
hardware: t4-small # 免费 T4
第 5 步:secrets
import os
api_key = os.environ["OPENAI_API_KEY"] # 自动注入