开始使用免费开始使用

从 API 返回结构化输出

您正在构建一个内容审核系统,需要定义一个 POST 端点,用预训练的情感分析模型测试用户评论。

您需要创建一个端点,利用 pydantic 模型以结构化格式返回预测结果。

注意:Pydantic 模型 CommentRequestCommentResponse 已为您创建,可与预定义的 SentimentAnalyzer 类中的预训练 sentiment_model 一起使用。

本练习是课程的一部分

使用 FastAPI 在生产环境中部署 AI

查看课程

练习说明

  • 在路由 /analyze 上实现一个 POST 端点。
  • analyze_comment() 函数中按照 CommentRequest 校验 request
  • 通过传入 requesttext,使用 sentiment_model 进行预测。
  • 返回预测属性(来自 requesttext,以及来自 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"
        )
编辑并运行代码