从 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"
)