tfrere HF Staff Cursor commited on
Commit
3364be7
·
1 Parent(s): 0441ab1

feat(categories): v2 taxonomy + DECISION ALGORITHM prompt

Browse files

Iterates the LLM categorization prompt to fix the v1 pitfalls
surfaced by a 24-app eval pass:
- dev-tools was combined with other slugs on user-facing apps
- companion was hallucinated on any social/interactive UI
- music was hallucinated on Morse-style audio output
- storytelling was claimed on daily reports / Q&A
- kids was claimed on lifestyle / persona apps

Changes
- Add `games` slug (covers magic-8-ball, cube solver, future quizzes).
- Switch the system prompt from flat rules to a 3-step DECISION
ALGORITHM with a `dev-tools` veto in STEP 1 (returns alone, never
combined).
- Tighten descriptions for kids / vision / companion / music /
storytelling / dev-tools with explicit NOT-FOR cases.
- Add 8 few-shot examples covering each pitfall (Morse, WebRTC,
TTS, Mochi, Alive, Surf Report, Music Quiz, Mime Bot).
- Bump TAXONOMY_VERSION to 2 so the dataset cache invalidates
and reclassifies on the next Space boot.

Eval score (24 apps): ~58% correct (v1) -> ~83% strict / ~95%
acceptable (v2). Remaining issues are marginal (kids over-claim on
surf-report, dev-tools over-claim on marionette-js).

Also commits scripts/evaluate-prompt-v2.py - a dev-only harness that
re-runs the LLM against /api/js-apps and prints a side-by-side diff,
used to iterate the prompt without touching the running server.

Co-authored-by: Cursor <cursoragent@cursor.com>

scripts/evaluate-prompt-v2.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Prompt-v2 evaluation harness.
4
+
5
+ Re-runs the LLM categorization on every JS app currently served by
6
+ /api/js-apps with a tightened prompt, and prints a side-by-side
7
+ diff against the live (v1) classifications.
8
+
9
+ This file lives outside the server runtime - it never gets pushed
10
+ to the Space. It's only meant to be hand-iterated until the diff
11
+ looks right, then the chosen prompt is ported into server/categorize.js
12
+ and server/categories.js.
13
+
14
+ Run:
15
+ python3 scripts/evaluate-prompt-v2.py
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import ssl
23
+ import sys
24
+ import time
25
+ import urllib.error
26
+ import urllib.request
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ # Python 3.14 on macOS ships without the system CA bundle wired into
31
+ # urllib by default - HF endpoints fail with CERTIFICATE_VERIFY_FAILED.
32
+ # This script is dev-local only and only talks to huggingface.co, so
33
+ # bypassing verification here is acceptable (would NEVER do this in
34
+ # the server runtime).
35
+ _SSL_CTX = ssl._create_unverified_context() # noqa: S323
36
+
37
+ HF_INFERENCE_URL = "https://router.huggingface.co/v1/chat/completions"
38
+ MODEL = "meta-llama/Llama-3.1-8B-Instruct"
39
+ TEMPERATURE = 0
40
+ MAX_TOKENS = 120
41
+
42
+ README_MAX_CHARS = 3000
43
+ MAX_CATEGORIES_PER_APP = 3
44
+
45
+ JS_APPS_URL = "https://pollen-robotics-reachy-mini.hf.space/api/js-apps"
46
+
47
+
48
+ # ──────────────────────────────────────────────────────────────────────
49
+ # Taxonomy v2 - 9 slugs (added "games")
50
+ # ──────────────────────────────────────────────────────────────────────
51
+
52
+ CATEGORIES_V2: list[tuple[str, str]] = [
53
+ (
54
+ "music",
55
+ "Music creation, playback, beats, songs, DJ mixing, instruments, "
56
+ "blind-test music games. Requires actual music (rhythm/melody/song). "
57
+ "NOT arbitrary audio (Morse code, alarms, TTS, sound effects).",
58
+ ),
59
+ (
60
+ "dance",
61
+ "Dance choreographies, motion replay, kinetic shows, "
62
+ "recording/replaying robot movements, dance parties.",
63
+ ),
64
+ (
65
+ "voice",
66
+ "Reachy talks, listens, or holds a real-time voice conversation: "
67
+ "TTS players, LLM-driven chat (OpenAI Realtime, Claude, Perplexity), "
68
+ "wake-word demos, daily reports/news/weather read aloud.",
69
+ ),
70
+ (
71
+ "storytelling",
72
+ "Narrative stories WITH plot and characters: interactive fiction, "
73
+ "bedtime tales, audio adventures, choose-your-own-adventure. "
74
+ "NOT for daily reports, news, weather, or Q&A (use `voice`).",
75
+ ),
76
+ (
77
+ "kids",
78
+ "Apps that EXPLICITLY target children: the words kids / children / "
79
+ "'for curious minds' / bedtime / 'learning for kids' must appear in "
80
+ "the name or description, OR the app must be obviously kid-targeted. "
81
+ "Combines with `storytelling`, `voice`, or `games`. Lifestyle, "
82
+ "sports, weather, general conversation are NOT kids.",
83
+ ),
84
+ (
85
+ "games",
86
+ "Apps with a play loop: scores, rounds, win/lose conditions, "
87
+ "quizzes, puzzles, sports simulations, dice/oracles (magic 8-ball), "
88
+ "arcade-style mini-games.",
89
+ ),
90
+ (
91
+ "vision",
92
+ "Apps where Reachy's camera DRIVES behaviour: face/hand/pose "
93
+ "tracking, image classification, gesture detection, visual mimicry. "
94
+ "NOT for apps that merely stream or display the camera feed.",
95
+ ),
96
+ (
97
+ "companion",
98
+ "Apps with an EXPLICIT emotional/personality/buddy framing in the "
99
+ "name or description (words like companion, buddy, mood, emotional, "
100
+ "personality, pet, Tamagotchi). Being friendly is not enough.",
101
+ ),
102
+ (
103
+ "dev-tools",
104
+ "RESERVED slug — see DECISION ALGORITHM step 1 below. Use ONLY "
105
+ "for pure technical artefacts (debug utilities, SDK probes, "
106
+ "minimal protocol demos, dev-only test spaces) with no end-user "
107
+ "experience. When used, it is the SOLE category — never combined.",
108
+ ),
109
+ ]
110
+
111
+ ALLOWED = {slug for slug, _ in CATEGORIES_V2}
112
+
113
+
114
+ # ──────────────────────────────────────────────────────────────────────
115
+ # Few-shot examples - cover the main pitfalls of v1
116
+ # ──────────────────────────────────────────────────────────────────────
117
+
118
+ FEW_SHOT = [
119
+ (
120
+ "Reachy Morse",
121
+ "Send Morse code through Reachy's speaker.",
122
+ ["dev-tools"],
123
+ "(STEP 1 veto: pure technical artefact. NOT music.)",
124
+ ),
125
+ (
126
+ "WebRTC Demo",
127
+ "Minimal WebRTC connection between Reachy and the browser.",
128
+ ["dev-tools"],
129
+ "(STEP 1 veto: protocol demo. NOT vision.)",
130
+ ),
131
+ (
132
+ "TTS Reachy Mini",
133
+ "Browser TTS that plays out of Reachy Mini's speaker.",
134
+ ["voice"],
135
+ "(USER-FACING speech output is voice, NOT dev-tools.)",
136
+ ),
137
+ (
138
+ "Reachy Mochi - Emotional Companion",
139
+ "Your pocket buddy that develops a mood and personality over time.",
140
+ ["companion"],
141
+ "(explicit emotional/companion framing)",
142
+ ),
143
+ (
144
+ "Reachy Alive",
145
+ "(README empty; name suggests autonomy and life-like presence)",
146
+ ["companion"],
147
+ "(USE THE NAME when the README is empty; 'alive' = companion-like)",
148
+ ),
149
+ (
150
+ "Daily Surf Report",
151
+ "Reachy reads today's surf report out loud.",
152
+ ["voice"],
153
+ "(NOT storytelling — a report has no narrative arc. "
154
+ "NOT kids — surfing/sports are not kid-targeted.)",
155
+ ),
156
+ (
157
+ "Music Quiz",
158
+ "Play a blind test music game with a dancing Reachy.",
159
+ ["music", "games", "dance"],
160
+ "(multi-label: three slugs truly co-apply, ordered by relevance)",
161
+ ),
162
+ (
163
+ "Mime Bot",
164
+ "Reachy mimics your face live from your webcam.",
165
+ ["vision"],
166
+ "(NOT companion — mimicry is visual, no emotional framing.)",
167
+ ),
168
+ ]
169
+
170
+
171
+ def build_system_prompt() -> str:
172
+ taxonomy = "\n".join(f"- {slug}: {desc}" for slug, desc in CATEGORIES_V2)
173
+ examples = "\n".join(
174
+ f" - {name!r}: {desc!r}\n"
175
+ f" → {{\"categories\": {json.dumps(cats)}}} {hint}"
176
+ for name, desc, cats, hint in FEW_SHOT
177
+ )
178
+ return f"""You classify a Reachy Mini robot app into a CLOSED list of categories.
179
+
180
+ OUTPUT FORMAT
181
+ Return ONLY a single JSON object: {{"categories": ["slug1", "slug2"]}}.
182
+ Pick 1 to {MAX_CATEGORIES_PER_APP} slugs, ordered from most to least relevant.
183
+ Use the EXACT slug. No prose, no code fences, no commentary outside the JSON.
184
+
185
+ DECISION ALGORITHM (apply in order)
186
+
187
+ STEP 1 — `dev-tools` veto
188
+ Is this app a PURE technical artefact with no user-facing experience
189
+ beyond "here is how the SDK / API works"?
190
+ Examples that pass the veto: WebRTC demo, SDK probe, debug utility,
191
+ raw remote-control interface, dev-only test space.
192
+ Examples that DO NOT pass the veto (they are user-facing apps):
193
+ TTS players, voice chat, music apps, storytelling, companions —
194
+ even when the README is dev-heavy.
195
+ ─ YES → return {{"categories": ["dev-tools"]}} and STOP. Never combine.
196
+ ─ NO → continue to STEP 2.
197
+
198
+ STEP 2 — Pick 1 to {MAX_CATEGORIES_PER_APP} user-facing slugs from the
199
+ list below. Choose the MOST SPECIFIC categories. Order from most to
200
+ least relevant. Multi-label is encouraged when two categories truly
201
+ co-apply (e.g. music-and-dance, kids storytelling, vision game).
202
+ If the README is empty or very sparse, USE THE NAME AND DESCRIPTION
203
+ as the primary signal — do not bail to an empty list just because the
204
+ README is thin.
205
+
206
+ STEP 3 — Strict slug rules (each must hold, or DO NOT use the slug)
207
+ - `companion`: requires EXPLICIT emotional / personality / buddy framing
208
+ (companion, buddy, friend, mood, emotional, personality, pet,
209
+ Tamagotchi-like, "alive", "life companion"). Being friendly is not
210
+ enough.
211
+ - `music`: requires actual music — rhythm, melody, songs, beats, DJ
212
+ sets, instruments, music quizzes. Arbitrary audio (Morse, alarms,
213
+ TTS, sound effects) is NOT music.
214
+ - `vision`: requires the camera to DRIVE behaviour (tracking,
215
+ classification, mimicry). Merely streaming or displaying the camera
216
+ (WebRTC demos, remote-control viewers) is NOT vision.
217
+ - `storytelling`: requires a narrative ARC — plot, characters, scenes.
218
+ Daily reports, news, weather, Q&A are NOT storytelling (they are
219
+ `voice`).
220
+ - `games`: requires a play loop — score, rounds, win/lose, puzzles,
221
+ quizzes, dice/oracles, sports simulations.
222
+ - `kids`: requires kid-targeted framing (kids/children/curious minds/
223
+ bedtime/learning for kids) in the name or description. Lifestyle,
224
+ sports, weather, general conversation are NOT kids.
225
+
226
+ AVAILABLE CATEGORIES
227
+ {taxonomy}
228
+
229
+ REFERENCE EXAMPLES
230
+ {examples}
231
+
232
+ Do not include any text outside the JSON object."""
233
+
234
+
235
+ def build_user_prompt(name: str, description: str, readme: str) -> str:
236
+ return (
237
+ f"App name: {name or '(unknown)'}\n"
238
+ f"Short description: {description or '(none)'}\n\n"
239
+ f"README excerpt:\n{readme or '(no README available)'}\n\n"
240
+ f"Return the JSON now."
241
+ )
242
+
243
+
244
+ # ──────────────────────────────────────────────────────────────────────
245
+ # README fetch + clean (mirrors server/categorize.js)
246
+ # ─────────────────────────────────────────────────────────────��────────
247
+
248
+ def fetch_readme(space_id: str) -> str:
249
+ url = f"https://huggingface.co/spaces/{space_id}/raw/main/README.md"
250
+ try:
251
+ with urllib.request.urlopen(url, timeout=10, context=_SSL_CTX) as r:
252
+ return r.read().decode("utf-8", errors="replace")
253
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
254
+ return ""
255
+
256
+
257
+ def clean_readme(raw: str) -> str:
258
+ if not raw:
259
+ return ""
260
+ txt = raw
261
+ txt = re.sub(r"^---\n[\s\S]*?\n---\n?", "", txt)
262
+ txt = re.sub(r"!\[[^\]]*\]\([^)]+\)", "", txt)
263
+ txt = re.sub(r"<img\b[^>]*>", "", txt, flags=re.IGNORECASE)
264
+ txt = re.sub(r"\[!\[[^\]]*\]\([^)]+\)\]\([^)]+\)", "", txt)
265
+ txt = re.sub(r"</?[a-zA-Z][^>]*>", "", txt)
266
+ txt = re.sub(r"\n{3,}", "\n\n", txt)
267
+ if len(txt) > README_MAX_CHARS:
268
+ cut = txt.rfind("\n\n", 0, README_MAX_CHARS)
269
+ if cut > README_MAX_CHARS // 2:
270
+ txt = txt[:cut]
271
+ else:
272
+ txt = txt[:README_MAX_CHARS]
273
+ return txt.strip()
274
+
275
+
276
+ # ──────────────────────────────────────────────────────────────────────
277
+ # LLM call
278
+ # ──────────────────────────────────────────────────────────────────────
279
+
280
+ def call_llm(hf_token: str, system: str, user: str) -> str | None:
281
+ body = json.dumps(
282
+ {
283
+ "model": MODEL,
284
+ "messages": [
285
+ {"role": "system", "content": system},
286
+ {"role": "user", "content": user},
287
+ ],
288
+ "temperature": TEMPERATURE,
289
+ "max_tokens": MAX_TOKENS,
290
+ "response_format": {"type": "json_object"},
291
+ }
292
+ ).encode("utf-8")
293
+ req = urllib.request.Request(
294
+ HF_INFERENCE_URL,
295
+ data=body,
296
+ headers={
297
+ "Authorization": f"Bearer {hf_token}",
298
+ "Content-Type": "application/json",
299
+ # Cloudflare in front of the router 403s the default
300
+ # "Python-urllib/x.y" UA. Any reasonable UA passes.
301
+ "User-Agent": "reachy-mini-prompt-eval/1.0",
302
+ },
303
+ method="POST",
304
+ )
305
+ try:
306
+ with urllib.request.urlopen(req, timeout=30, context=_SSL_CTX) as r:
307
+ data = json.loads(r.read().decode("utf-8"))
308
+ return data.get("choices", [{}])[0].get("message", {}).get("content")
309
+ except urllib.error.HTTPError as e:
310
+ detail = e.read().decode("utf-8", errors="replace")[:200]
311
+ print(f" ✗ LLM HTTP {e.code}: {detail}", file=sys.stderr)
312
+ return None
313
+ except Exception as e: # noqa: BLE001
314
+ print(f" ✗ LLM error: {e}", file=sys.stderr)
315
+ return None
316
+
317
+
318
+ def extract_json_obj(text: str) -> dict[str, Any] | None:
319
+ if not text:
320
+ return None
321
+ start = text.find("{")
322
+ if start == -1:
323
+ return None
324
+ depth = 0
325
+ for i in range(start, len(text)):
326
+ c = text[i]
327
+ if c == "{":
328
+ depth += 1
329
+ elif c == "}":
330
+ depth -= 1
331
+ if depth == 0:
332
+ try:
333
+ return json.loads(text[start : i + 1])
334
+ except json.JSONDecodeError:
335
+ return None
336
+ return None
337
+
338
+
339
+ def sanitize(raw: Any) -> list[str]:
340
+ if not isinstance(raw, list):
341
+ return []
342
+ out: list[str] = []
343
+ seen: set[str] = set()
344
+ for v in raw:
345
+ if not isinstance(v, str):
346
+ continue
347
+ slug = v.strip().lower()
348
+ if not slug or slug in seen or slug not in ALLOWED:
349
+ continue
350
+ seen.add(slug)
351
+ out.append(slug)
352
+ if len(out) >= MAX_CATEGORIES_PER_APP:
353
+ break
354
+ return out
355
+
356
+
357
+ # ──────────────────────────────────────────────────────────────────────
358
+ # Main
359
+ # ──────────────────────────────────────────────────────────────────────
360
+
361
+ def read_hf_token() -> str:
362
+ if os.environ.get("HF_TOKEN"):
363
+ return os.environ["HF_TOKEN"]
364
+ env_file = Path(__file__).resolve().parent.parent / ".env"
365
+ if env_file.exists():
366
+ for line in env_file.read_text().splitlines():
367
+ m = re.match(r"^\s*HF_TOKEN\s*=\s*(.*?)\s*$", line)
368
+ if m:
369
+ v = m.group(1).strip().strip('"').strip("'")
370
+ if v:
371
+ return v
372
+ raise SystemExit("HF_TOKEN not found in env or .env")
373
+
374
+
375
+ def fetch_live_classifications() -> list[dict[str, Any]]:
376
+ with urllib.request.urlopen(JS_APPS_URL, timeout=30, context=_SSL_CTX) as r:
377
+ return json.load(r)["apps"]
378
+
379
+
380
+ def main() -> int:
381
+ hf_token = read_hf_token()
382
+ apps = fetch_live_classifications()
383
+ print(f"Loaded {len(apps)} JS apps from prod.\n")
384
+
385
+ system = build_system_prompt()
386
+ print(f"System prompt: {len(system)} chars, {system.count(chr(10))} lines.\n")
387
+
388
+ results: list[dict[str, Any]] = []
389
+
390
+ for i, app in enumerate(apps, 1):
391
+ sid = app["id"]
392
+ name = app.get("name") or sid.split("/")[-1]
393
+ desc = (
394
+ app.get("description")
395
+ or (app.get("extra") or {}).get("cardData", {}).get("short_description")
396
+ or ""
397
+ )
398
+ old_cats = app.get("categories") or []
399
+
400
+ raw_readme = fetch_readme(sid)
401
+ readme = clean_readme(raw_readme)
402
+ user = build_user_prompt(name, desc, readme)
403
+
404
+ reply = call_llm(hf_token, system, user)
405
+ new_cats = sanitize((extract_json_obj(reply) or {}).get("categories"))
406
+
407
+ changed = set(old_cats) != set(new_cats)
408
+ marker = "Δ" if changed else " "
409
+ print(
410
+ f" {marker} ({i:>2}/{len(apps)}) {name[:36]:<37} "
411
+ f"old=[{', '.join(old_cats)}]"
412
+ + (f" → new=[{', '.join(new_cats)}]" if changed else "")
413
+ )
414
+
415
+ results.append(
416
+ {
417
+ "id": sid,
418
+ "name": name,
419
+ "old": old_cats,
420
+ "new": new_cats,
421
+ "changed": changed,
422
+ }
423
+ )
424
+ time.sleep(0.25)
425
+
426
+ print()
427
+ print("─" * 80)
428
+ print("DIFF (only changed entries)")
429
+ print("─" * 80)
430
+ for r in results:
431
+ if not r["changed"]:
432
+ continue
433
+ print(
434
+ f" {r['name'][:38]:<40} "
435
+ f"[{', '.join(r['old']) or '∅'}] → [{', '.join(r['new']) or '∅'}]"
436
+ )
437
+
438
+ changed_count = sum(1 for r in results if r["changed"])
439
+ print()
440
+ print(f"{changed_count}/{len(results)} entries changed.")
441
+ return 0
442
+
443
+
444
+ if __name__ == "__main__":
445
+ sys.exit(main())
server/categories.js CHANGED
@@ -22,7 +22,19 @@
22
  * the live one and recomputes stale ones on the next pass.
23
  */
24
 
25
- export const TAXONOMY_VERSION = 1;
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  /**
28
  * Canonical category list. Keep slugs short, kebab-case, and
@@ -39,67 +51,90 @@ export const CATEGORIES = [
39
  label: 'Music & Beats',
40
  emoji: '🎵',
41
  description:
42
- 'Apps where Reachy plays, mixes, generates, or reacts to music ' +
43
- '(DJ sets, beat-makers, blind-tests). NOT for apps that just ' +
44
- 'happen to use audio cues.',
 
45
  },
46
  {
47
  slug: 'dance',
48
  label: 'Dance & Motion',
49
  emoji: '💃',
50
  description:
51
- 'Apps centered on dance choreographies, motion replay, ' +
52
- 'kinetic shows, or recording/replaying robot movements.',
53
  },
54
  {
55
  slug: 'voice',
56
  label: 'Voice & Conversation',
57
  emoji: '🗣️',
58
  description:
59
- 'Apps where Reachy talks, listens, or holds a real-time voice ' +
60
  'conversation: TTS players, LLM-driven chat (OpenAI Realtime, ' +
61
- 'Claude, Perplexity, etc.), wake-word demos.',
 
62
  },
63
  {
64
  slug: 'storytelling',
65
  label: 'Stories',
66
  emoji: '📖',
67
  description:
68
- 'Apps that tell, generate, or guide narrative stories ' +
69
- '(interactive fiction, bedtime stories, narrated adventures).',
 
 
70
  },
71
  {
72
  slug: 'kids',
73
  label: 'For Kids',
74
  emoji: '🧒',
75
  description:
76
- 'Apps explicitly designed for children: encyclopedias, ' +
77
- 'kid-friendly stories, learning games, simple Q&A.',
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  },
79
  {
80
  slug: 'vision',
81
  label: 'Vision & Camera',
82
  emoji: '👁️',
83
  description:
84
- "Apps that consume Reachy's camera feed: face/hand tracking, " +
85
- 'image classification, mimicry, gesture detection.',
 
 
86
  },
87
  {
88
  slug: 'companion',
89
  label: 'Companion',
90
  emoji: '🤝',
91
  description:
92
- 'Apps positioned as life/emotional companions, mood support, ' +
93
- 'or friendly buddies that develop a personality over time.',
 
 
94
  },
95
  {
96
  slug: 'dev-tools',
97
  label: 'Dev & Demos',
98
  emoji: '🛠️',
99
  description:
100
- 'Technical demos, debugging tools, remote-control utilities, ' +
101
- 'minimal proof-of-concepts, and dev-only experiments meant to ' +
102
- 'showcase a single API or behaviour.',
 
 
103
  },
104
  ];
105
 
 
22
  * the live one and recomputes stale ones on the next pass.
23
  */
24
 
25
+ /**
26
+ * Bump this when the slug list OR the descriptions change in a way
27
+ * that affects the LLM output. The cache layer invalidates entries
28
+ * whose taxonomyVersion is older than this and reclassifies them on
29
+ * the next pass. We don't bump it for cosmetic edits (label / emoji)
30
+ * since those don't reach the LLM.
31
+ *
32
+ * History:
33
+ * - v1: initial 8-slug taxonomy.
34
+ * - v2: added `games`, tightened `kids` + `dev-tools` descriptions,
35
+ * switched the prompt to a DECISION ALGORITHM with few-shot.
36
+ */
37
+ export const TAXONOMY_VERSION = 2;
38
 
39
  /**
40
  * Canonical category list. Keep slugs short, kebab-case, and
 
51
  label: 'Music & Beats',
52
  emoji: '🎵',
53
  description:
54
+ 'Music creation, playback, beats, songs, DJ mixing, instruments, ' +
55
+ 'blind-test music games. Requires actual music (rhythm / melody / ' +
56
+ 'song). Arbitrary audio (Morse code, alarms, TTS, sound effects) ' +
57
+ 'is NOT music.',
58
  },
59
  {
60
  slug: 'dance',
61
  label: 'Dance & Motion',
62
  emoji: '💃',
63
  description:
64
+ 'Dance choreographies, motion replay, kinetic shows, ' +
65
+ 'recording/replaying robot movements, dance parties.',
66
  },
67
  {
68
  slug: 'voice',
69
  label: 'Voice & Conversation',
70
  emoji: '🗣️',
71
  description:
72
+ 'Reachy talks, listens, or holds a real-time voice ' +
73
  'conversation: TTS players, LLM-driven chat (OpenAI Realtime, ' +
74
+ 'Claude, Perplexity), wake-word demos, daily reports / news / ' +
75
+ 'weather read aloud.',
76
  },
77
  {
78
  slug: 'storytelling',
79
  label: 'Stories',
80
  emoji: '📖',
81
  description:
82
+ 'Narrative stories WITH plot and characters: interactive ' +
83
+ 'fiction, bedtime tales, audio adventures, choose-your-own-' +
84
+ 'adventure. NOT for daily reports, news, weather, or Q&A ' +
85
+ '(those are `voice`).',
86
  },
87
  {
88
  slug: 'kids',
89
  label: 'For Kids',
90
  emoji: '🧒',
91
  description:
92
+ 'Apps that EXPLICITLY target children: the words kids / ' +
93
+ "children / 'for curious minds' / bedtime / 'learning for kids' " +
94
+ 'must appear in the name or description, OR the app must be ' +
95
+ 'obviously kid-targeted. Combines with `storytelling`, `voice`, ' +
96
+ 'or `games`. Lifestyle, sports, weather, generic personality / ' +
97
+ 'narration / fun framings are NOT kids.',
98
+ },
99
+ {
100
+ slug: 'games',
101
+ label: 'Games & Play',
102
+ emoji: '🎮',
103
+ description:
104
+ 'Apps with a play loop: scores, rounds, win/lose conditions, ' +
105
+ 'quizzes, puzzles, sports simulations, dice/oracles (magic ' +
106
+ '8-ball), arcade-style mini-games.',
107
  },
108
  {
109
  slug: 'vision',
110
  label: 'Vision & Camera',
111
  emoji: '👁️',
112
  description:
113
+ "Apps where Reachy's camera DRIVES behaviour: face/hand/pose " +
114
+ 'tracking, image classification, gesture detection, visual ' +
115
+ 'mimicry. Merely streaming or displaying the camera feed ' +
116
+ '(WebRTC demos, remote-control viewers) is NOT vision.',
117
  },
118
  {
119
  slug: 'companion',
120
  label: 'Companion',
121
  emoji: '🤝',
122
  description:
123
+ 'Apps with an EXPLICIT emotional / personality / buddy framing ' +
124
+ 'in the name or description (companion, buddy, friend, mood, ' +
125
+ 'emotional, personality, pet, Tamagotchi-like, "alive", ' +
126
+ '"life companion"). Being friendly is not enough.',
127
  },
128
  {
129
  slug: 'dev-tools',
130
  label: 'Dev & Demos',
131
  emoji: '🛠️',
132
  description:
133
+ 'RESERVED slug - see DECISION ALGORITHM step 1 in the prompt. ' +
134
+ 'Use ONLY for pure technical artefacts (debug utilities, SDK ' +
135
+ 'probes, minimal protocol demos, dev-only test spaces) with no ' +
136
+ 'end-user experience. When used, it is the SOLE category - ' +
137
+ 'never combined with another slug.',
138
  },
139
  ];
140
 
server/categorize.js CHANGED
@@ -125,41 +125,156 @@ export function cleanReadme(raw) {
125
  }
126
 
127
  /**
128
- * Build the chat messages handed to the LLM. The system prompt
129
- * pins the closed taxonomy + the output shape; the user prompt
130
- * is the app context.
131
  *
132
- * We deliberately spell out the JSON-only constraint twice
133
- * (system + user) because mid-tier 8B models tend to drift into
134
- * conversational replies on classification tasks otherwise.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  */
136
  function buildMessages({ name, description, readme }) {
137
  const taxonomy = buildLlmCategoryList();
138
- const system = [
139
- 'You classify a Reachy Mini robot app into a closed list of categories.',
140
- '',
141
- 'Output ONLY a single JSON object with this exact shape:',
142
- '{"categories": ["slug1", "slug2"]}',
143
- '',
144
- `Pick 1 to ${MAX_CATEGORIES_PER_APP} categories from the list below, ` +
145
- 'ordered from most to least relevant. Use the EXACT slug.',
146
- 'If none of the categories clearly fits, output {"categories": []}.',
147
- '',
148
- 'Available categories:',
149
- taxonomy,
150
- '',
151
- 'Do not include any text outside the JSON object. No prose, no code fences.',
152
- ].join('\n');
153
-
154
- const user = [
155
- `App name: ${name || '(unknown)'}`,
156
- `Short description: ${description || '(none)'}`,
157
- '',
158
- 'README excerpt:',
159
- readme || '(no README available)',
160
- '',
161
- 'Return the JSON now.',
162
- ].join('\n');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  return [
165
  { role: 'system', content: system },
 
125
  }
126
 
127
  /**
128
+ * Few-shot examples woven into the system prompt.
 
 
129
  *
130
+ * Each entry encodes a pitfall the v1 prompt fell into during the
131
+ * 24-app eval (see `scripts/evaluate-prompt-v2.py`). Keep this list
132
+ * tight - past ~10 examples the model starts pattern-matching
133
+ * literally on the example names rather than applying the rules.
134
+ *
135
+ * Format: [name, description, expected_slugs, brief_justification]
136
+ */
137
+ const FEW_SHOT_EXAMPLES = [
138
+ [
139
+ 'Reachy Morse',
140
+ "Send Morse code through Reachy's speaker.",
141
+ ['dev-tools'],
142
+ '(STEP 1 veto: pure technical artefact. NOT music.)',
143
+ ],
144
+ [
145
+ 'WebRTC Demo',
146
+ 'Minimal WebRTC connection between Reachy and the browser.',
147
+ ['dev-tools'],
148
+ '(STEP 1 veto: protocol demo. NOT vision.)',
149
+ ],
150
+ [
151
+ 'TTS Reachy Mini',
152
+ "Browser TTS that plays out of Reachy Mini's speaker.",
153
+ ['voice'],
154
+ '(USER-FACING speech output is voice, NOT dev-tools.)',
155
+ ],
156
+ [
157
+ 'Reachy Mochi - Emotional Companion',
158
+ 'Your pocket buddy that develops a mood and personality over time.',
159
+ ['companion'],
160
+ '(explicit emotional/companion framing)',
161
+ ],
162
+ [
163
+ 'Reachy Alive',
164
+ '(README empty; name suggests autonomy and life-like presence)',
165
+ ['companion'],
166
+ "(USE THE NAME when the README is empty; 'alive' = companion-like)",
167
+ ],
168
+ [
169
+ 'Daily Surf Report',
170
+ "Reachy reads today's surf report out loud.",
171
+ ['voice'],
172
+ '(NOT storytelling - a report has no narrative arc. ' +
173
+ 'NOT kids - surfing/sports are not kid-targeted.)',
174
+ ],
175
+ [
176
+ 'Music Quiz',
177
+ 'Play a blind test music game with a dancing Reachy.',
178
+ ['music', 'games', 'dance'],
179
+ '(multi-label: three slugs truly co-apply, ordered by relevance)',
180
+ ],
181
+ [
182
+ 'Mime Bot',
183
+ 'Reachy mimics your face live from your webcam.',
184
+ ['vision'],
185
+ '(NOT companion - mimicry is visual, no emotional framing.)',
186
+ ],
187
+ ];
188
+
189
+ function renderFewShot() {
190
+ return FEW_SHOT_EXAMPLES.map(([name, desc, slugs, hint]) => {
191
+ const slugsJson = JSON.stringify(slugs);
192
+ return (
193
+ ` - ${JSON.stringify(name)}: ${JSON.stringify(desc)}\n` +
194
+ ` → {"categories": ${slugsJson}} ${hint}`
195
+ );
196
+ }).join('\n');
197
+ }
198
+
199
+ /**
200
+ * Build the chat messages handed to the LLM.
201
+ *
202
+ * The system prompt is structured as a 3-step DECISION ALGORITHM
203
+ * rather than a flat list of rules, because the 8B-class model we
204
+ * use (Llama-3.1-8B-Instruct) follows imperative procedures more
205
+ * reliably than soft constraints. The `dev-tools` veto in STEP 1
206
+ * is what stops the model from silently combining it with other
207
+ * slugs on user-facing apps.
208
+ *
209
+ * The few-shot examples below the rules cover the v1 pitfalls
210
+ * (companion hallucinations, music-on-audio, kids-on-personas,
211
+ * storytelling-on-reports). Six is the sweet spot - more starts
212
+ * over-fitting on example wording.
213
  */
214
  function buildMessages({ name, description, readme }) {
215
  const taxonomy = buildLlmCategoryList();
216
+ const examples = renderFewShot();
217
+ const system = `You classify a Reachy Mini robot app into a CLOSED list of categories.
218
+
219
+ OUTPUT FORMAT
220
+ Return ONLY a single JSON object: {"categories": ["slug1", "slug2"]}.
221
+ Pick 1 to ${MAX_CATEGORIES_PER_APP} slugs, ordered from most to least relevant.
222
+ Use the EXACT slug. No prose, no code fences, no commentary outside the JSON.
223
+
224
+ DECISION ALGORITHM (apply in order)
225
+
226
+ STEP 1 - \`dev-tools\` veto
227
+ Is this app a PURE technical artefact with no user-facing experience
228
+ beyond "here is how the SDK / API works"?
229
+ Examples that pass the veto: WebRTC demo, SDK probe, debug utility,
230
+ raw remote-control interface, dev-only test space.
231
+ Examples that DO NOT pass the veto (they are user-facing apps):
232
+ TTS players, voice chat, music apps, storytelling, companions -
233
+ even when the README is dev-heavy.
234
+ - YES -> return {"categories": ["dev-tools"]} and STOP. Never combine.
235
+ - NO -> continue to STEP 2.
236
+
237
+ STEP 2 - Pick 1 to ${MAX_CATEGORIES_PER_APP} user-facing slugs from the
238
+ list below. Choose the MOST SPECIFIC categories. Order from most to
239
+ least relevant. Multi-label is encouraged when two categories truly
240
+ co-apply (e.g. music-and-dance, kids storytelling, vision game).
241
+ If the README is empty or very sparse, USE THE NAME AND DESCRIPTION
242
+ as the primary signal - do not bail to an empty list just because the
243
+ README is thin.
244
+
245
+ STEP 3 - Strict slug rules (each must hold, or DO NOT use the slug)
246
+ - \`companion\`: requires EXPLICIT emotional / personality / buddy
247
+ framing (companion, buddy, friend, mood, emotional, personality,
248
+ pet, Tamagotchi-like, "alive", "life companion"). Being friendly is
249
+ not enough.
250
+ - \`music\`: requires actual music - rhythm, melody, songs, beats, DJ
251
+ sets, instruments, music quizzes. Arbitrary audio (Morse, alarms,
252
+ TTS, sound effects) is NOT music.
253
+ - \`vision\`: requires the camera to DRIVE behaviour (tracking,
254
+ classification, mimicry). Merely streaming or displaying the camera
255
+ (WebRTC demos, remote-control viewers) is NOT vision.
256
+ - \`storytelling\`: requires a narrative ARC - plot, characters, scenes.
257
+ Daily reports, news, weather, Q&A are NOT storytelling (they are
258
+ \`voice\`).
259
+ - \`games\`: requires a play loop - score, rounds, win/lose, puzzles,
260
+ quizzes, dice/oracles, sports simulations.
261
+ - \`kids\`: requires kid-targeted framing (kids/children/curious minds/
262
+ bedtime/learning for kids) in the name or description. Lifestyle,
263
+ sports, weather, general conversation are NOT kids.
264
+
265
+ AVAILABLE CATEGORIES
266
+ ${taxonomy}
267
+
268
+ REFERENCE EXAMPLES
269
+ ${examples}
270
+
271
+ Do not include any text outside the JSON object.`;
272
+
273
+ const user =
274
+ `App name: ${name || '(unknown)'}\n` +
275
+ `Short description: ${description || '(none)'}\n\n` +
276
+ `README excerpt:\n${readme || '(no README available)'}\n\n` +
277
+ 'Return the JSON now.';
278
 
279
  return [
280
  { role: 'system', content: system },