การคืนค่าผลลัพธ์แบบมีโครงสร้างจาก API
คุณกำลังสร้างระบบกลั่นกรองเนื้อหา โดยต้องกำหนด POST endpoint เพื่อทดสอบโมเดลวิเคราะห์ความรู้สึก (sentiment analysis) ที่ผ่านการฝึกมาแล้วบนความคิดเห็นของผู้ใช้
ต้องสร้าง endpoint ที่ใช้โมเดล pydantic เพื่อคืนค่าผลการพยากรณ์ในรูปแบบที่มีโครงสร้างชัดเจน
หมายเหตุ: โมเดล Pydantic ได้แก่ CommentRequest และ CommentResponse ถูกสร้างไว้ให้แล้ว พร้อมกับ sentiment_model จากคลาส SentimentAnalyzer ที่กำหนดไว้ล่วงหน้า
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การ Deploy AI สู่ Production ด้วย FastAPI
คำแนะนำการฝึกหัด
- กำหนด
POSTendpoint ที่เส้นทาง/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"
)