""" FastAPI application for intent classification using fine-tuned Falcon AI model. """ from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch from typing import List, Dict import logging # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize FastAPI app app = FastAPI( title="Intent Classification API", description="API for classifying user intents using fine-tuned Falcon AI model", version="1.0.0" ) # Global model and tokenizer model = None tokenizer = None MODEL_PATH = "./finetuned_intent_falconsai" class PredictionRequest(BaseModel): """Request model for intent prediction.""" text: str = Field(..., description="Text to classify", min_length=1, max_length=512) return_all_scores: bool = Field(False, description="Return scores for all labels") class PredictionResponse(BaseModel): """Response model for intent prediction.""" text: str intent: str confidence: float all_scores: List[Dict[str, float]] = None class BatchPredictionRequest(BaseModel): """Request model for batch predictions.""" texts: List[str] = Field(..., description="List of texts to classify", max_items=100) return_all_scores: bool = Field(False, description="Return scores for all labels") class HealthResponse(BaseModel): """Health check response.""" model_config = {"protected_namespaces": ()} status: str model_loaded: bool @app.on_event("startup") async def load_model(): """Load model and tokenizer on startup.""" global model, tokenizer try: logger.info(f"Loading model from {MODEL_PATH}...") tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH) model.eval() # Set to evaluation mode logger.info("Model loaded successfully!") except Exception as e: logger.error(f"Failed to load model: {str(e)}") raise @app.get("/", response_model=HealthResponse) async def root(): """Root endpoint with basic health check.""" return { "status": "online", "model_loaded": model is not None and tokenizer is not None } @app.get("/health", response_model=HealthResponse) async def health_check(): """Health check endpoint.""" return { "status": "healthy" if model is not None else "unhealthy", "model_loaded": model is not None and tokenizer is not None } @app.post("/predict", response_model=PredictionResponse) async def predict_intent(request: PredictionRequest): """ Predict intent for a single text input. Args: request: PredictionRequest containing text and options Returns: PredictionResponse with predicted intent and confidence """ if model is None or tokenizer is None: raise HTTPException(status_code=503, detail="Model not loaded") try: # Tokenize input inputs = tokenizer( request.text, return_tensors="pt", truncation=True, max_length=128, padding=True ) # Get prediction with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=-1)[0] predicted_class = torch.argmax(logits, dim=-1).item() # Get predicted label and confidence predicted_label = model.config.id2label[predicted_class] confidence = probabilities[predicted_class].item() # Prepare response response = { "text": request.text, "intent": predicted_label, "confidence": confidence } # Add all scores if requested if request.return_all_scores: all_scores = [ { "label": model.config.id2label[i], "score": probabilities[i].item() } for i in range(len(probabilities)) ] all_scores.sort(key=lambda x: x["score"], reverse=True) response["all_scores"] = all_scores return response except Exception as e: logger.error(f"Prediction error: {str(e)}") raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}") @app.post("/predict/batch") async def predict_batch(request: BatchPredictionRequest): """ Predict intents for multiple texts in batch. Args: request: BatchPredictionRequest containing list of texts Returns: List of predictions """ if model is None or tokenizer is None: raise HTTPException(status_code=503, detail="Model not loaded") if len(request.texts) == 0: raise HTTPException(status_code=400, detail="No texts provided") try: results = [] # Process in batch inputs = tokenizer( request.texts, return_tensors="pt", truncation=True, max_length=128, padding=True ) with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=-1) predicted_classes = torch.argmax(logits, dim=-1) # Build results for i, text in enumerate(request.texts): predicted_class = predicted_classes[i].item() predicted_label = model.config.id2label[predicted_class] confidence = probabilities[i][predicted_class].item() result = { "text": text, "intent": predicted_label, "confidence": confidence } if request.return_all_scores: all_scores = [ { "label": model.config.id2label[j], "score": probabilities[i][j].item() } for j in range(len(probabilities[i])) ] all_scores.sort(key=lambda x: x["score"], reverse=True) result["all_scores"] = all_scores results.append(result) return {"predictions": results} except Exception as e: logger.error(f"Batch prediction error: {str(e)}") raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}") @app.get("/labels") async def get_labels(): """Get all available intent labels.""" if model is None: raise HTTPException(status_code=503, detail="Model not loaded") return { "labels": list(model.config.id2label.values()), "num_labels": len(model.config.id2label) } if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)