异步处理

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

Vamos praticar!

使用 FastAPI 在生产环境中部署 AI

Preparing Video For Download...