SPB Git

Repository Public

routes_openai.py 4.4 KB 113 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr LLM API7# File             : src/maclustr_llm/routes_openai.py8# Description      : Routes /v1 compatibles OpenAI.9# Module           : maclustr_llm10# Repository       : https://git.spboucher.ai/maclustr-llm11# Created          : 2026-11-1912# Last Modified    : 2026-11-1913#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: admin@spboucher.ai22# Technical Contact: dev@spboucher.ai23# Security/Admin   : admin@spboucher.ai24#25# Copyright (c) 202626# Simon-Pierre Boucher27# All rights reserved where applicable. This file is governed by the28# applicable project license, copyright notices and relevant law.29# Existing third-party rights and notices remain unaffected.30#31# License          : None specified (no license file in this repository)32#33# Do not embed credentials, private keys, access tokens,34# certificates or confidential personal information.35#36# =============================================================================37# END OF SP BOUCHER SOURCE HEADER38# =============================================================================3940"""Routes /v1 compatibles OpenAI."""4142from __future__ import annotations4344from typing import Any, cast4546from fastapi import APIRouter, Depends, Request47from fastapi.responses import JSONResponse, Response4849from .auth import client_ip50from .errors import forbidden, not_found, unauthorized51from .keys import ADMIN_PRINCIPAL, Principal52from .schemas import ChatRequest, CompletionRequest5354router = APIRouter(prefix="/v1")555657def svc_of(request: Request) -> Any:58    return request.app.state.svc596061async def principal_of(request: Request) -> Principal:62    """Authentifie l'appelant : jeton Bearer (clé API), ou session administrateur + CSRF (Playground)."""63    svc = svc_of(request)64    header = request.headers.get("authorization", "")65    if header[:7].lower() == "bearer ":66        ip = client_ip(request, svc.settings.trust_proxy)67        p = cast(Principal | None, await svc.keys.resolve(header[7:].strip()))68        if p is None:69            svc.badkey_throttle.check(ip)70            raise unauthorized("Clé API invalide, révoquée ou expirée.")71        return p72    session = await svc.auth.session_from(request)73    if session is not None:74        svc.auth.check_csrf(request, session)75        return ADMIN_PRINCIPAL76    raise unauthorized("Clé API requise : en-tête « Authorization: Bearer <clé> ».", code="missing_api_key")777879# L'authentification est une dépendance : elle s'exécute avant la validation du corps (401 avant 400).80Auth = Depends(principal_of)818283@router.get("/models")84async def list_models(request: Request, p: Principal = Auth) -> JSONResponse:85    svc = svc_of(request)86    if not p.allows_endpoint("models"):87        raise forbidden("Cette clé n'a pas accès à l'endpoint « models ».", code="endpoint_not_allowed")88    data = [m.public() for m in svc.settings.models.values() if p.allows_model(m.id)]89    return JSONResponse({"object": "list", "data": data})909192@router.get("/models/{model:path}")93async def get_model(model: str, request: Request, p: Principal = Auth) -> JSONResponse:94    svc = svc_of(request)95    spec = svc.settings.models.get(model)96    if spec is None or not p.allows_model(model) or not p.allows_endpoint("models"):97        raise not_found(f"Le modèle « {model} » n'existe pas.", code="model_not_found")98    return JSONResponse(spec.public())99100101@router.post("/chat/completions")102async def chat_completions(body: ChatRequest, request: Request, p: Principal = Auth) -> Response:103    svc = svc_of(request)104    prep = svc.inference.prepare_chat(body, p)105    return cast(Response, await svc.inference.handle(request, p, prep, request.state.request_id))106107108@router.post("/completions")109async def completions(body: CompletionRequest, request: Request, p: Principal = Auth) -> Response:110    svc = svc_of(request)111    prep = svc.inference.prepare_completion(body, p)112    return cast(Response, await svc.inference.handle(request, p, prep, request.state.request_id))113
Files main
Menu

Theme