始める無料で始める

API から構造化された出力を返す

ここでは、コンテンツモデレーションシステムを構築します。ユーザーコメントに対して事前学習済みの感情分析モデルをテストするために、POST エンドポイントを定義する必要があります。

pydantic モデルを活用して、予測結果を構造化された形式で返すエンドポイントを作成しましょう。

注意:Pydantic モデルである CommentRequestCommentResponse は、事前定義済みの SentimentAnalyzer クラスの sentiment_model とともに、すでに用意されています。

この演習はコースの一部です

FastAPI を使った AI のプロダクション環境へのデプロイ

コースを見る

演習の手順

  • /analyze ルートに POST エンドポイントを実装しましょう。
  • analyze_comment() 関数内で、CommentRequest に基づいて request を検証しましょう。
  • requesttext を渡して、sentiment_model で予測を行いましょう。
  • requesttextresult[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"
        )
コードを編集して実行