Hugging Face Inference API 指南
Hugging Face 提供了多种方式来消费托管在 Hub 上的模型。从免费的 Serverless API 到生产级的专用端点(Endpoints),你可以根据需求选择合适的方案。
1. Serverless Inference API (免费版)
这是最快、最简单的调用模型方式。Hugging Face 预先部署了成千上万个热门模型供公众使用。
获取 API Token
- 登录 Hugging Face 账号。
- 前往 Settings > Access Tokens。
- 创建一个带有
read权限的 token。
Python 调用示例
使用标准的 requests 库或官方的 huggingface_hub 库。
import requests
# 模型地址
API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
headers = {"Authorization": "Bearer hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
output = query({
"inputs": "Can you please explain what is Hugging Face?",
"parameters": {"max_new_tokens": 100}
})
print(output)
推荐使用官方 SDK
from huggingface_hub import InferenceClient
client = InferenceClient(model="mistralai/Mistral-7B-Instruct-v0.2", token="hf_xxx")
# 文本生成
response = client.text_generation("The capital of France is")
print(response)
# 图像生成 (Text-to-Image)
image = client.text_to_image("An astronaut riding a horse on mars")
image.save("astronaut.png")
2. Serverless 向量提取 (RAG 必备)
对于构建 RAG (检索增强生成) 系统,这是获取文本向量(Embeddings)最便捷的方式。
client = InferenceClient(model="BAAI/bge-small-zh-v1.5", token="hf_xxx")
embedding = client.feature_extraction("这是一段需要向量化的中文文本")
print(len(embedding)) # 对于 bge-small,维度通常是 512
3. Inference Endpoints (生产级专用端点)
Serverless API 虽然方便,但有速率限制且不保证稳定性。对于生产环境,推荐使用 Inference Endpoints。
主要特点
- 独享资源:你可以选择专用的 CPU 或 GPU(如 A10G, T4, A100)。
- 完全控制:支持设置自动休眠、私有连接和安全选项。
- 自定义框架:支持加载自定义推理代码。
- 按量计费:根据硬件使用时长按小时计费。
创建流程
- 在 Hub 上选择一个模型。
- 点击模型页面右上角的 Deploy > Inference Endpoints。
- 选择云服务商(AWS/Azure)和硬件。
- 部署完成后,你将获得一个私有的 URL,调用方式与 Serverless API 基本一致。
4. 常见问题与局限性
Serverless API 限制
- 速率限制 (Rate Limiting):如果请求太频繁,会返回
503 Service Unavailable。 - 冷启动:某些未处于活动状态的模型在第一次请求时可能需要 1-2 分钟加载(返回 "Model is loading")。
- 最大请求量:对输入长度和生成长度有一定限制。
性能建议
- Batching:如果可能,将多个输入合并为一个请求以提高效率。
- Caching:在客户端对常见查询的结果进行缓存。
提示:如果你需要完全的隐私和最高的性能,且具备服务器管理能力,也可以使用 Text Generation Inference (TGI) 在自己的服务器上进行 Docker 部署。