Gemini: how it works
Gemini Live is Google's realtime speech model API: one WebSocket carries your audio in and the model's speech, transcripts and function calls out. Taji takes from it one thing, a voice: it hears the open microphone, speaks the conversation's replies, and hands your requests to your desk's agent. The plugin is one crate, taji-gemini, built from plugins/gemini/src/lib.rs. It implements taji_plugin::voice::Voice, the kernel holds its one socket to generativelanguage.googleapis.com, and it serves no market data, places no orders and feeds no hub product.
Voice is the one exception to 0002: Taji calls no model API, voice aside. The boundary that exception keeps is the shape of this crate. The voice model is a relay, not a second agent. Its whole tool set is six dispatch tools (send, read, stop, open_desk, set_progress_updates, hang_up, Tool::ALL in engine/crates/taji-plugin/src/voice.rs). It reads no quote, holds none of the agent's eight MCP tools, and places and approves nothing. Every request with trading meaning goes, as your words, to the agent your own platform runs. The key is yours, sealed in your vault, and Google bills it, not Taji.
The vendor
All facts here come from Google's Gemini API docs, fetched 2026-12-02. The ai.google.dev paths now redirect (301) to aistudio.google.com, which is where each link below points.
Hosts. One environment, with no sandbox. The Live socket is wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent, API version v1beta (Live API reference). REST calls go to https://generativelanguage.googleapis.com/v1beta/….
Auth. A Gemini API key belongs to a Google Cloud project, and the project carries billing, collaborators and permissions. The REST docs pass the key in an x-goog-api-key header (API keys). The WebSocket guide passes it as a key query parameter on the socket URL: "Authentication is handled by including your API key as a query parameter in the WebSocket URL" (Get started with the WebSocket API). The key page states no expiry, but says Google blocks unrestricted keys left dormant for an extended period, from 2026-05-07. It warns never to put a key in a web or mobile client.
For a client-side app Google offers ephemeral tokens: POST /v1beta/auth_tokens mints a token for BidiGenerateContentConstrained, by default valid 30 minutes, able to open a new session for 60 seconds, and good for one use (Live API reference).
The Live protocol. Each message is JSON. The first client message is setup; the server answers setupComplete. After that:
| Direction | Message | What it carries |
|---|---|---|
| client | realtimeInput.audio | a Blob: base64 data and a mimeType such as audio/pcm;rate=16000 |
| client | clientContent | turns of text, with turnComplete |
| client | toolResponse | functionResponses, each id, name, response |
| server | serverContent | modelTurn.parts[].inlineData (audio), inputTranscription, outputTranscription, interrupted, generationComplete, turnComplete |
| server | toolCall | functionCalls, each id, name, args |
| server | toolCallCancellation | the ids of calls the server dropped |
| server | goAway | timeLeft before the connection is "terminated as ABORTED" |
| server | sessionResumptionUpdate | newHandle, resumable |
setup's fields are model, generationConfig, systemInstruction, tools, realtimeInputConfig, sessionResumption, contextWindowCompression, inputAudioTranscription, outputAudioTranscription, proactivity, historyConfig and labels. The reference says input transcription is sent "independently with no guaranteed ordering".
Audio. Input is "raw 16-bit PCM audio, 16kHz, little-endian", and the API resamples another rate if the mimeType names it. Output "always uses a sample rate of 24kHz" (Live API capabilities).
Turn detection. "By default, the model automatically performs VAD on a continuous audio input stream." Its silence threshold defaults to "approximately 800ms". The default activityHandling is START_OF_ACTIVITY_INTERRUPTS: your speech cancels the generation, and "Only the information already sent to the client is retained in the session history". With detection disabled, the client sends activityStart and activityEnd itself.
Function calling. The Live API has no automatic tool handling: the client must answer each call with a toolResponse. "On gemini-4-live and gemini-3.8-live, function calling runs asynchronously (NON_BLOCKING) by default", and a declaration's behavior: BLOCKING keeps the synchronous mode (Tool use). With thinking at LOW or above only NON_BLOCKING is allowed, and BLOCKING or scheduling returns an error (Live thinking). The FunctionDeclaration schema defines BLOCKING as "the system will wait to receive the function response before continuing the conversation" and NON_BLOCKING as "the system will not wait". A response's scheduling (INTERRUPT, WHEN_IDLE, SILENT, default WHEN_IDLE) is "Only applicable to NON_BLOCKING function calls" (Function declarations). The Tool use page does not describe toolCallCancellation.
Sessions. A connection lasts "around 10 minutes". Without compression, an audio-only session is capped at 15 minutes. contextWindowCompression with a sliding window allows sessions of unlimited length. With sessionResumption on, the server sends handles; a handle passed in a new connection's setup resumes the session, and stays valid 2 hours after the session last ended (Session management). The reference defines sessionResumption.handle as "The handle of a previous session. If not present then a new session is created", SessionResumptionUpdate.newHandle as the "New handle that represents a state that can be resumed. Empty if resumable=false", and GoAway.timeLeft as "The remaining time before the connection will be terminated as ABORTED" (Live API reference).
The model. gemini-4-live, released 2026-12-02, "replaces both Gemini 3.8 Live and Gemini 3.8 Live Extended Thinking with a single gemini-4-live endpoint": 131,072 input and 65,536 output tokens, with function calling, Google Search grounding and optional thinking (Gemini 4 Live). Google's migration is to "change the model string to models/gemini-4-live and omit thinking_level (or set MINIMAL)"; "turn lifecycle and turnComplete signals remain identical" (Live thinking). gemini-3.8-live has no shutdown date yet (Deprecations). Native audio models answer only in the AUDIO modality. Proactive audio is permanently enabled, and setting proactive_audio: false "returns an error"; affective dialog is removed. The reference says of proactive audio: "If enabled, the model can reject responding to the last prompt", such as out-of-context speech.
Models list. GET /v1beta/models with pageSize (default 50, at most 1000) and pageToken; it answers models and nextPageToken (List models).
Limits and errors. Rate limits apply per project, not per key, and rise with the project's usage tier: Tier 1 is an active billing account, Tier 2 $100 paid plus 3 days, Tier 3 $1,000 plus 30 days (Rate limits). gemini-4-live is limited in tokens per minute alone (Tier 1 250K, Tier 2 600K, Tier 3 15M), and no Live concurrent-session limit is listed. The error page (API errors) lists, among others: 401 a missing, invalid or expired key; 402 "Your Prepay credit balance is depleted", not to be retried; 403 a key lacking permission; 429 a per-minute limit (retry with backoff) or the daily quota.
What Taji does not use:
- Google Search grounding and every other built-in tool. The voice may declare only
Tool::ALL. A searching voice would answer market questions itself, which 0002 rules out. - Ephemeral tokens. The kernel holds the socket, so the key never needs to reach a client (0005).
- Client-side turn detection (
realtimeInputConfig,activityStart,activityEnd). TheVoicecontract asks for "the provider's own turn detection on the open microphone". Tuning the detector waits on a repro. - Non-blocking calls and
scheduling. Every declaration isBLOCKING(below), andschedulingapplies only to non-blocking calls. - A chosen language or thinking level (
speechConfig.languageCode,thinkingLevel). Taji takes Google's defaults. - Image and video input, text output. Voice is audio both ways. Not yet built.
usageMetadata,generationComplete,proactivity,historyConfig. The arm ignores them. Showing a session's spend is not yet built.
Code map
plugins/gemini/src/lib.rs: the whole arm. Readimpl Voice for Geminifirst, thenState::on_event.Gemini: the two URLs,live(the socket, without?key=) andmodels;Defaultpoints at Google and a test points them at a local server.MODEL,INPUT_HZ,OUTPUT_HZ,INPUT_MIME:gemini-4-live, 16 kHz in, 24 kHz out.setup_frame: thesetupmessage: the model,AUDIOoutput, the instructions, the six tools, eachBLOCKING, both transcriptions, resumption and the sliding window.Gemini::open: connect with the key in the query, sendsetup, wait forsetupComplete.Voice::run: the loop. It selects between the kernel'sInput, Google's frames and the pendinggoAway's timer, and reconnects once agoAwayis due (State::swap_due) or on a lost connection that has a handle.Gemini::resume: the reconnect after an unplanned loss or a failed swap, one attempt after each ofRECONNECT_WAITSnot yet used.State: the turn bookkeeping.on_inputsends audio, results, cuts and Tells;on_eventroutes Google's messages toon_tool_callandon_content;begin,cutandflushkeep theBegan/Donerules over the SDK'svoice::Turns, which also opens a reconnect.Turn: one turn'stold,cut,over, its pending calls and the responses held for onetoolResponse.response_of: the kernel's result string as a function response object.refusal,connect_error,sanitize: Google's errors asFailed, with the key masked.next_ws_event: a text or binary frame as JSON, or a close asFailed.
plugins/gemini/tests/scripted.rs: offline tests against a localtokio-tungsteniteserver replaying Live message sequences, and awiremockmodels list.plugins/gemini/tests/live.rs: ignored tests against Google, keyed byGEMINI_API_KEY.plugins/gemini/taji-plugin.toml: identity, thegeminilink form, its step, field and refusal words.plugins/gemini/Cargo.toml: depends ontaji-pluginwith itsvoicefeature,tokio-tungstenite,reqwest,base64andserde_json, and on no other Taji crate.plugins/gemini/README.md: the page for the person linking, and the measured behaviour.
How it plugs into Taji
The trait. Gemini implements Plugin, whose build calls b.voice(Self::default()), and Voice (engine/crates/taji-plugin/src/voice.rs):
| Method | Gemini's answer |
|---|---|
id, name | gemini, Gemini |
fields | key |
format | 16,000 Hz in, 24,000 Hz out, PCM s16le mono |
link | GET /v1beta/models?pageSize=1 with x-goog-api-key; any 2xx links |
voices | the nine prebuilt voices, Kore first, each with Google's descriptor |
run | one Live session for as long as the kernel's hears stays open, reconnecting inside on a quiet goAway and on a lost connection |
Voice::run's doc comment holds eight turn rules, and the arm exists to keep them: each turn opens with Began { spoken } and closes with one Done, in order; a turn that began while a Tell was unanswered is marked not spoken (fail closed); after a cut, nothing of an older turn but its Done; no Done between a Call and its Result; a Tell waits until no turn runs; a swap that ends a running turn is Reconnecting, that turn's Done, Reconnected, and nothing else between them.
The plugin has no FACTS, VenueFacts or OFFER statics: it is no data source or venue. engine/crates/taji-open/src/lib.rs composes it with .add(taji_gemini::Gemini::default), after OpenAI's arm.
The link form. The manifest's one [[link]] is the form gemini (kind fields, group Voice), with one step and one secret field key; the step text is the manifest's. It posts voice/link with {"provider": "gemini"}. Its refusal words are invalid_key and no_credit; the kernel turns each into the manifest's sentence (Sealed::word_sentence in engine/crates/taji/src/wire/sealed.rs).
The kernel side. engine/crates/taji/src/wire/voice.rs owns everything that is not Gemini:
- the link: it calls
Voice::link, seals the fields under vault recordvoice_gemini, and writesvoice.json; - the session:
/ws/voiceis open to the window's scopes alone (get("ws/voice", WINDOW)inengine/crates/taji/src/wire/routes.rs), so your agent cannot open the microphone; a kernel runs one session, and a newerstartends the olderreplaced; - the tools:
run_toolruns each call against the bound conversation (crate::agent::Agent); - the gate: only
readruns in a turn your speech did not begin; any other call there is answered "Only the user's own speech can do that."; - the replies: the relay watches the bound chat and tells the voice each answer, card, question and failure as a cue line (
[answer to "…"],[waiting on the user],[failed]); - the captions, the timers and the session's end.
The window's end is ui/src/agent/voice.ts: it captures the microphone with echo cancellation on, resamples it to ready.input_hz in ui/src/agent/voice.worklet.ts, and plays the kernel's audio at output_hz.
Surfaces.
| Taji surface | Gemini call | Made in |
|---|---|---|
POST /verb/voice/link (provider: "gemini") | GET /v1beta/models?pageSize=1 | Voice::link |
GET /read/voice, Gemini's row | none: the kernel's slot | engine/crates/taji/src/wire/voice.rs |
/ws/voice start → ready | the socket, setup, setupComplete | Gemini::open |
/ws/voice client audio | realtimeInput.audio | State::on_input |
kernel audio and caption (you, voice) | serverContent audio and transcriptions | State::on_content |
kernel cut | serverContent.interrupted | State::on_content, State::cut |
| the six tools | toolCall, then toolResponse | State::on_tool_call, State::on_input |
an agent caption, spoken | clientContent with the cue line | State::flush |
kernel ended provider | a close or socket error with no handle, a refusal, or a spent RECONNECT_WAITS | next_ws_event, Gemini::resume |
POST /verb/voice/unlink | none: the sealed record is deleted | engine/crates/taji/src/wire/voice.rs |
The routes' full contracts are the voice rows of the //! header of engine/crates/taji/src/wire/mod.rs.
One spoken turn, from the microphone to the dispatched act and back. You say "Buy one share of Apple" on desk Main.
- Start. The window opens
/ws/voiceand sendsstartwith its desk.Voices::servechecks the scope, unsealsvoice_gemini(armed), binds the desk's conversation (bind), and spawnsGemini::runwithINSTRUCTIONSas the system instruction.runopens the socket with?key=, sendssetupand waits forsetupComplete. The kernel framesreadywithinput_hz16000 andoutput_hz24000, and the window asks for the microphone. - The microphone. Every 40 ms the worklet posts 16 kHz samples; the window sends each as a binary
audioframe.Session::audiopasses it asInput::Audio, andon_inputsends it asrealtimeInput.audio, base64,audio/pcm;rate=16000. Audio streams fromreadyto the socket's end, silence included. - Google ends your utterance. Its detector hears about 800 ms of silence.
inputTranscriptiondeltas arrive asOutput::Heard, and the kernel captions themyou. - The model calls
send. AtoolCallarrives withsendandargs{"text": "Buy 1 AAPL"}. With no turn live,beginemitsBegan { spoken: true };on_tool_callrecords the call as pending and emitsOutput::Call. A name outsideTool::ALLis answered "Unknown tool." and never reaches the kernel. - The kernel dispatches.
Session::outputsees a spoken turn and queues the call;startruns it on a blocking task.run_toolcallsAgent::hand_off, which puts a question into the bound chat withorigin.channelvoiceand ataji://voicemention. The mention carries, on the call's first hand-off to this chat,VOICE_INSTRUCTIONS(engine/crates/taji/src/agent.rs): the text came from speech, your own words in the transcript win, and an order is read back and placed only once you confirm. It also carries what was said since the last hand-off, up to 12 lines and 2,000 characters. Your agent, over ACP on your platform's sign-in, now owns the request. An order it places follows the account's approvals (0008); the voice can approve nothing. - The result goes back.
run_toolanswers "Working on it; the answer comes as an [answer] line." The kernel hands it back asInput::Result. Once every call of thattoolCallhas its result, the arm sends onetoolResponse, the string wrapped as{"result": …}. - Gemini speaks.
modelTurnaudio parts becomeOutput::Audio, framedaudiowith 24 kHz PCM, and the window plays them.outputTranscriptionbecomesOutput::Spoke, captionedvoice. AturnCompletethat came while the call waited was held; the one after the response ends the turn withDone. - The agent's reply. Later the agent answers in the chat. The relay turns it into an
[answer to "Buy 1 AAPL"] …cue, at most 1,000 characters of answer (ANSWER_CHARS), captions itagent, and, once no turn runs, passes it asInput::Tell.State::flushemitsBegan { spoken: false }and sends it asclientContent; Gemini speaks it in the first person, as its own words, and ends the turn. In that told turn onlyreadruns. If the agent parks an approval, the cue is[waiting on the user] approval: …and the voice says approving happens only in Taji's window.
If you speak during step 7, Google sends interrupted: the arm emits Output::Interrupted, the kernel frames cut, the window stops playback, and nothing more of that turn reaches you.
Why it is built this way
- A voice, not a model, inside Taji. 0002 lets voice call a model only as a relay to your own agent; its Alternatives reject a text model between the voice and your agent. Hence the six tools,
INSTRUCTIONSforbidding the voice to answer market questions itself, and no built-in Google tool. - Only your speech can act. A Tell carries the agent's text, and a reply could carry an instruction. So a turn not begun by your speech may only
read(a_turn_a_tell_began_may_read_and_nothing_elseinengine/crates/taji/src/wire/voice.rs), and rule 2 ofVoice::runfails closed: a turn beginning while a Tell is unanswered counts as told, since the arm cannot tell whose turn Google started. The README's measured section shows the cost: a request spoken in that instant is not handed over, and you say it again. - The kernel holds the socket. The key is unsealed in the kernel and sent only to Google; no client or process plugin sees it (0005, and the Voice section of security). This is also why ephemeral tokens are unneeded.
- The key goes in the query string. That is how Google's WebSocket guide authenticates the socket. The URL lives only inside
run; every error that might echo it passessanitize, and the crate never logs a key, audio or a transcript. - Google's own turn detection. The
Voicecontract leaves detection to the provider, and the measured defaults (about 800 ms of silence, barge-in on) are what the README records.setupsends norealtimeInputConfigso the defaults stand. responseModalitiessits ingenerationConfig. The WebSocket guide's example puts it at the top ofsetup; Google refused that with close 1007 "Cannot find field" (the comment onsetup_frame). The reference's form works.- Blocking calls. Rule 5 of
Voice::runholds a turn's output until everyCallhas itsResult, and the kernel's results ("Not sent. Do not say it happened.") must reach the model before it speaks of the outcome.gemini-4-livedefaults toNON_BLOCKING, which goes on speaking, sosetup_framedeclares each toolBLOCKING. Google refusesBLOCKINGonce thinking is aboveMINIMAL, sosetupnames no thinking level. - A held
turnComplete. Google can sendturnCompletewhile a call waits on its result. Rule 3 forbids aDonebetween aCalland itsResult, so the arm keeps the turn open until the tool response starts the generation whose ownturnCompleteends it. - One
toolResponsepertoolCall. The arm holds results until every call of atoolCallis answered, then sends them together (a_tool_call_is_answered_in_one_tool_response_and_its_turn_complete_is_held). Why one message rather than one per result is not on record. - Cut calls are answered, not dropped. On
Input::Cutthe arm answers every waiting call with "The user interrupted.", so Google's turn reachesturnCompleteand the next can begin. On Google's owninterruptedit sends nothing, since the server discards those calls itself. - Reconnects stay inside
run. TheVoicecontract keeps "a provider's reconnects and resumption" inside the arm. A connection lasts about ten minutes, so ongoAwaythe arm opens a new one with the newest resumable handle, closing the old one after. It does not swap at once: Google does not document that a resume keeps partial input, so the old socket keeps serving until no turn runs and noinputTranscriptionarrived forGemini::quiet(1 s), or until 5 s of thegoAway'stimeLeftremain.timeLeftis a protobufDuration, which JSON writes as seconds ending ins("10s","3.5s"); the reference types itDurationand the session-management page gives no format, so a frame with no parsabletimeLeftswaps at the first quiet moment only. The kernel sees a swap only when it ends a running turn:Reconnecting, theDoneof each turn running,Reconnected(rule 8). The turns end rather than carry over because a running generation does not continue on the new connection, and the kernel's cut path (Reconnectingcuts like an interruption) already drops the turn's calls; the arm drops them too, so a lateResultsends nothing. - A lost connection resumes on the handle, or ends the session. A close, a socket error or a failed send while a resumption handle is held emits
Reconnecting(always: the connection was lost, so the user's speech goes nowhere), ends every running turn, then reopens on the handle after each ofRECONNECT_WAITS(0.5, 1, 2, 4 and 8 s) and emitsReconnected. Audio the kernel sent meanwhile waits inhearsand reaches the new session in order; Google acknowledges no audio, so what the dead socket had not delivered is not replayed. With no handle there is no context to resume and the loss endsrun, as before.Failed::Word(a key or credit failure) andFailed::Refused(a 1007 or 1008 close) are never retried: waiting cannot fix them. A spent list returns the last error. The list is walked across reconnects: it starts again from 0.5 s only once a connection has stayed upReconnect::steady(30 s), so an open that succeeds and then closes each time still waits 0.5, 1, 2, 4, 8 s and then endsrun. - A chosen voice and the desk's vocabulary.
setup.voiceis sent asgenerationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName;VOICESis a static list, and Google's one-word descriptors are thetone.setup.vocabularyis sent asinputAudioTranscription.customVocabularywhen it is not empty.Input::Playedis ignored: Gemini has no truncate. Both are re-sent on every reconnect, sincesetup_frameis built from the sameSetup. - A sliding context window. Without it an audio session ends at 15 minutes; the README measured that it lifts the limit.
- Both transcriptions on. The kernel needs text for captions and for the transcript each hand-off carries. Your own words in that transcript are what lets
VOICE_INSTRUCTIONStell the agent to trust them over the voice's wording. linkis a models read.Voice::linkmust prove the key "with one authenticated call that opens no session", so linking bills no audio. The README records the cost: it proves the key, not its credit.- One pinned model.
MODELisgemini-4-live, and a picker is not yet built. - A plugin on the SDK alone. The crate depends on
taji-pluginand no kernel crate (0003).
Constraints and limits
The numbers measured against Google are the README's, under its Use section: the detector's silence, interruptions, reconnects, compression, noise and the models read.
-
Failures map onto
Failed:Where What fails Result linkor the socket upgrade401, API_KEY_INVALIDor "API key not valid"the word invalid_keylinkor the socket upgrade402 or "credit balance is depleted" the word no_creditlinkor the socket upgradeanother 4xx but 429 Failed::Refusedwith Google's text, key maskedlinkor the socket upgrade429, 5xx, transport Failed::Unreacheda live socket close 1007 or 1008 as a 400: one of the words if the reason names it, else Refuseda live socket any other close, a socket error, a lost send Failed::Unreached; with a resumption handle held, the arm reconnects first and returns this only onceRECONNECT_WAITSis spentkeyno keyfieldFailed::Refused("Gemini needs an API key.")When
runreturns an error the kernel ends the sessionendedproviderwith that sentence and sets the row'serror; it never restarts a voice session. You turn voice on again. -
Rate limits. The arm reads no rate limit and retries nothing: a 429 at connect ends the session. Google's error page names no
Retry-Afteror retry delay for a 429, only "Wait and retry with exponential backoff" for a per-minute limit and waiting for the reset for the daily quota. Limits are per project and by tier. -
Reconnects. A
goAwayreconnects at the first moment no turn runs and no input transcription arrived in the last second, or once 5 s of itstimeLeftremain; a lost connection with a handle waits 0.5 s first, then 1, 2, 4 and 8 s between attempts, starting again from 0.5 s only after a connection has stayed up 30 s. A turn running at either ends with itsDone, its calls dropped, betweenReconnectingandReconnected; aTellwaits until the new session is up. With no resumable handle yet, agoAway's new connection starts without the conversation's context, and a lost connection endsrun. AgoAwaywhose reopen fails withUnreachedtakes the same waits on the same handle, withReconnectingandReconnectedaround them whether or not a turn was running. A refused reconnect endsrun. -
Barge-in and history. Google keeps in its history all it sent, not what the window played, so after an interruption the model may believe you heard more than you did. Truncating it to what was played is not yet built.
-
Kernel timers (
engine/crates/taji/src/wire/voice.rs):- a call has
CALL_TIME, the agent's 60 sASK_WAITplus 5 s; past it the voice is told the call is unfinished, and its late result is told as a[late result] <tool>: <output>line; - a turn with nothing exchanged for 30 s (
TURN_IDLE) is cut; - a turn may make 8 calls per desk it reaches (
DESK_CALLS) before it is cut.
- a call has
-
Audio back-pressure. The kernel keeps 16 slots of the arm's input queue for results, cuts and Tells (
HEARD_ROOM). While the arm is not reading, during a reconnect, live audio past that is dropped rather than stalling the session. -
Noise and other people. The microphone is always open, and proactive audio, which lets the model decline speech not meant for it, is always on and cannot be turned off. 3.8 Live answered a remark to someone else 1 run of 3 and 4 Live 0 of 3 (
a_cough_and_a_remark_to_someone_else_are_not_answeredintests/live.rs); instruction wording did not close it on 3.8. A turn Gemini keeps silent still carries a transcript (<!-- no speech output -->), which the next hand-off's transcript keeps. -
What reaches Google. Everything the microphone hears while voice is on, the cue lines, and the results of
read: the conversation's last six messages, 400 characters each, and whether the agent is working or waiting for approval.
Examples
Each comes from a test body, its values made up, in plugins/gemini/tests/scripted.rs unless it names another source. Function call ids and resumption handles are masked pN; the key is shown as ….
The link (link_reads_the_models_and_maps_an_invalid_key_and_no_credit). POST /verb/voice/link with {"provider": "gemini", "key": …} makes the arm call:
GET /v1beta/models?pageSize=1 x-goog-api-key: …
→ 200 {"models": []} links
→ 400 {"error": {"code": 400, "message": "API key not valid. Please pass a valid API key.",
"status": "INVALID_ARGUMENT",
"details": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "API_KEY_INVALID", …}]}}
Failed::Word("invalid_key")
→ 402 {"error": {"code": 402, "message": "Your Prepay credit balance is depleted.", "status": "RESOURCE_EXHAUSTED"}}
Failed::Word("no_credit")
The link form (engine/crates/taji/tests/fixtures/wire/link-forms.json, trimmed). GET /read/link/forms serves {"form": "gemini", "group": "Voice", "kind": "fields", "fields": [{"name": "key", "kind": "secret", "label": "API key", …}], "post": {"route": "voice/link", "body": {"provider": "gemini"}}, "refusals": {"invalid_key": "Google did not accept that API key. …", "no_credit": "Google's prepay credit balance is depleted. …"}, …}.
The setup (the_setup_leaves_turn_detection_to_google_and_a_spoken_turn_begins_spoken). The socket opens on …BidiGenerateContent?key=… and the arm's first message is:
{"setup": {
"model": "models/gemini-4-live",
"generationConfig": {"responseModalities": ["AUDIO"]},
"systemInstruction": {"parts": [{"text": "Speak briefly and call dispatch tools."}]},
"tools": [{"functionDeclarations": [
{"name": "send", "description": "Hand a request to the agent in the bound conversation on the current desk.",
"parametersJsonSchema": {"type": "object", "properties": {"text": {"type": "string"},
"delivery": {"type": "string", "enum": ["steer", "queue"], "default": "steer"}},
"required": ["text"], "additionalProperties": false},
"behavior": "BLOCKING"},
{"name": "read", …}, {"name": "stop", …}, {"name": "open_desk", …}]}],
"inputAudioTranscription": {}, "outputAudioTranscription": {},
"sessionResumption": {}, "contextWindowCompression": {"slidingWindow": {}}}}
The test's instruction stands in for INSTRUCTIONS, and setup has no realtimeInputConfig.
A spoken turn (the same test). After setupComplete, the arm sends a microphone chunk as {"realtimeInput": {"audio": {"data": …, "mimeType": "audio/pcm;rate=16000"}}}, the data base64. Google answers:
{"serverContent": {"inputTranscription": {"text": "What is AAPL?"}}} → Heard("What is AAPL?")
{"serverContent": {"modelTurn": {"parts": [{"inlineData":
{"mimeType": "audio/pcm;rate=24000", "data": "MjxGUA=="}}]}}} → Began { spoken: true }, Audio([50, 60, 70, 80])
{"serverContent": {"outputTranscription": {"text": "Checking now."}}} → Spoke("Checking now.")
{"serverContent": {"generationComplete": true}} → nothing
{"serverContent": {"turnComplete": true}} → Done
A tool call (a_tool_call_is_answered_in_one_tool_response_and_its_turn_complete_is_held). Google sends:
{"toolCall": {"functionCalls": [
{"id": "p1", "name": "open_desk", "args": {"name": "Main"}},
{"id": "p2", "name": "send", "args": {"text": "check AAPL"}}]}}
then {"serverContent": {"turnComplete": true}}, which the arm holds. It emits Began { spoken: true } and the two Calls. The kernel answers Result { call: "p1", output: "Opened Main." } and Result { call: "p2", output: "{\"error\":\"Not sent. Do not say it happened.\"}" }, and only then does the arm send:
{"toolResponse": {"functionResponses": [
{"id": "p1", "name": "open_desk", "response": {"result": "Opened Main."}},
{"id": "p2", "name": "send", "response": {"error": "Not sent. Do not say it happened."}}]}}
A told turn (a_tell_begins_a_told_turn_with_client_content). The kernel passes Input::Tell("[answer to \"q\"] AAPL is 200.") with no turn live. The arm emits Began { spoken: false } and sends:
{"clientContent": {"turns": [{"role": "user", "parts": [{"text": "[answer to \"q\"] AAPL is 200."}]}],
"turnComplete": true}}
Google's audio and {"outputTranscription": {"text": "Apple is 200."}} come back as Audio, Spoke("Apple is 200."), then Done.
A reconnect (a_session_outlives_one_go_away_with_its_context). Google sends {"sessionResumptionUpdate": {"newHandle": "p3", "resumable": true}}, later {"newHandle": "", "resumable": false} (ignored), then {"newHandle": "p4", "resumable": true} and {"goAway": {"timeLeft": "10s"}}. The arm opens a second socket whose setup carries "sessionResumption": {"handle": "p4"} and the same instruction, closes the first, and the microphone's next chunk is the new socket's first message. With no turn running and no speech in the last second the kernel sees nothing; while the user is mid-sentence the swap waits for a quiet second (a_go_away_during_input_transcription_keeps_the_old_socket_until_quiet). In a_close_mid_turn_resumes_on_the_handle_and_keeps_waiting_audio_in_order Google closes the socket instead, mid-reply, after handle p3: the arm emits Reconnecting, Done, waits 0.5 s, opens a socket whose setup carries {"handle": "p3"}, emits Reconnected, and the chunks that arrived meanwhile are that socket's first messages, in order.
The kernel's side of a send (a_send_puts_the_hand_off_and_its_answer_is_told_once_after_the_turn in engine/crates/taji/src/wire/voice.rs, with a scripted stand-in arm alpha, so its rates are its own). /ws/voice frames {"type": "ready", "provider": "alpha", "name": "Alpha", "desk": "d1", "session": …, "input_hz": 24000, "output_hz": 24000, "seq": 1}; the chat gets the prompt Buy 1 AAPL with "channel":"voice"; the captions run you "buy one apple", voice "Sending.", then agent with from "Claude Code".
Google's own frames for a real turn. No capture yet. The live suite asserts on Outputs and prints only CELL and ORDER lines; recording the frames of spoken_question_begins_spoken_and_ends_with_its_done would make one.
Testing
- The arm, offline:
cargo test -p taji-gemini. No key and no network: a local WebSocket server plays Live andwiremockplays the models list. The tests cover the setup and URLs, spoken and told turns, a heldturnComplete, interruptions and cuts with calls waiting, a late result, a cancelled call, an unknown tool,goAwaywith and without a turn running or speech arriving, a close mid-turn resumed on the handle, a close with no handle, a word or a refusal not retried, a close naming an invalid key (with the key kept out of the error), and the link's refusals. - The kernel's session, against a scripted arm:
cargo test -p taji --lib wire::voice. It covers link and unlink, the spoken-only gate, Tells and their order, cards and approvals, cuts, timers, binds and replacements. - The tool set:
cargo test -p taji-plugin --features voice the_voice_model_has_only_the_dispatch_tools. - Live:
cargo test -p taji-gemini --test live -- --ignored --test-threads=1 --nocapture, withGEMINI_API_KEYin your environment or the repo's.env, billed to that key. Speech comes from macOSsay, or a PCM or WAV file named byVOICE_LIVE_PCM. The tests:link_proves_key,spoken_question_begins_spoken_and_ends_with_its_done,speech_mid_answer_interrupts_it_and_is_answered,speech_while_a_call_waits_ends_every_turn, anda_cough_and_a_remark_to_someone_else_are_not_answered, which fails some runs until a remark to someone else goes unanswered. - The walk:
engine/crates/taji/scripts/voice_walk.py <port> link|say|steer|stop|order --provider gemini, against a headless kernel you started asAGENTS.mdsays, never your own Taji. Its header lists what each step speaks and checks;orderruns only ontaji_simand skips while any live account is linked.
References
Google's Gemini API docs, each fetched 2026-12-02:
- Live API WebSocket reference
- Get started with the WebSocket API
- Live API capabilities
- Session management
- Tool use
- Function declarations
- Gemini 4 Live
- Live thinking
- Deprecations
- List models
- API keys
- Rate limits
- API errors
In Taji: 0002, 0005, security, the README, the manifest.