API से संरचित आउटपुट लौटाना
आप एक कंटेंट मॉडरेशन सिस्टम बना रहे हैं, जहाँ आपको यूज़र कमेंट्स पर प्री-ट्रेंड sentiment analysis मॉडल को टेस्ट करने के लिए एक POST endpoint परिभाषित करना है.
आपको ऐसा endpoint बनाना है जो प्रेडिक्शन को संरचित फ़ॉर्मेट में लौटाने के लिए pydantic मॉडल्स का उपयोग करे.
ध्यान दें: Pydantic मॉडल्स — CommentRequest और CommentResponse पहले से बनाए गए हैं, ताकि आप प्री-डिफ़ाइंड SentimentAnalyzer क्लास के प्री-ट्रेंड sentiment_model के साथ उनका उपयोग कर सकें.
यह अभ्यास पाठ्यक्रम का हिस्सा है
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना
अभ्यास निर्देश
- रूट
/analyzeपर एकPOSTendpoint इम्प्लीमेंट करें. CommentRequestके अनुसारanalyze_comment()फंक्शन मेंrequestको वैलिडेट करें.requestकेtextको पास करकेsentiment_modelसे प्रेडिक्शन लें.- आउटगोइंग रिस्पॉन्स को
CommentResponseमें फ़ॉर्मेट करने के लिए प्रेडिक्शन के एट्रिब्यूट्स लौटाएँ (requestसेtext, औरresult[0]से"label"तथा"score").
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# 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"
)