Asynchrone verwerking

AI in productie brengen met FastAPI

Matt Eckerle

Software and Data Engineering Leader

Wat is asynchrone verwerking

Iemand die een drankje serveert aan iemand aan een tafel

 

Maakt gelijktijdige afhandeling van meerdere requests mogelijk

AI in productie brengen met FastAPI

Synchrone vs asynchrone requests

Een grafiek met het verschil in verwerkingstijd voor synchrone en asynchrone requests

AI in productie brengen met FastAPI

Synchrone endpoints asynchroon maken

 

@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}
AI in productie brengen met FastAPI

Achtergrondtaken implementeren

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 beheert de wachtrij voor commentverwerking

 

  • background_tasks handelt verwerking na de response af.

 

  • add_task plant process_comments asynchroon in.
AI in productie brengen met FastAPI

Foutafhandeling toevoegen

@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"]}
AI in productie brengen met FastAPI

Foutafhandeling toevoegen

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
AI in productie brengen met FastAPI

Laten we oefenen!

AI in productie brengen met FastAPI

Preparing Video For Download...