從 API 回傳結構化輸出
你正在建立一個內容審核系統,需要定義一個 POST 端點,用來在使用者留言上測試一個預先訓練好的情感分析模型。
你需要建立一個端點,使用 pydantic 模型,將預測結果以結構化格式回傳。
注意:Pydantic 模型 CommentRequest 與 CommentResponse 已為你建立好;另外也提供了來自預先定義 SentimentAnalyzer 類別的預訓練 sentiment_model 可供使用。
本練習屬於課程
使用 FastAPI 將 AI 佈署到生產環境
練習說明
- 在路由
/analyze實作一個POST端點。 - 在
analyze_comment()函式中,依據CommentRequest驗證request。 - 將
request的text傳入sentiment_model進行預測。 - 回傳預測屬性(
request中的text,以及result[0]中的"label"與"score"),並以CommentResponse格式輸出回應。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a POST request endpoint
@app.____("/analyze")
# Capture the request text for validation as per CommentRequest model
def analyze_comment(____: CommentRequest):
try:
# Specify pass the request text to the model
result = sentiment_model(____.____)
# Specify the result attributes to complete the comment response
return CommentResponse(text=____,
sentiment=____,
confidence=____)
except Exception:
raise HTTPException(status_code=500,
detail="Prediction failed"
)