开始使用免费开始使用

创建一个异步情感分析端点

您正在构建一个社交媒体分析平台,需要对评论进行情感分析。为高效应对高并发流量,您需要实现一个 async 端点。情感分析模型已加载,可通过 sentiment_model 使用。

本练习是课程的一部分

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

查看课程

练习说明

  • 使用 FastAPI 应用创建一个异步 POST 端点 /analyze
  • 添加关键字,以异步方式调用 sentiment_model,避免阻塞其他操作。
  • 在单独的线程中运行 sentiment_model 并传入评论文本,确保不会阻塞事件循环。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Review(BaseModel):
    text: str

# Create async endpoint at /analyze route
@app.post("____")
# Write an asynchronous function to process review's text
____ def analyze_review(review: Review):
    # Run the model in a separate thread to avoid any event loop blockage
    result = ____ asyncio.____(sentiment_model, ____)
    return {"sentiment": result[0]["label"]}
编辑并运行代码