当前位置: 首页 > 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即可实现改功能

相关文章:

  • 物种分化在进化拓扑中的作用
  • 《深度学习》—— 模型部署
  • 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++进阶】深入探索类型转换
  • 重庆发布经济犯罪案件接报警电子地图,企业可查询导航属地经侦服务点
  • 继71路之后,上海中心城区将迎来第二条中运量公交
  • 这一次,又被南昌“秀”到了
  • 科学家用AI寻找外星生命
  • 汇源果汁发文:经营情况一切正常
  • 媒体谈法院就“行人相撞案”道歉:执法公正,普法莫拉开“距离”