sisyo 1.5.1 → 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.
@@ -0,0 +1,242 @@
1
+ # Live Voice (client-side WebSocket via ephemeral token)
2
+
3
+ Voice runs **in the browser** against the Live API. The backend only mints a constrained
4
+ ephemeral token; tools are still executed by the backend.
5
+
6
+ ```
7
+ FE POST /api/live/token?lang= → BE: validate agent → client.auth_tokens.create() → {token, model, voice_name, session_id}
8
+ FE ai.live.connect({model, config, callbacks}) (apiKey = token, apiVersion v1alpha)
9
+ FE mic PCM 16 kHz, 20–40 ms chunks → sendRealtimeInput({ audio })
10
+ BE→FE audio PCM 24 kHz in serverContent.modelTurn.parts[].inlineData
11
+ FE toolCall → POST /api/tools/execute → sendToolResponse({ functionResponses })
12
+ ```
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
+
43
+ ## Backend — mint the token
44
+
45
+ ```python
46
+ from google import genai
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
+
56
+ client = genai.Client(api_key=settings.GEMINI_API_KEY, http_options={"api_version": "v1alpha"})
57
+ family = _live_family(model)
58
+
59
+ live_config = {
60
+ "response_modalities": ["AUDIO"],
61
+ "system_instruction": system_instruction, # same template as text chat + voice block
62
+ "tools": live_tools(family),
63
+ "speech_config": {"voice_config": {"prebuilt_voice_config": {"voice_name": voice_name}}},
64
+ "input_audio_transcription": {}, # server-side STT of the user → live transcript
65
+ "output_audio_transcription": {}, # STT of the model's speech
66
+ }
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.
70
+
71
+ token = client.auth_tokens.create(config={
72
+ "uses": 1,
73
+ "expire_time": (now + 30min).isoformat(),
74
+ "new_session_expire_time": (now + 2min).isoformat(),
75
+ "live_connect_constraints": {"model": model, "config": live_config},
76
+ "http_options": {"api_version": "v1alpha"},
77
+ })
78
+ return {"token": token.name, "model": model, "voice_name": voice_name, "session_id": session_id}
79
+ ```
80
+
81
+ Rules:
82
+
83
+ - Validate the agent / feature flag **before** creating a session row or minting — the endpoint
84
+ is public. Raise a dedicated `AgentNotFound` and map ONLY that to 404 (catching the
85
+ `LookupError` base class turned `KeyError`s from deeper code into bogus 404s).
86
+ - Return `voice_name` — the FE **must** pass it again in `live.connect({ speechConfig })`; the
87
+ server ignores the token's voice otherwise.
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…".
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.
94
+
95
+ ## Frontend — connect
96
+
97
+ ```ts
98
+ import { GoogleGenAI, Modality, type LiveServerMessage } from '@google/genai'
99
+
100
+ const ai = new GoogleGenAI({ apiKey: tokenData.token, httpOptions: { apiVersion: 'v1alpha' } })
101
+ const outputCtx = new AudioContext({ sampleRate: 24000 })
102
+ if (outputCtx.state === 'suspended') await outputCtx.resume() // else "connected but silent"
103
+
104
+ const session = await Promise.race([
105
+ ai.live.connect({
106
+ model: tokenData.model,
107
+ config: {
108
+ responseModalities: [Modality.AUDIO],
109
+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: tokenData.voice_name } } },
110
+ },
111
+ callbacks: { onopen, onmessage, onerror, onclose },
112
+ }),
113
+ timeout(15000, 'WebSocket to Gemini Live did not open (proxy / extension / CSP?)'),
114
+ ])
115
+ ```
116
+
117
+ - `connect()` resolves only on WS `onopen` → always race it with a timeout so the UI never
118
+ hangs on "connecting…".
119
+ - Track a **phase** state (`idle | token | opening | open | recording | ending | ended | error`)
120
+ and log it — a hang is then observable. Log a build marker too (stale bundles look like hangs).
121
+ - `onclose`: codes 1000/1005 are normal; anything else → surface `reason` as an error.
122
+ 1007 = bad payload (see the differences table).
123
+
124
+ ## Audio
125
+
126
+ | Direction | Format | API |
127
+ |---|---|---|
128
+ | Mic → model | PCM 16-bit mono, **16 kHz**, **20–40 ms chunks** (≤ 100 ms) | `sendRealtimeInput({ audio: pcmBlob })` |
129
+ | Model → speaker | PCM 16-bit mono, **24 kHz** | `serverContent.modelTurn.parts[].inlineData.data` |
130
+
131
+ - `ScriptProcessor` buffer 512 @ 16 kHz = 32 ms per chunk; 4096 = 256 ms held back per send.
132
+ - Schedule output buffers back-to-back on the AudioContext clock (`nextStartTime`), don't play
133
+ each chunk immediately.
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
+ ```
153
+ - Route output through an `AnalyserNode` if the UI animates on loudness.
154
+ - Transcripts: `serverContent.inputTranscription.text` / `outputTranscription.text` arrive as
155
+ deltas; append to the current turn's bubble, reset indexes on `turnComplete`.
156
+
157
+ ## Tool calls
158
+
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
+
163
+ if (msg.toolCall) {
164
+ const functionResponses = (await Promise.all((msg.toolCall.functionCalls || []).map(async fc => {
165
+ let response: Record<string, unknown>
166
+ try { response = { result: await executeTool(fc.name, fc.args) } }
167
+ catch (e) { response = { error: e instanceof Error ? e.message : 'Tool execution failed' } }
168
+ return { id: fc.id || '', name: fc.name || '', response }
169
+ }))).filter(fr => !cancelled.has(fr.id))
170
+ if (functionResponses.length) session.sendToolResponse({ functionResponses }) // ALL calls, ONE message
171
+ }
172
+ ```
173
+
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.
190
+
191
+ ## end_conversation — hang up AFTER the farewell
192
+
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…").
196
+
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
199
+ grace timer.
200
+ 2. Send the tool response normally.
201
+ 3. On `turnComplete` while `ending`: wait for the audio queue to drain (+400 ms) → disconnect →
202
+ phase `ended` (show "Call again", not "idle").
203
+ 4. Grace timer fires first → disconnect anyway.
204
+
205
+ System prompt line: *"When the customer says goodbye, say ONE short farewell sentence and call
206
+ end_conversation in that same turn."*
207
+
208
+ ## Session language + greeting
209
+
210
+ - Widget passes `?lang=` → token endpoint → appended `## Voice Mode` block in the system
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.
217
+ - The FE's first turn is a control message `[Session start] … Greet them now in {lang}` — **not**
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`.
220
+ - Tell the model the `[Session start]` turn is a control signal: never read it aloud, never
221
+ mirror its language.
222
+ - Per-language overrides live in `config.locales[lang]` merged over defaults by ONE resolver
223
+ used by both the token endpoint and the public config endpoint.
224
+
225
+ ## Differences 2.5 → 3.1 → 3.8
226
+
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`.
237
+
238
+ ## Persisting the voice transcript
239
+
240
+ Create a `live_*` session row when minting the token and return its id. FE flushes new
241
+ transcript entries on `turnComplete`, `onclose` and disconnect — fire-and-forget, watermark
242
+ advances only after a successful save, and persistence must never break the call.
@@ -0,0 +1,93 @@
1
+ # Embeddings + LLM Reranker (RAG)
2
+
3
+ ## Embedder
4
+
5
+ ```python
6
+ class GeminiEmbedder:
7
+ def __init__(self):
8
+ self.model = settings.GEMINI_EMBEDDING_MODEL # gemini-embedding-2
9
+ self.dim = settings.EMBEDDING_DIM # 768 via Matryoshka
10
+ self._client = None
11
+
12
+ def _get_client(self):
13
+ if self._client is None:
14
+ from google import genai
15
+ if not settings.GEMINI_API_KEY:
16
+ raise RuntimeError("GEMINI_API_KEY not set — cannot use GeminiEmbedder")
17
+ self._client = genai.Client(api_key=settings.GEMINI_API_KEY)
18
+ return self._client
19
+
20
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
21
+ # ONE text per call. gemini-embedding-2 is multimodal and treats a LIST in
22
+ # `contents` as the parts of a SINGLE input → N chunks collapse into 1 vector.
23
+ out = []
24
+ for text in texts:
25
+ resp = self._get_client().models.embed_content(
26
+ model=self.model, contents=text,
27
+ config={"task_type": "RETRIEVAL_DOCUMENT", "output_dimensionality": self.dim},
28
+ )
29
+ out.append(resp.embeddings[0].values)
30
+ return out
31
+
32
+ def embed_query(self, text: str) -> list[float]:
33
+ resp = self._get_client().models.embed_content(
34
+ model=self.model, contents=[text],
35
+ config={"task_type": "RETRIEVAL_QUERY", "output_dimensionality": self.dim},
36
+ )
37
+ return resp.embeddings[0].values
38
+ ```
39
+
40
+ Rules:
41
+
42
+ - `task_type`: `RETRIEVAL_DOCUMENT` for indexing, `RETRIEVAL_QUERY` for search. Mixing them
43
+ degrades recall.
44
+ - Request `output_dimensionality` explicitly so the vector store collection width is fixed
45
+ by config, not by the model default.
46
+ - **Changing the embedding model changes the vector space.** Existing vectors become
47
+ incomparable → ship a `migrate_embeddings --recreate` script and mention it in the docs next
48
+ to the config key.
49
+ - Put the embedder behind an interface (`source = "gemini"`) so a swap to another provider is
50
+ one class.
51
+
52
+ ## LLM reranker (small candidate sets)
53
+
54
+ Ask the **chat** model (fast, cheap) to score candidates as JSON. Good up to ~20 passages;
55
+ beyond that use a dedicated reranker.
56
+
57
+ ```python
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}]}")
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.
64
+ prompt = "\n".join([f"Query: {query}", "Candidates:"] +
65
+ [f"[{i}] {c.text[:600]}" for i, c in enumerate(candidates)])
66
+
67
+ resp = client.models.generate_content(
68
+ model=settings.GEMINI_CHAT_MODEL,
69
+ contents=prompt,
70
+ config={
71
+ "system_instruction": _SYS,
72
+ "response_mime_type": "application/json",
73
+ "thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL}, # minimal on flash-lite
74
+ },
75
+ )
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
85
+ ```
86
+
87
+ Rules:
88
+
89
+ - Skip the call for 0–1 candidates.
90
+ - On any exception or empty scores → return the input order (`candidates[:top_n]`), log it.
91
+ - Truncate passage previews (~600 chars) — reranking must stay sub-second on the chat path.
92
+ - Voice forces the fast retrieval profile (no LLM rerank) — latency matters more than
93
+ precision when someone is listening.
@@ -0,0 +1,157 @@
1
+ ---
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 (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
+ license: MIT
5
+ metadata:
6
+ author: HoangThang
7
+ version: '1.0.0'
8
+ ---
9
+
10
+ # Gemini Integration
11
+
12
+ Rules for wiring Google Gemini into a project. Read this before touching any code that
13
+ imports `google.genai` / `@google/genai` or reads a `GEMINI_*` setting.
14
+
15
+ ## When to trigger
16
+
17
+ - Adding or editing Gemini calls (chat, generate, embed, TTS, Live)
18
+ - Changing a `GEMINI_*` model / env key
19
+ - Building voice chat, function calling / tools, RAG embeddings, PDF extraction
20
+ - User says **"gemini"**, **"live api"**, **"function calling"**, **"embedding"**, **"voice"**
21
+ - Debugging: 400 on request config, socket closed 1007, "connecting…" forever, empty text chunks
22
+
23
+ ## Detail files — load ONLY what the task needs
24
+
25
+ | File | Load when |
26
+ |---|---|
27
+ | `TEXT-CHAT.md` | Server-side chat session, streaming to SSE, tool loop |
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, async (3.8) / sync (3.1) tool calls, 2.5 → 3.1 → 3.8 differences |
30
+ | `RAG-EMBEDDING.md` | Embeddings for vector search + LLM reranker |
31
+ | `TROUBLESHOOTING.md` | An error code or a hang you need to map to a cause |
32
+
33
+ ## 1. One model per job — all via config keys
34
+
35
+ Never hardcode a model id in business code. Read it from settings so a box can pin or
36
+ roll back via `.env` without a deploy.
37
+
38
+ | Use case | Default model | Config key | SDK |
39
+ |---|---|---|---|
40
+ | Text chat, summary, LLM rerank | `gemini-3.5-flash-lite` | `GEMINI_CHAT_MODEL` | `google-genai` (Python) |
41
+ | Agent / Q&A generation, PDF extract | `gemini-3.8-flash` | `GEMINI_GENERATE_MODEL` | `google-genai` (Python) |
42
+ | TTS sample clips | `gemini-2.5-flash-preview-tts` | `GEMINI_TTS_MODEL` | `google-genai` (Python) |
43
+ | Embedding (RAG) | `gemini-embedding-2` | `GEMINI_EMBEDDING_MODEL` | `google-genai` (Python) |
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
+
47
+ - Cheap/fast model for anything on the interactive path (chat, rerank, summary).
48
+ - Bigger model only for offline / admin generation and document extraction.
49
+ - Every model key gets a documented **rollback value** (see `TROUBLESHOOTING.md`).
50
+ - `.env` on a server is usually NOT overwritten by deploy — a pinned `GEMINI_*` there wins over
51
+ code defaults. Expose the live model on a health/token endpoint so it can be verified.
52
+
53
+ ```python
54
+ # config.py (pydantic-settings style)
55
+ GEMINI_API_KEY: str = ""
56
+ GEMINI_CHAT_MODEL: str = "gemini-3.5-flash-lite"
57
+ GEMINI_CHAT_THINKING_LEVEL: str = "minimal" # 3.5 Flash-Lite default + fastest; 3.7/3.8 Flash reject it → "low"
58
+ GEMINI_GENERATE_MODEL: str = "gemini-3.8-flash"
59
+ GEMINI_LIVE_MODEL: str = "gemini-3.8-live" # rollback: gemini-3.1-flash-live-preview (sync tools)
60
+ GEMINI_TTS_MODEL: str = "gemini-2.5-flash-preview-tts"
61
+ GEMINI_EMBEDDING_MODEL: str = "gemini-embedding-2"
62
+ EMBEDDING_DIM: int = 768
63
+ ```
64
+
65
+ ## 2. Client setup
66
+
67
+ - Python: `google-genai>=2.0.0` for 3.5+ models (thought signatures in multi-turn tool calls).
68
+ JS: `@google/genai` (browser, Live only — the API key never ships to the browser).
69
+ - **Singleton client**, lazily created, SDK imported inside the function so the module loads
70
+ without the SDK installed in tests:
71
+
72
+ ```python
73
+ _client = None
74
+
75
+ def get_gemini_client():
76
+ global _client
77
+ if not settings.GEMINI_API_KEY:
78
+ return None # → echo stub mode
79
+ if _client is None:
80
+ from google import genai
81
+ _client = genai.Client(api_key=settings.GEMINI_API_KEY)
82
+ return _client
83
+ ```
84
+
85
+ - Live ephemeral tokens need `http_options={"api_version": "v1alpha"}` on a separate client.
86
+
87
+ ## 3. Echo stub mode — mandatory
88
+
89
+ When `GEMINI_API_KEY` is empty the app must still boot and the UI must still be testable:
90
+
91
+ - Text chat returns `[Echo] {message}` through the same SSE events.
92
+ - Voice token endpoint returns `{"token": "stub-token-no-api-key", ...}` (won't connect).
93
+ - Embedding / rerank / TTS raise a clear `RuntimeError("GEMINI_API_KEY not set")` — never a
94
+ silent empty result.
95
+
96
+ ## 4. CRITICAL — Gemini 3.x request rules
97
+
98
+ Apply to every `generate_content` / `chats.create` / `embed_content` on 3.5+ / 3.8:
99
+
100
+ - **`thinking_budget` is NOT supported.** Use `thinking_config={"thinking_level": ...}`.
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`).
105
+ - **Do NOT send** `temperature`, `top_p`, `top_k`, `candidate_count` — deprecated on 3.x.
106
+ - Every `FunctionResponse` **must carry `id` + `name`**, or the next turn is rejected.
107
+ - **Accumulate function calls across ALL stream chunks** — parallel calls can span chunks;
108
+ a call left without a response breaks the session.
109
+ - Send **all** function responses of a turn in **ONE** `send_message_stream(parts)`. One call per
110
+ response only streams the reply to the last one and silently drops the rest.
111
+ - A chunk may contain only function calls and no text — wrap `chunk.text` in a safe getter.
112
+ - JSON output: `response_mime_type="application/json"` + still parse defensively (regex the
113
+ first `{...}` on failure).
114
+
115
+ ## 5. Function calling (server-side tools)
116
+
117
+ - Declare tools once (`TOOL_DEFINITIONS`) in Gemini schema form (`"type": "OBJECT"`,
118
+ `"STRING"`). Share the same list between text chat and Live so both channels have identical
119
+ capabilities.
120
+ - Tools are executed by **your backend**, never inside the model prompt. For Live, the browser
121
+ receives the `toolCall`, POSTs to your `/api/tools/execute`, then `sendToolResponse`.
122
+ - Tool descriptions are prompts: say **when** to call it and what it returns.
123
+ - Always ship an `end_conversation`-style tool if the model may close a session, and handle it
124
+ after the farewell turn (see `LIVE-VOICE.md`).
125
+ - A tool that throws must still answer with `{"error": "..."}` — a missing response makes the
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.
133
+
134
+ ## 6. Security
135
+
136
+ - API key only on the server, sent via header (`x-goog-api-key`) — never `?key=` in a URL
137
+ (lands in access logs).
138
+ - Browser gets a **single-use ephemeral token** constrained to model + system prompt + tools
139
+ + voice config; expire ~30 min, new-session window ~2 min.
140
+ - Public token endpoints must validate the resource (agent id, feature flag) **before** minting
141
+ a token or creating any DB row — otherwise unauthenticated callers can spend your quota.
142
+ - Log the model + voice on every token mint so a "wrong voice / wrong model" report is
143
+ traceable.
144
+
145
+ ## 7. Docs — what to record (vibe-docs)
146
+
147
+ After integrating or changing Gemini usage, update `docs/09_integrations/gemini.md`
148
+ (`_summary.md` + MAP.md line as usual) with:
149
+
150
+ 1. **Models table** (use case → model → config key → SDK) and the rollback value per key
151
+ 2. Dated "what changed" notes per model bump (e.g. rules that started failing)
152
+ 3. Tools table (name → description)
153
+ 4. Live differences handled in code (only if voice is used)
154
+ 5. Echo stub behaviour
155
+
156
+ Keep the sections chronological with a date header — model migrations are the #1 thing the
157
+ next session needs to know.
@@ -0,0 +1,133 @@
1
+ # Text Chat (server-side, streaming + tools)
2
+
3
+ Backend owns the chat session. Client only sees SSE events.
4
+
5
+ ## Flow
6
+
7
+ ```
8
+ POST /api/chat/session → client.chats.create(system_instruction, tools, thinking) → session_id
9
+ POST /api/chat/message → chat.send_message_stream(text) → SSE: text* | function_calls | done
10
+ (server executes tools)
11
+ POST /api/chat/tool → chat.send_message_stream(parts) → SSE: text* | function_calls | done
12
+ ```
13
+
14
+ Loop `message → function_calls → tool → …` until a turn ends with no function calls.
15
+
16
+ ## Create the session
17
+
18
+ ```python
19
+ chat = client.chats.create(
20
+ model=settings.GEMINI_CHAT_MODEL,
21
+ config={
22
+ "system_instruction": system_instruction,
23
+ "tools": [{"function_declarations": TOOL_DEFINITIONS}] if TOOL_DEFINITIONS else [],
24
+ "thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL},
25
+ # NO temperature / top_p / top_k / candidate_count on 3.x
26
+ },
27
+ )
28
+ ```
29
+
30
+ - The chats API keeps history automatically — do not re-send previous turns.
31
+ - Keep the `chat` object in an in-memory store keyed by `session_id` (with TTL). Persist the
32
+ transcript to your DB separately; the Gemini object is not serializable.
33
+ - Client is `None` (no API key) → still create a session id, reply `[Echo] ...`.
34
+
35
+ ## Stream a message
36
+
37
+ ```python
38
+ def _safe_get_text(chunk) -> str:
39
+ try:
40
+ return chunk.text or "" # raises / empty on function-call-only chunks
41
+ except Exception:
42
+ return ""
43
+
44
+ def _extract_function_calls(chunk) -> list[dict] | None:
45
+ try:
46
+ calls = chunk.function_calls
47
+ if calls:
48
+ return [{"id": getattr(fc, "id", "") or "", "name": fc.name, "args": fc.args} for fc in calls]
49
+ except Exception:
50
+ pass
51
+ return None
52
+
53
+ async def stream_chat_message(session_id: str, message: str):
54
+ chat = store.get(session_id)
55
+ if chat is None:
56
+ yield {"event": "text", "data": json.dumps({"text": f"[Echo] {message}"})}
57
+ yield {"event": "done", "data": "{}"}
58
+ return
59
+
60
+ stream = chat.send_message_stream(message)
61
+ pending_calls = None
62
+ full = []
63
+ for chunk in stream:
64
+ text = _safe_get_text(chunk)
65
+ if text:
66
+ full.append(text)
67
+ yield {"event": "text", "data": json.dumps({"text": text})}
68
+ calls = _extract_function_calls(chunk)
69
+ if calls:
70
+ # Accumulate: parallel calls can span chunks; 3.x rejects the next turn
71
+ # unless EVERY call gets a FunctionResponse (id + name).
72
+ pending_calls = (pending_calls or []) + calls
73
+
74
+ if pending_calls:
75
+ yield {"event": "function_calls", "data": json.dumps({"calls": pending_calls})}
76
+ yield {"event": "done", "data": "{}"}
77
+ ```
78
+
79
+ ## Return tool results — ONE call, all responses
80
+
81
+ ```python
82
+ from google.genai import types
83
+
84
+ parts = [
85
+ types.Part(function_response=types.FunctionResponse(
86
+ id=fr["id"], name=fr["name"], response=fr["response"],
87
+ ))
88
+ for fr in function_responses
89
+ ]
90
+ stream = chat.send_message_stream(parts) # same chunk loop as above
91
+ ```
92
+
93
+ - Sending one `send_message_stream` per response only streams the reply to the LAST one.
94
+ - `response` is a dict (`{"result": ...}` or `{"error": "..."}`) — never a bare string.
95
+
96
+ ## SSE contract (keep it stable for the FE)
97
+
98
+ | event | data |
99
+ |---|---|
100
+ | `text` | `{"text": "..."}` — append to the current assistant bubble |
101
+ | `function_calls` | `{"calls": [{"id","name","args"}]}` — FE calls `/api/chat/tool` after server executes |
102
+ | `error` | `{"message": "..."}` |
103
+ | `done` | `{}` |
104
+
105
+ Wrap the whole generator in `try/except` → `error` event; log with `logger.exception`.
106
+
107
+ ## Summaries and other side calls
108
+
109
+ Use `generate_content` on the **chat** model with a tight system instruction, same
110
+ `thinking_config`, and return `""` on any failure — a summary must never break a conversation.
111
+
112
+ ```python
113
+ resp = client.models.generate_content(
114
+ model=settings.GEMINI_CHAT_MODEL,
115
+ contents=conversation_text,
116
+ config={
117
+ "system_instruction": "Summarize in 1-2 sentences, same language as the conversation.",
118
+ "thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL},
119
+ },
120
+ )
121
+ ```
122
+
123
+ ## System prompt — knowledge via tool, not stuffing
124
+
125
+ If the agent has a knowledge base, do NOT paste it into the prompt. Describe what is
126
+ available and **mandate** a `search_knowledge_base` tool call before answering business
127
+ questions. Build that block in ONE shared function and reuse it for text chat and voice, so
128
+ both channels reach the same knowledge.
129
+
130
+ ## Timing
131
+
132
+ Log time-to-first-chunk and total per call (`gemini.chat.send TTFC` / `TOTAL`, with
133
+ `tool_call=bool`). This is how you notice a model bump made chat slower.