Akshay Babbar commited on
Commit
f1cf4a9
Β·
1 Parent(s): 34b52e0

interim commit-v2

Browse files
.agents/workflows/project-context.md CHANGED
@@ -1,4 +1,49 @@
1
  ---
2
- description: Win this hackathon of
3
  ---
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ description: Comprehensive background, architectural layout, and active execution guides for the WitGym project.
3
  ---
4
 
5
+ # Project Context: WitGym Comedy Engine
6
+
7
+ This workflow provides a strategic breakdown of the WitGym project context to assist incoming agents in executing tasks efficiently.
8
+
9
+ ---
10
+
11
+ ## 🎭 Context & Background
12
+ WitGym is an experimental conversational AI grounded in Case-Based Reasoning (CBR) and Retrieval-Augmented Generation (RAG) to generate contextually relevant, sharp, and brief comedy responses inspired by **The Office**.
13
+
14
+ The engine operates on two core principles:
15
+ 1. **Pass 1 β€” Abstract Conceptual Indexing**: We extract comedy archetypes and tension points from user setups instead of relying on direct text similarity.
16
+ 2. **Pass 2 β€” Grounded Persona Generation**: We retrieve analogous Office scenarios and feed them into three creative generation pipelines (Cynic, Observer, Absurdist), selecting the final response through a brevity-biased ranker.
17
+
18
+ ---
19
+
20
+ ## πŸ“‚ Codebase Navigation & Key Interfaces
21
+
22
+ ### [config.py](file:///Users/akshaybabbar/Desktop/work/huggingface_witgym_hackathon_2026/witgym/config.py)
23
+ Defines constants, model targets, context window limits, and clichΓ©s. Keeps variables decoupled.
24
+
25
+ ### [model.py](file:///Users/akshaybabbar/Desktop/work/huggingface_witgym_hackathon_2026/witgym/model.py)
26
+ Contains model loading and direct PyTorch operations. Implements `ClichePenaltyProcessor` (soft logits manipulation) and MPS cache eviction mechanics.
27
+
28
+ ### [engine.py](file:///Users/akshaybabbar/Desktop/work/huggingface_witgym_hackathon_2026/witgym/engine.py)
29
+ The stateful orchestration core. Keeps the API completely clean and separate from user interface logic.
30
+
31
+ ### [generator.py](file:///Users/akshaybabbar/Desktop/work/huggingface_witgym_hackathon_2026/witgym/generator.py)
32
+ Houses the candidate generation prompts and the positional-bias-free brevity ranking logic.
33
+
34
+ ---
35
+
36
+ ## βš™οΈ RAM Optimization Strategy
37
+ When transitioning to larger models (e.g. Qwen3.5-9B) on local hardware (48 GB Unified Memory Macs):
38
+ - **Reduce KV Cache Size**: Set `CONTEXT_WINDOW` in `config.py` to `4096`.
39
+ - **Force PyTorch Garbage Collection**: Call `torch.mps.empty_cache()` and `gc.collect()` after each run.
40
+ - **Process Termination**: Kill dangling python processes before execution.
41
+
42
+ ---
43
+
44
+ ## πŸ”¬ Next Closed-Loop Experiment Steps
45
+ To verify correctness and rule out regressions:
46
+ 1. Re-index with `python -m witgym.main index`.
47
+ 2. Run interactive chat via `python -m witgym.main --debug`.
48
+ 3. Input 5 diverse setup prompts representing all archetypes.
49
+ 4. Evaluate and refine generation prompts or penalties if necessary.
scripts/build_transcripts.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Office transcript labeler β€” DeepSeek V4 Flash (deepseek-chat).
3
+
4
+ Cost math (all 4055 candidate scenes):
5
+ ~300 tokens input + ~180 tokens output per scene
6
+ = ~$0.32 total at deepseek-v4-flash pricing ($0.14/M in, $0.28/M out)
7
+
8
+ Concurrency: 50 simultaneous requests (limit is 2500 β€” zero 429 risk).
9
+ Speed: ~50 scenes/wave Γ— ~2s/wave = all 4055 done in ~3 minutes.
10
+
11
+ Usage:
12
+ uv run python scripts/build_transcripts.py
13
+
14
+ Resume-safe: already-labeled scenes are skipped on re-run.
15
+ """
16
+ import asyncio
17
+ import json
18
+ import os
19
+ import random
20
+ import re
21
+ import subprocess
22
+ import sys
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+
26
+ from datasets import load_dataset
27
+ from loguru import logger
28
+ from openai import AsyncOpenAI
29
+
30
+ # ── Config ─────────────────────────────────────────────────────────────────────
31
+ DEEPSEEK_BASE = "https://api.deepseek.com"
32
+ MODEL = "deepseek-chat" # = deepseek-v4-flash: $0.14/M in, $0.28/M out, 2500 concurrency
33
+ CONCURRENCY = 50 # Safe: limit is 2500
34
+ TARGET_SCENES = 4055 # Label the whole candidate pool (~$0.32 total)
35
+ OUTPUT_PATH = "data/transcripts/office_generated.txt"
36
+
37
+ VALID_ARCHETYPES = {
38
+ "status_assertion", "self_delusion", "power_inversion",
39
+ "anxiety_escalation", "social_fail", "misplaced_conf",
40
+ }
41
+ VALID_TENSIONS = {
42
+ "social_embarrass", "existential", "status_threat",
43
+ "identity_expose", "logic_collapse",
44
+ }
45
+ VALID_DISTANCES = {"mild", "moderate", "sharp"}
46
+ VALID_REGISTERS = {"resigned", "gleeful", "deadpan", "panicked", "oblivious", "indignant"}
47
+
48
+ COMEDY_CHARACTERS = {
49
+ "Michael", "Dwight", "Jim", "Pam", "Ryan", "Andy", "Kevin",
50
+ "Angela", "Oscar", "Phyllis", "Stanley", "Creed", "Meredith",
51
+ "Kelly", "Toby", "Jan", "Darryl", "Gabe", "Robert",
52
+ }
53
+
54
+ LABEL_PROMPT = """\
55
+ You are labeling a scene from The Office (US) for a comedy retrieval engine.
56
+
57
+ SCENE (Season {season}, Episode {episode}):
58
+ {scene_text}
59
+
60
+ Identify the single FUNNIEST line and return ONLY this JSON (no markdown):
61
+ {{
62
+ "character": "speaker of the funniest line",
63
+ "setup": "one sentence: situation that makes the line funny (no spoilers)",
64
+ "response": "exact verbatim funniest line from the scene",
65
+ "archetype": "status_assertion | self_delusion | power_inversion | anxiety_escalation | social_fail | misplaced_conf",
66
+ "tension_type": "social_embarrass | existential | status_threat | identity_expose | logic_collapse",
67
+ "violation_distance": "mild | moderate | sharp",
68
+ "why_it_works": "one sentence: what expectation is violated and why it lands",
69
+ "emotional_register": "resigned | gleeful | deadpan | panicked | oblivious | indignant"
70
+ }}
71
+ If no genuinely funny line exists, return {{"skip": true}}"""
72
+
73
+
74
+ # ── Dataset ─────────────────────────────────────────────────────────────────────
75
+ def load_office_lines():
76
+ logger.info("Loading jxm/the_office_lines from HuggingFace...")
77
+ ds = load_dataset("jxm/the_office_lines", split="train")
78
+ logger.info(f"Loaded {len(ds)} lines")
79
+ return ds
80
+
81
+
82
+ def group_into_scenes(ds) -> list[dict]:
83
+ scene_map = defaultdict(list)
84
+ for row in ds:
85
+ if row.get("deleted"):
86
+ continue
87
+ key = (row["season"], row["episode"], row["scene"])
88
+ scene_map[key].append(row)
89
+
90
+ candidates = []
91
+ for (season, episode, scene_num), lines in scene_map.items():
92
+ speakers = {l["speaker"] for l in lines}
93
+ if not (speakers & COMEDY_CHARACTERS):
94
+ continue
95
+ if not (3 <= len(lines) <= 15):
96
+ continue
97
+ if not any(len(l["line_text"].split()) > 7 for l in lines):
98
+ continue
99
+ candidates.append({
100
+ "season": season, "episode": episode,
101
+ "scene": scene_num, "lines": lines,
102
+ })
103
+
104
+ logger.info(f"Candidate scenes: {len(candidates)}")
105
+ return candidates
106
+
107
+
108
+ def format_scene(lines: list[dict]) -> str:
109
+ return "\n".join(
110
+ f"{l['speaker']}: {l['line_text'].strip()}"
111
+ for l in lines if l["line_text"].strip()
112
+ )
113
+
114
+
115
+ def load_already_done(path: str) -> set:
116
+ done = set()
117
+ p = Path(path)
118
+ if not p.exists():
119
+ return done
120
+ for line in p.read_text().splitlines():
121
+ m = re.match(r"# S(\d+)E(\d+)Scene(\d+)", line)
122
+ if m:
123
+ done.add((int(m.group(1)), int(m.group(2)), int(m.group(3))))
124
+ return done
125
+
126
+
127
+ def to_pipe(scene: dict, label: dict) -> str:
128
+ reg = label.get("emotional_register", "deadpan")
129
+ if reg not in VALID_REGISTERS:
130
+ reg = "deadpan"
131
+ return (
132
+ f"The Office|{label['character']}|{label['setup']}|{label['response']}"
133
+ f"|{label['archetype']}|{label['tension_type']}|{label['violation_distance']}"
134
+ f"|{label['why_it_works']}|{reg}"
135
+ )
136
+
137
+
138
+ # ── API ─────────────────────────────────────────────────────────────────────────
139
+ def get_api_key() -> str:
140
+ for var in ["DEEPSEEK_API_KEY", "DEEPSEEK_KEY"]:
141
+ key = os.environ.get(var)
142
+ if key:
143
+ return key
144
+ # Fallback: extract from ~/.zshrc
145
+ for var in ["DEEPSEEK_API_KEY", "DEEPSEEK_KEY"]:
146
+ try:
147
+ r = subprocess.run(
148
+ ["bash", "-c", f"source ~/.zshrc 2>/dev/null; echo ${var}"],
149
+ capture_output=True, text=True, timeout=5,
150
+ )
151
+ val = r.stdout.strip()
152
+ if val and not val.startswith("$"):
153
+ logger.info(f"Loaded {var} from ~/.zshrc")
154
+ return val
155
+ except Exception:
156
+ pass
157
+ logger.error("No DEEPSEEK_API_KEY or DEEPSEEK_KEY found in env or ~/.zshrc")
158
+ sys.exit(1)
159
+
160
+
161
+ def parse_label(raw: str) -> dict | None:
162
+ cleaned = re.sub(r"```(?:json)?|```", "", raw).strip()
163
+ m = re.search(r"\{.*\}", cleaned, re.DOTALL)
164
+ if not m:
165
+ return None
166
+ try:
167
+ d = json.loads(m.group())
168
+ if d.get("skip"):
169
+ return None
170
+ if d.get("archetype") not in VALID_ARCHETYPES:
171
+ return None
172
+ if d.get("tension_type") not in VALID_TENSIONS:
173
+ return None
174
+ if d.get("violation_distance") not in VALID_DISTANCES:
175
+ return None
176
+ for f in ["character", "setup", "response", "why_it_works"]:
177
+ if not d.get(f):
178
+ return None
179
+ d[f] = d[f].replace("|", " ").strip()
180
+ d["emotional_register"] = d.get("emotional_register", "deadpan").replace("|", " ").strip()
181
+ return d
182
+ except (json.JSONDecodeError, KeyError):
183
+ return None
184
+
185
+
186
+ async def label_one(
187
+ client: AsyncOpenAI,
188
+ scene: dict,
189
+ sem: asyncio.Semaphore,
190
+ n_done: list, # mutable counter [int]
191
+ n_total: int,
192
+ out_f,
193
+ lock: asyncio.Lock,
194
+ ) -> None:
195
+ prompt = LABEL_PROMPT.format(
196
+ season=scene["season"],
197
+ episode=scene["episode"],
198
+ scene_text=format_scene(scene["lines"]),
199
+ )
200
+ try:
201
+ async with sem:
202
+ resp = await client.chat.completions.create(
203
+ model=MODEL,
204
+ messages=[{"role": "user", "content": prompt}],
205
+ temperature=0.3,
206
+ max_tokens=380,
207
+ )
208
+ label = parse_label(resp.choices[0].message.content or "")
209
+ except Exception as e:
210
+ logger.warning(f"S{scene['season']}E{scene['episode']}: {str(e)[:60]}")
211
+ return
212
+
213
+ if label is None:
214
+ return
215
+
216
+ sid = (scene["season"], scene["episode"], scene["scene"])
217
+ line = f"# S{sid[0]}E{sid[1]}Scene{sid[2]}\n{to_pipe(scene, label)}\n"
218
+
219
+ async with lock:
220
+ out_f.write(line)
221
+ out_f.flush()
222
+ n_done[0] += 1
223
+ if n_done[0] % 50 == 0 or n_done[0] <= 5:
224
+ logger.info(
225
+ f"[{n_done[0]}/{n_total}] S{sid[0]}E{sid[1]} "
226
+ f"β†’ {label['archetype']} | {label['character']}: {label['response'][:55]}..."
227
+ )
228
+
229
+
230
+ async def main_async():
231
+ Path(OUTPUT_PATH).parent.mkdir(parents=True, exist_ok=True)
232
+
233
+ ds = load_office_lines()
234
+ candidates = group_into_scenes(ds)
235
+
236
+ already_done = load_already_done(OUTPUT_PATH)
237
+ logger.info(f"Already labeled: {len(already_done)}")
238
+
239
+ todo = [
240
+ c for c in candidates
241
+ if (c["season"], c["episode"], c["scene"]) not in already_done
242
+ ]
243
+ random.seed(42)
244
+ random.shuffle(todo)
245
+ todo = todo[:TARGET_SCENES]
246
+
247
+ if not todo:
248
+ logger.success("Nothing to do β€” all scenes already labeled.")
249
+ return
250
+
251
+ # Cost estimate
252
+ n = len(todo)
253
+ est_cost = n * (300 * 0.14 + 180 * 0.28) / 1_000_000
254
+ est_min = round(n / CONCURRENCY * 2 / 60, 1) # ~2s per wave
255
+ logger.info(
256
+ f"Labeling {n} scenes | est. cost β‰ˆ ${est_cost:.3f} | "
257
+ f"est. time β‰ˆ {est_min} min @ concurrency={CONCURRENCY}"
258
+ )
259
+
260
+ api_key = get_api_key()
261
+ client = AsyncOpenAI(api_key=api_key, base_url=DEEPSEEK_BASE)
262
+
263
+ # Quick connectivity check
264
+ try:
265
+ test = await client.chat.completions.create(
266
+ model=MODEL,
267
+ messages=[{"role": "user", "content": "Say OK"}],
268
+ temperature=0.1, max_tokens=5,
269
+ )
270
+ logger.success(f"API OK β€” {test.choices[0].message.content!r}")
271
+ except Exception as e:
272
+ logger.error(f"API failed: {e}")
273
+ sys.exit(1)
274
+
275
+ sem = asyncio.Semaphore(CONCURRENCY)
276
+ lock = asyncio.Lock()
277
+ n_done = [0]
278
+
279
+ with open(OUTPUT_PATH, "a", encoding="utf-8") as out_f:
280
+ tasks = [
281
+ label_one(client, scene, sem, n_done, n, out_f, lock)
282
+ for scene in todo
283
+ ]
284
+ await asyncio.gather(*tasks)
285
+
286
+ total = len(already_done) + n_done[0]
287
+ logger.success(f"Done. Labeled={n_done[0]}, total in file={total}")
288
+
289
+
290
+ if __name__ == "__main__":
291
+ asyncio.run(main_async())
scripts/eval.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WitGym closed-loop evaluation harness.
3
+
4
+ Usage:
5
+ # Before any changes β€” capture baseline:
6
+ python scripts/eval.py --tag before
7
+
8
+ # After all changes + index rebuild:
9
+ python scripts/eval.py --tag after
10
+
11
+ # Compare the two snapshots:
12
+ python scripts/eval.py --compare
13
+
14
+ Each run saves results to data/eval_{tag}.json.
15
+ Compare prints a side-by-side table of selected outputs + word counts.
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import sys
21
+ import time
22
+ from pathlib import Path
23
+
24
+ from dotenv import load_dotenv
25
+ load_dotenv()
26
+
27
+ # Five canonical test inputs (from durable_memory.md Β§5)
28
+ TEST_INPUTS = [
29
+ "I just got promoted to manager and I have no idea what I'm doing.",
30
+ "My coworker keeps stealing my lunch from the fridge.",
31
+ "I've been cc'd on an email chain I definitely should not be reading.",
32
+ "I'm pretending to understand cryptocurrency at dinner parties.",
33
+ "My therapist fell asleep during our session.",
34
+ ]
35
+
36
+
37
+ def run_eval(tag: str, index_path: str = "data/index.json") -> None:
38
+ """Run all 5 test inputs, save results snapshot."""
39
+ from witgym.engine import WitGymEngine
40
+
41
+ if not Path(index_path).exists():
42
+ print(f"[ERROR] Index not found at {index_path}. Run `witgym-index` first.")
43
+ sys.exit(1)
44
+
45
+ engine = WitGymEngine(index_path=index_path)
46
+ results = []
47
+
48
+ for i, user_input in enumerate(TEST_INPUTS, 1):
49
+ print(f"\n[{i}/5] Input: {user_input[:60]}...")
50
+ t0 = time.time()
51
+ response = engine.respond(user_input)
52
+ elapsed = time.time() - t0
53
+
54
+ result = {
55
+ "input": user_input,
56
+ "selected": response.selected,
57
+ "word_count": len(response.selected.split()),
58
+ "archetype": response.metadata.archetype.value,
59
+ "tension": response.metadata.tension_type.value,
60
+ "violation_distance": response.metadata.violation_distance.value,
61
+ "candidates": [
62
+ {"persona": c.persona, "text": c.text, "words": len(c.text.split())}
63
+ for c in response.candidates
64
+ ],
65
+ "retrieved_scenes": [
66
+ {"show": s.show, "archetype": s.archetype.value, "setup": s.setup[:80]}
67
+ for s in response.retrieved_scenes
68
+ ],
69
+ "latency_s": round(elapsed, 1),
70
+ }
71
+
72
+ # Add twist_potential if present (post-v2 schema)
73
+ if hasattr(response.metadata, "twist_potential"):
74
+ result["twist_potential"] = response.metadata.twist_potential
75
+
76
+ print(f" β†’ [{response.metadata.archetype.value}] {response.selected}")
77
+ print(f" β†’ {len(response.selected.split())} words | {elapsed:.1f}s")
78
+ results.append(result)
79
+
80
+ out_path = f"data/eval_{tag}.json"
81
+ with open(out_path, "w", encoding="utf-8") as f:
82
+ json.dump({"tag": tag, "results": results}, f, indent=2)
83
+ print(f"\nβœ“ Saved eval snapshot β†’ {out_path}")
84
+
85
+
86
+ def compare_evals() -> None:
87
+ """Side-by-side comparison of before vs after snapshots."""
88
+ before_path = "data/eval_before.json"
89
+ after_path = "data/eval_after.json"
90
+
91
+ missing = [p for p in [before_path, after_path] if not Path(p).exists()]
92
+ if missing:
93
+ print(f"[ERROR] Missing snapshots: {missing}")
94
+ print(" Run: python scripts/eval.py --tag before")
95
+ print(" Then: python scripts/eval.py --tag after")
96
+ sys.exit(1)
97
+
98
+ with open(before_path) as f:
99
+ before_data = json.load(f)
100
+ with open(after_path) as f:
101
+ after_data = json.load(f)
102
+
103
+ before_results = {r["input"]: r for r in before_data["results"]}
104
+ after_results = {r["input"]: r for r in after_data["results"]}
105
+
106
+ print("\n" + "=" * 90)
107
+ print("WITGYM EVAL: BEFORE vs AFTER")
108
+ print("=" * 90)
109
+
110
+ total_word_delta = 0
111
+ total_latency_delta = 0
112
+
113
+ for inp in TEST_INPUTS:
114
+ b = before_results.get(inp)
115
+ a = after_results.get(inp)
116
+ if not b or not a:
117
+ continue
118
+
119
+ word_delta = a["word_count"] - b["word_count"]
120
+ latency_delta = a["latency_s"] - b["latency_s"]
121
+ total_word_delta += word_delta
122
+ total_latency_delta += latency_delta
123
+
124
+ print(f"\nπŸ“ Input: {inp[:70]}")
125
+ print(f" BEFORE [{b['word_count']}w, {b['latency_s']}s, {b['archetype']}]:")
126
+ print(f" βœ— {b['selected']}")
127
+ print(f" AFTER [{a['word_count']}w, {a['latency_s']}s, {a['archetype']}]:")
128
+ print(f" βœ“ {a['selected']}")
129
+ word_indicator = "↓ shorter" if word_delta < 0 else ("↑ longer" if word_delta > 0 else "= same")
130
+ lat_indicator = "↓ faster" if latency_delta < 0 else ("↑ slower" if latency_delta > 0 else "= same")
131
+ print(f" Ξ” words={word_delta:+d} ({word_indicator}), Ξ” latency={latency_delta:+.1f}s ({lat_indicator})")
132
+
133
+ # Show candidate diversity
134
+ if a.get("candidates"):
135
+ personas_after = [c["persona"] for c in a["candidates"]]
136
+ print(f" Candidates: {personas_after}")
137
+
138
+ print("\n" + "-" * 90)
139
+ print(f"SUMMARY β€” avg word delta: {total_word_delta/len(TEST_INPUTS):+.1f} words | avg latency delta: {total_latency_delta/len(TEST_INPUTS):+.1f}s")
140
+ print("=" * 90)
141
+
142
+
143
+ def main():
144
+ parser = argparse.ArgumentParser(description="WitGym closed-loop evaluator")
145
+ parser.add_argument("--tag", choices=["before", "after"], help="Run eval and save snapshot with this tag")
146
+ parser.add_argument("--compare", action="store_true", help="Compare before vs after snapshots")
147
+ parser.add_argument("--index", default="data/index.json")
148
+ args = parser.parse_args()
149
+
150
+ if args.compare:
151
+ compare_evals()
152
+ elif args.tag:
153
+ run_eval(args.tag, args.index)
154
+ else:
155
+ parser.print_help()
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
witgym/engine.py CHANGED
@@ -10,7 +10,7 @@ from witgym.model import load_model
10
  from witgym.schemas import WitGymResponse
11
  from witgym.extractor import extract_comedy_metadata
12
  from witgym.retriever import load_index, retrieve_scenes
13
- from witgym.generator import generate_candidates, rank_candidates
14
  from witgym.conversation import ConversationManager
15
 
16
 
@@ -41,9 +41,23 @@ class WitGymEngine:
41
  if self.conversation.needs_compression(self.tokenizer):
42
  self.conversation.compress(self.model, self.tokenizer)
43
 
44
- # PASS 1 β€” Extract comedy metadata
45
  metadata = extract_comedy_metadata(user_input, self.model, self.tokenizer)
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # RAG β€” Retrieve analogous situations (not similar text)
48
  scenes = retrieve_scenes(
49
  self.index,
@@ -52,16 +66,29 @@ class WitGymEngine:
52
  self.embed_model,
53
  )
54
 
55
- # PASS 2 β€” Generate 3 persona candidates
 
 
56
  context_str = self.conversation.get_context_string()
 
 
 
 
 
57
  candidates = generate_candidates(
58
  user_input, metadata, scenes,
59
  self.model, self.tokenizer,
60
  context_str, self.conversation.used_archetypes,
 
61
  )
62
 
63
- # RANK β€” Pick best candidate + hard cap at 2 sentences
64
  selected = rank_candidates(user_input, candidates, self.model, self.tokenizer)
 
 
 
 
 
65
  selected = _cap_two_sentences(selected)
66
 
67
  # Update state
 
10
  from witgym.schemas import WitGymResponse
11
  from witgym.extractor import extract_comedy_metadata
12
  from witgym.retriever import load_index, retrieve_scenes
13
+ from witgym.generator import generate_candidates, rank_candidates, compress_winner
14
  from witgym.conversation import ConversationManager
15
 
16
 
 
41
  if self.conversation.needs_compression(self.tokenizer):
42
  self.conversation.compress(self.model, self.tokenizer)
43
 
44
+ # PASS 1 β€” Extract comedy metadata (includes twist_potential 1-10)
45
  metadata = extract_comedy_metadata(user_input, self.model, self.tokenizer)
46
 
47
+ # GATE β€” Flat inputs (twist_potential < 4) skip the full wit pipeline.
48
+ # Prevents the uncanny valley: "structured-like-a-joke, lands-as-bizarre"
49
+ # on inputs with no real comedy tension.
50
+ if metadata.twist_potential < 4:
51
+ logger.info(f"twist_potential={metadata.twist_potential} < 4 β€” returning straight reply")
52
+ selected = "Yeah, that tracks."
53
+ self.conversation.add_turn(user_input, selected, metadata.archetype)
54
+ return WitGymResponse(
55
+ metadata=metadata,
56
+ retrieved_scenes=[],
57
+ candidates=[],
58
+ selected=selected,
59
+ )
60
+
61
  # RAG β€” Retrieve analogous situations (not similar text)
62
  scenes = retrieve_scenes(
63
  self.index,
 
66
  self.embed_model,
67
  )
68
 
69
+ # PASS 2 β€” Generate persona candidates.
70
+ # Medium inputs (4-6): run cynic + absurdist only.
71
+ # Rich inputs (> 6): run all three including frame_switcher.
72
  context_str = self.conversation.get_context_string()
73
+ personas_to_run = None # None = all three
74
+ if metadata.twist_potential <= 6:
75
+ personas_to_run = ["cynic", "absurdist"] # Frame switcher needs rich tension
76
+ logger.info(f"twist_potential={metadata.twist_potential} ≀ 6 β€” skipping frame_switcher")
77
+
78
  candidates = generate_candidates(
79
  user_input, metadata, scenes,
80
  self.model, self.tokenizer,
81
  context_str, self.conversation.used_archetypes,
82
+ personas_to_run=personas_to_run,
83
  )
84
 
85
+ # RANK β€” Pick best candidate
86
  selected = rank_candidates(user_input, candidates, self.model, self.tokenizer)
87
+
88
+ # COMPRESS β€” Swartzwelder pass: generate loose, cut ruthless (skips if ≀12 words)
89
+ selected = compress_winner(selected, self.model, self.tokenizer)
90
+
91
+ # Hard safety cap at 2 sentences
92
  selected = _cap_two_sentences(selected)
93
 
94
  # Update state
witgym/extractor.py CHANGED
@@ -18,10 +18,12 @@ Return ONLY a JSON object with these exact fields (no explanation, no markdown,
18
  "tension_type": one of ["social_embarrass", "existential", "status_threat", "identity_expose", "logic_collapse"],
19
  "power_dynamic": "who has power and who doesn't, one sentence",
20
  "obvious_response": "the most boring, expected response to this input",
21
- "violation_distance": one of ["mild", "moderate", "sharp"]
 
22
  }}
23
 
24
  Think carefully about the ARCHETYPE β€” pick the one that most accurately describes the comedy mechanism hiding in this input.
 
25
  Return ONLY the JSON. Nothing else."""
26
 
27
 
@@ -47,7 +49,7 @@ def extract_comedy_metadata(user_input: str, model, tokenizer) -> ComedyMetadata
47
  try:
48
  data = json.loads(match.group())
49
  metadata = ComedyMetadata.model_validate(data)
50
- logger.info(f"Extracted: archetype={metadata.archetype.value}, tension={metadata.tension_type.value}")
51
  return metadata
52
  except Exception as e:
53
  logger.warning(f"Parse error (attempt {attempt + 1}): {e}")
 
18
  "tension_type": one of ["social_embarrass", "existential", "status_threat", "identity_expose", "logic_collapse"],
19
  "power_dynamic": "who has power and who doesn't, one sentence",
20
  "obvious_response": "the most boring, expected response to this input",
21
+ "violation_distance": one of ["mild", "moderate", "sharp"],
22
+ "twist_potential": an integer from 1 to 10 rating how much hidden comedy tension is in this input (1=completely flat, 10=extremely rich setup for wit)
23
  }}
24
 
25
  Think carefully about the ARCHETYPE β€” pick the one that most accurately describes the comedy mechanism hiding in this input.
26
+ For twist_potential: score high if the input has self-delusion, status gap, or absurd logic. Score low if it is a neutral factual statement with no tension.
27
  Return ONLY the JSON. Nothing else."""
28
 
29
 
 
49
  try:
50
  data = json.loads(match.group())
51
  metadata = ComedyMetadata.model_validate(data)
52
+ logger.info(f"Extracted: archetype={metadata.archetype.value}, tension={metadata.tension_type.value}, twist_potential={metadata.twist_potential}")
53
  return metadata
54
  except Exception as e:
55
  logger.warning(f"Parse error (attempt {attempt + 1}): {e}")
witgym/generator.py CHANGED
@@ -2,7 +2,9 @@
2
 
3
  Implements Principles 4, 5, and 6 from the spec.
4
  """
5
- from typing import List
 
 
6
  from loguru import logger
7
  from transformers import LogitsProcessorList
8
  from witgym.model import generate_text, ClichePenaltyProcessor
@@ -12,19 +14,28 @@ from witgym.schemas import (
12
 
13
  PERSONA_INSTRUCTIONS = {
14
  "cynic": (
15
- "Expose the social hypocrisy or delusion in what was said. "
16
- "Find the gap between their self-image and reality. "
17
- "Be sharp but not cruel."
 
 
18
  ),
19
- "observer": (
20
- "Say the thing everyone sees but nobody says. "
21
- "Point at the recognizable truth they didn't intend to reveal. "
22
- "Be precise, not mean."
 
 
 
 
 
23
  ),
24
  "absurdist": (
25
- "Follow the logic of their situation to its most surreal honest conclusion. "
26
- "Stay grounded in their reality, then take one step too far. "
27
- "No random weirdness β€” logical weirdness only."
 
 
28
  ),
29
  }
30
 
@@ -83,16 +94,26 @@ def generate_candidates(
83
  tokenizer,
84
  context_str: str,
85
  used_archetypes: set,
 
86
  ) -> List[CandidateResponse]:
87
- """Generate 3 candidates β€” one per persona β€” with ClichePenalty applied."""
 
 
 
 
88
  scenes_block = _build_scenes_block(scenes)
89
  used_str = ", ".join(a.value for a in used_archetypes) if used_archetypes else "none yet"
90
 
 
 
 
 
 
91
  cliche_processor = ClichePenaltyProcessor(metadata.obvious_response, tokenizer)
92
  processors = LogitsProcessorList([cliche_processor])
93
 
94
  candidates = []
95
- for persona_name, persona_instruction in PERSONA_INSTRUCTIONS.items():
96
  prompt = GENERATION_PROMPT.format(
97
  user_input=user_input,
98
  surface=metadata.surface,
@@ -117,27 +138,43 @@ def generate_candidates(
117
  violation_type=f"{metadata.archetype.value} via {persona_name} lens",
118
  ))
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  return candidates
121
 
122
 
123
  RANK_PROMPT = """\
124
- You are judging three comedy responses to: "{user_input}"
125
 
126
- Candidate 1 ({p1}, {w1} words): {c1}
127
- Candidate 2 ({p2}, {w2} words): {c2}
128
- Candidate 3 ({p3}, {w3} words): {c3}
129
 
130
- Pick the funniest one. Judge in this exact order of priority:
131
 
132
- 1. BREVITY β€” Shorter is almost always funnier. Compression is comedy. The correct answer is almost never the longest one.
133
- 2. SHARPNESS β€” Does the punchline land immediately, without unpacking? Can you feel it the first time you read it?
134
- 3. TRUTH β€” Does it say something recognizable that nobody said out loud?
135
- 4. BENIGN β€” Slightly uncomfortable but not offensive.
136
 
137
- The correct answer is almost always NOT the longest or most complex one.
138
- If two candidates are close on sharpness, always pick the shorter one.
139
 
140
- Reply ONLY with a single digit: 1, 2, or 3. Nothing else."""
141
 
142
 
143
  def rank_candidates(
@@ -154,6 +191,29 @@ def rank_candidates(
154
  if len(candidates) == 1:
155
  return candidates[0].text
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  # Shuffle into a random order for this call β€” eliminates positional bias
158
  import random
159
  shuffled = list(enumerate(candidates)) # [(orig_idx, candidate), ...]
@@ -162,11 +222,17 @@ def rank_candidates(
162
  # Word counts β€” makes brevity signal machine-readable, not just verbal
163
  w_shuffled = [len(c.text.split()) for _, c in shuffled]
164
 
 
 
 
 
 
 
165
  prompt = RANK_PROMPT.format(
 
166
  user_input=user_input,
167
- p1=shuffled[0][1].persona, w1=w_shuffled[0], c1=shuffled[0][1].text,
168
- p2=shuffled[1][1].persona, w2=w_shuffled[1], c2=shuffled[1][1].text,
169
- p3=shuffled[2][1].persona, w3=w_shuffled[2], c3=shuffled[2][1].text,
170
  )
171
 
172
  raw = generate_text(prompt, model, tokenizer, config_type="rank")
@@ -175,7 +241,7 @@ def rank_candidates(
175
 
176
  # Map chosen digit back through the shuffle to original candidate
177
  for ch in raw:
178
- if ch in "123":
179
  shuffled_choice = int(ch) - 1
180
  if 0 <= shuffled_choice < len(shuffled):
181
  orig_idx, winner = shuffled[shuffled_choice]
@@ -188,3 +254,44 @@ def rank_candidates(
188
  logger.warning(f"Ranking failed β€” shortest fallback: {candidates[shortest_idx].persona} ({w_orig[shortest_idx]} words)")
189
  return candidates[shortest_idx].text
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  Implements Principles 4, 5, and 6 from the spec.
4
  """
5
+ from typing import List, Set
6
+ from collections import Counter
7
+ import re as _re
8
  from loguru import logger
9
  from transformers import LogitsProcessorList
10
  from witgym.model import generate_text, ClichePenaltyProcessor
 
14
 
15
  PERSONA_INSTRUCTIONS = {
16
  "cynic": (
17
+ "You've seen this exact rationalization a hundred times. "
18
+ "You're not angry about it β€” you're just tired. "
19
+ "State what's actually happening with the weariness of someone who has been right about this for years. "
20
+ "Open with the situation, the consequence, or the outcome as your subject β€” "
21
+ "lead with something concrete and specific, not a generic observation about the person."
22
  ),
23
+ "frame_switcher": (
24
+ "This situation is actually being processed by a completely unrelated formal institution. "
25
+ "Choose whichever institution maps most absurdly and precisely onto the specific tension in this input β€” "
26
+ "a regulatory body, a scientific agency, a legal tribunal, a certification board, an athletic committee, "
27
+ "or any other formal system whose rules would make this situation absurd. "
28
+ "Do not list the institution's name as a setup β€” just speak in its voice directly. "
29
+ "Check the CONVERSATION CONTEXT: if a prior WitGym response already used a particular institution type, "
30
+ "pick a different one. "
31
+ "Report with total conviction, as if this framing is obviously correct."
32
  ),
33
  "absurdist": (
34
+ "You're the only person in the room who sees where this logically ends. "
35
+ "You're not being weird β€” you're just following the math. "
36
+ "State the inevitable conclusion with the calm of someone reading from a manual. "
37
+ "End with a single, specific concrete image that makes the conclusion visible β€” "
38
+ "not an abstraction, not a restatement. A physical object, a measurable action, a named institution."
39
  ),
40
  }
41
 
 
94
  tokenizer,
95
  context_str: str,
96
  used_archetypes: set,
97
+ personas_to_run: List[str] = None,
98
  ) -> List[CandidateResponse]:
99
+ """Generate persona candidates (1-3) with ClichePenalty applied.
100
+
101
+ personas_to_run: optional subset of PERSONA_INSTRUCTIONS keys.
102
+ None = all three (default). Engine gates this based on twist_potential.
103
+ """
104
  scenes_block = _build_scenes_block(scenes)
105
  used_str = ", ".join(a.value for a in used_archetypes) if used_archetypes else "none yet"
106
 
107
+ active_personas = {
108
+ name: instr for name, instr in PERSONA_INSTRUCTIONS.items()
109
+ if personas_to_run is None or name in personas_to_run
110
+ }
111
+
112
  cliche_processor = ClichePenaltyProcessor(metadata.obvious_response, tokenizer)
113
  processors = LogitsProcessorList([cliche_processor])
114
 
115
  candidates = []
116
+ for persona_name, persona_instruction in active_personas.items():
117
  prompt = GENERATION_PROMPT.format(
118
  user_input=user_input,
119
  surface=metadata.surface,
 
138
  violation_type=f"{metadata.archetype.value} via {persona_name} lens",
139
  ))
140
 
141
+ # Lexical carry-forward: ban top content words from previous candidate
142
+ # in all subsequent candidates to force vocabulary divergence
143
+ _STOP_WORDS = {
144
+ "the", "a", "an", "is", "was", "i", "you", "it", "in", "of",
145
+ "to", "and", "that", "this", "they", "their", "are", "be",
146
+ "have", "has", "but", "not", "or", "at", "by", "we", "he", "she",
147
+ }
148
+ words = [
149
+ w.lower() for w in _re.findall(r"\b\w+\b", raw)
150
+ if w.lower() not in _STOP_WORDS and len(w) > 3
151
+ ]
152
+ if words:
153
+ top_words = [w for w, _ in Counter(words).most_common(8)]
154
+ # Add these word token IDs to the penalty set for next candidates
155
+ for word in top_words:
156
+ extra_ids = tokenizer.encode(word, add_special_tokens=False)
157
+ cliche_processor.penalty_ids.update(extra_ids[:2]) # first 2 tokens of each word
158
+
159
  return candidates
160
 
161
 
162
  RANK_PROMPT = """\
163
+ You are judging {n} comedy responses to: "{user_input}"
164
 
165
+ {candidates_block}
 
 
166
 
167
+ Pick the funniest one using this exact priority order:
168
 
169
+ 1. CONCRETE IMAGE β€” The best response ends with a single specific, unexpected image or action that makes the human truth visible. Responses using only abstract concepts or bureaucratic jargon with no specific image always lose. "The drill is merely a gentle hug" beats "the patient submitted a fitness statement."
170
+ 2. SHARPNESS β€” Does the punchline land on first read without unpacking?
171
+ 3. TRUTH β€” Does it name something recognizable that nobody said out loud?
172
+ 4. BREVITY β€” If sharpness and image quality are equal, pick the shorter one.
173
 
174
+ A sharp 20-word line with a specific concrete image beats a flat 10-word line of jargon.
175
+ Responses that are purely bureaucratic or purely abstract always lose, regardless of length.
176
 
177
+ Reply ONLY with a single digit ({valid_digits}). Nothing else."""
178
 
179
 
180
  def rank_candidates(
 
191
  if len(candidates) == 1:
192
  return candidates[0].text
193
 
194
+ # Pre-rank refusal filter: remove any candidate that leaked prompt internals or refused
195
+ # This must happen BEFORE the LLM ranker sees candidates
196
+ _REFUSAL_SIGNALS = (
197
+ "i cannot", "i'm unable", "the prompt requires", "i am unable",
198
+ "i need to clarify", "as an ai", "i can't complete",
199
+ )
200
+ clean_candidates = [
201
+ c for c in candidates
202
+ if not any(sig in c.text.lower() for sig in _REFUSAL_SIGNALS)
203
+ ]
204
+ if len(clean_candidates) == 0:
205
+ logger.warning("All candidates were refusals β€” returning shortest original")
206
+ w_orig = [len(c.text.split()) for c in candidates]
207
+ return candidates[min(range(len(candidates)), key=lambda i: w_orig[i])].text
208
+ if len(clean_candidates) < len(candidates):
209
+ logger.warning(f"Filtered {len(candidates) - len(clean_candidates)} refusal candidate(s) before ranking")
210
+ candidates = clean_candidates
211
+
212
+ if len(candidates) == 1:
213
+ return candidates[0].text
214
+
215
+ # Fall through to LLM ranker for both 2 and 3 candidate paths
216
+
217
  # Shuffle into a random order for this call β€” eliminates positional bias
218
  import random
219
  shuffled = list(enumerate(candidates)) # [(orig_idx, candidate), ...]
 
222
  # Word counts β€” makes brevity signal machine-readable, not just verbal
223
  w_shuffled = [len(c.text.split()) for _, c in shuffled]
224
 
225
+ # Build dynamic candidates block (works for 2 or 3 candidates)
226
+ digits = [str(i + 1) for i in range(len(shuffled))]
227
+ lines = [
228
+ f"Candidate {i + 1} ({shuffled[i][1].persona}, {w_shuffled[i]} words): {shuffled[i][1].text}"
229
+ for i in range(len(shuffled))
230
+ ]
231
  prompt = RANK_PROMPT.format(
232
+ n=len(shuffled),
233
  user_input=user_input,
234
+ candidates_block="\n".join(lines),
235
+ valid_digits="/".join(digits),
 
236
  )
237
 
238
  raw = generate_text(prompt, model, tokenizer, config_type="rank")
 
241
 
242
  # Map chosen digit back through the shuffle to original candidate
243
  for ch in raw:
244
+ if ch in digits:
245
  shuffled_choice = int(ch) - 1
246
  if 0 <= shuffled_choice < len(shuffled):
247
  orig_idx, winner = shuffled[shuffled_choice]
 
254
  logger.warning(f"Ranking failed β€” shortest fallback: {candidates[shortest_idx].persona} ({w_orig[shortest_idx]} words)")
255
  return candidates[shortest_idx].text
256
 
257
+
258
+ _COMPRESS_PROMPT = """\
259
+ The following comedy line is good but possibly too long. Compress it to ≀12 words while keeping the punchline completely intact.
260
+
261
+ Original: "{winner}"
262
+
263
+ Rules:
264
+ - The FINAL CLAUSE of the sentence is almost always the punchline. NEVER cut it. Cut from the setup or the middle only.
265
+ - If the final clause must be removed to hit ≀12 words, return the original UNCHANGED.
266
+ - Do NOT change the joke structure β€” only remove filler words from the setup.
267
+ - Return ONLY the compressed version or the original. No explanation. No quotes."""
268
+
269
+
270
+ def compress_winner(winner: str, model, tokenizer) -> str:
271
+ """Swartzwelder compression pass: generate loose, cut ruthless.
272
+
273
+ Skipped if winner is already ≀12 words (already tight).
274
+ Guards: rejects output that is < 4 words or longer than the original.
275
+ """
276
+ if len(winner.split()) <= 12:
277
+ return winner # Already tight β€” skip the LLM call
278
+
279
+ prompt = _COMPRESS_PROMPT.format(winner=winner)
280
+ compressed = generate_text(prompt, model, tokenizer, config_type="extract")
281
+ compressed = compressed.strip().strip('"').strip("'")
282
+
283
+ # Sanity guards: reject if collapsed, expanded, or starts with a fragment marker
284
+ _FRAGMENT_STARTS = (
285
+ "but ", "and ", "or ", "which ", "that ", "because ",
286
+ "while ", "since ", "although ", "if ", "though ",
287
+ )
288
+ if len(compressed.split()) < 4 or len(compressed.split()) >= len(winner.split()):
289
+ logger.debug(f"Compression rejected (collapsed/expanded). Keeping original.")
290
+ return winner
291
+ if compressed.lower().startswith(_FRAGMENT_STARTS):
292
+ logger.debug(f"Compression rejected (fragment start: '{compressed[:20]}'). Keeping original.")
293
+ return winner
294
+
295
+ logger.info(f"Compressed: {len(winner.split())}w β†’ {len(compressed.split())}w | '{compressed}'")
296
+ return compressed
297
+
witgym/indexer.py CHANGED
@@ -24,10 +24,10 @@ def _parse_transcript_file(filepath: Path) -> List[TranscriptScene]:
24
  if not line or line.startswith("#"):
25
  continue
26
  parts = line.split("|")
27
- if len(parts) != 8:
28
- logger.warning(f"{filepath.name}:{lineno} β€” expected 8 fields, got {len(parts)}. Skipping.")
29
  continue
30
- show, character, setup, response, arch_raw, tension_raw, dist_raw, why = parts
31
  try:
32
  scene = TranscriptScene(
33
  show=show.strip(),
 
24
  if not line or line.startswith("#"):
25
  continue
26
  parts = line.split("|")
27
+ if len(parts) not in (8, 9):
28
+ logger.warning(f"{filepath.name}:{lineno} β€” expected 8-9 fields, got {len(parts)}. Skipping.")
29
  continue
30
+ show, character, setup, response, arch_raw, tension_raw, dist_raw, why = parts[:8]
31
  try:
32
  scene = TranscriptScene(
33
  show=show.strip(),
witgym/main.py CHANGED
@@ -109,16 +109,16 @@ def chat_cmd():
109
  console.print(f"[red]Error: {e}[/red]")
110
  continue
111
 
112
- # Main response
 
 
 
113
  console.print(Panel(
114
  f"[bold white]{result.selected}[/bold white]",
115
  title=f"[cyan]WitGym[/cyan] [dim]({result.metadata.archetype.value})[/dim]",
116
  border_style="cyan",
117
  ))
118
 
119
- if args.debug:
120
- _show_debug_panel(result)
121
-
122
 
123
  def index_cmd():
124
  parser = argparse.ArgumentParser(description="WitGym β€” build RAG index from transcript files")
 
109
  console.print(f"[red]Error: {e}[/red]")
110
  continue
111
 
112
+ if args.debug:
113
+ _show_debug_panel(result)
114
+
115
+ # Main response β€” always last so it's visible at the bottom of the terminal
116
  console.print(Panel(
117
  f"[bold white]{result.selected}[/bold white]",
118
  title=f"[cyan]WitGym[/cyan] [dim]({result.metadata.archetype.value})[/dim]",
119
  border_style="cyan",
120
  ))
121
 
 
 
 
122
 
123
  def index_cmd():
124
  parser = argparse.ArgumentParser(description="WitGym β€” build RAG index from transcript files")
witgym/retriever.py CHANGED
@@ -60,16 +60,33 @@ def retrieve_scenes(
60
  # Rank all scenes by similarity
61
  ranked_indices = np.argsort(scores)[::-1]
62
 
63
- # Filter: exclude scenes whose archetype is already used in this session
 
64
  selected = []
 
65
  for idx in ranked_indices:
66
  scene = scenes[idx]
67
- if scene.archetype not in used_archetypes:
68
- selected.append(scene)
 
 
 
 
69
  if len(selected) >= top_k:
70
  break
71
 
72
- # If all archetypes exhausted (after 6 turns), just return top matches without filter
 
 
 
 
 
 
 
 
 
 
 
73
  if not selected:
74
  logger.warning("All archetypes used β€” returning top scenes without archetype filter")
75
  selected = [scenes[i] for i in ranked_indices[:top_k]]
 
60
  # Rank all scenes by similarity
61
  ranked_indices = np.argsort(scores)[::-1]
62
 
63
+ # Filter: exclude scenes whose archetype is already used in this session,
64
+ # AND enforce intra-call diversity (no two retrieved scenes share the same archetype)
65
  selected = []
66
+ selected_archetypes: Set[ComedyArchetype] = set()
67
  for idx in ranked_indices:
68
  scene = scenes[idx]
69
+ if scene.archetype in used_archetypes:
70
+ continue
71
+ if scene.archetype in selected_archetypes:
72
+ continue # Already have a scene of this archetype in this call
73
+ selected.append(scene)
74
+ selected_archetypes.add(scene.archetype)
75
  if len(selected) >= top_k:
76
  break
77
 
78
+ # Fallback 1: relax intra-call diversity if not enough distinct archetypes found
79
+ if len(selected) < top_k:
80
+ for idx in ranked_indices:
81
+ scene = scenes[idx]
82
+ if scene.archetype in used_archetypes:
83
+ continue
84
+ if scene not in selected:
85
+ selected.append(scene)
86
+ if len(selected) >= top_k:
87
+ break
88
+
89
+ # Fallback 2: all session archetypes exhausted β€” return top matches without filter
90
  if not selected:
91
  logger.warning("All archetypes used β€” returning top scenes without archetype filter")
92
  selected = [scenes[i] for i in ranked_indices[:top_k]]
witgym/schemas.py CHANGED
@@ -35,6 +35,7 @@ class ComedyMetadata(BaseModel):
35
  power_dynamic: str
36
  obvious_response: str
37
  violation_distance: ViolationDistance
 
38
 
39
 
40
  class TranscriptScene(BaseModel):
@@ -71,4 +72,5 @@ def fallback_metadata(user_input: str) -> ComedyMetadata:
71
  power_dynamic="speaker vs. social expectation",
72
  obvious_response="I see. That sounds challenging.",
73
  violation_distance=ViolationDistance.MODERATE,
 
74
  )
 
35
  power_dynamic: str
36
  obvious_response: str
37
  violation_distance: ViolationDistance
38
+ twist_potential: int = 5 # 1-10: comedy richness of the input; drives pipeline gating
39
 
40
 
41
  class TranscriptScene(BaseModel):
 
72
  power_dynamic="speaker vs. social expectation",
73
  obvious_response="I see. That sounds challenging.",
74
  violation_distance=ViolationDistance.MODERATE,
75
+ twist_potential=5,
76
  )