시작하기무료로 시작하기

API에서 구조화된 출력 반환하기

사용자 댓글에 사전 학습된 감성 분석 모델을 테스트하기 위해 POST 엔드포인트를 정의하는 콘텐츠 검수 시스템을 구축하고 있습니다.

pydantic 모델을 활용하여 예측 결과를 구조화된 형식으로 반환하는 엔드포인트를 만들어야 합니다.

참고: Pydantic 모델인 CommentRequestCommentResponse, 그리고 사전 정의된 SentimentAnalyzer 클래스의 sentiment_model은 이미 준비되어 있습니다.

이 연습은 강의의 일부입니다

FastAPI로 AI 프로덕션 배포하기

강의 보기

연습 안내

  • /analyze 경로에 POST 엔드포인트를 구현하세요.
  • analyze_comment() 함수에서 CommentRequest에 따라 request의 유효성을 검사하세요.
  • requesttext를 전달하여 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"
        )
코드 편집 및 실행