feat: async analyze + frontend polling, quota enforcement, persona tier batching

- analyze returns 202 immediately; frontend polls group status (3s interval, 30min cap)
- quota system: atomic check-and-consume, trial/team/enterprise plans, 402 on exceed
- persona generation split into tier batches (Cloudflare 120s limit safe)
- LLM client: 105s timeout, thinking param for reasoning models
- tests: quota suite (4), persona cardinality/initiation updates
This commit is contained in:
Macky committed 2026-10-01 15:19:46 +07:00
1 parent 1ad21cc8f1
commit df0428d7d2
15 files changed
+930 -147

No files matched your search

+26 -1
View File
@@ -5,7 +5,7 @@ from collections.abc import Collection
import functools
import math
from flask import Blueprint, jsonify, request
from flask import Blueprint, current_app, jsonify, request
from ..config import Config
from ..llm import LLMError
@@ -581,6 +581,31 @@ def start_session(gid: str, pid: str):
and "owner_user_id" not in group
):
requested_mode = "trainee"
# Quota: only brand-new trainee sessions consume a monthly slot. A resume
# (an active session already exists in this scope) and preview sessions do
# not. Check-and-consume is atomic per org; a storage fault fails closed.
if requested_mode == "trainee":
existing_active = s["sessions"].active_for_scope(
org_id=org_id,
user_id=actor["id"],
group_id=gid,
persona_id=pid,
mode="trainee",
)
if existing_active is None:
user_store = current_app.extensions["user_store"]
org = user_store.get_org_or_none(org_id) or {}
plan = org.get("plan", "trial")
seats = org.get("seats", 5)
quota = current_app.extensions["quota"]
result = quota.check_and_consume(org_id, plan, seats)
if not result.get("allowed"):
raise ApiError(
"monthly session quota reached — contact us to upgrade your plan",
402,
)
scenario_raw = body.get("scenario", "social")
scenario = _safe_scenario(
scenario_raw.strip().lower() if isinstance(scenario_raw, str) else scenario_raw
+130 -63
View File
@@ -609,10 +609,13 @@ def list_groups():
@require_roles("user", "admin")
@_group_analysis_lock
def analyze_group(gid: str):
"""Run one deterministic analysis: sales kit + exactly 15 personas.
"""Start one deterministic analysis: sales kit + exactly 15 personas.
A trainee may analyze their own private group (owner marker); an admin may
analyze (or re-analyze) any org-shared group.
The analysis runs in a background thread (it makes ~17 sequential LLM calls that
take many minutes on the local model), so this returns 202 immediately and the
client polls GET /groups/<gid> until status is "ready" or "failed". A trainee may
analyze their own private group (owner marker); an admin may analyze (or
re-analyze) any org-shared group.
"""
s = _stores()
# The owner (user or admin) may analyze; super_admin may analyze any group.
@@ -647,71 +650,135 @@ def analyze_group(gid: str):
else "facebook"
)
# A group already "analyzing" is either (a) a live background analysis in flight,
# or (b) a stale one left by a dead process. Re-analyzing a live one is a no-op
# (return 202, keep polling); a stale one is reset to failed and re-run.
if group.get("status") == "analyzing" and not _is_stale_analyzing(group):
return jsonify({"group": serialize_group(group, current_user()), "status": "analyzing"}), 202
s["groups"].update(gid, status="analyzing", error=None, analysis_started_at=_now_iso())
app = current_app._get_current_object()
llm = s["llm"]
if app.testing:
# Keep route tests deterministic: execute the worker inline under Flask's
# test config so assertions can inspect the published record immediately.
_run_analysis(app, gid, inp, persona_channel, llm)
published = s["groups"].get(gid)
if published.get("status") == "failed":
raise internal_error("analysis failed", RuntimeError("analysis failed"))
serialized = serialize_group(published, current_user())
return jsonify({
"group": serialized,
"sales_kit": serialized.get("sales_kit"),
"personas": serialized["personas"],
})
thread = threading.Thread(
target=_run_analysis,
args=(app, gid, inp, persona_channel, llm),
name=f"analyze-{gid}",
daemon=True,
)
thread.start()
started = s["groups"].get(gid)
return jsonify({"group": serialize_group(started, current_user()), "status": "analyzing"}), 202
# How long a group may sit in "analyzing" before we treat it as stale (a dead
# process left it there). Generous: a full analysis on the local model can take
# ~15 minutes, so 30 minutes leaves headroom.
_ANALYZE_STALE_SECONDS = 30 * 60
def _now_iso() -> str:
from datetime import datetime, timezone
return datetime.now(timezone.utc).isoformat()
def _is_stale_analyzing(group: dict) -> bool:
"""True if a group has been stuck in 'analyzing' longer than the stale window.
A dead process (crash, deploy, OOM) leaves the group 'analyzing' forever; after the
window we treat it as failed so the next analyze/poll can recover it.
"""
from datetime import datetime, timezone
started = group.get("analysis_started_at")
# Legacy/stale records from before async tracking have no start marker; they
# cannot correspond to a live background worker, so allow recovery immediately.
if started is None:
return True
if not isinstance(started, str) or not started.strip():
return True
try:
ts = datetime.fromisoformat(started)
except ValueError:
return False
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - ts).total_seconds()
return age > _ANALYZE_STALE_SECONDS
def _run_analysis(app, gid: str, inp: dict, persona_channel: str, llm) -> None:
"""Background worker: sales kit + 15 personas + report, then publish (or fail)."""
from ..services.analyzer import Analyzer
from ..services.persona_generator import PersonaGenerator
s["groups"].update(gid, status="analyzing", error=None)
try:
sales_kit = Analyzer(s["llm"]).analyze(
product=inp.get("product", ""),
segment=inp.get("segment", ""),
description=inp.get("description", ""),
file_text=inp.get("file_text", ""),
channel=inp.get("channel", "social"),
)
except Exception as exc:
s["groups"].update(gid, status="failed", error="analysis_failed")
raise internal_error("analysis failed", exc)
try:
generated_personas = PersonaGenerator(s["llm"]).generate(
sales_kit=sales_kit,
language=inp.get("language", "th"),
channel=persona_channel,
)
if not isinstance(generated_personas, list) or not generated_personas:
raise ValueError("persona generation returned no usable personas")
personas = [_validated_persona(persona) for persona in generated_personas]
if any(persona is None for persona in personas):
raise ValueError("persona generation returned malformed personas")
personas = [persona for persona in personas if persona is not None]
except Exception as exc:
s["groups"].update(gid, status="failed", error="analysis_failed")
raise internal_error("analysis failed", exc)
# Analysis replaces the generated base personas, but preserves accepted
# variants that were appended in the previous ready state.
current_before_publish = s["groups"].get(gid)
personas = _merge_preserved_variants(
current_before_publish.get("personas") if isinstance(current_before_publish, dict) else [],
personas,
)
from ..services.report import build_report
try:
report = build_report(sales_kit=sales_kit, personas=personas, language=inp.get("language", "th"))
except Exception as exc:
s["groups"].update(gid, status="failed", error="analysis_failed")
raise internal_error("analysis failed", exc)
# Publish the completed analysis as one atomic record replacement. Readers
# do not take the group mutation lock, so status must never become ready
# before personas/report/sales_kit are visible together.
try:
published = s["groups"].publish_analysis(
gid,
sales_kit=sales_kit,
personas=personas,
report=report,
with app.app_context():
s = _stores()
try:
sales_kit = Analyzer(llm).analyze(
product=inp.get("product", ""),
segment=inp.get("segment", ""),
description=inp.get("description", ""),
file_text=inp.get("file_text", ""),
channel=inp.get("channel", "social"),
)
except Exception:
s["groups"].update(gid, status="failed", error="analysis_failed")
return
try:
generated_personas = PersonaGenerator(llm).generate(
sales_kit=sales_kit,
language=inp.get("language", "th"),
channel=persona_channel,
)
if not isinstance(generated_personas, list) or not generated_personas:
raise ValueError("persona generation returned no usable personas")
personas = [_validated_persona(persona) for persona in generated_personas]
if any(persona is None for persona in personas):
raise ValueError("persona generation returned malformed personas")
personas = [persona for persona in personas if persona is not None]
except Exception:
s["groups"].update(gid, status="failed", error="analysis_failed")
return
# Analysis replaces the generated base personas, but preserves accepted
# variants that were appended in the previous ready state.
current_before_publish = s["groups"].get(gid)
personas = _merge_preserved_variants(
current_before_publish.get("personas") if isinstance(current_before_publish, dict) else [],
personas,
)
except (TypeError, ValueError) as exc:
s["groups"].update(gid, status="failed", error="analysis_failed")
raise internal_error("analysis failed", exc)
serialized = serialize_group(published, current_user())
return jsonify({
"group": serialized,
"sales_kit": serialized.get("sales_kit"),
"personas": serialized["personas"],
})
try:
report = build_report(sales_kit=sales_kit, personas=personas, language=inp.get("language", "th"))
except Exception:
s["groups"].update(gid, status="failed", error="analysis_failed")
return
# Publish the completed analysis as one atomic record replacement. Readers
# do not take the group mutation lock, so status must never become ready
# before personas/report/sales_kit are visible together.
try:
s["groups"].publish_analysis(
gid,
sales_kit=sales_kit,
personas=personas,
report=report,
)
except (TypeError, ValueError):
s["groups"].update(gid, status="failed", error="analysis_failed")
@groups_bp.get("/<gid>")
+18
View File
@@ -114,6 +114,24 @@ def _authorized_finished_trainee_sessions(
return authorized
@me_bp.get("/quota")
@require_auth
def quota_status():
"""Current org's monthly session quota usage (any authenticated user)."""
from flask import current_app
actor = current_user()
org_id = actor.get("org_id")
if not is_valid_tenant_id(org_id):
raise ApiError("permission denied", 403)
user_store = current_app.extensions["user_store"]
org = user_store.get_org_or_none(org_id) or {}
plan = org.get("plan", "trial")
seats = org.get("seats", 5)
quota = current_app.extensions["quota"]
return jsonify({"quota": quota.get_status(org_id, plan, seats)})
@me_bp.get("/board")
@require_auth
def win_lose_board():
+2
View File
@@ -73,12 +73,14 @@ def create_app() -> Flask:
from .services.groups import GroupStore
from .services.sessions import SessionStore
from .services.trainee import MyPersonaStore
from .services.quota import QuotaService
app.extensions["user_store"] = UserStore(Config.DATA_DIR)
app.extensions["group_store"] = GroupStore(Config.DATA_DIR)
app.extensions["session_store"] = SessionStore(Config.DATA_DIR)
app.extensions["my_persona_store"] = MyPersonaStore(Config.DATA_DIR)
app.extensions["demo_delivery"] = DemoCredentialDelivery(Config.DATA_DIR)
app.extensions["quota"] = QuotaService(Config.DATA_DIR)
try:
app.extensions["llm"] = LLMClient()
except LLMError as exc:
+10 -1
View File
@@ -55,7 +55,7 @@ class LLMClient:
raise LLMError("LLM_API_KEY is not configured in .env")
if not self.base_url:
raise LLMError("LLM_BASE_URL is not configured (unknown provider)")
self.client = OpenAI(base_url=self.base_url, api_key=self.api_key)
self.client = OpenAI(base_url=self.base_url, api_key=self.api_key, timeout=105.0, max_retries=0)
def complete(
self,
@@ -64,7 +64,13 @@ class LLMClient:
*,
temperature: float = 0.5,
max_tokens: int = 3000,
thinking: bool = True,
) -> str:
extra_body = None
if not thinking:
# Qwen3-style thinking models: disable chain-of-thought to cut latency
# (measured 313s -> 44s per persona on the local tabbyAPI server).
extra_body = {"enable_thinking": False}
try:
resp = self.client.chat.completions.create(
model=self.model,
@@ -74,6 +80,7 @@ class LLMClient:
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
extra_body=extra_body,
)
except Exception as exc: # network/auth/provider
raise LLMError(f"LLM call failed: {exc}") from exc
@@ -89,12 +96,14 @@ class LLMClient:
*,
temperature: float = 0.2,
max_tokens: int = 6000,
thinking: bool = True,
) -> dict[str, Any]:
text = self.complete(
system_prompt,
user_prompt,
temperature=temperature,
max_tokens=max_tokens,
thinking=thinking,
)
text = _strip_thinking_trace(text)
try:
+96 -38
View File
@@ -1,11 +1,20 @@
"""Persona generator: builds 15 personas (5 per tier) from a Sales Kit + scenario."""
"""Persona generator: builds 15 personas (5 per tier) from a Sales Kit + scenario.
Generation is split into ONE persona per LLM call (thinking disabled) so each call
finishes well under the Cloudflare 120s proxy timeout that kills the single 15-persona
call. The 15 calls run in a small thread pool (the local LLM tolerates a few
concurrent requests) to cut total wall-clock time.
"""
from __future__ import annotations
import json
import os
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any
from ..llm import LLMClient
from .persona_prompts import PERSONA_SYSTEM
from ..llm import LLMClient, LLMError
from .persona_prompts import PERSONA_SYSTEM, PERSONA_SYSTEM_TIER
from .store import PERSONA_CHANNELS, validate_persona_traits
TIERS = ["A", "B", "C"]
@@ -13,6 +22,17 @@ PER_TIER = 5 # 5 per tier = 15 total
TARGET = 15 # total personas the system generates (no "add more" button needed)
def _parallel_workers() -> int:
"""How many persona calls to run concurrently. The local LLM is a single slow
model, so serial (default 1) is fastest — parallel calls just contend and slow
each other down (measured: 5 concurrent = 277s vs ~220s serial). Bump via
PERSONA_PARALLEL only for fast cloud providers where overlap wins."""
try:
return max(1, int(os.environ.get("PERSONA_PARALLEL", "1")))
except (TypeError, ValueError):
return 1
class PersonaGenerator:
def __init__(self, llm: LLMClient) -> None:
self.llm = llm
@@ -28,29 +48,84 @@ class PersonaGenerator:
raise ValueError("persona channel must be facebook or line")
kit_json = json.dumps(sales_kit, ensure_ascii=False)[:12000]
lang_name = "Thai" if language == "th" else "English"
scenario = (sales_kit.get("scenarioFrame") or "").strip() or "a general product sale"
user_prompt = (
base = (
f"Platform/channel preference: {channel}\n"
f"Language: {lang_name} (all persona text in {lang_name})\n"
f"Sales Kit:\n{kit_json}\n\n"
f"Generate exactly 15 personas (5 per tier A/B/C) as JSON."
)
last_error: ValueError | None = None
for attempt in range(1, 4):
prompt = user_prompt + (
""
if attempt == 1
else "\n\n(Note: the previous output failed the strict persona schema. Output exactly 15 valid personas: 5 A, 5 B, 5 C, unique ids, valid Facebook/LINE channel, valid customer/seller initiation, and one tier-C wrong_text persona. No extra prose.)"
)
result = self.llm.complete_json(
PERSONA_SYSTEM, prompt, temperature=0.8, max_tokens=14000
)
# One persona per call, 15 calls total (5 per tier). Each call is small enough
# to finish under the proxy timeout; they run in a small thread pool.
slots = [(tier, slot) for tier in TIERS for slot in range(PER_TIER)]
with ThreadPoolExecutor(max_workers=_parallel_workers()) as pool:
futures = {
pool.submit(self._generate_one, base, tier, slot, channel): (tier, slot)
for tier, slot in slots
}
personas: list[dict[str, Any]] = []
for future in futures:
tier, slot = futures[future]
personas.append(future.result())
return self._normalize_personas(personas, channel)
def _generate_one(self, base: str, tier: str, slot: int, channel: str) -> dict[str, Any]:
"""Generate a single persona (one LLM call) and validate it. Retries on its own."""
extra = (
"IMPORTANT: this persona must have special=\"wrong_text\" "
"(the other tier-C personas have special=\"\")."
if tier == "C" and slot == 0
else ""
)
prompt = (base + f"Generate exactly 1 persona, tier {tier}. {extra}").strip()
last_error: Exception | None = None
for _attempt in range(1, 4):
try:
result = self.llm.complete_json(
PERSONA_SYSTEM_TIER, prompt, temperature=0.8, max_tokens=4000,
thinking=False,
)
except LLMError as exc:
# Transient provider failure (timeout / 5xx / rate limit) on ONE
# persona should not abort the whole 15-persona run. Retry a few
# times with backoff before giving up on this slot.
last_error = exc
if _attempt < 3:
time.sleep(2 * _attempt)
continue
try:
payload = result.get("personas") if isinstance(result, dict) else None
return self._normalize_personas(payload, channel)
if not isinstance(payload, list) or len(payload) != 1:
raise ValueError(f"tier {tier} slot {slot} must return exactly 1 persona")
p = payload[0]
if not isinstance(p, dict):
raise ValueError(f"tier {tier} slot {slot} returned invalid persona object")
if p.get("tier") != tier:
raise ValueError(f"tier {tier} slot {slot} returned a persona of a different tier")
self._validate_persona_fields(p)
return p
except ValueError as exc:
last_error = exc
raise last_error or ValueError("persona generator returned invalid personas")
raise last_error or ValueError(f"persona generator returned invalid tier {tier} persona")
def _validate_persona_fields(self, p: dict[str, Any]) -> None:
"""Per-persona field validation shared by single + full normalization."""
if not isinstance(p.get("name"), str) or not p["name"].strip():
raise ValueError("persona name is invalid")
if p.get("channel") not in PERSONA_CHANNELS:
raise ValueError("persona channel must be facebook or line")
if p.get("initiation_mode") not in ("customer", "seller"):
raise ValueError("persona initiation_mode must be customer or seller")
for field in ("pains", "objections", "negotiation_levers"):
if not isinstance(p.get(field), list):
raise ValueError(f"persona {field} is invalid")
for field, low, high in (("difficulty", 1, 5), ("tolerance", 1, 5)):
value = p.get(field, 1 if field == "difficulty" else 3)
if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
raise ValueError(f"persona {field} is invalid")
p[field] = value
if "recontact" in p and not isinstance(p["recontact"], bool):
raise ValueError("persona recontact is invalid")
p.setdefault("recontact", False)
p.setdefault("special", "")
def _normalize_personas(self, personas: object, channel: str) -> list[dict[str, Any]]:
if not isinstance(personas, list):
@@ -72,27 +147,10 @@ class PersonaGenerator:
raise ValueError("duplicate persona id")
raw_ids.add(source_id)
p = dict(raw)
if not isinstance(p.get("name"), str) or not p["name"].strip():
raise ValueError("persona name is invalid")
tier = p.get("tier", p.get("intent_tier"))
if tier not in TIERS:
raise ValueError("persona tier is invalid")
if p.get("channel") not in PERSONA_CHANNELS:
raise ValueError("persona channel must be facebook or line")
if p.get("initiation_mode") not in ("customer", "seller"):
raise ValueError("persona initiation_mode must be customer or seller")
for field in ("pains", "objections", "negotiation_levers"):
if not isinstance(p.get(field), list):
raise ValueError(f"persona {field} is invalid")
for field, low, high in (("difficulty", 1, 5), ("tolerance", 1, 5)):
value = p.get(field, 1 if field == "difficulty" else 3)
if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
raise ValueError(f"persona {field} is invalid")
p[field] = value
if "recontact" in p and not isinstance(p["recontact"], bool):
raise ValueError("persona recontact is invalid")
p.setdefault("recontact", False)
p.setdefault("special", "")
self._validate_persona_fields(p)
counts[tier] += 1
normalized.append(p)
@@ -160,7 +218,7 @@ class PersonaGenerator:
f"Output exactly one JSON object for the persona.\n"
)
result = self.llm.complete_json(
PERSONA_SYSTEM, prompt, temperature=0.9, max_tokens=3000
PERSONA_SYSTEM, prompt, temperature=0.9, max_tokens=3000, thinking=False
)
variant = result if isinstance(result, dict) else {}
# Accept either a single persona object or a {"personas": [...]} container.
@@ -178,4 +236,4 @@ class PersonaGenerator:
variant.setdefault("channel", source.get("channel", "facebook"))
variant.setdefault("pains", source.get("pains", []))
validate_persona_traits(variant)
return variant
return variant
+72
View File
@@ -68,3 +68,75 @@ RULES:
9. Language: output all human text in the requested language.
Only output valid JSON: {"personas": [ ... ]}
"""
# Per-tier system prompt: generates exactly 5 personas for ONE tier. Used to split the
# 15-persona generation into 3 smaller calls (5 per tier) so each call finishes well under
# the Cloudflare 120s proxy timeout that kills the single 15-persona call.
PERSONA_SYSTEM_TIER = """You are a world-class market-research persona designer for a sales-training
simulator. Given a Sales Kit (product facts + initial pain-fit) and a scenario frame, you generate
REALISTIC customer personas that a trainee will chat with to practice closing a sale.
Generate exactly 5 personas, ALL in the tier specified in the user prompt.
TIER MEANING:
- A = Ready to buy (has budget+authority+urgency, but still expects fit confirmation & handles 1-2
objections; can still WALK AWAY if the seller is rude or clearly wrong).
- B = Unsure / educating (researching; needs discovery, trust, proof, reason-to-act-now; stalls easily).
- C = Not interested but has pain (resistant, unaware/skeptical/budget-constrained, BUT has a real
unresolved pain; the ONLY path to close is surfacing and resolving it).
EACH persona MUST include ALL of these fields:
- name, tier, channel, initiation_mode
- profession, age_group, location, product_context (REVEALABLE - what a real seller could know)
- background, income, lifestyle, personality, communication_style (LATENT)
- budget, decision_timeline, goal, objections[] (LATENT)
- pains[] (LATENT)
- negotiation_levers[] (LATENT)
- opener, special, difficulty, notes
- tolerance (1-5): how many irritant/poor answers you tolerate before you walk away ("heart"). IMPORTANT:
a temperamental/impatient persona has LOW tolerance (1-2, walks away fast after poor answers); a patient
one has HIGH (4-5). Avg is 3. Match tolerance to personality (e.g. a busy owner / abrupt personality = low).
- recontact (true/false): if true, this persona asked about the product BEFORE (earlier contact, e.g. a few
weeks/months back) and is ONLY NOW coming back / re-opening, more ready to buy and less price-sensitive.
These are already-pre-qualified, warmer leads. Make about 1 in every 4 personas recontact=true, spread across tiers.
A recontact persona opener/small-talk often references "I asked about this before" naturally.
RULES:
1. DIVERSITY: 5 distinct people across age groups, occupations, incomes, lifestyles,
personalities. Consistent with the product's target audience + scenario frame.
2. PAIN VARIETY: most pains do NOT map 1:1 to the product. Include pains the product solves
DIRECTLY (fit=strong), some only PARTIALLY solve (fit=partial), and some UNRELATED (fit=weak /
red herring). For each pain give: id, name, fit, description, rootCause, and resolutionConditions[]
(what the seller must satisfy to resolve it).
3. NEGOTIATION: every persona negotiates. negotiation_levers[] lists what they push on
(price reduction, freebies, delivery time for made-to-order, scope, payment terms, guarantee).
4. DECISION BEHAVIOR: when the persona decides to buy (after their pain is resolved + price accepted)
OR to walk away (after too many misses / rude / pushy / wrong), the persona STATES the decision in
ordinary dialogue (e.g. "ok I'll go with it" / "no thanks, forget it") — it does NOT announce it as meta.
5. CHANNEL: "facebook" or "line".
6. SPECIAL PERSONA: only when the user prompt says so — special="wrong_text". They message the seller
normally first (see the opener rule below) as if genuinely interested, then AFTER the seller's very
first reply they cool off and try to end the chat (e.g. "sorry, wrong chat" / "never mind, forget it"),
yet still have a live pain. A seller who gently re-engages without pushing may earn a second chance;
a pushy seller drives them away. Otherwise special="".
7. difficulty 1-5. special="" unless wrong_text.
8. OPENER RULE (IMPORTANT): the `opener` is what the customer says FIRST when initiation_mode="customer".
Every opener — for EVERY tier, including wrong_text — must be a natural, polite, in-character customer
greeting that EITHER asks a question directly OR declares interest, and nothing else.
GOOD Thai openers (ask OR show interest): "สวัสดีครับ สนใจสินค้าตัวนี้ ขอถามราคาหน่อยได้ไหม" /
"สวัสดีค่ะ เห็นโฆษณาแฟนเพจมา เลยอยากสอบถามรายละเอียดครับ" / "สวัสดีครับ ขอถามหน่อย ซื้อที่ร้านแล้วจัดส่งยังไงบ้าง" /
"สนใจสินค้าในแฟนเพจครับ สอบถามราคาได้ไหม".
THAI STYLE (MANDATORY): Start with "สวัสดีครับ/ค่ะ" then go straight to a question or the word "สนใจ/สอบถาม".
NEVER phrase the opener as "ลองดู / ลอง / มาลอง / แค่มาดู / กดดู / แวะดู" (trying/looking) — Thai customers do
NOT open by saying they will "just try or browse"; they ask a question or say they are interested instead.
Do NOT open with casual English-style interjections or filler like "เฮ้", "เอ้", "เอ่อ", "hey", "hi ya", or
singsong slang ("ไง", "นี่ๆ", "ว่าไง"). For English, a plain "Hi/Hello + question" is fine.
NEVER open with ellipsis/dots ("..", "..."), and NEVER end the opener by dismissing or downgrading the
product — e.g. do NOT write "แต่ไม่คิดจะซื้อหรอกนะ", "แค่มาดูเล่น", "ก็แค่มาเมิน", "ไม่ได้จะซื้อ".
An opener must show polite interest or ask a question; it must NOT pre-dismiss, belittle, or merely say it is
"trying/looking".
NEVER make the opener a complaint, a refusal, a price grumble, a "never mind", or anything negative — the
customer's resistance must only surface DURING the conversation, not in their very first message.
9. Language: output all human text in the requested language.
Only output valid JSON: {"personas": [ ... ]}
"""
+133
View File
@@ -0,0 +1,133 @@
"""Per-org monthly session quota enforcement.
Quota is tracked per organization per calendar month (UTC). The limit is
derived from the org's plan:
- trial: 50 sessions/month
- paid: 200 sessions/seat/month (limit = 200 × seats)
- enterprise: unlimited (no cap)
The check-and-consume is atomic under a per-org record lock so concurrent
workers cannot over-consume. Only brand-new trainee sessions consume quota;
resumes and preview sessions do not.
"""
from __future__ import annotations
import datetime
import os
from typing import Any
from ..config import Config
from ..storage.store import JsonStore, StoreError, StoreNotFoundError
def _limit_from_env(name: str, default: int) -> int:
try:
value = int(os.environ.get(name, str(default)))
except (TypeError, ValueError):
return default
return value if value >= 0 else default
def _trial_limit() -> int:
return _limit_from_env("QUOTA_TRIAL_LIMIT", 50)
def _paid_per_seat() -> int:
return _limit_from_env("QUOTA_PAID_PER_SEAT", 200)
def _month_key() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m")
class QuotaService:
def __init__(self, data_dir) -> None:
self.quota = JsonStore(data_dir / "quota")
@staticmethod
def _record_key(org_id: str) -> str:
return f"org-{org_id}"
@staticmethod
def _limit(plan: str, seats: int) -> int | None:
if plan == "enterprise":
return None
if plan == "paid":
return _paid_per_seat() * max(1, seats)
return _trial_limit()
def get_status(self, org_id: str, plan: str, seats: int) -> dict[str, Any]:
"""Return current usage without consuming a slot."""
limit = self._limit(plan, seats)
used = self._used(org_id)
remaining = None if limit is None else max(0, limit - used)
return {
"plan": plan,
"seats": seats,
"limit": limit,
"used": used,
"remaining": remaining,
"month": _month_key(),
}
def check_and_consume(self, org_id: str, plan: str, seats: int) -> dict[str, Any]:
"""Atomically check quota and consume one session slot.
Returns ``{"allowed": bool, "used": int, "limit": int|None,
"remaining": int|None, "month": str}``. A storage fault fails
closed (allowed=False).
"""
limit = self._limit(plan, seats)
key = self._record_key(org_id)
try:
with self.quota.record_lock(key):
record = self.quota.get_or_none(key)
if record is None:
record = {"id": key, "month": _month_key(), "used": 0}
self.quota.create(record, key=key)
else:
if record.get("month") != _month_key():
self.quota.update(key, month=_month_key(), used=0)
used = self.quota.get(key).get("used", 0)
if not isinstance(used, int) or used < 0:
used = 0
if limit is not None and used >= limit:
return {
"allowed": False,
"used": used,
"limit": limit,
"remaining": 0,
"month": _month_key(),
}
used += 1
self.quota.update(key, month=_month_key(), used=used)
remaining = None if limit is None else max(0, limit - used)
return {
"allowed": True,
"used": used,
"limit": limit,
"remaining": remaining,
"month": _month_key(),
}
except (OSError, StoreError, TypeError, ValueError, UnicodeError):
return {
"allowed": False,
"used": 0,
"limit": limit,
"remaining": None,
"month": _month_key(),
}
def _used(self, org_id: str) -> int:
key = self._record_key(org_id)
try:
record = self.quota.get_or_none(key)
if record is None:
return 0
if record.get("month") != _month_key():
return 0
used = record.get("used", 0)
return used if isinstance(used, int) and used >= 0 else 0
except (OSError, StoreError, TypeError, ValueError, UnicodeError):
return 0
+37 -5
View File
@@ -71,18 +71,47 @@ def make_personas() -> list[dict[str, Any]]:
return out
def make_tier_personas(tier: str) -> list[dict[str, Any]]:
"""5 personas for ONE tier (mock of the per-tier generation calls)."""
start = {"A": 1, "B": 6, "C": 11}[tier]
return [_sample_persona(start + i, tier) for i in range(5)]
def make_one_persona(tier: str, idx: int, *, wrong_text: bool = False) -> dict[str, Any]:
"""A single persona for a one-persona-per-call generation."""
p = _sample_persona(idx, tier)
if wrong_text:
p["special"] = "wrong_text"
elif tier == "C":
p["special"] = ""
return p
class MockLLM:
"""Drop-in for app.llm.LLMClient — reads config the same way."""
persona_count = 0
def __init__(self, **kwargs):
pass
self._tier_calls: dict[str, int] = {"A": 0, "B": 0, "C": 0}
def _next_persona(self, user_prompt: str) -> dict[str, Any] | None:
"""Return the next single persona for a one-persona-per-call prompt, or None."""
tier = None
for t in ("A", "B", "C"):
if f"Generate exactly 1 persona, tier {t}" in user_prompt:
tier = t
break
if tier is None:
return None
slot = self._tier_calls[tier]
self._tier_calls[tier] += 1
start = {"A": 1, "B": 6, "C": 11}[tier]
return make_one_persona(tier, start + slot, wrong_text=(tier == "C" and slot % 5 == 0))
def complete(self, system_prompt: str, user_prompt: str, **kw) -> str:
if "Persona generation prompts" in system_prompt or "persona designer" in system_prompt.lower():
return json.dumps({"personas": make_personas()}, ensure_ascii=False)
if "market-research persona designer" in system_prompt.lower():
one = self._next_persona(user_prompt)
if one is not None:
return json.dumps({"personas": [one]}, ensure_ascii=False)
return json.dumps({"personas": make_personas()}, ensure_ascii=False)
return "ok"
@@ -91,6 +120,9 @@ class MockLLM:
if "ecommerce/b2b analyst" in sp:
return dict(SAMPLE_SALES_KIT)
if "market-research persona designer" in sp:
one = self._next_persona(user_prompt)
if one is not None:
return {"personas": [one]}
return {"personas": make_personas()}
if "sales-training simulator" in sp and "PRIVATE" in system_prompt:
return {"persona": _sample_persona(99, "C")}
+97 -29
View File
@@ -1,21 +1,41 @@
"""Exact persona cardinality and schema contract tests."""
"""Exact persona cardinality and schema contract tests (one-persona-per-call flow)."""
from __future__ import annotations
import copy
import pytest
from app.llm import LLMError
from app.services.persona_generator import PersonaGenerator
class QueueLLM:
def __init__(self, results):
self.results = [copy.deepcopy(result) for result in results]
class SingleQueueLLM:
"""Returns ONE persona per call, matching the generator's 15-call (one per
persona) flow. Each call is keyed by the tier in the prompt; the next persona
of that tier is returned. Repeats the last persona once the tier queue is empty
(so a retry of a bad slot keeps failing instead of advancing to a good one)."""
def __init__(self, personas):
self.by_tier = {t: [copy.deepcopy(p) for p in personas if p.get("tier") == t] for t in "ABC"}
self.last = {t: None for t in "ABC"}
self.calls = 0
def complete_json(self, system_prompt, user_prompt, **kwargs):
self.calls += 1
return self.results[min(self.calls - 1, len(self.results) - 1)]
tier = None
for t in ("A", "B", "C"):
if f"Generate exactly 1 persona, tier {t}" in user_prompt:
tier = t
break
if tier is None:
return {"personas": []}
queue = self.by_tier[tier]
if queue:
self.last[tier] = queue.pop(0)
persona = self.last[tier]
if persona is None:
return {"personas": []}
return {"personas": [copy.deepcopy(persona)]}
def _persona(index: int, tier: str, *, special: str = ""):
@@ -59,14 +79,14 @@ def _valid_personas():
return people
def _generate(results):
return PersonaGenerator(QueueLLM(results)).generate(
def _generate(personas):
return PersonaGenerator(SingleQueueLLM(personas)).generate(
sales_kit={}, language="th", channel="line"
)
def test_generator_returns_exact_15_with_five_per_tier_and_special_c():
personas = _generate([{"personas": _valid_personas()}])
personas = _generate(_valid_personas())
assert len(personas) == 15
assert {tier: sum(p["tier"] == tier for p in personas) for tier in "ABC"} == {
@@ -76,32 +96,80 @@ def test_generator_returns_exact_15_with_five_per_tier_and_special_c():
assert len({p["id"] for p in personas}) == 15
@pytest.mark.parametrize(
"mutate, message",
[
(lambda people: people.pop(), "exactly 15"),
(lambda people: people.__setitem__(0, {**people[0], "tier": "D"}), "tier"),
(lambda people: people.__setitem__(1, {**people[1], "id": people[0]["id"]}), "duplicate"),
(lambda people: people.__setitem__(0, {**people[0], "channel": "social"}), "channel"),
(lambda people: people.__setitem__(0, {**people[0], "initiation_mode": "f2f_call"}), "initiation"),
(lambda people: [p.update(special="") for p in people if p["tier"] == "C"], "wrong_text"),
],
)
def test_invalid_generation_retries_then_fails_closed(mutate, message):
def test_invalid_channel_retries_then_fails_closed():
people = _valid_personas()
mutate(people)
for p in people:
if p["tier"] == "A":
p["channel"] = "social" # every tier-A persona is invalid → retries fail
with pytest.raises(ValueError, match="channel"):
_generate(people)
llm = QueueLLM([{"personas": people}])
generator = PersonaGenerator(llm)
with pytest.raises(ValueError, match=message):
generator.generate(sales_kit={}, language="th", channel="line")
assert llm.calls == 3
def test_invalid_initiation_retries_then_fails_closed():
people = _valid_personas()
for p in people:
if p["tier"] == "B":
p["initiation_mode"] = "f2f_call"
with pytest.raises(ValueError, match="initiation"):
_generate(people)
def test_missing_wrong_text_in_tier_c_fails_closed():
people = _valid_personas()
for p in people:
if p["tier"] == "C":
p["special"] = "" # no wrong_text persona in tier C
with pytest.raises(ValueError, match="wrong_text"):
_generate(people)
def test_malformed_provider_container_retries_then_fails():
llm = QueueLLM([{"personas": "not-a-list"}])
generator = PersonaGenerator(llm)
class BadLLM:
def __init__(self):
self.calls = 0
def complete_json(self, system_prompt, user_prompt, **kwargs):
self.calls += 1
return {"personas": "not-a-list"}
llm = BadLLM()
generator = PersonaGenerator(llm)
with pytest.raises(ValueError, match="persona"):
generator.generate(sales_kit={}, language="th", channel="line")
assert llm.calls == 3
assert llm.calls >= 2 # at least one slot retried before failing closed
def test_transient_llm_error_is_retried_not_aborted(monkeypatch):
"""A one-shot LLMError (timeout/5xx) on a single persona must be retried,
NOT abort the whole 15-persona run — the run should still produce 15."""
import app.services.persona_generator as pg
good = _valid_personas()
class FlakyLLM:
def __init__(self):
self.calls = 0
self.q = {t: [p for p in good if p["tier"] == t] for t in "ABC"}
def complete_json(self, system_prompt, user_prompt, **kwargs):
self.calls += 1
# The very first call always times out; everything after succeeds.
if self.calls == 1:
raise LLMError("LLM call failed: Request timed out.")
tier = None
for t in ("A", "B", "C"):
if f"Generate exactly 1 persona, tier {t}" in user_prompt:
tier = t
break
if tier is None or not self.q[tier]:
return {"personas": []}
return {"personas": [copy.deepcopy(self.q[tier].pop(0))]}
# No backoff wait in tests.
monkeypatch.setattr(pg.time, "sleep", lambda _s: None)
llm = FlakyLLM()
personas = PersonaGenerator(llm).generate(sales_kit={}, language="th", channel="line")
assert len(personas) == 15
# First call failed (1), then 15 more succeeded = 16 total.
assert llm.calls == 16
+15 -1
View File
@@ -15,6 +15,16 @@ class StubPersonaLLM:
self.personas = personas
def complete_json(self, system_prompt, user_prompt, **kwargs):
tier = None
for t in ("A", "B", "C"):
if f"Generate exactly 1 persona, tier {t}" in user_prompt:
tier = t
break
if tier is not None:
for p in self.personas:
if p.get("tier") == tier:
return {"personas": [p]}
return {"personas": []}
return {"personas": self.personas}
@@ -30,7 +40,11 @@ def _persona(channel="line", initiation_mode="customer", **extra):
def _fifteen(**kwargs):
return [_persona(**kwargs) for _ in range(15)]
out = []
for tier in ("A", "B", "C"):
for _ in range(5):
out.append(_persona(tier=tier, **kwargs))
return out
def test_persona_owns_initiation_even_when_scenario_changes():
+163
View File
@@ -0,0 +1,163 @@
"""Quota enforcement tests: trial cap, paid per-seat, enterprise unlimited, resume no-consume."""
from __future__ import annotations
import os
from pathlib import Path
import pytest
@pytest.fixture()
def quota_app(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
"""App with a small trial quota (3) so tests don't need 50 sessions."""
monkeypatch.setenv("DATA_DIR", str(tmp_path))
monkeypatch.setenv("JWT_SECRET", "pytest-only-secret-0123456789abcdef")
monkeypatch.setenv("APP_ENV", "test")
monkeypatch.setenv("BOOTSTRAP_ADMIN_PASSWORD", "pytest-bootstrap-password")
monkeypatch.setenv("FLASK_DEBUG", "false")
monkeypatch.setenv("QUOTA_TRIAL_LIMIT", "3")
monkeypatch.setenv("QUOTA_PAID_PER_SEAT", "2")
from app.config import Config
Config.DATA_DIR = tmp_path
Config.SECRET_KEY = "pytest-only-secret-0123456789abcdef"
Config.APP_ENV = "test"
Config.BOOTSTRAP_ADMIN_PASSWORD = "pytest-bootstrap-password"
Config.FLASK_DEBUG = False
from app.factory import create_app
from app.services import rate_limit
rate_limit._mem.clear()
application = create_app()
application.config.update(TESTING=True)
# Inject mock LLM so analyze works without external API.
import sys
scripts = str(Path(__file__).resolve().parents[1] / "scripts")
if scripts not in sys.path:
sys.path.insert(0, scripts)
from mock_llm import MockLLM
application.extensions["llm"] = MockLLM()
return application
def _bootstrap(client):
"""Create super admin + return auth header."""
r = client.post("/api/auth/login", json={"username": "admin", "password": "pytest-bootstrap-password"})
assert r.status_code == 200, r.get_json()
token = r.get_json()["token"]
h = {"Authorization": f"Bearer {token}"}
client.post("/api/auth/setup", headers=h, json={
"username": "admin", "email": "[email protected]",
"password": "admin-ready-password", "accepted_terms": True,
})
r = client.post("/api/auth/login", json={"username": "admin", "password": "admin-ready-password"})
token = r.get_json()["token"]
return {"Authorization": f"Bearer {token}"}
def _make_group_with_personas(client, admin_h):
"""Create a group and analyze it → 15 personas."""
r = client.post("/api/groups", headers=admin_h, json={
"product": "CloudPOS", "segment": "SME", "channel": "line", "language": "th",
})
assert r.status_code == 201, r.get_json()
gid = r.get_json()["group"]["id"]
r = client.post(f"/api/groups/{gid}/analyze", headers=admin_h)
assert r.status_code == 200, r.get_json()
return gid
def _make_trainee(app, client, admin_h, username):
r = client.post("/api/admin/users", headers=admin_h, json={
"username": username, "password": "trainee-pw-123", "role": "user",
})
assert r.status_code == 201, r.get_json()
# Mark terms accepted so the trainee can use business routes (mirrors the
# demo-account helper; the HTTP /auth/setup flow is covered elsewhere).
app.extensions["user_store"].users.update(
username, must_setup=False, accepted_terms=True,
accepted_terms_at="2026-09-30T00:00:00Z",
)
r = client.post("/api/auth/login", json={"username": username, "password": "trainee-pw-123"})
assert r.status_code == 200, r.get_json()
return {"Authorization": f"Bearer {r.get_json()['token']}"}
def _start_session(client, user_h, gid, persona_id):
return client.post(f"/api/chat/{gid}/personas/{persona_id}/chat/start", headers=user_h, json={
"mode": "trainee", "scenario": "social",
})
def test_trial_quota_blocks_after_limit(quota_app):
"""Trial org (limit=3): 3 trainee sessions OK, 4th → 402."""
client = quota_app.test_client()
admin_h = _bootstrap(client)
gid = _make_group_with_personas(client, admin_h)
# Get persona IDs from the group.
r = client.get(f"/api/groups/{gid}", headers=admin_h)
personas = r.get_json()["group"]["personas"]
assert len(personas) == 15
pids = [p["id"] for p in personas]
# Create 4 trainees (each can start 1 session per persona, one-shot).
trainees = [_make_trainee(quota_app, client, admin_h, f"t{i}") for i in range(4)]
# First 3 sessions should succeed (quota=3).
for i in range(3):
r = _start_session(client, trainees[i], gid, pids[i])
assert r.status_code == 200, f"session {i} should succeed: {r.get_json()}"
# 4th session should be blocked (quota exhausted).
r = _start_session(client, trainees[3], gid, pids[3])
assert r.status_code == 402, f"session 3 should be blocked: {r.status_code} {r.get_json()}"
def test_quota_status_endpoint(quota_app):
"""GET /api/me/quota returns usage for the current org."""
client = quota_app.test_client()
admin_h = _bootstrap(client)
gid = _make_group_with_personas(client, admin_h)
r = client.get("/api/me/quota", headers=admin_h)
assert r.status_code == 200, r.get_json()
q = r.get_json()["quota"]
assert q["plan"] == "trial"
assert q["limit"] == 3
assert q["used"] == 0
assert q["remaining"] == 3
def test_paid_plan_per_seat(quota_app):
"""Paid org (limit=2/seat × 5 seats = 10): quota reflects seats."""
client = quota_app.test_client()
admin_h = _bootstrap(client)
# Bump default org to paid plan.
r = client.patch("/api/admin/orgs/org-default", headers=admin_h, json={"plan": "paid"})
assert r.status_code == 200, r.get_json()
r = client.get("/api/me/quota", headers=admin_h)
q = r.get_json()["quota"]
assert q["plan"] == "paid"
assert q["limit"] == 10 # 2 per seat × 5 seats
def test_enterprise_unlimited(quota_app):
"""Enterprise org: no quota cap."""
client = quota_app.test_client()
admin_h = _bootstrap(client)
r = client.patch("/api/admin/orgs/org-default", headers=admin_h, json={"plan": "enterprise"})
assert r.status_code == 200, r.get_json()
r = client.get("/api/me/quota", headers=admin_h)
q = r.get_json()["quota"]
assert q["plan"] == "enterprise"
assert q["limit"] is None
assert q["remaining"] is None
+94
View File
@@ -0,0 +1,94 @@
# Outreach Templates — Sales Trainer
Pitch แกน (ใช้ทุกช่องทาง): **ทีมขายที่คนลาออกบ่อย → ความรู้การขายหนีไปด้วย → ฝึกคนใหม่แพงและช้า → Sales Trainer ให้ทีมฝึกปิดการขายกับลูกค้า AI ที่ต่อรอง/ปฏิเสธจริง + AI โค้ชทุกข้อความ → คนใหม่ปิดเป็นเร็ว และความรู้ติดอยู่ในทีม**
กฎ:
- ไม่ขายเกินจริง — ไม่สัญญาตัวเลข "ปิดเพิ่ม X%" (ยังไม่มีข้อมูลลูกค้าจริง)
- ทุกข้อความจบด้วย CTA เดียว: ขอเดโม 30 นาที หรือ ทดลองฟรี 30 วัน
- ตัว [ ] = ให้กรอกตามลูกค้าจริง
---
## 1. LINE — ตัวแรก (cold)
> สวัสดีครับ [ชื่อ] ผม [ชื่อเรา] จาก Sales Trainer
>
> เห็นว่า [บริษัท] ขายผ่าน [LINE/โทรศัพท์/หน้าร้าน] — ทีมขายแบบนี้คนลาออกบ่อย และทุกครั้งที่ลาออก ความรู้การขายก็ไปด้วย ฝึกคนใหม่ทีละ 2–3 เดือน
>
> ผมทำระบบให้พนักงานฝึกปิดการขายกับลูกค้า AI 15 คน — ลูกค้าต่อรอง ปฏิเสธ และถ่วงเหมือนจริง แล้วมี AI โค้ชบอกวิธีตอบให้ดีขึ้นทุกข้อความ คนใหม่ปิดเป็นเร็วขึ้น และเมื่อใครลาออก ความรู้ก็อยู่กับทีม
>
> ลองดูเดโม 30 นาทีได้ไหมครับ? ผมจะเอาสินค้าของ [บริษัท] มาสร้างลูกค้าจำลองให้ดูสดเลย — ทดลองใช้ฟรี 30 วัน ไม่ต้องผูกมัด
**Follow-up (3 วันหลังไม่ตอบ):**
> [ชื่อ] ครับ — ไม่ได้รบกวนเยอะ แค่ถามสั้นๆ: ถ้าพนักงานใหม่ปิดการขายได้เร็วขึ้น 1 เดือน ทีม [บริษัท] จะประหยัดค่าฝึกได้เท่าไหร่ครับ? ถ้าสนใจ ผมส่งเดโม 30 นาทีให้ดูได้ครับ
---
## 2. โทรศัพท์ — สคริปต์ 90 วินาที
**เปิด (15 วิ):**
> "สวัสดีครับ [ชื่อ] ผม [ชื่อเรา] โทรมาเรื่องทีมขายของ [บริษัท] ครับ — ใช้เวลา 90 วินาทีได้ไหมครับ?"
**Hook (20 วิ):**
> "ผมทำระบบฝึกขายให้ทีมขายที่คนลาออกบ่อย — ปัญหาที่ผมเจอจากทีมขายหลายที่คือ คนลาออกที ความรู้การขายไปที ฝึกคนใหม่ 2–3 เดือน ทีมก็เสียลูกค้าระหว่างนั้น"
**เสนอ (30 วิ):**
> "ระบบนี้ให้พนักงานแชตฝึกกับลูกค้า AI 15 คน — ลูกค้าต่อรอง ปฏิเสธ ถ่วง เหมือนลูกค้าจริง แล้วมี AI โค้ชบอกทุกข้อความว่าตอบแบบไหนจะดีขึ้น ผู้จัดการก็เห็นแดชบอร์ดว่าใครอ่อนตรงไหน ฝึกซ้ำเฉพาะปมนั้นได้"
**CTA (15 วิ):**
> "ผมขอเดโม 30 นาทีได้ไหมครับ — ผมจะเอาสินค้าของ [บริษัท] มาสร้างลูกค้าจำลองให้ดูสดเลย ถ้าเห็นว่าคุ้ม ค่อยทดลองใช้ฟรี 30 วัน"
**ข้อโต้แย้งที่พบบ่อย:**
- *"ไม่มีเวลา"* → "เข้าใจครับ — เดโม 30 นาทีอย่างเดียว ถ้าไม่คุ้ม ไม่ต้องเสียเวลาเพิ่ม"
- *"พนักงานเราฝึกกันอยู่แล้ว"* → "ฝึกกับเพื่อนร่วมงานรู้กันหมดว่าใครจะพูดอะไร — ลูกค้า AI ไม่รู้จักบท และแพ้ได้จริง ลองดูเดโมแล้วเปรียบเทียบเองครับ"
- *"ราคาเท่าไหร่?"* → "แผนทีม 7,900/เดือน 10 ที่นั่ง ทดลองฟรี 30 วันก่อน — ดูเดโมก่อนแล้วค่อยตัดสินใจครับ"
---
## 3. LinkedIn — ข้อความแรก (InMail / connection note)
> [ชื่อ] — เห็นว่า [บริษัท] โตเร็วใน [สายธุรกิจ] ทีมขายแบบนี้ผมเจอปัญหาเดียวกัน: คนลาออกที ความรู้การขายไปที ฝึกคนใหม่ 2–3 เดือน
>
> ผมสร้าง Sales Trainer — ระบบให้พนักงานฝึกปิดการขายกับลูกค้า AI ที่ต่อรองและปฏิเสธจริง พร้อม AI โค้ชทุกข้อความ ผู้จัดการเห็นแดชบอร์ดจุดอ่อนรายคน
>
> ขอเดโม 30 นาทีได้ไหมครับ? ผมเอาสินค้าของ [บริษัท] มาสร้างลูกค้าจำลองให้ดูสด — ทดลองฟรี 30 วัน
**Post (โพสต์บน LinkedIn — สำหรับ content marketing, ไม่ใช่ outreach ตรง):**
> ทีมขายที่คนลาออกบ่อย เจอปัญหาเดียวกัน:
>
> ฝึกคนใหม่ 2–3 เดือน → ปิดเป็น → ลาออก → ความรู้การขายไปหมด → ฝึกใหม่
>
> วนลูปนี้ทุกปี ค่าฝึก ค่าเวลาที่เสีย และลูกค้าที่หลุดระหว่างที่คนใหม่ยังไม่เก่ง
>
> ทางออกที่เราทำ: ให้พนักงานฝึกกับลูกค้า AI ที่ต่อรองและปฏิเสธจริง — มี AI โค้ชทุกข้อความ และมีแดชบอร์ดให้ผู้จัดการเห็นจุดอ่อนรายคน
>
> คนใหม่ปิดเป็นเร็วขึ้น และเมื่อใครลาออก ความรู้ก็อยู่กับทีม ไม่ใช่เดินออกไปกับเขา
---
## 4. อีเมล (สำรอง — สำหรับ B2B ที่ติดต่อผ่านอีเมล)
**Subject:** ทีมขาย [บริษัท] — ฝึกคนใหม่ให้ปิดเป็นเร็วขึ้น
> สวัสดี [ชื่อ]
>
> ผม [ชื่อเรา] จาก Sales Trainer — ผมทำระบบฝึกขายสำหรับทีมขายที่คนลาออกบ่อย
>
> ปัญหาที่ทีมขายส่วนใหญ่เจอ: คนลาออกที ความรู้การขายไปที ฝึกคนใหม่ 2–3 เดือน ระหว่างนั้นทีมเสียลูกค้า
>
> Sales Trainer ให้พนักงานฝึกปิดการขายกับลูกค้า AI 15 คน (สร้างจากสินค้าจริงของ [บริษัท]) — ลูกค้าต่อรอง ปฏิเสธ ถ่วง เหมือนจริง และมี AI โค้ชบอกวิธีตอบให้ดีขึ้นทุกข้อความ
>
> ราคา: แผนทีม 7,900/เดือน (10 ที่นั่ง) · ทดลองฟรี 30 วัน
>
> ขอเดโม 30 นาทีได้ไหมครับ? ผมจะสร้างลูกค้าจำลองจากสินค้าของ [บริษัท] ให้ดูสด
>
> [ชื่อเรา] · [เบอร์] · [LINE]
---
## เป้าหมาย outreach (สัปดาห์แรก)
- ประกัน (beachhead): agent/ทีมขายประกันที่ขาย outbound — 20 ราย
- SME ที่ขายผ่าน LINE/โทรศัพท์: 10 ราย
- วัดผล: ตอบกลับ ≥ 5 → เดโม ≥ 2 → trial ≥ 1
+14 -1
View File
@@ -51,7 +51,20 @@ export const api = {
updateGroupVisibility: (id, visibility) => request('PATCH', `/api/groups/${id}/visibility`, { visibility }),
groupReport: (id) => request('GET', `/api/groups/${id}/report?format=json`),
deleteGroup: (id) => request('DELETE', `/api/groups/${id}`),
analyzeGroup: (id) => request('POST', `/api/groups/${id}/analyze`),
analyzeGroup: async (id) => {
await request('POST', `/api/groups/${id}/analyze`)
// Analysis runs server-side because local LLM generation can take several minutes.
// Poll the existing group resource until it is ready/failed; stop after 30 minutes.
const deadline = Date.now() + 30 * 60 * 1000
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 3000))
const result = await request('GET', `/api/groups/${id}`)
const status = result?.group?.status
if (status === 'ready') return result
if (status === 'failed') throw new Error('analysis failed')
}
throw new Error('analysis timed out')
},
listPersonas: (gid) => request('GET', `/api/groups/${gid}/personas`),
getPersona: (gid, pid) => request('GET', `/api/groups/${gid}/personas/${pid}`),
createPersonaVariant: (gid, pid) => request('POST', `/api/groups/${gid}/personas/${pid}/variant`),
+23 -8
View File
@@ -9,16 +9,31 @@ describe('API group analysis contract', () => {
vi.restoreAllMocks()
})
it('never emits the removed append query parameter', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: async () => ({ group: { id: 'g-1' } }),
it('starts analysis and polls until the group is ready', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({ ok: true, json: async () => ({ status: 'analyzing' }) })
.mockResolvedValueOnce({ ok: true, json: async () => ({ group: { id: 'g-1', status: 'ready' } }) })
vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback) => {
callback()
return 0
})
await api.analyzeGroup('g-1', { append: true })
const result = await api.analyzeGroup('g-1')
expect(fetchMock).toHaveBeenCalledWith('/api/groups/g-1/analyze', expect.objectContaining({
method: 'POST',
}))
expect(result.group.status).toBe('ready')
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/groups/g-1/analyze', expect.objectContaining({ method: 'POST' }))
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/groups/g-1', expect.objectContaining({ method: 'GET' }))
})
it('surfaces analysis failure from the polled group state', async () => {
vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({ ok: true, json: async () => ({ status: 'analyzing' }) })
.mockResolvedValueOnce({ ok: true, json: async () => ({ group: { id: 'g-1', status: 'failed' } }) })
vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback) => {
callback()
return 0
})
await expect(api.analyzeGroup('g-1')).rejects.toThrow('analysis failed')
})
})