test: cobre contratos locais de requests RAG

This commit is contained in:
Bruno Viana 2026-10-23 20:21:56 -03:00
parent c2c2fc716c
commit ce13a7cd09
7 changed files with 128 additions and 42 deletions

View file

@ -8,6 +8,7 @@ from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from request_contract import ContractError, extract_user_question, validate_api_key
from source_metadata import source_reference
@ -49,20 +50,10 @@ def check_auth(
x_api_key: str | None,
authorization: str | None,
) -> None:
if not API_KEY:
raise HTTPException(
status_code=503,
detail="ATIVA_RAG_API_KEY não configurada.",
)
supplied = x_api_key
if not supplied and authorization:
if authorization.lower().startswith("bearer "):
supplied = authorization[7:].strip()
if supplied != API_KEY:
raise HTTPException(status_code=401, detail="Não autorizado.")
try:
validate_api_key(API_KEY, x_api_key, authorization)
except ContractError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
async def embed(text: str) -> list[float]:
@ -324,27 +315,10 @@ async def chat_completions(
):
check_auth(x_api_key, authorization)
if not request.messages:
raise HTTPException(
status_code=400,
detail="messages não pode ser vazio.",
)
question = ""
for msg in reversed(request.messages):
if msg.get("role") == "user":
question = str(msg.get("content", "")).strip()
break
if not question:
raise HTTPException(
status_code=400,
detail="Nenhuma mensagem de usuário encontrada.",
)
if len(question) > MAX_QUESTION_CHARS:
raise HTTPException(status_code=400, detail="Pergunta muito longa.")
try:
question = extract_user_question(request.messages, MAX_QUESTION_CHARS)
except ContractError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
vector = await embed(question)