sisyo 1.6.0 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -144,7 +144,7 @@ Optional best-practice guides that Claude loads on demand:
144
144
  | `terraform-best-practices` | Terraform/AWS: never auto-apply, cost confirm, plan summary, module layout, IAM/SGR/secrets rules |
145
145
  | `fastapi-best-practices` | FastAPI backends, REST APIs, Python web services |
146
146
  | `react-page-oriented` | React/Next.js pages, component structure |
147
- | `gemini-integration` | Google Gemini API: model roles via config keys, 3.x request rules, streaming chat + tools, Live voice (ephemeral token, sync tool calls), embeddings/rerank, JSON mode, grounding, PDF, TTS, troubleshooting |
147
+ | `gemini-integration` | Google Gemini API: model roles via config keys, 3.x request rules, streaming chat + tools, Live voice (ephemeral token, gemini-3.8-live async tools / 3.1 sync), structured tool results, embeddings/rerank, JSON mode, grounding, PDF, TTS, troubleshooting |
148
148
 
149
149
  ## After install
150
150
 
@@ -0,0 +1,71 @@
1
+ {
2
+ ".claude/rules/docs.md": [
3
+ "1fc7e7ee81314cc57313919e3dcbd61c1c9abf271cb2728987a4650626c55cf2",
4
+ "2b89b91bdcee96353280b6f505be6c0909975d0aab8f5f4726a504b3c1fcbc05",
5
+ "e71d422d61809dbd3e1e9c1ed4b700bc145928265538d94974e8536fe99fa5dc"
6
+ ],
7
+ ".claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md": [
8
+ "7f4564de67ec06137b27066d965b2322d611653f1fd7137fcffe93154ca3f467"
9
+ ],
10
+ ".claude/skills/fastapi-best-practices/DATABASE.md": [
11
+ "800602caae2350f09a9438b0e1ff7fb8cd7b2bbc32f427ef58477e218ffb6fda"
12
+ ],
13
+ ".claude/skills/fastapi-best-practices/DEPENDENCIES.md": [
14
+ "411ec97878b94378229f28805a94a258af96557204439e12df6db0e6f82f0235"
15
+ ],
16
+ ".claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md": [
17
+ "66158e46de6d48125ddc9e1396a6fc70f361f29e12aebbcc20231bf51d70e813"
18
+ ],
19
+ ".claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md": [
20
+ "833ac269f41c3e5d02ae1c27619a44a782f6f79d5b0d0f42d8ecb14bdec444af"
21
+ ],
22
+ ".claude/skills/fastapi-best-practices/SKILL.md": [
23
+ "6d0424f4c7c8782cac6a1ffeed47d7187f92469e6c92fa76a499f275f571dfb9"
24
+ ],
25
+ ".claude/skills/gemini-integration/GENERATE.md": [
26
+ "422c523decaec584f7059f8b31e288b358dfde268da427afeeeb265b8a2e8050"
27
+ ],
28
+ ".claude/skills/gemini-integration/LIVE-VOICE.md": [
29
+ "2b6639113402482608ed376ad908ae54ba2d7dfe9a2817fd169d8a766e49ed9e",
30
+ "50f6d7f89ae59ed95c55b6d1d1f31bf80554ed6e6458444c76c2a2aec9f75ec3",
31
+ "5f2e40a1bad5aedc7848a52e14da67573f3e1c1ca4aec84de36c50f29719d606",
32
+ "90a6530dacb52cfc7bdaed379df70ece3e5e71ee7b175841330bbfb8f63d2976"
33
+ ],
34
+ ".claude/skills/gemini-integration/RAG-EMBEDDING.md": [
35
+ "5404eb9469add0af8956fe1803b451d3b9726607739ef9f61058777d0f89bca6",
36
+ "6ae84870fb0e3e1c8bc3e48eacb82e4e90125f3b5113e0d8f574caaa57341fda"
37
+ ],
38
+ ".claude/skills/gemini-integration/SKILL.md": [
39
+ "345d6aba2a3c9f0dcf62c8e4b3a11cae531637b34d0b934df206e40876f0d2b1",
40
+ "c24075202b5154a9c1821034af8cc3da8dd895ae0fba0d908f35fe2a11070532",
41
+ "f5c298b3013004125b458db7c9f5971cc047e9d57c02992edc3faed7c7b3f21f"
42
+ ],
43
+ ".claude/skills/gemini-integration/TEXT-CHAT.md": [
44
+ "165c30a0e85f9dcbb9889b1d20dc5ebd54082b05a07d646699dada3c80b72417"
45
+ ],
46
+ ".claude/skills/gemini-integration/TROUBLESHOOTING.md": [
47
+ "3659f0d83782da3ab55921d5bdce5222d531031b4bcb51f68db6dc80b6d120eb",
48
+ "36d519a3754a81862b3c1c080c8fcf16635820d3f7ef3f09625fc1a7195d7266",
49
+ "8e24e24ee5915908c204c42b094c82727bac7fb4214d54a7b30cb129ad781a6e",
50
+ "f8f77b65bbe86dc89408b8372685acf59774df93e4fd23f3563df0f55be07b8c"
51
+ ],
52
+ ".claude/skills/html-docs/SKILL.md": [
53
+ "8414e0166d4403fff509302f2973a8765441529584d710249eb1bf887e89caf2",
54
+ "a307853ca9bad1e0335cea6c477400048e2d17fcecaedd79b5b58b481666cbdf"
55
+ ],
56
+ ".claude/skills/react-page-oriented/SKILL.md": [
57
+ "dd57426f6be595b65b263b754e2c8c9cabce9e3ce332e80cbb1ddcebfab89e81"
58
+ ],
59
+ ".claude/skills/react-page-oriented/triggers.md": [
60
+ "489db92a891306ab76093c2d41681f3bff1a8343329179ca913f87405c661aaf"
61
+ ],
62
+ ".claude/skills/terraform-best-practices/SKILL.md": [
63
+ "4cd2cbf59c8d8755bf1b1c0f12553feb1ca7258ce44e5e91cf6baee3f0e23149",
64
+ "85eee170ef76a0d17ed7f44037cf4421eb879b74dce4fd452066f59c275d9616"
65
+ ],
66
+ ".claude/skills/vibe-docs/SKILL.md": [
67
+ "5bf3ef21df2315575479a610a15f935010673e74de3523c888e74a6c3f78b105",
68
+ "ba3f7176b4ae7088b0ebbfa08bfe8b06729bab6acaddb9b489a8a46233f62fc6",
69
+ "db40c330b6b19b5b78f8a28c6611d6db917ea225bbc316fd8fb5e881331e7ac5"
70
+ ]
71
+ }
package/bin/sisyo.js CHANGED
@@ -50,6 +50,12 @@ function sha256(buf) {
50
50
  }
51
51
  function hashFile(p) { return sha256(fs.readFileSync(p)); }
52
52
 
53
+ // Hashes of every version of each managed file sisyo has ever shipped (from git history).
54
+ // Lets an install that predates the manifest (< v1.6) be recognised as untouched.
55
+ function readKnownHashes() {
56
+ try { return require(path.join(__dirname, "known-hashes.json")); } catch { return {}; }
57
+ }
58
+
53
59
  function readManifest(target) {
54
60
  const p = path.join(target, MANIFEST_REL);
55
61
  if (!fs.existsSync(p)) return null;
@@ -94,7 +100,7 @@ function ensureClaudeMdImport(target, dryRun) {
94
100
  }
95
101
  }
96
102
 
97
- function fillDates(target) {
103
+ function fillDates(target, onlyRels) {
98
104
  const today = new Date().toISOString().split("T")[0];
99
105
  const files = [
100
106
  "docs/MAP.md",
@@ -103,6 +109,7 @@ function fillDates(target) {
103
109
  "docs/99_progress/features.md",
104
110
  ];
105
111
  for (const rel of files) {
112
+ if (!onlyRels.has(rel)) continue; // never rewrite docs that already existed
106
113
  const p = path.join(target, rel);
107
114
  if (!fs.existsSync(p)) continue;
108
115
  const content = fs.readFileSync(p, "utf8");
@@ -150,12 +157,14 @@ function main() {
150
157
  const prevFiles = manifest ? manifest.files : {};
151
158
  const nextFiles = {};
152
159
  const conflicts = [];
160
+ const known = readKnownHashes();
161
+ const addedRels = new Set();
153
162
  let updated = 0, added = 0, unchanged = 0;
154
163
 
155
164
  if (updateMode && manifest) info(`installed: v${manifest.version} → v${PKG.version}`);
156
165
  if (updateMode && !manifest) {
157
- info("no manifest found (installed before v1.6). Files that differ from the new");
158
- info("templates are treated as locally modified — review *.sisyo-new or use --force.");
166
+ info("no manifest found (installed before v1.6). Files identical to an older sisyo");
167
+ info("release are updated; anything else is treated as locally modified.");
159
168
  }
160
169
 
161
170
  const templates = listTemplateFiles(templatesDir);
@@ -173,6 +182,7 @@ function main() {
173
182
  }
174
183
  if (managed) nextFiles[rel] = srcHash;
175
184
  ok(rel);
185
+ addedRels.add(rel);
176
186
  added++;
177
187
  continue;
178
188
  }
@@ -198,7 +208,11 @@ function main() {
198
208
  continue;
199
209
  }
200
210
 
201
- const pristine = prevFiles[rel] !== undefined && prevFiles[rel] === curHash;
211
+ // Untouched = identical to what the manifest says sisyo installed, or (no manifest
212
+ // entry, i.e. installed before v1.6) identical to some version sisyo once shipped.
213
+ const pristine = prevFiles[rel] !== undefined
214
+ ? prevFiles[rel] === curHash
215
+ : (known[rel] || []).includes(curHash);
202
216
  if (pristine || force) {
203
217
  if (!dryRun) {
204
218
  fs.writeFileSync(dest, srcBuf);
@@ -238,7 +252,7 @@ function main() {
238
252
  }
239
253
 
240
254
  ensureClaudeMdImport(target, dryRun);
241
- if (!updateMode && !dryRun) fillDates(target);
255
+ if (!dryRun) fillDates(target, addedRels);
242
256
  ensureGitignore(target, dryRun);
243
257
  if (!dryRun) writeManifest(target, nextFiles);
244
258
 
package/package.json CHANGED
@@ -1,26 +1,30 @@
1
- {
2
- "name": "sisyo",
3
- "version": "1.6.0",
4
- "description": "Smart documentation system for vibe coding with Claude Code. Token-efficient MAP.md routing.",
5
- "bin": {
6
- "sisyo": "./bin/sisyo.js"
7
- },
8
- "files": [
9
- "bin/",
10
- "templates/"
11
- ],
12
- "keywords": [
13
- "claude-code",
14
- "vibe-coding",
15
- "documentation",
16
- "ai-coding",
17
- "developer-tools",
18
- "sisyo"
19
- ],
20
- "author": "HoangThang <blog.thangchiba.com>",
21
- "homepage": "https://blog.thangchiba.com",
22
- "license": "MIT",
23
- "engines": {
24
- "node": ">=16"
25
- }
26
- }
1
+ {
2
+ "name": "sisyo",
3
+ "version": "1.6.5",
4
+ "description": "Smart documentation system for vibe coding with Claude Code. Token-efficient MAP.md routing.",
5
+ "bin": {
6
+ "sisyo": "./bin/sisyo.js"
7
+ },
8
+ "scripts": {
9
+ "hashes": "node scripts/gen-known-hashes.js",
10
+ "prepublishOnly": "node scripts/gen-known-hashes.js"
11
+ },
12
+ "files": [
13
+ "bin/",
14
+ "templates/"
15
+ ],
16
+ "keywords": [
17
+ "claude-code",
18
+ "vibe-coding",
19
+ "documentation",
20
+ "ai-coding",
21
+ "developer-tools",
22
+ "sisyo"
23
+ ],
24
+ "author": "HoangThang <blog.thangchiba.com>",
25
+ "homepage": "https://blog.thangchiba.com",
26
+ "license": "MIT",
27
+ "engines": {
28
+ "node": ">=16"
29
+ }
30
+ }
@@ -6,28 +6,67 @@ ephemeral token; tools are still executed by the backend.
6
6
  ```
7
7
  FE POST /api/live/token?lang= → BE: validate agent → client.auth_tokens.create() → {token, model, voice_name, session_id}
8
8
  FE ai.live.connect({model, config, callbacks}) (apiKey = token, apiVersion v1alpha)
9
- FE mic PCM 16 kHz → sendRealtimeInput({ audio })
9
+ FE mic PCM 16 kHz, 20–40 ms chunks → sendRealtimeInput({ audio })
10
10
  BE→FE audio PCM 24 kHz in serverContent.modelTurn.parts[].inlineData
11
11
  FE toolCall → POST /api/tools/execute → sendToolResponse({ functionResponses })
12
12
  ```
13
13
 
14
+ ## Model families — branch on the family, not on one version string
15
+
16
+ | Family | Model id | Tools | Thinking | Notes |
17
+ |---|---|---|---|---|
18
+ | **3.8** (default) | `gemini-3.8-live` | `NON_BLOCKING` by default, `BLOCKING` per declaration; scheduling `WHEN_IDLE` (default) / `INTERRUPT` / `SILENT` | **none** — omit `thinking_config` | proactive audio always on (`proactive_audio: false` → error), affective dialog removed; a `BLOCKING` call the user talks over is auto-cancelled |
19
+ | 3.1 (legacy preview) | `gemini-3.1-flash-live-preview` | sync (blocking) only | `thinking_level: "minimal"` | rollback target |
20
+ | 2.5 | `gemini-2.5-flash-native-audio-preview-12-2025` | blocking by default, `NON_BLOCKING` opt-in | `thinking_budget` | text via `sendClientContent`; access limited since 2026-09-18 |
21
+
22
+ `gemini-3.8-live-extended-thinking` is **not** a drop-in: async-only tools (no `BLOCKING`, no
23
+ scheduling), `thinking_level` `low | medium | high` (no `minimal`), and `turnComplete` no longer
24
+ means idle — read `interaction_status` (`@google/genai` ≥ 2.17).
25
+
26
+ **Voice agents with an open mic: declare every tool `BLOCKING` on 3.8.** Async
27
+ (`NON_BLOCKING`) searches were tried in production and dropped: the model's filler speech was
28
+ said only sometimes, leaked back into the mic as "user speech", the server then cancelled the
29
+ pending call (`toolCallCancellation`) and some turns never got an answer. Blocking = silent
30
+ until the result is in, then always an answer; show a "fetching data" state in the UI instead.
31
+
32
+ ```python
33
+ def _live_family(model: str) -> str:
34
+ for family in ("2.5", "3.1"):
35
+ if family in model:
36
+ return family
37
+ return "3.8" # gemini-3.8-live and anything newer
38
+ ```
39
+
40
+ Branching on `"3.1" in model` breaks the day the model id changes: a 3.8 id then falls into the
41
+ 2.5 path (`media` mic field, `sendClientContent`, no thinking config).
42
+
14
43
  ## Backend — mint the token
15
44
 
16
45
  ```python
17
46
  from google import genai
18
47
 
48
+ def live_tools(family: str) -> list[dict]:
49
+ decls = TOOL_DEFINITIONS
50
+ if family == "3.8":
51
+ # 3.8 defaults to NON_BLOCKING — force BLOCKING for every tool (see above).
52
+ # `behavior` is Live-only — never add it to the TOOL_DEFINITIONS text chat also sends.
53
+ decls = [{**d, "behavior": "BLOCKING"} for d in TOOL_DEFINITIONS]
54
+ return [{"function_declarations": decls}] if decls else []
55
+
19
56
  client = genai.Client(api_key=settings.GEMINI_API_KEY, http_options={"api_version": "v1alpha"})
57
+ family = _live_family(model)
20
58
 
21
59
  live_config = {
22
60
  "response_modalities": ["AUDIO"],
23
61
  "system_instruction": system_instruction, # same template as text chat + voice block
24
- "tools": [{"function_declarations": TOOL_DEFINITIONS}],
62
+ "tools": live_tools(family),
25
63
  "speech_config": {"voice_config": {"prebuilt_voice_config": {"voice_name": voice_name}}},
26
64
  "input_audio_transcription": {}, # server-side STT of the user → live transcript
27
65
  "output_audio_transcription": {}, # STT of the model's speech
28
66
  }
29
- if "3.1" in model:
30
- live_config["thinking_config"] = {"thinking_level": "minimal"} # 3.1 only; NOT thinking_budget
67
+ if family == "3.1":
68
+ live_config["thinking_config"] = {"thinking_level": "minimal"} # 3.8: NO thinking_config at all
69
+ # Never send proactivity / enable_affective_dialog: always on / removed on 3.8.
31
70
 
32
71
  token = client.auth_tokens.create(config={
33
72
  "uses": 1,
@@ -46,9 +85,12 @@ Rules:
46
85
  `LookupError` base class turned `KeyError`s from deeper code into bogus 404s).
47
86
  - Return `voice_name` — the FE **must** pass it again in `live.connect({ speechConfig })`; the
48
87
  server ignores the token's voice otherwise.
49
- - Wrap `auth_tokens.create` in try/except + `logger.exception` — a 402 (billing / Live not
50
- enabled) or unknown model id otherwise shows up as a silent "connecting…".
88
+ - Wrap `auth_tokens.create` in try/except + `logger.exception` (log model + family) — a 402
89
+ (billing / Live not enabled) or unknown model id otherwise shows up as a silent "connecting…".
51
90
  - No API key → return `{"token": "stub-token-no-api-key", ...}`.
91
+ - After changing the config, validate it offline against the SDK:
92
+ `types.CreateAuthTokenConfig.model_validate(cfg)` raises on unknown fields / enum values
93
+ without spending an API call.
52
94
 
53
95
  ## Frontend — connect
54
96
 
@@ -75,47 +117,85 @@ const session = await Promise.race([
75
117
  - `connect()` resolves only on WS `onopen` → always race it with a timeout so the UI never
76
118
  hangs on "connecting…".
77
119
  - Track a **phase** state (`idle | token | opening | open | recording | ending | ended | error`)
78
- and log it — a hang is then observable.
120
+ and log it — a hang is then observable. Log a build marker too (stale bundles look like hangs).
79
121
  - `onclose`: codes 1000/1005 are normal; anything else → surface `reason` as an error.
80
- 1007 = bad payload (see 2.5 → 3.1 table).
122
+ 1007 = bad payload (see the differences table).
81
123
 
82
124
  ## Audio
83
125
 
84
126
  | Direction | Format | API |
85
127
  |---|---|---|
86
- | Mic → model | PCM 16-bit mono, **16 kHz** | `sendRealtimeInput({ audio: pcmBlob })` |
128
+ | Mic → model | PCM 16-bit mono, **16 kHz**, **20–40 ms chunks** (≤ 100 ms) | `sendRealtimeInput({ audio: pcmBlob })` |
87
129
  | Model → speaker | PCM 16-bit mono, **24 kHz** | `serverContent.modelTurn.parts[].inlineData.data` |
88
130
 
131
+ - `ScriptProcessor` buffer 512 @ 16 kHz = 32 ms per chunk; 4096 = 256 ms held back per send.
89
132
  - Schedule output buffers back-to-back on the AudioContext clock (`nextStartTime`), don't play
90
133
  each chunk immediately.
91
- - `serverContent.interrupted` (barge-in) → reset `nextStartTime` and clear speaking state.
134
+ - `serverContent.interrupted` (barge-in) → **stop every scheduled buffer**, not just future ones.
135
+ The model streams faster than real time, so resetting `nextStartTime` alone leaves seconds of
136
+ queued speech talking over the customer; it leaks into the mic and garbles recognition,
137
+ language included (Google: "discard your client-side audio buffer"):
138
+
139
+ ```ts
140
+ const scheduled = new Set<AudioBufferSourceNode>()
141
+ let epoch = 0
142
+ // per audio part
143
+ const e = epoch
144
+ const buf = await decodeAudioData(data, ctx, 24000)
145
+ if (e !== epoch) continue // interrupted while decoding
146
+ const src = ctx.createBufferSource(); src.buffer = buf; src.connect(out)
147
+ src.onended = () => scheduled.delete(src); scheduled.add(src)
148
+ src.start(nextStartTime); nextStartTime += buf.duration
149
+ // on msg.serverContent.interrupted
150
+ epoch++; scheduled.forEach(s => { try { s.stop() } catch {} }); scheduled.clear()
151
+ nextStartTime = ctx.currentTime
152
+ ```
92
153
  - Route output through an `AnalyserNode` if the UI animates on loudness.
93
154
  - Transcripts: `serverContent.inputTranscription.text` / `outputTranscription.text` arrive as
94
155
  deltas; append to the current turn's bubble, reset indexes on `turnComplete`.
95
156
 
96
- ## Tool calls on 3.1 — synchronous
157
+ ## Tool calls
97
158
 
98
159
  ```ts
160
+ // Barge-in cancels in-flight calls — never answer a call the server already dropped.
161
+ for (const id of msg.toolCallCancellation?.ids || []) cancelled.add(id)
162
+
99
163
  if (msg.toolCall) {
100
- const functionResponses = await Promise.all((msg.toolCall.functionCalls || []).map(async fc => {
164
+ const functionResponses = (await Promise.all((msg.toolCall.functionCalls || []).map(async fc => {
101
165
  let response: Record<string, unknown>
102
166
  try { response = { result: await executeTool(fc.name, fc.args) } }
103
167
  catch (e) { response = { error: e instanceof Error ? e.message : 'Tool execution failed' } }
104
168
  return { id: fc.id || '', name: fc.name || '', response }
105
- }))
106
- session.sendToolResponse({ functionResponses }) // ALL calls, ONE message
169
+ }))).filter(fr => !cancelled.has(fr.id))
170
+ if (functionResponses.length) session.sendToolResponse({ functionResponses }) // ALL calls, ONE message
107
171
  }
108
172
  ```
109
173
 
110
- - The model is **silent until every call is answered** — a thrown tool must still respond.
111
- - Show a "thinking" indicator from `toolCall` until the next audio chunk arrives.
174
+ - **BLOCKING** (every tool — 3.1 has nothing else, declare it on 3.8): the model is **silent
175
+ until every call is answered** — a thrown tool must still respond, and the tool request needs
176
+ a timeout (e.g. 15 s → answer `{ error }`) or a hung backend silences the call for good.
177
+ - Show a "fetching data" state from `toolCall` until the next audio chunk — not a spoken
178
+ filler. Prompt: *"A brief pause while you search is expected — do not narrate that you are
179
+ searching."* Anything the model says before the call just leaks back into the open mic.
180
+ - While the tool round-trip runs, **stream silence instead of the mic** (zeroed PCM frames):
181
+ 3.8 auto-cancels a BLOCKING call when it hears "speech" — noise or echo included — and the
182
+ turn then ends with no answer.
183
+ - Prompt rule for 3.8: *"If a search finds nothing, say so instead of searching again with a
184
+ rephrased query. Never run more than two searches in a row without speaking to the customer."*
185
+ - `NON_BLOCKING` + `FunctionResponse.scheduling` (`WHEN_IDLE` default / `INTERRUPT` / `SILENT`)
186
+ only make sense without an open mic (text / push-to-talk UIs).
187
+ - Tool results are structured (`status`, `retryable`, `guidance`) — see `SKILL.md` §5.
188
+ - Keep the voice tool path fast (retrieve-only RAG profile, no LLM rerank) — the customer
189
+ hears silence for as long as it takes.
112
190
 
113
191
  ## end_conversation — hang up AFTER the farewell
114
192
 
115
- Tool calls are sync, so the farewell audio comes **after** your tool response. Do not close the
116
- socket inside the tool handler (that produced no farewell + a UI stuck on "Connecting…").
193
+ Keep `end_conversation` **BLOCKING** (like every tool): the farewell audio then comes
194
+ **after** your tool response. Do not close the socket inside the tool handler (that produced no
195
+ farewell + a UI stuck on "Connecting…").
117
196
 
118
- 1. On `end_conversation`: set `ending = true`, phase `ending`, **stop the mic**, start a 12 s
197
+ 1. On `end_conversation`: set `ending = true`, phase `ending`, **stop the mic before the tool
198
+ round-trip** (on 3.8 a customer still talking auto-cancels the BLOCKING call), start a 12 s
119
199
  grace timer.
120
200
  2. Send the tool response normally.
121
201
  3. On `turnComplete` while `ending`: wait for the audio queue to drain (+400 ms) → disconnect →
@@ -128,26 +208,32 @@ end_conversation in that same turn."*
128
208
  ## Session language + greeting
129
209
 
130
210
  - Widget passes `?lang=` → token endpoint → appended `## Voice Mode` block in the system
131
- prompt: default language, greeting rule, control-turn rule, farewell rule.
211
+ prompt: default language, greeting rule, control-turn rule, tool-wait rule, farewell rule.
212
+ - Reply language: with `?lang=`, use Google's recommended line `RESPOND IN {LANG}. YOU MUST
213
+ RESPOND UNMISTAKABLY IN {LANG}.` and allow a switch only on an explicit request or several
214
+ clear sentences. A "switch to the customer's language" rule flips languages whenever speech
215
+ overlapping a barge-in is misheard. Native-audio models take no language code — the prompt
216
+ is the only lever.
132
217
  - The FE's first turn is a control message `[Session start] … Greet them now in {lang}` — **not**
133
218
  the greeting text. Sending the greeting as a user turn made the model mirror its language.
219
+ Send it with `sendRealtimeInput({ text })` on 3.x; only 2.5 needs `sendClientContent`.
134
220
  - Tell the model the `[Session start]` turn is a control signal: never read it aloud, never
135
221
  mirror its language.
136
222
  - Per-language overrides live in `config.locales[lang]` merged over defaults by ONE resolver
137
223
  used by both the token endpoint and the public config endpoint.
138
224
 
139
- ## 2.5 → 3.1 Live differences (branch on `'3.1' in model`)
225
+ ## Differences 2.5 → 3.1 → 3.8
140
226
 
141
- | Item | 2.5 | 3.1 |
142
- |---|---|---|
143
- | Mic stream | `sendRealtimeInput({ media })` | `sendRealtimeInput({ audio })` — `media` → close 1007 |
144
- | Mid-session text | `sendClientContent` | `sendRealtimeInput({ text })` |
145
- | Latency tuning | `thinking_budget` | `thinking_config.thinking_level = "minimal"` |
146
- | Server events | 1 part / event | multiple parts / event → loop over all `parts` |
147
- | Function calling | async (NON_BLOCKING) possible | **sync only** |
148
- | Proactive audio / affective dialog | yes | not supported |
149
-
150
- Fallback: `GEMINI_LIVE_MODEL=gemini-2.5-flash-native-audio-preview-12-2025`.
227
+ | Item | 2.5 | 3.1 | 3.8 (default) |
228
+ |---|---|---|---|
229
+ | Mic stream | `sendRealtimeInput({ media })` | `{ audio }` — `media` → close 1007 | `{ audio }` |
230
+ | Mid-session text | `sendClientContent` | `sendRealtimeInput({ text })` | `sendRealtimeInput({ text })` |
231
+ | Latency tuning | `thinking_budget` | `thinking_level: "minimal"` | none — omit `thinking_config` |
232
+ | Server events | 1 part / event | multiple parts / event → loop over all `parts` | multiple parts / event |
233
+ | Function calling | blocking; `NON_BLOCKING` opt-in | **sync only** | `NON_BLOCKING` default — declare `BLOCKING` for voice |
234
+ | Proactive audio / affective dialog | opt-in (`v1beta`) | not supported | always on / removed — don't configure |
235
+
236
+ Fallback: `GEMINI_LIVE_MODEL=gemini-3.1-flash-live-preview`.
151
237
 
152
238
  ## Persisting the voice transcript
153
239
 
@@ -55,11 +55,14 @@ Ask the **chat** model (fast, cheap) to score candidates as JSON. Good up to ~20
55
55
  beyond that use a dedicated reranker.
56
56
 
57
57
  ```python
58
- _SYS = ("You are a relevance reranker. Given a user query and candidate passages, score each "
59
- "0.0–1.0 for relevance. Return ONLY valid JSON: {\"scores\": [{\"id\": \"...\", \"score\": 0.85}]}")
58
+ _SYS = ("You are a relevance reranker. Given a user query and numbered candidate passages, score "
59
+ "each 0.0–1.0 for relevance. Return ONLY valid JSON, using the passage numbers as ids: "
60
+ "{\"scores\": [{\"id\": 0, \"score\": 0.85}]}")
60
61
 
62
+ # Number the candidates — echoing a 36-char chunk UUID per candidate roughly triples the JSON
63
+ # the model must write, and output length dominates rerank latency.
61
64
  prompt = "\n".join([f"Query: {query}", "Candidates:"] +
62
- [f"- id: {c.id}\n text: {c.text[:600]}" for c in candidates])
65
+ [f"[{i}] {c.text[:600]}" for i, c in enumerate(candidates)])
63
66
 
64
67
  resp = client.models.generate_content(
65
68
  model=settings.GEMINI_CHAT_MODEL,
@@ -67,11 +70,18 @@ resp = client.models.generate_content(
67
70
  config={
68
71
  "system_instruction": _SYS,
69
72
  "response_mime_type": "application/json",
70
- "thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL},
73
+ "thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL}, # minimal on flash-lite
71
74
  },
72
75
  )
73
- scores = {s["id"]: float(s["score"]) for s in _parse_json(resp.text or "").get("scores", [])
74
- if isinstance(s, dict) and isinstance(s.get("id"), str)}
76
+ scores: dict[int, float] = {}
77
+ for s in _parse_json(resp.text or "").get("scores", []):
78
+ try:
79
+ i, sc = int(float(str(s["id"]).strip("[] "))), float(s["score"]) # 3, "3", "[3]"
80
+ except (TypeError, ValueError, KeyError, OverflowError):
81
+ continue
82
+ if 0 <= i < len(candidates):
83
+ scores[i] = sc
84
+ order = sorted(range(len(candidates)), key=lambda i: scores.get(i, 0.0), reverse=True) # stable
75
85
  ```
76
86
 
77
87
  Rules:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: gemini-integration
3
- description: "Google Gemini API integration rules (google-genai Python / @google/genai JS): model roles per use case (chat, generate, embedding, TTS, Live voice) via env config keys, singleton client, echo stub when no API key, Gemini 3.x request rules (thinking_level not thinking_budget, no temperature/top_p, FunctionResponse needs id+name, accumulate function calls across stream chunks, send all tool results in ONE message), server-side text chat with SSE streaming, client-side Live voice via ephemeral token (sync tool calls on 3.1, sendRealtimeInput audio, PCM 16k in / 24k out), embeddings (one text per call, Matryoshka dims, re-embed on model change), LLM reranker, JSON mode, google_search / url_context grounding, PDF extract, TTS. Triggers on any Gemini / genai / GEMINI_* code, voice chat, RAG embedding, or user saying 'gemini', 'live api', 'function calling'."
3
+ description: "Google Gemini API integration rules (google-genai Python / @google/genai JS): model roles per use case (chat, generate, embedding, TTS, Live voice) via env config keys, singleton client, echo stub when no API key, Gemini 3.x request rules (thinking_level not thinking_budget, no temperature/top_p, FunctionResponse needs id+name, accumulate function calls across stream chunks, send all tool results in ONE message), server-side text chat with SSE streaming, client-side Live voice via ephemeral token (gemini-3.8-live: declare tools BLOCKING for voice, no thinking_level; per-model-family setup; sendRealtimeInput audio, PCM 16k in / 24k out), structured tool results (status/retryable/guidance), embeddings (one text per call, Matryoshka dims, re-embed on model change), LLM reranker, JSON mode, google_search / url_context grounding, PDF extract, TTS. Triggers on any Gemini / genai / GEMINI_* code, voice chat, RAG embedding, or user saying 'gemini', 'live api', 'function calling'."
4
4
  license: MIT
5
5
  metadata:
6
6
  author: HoangThang
@@ -26,7 +26,7 @@ imports `google.genai` / `@google/genai` or reads a `GEMINI_*` setting.
26
26
  |---|---|
27
27
  | `TEXT-CHAT.md` | Server-side chat session, streaming to SSE, tool loop |
28
28
  | `GENERATE.md` | One-shot generate: JSON mode, google_search / url_context grounding, PDF extract, TTS |
29
- | `LIVE-VOICE.md` | Client-side voice via Live API: ephemeral token, WebSocket, audio, sync tool calls |
29
+ | `LIVE-VOICE.md` | Client-side voice via Live API: ephemeral token, WebSocket, audio, async (3.8) / sync (3.1) tool calls, 2.5 → 3.1 → 3.8 differences |
30
30
  | `RAG-EMBEDDING.md` | Embeddings for vector search + LLM reranker |
31
31
  | `TROUBLESHOOTING.md` | An error code or a hang you need to map to a cause |
32
32
 
@@ -41,8 +41,8 @@ roll back via `.env` without a deploy.
41
41
  | Agent / Q&A generation, PDF extract | `gemini-3.8-flash` | `GEMINI_GENERATE_MODEL` | `google-genai` (Python) |
42
42
  | TTS sample clips | `gemini-2.5-flash-preview-tts` | `GEMINI_TTS_MODEL` | `google-genai` (Python) |
43
43
  | Embedding (RAG) | `gemini-embedding-2` | `GEMINI_EMBEDDING_MODEL` | `google-genai` (Python) |
44
- | Voice chat (Live) | `gemini-3.1-flash-live-preview` | `GEMINI_LIVE_MODEL` | `@google/genai` (JS, browser) |
45
- | Chat thinking level | `low` | `GEMINI_CHAT_THINKING_LEVEL` | — |
44
+ | Voice chat (Live) | `gemini-3.8-live` | `GEMINI_LIVE_MODEL` | `@google/genai` (JS, browser) |
45
+ | Chat thinking level | `minimal` | `GEMINI_CHAT_THINKING_LEVEL` | — |
46
46
 
47
47
  - Cheap/fast model for anything on the interactive path (chat, rerank, summary).
48
48
  - Bigger model only for offline / admin generation and document extraction.
@@ -54,9 +54,9 @@ roll back via `.env` without a deploy.
54
54
  # config.py (pydantic-settings style)
55
55
  GEMINI_API_KEY: str = ""
56
56
  GEMINI_CHAT_MODEL: str = "gemini-3.5-flash-lite"
57
- GEMINI_CHAT_THINKING_LEVEL: str = "low" # low | medium | high (3.5+/3.8; minimal is 3.1-Live only)
57
+ GEMINI_CHAT_THINKING_LEVEL: str = "minimal" # 3.5 Flash-Lite default + fastest; 3.7/3.8 Flash reject it → "low"
58
58
  GEMINI_GENERATE_MODEL: str = "gemini-3.8-flash"
59
- GEMINI_LIVE_MODEL: str = "gemini-3.1-flash-live-preview"
59
+ GEMINI_LIVE_MODEL: str = "gemini-3.8-live" # rollback: gemini-3.1-flash-live-preview (sync tools)
60
60
  GEMINI_TTS_MODEL: str = "gemini-2.5-flash-preview-tts"
61
61
  GEMINI_EMBEDDING_MODEL: str = "gemini-embedding-2"
62
62
  EMBEDDING_DIM: int = 768
@@ -98,8 +98,10 @@ When `GEMINI_API_KEY` is empty the app must still boot and the UI must still be
98
98
  Apply to every `generate_content` / `chats.create` / `embed_content` on 3.5+ / 3.8:
99
99
 
100
100
  - **`thinking_budget` is NOT supported.** Use `thinking_config={"thinking_level": ...}`.
101
- 3.8 Flash rejects `thinking_level="minimal"` with 400 — use `low`. `minimal` is valid only
102
- on 3.1 Live. `medium` is noticeably slower for a support chat.
101
+ Levels differ per model: 3.5 Flash-Lite accepts `minimal` (its default, the fastest);
102
+ 3.7/3.8 Flash reject `minimal` with 400 — use `low` — and default to `medium`, which is
103
+ noticeably slower for a support chat. Live: 3.1 takes `thinking_level` (`minimal`),
104
+ `gemini-3.8-live` takes **no** `thinking_level` at all (omit `thinking_config`).
103
105
  - **Do NOT send** `temperature`, `top_p`, `top_k`, `candidate_count` — deprecated on 3.x.
104
106
  - Every `FunctionResponse` **must carry `id` + `name`**, or the next turn is rejected.
105
107
  - **Accumulate function calls across ALL stream chunks** — parallel calls can span chunks;
@@ -122,6 +124,12 @@ Apply to every `generate_content` / `chats.create` / `embed_content` on 3.5+ / 3
122
124
  after the farewell turn (see `LIVE-VOICE.md`).
123
125
  - A tool that throws must still answer with `{"error": "..."}` — a missing response makes the
124
126
  model wait forever.
127
+ - Return **structured** results, never `{}` / `None`: `status` (`ok` | `no_results` |
128
+ `invalid_argument` | `error`), plus `retryable` and a model-facing `guidance` sentence when
129
+ nothing usable came back. Gemini 3.8 Live re-queries with rephrased variations on an
130
+ unexplained empty result. Keep any `message` short if an admin UI shows it verbatim.
131
+ - `behavior` (`BLOCKING` / `NON_BLOCKING`) is a Live-only declaration field — add it while
132
+ building the Live token config, not to the shared `TOOL_DEFINITIONS` text chat also sends.
125
133
 
126
134
  ## 6. Security
127
135
 
@@ -7,8 +7,9 @@ defaults and deploy does not rewrite it. Verify via the token / health endpoint
7
7
 
8
8
  | Symptom | Cause | Fix |
9
9
  |---|---|---|
10
- | 400 mentioning `thinking_budget` | 3.5+/3.8 dropped it | `thinking_config={"thinking_level": "low"}` |
11
- | 400 `thinking_level=minimal` | Only 3.1 Live accepts `minimal` | Use `low` on 3.5+/3.8 |
10
+ | 400 mentioning `thinking_budget` | 3.5+/3.8 dropped it | `thinking_config={"thinking_level": ...}` |
11
+ | 400 `thinking_level=minimal` | 3.7/3.8 Flash (and 3.8 Live Extended Thinking) reject `minimal` | `low` there; 3.5 Flash-Lite and 3.1 Live accept `minimal` |
12
+ | Live setup rejected / 400 mentioning `thinking_level` on `gemini-3.8-live` | 3.8 Live has no `thinking_level` | Omit `thinking_config` for the 3.8 family |
12
13
  | 400 on `temperature` / `top_p` / `top_k` / `candidate_count` | Deprecated on 3.x | Remove them |
13
14
  | 400 "function response … id/name" on the next turn | A `FunctionResponse` without `id` + `name`, or a call left unanswered | Accumulate calls across chunks; answer every call; include id + name |
14
15
  | Multi-turn tool calls fail after a model bump | Old `google-genai` without thought signatures | `google-genai>=2.0.0` |
@@ -19,7 +20,8 @@ defaults and deploy does not rewrite it. Verify via the token / health endpoint
19
20
  |---|---|---|
20
21
  | Reply ignores earlier tool results | One `send_message_stream` per response | Send all responses as ONE `parts` list |
21
22
  | `chunk.text` raises / empty | Chunk carries only function calls | `_safe_get_text()` wrapper |
22
- | Chat got slower after bump | `thinking_level=medium` or generate model used on chat path | `low`; chat/rerank on flash-lite |
23
+ | Chat got slower after bump | `medium` (3.7/3.8 default), `low` pinned on 3.5 Flash-Lite (its default is `minimal`), or generate model on the chat path | `minimal` on 3.5 Flash-Lite; chat/rerank on flash-lite |
24
+ | LLM rerank takes seconds | Output JSON echoes a long chunk id per candidate | Number candidates `[0]…[n-1]`, map back by index (see `RAG-EMBEDDING.md`) |
23
25
  | `[Echo] …` replies in prod | `GEMINI_API_KEY` empty on that box | Set the key; echo is the stub mode |
24
26
  | Embeddings: N chunks → 1 vector | Passed a list to `contents` | Embed one text per call |
25
27
  | Search results nonsense after embedding model change | Vector space changed | Re-embed everything (`--recreate`) |
@@ -29,25 +31,37 @@ defaults and deploy does not rewrite it. Verify via the token / health endpoint
29
31
  | Symptom | Cause | Fix |
30
32
  |---|---|---|
31
33
  | "Connecting…" forever, no error | `connect()` never resolves; or stale FE bundle | 15 s timeout race; log a build marker on `connect()`; hard reload |
32
- | Socket closed **1007** right after mic start | `sendRealtimeInput({ media })` on 3.1 | Use `{ audio }` |
34
+ | Socket closed **1007** right after mic start | `sendRealtimeInput({ media })` on 3.1 | Use `{ audio }` (3.x docs only list `audio`) |
35
+ | 3.8 id behaves like 2.5 (1007, text ignored, no thinking) | Code branches on `"3.1" in model` | Branch on the model family (`2.5` / `3.1` / else 3.8) |
36
+ | Setup error mentioning `proactivity` / `enable_affective_dialog` on 3.8 | Always on / removed on 3.8 | Drop those keys |
33
37
  | Token endpoint 402 | Billing / Live API not enabled for the key | Enable in AI Studio; log exception on mint |
34
38
  | Token endpoint 404 "Agent not found" for a real agent | Router caught `LookupError` base (KeyError/IndexError inside) or stale negative cache | Catch a dedicated `AgentNotFound`; short negative-cache TTL; `ConsistentRead` |
35
39
  | Token endpoint 403 | `voice_enabled` false on agent or plan | Expected — hide the voice toggle in the UI |
36
40
  | Connected but silent | `AudioContext` suspended (not from a user gesture) | `await ctx.resume()` after creating it |
37
41
  | Wrong voice every other session | FE didn't pass `speechConfig` on `connect` | Pass `voice_name` from the token response |
38
- | Model goes silent after a tool call | Sync function calling; a tool threw and never answered | Respond `{ error }` for failed tools, all in one `sendToolResponse` |
42
+ | Model goes silent after a tool call | BLOCKING call (3.1, or `behavior: BLOCKING` on 3.8); a tool threw and never answered | Respond `{ error }` for failed tools, all in one `sendToolResponse` |
43
+ | 3.8 answers before the search result arrives / makes things up | Tools are `NON_BLOCKING` by default — the model keeps talking | Declare every tool `behavior: BLOCKING` |
44
+ | 3.8 ran the tool but never answered | NON_BLOCKING filler leaked into the mic → server cancelled the call; or noise/echo during a BLOCKING call → auto-cancel | Tools BLOCKING, no spoken filler, stream silence instead of the mic during the tool round-trip, request `echoCancellation` |
45
+ | 3.8 searches again and again with rephrased queries | Empty or unexplained tool result | Return `status: no_results`, `retryable: false`, `guidance`; prompt: "never more than two searches in a row" |
46
+ | Error / odd reply after answering a tool call the customer talked over | Server cancelled it (`toolCallCancellation.ids`) | Drop responses for cancelled ids |
47
+ | 3.8 call doesn't hang up after goodbye (grace timer fires) | Customer kept talking → the BLOCKING `end_conversation` call was auto-cancelled | Mute the mic before the tool round-trip |
39
48
  | No farewell, UI stuck after `end_conversation` | Disconnected inside the tool handler | Mute mic, send response, wait `turnComplete` + audio drain, then close |
40
49
  | Greets in the wrong language | Greeting text sent as a user turn → model mirrors it | Send a `[Session start]` control turn; put the greeting rule in the system prompt |
41
- | Only first audio part plays | 3.1 sends multiple parts per event | Loop over all `parts` |
42
- | Mid-session text ignored on 3.1 | Used `sendClientContent` | `sendRealtimeInput({ text })` |
50
+ | Only first audio part plays | 3.x sends multiple parts per event | Loop over all `parts` |
51
+ | AI keeps talking for seconds after the customer interrupts | `interrupted` only reset `nextStartTime`; buffers already scheduled keep playing (audio arrives faster than real time) | `stop()` every scheduled `AudioBufferSourceNode` on `interrupted`; drop chunks still decoding |
52
+ | Replies switch to the wrong language after a barge-in | Prompt rule "switch to the customer's language" + a misheard overlapping fragment | `RESPOND IN {LANG}. YOU MUST RESPOND UNMISTAKABLY IN {LANG}.`; switch only on an explicit request; stop playback on `interrupted` |
53
+ | Waiting filler sounds unnatural / only said sometimes | Model-spoken filler (and example phrases in the prompt get parroted) | Don't use one: BLOCKING tools + a "fetching data" UI state |
54
+ | Mid-session text ignored on 3.1 | Used `sendClientContent` | `sendRealtimeInput({ text })` (the documented text path on 3.x) |
43
55
  | Voice sample button slow / times out | TTS on demand | Pre-generate at startup, cache on S3, key by version |
44
56
 
45
57
  ## Rollback values
46
58
 
47
59
  | Key | Rollback |
48
60
  |---|---|
49
- | `GEMINI_CHAT_MODEL` | `gemini-3.1-flash-lite-preview` (`low` valid there too) |
50
- | `GEMINI_LIVE_MODEL` | `gemini-2.5-flash-native-audio-preview-12-2025` (async tools, `thinking_budget`, `media` field) |
61
+ | `GEMINI_CHAT_MODEL` | `gemini-3.1-flash-lite` (`minimal`/`low` valid there) — the `-preview` id was shut down 2026-05-25 |
62
+ | `GEMINI_CHAT_THINKING_LEVEL` | `low` (deeper but slower than `minimal`) |
63
+ | `GEMINI_LIVE_MODEL` | `gemini-3.1-flash-live-preview` (sync tools, `thinking_level=minimal`); last resort `gemini-2.5-flash-native-audio-preview-12-2025` (access limited since 2026-09-18) |
64
+ | `GEMINI_TTS_MODEL` | 2.5 TTS access limited since 2026-09-18 — successors `gemini-3.8-flash-lite-tts` / `gemini-3.8-flash-tts` |
51
65
  | `GEMINI_EMBEDDING_MODEL` | Previous model **plus** full re-embed — no hot rollback |
52
66
 
53
67
  Always record the rollback + the date of the bump in `docs/09_integrations/gemini.md`.
@@ -0,0 +1,149 @@
1
+ ---
2
+ name: typesafe-jev
3
+ license: MIT
4
+ description: >
5
+ Build AI-powered software with TypeSafe: small units of AI intelligence you
6
+ can use like programming primitives. Its System One models, including Jev,
7
+ turn natural language and application state into typed judgments and
8
+ probabilities that code can combine. Use when a feature needs programmable
9
+ common sense, when brainstorming what AI could make possible in an app, or
10
+ when an LLM prompt-and-parse step could become a structured decision.
11
+ Applications include routing, ranking, extraction, verification, and
12
+ interactive experiences; these are starting points, not the limits.
13
+ Read live docs and cookbooks to find useful patterns and discover new combinations.
14
+ ---
15
+
16
+ # Build with TypeSafe
17
+
18
+ TypeSafe makes units of AI intelligence usable like programming primitives: small
19
+ judgments you can compose into larger capabilities. Its **System One models** return
20
+ fast, focused judgments that software can consume directly. **Jev** is TypeSafe's
21
+ flagship and first System One model. It understands natural language and returns
22
+ typed answers and probabilities rather
23
+ than generating text or reasoning explanations. Code owns the workflow; the model
24
+ supplies programmable common sense where ordinary code needs semantic understanding.
25
+
26
+ ## Read the live docs
27
+
28
+ **The live TypeSafe docs are the source of truth. Read them as part of the task.**
29
+ This skill gives direction; the docs carry current concepts, prompting guidance,
30
+ API contracts, SDK usage, models, limits, and worked examples.
31
+
32
+ - Start with the [documentation index](https://docs.typesafe.ai/llms.txt) to discover
33
+ relevant pages and cookbooks. Use targeted reads rather than loading the entire site.
34
+ - Mintlify serves Markdown by appending `.md` to a page path, for example
35
+ [how to build with TypeSafe](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md).
36
+ Follow links from the index; convert extensionless documentation page links to
37
+ `.md` when useful. Resolve relative links against `https://docs.typesafe.ai`.
38
+ - Before writing an integration, read the current API or chosen SDK page and the
39
+ question guidance relevant to the design. For a new workflow, also inspect the
40
+ closest cookbook: it often shows a better decomposition than a generic classifier.
41
+ - If the index is unavailable, use the direct links below or the site's navigation.
42
+ If Markdown fetching fails, try the normal page. If live access is unavailable,
43
+ use available local docs or installed SDK types, state that limitation, and avoid
44
+ inventing version-dependent details.
45
+
46
+ | Task | Start here; follow the relevant details |
47
+ | --- | --- |
48
+ | Understand the programming model | [System One](https://docs.typesafe.ai/concepts/system-one.md), [building guide](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md) |
49
+ | Explore what to build | [Use-case map](https://docs.typesafe.ai/concepts/use-case-map.md), then relevant cookbooks from the index |
50
+ | Prepare inputs and questions | [State](https://docs.typesafe.ai/concepts/state.md), [primitives](https://docs.typesafe.ai/primitives.md), then the chosen primitive's page |
51
+ | Decide how to handle uncertainty | [Confidence](https://docs.typesafe.ai/confidence.md) |
52
+ | Write API code | [HTTP API](https://docs.typesafe.ai/api.md), [Python SDK](https://docs.typesafe.ai/sdk/python.md), or [JavaScript SDK](https://docs.typesafe.ai/sdk/javascript.md) |
53
+ | Update an older integration | [Migration guide](https://docs.typesafe.ai/migrating-to-v1.md) and the installed SDK's current reference |
54
+
55
+ ## Find the useful shape
56
+
57
+ Start from the behavior the user wants: what will the application show, select,
58
+ change, or hand off? Work backward to the judgments it needs. Keep known rules,
59
+ calculations, exact lookups, and execution in code. Preserve the user's chosen stack
60
+ and scope; add TypeSafe where semantic understanding helps.
61
+
62
+ When brainstorming or choosing an architecture, consider more than classification.
63
+ The patterns below are starting points: combine primitives around the user's goal,
64
+ including ideas that do not fit an established recipe.
65
+
66
+ - **Route and fill known arguments.** A request can select a handler and its typed
67
+ parameters. Ask useful branch-specific questions up front and consume only the
68
+ relevant answers. Explore [function calling](https://docs.typesafe.ai/cookbooks/function_calling.md)
69
+ and [speculative fan-out](https://docs.typesafe.ai/patterns/fan-out.md).
70
+ - **Select instead of generate.** Find candidate values or source spans in code,
71
+ use a judgment to select the intended one, then copy or normalize it. Code can
72
+ also assemble source text into a formatted document or reading guide. Explore
73
+ [value extraction](https://docs.typesafe.ai/cookbooks/pre_parsed_value_extraction_cookbook.md)
74
+ and [structure recovery](https://docs.typesafe.ai/cookbooks/autoformat.md).
75
+ - **Find and judge evidence.** Retrieve candidates, compare their relevance to a
76
+ query, and select useful context. Explore [reranking](https://docs.typesafe.ai/cookbooks/rerank_typesafe.md)
77
+ and [hierarchical classification](https://docs.typesafe.ai/cookbooks/hierarchical_classification.md).
78
+ - **Turn judgments into reusable data.** Score dimensions once, then let code or
79
+ user controls change weights, thresholds, rankings, and views. With labeled
80
+ outcomes, those signals can become classical ML features. Explore
81
+ [composite scoring](https://docs.typesafe.ai/patterns/composite-scoring.md) and
82
+ [feature discovery](https://docs.typesafe.ai/cookbooks/autoresearch_feature_discovery.md).
83
+ - **Verify and escalate.** Check specific claims or fields against their evidence;
84
+ send uncertain or failing cases to a person or reasoning model. Explore
85
+ [citation checks](https://docs.typesafe.ai/cookbooks/citation_check.md) and
86
+ [extraction cascades](https://docs.typesafe.ai/cookbooks/sde_cascade.md).
87
+ - **Respond to changing state.** Code can retain goals and observations while fresh
88
+ judgments guide the next bounded step. Keep inferred state distinct from observed
89
+ facts, and check freshness before applying a result to a changed situation.
90
+
91
+ For open-ended requests, offer the few directions that best serve the user's goal
92
+ and recommend a starting point. For a concrete request, choose the relevant pattern
93
+ and build; a brainstorm is not a mandatory detour.
94
+
95
+ ## Design the judgments
96
+
97
+ Choose by what the answer means, then read the relevant primitive page:
98
+
99
+ | Need | Primitive | Important distinction |
100
+ | --- | --- | --- |
101
+ | One of a defined set | [Choice](https://docs.typesafe.ai/primitives/choice.md) | Picks one option; its distribution compares competing options |
102
+ | Whether a condition holds | [Noul](https://docs.typesafe.ai/primitives/noul.md) | Probability of yes; no separate confidence; use one per label when several may apply |
103
+ | Degree along a described dimension | [Score](https://docs.typesafe.ai/primitives/score.md) | Probability-weighted position on ordered levels; use comparable per-item Scores for graded ranking |
104
+
105
+ Give each question enough relevant **state** to answer: source text, identities,
106
+ relationships, policies, and current facts. Prefer named JSON fields when context
107
+ has several parts. Put the judgment in **instructions** and define its possible
108
+ answers in **criteria**. Question IDs are for code and are not sent to the model;
109
+ include complete meaning in the question. Reference nested state with backticked
110
+ paths such as `ticket.messages[0].text`.
111
+
112
+ Ask one narrow, coherent judgment per question. Split independently useful dimensions,
113
+ without destroying the relationship being judged. A bounded action selection or
114
+ contextual interpretation is valid; atomic does not mean literal fact extraction
115
+ or a one-sentence limit. Strings work for simple questions. Use structured objects
116
+ or arrays when definitions, contrasts, exclusions, or examples clarify instructions
117
+ or criteria. Score levels must describe concrete situations and stand on their own.
118
+
119
+ Keep the needed answers available. Include a no-match outcome when nothing may fit;
120
+ use a separate presence judgment when it is independently useful. For source-value
121
+ selection, check candidate coverage: the model cannot choose an omitted value.
122
+
123
+ ## Compose and verify
124
+
125
+ **Ask independent questions over the same state together**, including useful
126
+ speculative questions. They run in parallel and cannot see one another's answers.
127
+ State each speculative premise explicitly; code consumes the applicable answers.
128
+ A second request is warranted when an earlier answer is needed to fetch evidence,
129
+ construct new state, or determine the next options. Extra questions still use tokens;
130
+ measure actual request budgets, cost, and end-to-end latency.
131
+
132
+ Use probabilities and confidence to guide behavior, with thresholds evaluated on
133
+ the user's data and consequences. Choice/Score confidence summarizes distribution
134
+ concentration, not overall workflow correctness or permission to act. A Noul near
135
+ 0.5 means similar probability for yes and no, not medium intensity. Several
136
+ acceptable alternatives can also spread probability; low confidence need not
137
+ invalidate a harmless preference choice. Ignore uncertainty on unused branches.
138
+
139
+ Keep policy explicit and raw judgments reusable. Weighted scores suit compensating
140
+ preferences; an “any serious violation” rule needs separate conditions. Changing a
141
+ weight or display filter need not rerun inference when evidence and question meanings
142
+ are unchanged. Typed output guarantees the interface, not truth. System One models
143
+ are trained for calibrated decisions; validate their performance in the target domain.
144
+
145
+ Test representative cases and the resulting application behavior. For failures,
146
+ inspect the exact state, questions, candidates, answers, composition, and observed
147
+ outcome. Separate missing evidence, model errors, code errors, and service failures.
148
+ Treat cookbook thresholds and demo results as examples to evaluate, not universal
149
+ rules or permanent model limitations. Keep API credentials server-side in web apps.