असिंक्रोनस प्रोसेसिंग

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Matt Eckerle

Software and Data Engineering Leader

असिंक्रोनस प्रोसेसिंग क्या है

टेबल पर बैठे व्यक्ति को पेय सर्व करता एक वेटर

 

एक साथ कई रिक्वेस्ट संभालने में सक्षम

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Synchronous बनाम Asynchronous रिक्वेस्ट

सिंक्रोनस और असिंक्रोनस रिक्वेस्ट के प्रोसेसिंग समय का फर्क दिखाता चार्ट

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Synchronous endpoints को Asynchronous में बदलना

 

@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 डिप्लॉय करना

Background tasks लागू करना

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 डिप्लॉय करना

Error handling जोड़ना

@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 डिप्लॉय करना

Error handling जोड़ना

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