跳至主要內容

1 篇文章 含有標籤「fastapi」

檢視所有標籤

您的中介軟體可能是瓶頸

Krrish Dholakia
CEO, LiteLLM
Ishaan Jaffer
CTO, LiteLLM
Ryan Crabbe
Performance Engineer, LiteLLM

我們如何透過替換單一、簡單的中介軟體基底類別,改善 LiteLLM proxy 的延遲與吞吐量


我們的設定

LiteLLM proxy 伺服器有兩層中介軟體。第一層是 Starlette 的 CORSMiddleware(由 FastAPI 重新匯出),這是一個純 ASGI 中介軟體。然後我們還有一個名為 PrometheusAuthMiddleware 的簡單 BaseHTTPMiddleware。

PrometheusAuthMiddleware 的工作是驗證對 /metrics 端點的請求。它預設不啟用,您可以在 proxy 設定中透過旗標啟用:

Proxy 設定旗標
litellm_settings:
require_auth_for_metrics_endpoint: true

這個中介軟體會檢查兩件事:請求是否打到 /metrics,以及是否已啟用驗證?如果兩項檢查都未通過——而大多數請求都是如此——它就會直接原樣放行請求。

PrometheusAuthMiddleware 原始碼
class PrometheusAuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if self._is_prometheus_metrics_endpoint(request):
if self._should_run_auth_on_metrics_endpoint() is True:
try:
await user_api_key_auth(request=request, api_key=...)
except Exception as e:
return JSONResponse(status_code=401, content=...)
response = await call_next(request)
return response

@staticmethod
def _is_prometheus_metrics_endpoint(request: Request):
if "/metrics" in request.url.path:
return True
return False

看起來無害。繼承 BaseHTTPMiddleware,實作 dispatch(),完成。這正是您會在 Starlette 文件1中看到的內容。