"""모델의 네 필드 응답을 파싱한다."""
import json
from response_schema import SchemaError
def parse_rag_response(raw):
try:
value = json.loads(raw)
except (ValueError, TypeError):
raise SchemaError("응답이 JSON 객체 형식이어야 합니다.") from None
fields = {"answer", "sources", "needs_followup", "followup_question"}
if not isinstance(value, dict) or set(value) != fields:
raise SchemaError("응답에는 약속한 네 필드가 필요합니다.")
answer = value["answer"]
if not isinstance(answer, str) or not 1 <= len(answer.strip()) <= 500:
raise SchemaError("답변은 1~500자의 문자열이어야 합니다.")
ids = value["sources"]
if (not isinstance(ids, list) or len(ids) > 8
or any(not isinstance(x, str) or not x.strip() for x in ids)):
raise SchemaError("sources는 최대 여덟 문서 ID의 배열이어야 합니다.")
if len(ids) != len(set(ids)):
raise SchemaError("출처 ID가 중복되었습니다.")
flag, question = value["needs_followup"], value["followup_question"]
if type(flag) is not bool:
raise SchemaError("needs_followup은 참·거짓이어야 합니다.")
if flag:
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(), "sources": ids,
"needs_followup": flag, "followup_question": question}