[fix] solution/backend: 대화 수정의 값 형식 검증 · 여러 요청의 못 한 것·남은 것 안내 — 조용히 틀리던 경로 정리

말로 고친 값이 형식 검증 없이 저장됐다 — "반려동물 이제 돼요" 가 "가능" 으로 들어가면
화면엔 "가능" 이 뜨는데 factBool 은 'true' 만 참으로 읽어 구조화 데이터가 거짓이 된다.
여러 요청을 한 번에 받을 때도 할 수 없는 것·멈춘 뒤의 것이 말없이 사라져 사장님은
전부 된 줄 알았다(message 는 actions 가 있으면 버려졌다).

- tools: set_fact 값을 스키마 형식으로 맞춘다(bool true/false · time HH:MM · number 숫자) —
  "3시" 처럼 오전·오후를 모르면 저장하지 않고 되묻는다. 알림 문구는 가능·불가로 말한다
- tools: enabled 를 모르면 끄지 않고 되묻는다 — "" 를 끄기로 읽어 "다시 보여줘" 가 섹션을 껐다
- tools: 대표 지정·사진 목록·프롬프트를 '나가는 사진' 기준으로 — 내린 사진을 대표로 지정하고
  "바꿨습니다" 라고 하던 것. 정확히 맞는 이름을 부분 일치보다 먼저 고른다
- tools: Unchanged 표시 — "이미 켜져 있어요" 에 재발행 안내·카톡 발행 대기가 붙던 것
- tools/runtime: 인자가 문자열·dict 가 아니어도 죽지 않는다(모델의 스키마 위반)
- runtime: 같은 대상은 마지막 하나로 합친다(Tool.target, 상한 세기 전). 멈춘 뒤 남은 요청과
  지어낸 도구를 코드가 만든 이름으로 알린다. 발행 확인 문구는 맨 끝에 선다
- prompts: 항목마다 형식을 싣고 skipped(할 수 없는 요청의 이름) 칸 추가 — 문장은 런타임이 만든다.
  다른 가게 이야기면 되묻는 규칙
- channel: 발화에 다른 내 가게 이름이 나오면 모델을 부르기 전에 고르게 한다. 기억한 가게가
  목록에 없으면 비우고 목록으로. 확인 경로의 AgentError 를 사장님 말로 옮긴다
- docs/AGENT.md: 값 형식 · 못 한 것·남은 것·겹친 것 · 나가는 사진 기준

테스트 48건 추가, 에이전트·카카오 153 passed. 전체 932 passed / 47 failed —
실패 47건은 변경 전과 동일(gemini·openai 키 미설정, search_console KeyError, weather_notes)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Opus 5.5 committed 2026-09-29 15:11:00 +09:00
1 parent 86d870bab5
commit aaf97f2797
7 files changed
+827 -41

No files matched your search

@@ -583,3 +583,309 @@ async def test_모델이_지어낸_도구는_건너뛰고_나머지는_한다(cl
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "다 지우고 체크인 3시로"})).json()
assert "체크인 시간" in body["reply"]
assert body.get("rejected") is not True
# ── 값 형식 (bool · time · number) ──────────────────────────────────────
async def _fact_value(db_engine, place_id, key):
async with db_engine.begin() as c:
return (await c.execute(
text("SELECT value FROM place_facts WHERE place_id=:p AND key=:k AND deleted=false"),
{"p": uuid.UUID(place_id), "k": key},
)).scalars().all()
@pytest.mark.parametrize("said, stored", [
("가능", "true"), ("돼요", "true"), ("있음", "true"), ("True", "true"),
("불가", "false"), ("안 돼요", "false"), ("없음", "false"),
])
async def test_예_아니오_항목은_true_false_로_저장한다(said, stored, client, auth_headers, choose, db_engine):
"""★ 렌더러(shared/src/lib/facts.ts factBool)는 'true' 만 참으로 읽는다. "가능" 으로 저장하면
화면에는 "가능" 이 뜨는데 구조화 데이터는 거짓이 된다 — 조용히 틀리는 종류다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "pet_allowed", "value": said}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "반려동물 바꿔줘"})).json()
assert body.get("rejected") is not True, body["reply"]
assert await _fact_value(db_engine, pid, "pet_allowed") == [stored]
assert "true" not in body["reply"] and "false" not in body["reply"] # 사장님께는 가능·불가로 말한다
async def test_예_아니오를_알아볼_수_없으면_저장하지_않는다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "pet_allowed", "value": "소형견만"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "소형견만 돼"})).json()
assert body["rejected"] is True
assert await _fact_value(db_engine, pid, "pet_allowed") == []
@pytest.mark.parametrize("said, stored", [
("15:00", "15:00"), ("9:30", "09:30"), ("오후 3시", "15:00"), ("15시 30분", "15:30"),
("오후 3시 반", "15:30"), ("오전 11시", "11:00"), ("12시", "12:00"),
])
async def test_시각은_HH_MM_으로_저장한다(said, stored, client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "check_in_time", "value": said}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "체크인 바꿔줘"})).json()
assert body.get("rejected") is not True, body["reply"]
assert await _fact_value(db_engine, pid, "check_in_time") == [stored]
@pytest.mark.parametrize("said", ["3시", "25:00", "곧"])
async def test_오전_오후가_모호하거나_시각이_아니면_되묻는다(said, client, auth_headers, choose, db_engine):
"""★ '3시' 를 03:00 으로 넣으면 손님이 새벽에 온다. 추측하지 않고 묻는다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "check_in_time", "value": said}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "체크인 바꿔줘"})).json()
assert body["rejected"] is True
assert await _fact_value(db_engine, pid, "check_in_time") == []
@pytest.mark.parametrize("said, stored", [
("20000", "20000"), ("2만원", "20000"), ("2만 5천원", "25000"), ("20,000원", "20000"), ("무료", "0"),
])
async def test_숫자_항목은_숫자만_저장한다(said, stored, client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "extra_person_fee", "value": said}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "추가 요금 바꿔줘"})).json()
assert body.get("rejected") is not True, body["reply"]
assert await _fact_value(db_engine, pid, "extra_person_fee") == [stored]
async def test_숫자가_아니면_저장하지_않는다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "extra_person_fee", "value": "문의"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "추가 요금은 문의"})).json()
assert body["rejected"] is True
assert await _fact_value(db_engine, pid, "extra_person_fee") == []
def test_프롬프트에_항목_형식이_실린다():
"""★ 형식을 안 알려 주면 모델은 '주차 가능' 에 "가능" 을 쓴다 — 코드가 고쳐 주기 전에 맞게 오게 한다."""
from services.prompts import agent as prompt
fields = tools.fields_of(SimpleNamespace(category=PlaceCategory.LODGING.value))
text_ = prompt.build_prompt(place_name="가게", tools=tools.describe(), fields=fields, facts=[],
sections=[], photos=[], message="안녕")
assert "pet_allowed: 반려동물 동반 (true/false)" in text_
assert "check_in_time: 체크인 시간 (HH:MM" in text_
assert "extra_person_fee: 인원 추가 요금 (숫자만" in text_
async def test_모델이_문자열이_아닌_값을_줘도_터지지_않는다(client, auth_headers, choose, db_engine):
"""모델은 스키마를 어길 수 있다 — true 를 불리언으로, 인자를 배열로 보낸다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [
{"tool": "set_fact", "args": {"key": "pet_allowed", "value": True}},
{"tool": "toggle_section", "args": ["사진 갤러리"]},
], "message": ""})
res = await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "둘 다"})
assert res.status_code == 200, res.text
assert await _fact_value(db_engine, pid, "pet_allowed") == ["true"]
# ── 켜기·끄기가 비었을 때 ────────────────────────────────────────────────
async def test_켤지_끌지_모르면_끄지_않고_되묻는다(client, auth_headers, choose, db_engine):
"""★ 스키마가 모든 인자를 필수로 받아서 모델이 enabled 를 "" 로 채울 수 있다.
그걸 '끄기' 로 읽으면 "후기 다시 보여줘" 가 후기를 끈다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": ""}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 갤러리 다시"})).json()
assert body["rejected"] is True
assert "켤지 끌지" in body["reply"]
rows, _t = await _sections(client, h, pid)
assert next(r for r in rows if r["name"] == "사진 갤러리")["enabled"] is True
@pytest.mark.parametrize("said", ["false", "끄기", "off", "빼기"])
async def test_끄는_말은_끈다(said, client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": said}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "빼줘"})).json()
assert body.get("rejected") is not True, body["reply"]
rows, _t = await _sections(client, h, pid)
assert next(r for r in rows if r["name"] == "사진 갤러리")["enabled"] is False
# ── 사진 — 사이트에 안 나가는 사진 ───────────────────────────────────────
async def _hide(db_engine, place_id, label):
from common.enums import MediaStatus
async with db_engine.begin() as c:
await c.execute(
text("UPDATE place_photos SET status=:s WHERE place_id=:p AND label=:l"),
{"s": MediaStatus.REJECTED.value, "p": uuid.UUID(place_id), "l": label},
)
async def test_내린_사진은_대표가_될_수_없다(client, auth_headers, choose, db_engine):
"""★ 내린 사진의 순서만 당기면 "바꿨습니다" 라고 말하는데 발행본의 대표는 그대로다 —
화면만 거짓말한다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("수영장", None, 1)])
await _hide(db_engine, pid, "수영장")
choose({"actions": [{"tool": "set_primary_photo", "args": {"name": "수영장"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "대표 사진 수영장으로"})).json()
assert body["rejected"] is True
assert "안 나가는 사진" in body["reply"]
rows = await _photo_rows(db_engine, pid)
assert rows[0].label == "외관"
async def test_이미_내린_사진을_또_내리라면_그렇다고_말한다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("객실", None, 1)])
await _hide(db_engine, pid, "객실")
choose({"actions": [{"tool": "hide_photo", "args": {"name": "객실"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "객실 사진 내려줘"})).json()
assert "이미" in body["reply"]
async def test_사진_목록의_대표는_실제로_나가는_사진이다(client, auth_headers, choose, db_engine):
"""★ 맨 앞 사진이 내려가 있으면 그건 대표가 아니다 — primary_media 는 나가는 사진에서 고른다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("수영장", None, 1)])
await _hide(db_engine, pid, "외관")
choose({"actions": [{"tool": "list_photos", "args": {}}], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 보여줘"})).json()["reply"]
assert "대표 수영장" in reply
assert "대표 외관" not in reply
async def test_프롬프트에는_나가는_사진만_대표를_맨_앞에_싣는다(client, auth_headers, db_engine):
"""모델은 '맨 앞이 대표' 로 읽는다. 객실 전용 사진이 앞에 있거나 내린 사진이 섞이면 틀리게 읽는다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("침대", uuid.uuid4(), 0), ("외관", None, 1), ("주차장", None, 2)])
await _hide(db_engine, pid, "주차장")
from router.v1.validator.dependencies import DecodeAccessToken
user = DecodeAccessToken(h["Authorization"].split(" ", 1)[1])
place = await runtime._load_place(user, pid)
names = await tools.photo_names(tools.ToolContext(user=user, place_id=pid, place=place))
assert names[0] == "외관"
assert "주차장" not in names
async def test_이름이_정확히_맞으면_그_사진을_고른다(client, auth_headers, choose, db_engine):
"""'객실' 과 '객실 욕실' 이 있을 때 '객실' 은 모호하지 않다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("객실", None, 0), ("객실 욕실", None, 1)])
choose({"actions": [{"tool": "hide_photo", "args": {"name": "객실"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "객실 사진 내려줘"})).json()
assert body.get("rejected") is not True, body["reply"]
from common.enums import MediaStatus
rows = {r.label: r.status for r in await _photo_rows(db_engine, pid)}
assert rows["객실"] == MediaStatus.REJECTED.value
assert rows["객실 욕실"] != MediaStatus.REJECTED.value
# ── 한 발화에 여러 가지 — 못 한 것·남은 것·겹친 것 ─────────────────────
async def test_할_수_없는_요청이_섞이면_그것도_말한다(client, auth_headers, choose, db_engine):
"""★ 되는 것만 하고 입을 다물면 사장님은 전부 된 줄 안다. 문장은 코드가 만든다 —
모델은 '무엇을 못 했는지' 이름만 준다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}}],
"skipped": ["전화번호 변경"], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h,
json={"message": "체크인 3시로 바꾸고 전화번호도 바꿔줘"})).json()["reply"]
assert "체크인 시간" in reply
assert "'전화번호 변경' 은(는) 대화로는 아직 할 수 없어요." in reply
async def test_할_수_없는_요청뿐이면_그렇다고_말한다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [], "skipped": ["주소 변경"], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "주소 바꿔줘"})).json()
assert "'주소 변경' 은(는) 대화로는 아직 할 수 없어요." in body["reply"]
assert body["tool"] is None
async def test_지어낸_도구는_건너뛰었다고_말한다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
choose({"actions": [
{"tool": "delete_everything", "args": {}},
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}},
], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "다 지우고 체크인 3시로"})).json()["reply"]
assert "알아듣지 못한 요청 1가지" in reply
async def test_중간에_멈추면_남은_요청을_알려준다(client, auth_headers, choose, db_engine):
"""★ 멈춘 뒤의 요청을 말없이 버리면 사장님은 그것도 된 줄 안다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}},
{"tool": "toggle_section", "args": {"name": "없는섹션", "enabled": "false"}},
{"tool": "move_section", "args": {"name": "소개", "to": "맨 위"}},
{"tool": "set_fact", "args": {"key": "check_out_time", "value": "11:00"}},
], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "넷 다 해줘"})).json()["reply"]
assert "소개 옮기기, 체크아웃 시간 변경 은(는) 아직 하지 않았어요." in reply
async def test_발행에서_멈추면_뒤의_요청도_알려준다(client, auth_headers, choose, db_engine):
"""★ 발행 뒤의 요청은 확인을 눌러도 실행되지 않는다 — 확인 전에 알려야 한다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [
{"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": "false"}},
{"tool": "publish", "args": {}},
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}},
], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h,
json={"message": "갤러리 빼고 발행하고 체크인 3시로"})).json()
assert body["needs_confirm"] is True
assert "체크인 시간 변경 은(는) 아직 하지 않았어요." in body["reply"]
assert body["reply"].endswith(tools.REGISTRY["publish"].confirm) # 묻는 말은 맨 끝에 선다
assert await _fact_value(db_engine, pid, "check_in_time") == []
async def test_같은_항목을_고쳐_말하면_마지막_값만_남긴다(client, auth_headers, choose, db_engine):
""""체크인 3시… 아니 4시로" — 둘 다 하면 문구에 두 값이 함께 서서 어느 쪽이 남았는지 모른다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}},
{"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": "false"}},
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "16:00"}},
], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "3시 아니 4시"})).json()["reply"]
assert reply.count("체크인 시간") == 1
assert "16:00" in reply and "15:00" not in reply
assert await _fact_value(db_engine, pid, "check_in_time") == ["16:00"]
async def test_겹친_요청은_상한을_세기_전에_합친다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
names = ["사진 갤러리", "소개", "예약 안내", "자주 묻는 질문", "날씨"]
choose({"actions": [
{"tool": "toggle_section", "args": {"name": n, "enabled": "false"}} for n in names
] + [{"tool": "toggle_section", "args": {"name": "날씨", "enabled": "false"}}], "message": ""})
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "다 빼줘"})).json()["reply"]
assert f"{runtime.MAX_ACTIONS}가지까지" not in reply
async def test_바뀐_것이_없으면_재발행을_권하지_않는다(client, auth_headers, choose, db_engine):
"""★ "이미 켜져 있어요" 에 "다시 발행해야 해요" 가 붙으면, 사장님은 무언가 바뀐 줄 안다."""
h, pid = await seed(client, auth_headers)
choose({"actions": [{"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": "true"}}], "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 갤러리 켜줘"})).json()
assert "이미" in body["reply"]
assert runtime.REPUBLISH_NOTICE not in body["reply"]
assert body["done"] is False
def test_응답_스키마에_못_한_요청_칸이_있다():
"""OpenAI strict 모드는 properties 를 전부 required 로 요구한다."""
from services.prompts import agent as prompt
assert "skipped" in prompt.RESPONSE_SCHEMA["properties"]
assert "skipped" in prompt.RESPONSE_SCHEMA["required"]
@@ -371,3 +371,57 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
monkeypatch.setattr(bot.httpx, "AsyncClient", lambda **_kw: Boom())
await bot._push("https://callback.example/x", "안녕", "누구") # 예외가 새 나오지 않는다
# ── 여러 가게 ────────────────────────────────────────────────────────────
async def test_다른_가게_이름이_나오면_지금_가게를_고치지_않는다(client, auth_headers, db_engine, monkeypatch):
"""★ 프롬프트에는 지금 가게 하나만 실린다. "둘째가게 휴무 바꿔줘" 를 그대로 넘기면
첫째가게가 바뀌고, 사장님은 둘째가게가 바뀐 줄 안다."""
speaker = "다른가게-발화자"
h, _pid, _uid = await link(db_engine, client, auth_headers, speaker, "첫째가게")
await client.post("/v1/place", headers=h, json={"name": "둘째가게", "category": 1})
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("첫째가게", speaker))
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("둘째가게 체크인 3시로 바꿔줘", speaker))
assert "지금은 '첫째가게'" in said(res)
assert "둘째가게" in quick(res)
called.assert_not_awaited()
async def test_고른_가게가_사라지면_목록으로_돌아간다(client, auth_headers, db_engine, monkeypatch):
"""★ 기억한 가게를 목록과 대조하지 않으면, 그 가게가 없어진 뒤로는 매번
"그 가게를 찾지 못했어요" 만 돌아온다 — 사장님은 '목록' 을 쳐야 풀린다는 걸 모른다."""
speaker = "사라진가게-발화자"
h, _pid, _uid = await link(db_engine, client, auth_headers, speaker, "첫째가게")
await client.post("/v1/place", headers=h, json={"name": "둘째가게", "category": 1})
async with db_engine.begin() as c:
await c.execute(
text("UPDATE owner_kakao_links SET current_place_id=:g WHERE channel_user_key=:k"),
{"g": uuid.uuid4(), "k": speaker},
)
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("정보 보여줘", speaker))
assert "어느 가게" in said(res)
called.assert_not_awaited()
async def test_확인을_눌렀는데_가게가_없으면_그렇다고_말한다(client, auth_headers, db_engine, monkeypatch):
"""확인 경로도 런타임 오류를 사장님 말로 옮긴다 — "처리할 수 없어요" 로는 원인을 모른다."""
speaker = "확인-가게없음-키"
await link(db_engine, client, auth_headers, speaker)
async with db_engine.begin() as c:
await c.execute(
text("""UPDATE owner_kakao_links
SET pending_tool='publish', pending_args='{}'::jsonb,
pending_expires_at = now() + interval '1 minute', current_place_id=:g
WHERE channel_user_key=:k"""),
{"g": uuid.uuid4(), "k": speaker},
)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("네", speaker))
assert said(res) == channel._ERRORS["PLACE_NOT_FOUND"]