sisyo 1.5.0 → 1.6.0
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/LICENSE +16 -16
- package/README.md +161 -139
- package/bin/sisyo.js +186 -78
- package/package.json +1 -1
- package/templates/.claude/rules/docs.md +19 -19
- package/templates/.claude/skills/gemini-integration/GENERATE.md +111 -0
- package/templates/.claude/skills/gemini-integration/LIVE-VOICE.md +156 -0
- package/templates/.claude/skills/gemini-integration/RAG-EMBEDDING.md +83 -0
- package/templates/.claude/skills/gemini-integration/SKILL.md +149 -0
- package/templates/.claude/skills/gemini-integration/TEXT-CHAT.md +133 -0
- package/templates/.claude/skills/gemini-integration/TROUBLESHOOTING.md +53 -0
- package/templates/.claude/skills/html-docs/SKILL.md +207 -160
- package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
- package/templates/.claude/skills/vibe-docs/SKILL.md +242 -242
- package/templates/SISYO.md +37 -37
- package/templates/docs/99_progress/features.md +7 -7
- package/templates/docs/99_progress/handoff.md +19 -19
- package/templates/docs/99_progress/todo.md +15 -15
- package/templates/docs/MAP.md +26 -26
|
@@ -0,0 +1,83 @@
|
|
|
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 candidate passages, score each "
|
|
59
|
+
"0.0–1.0 for relevance. Return ONLY valid JSON: {\"scores\": [{\"id\": \"...\", \"score\": 0.85}]}")
|
|
60
|
+
|
|
61
|
+
prompt = "\n".join([f"Query: {query}", "Candidates:"] +
|
|
62
|
+
[f"- id: {c.id}\n text: {c.text[:600]}" for c in candidates])
|
|
63
|
+
|
|
64
|
+
resp = client.models.generate_content(
|
|
65
|
+
model=settings.GEMINI_CHAT_MODEL,
|
|
66
|
+
contents=prompt,
|
|
67
|
+
config={
|
|
68
|
+
"system_instruction": _SYS,
|
|
69
|
+
"response_mime_type": "application/json",
|
|
70
|
+
"thinking_config": {"thinking_level": settings.GEMINI_CHAT_THINKING_LEVEL},
|
|
71
|
+
},
|
|
72
|
+
)
|
|
73
|
+
scores = {s["id"]: float(s["score"]) for s in _parse_json(resp.text or "").get("scores", [])
|
|
74
|
+
if isinstance(s, dict) and isinstance(s.get("id"), str)}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Rules:
|
|
78
|
+
|
|
79
|
+
- Skip the call for 0–1 candidates.
|
|
80
|
+
- On any exception or empty scores → return the input order (`candidates[:top_n]`), log it.
|
|
81
|
+
- Truncate passage previews (~600 chars) — reranking must stay sub-second on the chat path.
|
|
82
|
+
- Voice forces the fast retrieval profile (no LLM rerank) — latency matters more than
|
|
83
|
+
precision when someone is listening.
|
|
@@ -0,0 +1,149 @@
|
|
|
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 (sync tool calls on 3.1, sendRealtimeInput audio, PCM 16k in / 24k out), embeddings (one text per call, Matryoshka dims, re-embed on model change), LLM reranker, JSON mode, google_search / url_context grounding, PDF extract, TTS. Triggers on any Gemini / genai / GEMINI_* code, voice chat, RAG embedding, or user saying 'gemini', 'live api', 'function calling'."
|
|
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, sync tool calls |
|
|
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.1-flash-live-preview` | `GEMINI_LIVE_MODEL` | `@google/genai` (JS, browser) |
|
|
45
|
+
| Chat thinking level | `low` | `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 = "low" # low | medium | high (3.5+/3.8; minimal is 3.1-Live only)
|
|
58
|
+
GEMINI_GENERATE_MODEL: str = "gemini-3.8-flash"
|
|
59
|
+
GEMINI_LIVE_MODEL: str = "gemini-3.1-flash-live-preview"
|
|
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
|
+
3.8 Flash rejects `thinking_level="minimal"` with 400 — use `low`. `minimal` is valid only
|
|
102
|
+
on 3.1 Live. `medium` is noticeably slower for a support chat.
|
|
103
|
+
- **Do NOT send** `temperature`, `top_p`, `top_k`, `candidate_count` — deprecated on 3.x.
|
|
104
|
+
- Every `FunctionResponse` **must carry `id` + `name`**, or the next turn is rejected.
|
|
105
|
+
- **Accumulate function calls across ALL stream chunks** — parallel calls can span chunks;
|
|
106
|
+
a call left without a response breaks the session.
|
|
107
|
+
- Send **all** function responses of a turn in **ONE** `send_message_stream(parts)`. One call per
|
|
108
|
+
response only streams the reply to the last one and silently drops the rest.
|
|
109
|
+
- A chunk may contain only function calls and no text — wrap `chunk.text` in a safe getter.
|
|
110
|
+
- JSON output: `response_mime_type="application/json"` + still parse defensively (regex the
|
|
111
|
+
first `{...}` on failure).
|
|
112
|
+
|
|
113
|
+
## 5. Function calling (server-side tools)
|
|
114
|
+
|
|
115
|
+
- Declare tools once (`TOOL_DEFINITIONS`) in Gemini schema form (`"type": "OBJECT"`,
|
|
116
|
+
`"STRING"`). Share the same list between text chat and Live so both channels have identical
|
|
117
|
+
capabilities.
|
|
118
|
+
- Tools are executed by **your backend**, never inside the model prompt. For Live, the browser
|
|
119
|
+
receives the `toolCall`, POSTs to your `/api/tools/execute`, then `sendToolResponse`.
|
|
120
|
+
- Tool descriptions are prompts: say **when** to call it and what it returns.
|
|
121
|
+
- Always ship an `end_conversation`-style tool if the model may close a session, and handle it
|
|
122
|
+
after the farewell turn (see `LIVE-VOICE.md`).
|
|
123
|
+
- A tool that throws must still answer with `{"error": "..."}` — a missing response makes the
|
|
124
|
+
model wait forever.
|
|
125
|
+
|
|
126
|
+
## 6. Security
|
|
127
|
+
|
|
128
|
+
- API key only on the server, sent via header (`x-goog-api-key`) — never `?key=` in a URL
|
|
129
|
+
(lands in access logs).
|
|
130
|
+
- Browser gets a **single-use ephemeral token** constrained to model + system prompt + tools
|
|
131
|
+
+ voice config; expire ~30 min, new-session window ~2 min.
|
|
132
|
+
- Public token endpoints must validate the resource (agent id, feature flag) **before** minting
|
|
133
|
+
a token or creating any DB row — otherwise unauthenticated callers can spend your quota.
|
|
134
|
+
- Log the model + voice on every token mint so a "wrong voice / wrong model" report is
|
|
135
|
+
traceable.
|
|
136
|
+
|
|
137
|
+
## 7. Docs — what to record (vibe-docs)
|
|
138
|
+
|
|
139
|
+
After integrating or changing Gemini usage, update `docs/09_integrations/gemini.md`
|
|
140
|
+
(`_summary.md` + MAP.md line as usual) with:
|
|
141
|
+
|
|
142
|
+
1. **Models table** (use case → model → config key → SDK) and the rollback value per key
|
|
143
|
+
2. Dated "what changed" notes per model bump (e.g. rules that started failing)
|
|
144
|
+
3. Tools table (name → description)
|
|
145
|
+
4. Live differences handled in code (only if voice is used)
|
|
146
|
+
5. Echo stub behaviour
|
|
147
|
+
|
|
148
|
+
Keep the sections chronological with a date header — model migrations are the #1 thing the
|
|
149
|
+
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.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Troubleshooting
|
|
2
|
+
|
|
3
|
+
Symptom → cause → fix. Check the **live** model first: `.env` on the server overrides code
|
|
4
|
+
defaults and deploy does not rewrite it. Verify via the token / health endpoint `model` field.
|
|
5
|
+
|
|
6
|
+
## Request errors (400)
|
|
7
|
+
|
|
8
|
+
| Symptom | Cause | Fix |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| 400 mentioning `thinking_budget` | 3.5+/3.8 dropped it | `thinking_config={"thinking_level": "low"}` |
|
|
11
|
+
| 400 `thinking_level=minimal` | Only 3.1 Live accepts `minimal` | Use `low` on 3.5+/3.8 |
|
|
12
|
+
| 400 on `temperature` / `top_p` / `top_k` / `candidate_count` | Deprecated on 3.x | Remove them |
|
|
13
|
+
| 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
|
+
| Multi-turn tool calls fail after a model bump | Old `google-genai` without thought signatures | `google-genai>=2.0.0` |
|
|
15
|
+
|
|
16
|
+
## Chat behaviour
|
|
17
|
+
|
|
18
|
+
| Symptom | Cause | Fix |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| Reply ignores earlier tool results | One `send_message_stream` per response | Send all responses as ONE `parts` list |
|
|
21
|
+
| `chunk.text` raises / empty | Chunk carries only function calls | `_safe_get_text()` wrapper |
|
|
22
|
+
| Chat got slower after bump | `thinking_level=medium` or generate model used on chat path | `low`; chat/rerank on flash-lite |
|
|
23
|
+
| `[Echo] …` replies in prod | `GEMINI_API_KEY` empty on that box | Set the key; echo is the stub mode |
|
|
24
|
+
| Embeddings: N chunks → 1 vector | Passed a list to `contents` | Embed one text per call |
|
|
25
|
+
| Search results nonsense after embedding model change | Vector space changed | Re-embed everything (`--recreate`) |
|
|
26
|
+
|
|
27
|
+
## Live voice
|
|
28
|
+
|
|
29
|
+
| Symptom | Cause | Fix |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| "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 }` |
|
|
33
|
+
| Token endpoint 402 | Billing / Live API not enabled for the key | Enable in AI Studio; log exception on mint |
|
|
34
|
+
| 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
|
+
| Token endpoint 403 | `voice_enabled` false on agent or plan | Expected — hide the voice toggle in the UI |
|
|
36
|
+
| Connected but silent | `AudioContext` suspended (not from a user gesture) | `await ctx.resume()` after creating it |
|
|
37
|
+
| Wrong voice every other session | FE didn't pass `speechConfig` on `connect` | Pass `voice_name` from the token response |
|
|
38
|
+
| Model goes silent after a tool call | Sync function calling; a tool threw and never answered | Respond `{ error }` for failed tools, all in one `sendToolResponse` |
|
|
39
|
+
| No farewell, UI stuck after `end_conversation` | Disconnected inside the tool handler | Mute mic, send response, wait `turnComplete` + audio drain, then close |
|
|
40
|
+
| Greets in the wrong language | Greeting text sent as a user turn → model mirrors it | Send a `[Session start]` control turn; put the greeting rule in the system prompt |
|
|
41
|
+
| Only first audio part plays | 3.1 sends multiple parts per event | Loop over all `parts` |
|
|
42
|
+
| Mid-session text ignored on 3.1 | Used `sendClientContent` | `sendRealtimeInput({ text })` |
|
|
43
|
+
| Voice sample button slow / times out | TTS on demand | Pre-generate at startup, cache on S3, key by version |
|
|
44
|
+
|
|
45
|
+
## Rollback values
|
|
46
|
+
|
|
47
|
+
| Key | Rollback |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `GEMINI_CHAT_MODEL` | `gemini-3.1-flash-lite-preview` (`low` valid there too) |
|
|
50
|
+
| `GEMINI_LIVE_MODEL` | `gemini-2.5-flash-native-audio-preview-12-2025` (async tools, `thinking_budget`, `media` field) |
|
|
51
|
+
| `GEMINI_EMBEDDING_MODEL` | Previous model **plus** full re-embed — no hot rollback |
|
|
52
|
+
|
|
53
|
+
Always record the rollback + the date of the bump in `docs/09_integrations/gemini.md`.
|