test: cobre contratos locais de requests RAG
This commit is contained in:
parent
c2c2fc716c
commit
ce13a7cd09
7 changed files with 128 additions and 42 deletions
48
rag-api/request_contract.py
Normal file
48
rag-api/request_contract.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"""Dependency-free request validation shared by the RAG API and tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ContractError(ValueError):
|
||||
def __init__(self, status_code: int, detail: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def validate_api_key(
|
||||
configured_key: str,
|
||||
x_api_key: str | None,
|
||||
authorization: str | None,
|
||||
) -> None:
|
||||
if not configured_key:
|
||||
raise ContractError(503, "ATIVA_RAG_API_KEY não configurada.")
|
||||
|
||||
supplied = x_api_key
|
||||
if not supplied and authorization and authorization.lower().startswith("bearer "):
|
||||
supplied = authorization[7:].strip()
|
||||
|
||||
if supplied != configured_key:
|
||||
raise ContractError(401, "Não autorizado.")
|
||||
|
||||
|
||||
def extract_user_question(
|
||||
messages: list[dict[str, Any]],
|
||||
max_question_chars: int,
|
||||
) -> str:
|
||||
if not messages:
|
||||
raise ContractError(400, "messages não pode ser vazio.")
|
||||
|
||||
for message in reversed(messages):
|
||||
if message.get("role") != "user":
|
||||
continue
|
||||
question = str(message.get("content", "")).strip()
|
||||
if not question:
|
||||
break
|
||||
if len(question) > max_question_chars:
|
||||
raise ContractError(400, "Pergunta muito longa.")
|
||||
return question
|
||||
|
||||
raise ContractError(400, "Nenhuma mensagem de usuário encontrada.")
|
||||
Loading…
Add table
Add a link
Reference in a new issue