response_schema.py

파일 다운로드

import json


class SchemaError(ValueError):
    pass


def parse_response(raw):
    try:
        data = json.loads(raw)
    except (TypeError, ValueError):
        raise SchemaError("응답이 JSON 객체 형식이어야 합니다.") from None
    fields = {"answer", "needs_followup", "followup_question"}
    if not isinstance(data, dict) or set(data) != fields:
        raise SchemaError("응답에는 약속한 세 필드가 필요합니다.")
    answer = data["answer"]
    if not isinstance(answer, str) or not 1 <= len(answer.strip()) <= 500:
        raise SchemaError("답변은 1~500자의 문자열이어야 합니다.")
    if type(data["needs_followup"]) is not bool:
        raise SchemaError("needs_followup은 참·거짓이어야 합니다.")
    question = data["followup_question"]
    if data["needs_followup"]:
        if not isinstance(question, str) or not 1 <= len(question.strip()) <= 200:
            raise SchemaError("추가 질문은 1~200자의 문자열이어야 합니다.")
        question = question.strip()
    elif question is not None:
        raise SchemaError("추가 질문이 없으면 null이어야 합니다.")
    return {"answer": answer.strip(), "needs_followup": data["needs_followup"],
            "followup_question": question}