非同期処理

FastAPI を使った AI のプロダクション環境へのデプロイ

Matt Eckerle

Software and Data Engineering Leader

非同期処理とは

テーブルに座った人に飲み物を提供するウェイター

 

複数のリクエストを同時に処理できます

FastAPI を使った AI のプロダクション環境へのデプロイ

同期リクエストと非同期リクエスト

同期リクエストと非同期リクエストの処理時間の差を示すグラフ

FastAPI を使った AI のプロダクション環境へのデプロイ

同期エンドポイントの非同期化

 

@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}
FastAPI を使った AI のプロダクション環境へのデプロイ

バックグラウンドタスクの実装

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 はコメント処理キューを管理します

 

  • background_tasks はレスポンス後の処理を担当します

 

  • add_task は process_comments を非同期でスケジュールします
FastAPI を使った AI のプロダクション環境へのデプロイ

エラーハンドリングの追加

@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"]}
FastAPI を使った AI のプロダクション環境へのデプロイ

エラーハンドリングの追加

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
FastAPI を使った AI のプロダクション環境へのデプロイ

さあ、練習しましょう!

FastAPI を使った AI のプロダクション環境へのデプロイ

Preparing Video For Download...