feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy. Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics. Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
# Authenticated Gemini voice integration
|
||||
# Authenticated voice integration
|
||||
|
||||
Gemini Live is temporarily the sole voice provider because an OpenAI Realtime
|
||||
voice key is unavailable. Extraction, embeddings, calibration and canonical
|
||||
The backend selects Gemini Live or OpenAI Realtime with `VOICE_PROVIDER`. Gemini
|
||||
is the temporary default while an OpenAI Realtime voice key is unavailable. Extraction, embeddings, calibration and canonical
|
||||
search retain their existing providers and frozen profiles. The browser never
|
||||
receives a provider credential, event, model selector or private call ID.
|
||||
|
||||
@@ -13,7 +13,8 @@ same origin. This is a developer example, not a production interface.
|
||||
import {VoiceClient} from './voice-client.js';
|
||||
const client = new VoiceClient(event => console.log(event.type));
|
||||
await client.login(username, password); // supply credentials from your local form
|
||||
await client.reserve(); // retain request IDs for identical retries/recovery
|
||||
client.newCreationAttempt(); // exposes IDs before C01 and retains immutable payloads
|
||||
await client.reserve(); // after an ambiguous response: await client.retryCreation()
|
||||
await client.connect(); // call from a user gesture permitting AudioContext
|
||||
// On explicit stop: await client.close(); await client.poll();
|
||||
// On media loss: await client.recover(); await client.freshSession();
|
||||
@@ -23,7 +24,7 @@ await client.connect(); // call from a user gesture permitting AudioContext
|
||||
`GET /api/v1/me` refreshes actual expiry and CSRF. HTTP mutations use the opaque
|
||||
cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin.
|
||||
The API accepts no bearer or query token. Preserve the same normalized payload
|
||||
and request ID after ambiguous creation; V03 recovers without opening Gemini.
|
||||
and request ID after ambiguous creation; V03 recovers without opening a provider connection.
|
||||
Connected/terminal recovery does not restore media/provider context. Close the
|
||||
old reservation before requesting a fresh conversation and session.
|
||||
|
||||
@@ -36,9 +37,20 @@ and sources are retrieved/current-session information, not durable full history.
|
||||
The client waits for `session_ready` before opening the microphone. It verifies
|
||||
an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes
|
||||
channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context
|
||||
rates fail explicitly. Sending is bounded by WebSocket buffered bytes. Ordered
|
||||
rates fail explicitly. Capture enforces dual capacity bounds of 96000 raw PCM bytes
|
||||
AND 100 messages across capture handoff and outgoing WebSocket buffering. The worklet
|
||||
tracks both pending messages and pending bytes (rejecting with overflow if either limit
|
||||
would be exceeded). Capture handoff does not falsely imply network completion: the client
|
||||
polls socket.bufferedAmount and delivers `{type: 'accepted', bytes}` to the worklet only
|
||||
upon verified conservative buffer drain (`captureBytes - bufferedAmount >= packetBytes`).
|
||||
Capacity is released exactly once on verified drain or terminal cleanup. Ordered
|
||||
binary playback belongs to the last audio_started reference and is sealed by
|
||||
audio_ended. The playback worklet bounds samples and reports the floor of actual
|
||||
audio_ended. The client reserves playback capacity before PCM conversion and counts pending
|
||||
MessagePort handoffs. The worklet independently enforces 96000 raw PCM bytes AND
|
||||
100 messages across references, retaining a partially consumed packet in the
|
||||
message count. Consumed-sample acknowledgements release byte reservations; only
|
||||
completed/discarded packets release message reservations, exactly once. Admission
|
||||
and flush acknowledgements never imply heard audio. The worklet reports the floor of actual
|
||||
consumed samples / 24, never estimated elapsed time or generated samples.
|
||||
Interruption flushes queued audio and reports each reference's final consumed
|
||||
position. Explicit close stops capture and tracks, flushes actual final playback progress
|
||||
@@ -71,3 +83,122 @@ Technical fake-wire/worklet checks, retrieval quality and real-browser speech
|
||||
acceptance are separate. Real microphone/Persian audio/network behavior remains
|
||||
unverified until explicit provider opt-in, approved corpus, measured compatible
|
||||
calibration and budgets are supplied. See the [repair report](realtime-agent-phase2-repair.md).
|
||||
|
||||
## Creation attempts and recovery
|
||||
|
||||
`newCreationAttempt()` explicitly selects new C01 and V01 request IDs and retains
|
||||
C01's immutable payload before either request. `creationAttempt`,
|
||||
`conversationRequestID` and `requestID` are inspectable after failure. Once C01's
|
||||
response supplies the owned conversation ID, V01's immutable payload is stored
|
||||
before sending V01. `retryCreation()` (or `reserve()` with the existing attempt)
|
||||
replays identical payloads and IDs after a committed response is lost. Calls with
|
||||
changed IDs require an explicit new attempt; payload mutation is rejected locally,
|
||||
and changed payloads at the backend retain IDEMPOTENCY_CONFLICT behavior.
|
||||
`recover()` uses V03 and never connects automatically; a lost C01 response may
|
||||
precede V01, so recovery can return SESSION_NOT_FOUND until identical C01/V01 retry.
|
||||
`freshSession()` explicitly closes/reconciles the old reservation, creates a new
|
||||
attempt and connects. Retain the attempt in application storage if page reload
|
||||
recovery is required; this example retains it only in the current JS instance.
|
||||
|
||||
## Backend configuration and supported startup
|
||||
|
||||
Gemini deployment (no OpenAI voice key required):
|
||||
|
||||
```dotenv
|
||||
VOICE_PROVIDER=gemini
|
||||
GEMINI_API_KEY=<server-only-key>
|
||||
GEMINI_MODEL=gemini-2.0-flash-exp
|
||||
GEMINI_VOICE=Aoede
|
||||
# GEMINI_PROXY=https://trusted-proxy.example:443
|
||||
```
|
||||
|
||||
OpenAI deployment (no Gemini key required):
|
||||
|
||||
```dotenv
|
||||
VOICE_PROVIDER=openai
|
||||
OPENAI_REALTIME_API_KEY=<server-only-voice-key>
|
||||
OPENAI_REALTIME_MODEL=gpt-realtime-mini
|
||||
OPENAI_REALTIME_VOICE=shimmer
|
||||
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
|
||||
```
|
||||
|
||||
Existing `GEMINI_*` names and legacy `PROVIDER` remain valid. Matching provider
|
||||
aliases are accepted; conflicting `VOICE_PROVIDER`/`PROVIDER` across environment
|
||||
and dotenv configuration fail. Explicit constructor settings otherwise take
|
||||
priority over environment, then dotenv. `OPENAI_API_KEY` is not a voice alias:
|
||||
embedding and other provider configuration remain independent. A compatible
|
||||
measured `SEARCH_CALIBRATION_REPORT` and the existing origin/host/cookie settings
|
||||
are still required. Do not put secrets in browser configuration. Model defaults
|
||||
are compatibility defaults, not claims of current live service availability.
|
||||
Reservation snapshots pin selected provider/model/voice/native rates plus search
|
||||
profile; stream admission rejects a changed configuration. Durable V01 replay
|
||||
still returns the original reservation without reinterpreting it.
|
||||
|
||||
```sh
|
||||
.venv/bin/python -m app.server --host 0.0.0.0 --port 8000
|
||||
# Separate ingestion process:
|
||||
.venv/bin/python -m app.worker
|
||||
```
|
||||
|
||||
Docker Compose uses the same API entrypoint. Run exactly one API process and no
|
||||
API reload/multiple workers: media admission and runtime registry are process-local,
|
||||
not distributed ownership. The ingestion worker is a separate process. For
|
||||
production use trusted same-origin HTTPS/cookie settings and bounded reverse proxy
|
||||
configuration; a proxy cannot substitute for backend message reassembly limits.
|
||||
|
||||
The supported entrypoint explicitly selects `BoundedWebSocketProtocol` over the
|
||||
installed Uvicorn legacy WebSocket implementation, configured with validated
|
||||
`LIVE_*` `RuntimeSettings`. It performs bounded reassembly using finite scratch
|
||||
storage (`bytearray`) and an incremental UTF-8 decoder without retaining an unbounded
|
||||
list of continuation metadata (preventing long empty-continuation memory retention).
|
||||
Cancellation and connection termination release all scratch and assembly resources.
|
||||
The parser rejects binary messages above `max_binary_message_bytes` (default 9600 bytes)
|
||||
and UTF-8 text above `max_client_control_bytes` (default 4096 bytes), including aggregate
|
||||
fragments, from declared frame lengths before reading payload/decoding. Compression is not
|
||||
negotiated; any RSV/compression bit is rejected from the first two header bytes.
|
||||
Total receive capacity strictly accounts for assembling, queued, and delivered/in-flight
|
||||
messages against `max_queued_audio_messages` and `max_queued_audio_bytes`. Delivering a
|
||||
message to the ASGI application retains its reservation until the next `recv()` call,
|
||||
preventing an unmonitored runtime audio backlog. Queue depth is configured as
|
||||
`max(1, max_queued_audio_messages - 2)` when the budget exceeds two, or one for small
|
||||
budgets, preventing zero-capacity deadlocks on message budgets of one and two while
|
||||
retaining deterministic wire backpressure. TCP/StreamReader scratch and kernel
|
||||
buffers are separate finite transport buffers, not playback or commitment evidence.
|
||||
Application checks remain defense in depth. Generic `uvicorn app.main:app`, `ws=auto`
|
||||
and alternate/sansio backends are outside this supported policy. The selected legacy
|
||||
backend is deprecated upstream: rerun real loopback tests on dependency upgrades;
|
||||
replacement needs equivalent pre-payload enforcement, not renamed flags alone.
|
||||
|
||||
Authority-check saturation, timeout and SQL failure stop the session with
|
||||
SEARCH_SATURATED, SEARCH_TIMEOUT and DEPENDENCY_UNAVAILABLE respectively; unverified
|
||||
content/continuation is withheld. Verified revocation uses CONTEXT_REVOKED. Technical
|
||||
failures persist `failed` with matching close reason/error code; committed terminal
|
||||
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
|
||||
saturation, but a database outage can still prevent a durable write and is logged.
|
||||
|
||||
## Continuous idle input limitation
|
||||
|
||||
The example continuously sends microphone PCM after readiness, including silence.
|
||||
The frozen input-since-commit budget is 480000 bytes (10 seconds at 24 kHz PCM16LE).
|
||||
Without verified native commitment, exactly 480000 bytes are accepted; the next
|
||||
sample fails LIVE_BUFFER_OVERFLOW and closes. Native input consumption/transport
|
||||
send is not commitment. This behavior is deterministic for an idle Gemini fake
|
||||
with no activity boundary and applies to uncommitted admission for either adapter.
|
||||
|
||||
Longer continuous idle operation remains a product/provider-contract decision.
|
||||
This example does not gate silence, fabricate commitment or add browser activity
|
||||
controls. Use explicit stop/close and a fresh eligible session after overflow;
|
||||
do not assume uninterrupted idle capture or seamless Gemini barge-in is supported.
|
||||
|
||||
Automated fake-provider/loopback/worklet results prove technical boundaries only.
|
||||
Real provider access, measured retrieval quality, Persian speech, microphone,
|
||||
heard audio and browser/hardware acceptance require their separate explicit opt-ins
|
||||
and prerequisites; frontend readiness is not certified.
|
||||
|
||||
## Document workflow integration
|
||||
|
||||
Use the [Phase 3 HTTP handoff](realtime-agent-phase3-handoff.md) and delivered
|
||||
DocumentClient with this VoiceClient. F01 exposes current OCR policy; document
|
||||
polling exposes its frozen policy and actual review state. Automatic OCR admission
|
||||
does not imply human review, factual authority, readiness or activation. Read K01
|
||||
before replacing selection; removal revokes active voice context.
|
||||
|
||||
Reference in New Issue
Block a user