| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import json |
| 5 | from http import HTTPStatus |
| 6 | from typing import Any |
| 7 | |
| 8 | from fastapi import APIRouter, FastAPI, HTTPException, Request |
| 9 | from fastapi.responses import JSONResponse, Response |
| 10 | |
| 11 | from vllm.engine.protocol import EngineClient |
| 12 | from vllm.logger import init_logger |
| 13 | |
| 14 | logger = init_logger(__name__) |
| 15 | |
| 16 | router = APIRouter() |
| 17 | |
| 18 | |
| 19 | def engine_client(request: Request) -> EngineClient: |
| 20 | return request.app.state.engine_client |
| 21 | |
| 22 | |
| 23 | @router.post("/collective_rpc") |
| 24 | async def collective_rpc(raw_request: Request): |
| 25 | try: |
| 26 | body = await raw_request.json() |
| 27 | except json.JSONDecodeError as e: |
| 28 | raise HTTPException( |
| 29 | status_code=HTTPStatus.BAD_REQUEST.value, |
| 30 | detail=f"JSON decode error: {e}", |
| 31 | ) from e |
| 32 | if not isinstance(body, dict): |
| 33 | raise HTTPException( |
| 34 | status_code=HTTPStatus.BAD_REQUEST.value, |
| 35 | detail="Request body must be a JSON object", |
| 36 | ) |
| 37 | method = body.get("method") |
| 38 | if method is None: |
| 39 | raise HTTPException( |
| 40 | status_code=HTTPStatus.BAD_REQUEST.value, |
| 41 | detail="Missing 'method' in request body", |
| 42 | ) |
| 43 | # For security reason, only serialized string args/kwargs are passed. |
| 44 | # User-defined `method` is responsible for deserialization if needed. |
| 45 | args: list[str] = body.get("args", []) |
| 46 | kwargs: dict[str, str] = body.get("kwargs", {}) |
| 47 | timeout: float | None = body.get("timeout") |
| 48 | results = await engine_client(raw_request).collective_rpc( |
| 49 | method=method, timeout=timeout, args=tuple(args), kwargs=kwargs |
| 50 | ) |
| 51 | if results is None: |
| 52 | return Response(status_code=200) |
| 53 | response: list[Any] = [] |
| 54 | for result in results: |
| 55 | if result is None or isinstance(result, dict | list): |
| 56 | response.append(result) |
| 57 | else: |
| 58 | response.append(str(result)) |
| 59 | return JSONResponse(content={"results": response}) |
| 60 | |
| 61 | |
| 62 | def attach_router(app: FastAPI): |
| 63 | app.include_router(router) |