sisyo 1.6.0 → 1.6.7
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 +1 -1
- package/bin/known-hashes.json +80 -0
- package/bin/sisyo.js +19 -5
- package/package.json +5 -1
- package/templates/.claude/skills/gemini-integration/LIVE-VOICE.md +117 -31
- package/templates/.claude/skills/gemini-integration/RAG-EMBEDDING.md +16 -6
- package/templates/.claude/skills/gemini-integration/SKILL.md +19 -8
- package/templates/.claude/skills/gemini-integration/TEXT-CHAT.md +11 -1
- package/templates/.claude/skills/gemini-integration/TROUBLESHOOTING.md +24 -9
- package/templates/.claude/skills/hindsight/SKILL.md +172 -0
- package/templates/.claude/skills/typesafe-jev/SKILL.md +149 -0
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
|
|
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,80 @@
|
|
|
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
|
+
"79829b4fb5c7afa7ce819d51087d69251d7552f91d183c2068b692eb53dd53e7",
|
|
41
|
+
"c24075202b5154a9c1821034af8cc3da8dd895ae0fba0d908f35fe2a11070532",
|
|
42
|
+
"f5c298b3013004125b458db7c9f5971cc047e9d57c02992edc3faed7c7b3f21f"
|
|
43
|
+
],
|
|
44
|
+
".claude/skills/gemini-integration/TEXT-CHAT.md": [
|
|
45
|
+
"165c30a0e85f9dcbb9889b1d20dc5ebd54082b05a07d646699dada3c80b72417",
|
|
46
|
+
"8c97bcfdf6161d2f8deb46d8105b417cdc6c14acab64779c6740d38e804a5097"
|
|
47
|
+
],
|
|
48
|
+
".claude/skills/gemini-integration/TROUBLESHOOTING.md": [
|
|
49
|
+
"3659f0d83782da3ab55921d5bdce5222d531031b4bcb51f68db6dc80b6d120eb",
|
|
50
|
+
"36d519a3754a81862b3c1c080c8fcf16635820d3f7ef3f09625fc1a7195d7266",
|
|
51
|
+
"8e24e24ee5915908c204c42b094c82727bac7fb4214d54a7b30cb129ad781a6e",
|
|
52
|
+
"e19f4742a1cdaf77d1e99a7747fd6d952a37a9183e1aae77997919eefcb8dd4f",
|
|
53
|
+
"f8f77b65bbe86dc89408b8372685acf59774df93e4fd23f3563df0f55be07b8c"
|
|
54
|
+
],
|
|
55
|
+
".claude/skills/hindsight/SKILL.md": [
|
|
56
|
+
"cd564d9f4227571ba0f366f9b816d49a70bb9ac2cff449a475f695324e83f4fa"
|
|
57
|
+
],
|
|
58
|
+
".claude/skills/html-docs/SKILL.md": [
|
|
59
|
+
"8414e0166d4403fff509302f2973a8765441529584d710249eb1bf887e89caf2",
|
|
60
|
+
"a307853ca9bad1e0335cea6c477400048e2d17fcecaedd79b5b58b481666cbdf"
|
|
61
|
+
],
|
|
62
|
+
".claude/skills/react-page-oriented/SKILL.md": [
|
|
63
|
+
"dd57426f6be595b65b263b754e2c8c9cabce9e3ce332e80cbb1ddcebfab89e81"
|
|
64
|
+
],
|
|
65
|
+
".claude/skills/react-page-oriented/triggers.md": [
|
|
66
|
+
"489db92a891306ab76093c2d41681f3bff1a8343329179ca913f87405c661aaf"
|
|
67
|
+
],
|
|
68
|
+
".claude/skills/terraform-best-practices/SKILL.md": [
|
|
69
|
+
"4cd2cbf59c8d8755bf1b1c0f12553feb1ca7258ce44e5e91cf6baee3f0e23149",
|
|
70
|
+
"85eee170ef76a0d17ed7f44037cf4421eb879b74dce4fd452066f59c275d9616"
|
|
71
|
+
],
|
|
72
|
+
".claude/skills/typesafe-jev/SKILL.md": [
|
|
73
|
+
"db5d6f3416ef9468f00dc2b55bd2a76d7ac6f6514ffc22eb27455f7b007d7241"
|
|
74
|
+
],
|
|
75
|
+
".claude/skills/vibe-docs/SKILL.md": [
|
|
76
|
+
"5bf3ef21df2315575479a610a15f935010673e74de3523c888e74a6c3f78b105",
|
|
77
|
+
"ba3f7176b4ae7088b0ebbfa08bfe8b06729bab6acaddb9b489a8a46233f62fc6",
|
|
78
|
+
"db40c330b6b19b5b78f8a28c6611d6db917ea225bbc316fd8fb5e881331e7ac5"
|
|
79
|
+
]
|
|
80
|
+
}
|
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
|
|
158
|
-
info("
|
|
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
|
-
|
|
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 (!
|
|
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,10 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sisyo",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.7",
|
|
4
4
|
"description": "Smart documentation system for vibe coding with Claude Code. Token-efficient MAP.md routing.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"sisyo": "./bin/sisyo.js"
|
|
7
7
|
},
|
|
8
|
+
"scripts": {
|
|
9
|
+
"hashes": "node scripts/gen-known-hashes.js",
|
|
10
|
+
"prepublishOnly": "node scripts/gen-known-hashes.js"
|
|
11
|
+
},
|
|
8
12
|
"files": [
|
|
9
13
|
"bin/",
|
|
10
14
|
"templates/"
|
|
@@ -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":
|
|
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"
|
|
30
|
-
live_config["thinking_config"] = {"thinking_level": "minimal"} # 3.
|
|
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`
|
|
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
|
|
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) →
|
|
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
|
|
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
|
-
-
|
|
111
|
-
|
|
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
|
-
|
|
116
|
-
socket inside the tool handler (that produced no
|
|
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
|
|
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
|
|
225
|
+
## Differences 2.5 → 3.1 → 3.8
|
|
140
226
|
|
|
141
|
-
| Item | 2.5 | 3.1 |
|
|
142
|
-
|
|
143
|
-
| Mic stream | `sendRealtimeInput({ media })` | `
|
|
144
|
-
| Mid-session text | `sendClientContent` | `sendRealtimeInput({ text })` |
|
|
145
|
-
| Latency tuning | `thinking_budget` | `
|
|
146
|
-
| Server events | 1 part / event | multiple parts / event → loop over all `parts` |
|
|
147
|
-
| Function calling |
|
|
148
|
-
| Proactive audio / affective dialog |
|
|
149
|
-
|
|
150
|
-
Fallback: `GEMINI_LIVE_MODEL=gemini-
|
|
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
|
|
59
|
-
"0.0–1.0 for relevance. Return ONLY valid JSON
|
|
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"
|
|
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
|
|
74
|
-
|
|
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 (
|
|
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.
|
|
45
|
-
| 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 = "
|
|
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.
|
|
102
|
-
|
|
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;
|
|
@@ -107,6 +109,9 @@ Apply to every `generate_content` / `chats.create` / `embed_content` on 3.5+ / 3
|
|
|
107
109
|
- Send **all** function responses of a turn in **ONE** `send_message_stream(parts)`. One call per
|
|
108
110
|
response only streams the reply to the last one and silently drops the rest.
|
|
109
111
|
- A chunk may contain only function calls and no text — wrap `chunk.text` in a safe getter.
|
|
112
|
+
- The sync client's `send_message_stream` is a **blocking** iterator: inside an async SSE generator
|
|
113
|
+
pull it with `starlette.concurrency.iterate_in_threadpool` (or use `client.aio`), never a bare
|
|
114
|
+
`for` — the event loop stalls and the whole reply reaches the browser at once.
|
|
110
115
|
- JSON output: `response_mime_type="application/json"` + still parse defensively (regex the
|
|
111
116
|
first `{...}` on failure).
|
|
112
117
|
|
|
@@ -122,6 +127,12 @@ Apply to every `generate_content` / `chats.create` / `embed_content` on 3.5+ / 3
|
|
|
122
127
|
after the farewell turn (see `LIVE-VOICE.md`).
|
|
123
128
|
- A tool that throws must still answer with `{"error": "..."}` — a missing response makes the
|
|
124
129
|
model wait forever.
|
|
130
|
+
- Return **structured** results, never `{}` / `None`: `status` (`ok` | `no_results` |
|
|
131
|
+
`invalid_argument` | `error`), plus `retryable` and a model-facing `guidance` sentence when
|
|
132
|
+
nothing usable came back. Gemini 3.8 Live re-queries with rephrased variations on an
|
|
133
|
+
unexplained empty result. Keep any `message` short if an admin UI shows it verbatim.
|
|
134
|
+
- `behavior` (`BLOCKING` / `NON_BLOCKING`) is a Live-only declaration field — add it while
|
|
135
|
+
building the Live token config, not to the shared `TOOL_DEFINITIONS` text chat also sends.
|
|
125
136
|
|
|
126
137
|
## 6. Security
|
|
127
138
|
|
|
@@ -35,6 +35,8 @@ chat = client.chats.create(
|
|
|
35
35
|
## Stream a message
|
|
36
36
|
|
|
37
37
|
```python
|
|
38
|
+
from starlette.concurrency import iterate_in_threadpool
|
|
39
|
+
|
|
38
40
|
def _safe_get_text(chunk) -> str:
|
|
39
41
|
try:
|
|
40
42
|
return chunk.text or "" # raises / empty on function-call-only chunks
|
|
@@ -60,7 +62,7 @@ async def stream_chat_message(session_id: str, message: str):
|
|
|
60
62
|
stream = chat.send_message_stream(message)
|
|
61
63
|
pending_calls = None
|
|
62
64
|
full = []
|
|
63
|
-
for chunk in stream:
|
|
65
|
+
async for chunk in iterate_in_threadpool(stream): # NOT `for chunk in stream` — see below
|
|
64
66
|
text = _safe_get_text(chunk)
|
|
65
67
|
if text:
|
|
66
68
|
full.append(text)
|
|
@@ -76,6 +78,14 @@ async def stream_chat_message(session_id: str, message: str):
|
|
|
76
78
|
yield {"event": "done", "data": "{}"}
|
|
77
79
|
```
|
|
78
80
|
|
|
81
|
+
**Pull the sync stream off the event loop.** `chat.send_message_stream()` on the sync client is a
|
|
82
|
+
*blocking* iterator. A bare `for chunk in stream` inside the async SSE generator stalls the event
|
|
83
|
+
loop while it waits for each chunk, so uvicorn (uvloop on Linux, Proactor on Windows) only flushes
|
|
84
|
+
the queued writes when the turn ends: every `text` event reaches the browser in the same
|
|
85
|
+
millisecond as `done` and the reply "pops in" whole. `iterate_in_threadpool` waits for each chunk
|
|
86
|
+
on a worker thread (or use the async client, `client.aio.chats`). Check it: `text` events should
|
|
87
|
+
arrive ~100–200 ms apart (sirisugi 2026-09-28: first words 1.3 s instead of the full reply at 2.2–3.4 s).
|
|
88
|
+
|
|
79
89
|
## Return tool results — ONE call, all responses
|
|
80
90
|
|
|
81
91
|
```python
|
|
@@ -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":
|
|
11
|
-
| 400 `thinking_level=minimal` |
|
|
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` |
|
|
@@ -18,8 +19,10 @@ defaults and deploy does not rewrite it. Verify via the token / health endpoint
|
|
|
18
19
|
| Symptom | Cause | Fix |
|
|
19
20
|
|---|---|---|
|
|
20
21
|
| Reply ignores earlier tool results | One `send_message_stream` per response | Send all responses as ONE `parts` list |
|
|
22
|
+
| Reply appears all at once — every SSE `text` event arrives together with `done` | Sync `send_message_stream` iterated with `for` inside the async SSE generator blocks the event loop; uvicorn flushes the queued writes only when the turn ends | `async for chunk in iterate_in_threadpool(stream)` (or `client.aio` chats) — see `TEXT-CHAT.md` |
|
|
21
23
|
| `chunk.text` raises / empty | Chunk carries only function calls | `_safe_get_text()` wrapper |
|
|
22
|
-
| Chat got slower after bump | `
|
|
24
|
+
| 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 |
|
|
25
|
+
| 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
26
|
| `[Echo] …` replies in prod | `GEMINI_API_KEY` empty on that box | Set the key; echo is the stub mode |
|
|
24
27
|
| Embeddings: N chunks → 1 vector | Passed a list to `contents` | Embed one text per call |
|
|
25
28
|
| Search results nonsense after embedding model change | Vector space changed | Re-embed everything (`--recreate`) |
|
|
@@ -29,25 +32,37 @@ defaults and deploy does not rewrite it. Verify via the token / health endpoint
|
|
|
29
32
|
| Symptom | Cause | Fix |
|
|
30
33
|
|---|---|---|
|
|
31
34
|
| "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 }` |
|
|
35
|
+
| Socket closed **1007** right after mic start | `sendRealtimeInput({ media })` on 3.1 | Use `{ audio }` (3.x docs only list `audio`) |
|
|
36
|
+
| 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) |
|
|
37
|
+
| Setup error mentioning `proactivity` / `enable_affective_dialog` on 3.8 | Always on / removed on 3.8 | Drop those keys |
|
|
33
38
|
| Token endpoint 402 | Billing / Live API not enabled for the key | Enable in AI Studio; log exception on mint |
|
|
34
39
|
| 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
40
|
| Token endpoint 403 | `voice_enabled` false on agent or plan | Expected — hide the voice toggle in the UI |
|
|
36
41
|
| Connected but silent | `AudioContext` suspended (not from a user gesture) | `await ctx.resume()` after creating it |
|
|
37
42
|
| 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 |
|
|
43
|
+
| 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` |
|
|
44
|
+
| 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` |
|
|
45
|
+
| 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` |
|
|
46
|
+
| 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" |
|
|
47
|
+
| Error / odd reply after answering a tool call the customer talked over | Server cancelled it (`toolCallCancellation.ids`) | Drop responses for cancelled ids |
|
|
48
|
+
| 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
49
|
| No farewell, UI stuck after `end_conversation` | Disconnected inside the tool handler | Mute mic, send response, wait `turnComplete` + audio drain, then close |
|
|
40
50
|
| 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.
|
|
42
|
-
|
|
|
51
|
+
| Only first audio part plays | 3.x sends multiple parts per event | Loop over all `parts` |
|
|
52
|
+
| 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 |
|
|
53
|
+
| 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` |
|
|
54
|
+
| 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 |
|
|
55
|
+
| Mid-session text ignored on 3.1 | Used `sendClientContent` | `sendRealtimeInput({ text })` (the documented text path on 3.x) |
|
|
43
56
|
| Voice sample button slow / times out | TTS on demand | Pre-generate at startup, cache on S3, key by version |
|
|
44
57
|
|
|
45
58
|
## Rollback values
|
|
46
59
|
|
|
47
60
|
| Key | Rollback |
|
|
48
61
|
|---|---|
|
|
49
|
-
| `GEMINI_CHAT_MODEL` | `gemini-3.1-flash-lite
|
|
50
|
-
| `
|
|
62
|
+
| `GEMINI_CHAT_MODEL` | `gemini-3.1-flash-lite` (`minimal`/`low` valid there) — the `-preview` id was shut down 2026-05-25 |
|
|
63
|
+
| `GEMINI_CHAT_THINKING_LEVEL` | `low` (deeper but slower than `minimal`) |
|
|
64
|
+
| `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) |
|
|
65
|
+
| `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
66
|
| `GEMINI_EMBEDDING_MODEL` | Previous model **plus** full re-embed — no hot rollback |
|
|
52
67
|
|
|
53
68
|
Always record the rollback + the date of the bump in `docs/09_integrations/gemini.md`.
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hindsight
|
|
3
|
+
description: >
|
|
4
|
+
Add long-term memory to a project with the shared Hindsight server on the LAN
|
|
5
|
+
Mac (vectorize-io/hindsight), or operate or redeploy that server. Use when a
|
|
6
|
+
project, app, agent system or coding setup should remember facts, decisions or
|
|
7
|
+
user preferences across sessions; when asked to "integrate Hindsight",
|
|
8
|
+
"add memory", "retain/recall/reflect"; or when the Hindsight stack in
|
|
9
|
+
~/Workspace/LanServer/Hindsight needs a restart, login, upgrade or rebuild.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Hindsight: long-term memory for any project
|
|
13
|
+
|
|
14
|
+
One Hindsight server runs on the always-on Mac and serves every project. A
|
|
15
|
+
**bank** holds one project's memories, and banks never see each other. Integrating a new
|
|
16
|
+
project means: pick a bank, decide what to retain, recall at the point of use.
|
|
17
|
+
Do not stand up a second server unless the project must run somewhere else.
|
|
18
|
+
|
|
19
|
+
Server details and the reasons behind its setup: `~/Workspace/LanServer/Hindsight/README.md`.
|
|
20
|
+
Paperclip's integration (capture plugin + per-run recall): the "Company memory
|
|
21
|
+
(Hindsight)" section of `~/Workspace/Hoang/paperclip/DEPLOY-DORAEMON.md`.
|
|
22
|
+
|
|
23
|
+
## The shared server
|
|
24
|
+
|
|
25
|
+
| | |
|
|
26
|
+
|---|---|
|
|
27
|
+
| API (and MCP) | `http://192.168.1.95:26352` from the LAN; `http://host.docker.internal:26352` from a container on the Mac |
|
|
28
|
+
| UI | `http://192.168.1.95:26353` (browse, edit, invalidate memories) |
|
|
29
|
+
| Auth | `Authorization: Bearer <HINDSIGHT_API_KEY>`; UI key `HINDSIGHT_UI_ACCESS_KEY` |
|
|
30
|
+
| Keys | in `~/Workspace/LanServer/Hindsight/.env` (mode 600) |
|
|
31
|
+
| LLM | Claude Sonnet 5.5 on the Claude **subscription** (`claude-code`), ChatGPT subscription (`openai-codex`) as fallback |
|
|
32
|
+
| Embeddings / rerank | Gemini `gemini-embedding-2` (768 d) / TypeSafe Jev, with `rrf` as fallback |
|
|
33
|
+
|
|
34
|
+
**Handling the key:** copy it into the new project's own secret store (its
|
|
35
|
+
`.env`, a Paperclip secret, and so on) without printing it:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
grep '^HINDSIGHT_API_KEY=' ~/Workspace/LanServer/Hindsight/.env | cut -d= -f2- | tr -d '\n' | pbcopy
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Hard rules
|
|
42
|
+
|
|
43
|
+
- **The LLM stays on subscriptions.** Never give Hindsight or a project's memory
|
|
44
|
+
path a pay-per-token LLM key (ANTHROPIC_API_KEY, OPENAI_API_KEY, Gemini as LLM).
|
|
45
|
+
The operator set this rule so the bill cannot grow. Gemini is for embeddings
|
|
46
|
+
only, and Jev is for reranking only.
|
|
47
|
+
- **One bank per project, or per tenant inside a project.** Name it
|
|
48
|
+
`<project>::<scope>`, for example `paperclip::<companyId>`, `fire::<userId>` or
|
|
49
|
+
`coding-agent::<repo>`. Add each new bank to the registry in the server README.
|
|
50
|
+
Never write one project's data into another's bank.
|
|
51
|
+
- **Keep the embedding model.** Changing it needs an empty database for every bank
|
|
52
|
+
(see "Rebuild" below). Agree on it before anyone depends on the memories.
|
|
53
|
+
- **Memory is evidence, not orders.** When recall goes into a prompt, show dates,
|
|
54
|
+
let the current request win, and invite corrections.
|
|
55
|
+
- **No secrets in memory.** Redact before retaining. The Paperclip plugin's
|
|
56
|
+
`redactSecrets()` in
|
|
57
|
+
`paperclip/packages/plugins/doraemon-hindsight-memory/src/items.ts` is a ready
|
|
58
|
+
pattern list.
|
|
59
|
+
|
|
60
|
+
## Integrating a project
|
|
61
|
+
|
|
62
|
+
1. **Create the bank with missions.** They steer what extraction keeps; see
|
|
63
|
+
`references/api.md`, section "Bank". Say whose words the items are, what to
|
|
64
|
+
keep (preferences, decisions, rules, facts, lessons), what to skip
|
|
65
|
+
(chit-chat, one-off scheduling, status noise), and that secrets are never
|
|
66
|
+
stored.
|
|
67
|
+
2. **Choose what to retain: durable signal, not logs.** Paperclip retains only
|
|
68
|
+
the human's own words (about 6 items a day) and not the agents' 70 comments a
|
|
69
|
+
day. For each item:
|
|
70
|
+
- `content`: the words to learn from, cleaned and redacted.
|
|
71
|
+
- `context`: who is speaking and what they reply to. Keep it **under about 400
|
|
72
|
+
characters**. It is prepended to every fact extracted from the item and sent
|
|
73
|
+
to Jev with each rerank candidate, and Jev refuses requests over about
|
|
74
|
+
16k tokens.
|
|
75
|
+
- `timestamp`: when it was said, for temporal ranking.
|
|
76
|
+
- `document_id`: a stable source id (`<project>:<kind>:<id>`). Re-sending
|
|
77
|
+
replaces instead of duplicating. Keep your own content hash, so that
|
|
78
|
+
unchanged rows never pay for another extraction.
|
|
79
|
+
- `tags`: provenance (`source:…`, `project:…`). Recall does not filter on
|
|
80
|
+
them unless asked.
|
|
81
|
+
- Send with `async: true`. Facts appear after extraction, in 5–10 s each.
|
|
82
|
+
3. **Recall where the answer is used.**
|
|
83
|
+
- Query from the task at hand, at most about 700 characters (Hindsight rejects
|
|
84
|
+
queries over 500 tokens).
|
|
85
|
+
- Use `budget: "mid"` and `max_tokens` around 800.
|
|
86
|
+
- Allow about a 6 s timeout, and **fail open**: a missing bank (404) or an
|
|
87
|
+
error means no memory, never a failed request. Recall uses no LLM and takes
|
|
88
|
+
about 1 s (Gemini embed plus Jev).
|
|
89
|
+
- Put the result into the per-request prompt, not a cached system prompt:
|
|
90
|
+
changing that prompt breaks prompt caching and session resume.
|
|
91
|
+
4. **Optionally add a mental model** for a stable summary, for example "how the
|
|
92
|
+
user wants work done". It is created once, refreshes itself after new
|
|
93
|
+
memories (at most every 30 min) and reads with a plain GET, with no LLM.
|
|
94
|
+
While the first refresh runs, its content is `Generating content...`: treat
|
|
95
|
+
that as empty.
|
|
96
|
+
5. **Use reflect only for deliberate questions** ("why did we drop X?"). It runs
|
|
97
|
+
an LLM loop and takes up to minutes.
|
|
98
|
+
6. **Verify.** Retain one representative item synchronously into
|
|
99
|
+
`zz-test-<project>` and read the extracted facts. Recall a query in the
|
|
100
|
+
project's language (Vietnamese works), then delete the test bank.
|
|
101
|
+
|
|
102
|
+
Client code for TypeScript and Python, and the exact endpoints, are in
|
|
103
|
+
`references/api.md`.
|
|
104
|
+
|
|
105
|
+
## Coding agents (Claude Code, Codex)
|
|
106
|
+
|
|
107
|
+
Use MCP: `claude mcp add --transport http hindsight http://192.168.1.95:26352/mcp/<bank>/ --header "Authorization: Bearer <key>"`,
|
|
108
|
+
with one bank per repo (`coding-agent::<repo>`).
|
|
109
|
+
|
|
110
|
+
**Do not install Hindsight hooks globally** (`~/.claude/settings.json`) on the Mac
|
|
111
|
+
or in WSL. Paperclip agents on those machines share `~/.claude`, so they would
|
|
112
|
+
get the hooks too: a second injection of memory, and agent transcripts retained
|
|
113
|
+
into the bank. Use MCP, or project-level hooks (`.claude/settings.json` in the
|
|
114
|
+
repo).
|
|
115
|
+
|
|
116
|
+
## Operating the server
|
|
117
|
+
|
|
118
|
+
All in `~/Workspace/LanServer/Hindsight`:
|
|
119
|
+
|
|
120
|
+
| Task | Do |
|
|
121
|
+
|---|---|
|
|
122
|
+
| Restart or look | `docker compose up -d`, `docker compose logs -f hindsight`, `curl -s http://127.0.0.1:26352/health` |
|
|
123
|
+
| Claude login expired (a year) | `./login-claude.sh` (or `--paste` with a `claude setup-token` token; the script strips the indentation and wrapping) |
|
|
124
|
+
| ChatGPT fallback login invalid | `./login-codex.sh`. It uses its own `codex-home/`; never `~/.codex`, where rotating refresh tokens would log the codex agents out |
|
|
125
|
+
| New Claude model or CLI | `docker compose build --no-cache hindsight && docker compose up -d`, then set `HINDSIGHT_LLM_MODEL` in `.env`. Look up model ids in the CLI binary: `docker exec hindsight sh -c 'grep -a -oE "claude-[a-z]+-[0-9-]+" /opt/claude/claude \| sort -u'` |
|
|
126
|
+
| Backup | `docker exec hindsight-db pg_dump -U hindsight hindsight \| gzip > backups/hindsight-$(date +%Y%m%d%H%M).sql.gz` |
|
|
127
|
+
| Upgrade Hindsight | bump `HINDSIGHT_VERSION` in `docker-compose.yml`, then `docker compose up -d --build`; migrations run on start |
|
|
128
|
+
| Rebuild (embedding change) | back up, `docker compose down`, `docker volume rm hindsight_db_data`, `docker compose up -d`. Paperclip's plugin resends its history by itself when its bank is missing; other projects must re-send theirs |
|
|
129
|
+
|
|
130
|
+
Health signals:
|
|
131
|
+
- the startup log shows `LLM: claude-code / claude-sonnet-5-5`,
|
|
132
|
+
`Claude Code connection verified`, `Codex LLM verified` and
|
|
133
|
+
`google provider initialized ... dim: 768`;
|
|
134
|
+
- recall takes about 1 s;
|
|
135
|
+
- the API process uses about 360 MB of RAM.
|
|
136
|
+
|
|
137
|
+
## Deploying a separate instance
|
|
138
|
+
|
|
139
|
+
Only when a project must run away from this Mac. Copy the directory (compose
|
|
140
|
+
file, `Dockerfile`, `login-*.sh`, README); do not copy `.env`, `codex-home/` or
|
|
141
|
+
`backups/`. Then:
|
|
142
|
+
|
|
143
|
+
1. **New secrets.** Create a new `.env` with fresh `HINDSIGHT_DB_PASSWORD`,
|
|
144
|
+
`HINDSIGHT_API_KEY` and `HINDSIGHT_UI_ACCESS_KEY` (`openssl rand -hex 24`),
|
|
145
|
+
plus the Gemini and Jev keys.
|
|
146
|
+
2. **A free subnet.** Pin `networks.default` to a free 10.x subnet. On this Mac,
|
|
147
|
+
an automatic pick lands on 192.168.0.0/20 and cuts containers off from the LAN.
|
|
148
|
+
3. **Build for the host's own architecture.** The Dockerfile copies the native
|
|
149
|
+
Claude CLI binary for that platform.
|
|
150
|
+
4. **Log in** with `login-claude.sh`, then `login-codex.sh`.
|
|
151
|
+
5. **Verify** as in "Integrating a project", step 6.
|
|
152
|
+
|
|
153
|
+
## Traps already paid for
|
|
154
|
+
|
|
155
|
+
- **Reranker.** A local cross-encoder reranker on the Mac's CPU took 36–97 s per
|
|
156
|
+
recall. Jev over the API, with `RECALL_MAX_CANDIDATES_PER_SOURCE=15`, takes
|
|
157
|
+
about 0.3 s. The recall budget does not bound the candidate pool; the
|
|
158
|
+
per-source cap does.
|
|
159
|
+
- **torch.** On arm64, the PyPI torch wheel pulls 3.3 GB of CUDA. Local models
|
|
160
|
+
are gone now; if they ever come back, install torch from the CPU index.
|
|
161
|
+
- **Codex models.** `gpt-5.4-mini` is refused on ChatGPT accounts; `gpt-6-luna`
|
|
162
|
+
works.
|
|
163
|
+
- **Reflect timeout.** It defaults to 30 s per LLM call, which is too short;
|
|
164
|
+
`HINDSIGHT_API_REFLECT_LLM_TIMEOUT=120`.
|
|
165
|
+
- **`HINDSIGHT_API_LLM_STRATEGY`.** It must be JSON (`{"mode": "failover"}`); a
|
|
166
|
+
bare word crashes startup.
|
|
167
|
+
- **Bank reads.** There is no GET for a single bank (405); list banks instead.
|
|
168
|
+
- **Deleting memories.** No endpoint hard-deletes one memory. Invalidate it, in
|
|
169
|
+
the UI or with `PATCH` `state: invalidated`, or delete its document.
|
|
170
|
+
- **Plugin workers (Paperclip).** Background calls must run outside host
|
|
171
|
+
invocations and name the company. The host expands array SQL parameters, so
|
|
172
|
+
pass lists as JSON. Details are in DEPLOY-DORAEMON.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.
|