非同步處理

使用 FastAPI 將 AI 佈署到生產環境

Matt Eckerle

Software and Data Engineering Leader

什麼是非同步處理

服務生在桌邊為客人送飲料

 

可同時處理多個請求

使用 FastAPI 將 AI 佈署到生產環境

同步 vs 非同步請求

顯示同步與非同步請求處理時間差異的圖表

使用 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...