chintakapp Claude Sonnet 5.5 commited on
Commit
81e6c3d
·
1 Parent(s): a30e9f9

Robot: Gemini Live hears and answers in one call (/robot/talk)

Browse files

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

brain/config.py CHANGED
@@ -53,6 +53,16 @@ EMBEDDING_DIMENSIONS = 768
53
 
54
  DEFAULT_TTS_MODEL = "gemini-2.5-flash-preview-tts"
55
  DEFAULT_TTS_VOICE = "Kore"
 
 
 
 
 
 
 
 
 
 
56
  #: Blueprint 9.2: cap the TTS input. Long replies are for reading, not for listening to.
57
  TTS_MAX_CHARS = 800
58
  TTS_SAMPLE_RATE = 24_000
@@ -121,6 +131,8 @@ class Settings:
121
  fallback_models: tuple[str, ...] = DEFAULT_FALLBACK_MODELS
122
  embedding_model: str = DEFAULT_EMBEDDING_MODEL
123
  tts_model: str = DEFAULT_TTS_MODEL
 
 
124
  temperature: float = TEMPERATURE_DEFAULT
125
  style_bank_enabled: bool = True
126
 
 
53
 
54
  DEFAULT_TTS_MODEL = "gemini-2.5-flash-preview-tts"
55
  DEFAULT_TTS_VOICE = "Kore"
56
+
57
+ # Gemini Live (native audio): hears and speaks in one connection, with its own quota.
58
+ DEFAULT_LIVE_MODEL = "gemini-3.8-live"
59
+ DEFAULT_LIVE_VOICE = "Aoede"
60
+ LIVE_INPUT_RATE = 16_000
61
+ LIVE_OUTPUT_RATE = 24_000
62
+ GEMINI_LIVE_URL = (
63
+ "wss://generativelanguage.googleapis.com/ws/"
64
+ "google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent"
65
+ )
66
  #: Blueprint 9.2: cap the TTS input. Long replies are for reading, not for listening to.
67
  TTS_MAX_CHARS = 800
68
  TTS_SAMPLE_RATE = 24_000
 
131
  fallback_models: tuple[str, ...] = DEFAULT_FALLBACK_MODELS
132
  embedding_model: str = DEFAULT_EMBEDDING_MODEL
133
  tts_model: str = DEFAULT_TTS_MODEL
134
+ live_model: str = DEFAULT_LIVE_MODEL
135
+ live_voice: str = DEFAULT_LIVE_VOICE
136
  temperature: float = TEMPERATURE_DEFAULT
137
  style_bank_enabled: bool = True
138
 
brain/deps.py CHANGED
@@ -15,6 +15,7 @@ from typing import Any
15
  from . import config
16
  from .auth import AuthConfig, AuthError, AuthService, User, Verifier
17
  from .llm.factory import build_router
 
18
  from .llm.groq_voice import GroqVoice
19
  from .llm.keys import KeyRing
20
  from .push.sender import PushSender, RecordingSender, VapidConfig, WebPushSender
@@ -45,6 +46,8 @@ class Deps:
45
  voice: Any = None
46
  #: Login, refresh and logout (``AuthService``). None in tests that never sign in.
47
  sessions: Any = None
 
 
48
 
49
  def authenticate(self, token: str) -> User:
50
  if self.dev:
@@ -138,6 +141,9 @@ def build(env: dict[str, str] | None = None) -> Deps:
138
  proactive_test_mode=_flag(env, "PROACTIVE_TEST_MODE"),
139
  voice=GroqVoice.from_env(env),
140
  sessions=AuthService(auth, store),
 
 
 
141
  )
142
 
143
 
 
15
  from . import config
16
  from .auth import AuthConfig, AuthError, AuthService, User, Verifier
17
  from .llm.factory import build_router
18
+ from .llm.gemini_live import GeminiLive
19
  from .llm.groq_voice import GroqVoice
20
  from .llm.keys import KeyRing
21
  from .push.sender import PushSender, RecordingSender, VapidConfig, WebPushSender
 
46
  voice: Any = None
47
  #: Login, refresh and logout (``AuthService``). None in tests that never sign in.
48
  sessions: Any = None
49
+ #: Gemini Live, for the robot's spoken turns. None without Gemini keys.
50
+ live: Any = None
51
 
52
  def authenticate(self, token: str) -> User:
53
  if self.dev:
 
141
  proactive_test_mode=_flag(env, "PROACTIVE_TEST_MODE"),
142
  voice=GroqVoice.from_env(env),
143
  sessions=AuthService(auth, store),
144
+ live=GeminiLive(KeyRing.from_env(env), settings)
145
+ if KeyRing.from_env(env).configured_slots()
146
+ else None,
147
  )
148
 
149
 
brain/llm/gemini_live.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gemini Live (native audio): one spoken turn, audio in and audio out, over a WebSocket.
2
+
3
+ The robot's old chain was recogniser -> Gemini -> voice, three things that could each disagree. This
4
+ is one: the recording goes in, Gemini listens to it itself (and says what it heard, so the log and
5
+ the follow-up memory have words), thinks, and answers in its own voice.
6
+
7
+ One turn per connection. The Live API is built for a long open conversation, but a turn-based robot
8
+ that sleeps between questions gains nothing from holding a socket open, and a fresh connection takes
9
+ about a second. The conversation so far goes in as text in the system prompt, which works the same
10
+ on every Live model.
11
+
12
+ Keys rotate exactly as Gemini's do (quota moves on to the next key, nothing else does). The key is
13
+ sent as a header, never in the URL, so it cannot land in a log.
14
+
15
+ Wire format (JSON, camelCase), as the official SDK sends it:
16
+
17
+ -> {"setup": {model, generationConfig, systemInstruction, inputAudioTranscription, ...}}
18
+ <- {"setupComplete": {}}
19
+ -> {"realtimeInput": {"audio": {"data": <base64 PCM>, "mimeType": "audio/pcm;rate=16000"}}}
20
+ -> {"realtimeInput": {"audioStreamEnd": true}}
21
+ <- {"serverContent": {"inputTranscription": {"text"}, "outputTranscription": {"text"},
22
+ "modelTurn": {"parts": [{"inlineData": {"data": <base64 PCM 24 kHz>}}]},
23
+ "turnComplete": true}}
24
+ """
25
+
26
+ import asyncio
27
+ import base64
28
+ import json
29
+ import time
30
+ from collections.abc import Callable
31
+ from dataclasses import dataclass
32
+ from typing import Any
33
+
34
+ import websockets
35
+ from websockets.exceptions import ConnectionClosed, InvalidStatus, WebSocketException
36
+
37
+ from .. import config
38
+ from .errors import LlmError, ModelUnavailable, QuotaExhausted, Rejected
39
+ from .keys import KeyRing
40
+ from .rotation import call_with_keys
41
+
42
+ #: Silence added after the recording, so the model hears that the speaker has finished.
43
+ TRAILING_SILENCE_SECONDS = 0.8
44
+ #: The longest one turn may take, connect to turn-complete.
45
+ TURN_TIMEOUT_SECONDS = 45
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class LiveTurn:
50
+ #: What Gemini heard, in the words it was said. Empty means there was no speech.
51
+ heard: str
52
+ #: What it answered, as text.
53
+ said: str
54
+ #: Its spoken answer: 16-bit little-endian mono PCM at 24 kHz.
55
+ pcm: bytes
56
+ model: str
57
+ ms: int
58
+
59
+
60
+ class GeminiLive:
61
+ def __init__(
62
+ self,
63
+ ring: KeyRing,
64
+ settings: config.Settings,
65
+ connect: Callable[..., Any] = websockets.connect,
66
+ ) -> None:
67
+ self.ring = ring
68
+ self.settings = settings
69
+ self._connect = connect
70
+
71
+ async def talk(self, system_prompt: str, pcm: bytes, *, voice: str | None = None) -> LiveTurn:
72
+ """One recording (16-bit mono PCM at 16 kHz) in, one spoken answer out."""
73
+ model = self.settings.live_model
74
+ chosen_voice = voice or self.settings.live_voice
75
+
76
+ async def call(key: str, model: str) -> LiveTurn:
77
+ return await self._turn(key, model, system_prompt, pcm, chosen_voice)
78
+
79
+ return await call_with_keys(self.ring, model, call)
80
+
81
+ async def _turn(
82
+ self, key: str, model: str, system_prompt: str, pcm: bytes, voice: str
83
+ ) -> LiveTurn:
84
+ started = time.monotonic()
85
+ setup = {
86
+ "setup": {
87
+ "model": f"models/{model}",
88
+ "generationConfig": {
89
+ "responseModalities": ["AUDIO"],
90
+ "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice}}},
91
+ },
92
+ "systemInstruction": {"parts": [{"text": system_prompt}]},
93
+ "inputAudioTranscription": {},
94
+ "outputAudioTranscription": {},
95
+ }
96
+ }
97
+ silence = bytes(int(config.LIVE_INPUT_RATE * 2 * TRAILING_SILENCE_SECONDS))
98
+ audio = base64.b64encode(pcm + silence).decode("ascii")
99
+ heard: list[str] = []
100
+ said: list[str] = []
101
+ spoken = bytearray()
102
+
103
+ try:
104
+ async with asyncio.timeout(TURN_TIMEOUT_SECONDS):
105
+ async with self._connect(
106
+ config.GEMINI_LIVE_URL,
107
+ additional_headers={"x-goog-api-key": key},
108
+ max_size=None,
109
+ ) as socket:
110
+ await socket.send(json.dumps(setup))
111
+ await self._wait_for(socket, "setupComplete")
112
+ mime = f"audio/pcm;rate={config.LIVE_INPUT_RATE}"
113
+ await socket.send(
114
+ json.dumps({"realtimeInput": {"audio": {"data": audio, "mimeType": mime}}})
115
+ )
116
+ await socket.send(json.dumps({"realtimeInput": {"audioStreamEnd": True}}))
117
+ async for raw in socket:
118
+ content = _decode(raw).get("serverContent") or {}
119
+ _collect(content, heard, said, spoken)
120
+ if content.get("turnComplete"):
121
+ break
122
+ except TimeoutError as exc:
123
+ raise Rejected(0, f"the Live turn took longer than {TURN_TIMEOUT_SECONDS}s") from exc
124
+ except InvalidStatus as exc:
125
+ raise _from_status(exc.response.status_code, str(exc)) from exc
126
+ except ConnectionClosed as exc:
127
+ raise _from_close(exc) from exc
128
+ except (WebSocketException, OSError) as exc:
129
+ raise Rejected(0, f"could not reach Gemini Live: {exc}") from exc
130
+
131
+ return LiveTurn(
132
+ heard="".join(heard).strip(),
133
+ said="".join(said).strip(),
134
+ pcm=bytes(spoken),
135
+ model=model,
136
+ ms=round((time.monotonic() - started) * 1000),
137
+ )
138
+
139
+ @staticmethod
140
+ async def _wait_for(socket: Any, key: str) -> None:
141
+ async for raw in socket:
142
+ if key in _decode(raw):
143
+ return
144
+ raise Rejected(0, f"Gemini Live closed before {key}")
145
+
146
+
147
+ def _decode(raw: str | bytes) -> dict[str, Any]:
148
+ """Live sends JSON as text or as UTF-8 bytes depending on the model."""
149
+ text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
150
+ try:
151
+ value = json.loads(text)
152
+ except ValueError:
153
+ return {}
154
+ return value if isinstance(value, dict) else {}
155
+
156
+
157
+ def _collect(content: dict[str, Any], heard: list[str], said: list[str], spoken: bytearray) -> None:
158
+ if text := (content.get("inputTranscription") or {}).get("text"):
159
+ heard.append(text)
160
+ if text := (content.get("outputTranscription") or {}).get("text"):
161
+ said.append(text)
162
+ for part in (content.get("modelTurn") or {}).get("parts") or []:
163
+ data = (part.get("inlineData") or {}).get("data")
164
+ if data:
165
+ spoken += base64.b64decode(data)
166
+
167
+
168
+ def _from_status(status: int, message: str) -> LlmError:
169
+ """The WebSocket handshake itself was refused."""
170
+ if status == 429:
171
+ return QuotaExhausted(status, message)
172
+ if status == 404:
173
+ return ModelUnavailable(status, message)
174
+ return Rejected(status, message)
175
+
176
+
177
+ def _from_close(exc: ConnectionClosed) -> LlmError:
178
+ """The server closed the socket. Code 1008 carries the reason; quota is the only one that
179
+ another key can fix."""
180
+ close = exc.rcvd
181
+ code, reason = (close.code, close.reason) if close else (0, str(exc))
182
+ lowered = (reason or "").lower()
183
+ if any(word in lowered for word in ("quota", "exhausted", "rate limit", "resource")):
184
+ return QuotaExhausted(code, reason)
185
+ if "not found" in lowered or "not supported" in lowered:
186
+ return ModelUnavailable(code, reason)
187
+ return Rejected(code, reason or "Gemini Live closed the connection")
brain/persona/prova.py CHANGED
@@ -629,6 +629,7 @@ you did not understand.
629
  You are an AI and can say so plainly if asked. Never claim to be a person.
630
  """
631
 
 
632
  ROBOT_ASSISTANT_GREETING = (
633
  "(Someone has just switched you on. Say a very short, friendly hello in English.)"
634
  )
 
629
  You are an AI and can say so plainly if asked. Never claim to be a person.
630
  """
631
 
632
+
633
  ROBOT_ASSISTANT_GREETING = (
634
  "(Someone has just switched you on. Say a very short, friendly hello in English.)"
635
  )
brain/routes/robot_ask.py CHANGED
@@ -1,17 +1,26 @@
1
- """``POST /robot/ask`` and ``/robot/hello``: the robot's plain Gemini assistant, text in, text out.
 
2
 
3
- The Pi does the listening and the speaking itself, so these routes carry only text. They touch
4
- no database and no memory — see ``services/assistant.py`` — and are open to the same callers as
5
- the other robot routes (``RobotDep``: an access token or a device token).
 
6
  """
7
 
 
 
8
  import logging
9
  import uuid
 
 
10
 
11
- from fastapi import APIRouter, HTTPException
12
  from pydantic import BaseModel, Field
13
 
 
14
  from ..llm.errors import LlmError
 
 
15
  from ..llm.metered import Metered
16
  from ..services import assistant
17
  from ..voice import speakable
@@ -65,3 +74,80 @@ async def hello(user: RobotDep, deps: DepsDep) -> dict:
65
  finally:
66
  await deps.chat.flush_usage(user.id, meter, deps.chat.local_now(deps.chat.zone()).date())
67
  return {"reply": speakable(reply)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The robot's plain Gemini assistant: ``/robot/talk`` (a recording in, a spoken answer out),
2
+ and ``/robot/ask`` and ``/robot/hello`` (text in, text out, the backup when Live is unavailable).
3
 
4
+ ``/robot/talk`` is the main one: Gemini Live listens to the recording and answers in its own
5
+ voice, in one call. None of these touch the database or any memory — see
6
+ ``services/assistant.py`` — and all are open to the same callers as the other robot routes
7
+ (``RobotDep``: an access token or a device token).
8
  """
9
 
10
+ import base64
11
+ import io
12
  import logging
13
  import uuid
14
+ import wave
15
+ from typing import Annotated
16
 
17
+ from fastapi import APIRouter, HTTPException, Query, Request
18
  from pydantic import BaseModel, Field
19
 
20
+ from .. import config
21
  from ..llm.errors import LlmError
22
+ from ..llm.gemini import pcm_to_wav
23
+ from ..llm.groq_voice import STT_MAX_BYTES
24
  from ..llm.metered import Metered
25
  from ..services import assistant
26
  from ..voice import speakable
 
74
  finally:
75
  await deps.chat.flush_usage(user.id, meter, deps.chat.local_now(deps.chat.zone()).date())
76
  return {"reply": speakable(reply)}
77
+
78
+
79
+ def _pcm_16k_mono(wav_bytes: bytes) -> bytes:
80
+ """The samples of a 16 kHz, 16-bit, mono WAV. Anything else is refused: Gemini Live is told the
81
+ rate, and sending it a different one would be heard as the wrong pitch and speed."""
82
+ try:
83
+ with wave.open(io.BytesIO(wav_bytes)) as clip:
84
+ if (clip.getframerate(), clip.getnchannels(), clip.getsampwidth()) != (
85
+ config.LIVE_INPUT_RATE,
86
+ 1,
87
+ 2,
88
+ ):
89
+ raise ValueError("needs 16 kHz, 16-bit, mono")
90
+ return clip.readframes(clip.getnframes())
91
+ except (wave.Error, EOFError, ValueError) as exc:
92
+ raise HTTPException(
93
+ 415, detail={"code": "bad_audio", "message": f"send a 16 kHz mono WAV: {exc}"}
94
+ ) from exc
95
+
96
+
97
+ @router.post("/talk")
98
+ async def talk(
99
+ request: Request,
100
+ user: RobotDep,
101
+ deps: DepsDep,
102
+ session_id: Annotated[str | None, Query(alias="sessionId", max_length=64)] = None,
103
+ ) -> dict:
104
+ """A recording in (the raw WAV as the body); what was said, and the spoken answer, out.
105
+
106
+ Gemini Live listens and answers in one call, so there is no separate recogniser to disagree
107
+ with it. ``heard`` is empty — and nothing is spoken — when the recording had no speech in it
108
+ (a click, a tap), so the robot keeps quiet instead of answering the keyboard.
109
+ """
110
+ if deps.live is None:
111
+ raise HTTPException(
112
+ 503, detail={"code": "live_unavailable", "message": "no Gemini key for Live"}
113
+ )
114
+ mime = request.headers.get("content-type", "audio/wav").split(";")[0].strip()
115
+ if not mime.startswith("audio/"):
116
+ raise HTTPException(415, detail={"code": "bad_type", "message": "send audio"})
117
+ declared = request.headers.get("content-length", "")
118
+ if declared.isdigit() and int(declared) > STT_MAX_BYTES:
119
+ raise HTTPException(413, detail={"code": "too_large", "message": "recording too long"})
120
+ body = bytearray()
121
+ async for chunk in request.stream():
122
+ body += chunk
123
+ if len(body) > STT_MAX_BYTES:
124
+ raise HTTPException(413, detail={"code": "too_large", "message": "recording too long"})
125
+ if not body:
126
+ raise HTTPException(422, detail={"code": "empty", "message": "no audio"})
127
+ pcm = _pcm_16k_mono(bytes(body))
128
+
129
+ session_id = session_id or str(uuid.uuid4())
130
+ key = f"{user.id}:{session_id}"
131
+ owner = deps.chat.settings.user_name
132
+ now = deps.chat.local_now(deps.chat.zone())
133
+ prompt = assistant.live_prompt(owner, now, conversations.history(key))
134
+ meter = Metered(deps.llm)
135
+ try:
136
+ turn = await deps.live.talk(prompt, pcm)
137
+ except LlmError as exc:
138
+ log.info("robot talk unavailable: %s", exc)
139
+ raise HTTPException(503, detail={"code": "unavailable", "message": str(exc)}) from exc
140
+ meter.count("chat", turn.model)
141
+ await deps.chat.flush_usage(user.id, meter, now.date())
142
+
143
+ if not turn.heard or not turn.pcm:
144
+ return {"heard": "", "reply": "", "audio": None, "sessionId": session_id}
145
+ conversations.add(key, turn.heard, turn.said or "(spoke)")
146
+ wav = pcm_to_wav(turn.pcm, config.LIVE_OUTPUT_RATE)
147
+ return {
148
+ "heard": turn.heard,
149
+ "reply": turn.said,
150
+ "audio": base64.b64encode(wav).decode("ascii"),
151
+ "sessionId": session_id,
152
+ "ms": turn.ms,
153
+ }
brain/services/assistant.py CHANGED
@@ -13,6 +13,7 @@ sense, is kept in this process's memory only, per session id, and forgotten afte
13
 
14
  import time
15
  from collections import OrderedDict
 
16
  from datetime import datetime
17
 
18
  from .. import config
@@ -87,3 +88,21 @@ async def greet(llm, *, owner: str, now: datetime) -> str:
87
  max_output_tokens=96,
88
  )
89
  return reply.text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  import time
15
  from collections import OrderedDict
16
+ from collections.abc import Sequence
17
  from datetime import datetime
18
 
19
  from .. import config
 
88
  max_output_tokens=96,
89
  )
90
  return reply.text.strip()
91
+
92
+
93
+ def live_prompt(owner: str, now: datetime, history: Sequence[Message]) -> str:
94
+ """The system prompt for a spoken turn: the usual one, plus the conversation so far.
95
+
96
+ The Live models take their context as text in the prompt, which works the same on every one
97
+ of them; the question itself arrives as the audio.
98
+ """
99
+ prompt = system_prompt(owner, now)
100
+ if not history:
101
+ return prompt
102
+ lines = [f"{'You' if m.role == 'model' else 'They'}: {m.text}" for m in history]
103
+ return (
104
+ prompt
105
+ + "\n\nThe conversation so far in this session (the new question is the audio you will "
106
+ + "hear next):\n"
107
+ + "\n".join(lines)
108
+ )
brain/tests/test_gemini_live.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gemini Live: what is sent, what comes back, and how each failure is classified.
2
+
3
+ No network: ``connect`` is replaced by a scripted socket, so these check the wire format the
4
+ official SDK uses and the rotation and error rules, not Google.
5
+ """
6
+
7
+ import base64
8
+ import json
9
+
10
+ import pytest
11
+ from websockets.datastructures import Headers
12
+ from websockets.exceptions import ConnectionClosed, InvalidStatus
13
+ from websockets.frames import Close
14
+ from websockets.http11 import Response
15
+
16
+ from brain import config
17
+ from brain.llm.errors import AllKeysExhausted, ModelUnavailable, Rejected
18
+ from brain.llm.gemini_live import GeminiLive
19
+ from brain.llm.keys import KeyRing
20
+
21
+ PCM_OUT = bytes(range(200)) # stands in for 24 kHz speech
22
+
23
+
24
+ class FakeSocket:
25
+ """An open connection that hands out the scripted server messages, one at a time."""
26
+
27
+ def __init__(self, incoming):
28
+ self.incoming = list(incoming)
29
+ self.sent = []
30
+
31
+ async def send(self, text):
32
+ self.sent.append(json.loads(text))
33
+
34
+ def __aiter__(self):
35
+ return self
36
+
37
+ async def __anext__(self):
38
+ if not self.incoming:
39
+ raise StopAsyncIteration
40
+ item = self.incoming.pop(0)
41
+ if isinstance(item, Exception):
42
+ raise item
43
+ return item if isinstance(item, bytes) else json.dumps(item)
44
+
45
+
46
+ class Attempt:
47
+ def __init__(self, outcome):
48
+ self.outcome = outcome
49
+
50
+ async def __aenter__(self):
51
+ if isinstance(self.outcome, Exception):
52
+ raise self.outcome
53
+ return self.outcome
54
+
55
+ async def __aexit__(self, *exc):
56
+ return False
57
+
58
+
59
+ class FakeConnect:
60
+ def __init__(self, *outcomes):
61
+ self.outcomes = list(outcomes)
62
+ self.calls = []
63
+
64
+ def __call__(self, url, **kwargs):
65
+ self.calls.append((url, kwargs))
66
+ return Attempt(self.outcomes.pop(0))
67
+
68
+
69
+ def good_conversation():
70
+ return FakeSocket(
71
+ [
72
+ {"setupComplete": {}},
73
+ {"serverContent": {"inputTranscription": {"text": "What is "}}},
74
+ {"serverContent": {"inputTranscription": {"text": "12 times 15?"}}},
75
+ {
76
+ "serverContent": {
77
+ "modelTurn": {
78
+ "parts": [
79
+ {"inlineData": {"data": base64.b64encode(PCM_OUT[:100]).decode()}}
80
+ ]
81
+ },
82
+ "outputTranscription": {"text": "That is "},
83
+ }
84
+ },
85
+ {
86
+ "serverContent": {
87
+ "modelTurn": {
88
+ "parts": [
89
+ {"inlineData": {"data": base64.b64encode(PCM_OUT[100:]).decode()}}
90
+ ]
91
+ },
92
+ "outputTranscription": {"text": "180."},
93
+ "turnComplete": True,
94
+ }
95
+ },
96
+ ]
97
+ )
98
+
99
+
100
+ def live(connect, keys=("key-one",)):
101
+ ring = KeyRing(list(keys))
102
+ return GeminiLive(ring, config.Settings(), connect=connect)
103
+
104
+
105
+ def handshake_refused(status):
106
+ return InvalidStatus(Response(status, "refused", Headers(), b""))
107
+
108
+
109
+ def closed(code, reason):
110
+ return ConnectionClosed(Close(code, reason), None)
111
+
112
+
113
+ async def test_a_turn_sends_the_setup_then_the_audio_and_collects_the_answer():
114
+ socket = good_conversation()
115
+ connect = FakeConnect(socket)
116
+ pcm = b"\x01\x02" * 800
117
+ turn = await live(connect).talk("You are a robot.", pcm)
118
+
119
+ assert (turn.heard, turn.said, turn.pcm) == ("What is 12 times 15?", "That is 180.", PCM_OUT)
120
+ assert turn.model == config.DEFAULT_LIVE_MODEL
121
+
122
+ setup, audio, end = socket.sent
123
+ assert setup["setup"]["model"] == f"models/{config.DEFAULT_LIVE_MODEL}"
124
+ assert setup["setup"]["generationConfig"]["responseModalities"] == ["AUDIO"]
125
+ voice = setup["setup"]["generationConfig"]["speechConfig"]["voiceConfig"]
126
+ assert voice["prebuiltVoiceConfig"]["voiceName"] == config.DEFAULT_LIVE_VOICE
127
+ assert setup["setup"]["systemInstruction"]["parts"][0]["text"] == "You are a robot."
128
+ assert "inputAudioTranscription" in setup["setup"]
129
+ assert "outputAudioTranscription" in setup["setup"]
130
+
131
+ sent_audio = audio["realtimeInput"]["audio"]
132
+ assert sent_audio["mimeType"] == "audio/pcm;rate=16000"
133
+ data = base64.b64decode(sent_audio["data"])
134
+ assert data.startswith(pcm) and len(data) > len(pcm) # the recording, then silence
135
+ assert set(data[len(pcm) :]) == {0}
136
+ assert end == {"realtimeInput": {"audioStreamEnd": True}}
137
+
138
+
139
+ async def test_the_key_goes_in_a_header_never_the_url():
140
+ connect = FakeConnect(good_conversation())
141
+ await live(connect, keys=("secret-key",)).talk("p", b"\x00\x00")
142
+ url, kwargs = connect.calls[0]
143
+ assert "secret-key" not in url
144
+ assert kwargs["additional_headers"] == {"x-goog-api-key": "secret-key"}
145
+
146
+
147
+ async def test_messages_sent_as_bytes_are_understood_too():
148
+ socket = FakeSocket(
149
+ [
150
+ json.dumps({"setupComplete": {}}).encode(),
151
+ json.dumps(
152
+ {"serverContent": {"inputTranscription": {"text": "hi"}, "turnComplete": True}}
153
+ ).encode(),
154
+ ]
155
+ )
156
+ turn = await live(FakeConnect(socket)).talk("p", b"\x00\x00")
157
+ assert turn.heard == "hi" and turn.pcm == b""
158
+
159
+
160
+ async def test_quota_moves_on_to_the_next_key():
161
+ connect = FakeConnect(handshake_refused(429), good_conversation())
162
+ turn = await live(connect, keys=("one", "two")).talk("p", b"\x00\x00")
163
+ assert turn.heard
164
+ assert [c[1]["additional_headers"]["x-goog-api-key"] for c in connect.calls] == ["one", "two"]
165
+
166
+
167
+ async def test_a_quota_close_after_connecting_also_rotates():
168
+ spent = FakeSocket([{"setupComplete": {}}, closed(1008, "Quota exceeded for this project")])
169
+ connect = FakeConnect(spent, good_conversation())
170
+ turn = await live(connect, keys=("one", "two")).talk("p", b"\x00\x00")
171
+ assert turn.heard
172
+
173
+
174
+ async def test_every_key_out_of_quota_is_said_plainly():
175
+ connect = FakeConnect(handshake_refused(429), handshake_refused(429))
176
+ with pytest.raises(AllKeysExhausted):
177
+ await live(connect, keys=("one", "two")).talk("p", b"\x00\x00")
178
+
179
+
180
+ async def test_an_unknown_model_does_not_burn_the_other_keys():
181
+ connect = FakeConnect(handshake_refused(404))
182
+ with pytest.raises(ModelUnavailable):
183
+ await live(connect, keys=("one", "two")).talk("p", b"\x00\x00")
184
+ assert len(connect.calls) == 1
185
+
186
+
187
+ @pytest.mark.parametrize("status", [400, 401, 403, 500])
188
+ async def test_other_refusals_fail_fast(status):
189
+ connect = FakeConnect(handshake_refused(status))
190
+ with pytest.raises(Rejected):
191
+ await live(connect, keys=("one", "two")).talk("p", b"\x00\x00")
192
+ assert len(connect.calls) == 1
193
+
194
+
195
+ async def test_a_close_that_is_not_about_quota_is_a_plain_failure():
196
+ socket = FakeSocket([{"setupComplete": {}}, closed(1008, "Session closed due to inactivity")])
197
+ with pytest.raises(Rejected):
198
+ await live(FakeConnect(socket)).talk("p", b"\x00\x00")
199
+
200
+
201
+ async def test_a_model_that_is_not_found_on_close_is_unavailable():
202
+ socket = FakeSocket([closed(1008, "models/x is not found for API version v1beta")])
203
+ with pytest.raises(ModelUnavailable):
204
+ await live(FakeConnect(socket)).talk("p", b"\x00\x00")
205
+
206
+
207
+ async def test_a_dropped_network_is_a_plain_failure():
208
+ with pytest.raises(Rejected):
209
+ await live(FakeConnect(OSError("network unreachable"))).talk("p", b"\x00\x00")
210
+
211
+
212
+ async def test_a_silent_recording_comes_back_with_nothing_heard():
213
+ socket = FakeSocket([{"setupComplete": {}}, {"serverContent": {"turnComplete": True}}])
214
+ turn = await live(FakeConnect(socket)).talk("p", b"\x00\x00")
215
+ assert (turn.heard, turn.said, turn.pcm) == ("", "", b"")
brain/tests/test_robot_ask.py CHANGED
@@ -1,5 +1,7 @@
1
  """The robot's plain assistant: text in, text out, no memory, no persona, no database."""
2
 
 
 
3
  import pytest
4
 
5
  from brain.services import assistant
@@ -157,3 +159,147 @@ def test_history_is_capped_and_old_sessions_are_forgotten():
157
  def test_empty_or_oversized_questions_are_refused(env, text): # noqa: F811
158
  client, *_ = env
159
  assert ask(client, text).status_code == 422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """The robot's plain assistant: text in, text out, no memory, no persona, no database."""
2
 
3
+ import base64
4
+
5
  import pytest
6
 
7
  from brain.services import assistant
 
159
  def test_empty_or_oversized_questions_are_refused(env, text): # noqa: F811
160
  client, *_ = env
161
  assert ask(client, text).status_code == 422
162
+
163
+
164
+ # --- Talking: a recording in, Gemini Live's spoken answer out ------------------------------
165
+
166
+ import io # noqa: E402
167
+ import wave # noqa: E402
168
+
169
+ from brain.llm.errors import QuotaExhausted # noqa: E402
170
+ from brain.llm.gemini_live import LiveTurn # noqa: E402
171
+
172
+
173
+ def wav_bytes(rate=16000, channels=1, width=2, seconds=0.5):
174
+ out = io.BytesIO()
175
+ with wave.open(out, "wb") as clip:
176
+ clip.setnchannels(channels)
177
+ clip.setsampwidth(width)
178
+ clip.setframerate(rate)
179
+ clip.writeframes(bytes(int(rate * seconds) * channels * width))
180
+ return out.getvalue()
181
+
182
+
183
+ class FakeLive:
184
+ """Stands in for Gemini Live: records what it was asked and answers from a script."""
185
+
186
+ def __init__(self, *turns):
187
+ self.turns = list(turns)
188
+ self.asked = []
189
+
190
+ async def talk(self, prompt, pcm, *, voice=None):
191
+ self.asked.append((prompt, pcm))
192
+ turn = self.turns.pop(0)
193
+ if isinstance(turn, Exception):
194
+ raise turn
195
+ return turn
196
+
197
+
198
+ def said(heard, reply, pcm=b"\x01\x00" * 2400):
199
+ return LiveTurn(heard=heard, said=reply, pcm=pcm, model="gemini-3.8-live", ms=1234)
200
+
201
+
202
+ def talk(client, live, audio=None, headers=DEVICE, **params):
203
+ client.app.state.deps.live = live
204
+ return client.post(
205
+ "/robot/talk",
206
+ content=wav_bytes() if audio is None else audio,
207
+ params=params,
208
+ headers={**headers, "content-type": "audio/wav"},
209
+ )
210
+
211
+
212
+ def test_a_recording_in_gives_what_was_heard_and_a_spoken_answer(env): # noqa: F811
213
+ client, *_ = env
214
+ live = FakeLive(said("what is twelve times fifteen", "That is one hundred eighty."))
215
+ body = talk(client, live).json()
216
+ assert body["heard"] == "what is twelve times fifteen"
217
+ assert body["reply"] == "That is one hundred eighty."
218
+ wav = base64.b64decode(body["audio"])
219
+ with wave.open(io.BytesIO(wav)) as clip: # the answer is a real, playable 24 kHz WAV
220
+ assert (clip.getframerate(), clip.getnchannels(), clip.getsampwidth()) == (24000, 1, 2)
221
+ assert body["sessionId"]
222
+
223
+
224
+ def test_the_recording_reaches_gemini_as_pcm_without_a_wav_header(env): # noqa: F811
225
+ client, *_ = env
226
+ live = FakeLive(said("hi", "Hello."))
227
+ talk(client, live, audio=wav_bytes(seconds=0.25))
228
+ _, pcm = live.asked[0]
229
+ assert len(pcm) == int(16000 * 0.25) * 2
230
+ assert not pcm.startswith(b"RIFF")
231
+
232
+
233
+ def test_the_prompt_is_the_plain_assistant_not_prova(env): # noqa: F811
234
+ client, *_ = env
235
+ live = FakeLive(said("hi", "Hello."))
236
+ talk(client, live)
237
+ prompt, _ = live.asked[0]
238
+ assert "built by Karnak" in prompt and "{{" not in prompt
239
+ assert "THINGS YOU KNOW ABOUT HIM" not in prompt and "WHO YOU ARE" not in prompt
240
+
241
+
242
+ def test_a_click_gets_no_answer_and_is_not_remembered(env): # noqa: F811
243
+ client, *_ = env
244
+ live = FakeLive(said("", "I did not catch that.", pcm=b"\x01\x00" * 100), said("hi", "Hello."))
245
+ first = talk(client, live).json()
246
+ assert first["heard"] == "" and first["reply"] == "" and first["audio"] is None
247
+ talk(client, live, sessionId=first["sessionId"])
248
+ assert "I did not catch that" not in live.asked[1][0]
249
+
250
+
251
+ def test_the_next_turn_is_told_what_was_said_before(env): # noqa: F811
252
+ client, *_ = env
253
+ live = FakeLive(said("two plus two", "Four."), said("times five", "Twenty."))
254
+ first = talk(client, live).json()
255
+ talk(client, live, sessionId=first["sessionId"])
256
+ prompt = live.asked[1][0]
257
+ assert "They: two plus two" in prompt and "You: Four." in prompt
258
+
259
+
260
+ def test_another_session_is_not_told_it(env): # noqa: F811
261
+ client, *_ = env
262
+ live = FakeLive(said("my code is 4711", "Noted."), said("hello", "Hi."))
263
+ talk(client, live, sessionId="a")
264
+ talk(client, live, sessionId="b")
265
+ assert "4711" not in live.asked[1][0]
266
+
267
+
268
+ def test_it_reads_and_writes_nothing_in_the_database_when_talking(env): # noqa: F811
269
+ client, store, *_ = env
270
+ talk(client, FakeLive(said("hi", "Hello.")))
271
+ assert store.messages == [] and store.memories == []
272
+
273
+
274
+ def test_gemini_being_out_of_quota_is_a_503_not_a_crash(env): # noqa: F811
275
+ client, *_ = env
276
+ response = talk(client, FakeLive(QuotaExhausted(429, "out of quota")))
277
+ assert response.status_code == 503
278
+ assert response.json()["detail"]["code"] == "unavailable"
279
+
280
+
281
+ def test_without_a_live_client_it_says_so(env): # noqa: F811
282
+ client, *_ = env
283
+ assert talk(client, None).status_code == 503
284
+
285
+
286
+ def test_talking_needs_a_token_and_a_16k_mono_wav(env): # noqa: F811
287
+ client, *_ = env
288
+ live = FakeLive(said("hi", "Hello."))
289
+ assert talk(client, live, headers={}).status_code == 401
290
+ assert talk(client, live, audio=wav_bytes(rate=8000)).status_code == 415
291
+ assert talk(client, live, audio=wav_bytes(channels=2)).status_code == 415
292
+ assert talk(client, live, audio=b"not a wav file").status_code == 415
293
+ assert talk(client, live, audio=b"").status_code == 422
294
+ assert not live.asked # nothing reached Gemini
295
+
296
+
297
+ def test_an_oversized_recording_is_refused_before_it_is_read(env): # noqa: F811
298
+ client, *_ = env
299
+ client.app.state.deps.live = FakeLive()
300
+ response = client.post(
301
+ "/robot/talk",
302
+ content=b"\x00",
303
+ headers={**DEVICE, "content-type": "audio/wav", "content-length": str(10**9)},
304
+ )
305
+ assert response.status_code == 413
requirements.txt CHANGED
@@ -4,6 +4,8 @@
4
  fastapi>=0.115
5
  uvicorn[standard]>=0.30
6
  httpx>=0.27
 
 
7
  pydantic>=2.7
8
  pyjwt[crypto]>=2.9
9
  pywebpush>=2.0
 
4
  fastapi>=0.115
5
  uvicorn[standard]>=0.30
6
  httpx>=0.27
7
+ # Gemini Live is a WebSocket; uvicorn[standard] brings it too, but the brain imports it itself.
8
+ websockets>=14
9
  pydantic>=2.7
10
  pyjwt[crypto]>=2.9
11
  pywebpush>=2.0