Traitement asynchrone

Déployer l'IA en production avec FastAPI

Matt Eckerle

Software and Data Engineering Leader

Qu'est-ce que le traitement asynchrone

Une personne sert un verre à quelqu'un assis à une table

 

Permet de traiter plusieurs requêtes en parallèle

Déployer l'IA en production avec FastAPI

Requêtes synchrones vs asynchrones

Un graphique comparant les temps de traitement des requêtes synchrones et asynchrones

Déployer l'IA en production avec FastAPI

Rendre des points de terminaison synchrones asynchrones

 

@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}
Déployer l'IA en production avec FastAPI

Mettre en œuvre des tâches en arrière-plan

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 gère la file de traitement des commentaires

 

  • background_tasks lance le traitement après la réponse.

 

  • add_task planifie process_comments de façon asynchrone.
Déployer l'IA en production avec FastAPI

Ajouter la gestion des erreurs

@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"]}
Déployer l'IA en production avec FastAPI

Ajouter la gestion des erreurs

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
Déployer l'IA en production avec FastAPI

Passons à la pratique !

Déployer l'IA en production avec FastAPI

Preparing Video For Download...