เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การคืนค่าผลลัพธ์แบบมีโครงสร้างจาก API

คุณกำลังสร้างระบบกลั่นกรองเนื้อหา โดยต้องกำหนด POST endpoint เพื่อทดสอบโมเดลวิเคราะห์ความรู้สึก (sentiment analysis) ที่ผ่านการฝึกมาแล้วบนความคิดเห็นของผู้ใช้

ต้องสร้าง endpoint ที่ใช้โมเดล pydantic เพื่อคืนค่าผลการพยากรณ์ในรูปแบบที่มีโครงสร้างชัดเจน

หมายเหตุ: โมเดล Pydantic ได้แก่ CommentRequest และ CommentResponse ถูกสร้างไว้ให้แล้ว พร้อมกับ sentiment_model จากคลาส SentimentAnalyzer ที่กำหนดไว้ล่วงหน้า

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การ Deploy AI สู่ Production ด้วย FastAPI

ดูคอร์ส

คำแนะนำการฝึกหัด

  • กำหนด POST endpoint ที่เส้นทาง /analyze
  • ตรวจสอบความถูกต้องของ request ในฟังก์ชัน analyze_comment() ตามรูปแบบของ CommentRequest
  • ทำการพยากรณ์โดยใช้ sentiment_model โดยส่ง text จาก request เข้าไป
  • คืนค่าแอตทริบิวต์ของผลการพยากรณ์ (ได้แก่ text จาก request, "label" และ "score" จาก result[0]) เพื่อจัดรูปแบบการตอบกลับใน 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"
        )
แก้ไขและรันโค้ด