diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md index 30682a5..ee0198d 100644 --- a/docs/AGENT_GUIDE.md +++ b/docs/AGENT_GUIDE.md @@ -47,8 +47,11 @@ ## 가게 정보 조회 · 수정 -동작 : "지금 저장된 정보 보여줘", "주차 정보 뭐로 돼 있어?" -행동 : 저장된 값을 최대 20개까지 보여 줌 (키워드를 말하면 그 항목만) +동작 : "가게 정보 알려줘", "지금 저장된 정보 보여줘" +행동 : 요약을 보여 줌 — 가게 이름·업종, 발행 여부·마지막 발행 시각·사이트 주소, 업종 핵심 항목(스키마 `critical`)만 한 줄씩(긴 값은 첫 줄 30자에서 자름), 나머지는 개수로만 + +동작 : "주차 정보 뭐로 돼 있어?", "취소 규정 보여줘" +행동 : 그 항목만 자르지 않고 보여 줌 (최대 20개) 동작 : "체크인 오후 3시로 바꿔줘", "체크인 15시 30분", "체크인 3시 반" 행동 : 시각으로 저장 (15:00 / 15:30). "3시"처럼 오전인지 오후인지 모르면 되물음 diff --git a/solution/backend/services/agent/tools.py b/solution/backend/services/agent/tools.py index 7c81897..123fe70 100644 --- a/solution/backend/services/agent/tools.py +++ b/solution/backend/services/agent/tools.py @@ -208,35 +208,79 @@ def _display(spec, value: str) -> str: # ── 읽기 ──────────────────────────────────────────────────────────────── -async def _get_site_status(ctx: ToolContext, args: dict) -> str: +async def _published(ctx: ToolContext) -> tuple[str, str] | None: + """(주소, 마지막 발행 시각). 발행 전이면 None.""" _fact, site_service = _services() - res = await site_service.get_site(ctx.user, ctx.place_id) - site = res.site + site = (await site_service.get_site(ctx.user, ctx.place_id)).site if site is None or site.published_at is None: - return "아직 발행 전입니다. 준비가 되면 발행해 드릴게요." + return None # ★ 주소는 site_payload 의 함수로 만든다. 문자열로 조립하면 canonical 과 갈린다 # (CLAUDE.md '슬러그 규칙은 두 곳에 있고 같아야 한다'). url = f"{site_payload.publish_origin()}/s/{site_payload.publish_slug(ctx.place, site)}" - when = site.published_at.strftime("%Y-%m-%d %H:%M") + return url, site.published_at.strftime("%Y-%m-%d %H:%M") + + +async def _get_site_status(ctx: ToolContext, args: dict) -> str: + published = await _published(ctx) + if published is None: + return "아직 발행 전입니다. 준비가 되면 발행해 드릴게요." + url, when = published return f"발행되어 있습니다.\n주소: {url}\n마지막 발행: {when}" +# 요약 한 줄에 싣는 값의 길이. 카톡 말풍선에서 한 줄로 읽히는 정도다. +SUMMARY_VALUE_MAX = 30 + + +def _short(value: str) -> str: + """첫 줄만, 길면 자른다 — 순환 문구처럼 수십 줄인 값이 요약을 통째로 덮었다(2026-10-21 캡처).""" + lines = value.strip().splitlines() + first = lines[0].strip() if lines else "" + if len(first) > SUMMARY_VALUE_MAX: + return first[:SUMMARY_VALUE_MAX].rstrip() + "…" + return first + ("…" if len(lines) > 1 else "") + + async def _list_facts(ctx: ToolContext, args: dict) -> str: + """키워드가 없으면 요약(발행 주소 + 업종 핵심 항목), 있으면 그 항목을 자르지 않고. + + ★ 요약 항목은 업종 스키마의 `critical` 이다 — 틀리면 예약 클레임이 나는 값이라 사장님이 + 제일 먼저 확인해야 하고, 목록을 여기 따로 두면 스키마와 갈린다.""" fact_service, _site = _services() res = await fact_service.list_facts(ctx.user, ctx.place_id, publishable_only=True) rows = [f for f in (res.facts or []) if (f.value or "").strip()] schema = get_schema(PlaceCategory(ctx.place.category)) + + def label(f) -> str: + spec = schema.get(f.key) + return spec.label if spec else f.key + + def shown(f) -> str: + spec = schema.get(f.key) + return _display(spec, f.value) if spec else f.value + keyword = _arg(args, "keyword") if keyword: - rows = [f for f in rows if keyword in f.key or keyword in ((schema.get(f.key).label if schema.get(f.key) else ""))] - if not rows: - return "저장된 가게 정보가 아직 없습니다." if not keyword else f"'{keyword}' 로 찾은 정보가 없습니다." - lines = [] - for f in rows[:20]: - spec = schema.get(f.key) - lines.append(f"· {spec.label if spec else f.key}: {f.value}") - more = f"\n(그 밖에 {len(rows) - 20}개 더 있습니다)" if len(rows) > 20 else "" - return "지금 저장된 정보입니다.\n" + "\n".join(lines) + more + rows = [f for f in rows if keyword in f.key or keyword in label(f)] + if not rows: + return f"'{keyword}' 로 찾은 정보가 없습니다." + lines = [f"· {label(f)}: {shown(f)}" for f in rows[:20]] + more = f"\n(그 밖에 {len(rows) - 20}개 더 있습니다)" if len(rows) > 20 else "" + return "\n".join(lines) + more + + published = await _published(ctx) + head = [f"{ctx.place.name} · {schema.label}"] + head += [f"발행됨 · {published[1]}", published[0]] if published else ["아직 발행 전이에요."] + + critical = set(schema.critical_keys()) + key_rows = [f for f in rows if f.key in critical] + body = ["핵심 정보"] + [f"· {label(f)}: {_short(shown(f))}" for f in key_rows] if key_rows \ + else ["저장된 핵심 정보가 아직 없어요."] + + rest = len(rows) - len(key_rows) + tail = [f"그 밖에 {rest}개 항목이 저장돼 있어요."] if rest else [] + tail.append("\"주차 정보 보여줘\"처럼 물어보시면 자세히 알려 드려요.") + return "\n\n".join(["\n".join(head), "\n".join(body), "\n".join(tail)]) # ── 되돌릴 수 있는 쓰기 ────────────────────────────────────────────────── @@ -688,7 +732,7 @@ REGISTRY: dict[str, Tool] = { name="list_facts", grade=ToolGrade.READ, title="가게 정보 보기", - summary="지금 저장된 가게 정보를 보여준다.", + summary="가게 정보를 요약해 보여준다(발행 주소 포함). 특정 항목을 물으면 그 값을 자세히 보여준다.", args={"keyword": "찾고 싶은 항목이 있으면 그 말(선택)"}, run=_list_facts, ), diff --git a/solution/backend/tests/test_agent_runtime.py b/solution/backend/tests/test_agent_runtime.py index ec0e6b1..ab63a3e 100644 --- a/solution/backend/tests/test_agent_runtime.py +++ b/solution/backend/tests/test_agent_runtime.py @@ -1116,3 +1116,54 @@ async def test_못_한_요청_이름의_줄바꿈은_한_칸으로_편다(client choose({"actions": [], "skipped": ["전화번호\n변경"], "message": ""}) reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "전화번호"})).json()["reply"] assert "'전화번호 변경' 은(는)" in reply + + +# ── 가게 정보 요약 (2026-10-23) ───────────────────────────────────────── + +async def _say(client, h, pid, choose, actions, message="해줘"): + choose({"actions": actions, "message": ""}) + return (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": message})).json()["reply"] + + +async def _fill(client, h, pid, choose): + await _say(client, h, pid, choose, [ + {"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}}, + {"tool": "set_fact", "args": {"key": "pet_allowed", "value": "가능"}}, + {"tool": "set_fact", "args": {"key": "cancel_policy", "value": "이용 7일 전까지 전액 환불, 3일 전까지 50% 환불, 이후 환불 불가\n당일 취소 불가"}}, + {"tool": "set_fact", "args": {"key": "wifi", "value": "가능"}}, + ]) + + +async def test_가게_정보는_핵심_항목만_요약한다(client, auth_headers, choose, db_engine): + """캡처(2026-10-21): 순환 문구 한 항목이 20줄을 넘겨 요약을 덮었고, 바비큐가 'true' 로 나왔다.""" + h, pid = await seed(client, auth_headers, name="요약숙소") + await _fill(client, h, pid, choose) + + reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {}}], "가게 정보 알려줘") + assert reply.startswith("요약숙소 · 숙박") + assert "아직 발행 전이에요." in reply + assert "· 체크인 시간: 15:00" in reply + assert "· 반려동물 동반: 가능" in reply + assert "true" not in reply + assert "와이파이" not in reply # critical 아님 → 개수로만 + assert "그 밖에 1개 항목이 저장돼 있어요." in reply + assert "당일 취소 불가" not in reply # 둘째 줄은 싣지 않는다 + line = next(x for x in reply.splitlines() if x.startswith("· 취소·환불 규정")) + assert line.endswith("…") and len(line.split(": ", 1)[1]) <= tools.SUMMARY_VALUE_MAX + 1 + + +async def test_발행됐으면_요약에_주소가_붙는다(client, auth_headers, choose, db_engine, monkeypatch): + h, pid = await seed(client, auth_headers) + monkeypatch.setattr(tools, "_published", AsyncMock(return_value=("https://host/s/x", "2026-10-21 14:30"))) + reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {}}], "가게 정보 알려줘") + assert "발행됨 · 2026-10-21 14:30\nhttps://host/s/x" in reply + assert "저장된 핵심 정보가 아직 없어요." in reply + + +async def test_항목을_물으면_자르지_않고_보여준다(client, auth_headers, choose, db_engine): + h, pid = await seed(client, auth_headers) + await _fill(client, h, pid, choose) + reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {"keyword": "취소"}}], "취소 규정 보여줘") + assert "당일 취소 불가" in reply + reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {"keyword": "와이파이"}}], "와이파이 보여줘") + assert "· 와이파이: 가능" in reply