from prompts import build_system_prompt
MAX_HISTORY_MESSAGES = 6
MAX_MESSAGE_CHARS = 1200
class HistoryError(ValueError):
pass
def build_messages(question, history=None, style="balanced"):
history = [] if history is None else history
if not isinstance(history, list) or len(history) > MAX_HISTORY_MESSAGES or len(history) % 2:
raise HistoryError("대화 기록은 최근 세 턴의 완성된 질문·답변 쌍이어야 합니다.")
clean = []
for index, message in enumerate(history):
expected = "user" if index % 2 == 0 else "assistant"
if not isinstance(message, dict) or set(message) != {"role", "content"}:
raise HistoryError("대화 기록의 필드를 확인하세요.")
if message["role"] != expected:
raise HistoryError("대화 기록은 user·assistant 순서여야 합니다.")
text = message["content"]
if not isinstance(text, str) or not 1 <= len(text.strip()) <= MAX_MESSAGE_CHARS:
raise HistoryError("이전 메시지는 1~1200자의 문자열이어야 합니다.")
clean.append({"role": expected, "content": text.strip()})
return ([{"role": "system", "content": build_system_prompt(style)}] + clean
+ [{"role": "user", "content": question}])