"""허용 함수·인자·호출 ID를 검사하고 도구 왕복을 완료한다."""
import json
import re
from conversation import build_messages
from evidence import validate_sources
from order_tools import ORDER_TOOL, get_order_status
from rag_schema import parse_rag_response
from tool_client import chat
TOOL_SYSTEM = """당신은 모아상점 고객지원 담당입니다. 한국어로 간결하게 답하세요.
개별 주문 상태는 get_order_status 결과로만 답하세요. 주문번호가 없으면 먼저 물으세요.
주문번호를 추측하지 말고 고객이 제공한 번호만 사용하세요. 사용자 ID를 인자로 만들지 마세요.
허용되지 않은 주문과 없는 주문은 같은 안내로 답하세요. 다른 사람의 주문 존재를 추측하지 마세요.
도구 실패나 결과 없음에는 상태·상품을 만들어 답하지 마세요. 환불·변경·취소 기능은 없습니다.
일반 규정이 아닌 주문 DB 결과에는 sources=[]를 사용하세요.
최종 응답은 JSON 하나입니다. answer(1~500자), sources(문서ID배열),
needs_followup(불리언), followup_question(질문 문자열 또는 null) 네 필드입니다.
필요한 조회를 끝냈으면 추가 질문 없이 false/null로 마치세요."""
def dispatch_call(call, current_user_id, lookup=get_order_status, allowed_order_ids=None):
if not isinstance(call, dict):
return {"ok": False, "error": "invalid_arguments"}
if call.get("type") != "function":
return {"ok": False, "error": "tool_not_allowed"}
function = call.get("function", {})
if not isinstance(function, dict) or function.get("name") != "get_order_status":
return {"ok": False, "error": "tool_not_allowed"}
try:
arguments = json.loads(function["arguments"])
if not isinstance(arguments, dict) or set(arguments) != {"order_id"} or not isinstance(arguments["order_id"], str):
raise ValueError
except (KeyError, TypeError, ValueError):
return {"ok": False, "error": "invalid_arguments"}
if allowed_order_ids is not None and arguments["order_id"] not in allowed_order_ids:
return {"ok": False, "error": "order_id_not_provided"}
return lookup(arguments["order_id"], current_user_id)
def generate_order_answer(question, history=None, current_user_id="U001", client=chat, lookup=get_order_status):
checked = build_messages(question, history)
messages = [{"role": "system", "content": TOOL_SYSTEM}] + checked[1:]
provided = set(re.findall(r"MO-\d{8}-\d{3}", " ".join(m["content"] for m in checked if m["role"] == "user")))
outputs, rounds, used_ids = [], [], set()
def finish(response, decision):
return {"answer": json.dumps(response, ensure_ascii=False),
"usage": [row.get("usage") for row in rounds],
"model": rounds[-1].get("model") if rounds else None,
"tool_results": outputs,
"trace": {"messages": messages, "rounds": rounds, "decision": decision}}
if not provided:
return finish({"answer": "주문 상태를 확인하려면 주문번호를 알려주세요.", "sources": [],
"needs_followup": True, "followup_question": "주문번호가 어떻게 되나요?"},
"order_number_required_before_model")
total_tools = 0
for round_number in range(3):
raw = client(messages, tools=[ORDER_TOOL], tool_choice="auto")
rounds.append(raw)
message = raw["message"]
calls = message.get("tool_calls", [])
messages.append(message)
if not calls:
response = parse_rag_response(message["content"])
validate_sources(response, [], "2026-06-15")
return finish(response, "model_final")
if len(calls) > 3 or total_tools + len(calls) > 3:
raise ValueError("도구 호출 수 제한에 도달했습니다.")
if any(not isinstance(call, dict) or not isinstance(call.get("function"), dict)
or not isinstance(call["function"].get("name"), str)
or not isinstance(call["function"].get("arguments"), str) for call in calls):
raise ValueError("도구 요청의 객체·함수 이름·인자를 확인하세요.")
ids = [call.get("id") for call in calls]
if (any(not isinstance(x, str) or not x for x in ids)
or len(ids) != len(set(ids)) or used_ids.intersection(ids)):
raise ValueError("도구 호출 ID가 없거나 중복되었습니다.")
used_ids.update(ids)
for call in calls:
result = dispatch_call(call, current_user_id, lookup, provided)
function = call.get("function")
outputs.append({"name": function.get("name") if isinstance(function, dict) else None,
"result": result})
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": json.dumps(result, ensure_ascii=False)})
if result.get("error") == "not_found_or_forbidden":
return finish({"answer": "해당 주문을 조회할 수 없습니다. 주문번호와 로그인 상태를 확인해 주세요.",
"sources": [], "needs_followup": False, "followup_question": None},
"server_denial_without_second_generation")
total_tools += len(calls)
raise ValueError("도구 왕복 횟수 제한에 도달했습니다.")
def wants_order_lookup(question):
if re.search(r"MO-\d{8}-\d{3}", question):
return True
return bool(re.search(r"(주문|배송|택배|운송장).{0,30}(어디|상태|조회|도착|왔|진행|추적)", question))
def support_answer(question, history=None, current_user_id="U001"):
if wants_order_lookup(question) and ("배송비" in question or "규정" in question):
build_messages(question, history)
return {"response": {"answer": "배송 규정과 개별 주문 상태는 각각 확인합니다.",
"sources": [], "needs_followup": True,
"followup_question": "배송 규정과 주문 상태 중 어느 것을 먼저 확인할까요?"},
"source_details": [], "tool_results": [], "usage": None, "model": None,
"trace": {"decision": "mixed_intent_clarification"}}
if not wants_order_lookup(question):
from answers import answer_question
return answer_question(question, history)
import settings
if settings.DEMO_MODE:
raise ValueError("주문 도구 경로는 DEMO_MODE=0과 실제 API 키가 필요합니다.")
raw = generate_order_answer(question, history, current_user_id)
response = parse_rag_response(raw["answer"])
return {"response": response, "source_details": [], "tool_results": raw["tool_results"],
"usage": raw["usage"], "model": raw["model"], "trace": raw["trace"]}