feat(chat): scenario-based training — choice of channel/Situation + realistic per-turn evaluation
Backend:
- Channel/initiation now driven by a SCENARIO chosen at chat start, not baked into the
persona: social (customer opens), f2f_call (seller must open, proactive), recontact
(customer re-contacts after 1-3 months).
- /chat/start accepts {scenario}; session stores scenario + internal{turns,score}.
- persona_reply takes scenario + adapts tone; system-role transcript entries are fed to
the persona as hidden scene notes.
- JUDGE updated for realism: good response can WIN even in hard/tough-text scenarios;
long/no-close chats (turns >~12) lose; pushy/ignoring-need loses. Efficiency rewarded.
Frontend:
- Scenario picker before chat (choose Social / Face-to-face-call / Re-contact).
- Chat thread renders role=system as a centered time-lapse/scene note.
- Choose-scenario i18n (EN+TH).
Rebuilt dist.
This commit is contained in:
@@ -27,6 +27,35 @@ def _sim(group, persona):
|
||||
return Simulator(llm)
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"social": {
|
||||
"label": "Social Media",
|
||||
"init": "customer",
|
||||
"system_preamble": "💬 ช่องทาง ข้อความโซเชียล — ลูกค้าทักมาหาคุณก่อน (โทนสั้น ทักๆ ตามสไตล์แชท)",
|
||||
"adapt": "You are chatting on a social-messaging app (LINE-style). Keep replies SHORT, casual, and quick — one line to a few lines. The customer opened the chat.",
|
||||
},
|
||||
"f2f_call": {
|
||||
"label": "พบหน้า / โทรศัพท์",
|
||||
"init": "seller",
|
||||
"system_preamble": "📞 สถานการณ์ พบหน้าหรือโทรศัพท์ — คุณต้องเป็นฝ่ายเปิดการสนทนาเชิงรุกกับลีด (lead)",
|
||||
"adapt": "This is a face-to-face or phone sales situation. You must sound natural and conversational like a live talk. The seller will open — you are the lead they are reaching out to.",
|
||||
},
|
||||
"recontact": {
|
||||
"label": "ลูกค้ากลับมาติดต่อ (เคยได้ข้อมูล 1-3 เดือน)",
|
||||
"init": "customer",
|
||||
"system_preamble": "⏳ 1-3 เดือนผ่านไป... ลูกค้าคนนี้เคยได้รับข้อมูลสินค้าไปแล้ว ตอนนี้กลับมาติดต่อคุณอีกครั้ง (พร้อมตัดสินใจมากขึ้น)",
|
||||
"adapt": "This customer researched you 1-3 months ago. They have already read about the product and are now more ready to decide. They re-contacted you on a messaging channel. Keep replies natural and fairly concise.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _scenario_config(scenario: str, persona: dict):
|
||||
cfg = SCENARIOS.get(scenario, SCENARIOS["social"])
|
||||
# OR with persona's own initiation preference: f2f/call forces seller-first unless persona
|
||||
# is strongly customer-initiated (we let scenario win, but keep persona special handling).
|
||||
return cfg, cfg["init"]
|
||||
|
||||
|
||||
def _get_ready_group(s, gid: str) -> dict:
|
||||
"""Org-scoped group access for trainees + require ready status (IDOR defense)."""
|
||||
group = s["groups"].get_or_none(gid)
|
||||
@@ -53,6 +82,12 @@ def start_session(gid: str, pid: str):
|
||||
if not persona:
|
||||
raise ApiError("persona not found", 404)
|
||||
actor = current_user()
|
||||
# Scenario chosen by the trainee at chat start (not baked into the persona).
|
||||
body = request.get_json(silent=True) or {}
|
||||
scenario = (body.get("scenario") or "social").strip().lower()
|
||||
if scenario not in ("social", "f2f_call", "recontact"):
|
||||
scenario = "social"
|
||||
scenario_meta, init_mode = _scenario_config(scenario, persona)
|
||||
# One-shot: reject if already finished this persona
|
||||
try:
|
||||
session = s["sessions"].create(
|
||||
@@ -60,27 +95,35 @@ def start_session(gid: str, pid: str):
|
||||
persona_name=persona.get("name", "?"),
|
||||
persona_meta={
|
||||
"tier": persona.get("tier"),
|
||||
"initiation_mode": persona.get("initiation_mode"),
|
||||
"initiation_mode": init_mode,
|
||||
"channel": persona.get("channel"),
|
||||
"scenario": scenario,
|
||||
},
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ApiError(str(exc), 400)
|
||||
|
||||
s["sessions"].update(
|
||||
session["id"],
|
||||
scenario=scenario,
|
||||
internal={**(session.get("internal") or {}), "turns": 0, "score": 50, "signals": []},
|
||||
)
|
||||
sim = _sim(group, persona)
|
||||
# Seller-initiated: give the trainee an opening task (no persona message yet).
|
||||
init_mode = persona.get("initiation_mode", "customer")
|
||||
# Seed messages: system note(s) then customer opener for customer-first scenarios.
|
||||
seeded = list(session.get("messages", []))
|
||||
if scenario_meta.get("system_preamble"):
|
||||
seeded.append({"role": "system", "text": scenario_meta["system_preamble"]})
|
||||
if init_mode == "customer":
|
||||
# Customer opens: inject the persona's opener as the first message.
|
||||
opener = persona.get("opener") or "Hi, I saw your product and had a question."
|
||||
s["sessions"].update(session["id"], messages=[{"role": "customer", "text": opener}])
|
||||
else:
|
||||
s["sessions"].update(
|
||||
session["id"],
|
||||
task="The customer did NOT message first. You must open the sale — start the "
|
||||
"conversation with this lead (e.g. introduce yourself and engage with interest).",
|
||||
)
|
||||
return jsonify({"session": s["sessions"].get(session["id"]), "initiation_mode": init_mode})
|
||||
seeded.append({"role": "customer", "text": opener})
|
||||
s["sessions"].update(session["id"], messages=seeded)
|
||||
sess = s["sessions"].get(session["id"])
|
||||
return jsonify({
|
||||
"session": sess,
|
||||
"initiation_mode": init_mode,
|
||||
"scenario": scenario,
|
||||
"scenario_meta": scenario_meta,
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.post("/<gid>/personas/<pid>/chat/send")
|
||||
@@ -106,6 +149,8 @@ def send_message(gid: str, pid: str):
|
||||
raise ApiError("session context missing", 404)
|
||||
messages = list(session.get("messages", []))
|
||||
messages.append({"role": "seller", "text": text})
|
||||
scenario = session.get("scenario", "social") or "social"
|
||||
adapt = SCENARIOS.get(scenario, SCENARIOS["social"]).get("adapt", "")
|
||||
|
||||
sim = _sim(group, persona)
|
||||
try:
|
||||
@@ -114,12 +159,19 @@ def send_message(gid: str, pid: str):
|
||||
sales_kit=group.get("sales_kit") or {},
|
||||
messages=messages,
|
||||
internal=session.get("internal", {}),
|
||||
scenario=scenario,
|
||||
scenario_adapt=adapt,
|
||||
)
|
||||
except LLMError as exc:
|
||||
raise ApiError(f"LLM error: {exc}", 500)
|
||||
messages.append({"role": "customer", "text": reply})
|
||||
|
||||
s["sessions"].update(session["id"], messages=messages)
|
||||
# Per-turn tracking: count exchanged turns + nudge score down as the chat drags.
|
||||
internal = session.get("internal", {}) or {}
|
||||
internal.setdefault("turns", 0)
|
||||
internal["turns"] = internal.get("turns", 0) + 1
|
||||
|
||||
s["sessions"].update(session["id"], messages=messages, internal=internal)
|
||||
return jsonify({"reply": reply, "messages": messages})
|
||||
|
||||
|
||||
@@ -139,7 +191,9 @@ def finish_session(gid: str, pid: str):
|
||||
sim = _sim(group, persona)
|
||||
messages = session.get("messages", [])
|
||||
try:
|
||||
verdict = sim.judge(persona=persona, messages=messages)
|
||||
verdict = sim.judge(
|
||||
persona=persona, messages=messages, internal=session.get("internal", {})
|
||||
)
|
||||
except LLMError as exc:
|
||||
raise ApiError(f"LLM error: {exc}", 500)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user