from fastapi import HTTPException, status from typing import List, Optional, Union, Dict, Any, Tuple def validate_single_or_batch(text: Optional[str], texts: Optional[List[str]]): """Validate that either text or texts is provided, but not both""" if text is None and texts is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": "Either 'text' or 'texts' must be provided", "details": {} } } ) if text is not None and texts is not None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": "Provide either 'text' or 'texts', not both", "details": {} } } ) if text == "" and texts is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": "'text' cannot be empty or only whitespace", "details": {} } } ) if texts is not None and len(texts) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": "Texts list cannot be empty", "details": {} } } ) if texts is not None and len(texts) != 0: # Check for empty strings within the list for i, t in enumerate(texts): if not isinstance(t, str) or not t.strip(): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": f"Text item at index {i} in 'texts' cannot be empty or only whitespace", "details": {} } } ) return text if text is not None else texts def handle_error(e: Exception): """Convert exceptions to consistent error format""" if isinstance(e, HTTPException): raise e if isinstance(e, ValueError): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ "error": { "code": "INVALID_INPUT", "message": str(e), "details": {} } } ) # Internal server error raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail={ "error": { "code": "INTERNAL_ERROR", "message": "An internal error occurred while processing your request", "details": {} } } )