Elaborazione asincrona

Deployment di AI in produzione con FastAPI

Matt Eckerle

Software and Data Engineering Leader

Cos'è l'elaborazione asincrona

Una persona che serve da bere a qualcuno seduto a un tavolo

 

Consente di gestire più richieste in parallelo

Deployment di AI in produzione con FastAPI

Richieste sincrone vs asincrone

Un grafico che mostra la differenza nei tempi tra richieste sincrone e asincrone

Deployment di AI in produzione con FastAPI

Rendere asincroni gli endpoint sincroni

 

@app.post("/analyze")
def analyze_sync(comment: Comment):
    result = sentiment_model(comment.text)
    return {"sentiment": result}

 

import asyncio

@app.post("/analyze")
async def analyze_async(comment: Comment):
    result = await asyncio.to_thread(
        sentiment_model, comment.text
    )
    return {"sentiment": result}
Deployment di AI in produzione con FastAPI

Implementare attività in background

from fastapi import BackgroundTasks
from typing import List
@app.post("/analyze_batch")
async def analyze_batch(
    comments: Comments,
    background_tasks: BackgroundTasks
):
    async def process_comments(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(
              sentiment_model, text)
    background_tasks.add_task(process_comments, 
                              comments.texts)
    return {"message": "Processing started"}
  • BackgroundTasks gestisce la coda di elaborazione dei commenti

 

  • background_tasks esegue attività dopo la risposta.

 

  • add_task pianifica process_comments in modo asincrono.
Deployment di AI in produzione con FastAPI

Aggiungere la gestione degli errori

@app.post("/analyze_comment")
async def analyze_comment(comment: Comment):
    try:
        sentiment_model = SentimentAnalyzer()
        result = await asyncio.wait_for(
            sentiment_model(comment.text),
            timeout=5.0
        )
        return {"sentiment": result["label"]}
Deployment di AI in produzione con FastAPI

Aggiungere la gestione degli errori

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
Deployment di AI in produzione con FastAPI

Esercitiamoci!

Deployment di AI in produzione con FastAPI

Preparing Video For Download...