零资源跑大模型:Hugging Face API + LiteLLM + Flask

前言

HuggingFace 是自然语言处理领域的开源软件库和平台,其收纳了众多最前沿的模型和数据集,并提供了 Serverless Inference API,用户可以轻松调用这些模型,甚至用于运行自己的私人模型。本教程将指导用户如何利用 Hugging Face API 零资源运行这些模型,并结合 LiteLLM 和 Flask 简化调用逻辑,以适配 OpenAI。

教程概要

  • 介绍 Hugging Face Serverless API 的使用方法,包括如何调用嵌入模型文本生成模型对话模型
  • 通过 LiteLLM 转换 Hugging Face 模型为 OpenAI 格式。
  • 使用 Flask 创建一个接口,转发请求并实现自定义逻辑。

Hugging Face

简介

参考文档: Hugging Face API Inference

Serverless Inference API 让用户通过简单的 HTTP 请求即可免费测试和评估超过 15 万个公开的机器学习模型,以及使用自己的私人模型。推理由 Hugging Face 提供的共享基础设施加速。

  • 免费使用:推理 API 免费提供使用,并且有速率限制。需要用于生产环境的推理解决方案,可使用 Inference Endpoints 服务。
  • 主要特点
    • 支持超过 15 万个 Transformers、Diffusers 或 Timm 模型。
    • 内置集成 20 多个开源库,如 spaCy、SpeechBrain、Keras 等。
    • 模型切换方便,通过切换模型 ID 即可。
    • 支持多种任务,如分类、图像分割、语音识别、对话、摘要、翻译、问答、嵌入提取等。
    • 基于 Intel Xeon Ice Lake 提供加速推理。

用户可通过 Inference Endpoints 标签 筛选支持 Inference API 的模型。

文生图模型

示例模型:stable-diffusion-xl-base-1.0

调用方式:

prompt="Imagine a delightful scene found in a children'\''s book. There'\''s a playful puppy with its adorable features exaggerated in classic cartoon style. Its fur is a soft golden color, with a pair of sparkling eyes full of curiosity. Its tail, bushy and wagging, is an embodiment of its joyful nature. The puppy is in a typical playful stance, a chew toy in its mouth and its tongue hanging out. The scene is set in a homely backyard with green grass and plenty colorful flowers, and a bright sun up in the sky, resulting in a warm, inviting atmosphere."

curl https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0 \
        -X POST \
        -d '{"inputs": "$prompt"}' \
        -H 'Content-Type: application/json' \
        -H "Authorization: Bearer $HF_TOKEN" \
        --output puppy.jpeg

返回二进制图片数据,输出到指定文件。

输出效果:
puppy

嵌入模型

以网易有道推出的 BCEmbedding 模型为例,先找到 Hugging Face 的地址:

调用方法:

curl https://api-inference.huggingface.co/models/maidalun1020/bce-embedding-base_v1 \
        -X POST \
        -d '{"inputs": "Today is a sunny day and I will get some ice cream."}' \
        -H 'Content-Type: application/json' \
        -H "Authorization: Bearer $HF_TOKEN"

返回结果:

[-0.0015705720288679004,0.008027488365769386,...]

还可用列表形式调用:

curl https://api-inference.huggingface.co/models/maidalun1020/bce-embedding-base_v1 \
        -X POST \
        -d '{"inputs": ["Today is a sunny day and I will get some ice cream.", ...]}' \
        -H 'Content-Type: application/json' \
        -H "Authorization: Bearer $HF_TOKEN"

文本生成模型

以 MetaAI 的 Llama3 为例:

调用方式:

curl https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct \
        -X POST \
        -d '{"inputs": "hello"}' \
        -H 'Content-Type: application/json' \
        -H "Authorization: Bearer $HF_TOKEN"

返回结果:

[{"generated_text":"hello! i am a junior high school student, and i am really interested in history..."}]

LiteLLM

简介

LiteLLM 项目 为主流的模型服务提供统一的调用方式。功能包括:

  • 标准化接口:调用超过 100 种 LLM 模型,提供统一的输入/输出格式。
  • 接口转换:支持将输入翻译成提供商的文本生成、嵌入和图像生成端点。
  • 多部署重试/后备机制:可以在多个部署(如 Azure/OpenAI)之间重试或切换。
  • 预算和速率限制:可为项目、API 密钥或模型设置预算和速率限制。
  • 跟踪开销:可监控项目花费,并设置预算限制。

安装

通过 pip 安装:

pip install litellm

如果希望将 LiteLLM 服务部署成类似 OneAPI 的形式,并带有 UI 管理界面,则用以下方式进行安装:

git clone https://github.com/BerriAI/litellm.git
cd litellm
pip install 'litellm[proxy]'

启动服务:

litellm

可参阅完整的参数文档:CLI Arguments

配置文件

为 litellm 添加下游模型并设置转发规则,参考文档:

配置文件中有五个主要设置:

参数名描述
model_list服务器上支持的模型列表及其特定配置
router_settingsLiteLLM 路由设置,如 routing_strategy="least-busy"
litellm_settingsLiteLLM 模块设置,如 litellm.drop_params=Truelitellm.set_verbose=Truelitellm.api_base
general_settings服务器设置,如 master_key: sk-my_special_key
environment_variables环境变量,如 REDIS_HOSTREDIS_PORT

项目仓库下的 proxy_server_config.yaml 提供了完整的示例配置文件。以下示例用于配置 Hugging Face 模型:

model_list:
  - model_name: bce-embedding-base_v1
    litellm_params: 
      model: huggingface/maidalun1020/bce-embedding-base_v1 # 自动路由到 Hugging Face
      api_key: hf_...  # Hugging Face API 密钥
  - model_name: Meta-Llama-3-8B-Instruct
    litellm_params: 
      model: huggingface/meta-llama/Meta-Llama-3-8B-Instruct
      api_key: hf_...

general_settings: 
  master_key: sk-1234  # 调用的密钥,也是管理员登录密码
  # 如果配置 UI 界面,需数据库支持
  store_model_in_db: True 
  database_url: "postgresql://<user>:<password>@<host>:<port>/<dbname>"  # [可选] 用于代理的数据库支持

参数说明:

  • master_key 作为调用的密钥,也作为管理员的登录密码
  • store_model_in_db 保存在线的模型修改
  • database_url UI 界面的管理需要数据库支持

Docker 配置

如果希望避免手动配置 Python 环境和数据库,官方提供了 Docker 部署方式。文档:Docker 部署

以下是个人经过调整并验证有效的 docker-compose.yaml

version: "3.9"
services:
  db:
    image: postgres:latest
    container_name: litellm_db
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    env_file:
      - .env
  litellm:
    build:
      context: .
      args:
        target: runtime
    image: ghcr.io/berriai/litellm:main-latest
    depends_on:
      - db
    ports:
      - "4000:4000"
    volumes:
      - ./litellm-config.yaml:/app/config.yaml
    command: [ "--config", "/app/config.yaml", "--port", "4000", "--num_workers", "8", "--detailed_debug" ]
    env_file:
      - .env

.env 文件的内容:

# Postgres 配置
POSTGRES_USER=
POSTGRES_PASSWORD=
POSTGRES_DB=
# LiteLLM 配置
LITELLM_MASTER_KEY="" # 主密钥,用于代理服务器
UI_USERNAME=""   # UI 界面的用户名
UI_PASSWORD=""      # UI 界面的密码
STORE_MODEL_IN_DB='True'
# 默认端口 5432,用户名密码需与上面的 POSTGRES_USER 和 POSTGRES_PASSWORD 一致
DATABASE_URL="postgresql://<user>:<password>@<host>:<port>/<dbname>"

Flask

简介

HuggingFace 的文生图接口返回的是二进制图片数据,我们可以使用 Flask 结合 Nginx 代理,将结果以链接形式返回。

下面的代码段展示了如何实现这个功能,将数据保存在 /storage/dalle3/ 目录下,并通过 CDN 链接返回。

from flask import Flask, request, jsonify
import requests, os, io, uuid
from datetime import datetime
from PIL import Image
import json

app = Flask(__name__)
HF_TOKEN = "hf_xxx"
HF_MODEL_ID = "ehristoforu/dalle-3-xl-v2"
HUGGING_FACE_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL_ID}"
IMAGE_SAVE_DIR = "/storage/dalle3/"
CDN_PREFIX = "https://cdn.example.com/dalle3"

def prompt_revision(prompt):
    # 自定义规则,将用户的 Prompt 进行优化,对图像进行更细致的描述
    return prompt

def generate_images(prompt):
    headers = {"Authorization" : f"Bearer {HF_TOKEN}"}
    response = requests.post(HUGGING_FACE_API_URL, headers=headers, json={"inputs": prompt})
    if response.status_code == 200:
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S") # Generate timestamp string
        image_path = os.path.join(IMAGE_SAVE_DIR, f"{timestamp}_{uuid.uuid4()[:8]}.jpeg")
        image = Image.open(io.BytesIO(response.content))
        image.save(image_path, "JPEG")
        url = f"{CDN_PREFIX}/{os.path.basename(image_path)}"
        return url
    else:
        return None

@app.route('/v1/images/generations', methods=['POST'])
def image_generation():
    # Get the raw data
    raw_data = request.data
    # Decode the raw data into a string
    decoded_data = raw_data.decode('utf-8')
    data = json.loads(decoded_data)
    prompt = data.get("prompt", "")
    n = data.get("n", 1) # Number of images to generate, TODO: support multiple images
    if prompt:
        revised_prompt = prompt_revision(prompt)
        url = generate_images(revised_prompt)
        if url:
            return jsonify({
                "created": int(datetime.now().timestamp()),
                "revised_prompt": revised_prompt,
                "data": [{"url": url}],
            })
        else:
            return jsonify({"error": "Failed to generate images"}), 500
    else:
        return jsonify({"error": "No prompt provided"}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

将文件保存为 dalle3.py 并启动模型:

# pip install gunicorn
gunicorn -w 4 -b 127.0.0.1:8080 dalle3:app

接着我们可以通过 Nginx 配置返回的 CDN 链接,如下所示:

server {
    listen 443 ssl;
    server_name cdn.example.com;
    # SSL 证书配置
    location /dalle3/ {
        alias /storage/dalle3/;
    }
}

最后,通过 OpenAI 接口的方式调用:

curl https://cdn.example.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model": "dall-e-3", "prompt": "..."}'

以上,通过 Hugging Face、LiteLLM 和 Flask 来创建一个自定义接口,用于转发并处理各种模型的请求。

  • 23
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

致宏Rex

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值