開始使用免費開始

建立非同步的情感分析端點

你正在建立一個社群媒體分析平台,需要對評論進行情感分析。為了有效處理高流量,你需要實作一個 async 端點。情感分析模型已載入,並可透過 sentiment_model 使用。

本練習屬於課程

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

檢視課程

練習說明

  • 使用 FastAPI app 建立一個非同步的 POST 端點 /analyze
  • 加上關鍵字,讓呼叫 sentiment_model 時能以非同步方式進行,不會阻塞其他操作。
  • 在獨立執行緒中以該評論的文字來執行 sentiment_model,確保不會阻塞事件迴圈。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Review(BaseModel):
    text: str

# Create async endpoint at /analyze route
@app.post("____")
# Write an asynchronous function to process review's text
____ def analyze_review(review: Review):
    # Run the model in a separate thread to avoid any event loop blockage
    result = ____ asyncio.____(sentiment_model, ____)
    return {"sentiment": result[0]["label"]}
編輯並執行程式碼