Beltbot / tests /test_simulate_customers.py
Claude
Claude Opus 5.5
รวม sim-fair (b2462d5) เข้า eval-movex-old · ผู้ใช้จำลอง v2 รันกับ agent v31 ได้
21cf25d unverified
Raw History Blame Contribute Delete
20.9 kB
"""
test_simulate_customers.py — ท่อของ simulate_customers.py แบบไม่ใช้ LLM (ลูกค้าจำลองตามบท · บอทผ่าน TurnEngine จริง)
python test_simulate_customers.py
"""
from __future__ import annotations
import os as _os, sys as _sys # รากของ repo: import แพ็กเกจได้ และพาธข้อมูลนับจากราก
_ROOT = _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))
if _ROOT not in _sys.path:
_sys.path.insert(0, _ROOT)
_os.chdir(_ROOT)
import json
import os
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from eval import simulate_customers as SC # noqa: E402
import test_conversation_leaks as L # noqa: E402
passed = failed = 0
def ok(name, cond, detail=""):
global passed, failed
if cond:
passed += 1
print(f" ✓ {name}")
else:
failed += 1
print(f" ✗ {name} {detail}")
goals = {g["id"]: g for g in SC.load_goals(os.path.join(ROOT, "training", "sim_goals.json"))}
judge = SC.Judge()
print("1) ชุดรุ่นที่ถูก (โค้ด ไม่ใช่ LLM)")
acc = judge.acceptable(goals["G01"])
ok("G01 ไก่ตัดแต่ง 50.8 · 5 °C เปียก → มีรุ่น และทุกรุ่นพิทช์ 50.8", acc["ok"] and all(
judge.cat.by_code[c]["specifications"]["pitch"]["mm"] == 50.8 for c in acc["ok"]), acc)
ok("G02 เตาอบ 25.4 · 120 °C แห้ง → ชุดว่าง (คาดว่าบอทต้องบอกว่าไม่มี)", judge.acceptable(goals["G02"])["ok"] == [])
ok("ทุกเป้าหมายมี id ไม่ซ้ำ และ Modutech มี application", len(goals) == len(SC.load_goals(
os.path.join(ROOT, "training", "sim_goals.json"))) and all(g.get("application") for g in goals.values()))
print("\n2) ให้คะแนน")
tr = [{"role": "customer", "text": "x"}, {"role": "bot", "text": "แนะนำ MP80 C และ EC508 C ครับ"}]
s = SC.score(goals["G01"], tr, judge, "done")
ok("MP80 C (พิทช์ 8) ผิดเงื่อนไขพิทช์ 50.8 → violation · EC508 C ถูก → hit", s["violations"] == ["MP80 C"]
and s["hit"], s)
tr = [{"role": "customer", "text": "x"}, {"role": "bot", "text": "ไม่มีรุ่นที่ตรงทุกเงื่อนไขครับ"}]
ok("ชุดว่าง + บอทบอกว่าไม่มี → hit", SC.score(goals["G02"], tr, judge, "done")["hit"])
tr = [{"role": "customer", "text": "a"}, {"role": "bot", "text": "ถามซ้ำ"}, {"role": "customer", "text": "b"},
{"role": "bot", "text": "ถามซ้ำ"}, {"role": "customer", "text": "c"},
{"role": "bot", "text": "ขออภัยครับ ผมตอบได้เฉพาะเรื่องสินค้า"}]
s = SC.score(goals["G01"], tr, judge, "giveup")
ok("นับข้อความซ้ำติดกัน + นอกเรื่อง", s["repeats"] == 1 and s["offtopic"] == 1 and not s["hit"], s)
ok("Movex: เจอ K450 → hit", SC.score(goals["G13"], [{"role": "bot", "text": "LF 880 TAB K450 กว้าง 114.3"}],
judge, "done")["hit"])
print("\n3) วนคุยทั้งเส้น (ลูกค้าตามบท · บอทผ่าน TurnEngine จริง)")
rec = L.Recorder()
eng = L.new_engine(rec)
SCRIPT = ["modutech", "ไก่ ไลน์ตัดแต่ง", "ประมาณ 50 มิลครับ", "ใช่", "5 องศา", "เปียก", "โอเคครับ [จบ]"]
calls = {"i": 0}
def fake_complete(system, user, json_mode=False, temperature=None):
assert "ห้ามคิดชื่อรุ่น" in system and "หัวหน้าไลน์" in system
m = SCRIPT[calls["i"]]
calls["i"] += 1
return m
def chat_fn(text, image, history, last_pids, session_id, vit, graph):
return eng.chat(text, image, history, last_pids, session_id or "s", vit, graph)
r = SC.run_goal(goals["G01"], chat_fn, fake_complete, judge, max_turns=10, temperature=1.0)
bot = [t["text"] for t in r["transcript"] if t["role"] == "bot"]
ok("ถามแบรนด์ → ถามงาน → พิทช์ → ยืนยัน 50.8 → อุณหภูมิ", "แบบไหน" in bot[0] and "ลำเลียงอะไร" in bot[1]
and "พิทช์" in bot[2] and "หมายถึง 50.8" in bot[3] and "อุณหภูมิ" in bot[4], [b[:30] for b in bot])
ok("จบแบบ done · ได้รุ่นที่ถูก · ไม่มีรุ่นผิดเงื่อนไข", r["ended"] == "done" and r["hit"] and not r["violations"], r)
ok("ไม่ส่ง [จบ] ไปหาบอท", all("[จบ]" not in t["text"] for t in r["transcript"]))
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "x.txt")
SC.write_txt(p, [dict(r, run=1)])
txt = open(p, encoding="utf-8").read()
ok("ไฟล์ .txt เป็นแชท ลูกค้า/บอท (บอทมีเลขข้อความไว้อ้างถึงใน 🚩)", "🧑 ลูกค้า: ไก่ ไลน์ตัดแต่ง" in txt and "🤖 บอท [1]:" in txt)
summ = SC.summarize([r])
ok("สรุป: hit 100% · ไม่มีผิดเงื่อนไข", summ["hit_pct"] == 100.0 and summ["with_violation_pct"] == 0.0, summ)
lat = summ["latency_sec"]
ok("เวลา: ทุกเทิร์นของบอทมี sec · แยกเทิร์นตอบคำถามค้าง (กฎ) ออกจากเทิร์นอื่น",
lat["all_turns"]["n"] == len(bot) and lat["answer_turns"]["n"] >= 3 and lat["answer_turns_by"].get("กฎ", 0) >= 3
and lat["answer_turns"]["n"] + lat["other_turns"]["n"] == lat["all_turns"]["n"], lat)
print("\n4) ตัวตีความ LLM (ปลอม · หน่วง 50 มิลลิวินาที) — วัดเวลาที่เพิ่ม")
import time as _t # noqa: E402
from engine.core.answer_interpreter import AnswerInterpreter # noqa: E402
def slow_llm(system, user, json_mode=False, temperature=None):
_t.sleep(0.05)
ans = user.split("คำตอบของลูกค้า: ")[-1]
if "มิล" in ans:
return '{"kind":"value","value":50,"unit":"mm"}'
if ans.strip() == "ใช่":
return '{"kind":"yes"}'
if "องศา" in ans:
return '{"kind":"value","value":5,"unit":"c"}'
return '{"kind":"value","wet_or_dry":"wet"}'
interp = AnswerInterpreter(slow_llm)
L.MOD._interpreter = interp
rec2 = L.Recorder()
eng = L.new_engine(rec2)
calls["i"] = 0
r2 = SC.run_goal(goals["G01"], chat_fn, fake_complete, judge, max_turns=10, temperature=1.0, interpreter=interp)
lat2 = SC.summarize([r2])["latency_sec"]
# 26 ต.ค.: กฎก่อน LLM — คำตอบในบทนี้ชัดทั้งหมด ("ประมาณ 50 มิลครับ" "ใช่" "5 องศา" "เปียก") จึงไม่เรียก LLM เลย
ok("คำตอบชัด → กฎอ่านทุกเทิร์น ไม่เสียเวลาเรียก LLM", lat2["answer_turns_by"].get("กฎ", 0) >= 3
and lat2["answer_turns_by"].get("LLM", 0) == 0 and interp.calls == 0, (lat2, interp.calls))
ok("ได้ผลเหมือนกฎ (hit · ไม่มีรุ่นผิดเงื่อนไข)", r2["hit"] and not r2["violations"], r2.get("violations"))
SCRIPT[2] = "เท่าของเดิมแหละ ราว ๆ สองนิ้วมั้ง" # กฎอ่านไม่ออก → LLM
calls["i"] = 0
_orig = slow_llm
def slow_llm2(system, user, json_mode=False, temperature=None):
if "สองนิ้ว" in user:
_t.sleep(0.05)
return '{"kind":"value","value":2,"unit":"inch"}'
return _orig(system, user, json_mode, temperature)
interp = AnswerInterpreter(slow_llm2)
L.MOD._interpreter = interp
eng = L.new_engine(L.Recorder())
r3 = SC.run_goal(goals["G01"], chat_fn, fake_complete, judge, max_turns=10, temperature=1.0, interpreter=interp)
lat3 = SC.summarize([r3])["latency_sec"]
ok("คำตอบที่กฎอ่านไม่ออก → LLM เฉพาะเทิร์นนั้น (\"สองนิ้วมั้ง\" · \"ใช่\" ตอนถามอุณหภูมิ) · interp_ms ≥ 50 · ได้รุ่นที่ถูก",
lat3["answer_turns_by"].get("LLM") == 2 and interp.calls == 2
and lat3["interpreter_ms"]["median"] >= 50 and r3["hit"] and not r3["violations"], (lat3, interp.calls))
with tempfile.TemporaryDirectory() as d:
pa, pb = os.path.join(d, "a.json"), os.path.join(d, "b.json")
json.dump({"answer_interpreter": "rules", "summary": summ}, open(pa, "w", encoding="utf-8"))
json.dump({"answer_interpreter": "llm", "summary": SC.summarize([r2])}, open(pb, "w", encoding="utf-8"))
import io, contextlib # noqa: E401,E402
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
SC.compare(pa, pb)
ok("--compare พิมพ์ตารางคุณภาพ + เวลา", "answer_turns" in buf.getvalue() and "hit_pct" in buf.getvalue(), buf.getvalue()[:200])
L.MOD._interpreter = None
L.MOD.runtime = None
print("\nredteam r3 (27 ต.ค.) ตัดสินเฉพาะเงื่อนไขที่ลูกค้าพิมพ์แล้ว")
_g = {"id": "T", "brand": "modutech", "application": "เครื่องตรวจจับโลหะ", "opening": "สายพาน modutech สำหรับเครื่องตรวจจับโลหะ",
"pitch_mm": 12.7, "temp_c": 30, "wet_or_dry": "dry"}
_tr = [{"role": "customer", "text": "สายพาน modutech สำหรับเครื่องตรวจจับโลหะ ตัวไหนดี"}, {"role": "bot", "text": "พิทช์เท่าไหร่ครับ"},
{"role": "customer", "text": "ห้องปกติ แห้ง"}, {"role": "bot", "text": "แนะนำ EC254 C และ EC127 C ครับ"}]
_s = SC.score(_g, _tr, judge, "done")
ok("ลูกค้าไม่เคยบอกพิทช์ → เสนอพิทช์อื่นไม่ผิดเงื่อนไข (R13#2)", _s["final_violations"] == [], _s["final_violations"])
_tr2 = _tr[:2] + [{"role": "customer", "text": "ครึ่งนิ้ว แห้ง ห้องปกติ"}, _tr[3]]
_s2 = SC.score(_g, _tr2, judge, "done")
ok("ลูกค้าบอกครึ่งนิ้วแล้ว → EC254 C ผิดเงื่อนไข", _s2["final_violations"] == ["EC254 C"], _s2["final_violations"])
print("\nชุด blind (2 พ.ย.) goal ให้คำตอบที่ถูกมาเอง → ไม่ใช้ need_flow ของบอท")
_gb = dict(_g, accept_codes=["EC127 C"], hard_ok_codes=["EC127 C", "HC127 C"],
hard_ok_by_stated={"temp+wet": ["EC127 C", "EC254 C"]})
ok("acceptable ใช้ชุดจาก goal", judge.acceptable(_gb)["ok"] == ["EC127 C"] and judge.acceptable(_gb)["source"] == "goal")
_s3 = SC.score(_gb, _tr, judge, "done")
ok("ยังไม่บอกพิทช์ → ใช้ hard_ok_by_stated['temp+wet']", _s3["final_violations"] == [], _s3["final_violations"])
_s4 = SC.score(_gb, _tr2, judge, "done")
ok("บอกครบแล้ว → EC254 C ไม่อยู่ใน hard_ok_codes", _s4["final_violations"] == ["EC254 C"], _s4["final_violations"])
_gn = dict(_g, accept_codes=[], hard_ok_codes=["EC508 C"], pitch_mm=50.8)
_trn = [{"role": "customer", "text": "ไลน์แช่แข็ง พิทช์ 1 นิ้ว แห้ง"}, {"role": "bot", "text": "แนะนำ EC254 NT ครับ"},
{"role": "customer", "text": "เดี๋ยวครับ พิทช์ 2 นิ้ว"}, {"role": "bot", "text": "พิทช์ 2 นิ้วไม่มีรุ่นที่แคตตาล็อกระบุงานนี้ครับ"}]
_s5 = SC.score(_gn, _trn, judge, "done")
ok("เปลี่ยนใจกลางทาง: แนะนำถูกก่อนเปลี่ยน + บอกไม่มีหลังเปลี่ยน → hit", _s5["hit"] is True, (_s5["hit"], _s5["final_violations"]))
print("\nsim-fair (4 พ.ย.) ก. ลูกค้าแยกจากระบบ · ค. ป้าย tactic — ของปลอมทั้งหมด ไม่เรียก API")
import contextlib as _cl # noqa: E402
import io as _io # noqa: E402
import sim_fair_fakes as F # noqa: E402
_GOLD = os.path.join(ROOT, "tests", "golden")
_ENV = ("SIM_CUSTOMER_MODEL", "SIM_CUSTOMER_THINKING", "SIM_TACTIC_LABEL", "GEMINI_THINKING")
def _run(module, extra=("--repeats", "2"), env=None):
saved = {k: os.environ.get(k) for k in _ENV}
for k in _ENV:
os.environ.pop(k, None)
os.environ.update(env or {})
try:
with tempfile.TemporaryDirectory() as d, _cl.redirect_stdout(_io.StringIO()):
res, txt = F.run_main(SC, module, d, list(extra))
return res, txt
finally:
for k, v in saved.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
def _same_as_golden(res, txt):
g = json.load(open(os.path.join(_GOLD, "sim_fake_bot.json"), encoding="utf-8"))
a = json.dumps(F.strip_volatile(res), sort_keys=True, ensure_ascii=False)
b = json.dumps(g, sort_keys=True, ensure_ascii=False)
return a == b and txt == open(os.path.join(_GOLD, "sim_fake_bot.txt"), encoding="utf-8").read()
_built = []
def _factory(model, thinking_raw):
c = F.FakeLLM(name=f"cust:{model}", usage=(1000, 10))
c.thinking_raw = thinking_raw
_built.append(c)
return c
_orig_build = SC.build_customer_client
SC.build_customer_client = _factory
b = F.make_bot_module()
res, txt = _run("fake_sim_bot")
ok("A1 ไม่ตั้ง env → json + txt เท่า golden ของ 509ae12 (ตัดเฉพาะ seconds/sec/interp_ms/latency_sec)",
_same_as_golden(res, txt))
ok("A1 meta ไม่มีคีย์ใหม่ · บทไม่มี usage", not ({"customer_model", "customer_source", "tactic_label"} & set(res))
and all("usage" not in t for r in res["results"] for t in r["transcript"]))
ok("A2 ไม่ตั้ง env → ลูกค้าใช้ bot.llm_client · ไม่สร้าง client แยก", len(b.llm_client.prompts) > 0 and not _built,
(len(b.llm_client.prompts), len(_built)))
b = F.make_bot_module()
res, txt = _run("fake_sim_bot", env={"SIM_CUSTOMER_MODEL": ""})
ok("A10 SIM_CUSTOMER_MODEL ว่าง = ไม่ตั้ง", _same_as_golden(res, txt) and not _built)
b = F.make_bot_module()
res, txt = _run("fake_sim_bot", env={"SIM_CUSTOMER_MODEL": "fake-cust", "SIM_CUSTOMER_THINKING": "none-x",
"GEMINI_THINKING": "low"})
cust = _built[-1] if _built else None
ok("A3 ตั้ง SIM_CUSTOMER_MODEL → prompt ลูกค้าไปที่ client แยกเท่านั้น", cust is not None and len(cust.prompts) > 0
and not b.llm_client.prompts and len(_built) == 1, (len(_built), len(b.llm_client.prompts)))
ok("A3 client แยกสร้างด้วยรุ่น fake-cust", cust is not None and cust.name == "cust:fake-cust")
ok("A4 thinking ของลูกค้าแยก · GEMINI_THINKING ของระบบไม่เปลี่ยน", cust is not None and cust.thinking_raw == "none-x"
and res.get("customer_thinking") == "none-x")
ok("A7 meta: customer_model · customer_thinking · customer_source=separate · llm ของระบบ",
res.get("customer_model") == "fake-cust" and res.get("customer_source") == "separate"
and res.get("llm") == "fake · bot" and res.get("customer_llm") == "fake · cust:fake-cust", {k: res.get(k) for k in
("customer_model", "customer_source", "llm", "customer_llm")})
bot_turns = sum(t["role"] == "bot" for r in res["results"] for t in r["transcript"])
ct = res.get("customer_usage_total") or {}
st = res.get("system_usage_total") or {}
ok("A8 โทเคนไม่ปน: ระบบ = 10 × เทิร์นบอท · ลูกค้า = 1010 × ครั้งที่ลูกค้าเรียก",
st.get("total_token_count") == 10 * bot_turns and ct.get("total_token_count") == 1010 * len(cust.prompts)
and st.get("prompt_token_count") == 7 * bot_turns, (st, ct, bot_turns))
import hashlib as _hl # noqa: E402
ok("A7 meta หลักฐาน: goals · goals_sha (sha256 ของไฟล์ที่ใช้จริง) · system_info.system=bot",
res.get("goals", "").endswith("goals.json") and len(res.get("goals_sha", "")) == 64
and res.get("system_info", {}).get("system") == "bot" and "commit" in res.get("system_info", {}), res.get("system_info"))
ok("A9 ทุกเทิร์นบอทมี usage ของเทิร์นนั้นเท่านั้น (7/3 · ไม่สะสมข้ามเทิร์น)",
all(t.get("usage", {}).get("total_token_count") == 10 and t["usage"]["llm_calls"] == 1
for r in res["results"] for t in r["transcript"] if t["role"] == "bot"))
F.make_agent_module()
saved_out = None
try:
with tempfile.TemporaryDirectory() as d, _cl.redirect_stdout(_io.StringIO()):
for k in _ENV:
os.environ.pop(k, None)
F.run_main(SC, "fake_sim_agent", d, [])
except SystemExit as e:
saved_out = str(e)
with tempfile.TemporaryDirectory() as d:
pass
ok("A5 agent ไม่มี llm_client + ไม่ตั้ง env → หยุด (SystemExit ไม่ใช่ AttributeError) ข้อความไทยบอกให้ตั้ง",
saved_out is not None and "SIM_CUSTOMER_MODEL" in saved_out and "ไม่มี llm_client" in saved_out, saved_out)
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "out.json")
try:
with _cl.redirect_stdout(_io.StringIO()):
sys.argv = ["x", "--module", "fake_sim_agent", "--goals", F.write_goals(d), "-o", out]
SC.main()
except SystemExit:
pass
ok("A5 ไม่มีไฟล์ผลถูกเขียน", not os.path.exists(out))
F.make_agent_module()
res, txt = _run("fake_sim_agent", env={"SIM_CUSTOMER_MODEL": "fake-cust"})
ok("A6 agent + SIM_CUSTOMER_MODEL → รันครบทุกเป้าหมาย · โครงไฟล์เหมือนของบอท",
len(res["results"]) == 4 and {"summary", "results", "module", "llm"} <= set(res) and res["llm"] == "fake agent")
ok("A6 โทเคนของ agent ต่อเทิร์นมาจาก engine.llm.last_usage",
all(t.get("usage", {}).get("total_token_count") == 10 for r in res["results"] for t in r["transcript"]
if t["role"] == "bot"))
F.make_agent_module(with_meter=False)
res, txt = _run("fake_sim_agent", env={"SIM_CUSTOMER_MODEL": "fake-cust"})
ok("A9 module ที่ไม่มีตัวนับ → usage = null (ไม่ใช่ 0) · system_usage_total = null",
all(t.get("usage", "x") is None for r in res["results"] for t in r["transcript"] if t["role"] == "bot")
and res.get("system_usage_total") is None)
n_before = len(_built)
b = F.make_bot_module()
res, txt = _run("fake_sim_bot", env={"SIM_TACTIC_LABEL": "1"})
hdr = [ln for ln in txt.splitlines() if ln.startswith("tactic: ")]
ok("C1 .txt ทุกบทมีบรรทัด tactic ตรงกับเป้าหมาย (ไม่มี tactic → (ไม่ระบุ))",
hdr == ["tactic: (ไม่ระบุ)"] * 2 + [f"tactic: {F.GOALS['goals'][1]['tactic']}"] * 2, hdr)
ok("C2 json ทุกบทมี tactic_checked: null", all("tactic_checked" in r and r["tactic_checked"] is None
for r in res["results"]))
ok("C3 ไม่มีการเรียก LLM เพิ่ม (ไม่ใช้ LLM ตัดสิน)", len(b.llm_client.prompts) == 8 and len(_built) == n_before,
len(b.llm_client.prompts))
b = F.make_bot_module()
res, txt = _run("fake_sim_bot", env={"SIM_TACTIC_LABEL": "0"})
ok("C5 SIM_TACTIC_LABEL ไม่ใช่ 1 → เท่า golden", _same_as_golden(res, txt))
SC.build_customer_client = _orig_build
print(f"\nรวม {passed}/{passed + failed}")
sys.exit(1 if failed else 0)