開始使用免費開始

從 API 回傳結構化輸出

你正在建立一個內容審核系統,需要定義一個 POST 端點,用來在使用者留言上測試一個預先訓練好的情感分析模型。

你需要建立一個端點,使用 pydantic 模型,將預測結果以結構化格式回傳。

注意:Pydantic 模型 CommentRequestCommentResponse 已為你建立好;另外也提供了來自預先定義 SentimentAnalyzer 類別的預訓練 sentiment_model 可供使用。

本練習屬於課程

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

檢視課程

練習說明

  • 在路由 /analyze 實作一個 POST 端點。
  • analyze_comment() 函式中,依據 CommentRequest 驗證 request
  • requesttext 傳入 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"
        )
編輯並執行程式碼