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