Xử lý bất đồng bộ

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Xử lý bất đồng bộ là gì

Một người phục vụ đồ uống cho khách ngồi tại bàn

 

Cho phép xử lý đồng thời nhiều yêu cầu

Triển khai AI vào môi trường sản xuất với FastAPI

Yêu cầu đồng bộ vs bất đồng bộ

Biểu đồ cho thấy khác biệt thời gian xử lý giữa yêu cầu đồng bộ và bất đồng bộ

Triển khai AI vào môi trường sản xuất với FastAPI

Chuyển endpoint đồng bộ sang bất đồng bộ

 

@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}
Triển khai AI vào môi trường sản xuất với FastAPI

Triển khai tác vụ nền

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 quản lý hàng đợi xử lý comment

 

  • background_tasks xử lý sau khi đã phản hồi.

 

  • add_task lên lịch process_comments bất đồng bộ.
Triển khai AI vào môi trường sản xuất với FastAPI

Thêm xử lý lỗi

@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"]}
Triển khai AI vào môi trường sản xuất với FastAPI

Thêm xử lý lỗi

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Phân tích quá thời gian chờ"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Phân tích thất bại"
        )
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...