48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
"""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.")
|