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

【大语言模型_8】vllm启动的模型通过fastapi封装增加api-key验证

背景:

      vllm推理框架启动模型不具备api-key验证。需借助fastapi可以实现该功能

代码实现:

rom fastapi import FastAPI, Header, HTTPException, Request,Response
import httpx
import logging

# 创建 FastAPI 应用
app = FastAPI()
logging.basicConfig(level=logging.DEBUG)
# 配置 vLLM 的服务地址
VLLM_BASE_URL = "http://localhost:25010"

# 定义合法的 API Key 列表(可以根据需要扩展为数据库或配置文件)
VALID_API_KEYS = {"zml_123456789", "zml_1234567890"}

# 中间件:验证 API Key
# 验证 API Key
async def verify_api_key(authorization: str = Header(None)):
    # 打印接收到的 Authorization 字段
    logging.debug(f"Received Authorization header: {authorization}")

    # 检查 Authorization 是否存在且以 "Bearer " 开头
    if not authorization or not isinstance(authorization, str) or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=403, detail="Invalid Authorization Header")

    # 提取 API Key
    try:
        api_key = authorization.split(" ")[1]  # 提取 "Bearer " 后的部分
    except IndexError:
        raise HTTPException(status_code=403, detail="Malformed Authorization Header")

    # 验证 API Key 是否合法
    if api_key not in VALID_API_KEYS:
        raise HTTPException(status_code=403, detail="Invalid API Key")



# 代理路由:转发请求到 vLLM
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(request: Request, path: str, authorization: str = Header(None)):
    # 验证 API Key
    logging.debug(f"Received request with path: {path}")
    logging.debug(f"Received headers: {request.headers}")
    await verify_api_key(authorization)

    # 构造转发的目标 URL
    target_url = f"{VLLM_BASE_URL}/{path}"

    # 获取请求体和查询参数
    body = await request.body()
    query_params = request.query_params

    # 使用 httpx 转发请求
    async with httpx.AsyncClient() as client:
        # 根据请求方法转发
        response = await client.request(
            method=request.method,
            url=target_url,
            params=query_params,
            data=body,
            headers={key: value for key, value in request.headers.items() if key != "host"}
        )

    # 返回 vLLM 的响应
    return Response(content=response.content, status_code=response.status_code, headers=dict(response.headers))

三、启动

uvicorn my_fastapi:app  --host=0.0.0.0 --port=12345
# my_fastapi 为脚本名称

通过访问fastapi提供的12345即可实现改功能

http://www.dtcms.com/a/82889.html

相关文章:

  • 物种分化在进化拓扑中的作用
  • 《深度学习》—— 模型部署
  • JAVA泛型的作用
  • RAGFlow爬虫组件使用及ragflow vs dify 组件设计对比
  • 深度学习篇---深度学习中的范数
  • 软考中级网络工程师第八章网络安全
  • 【react】工程项目中的通过自定义Hook进行路由设计以及路由鉴权
  • Python Django入门(创建应用程序)
  • Mysql表的简单操作
  • 深度解析学术论文成果评估(Artifact Evaluation):从历史到现状
  • 【React】基于自定义Hook提取公共逻辑
  • MySQL:float,decimal(1)
  • Python学习第二十一天
  • 风暴潮、潮汐潮流模拟:ROMS模型如何精准预测海洋现象?
  • 云盘搭建笔记
  • 《Python实战进阶》No42: 多线程与多进程编程详解(下)
  • 四种事件类型
  • 自适应柔顺性策略:扩散引导控制中学习近似的柔顺
  • Python中的null是什么?
  • 【C++进阶】深入探索类型转换
  • (electron 报错)TypeError: Cannot read property ‘upgrade‘ of undefined
  • Linux驱动开发-①中断②阻塞、非阻塞IO和异步通知
  • VLAN:逻辑隔离冲突网络的详细讲解
  • Android第四次面试(Java基础篇)
  • Unity动画片段丢失(AnimationClip),如何进行重新绑定
  • OpenCV旋转估计(5)图像拼接的一个函数waveCorrect()
  • 【云上CPU玩转AIGC】——腾讯云高性能应用服务HAI已支持DeepSeek-R1模型预装环境和CPU算力
  • 基于Spring Boot的本科生交流培养管理平台的设计与实现(LW+源码+讲解)
  • c++ XML库用法
  • 【机器学习-模型评估】