docs(voice): freeze OpenAI Realtime Phase 0 contracts

Align voice specifications and the MVP plan with OpenAI Realtime.
Document audio admission, bounded playback, cancellation ownership,
turn correlation, cleanup barriers and calibration prerequisites.
Preserve historical checkpoints and record unrun acceptance gates.
This commit is contained in:
amirhosein mazaheri
2026-10-08 18:07:38 +03:30
parent 9dac244590
commit 6f0561c490
10 changed files with 834 additions and 48 deletions
+20 -20
View File
@@ -13,7 +13,7 @@ Document lifecycle decision (revision 1.1): every upload is an independent immut
## 1. Purpose and Scope
The current milestone is the conditional four-day Live document MVP governed by delivery plan revision 1.3. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; Gemini Live owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
The current milestone follows the delivery plan's scoped Phase 0 amendment and the Realtime MVP backend plan; its conditional 3-5 day estimate supersedes the earlier four-day integration sequence. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; OpenAI Realtime owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
@@ -23,7 +23,7 @@ The initial business use case is a reliable demonstration and subsequent organiz
- PostgreSQL with pgvector stores application data and document embeddings.
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
- Initial voice uses direct Gemini Live API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
- Initial voice uses direct OpenAI Realtime API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
- Documents are dynamically uploaded, updated and selected by the organization.
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
@@ -46,7 +46,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
4. **Backend-managed live audio:** the backend relays client audio to direct Gemini Live and executes authorized tools on the same controlled session.
4. **Backend-managed live audio:** the backend relays client audio to direct OpenAI Realtime and executes authorized tools on the same controlled session.
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
@@ -64,7 +64,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
| Live provider | Direct audio understanding and speech generation | External live model service |
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the Gemini Live connection, credentials, policy and tool execution; the provider service remains external.
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the OpenAI Realtime connection, credentials, policy and tool execution; the provider service remains external.
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
@@ -295,17 +295,17 @@ The worker claims jobs with a lease and claim token, updates progress and publis
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
## 8. Live Voice with direct Gemini API access
## 8. Live Voice with backend-managed OpenAI Realtime
### 8.1 Connection responsibilities
Use direct Gemini Live for the initial voice MVP. The provider connection is stateful WSS; the backend relays client audio and controls private tools. Browser-to-provider SDP/WebRTC from revision 1.1 is superseded for this MVP, not assumed compatible with Gemini. See [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api).
Use backend-managed OpenAI Realtime for voice, as authorized in the [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md). The provider connection is stateful WSS; the backend relays client audio and controls private tools. The browser uses the application stream, not provider SDP or credentials. See [Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations).
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional Gemini Live session.
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional OpenAI Realtime session.
### 8.2 Session establishment
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to Gemini with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS transport/event fields are proposed in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to OpenAI Realtime with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS audio/event fields are frozen in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
### 8.3 Voice tool cycle
@@ -313,7 +313,7 @@ Authenticate the HTTP creation request; persist the owned reservation and idempo
sequenceDiagram
participant U as Browser or approved audio bridge
participant B as Backend Live controller
participant L as Gemini Live
participant L as OpenAI Realtime
participant K as Shared knowledge service
participant D as PostgreSQL and pgvector
U->>B: Authenticated audio stream
@@ -331,7 +331,7 @@ sequenceDiagram
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools) require application handling of function responses; validate the chosen model's blocking/asynchronous capabilities rather than combining incompatible examples.
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Realtime function calling](https://developers.openai.com/api/docs/guides/realtime-conversations) requires application handling of function results and authorized response continuation through private provider call IDs.
### 8.4 Conversation, interruption and failure behavior
@@ -351,7 +351,7 @@ Seamless reconnect and provider context restoration are deferred. A new session
### 8.5 Audio, transcripts and telephony boundaries
The proposed application stream uses mono raw PCM matching Gemini: 16-bit little-endian input at 16 kHz and output at 24 kHz. Capture/resample browser audio and convert output for playback; do not forward compressed browser blobs as PCM. The provider accepts explicitly declared input rates, but standardizing the bridge simplifies the MVP. Interruption clears playback buffers. Verify these behaviors against the configured model using [Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
The frozen application stream uses raw mono signed PCM16LE at 24 kHz in both directions, governed by API Section 7.1. Capture/resample browser audio and convert output for playback; do not forward compressed blobs as PCM. user_speech_started, audio_started and validated playback_progress correlate turns and reported playback. One audio_ref covers one provider item/audio content part; audio_ended seals generation, not playback. API 7.1.1-7.1.4 governs integer sample coordinates, retained references, final reports after interruption, acknowledged private cleanup before continuation, transport bounds and sixteen walkthroughs. API 7.1.5 separately bounds generated audio and paces delivery using validated progress credits; 7.1.6 preserves delayed user ASR and gates response release on current committed input, valid authority/epoch and all cleanup barriers. Both VAD flags are false with backend-owned response-specific cancellation and narrow completion-race handling; normal exchanges are not relabeled interrupted. Interruption clears playback; cleanup failure closes the session instead of continuing with unheard context. See [Realtime audio and interruption](https://developers.openai.com/api/docs/guides/realtime-conversations).
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
@@ -454,7 +454,7 @@ Final application statuses include `answered`, `needs_clarification`, `insuffici
### 10.3 Live session application contract
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct Gemini Live. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct OpenAI Realtime. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
### 10.4 Error envelope
@@ -565,7 +565,7 @@ Remove indexing side effects from module imports. Re-embed the source documents
## 18. Implementation Sequence
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
1. Prove actual funded OpenAI Realtime Persian audio/transcripts/tools and target-network access early.
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
4. Implement one scoped pgvector search service using compatible existing embeddings.
@@ -584,7 +584,7 @@ and capacity/quality targets require confirmation. Documentation is not runtime
| --- | --- | --- |
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
| Configured OpenAI Realtime model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
@@ -601,9 +601,9 @@ These items must be resolved by their owners rather than silently converted into
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
- **[R3]** [Gemini Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools): correlated function calls/results.
- **[R1]** [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime): initial direct provider/session access.
- **[R2]** [OpenAI Realtime capabilities](https://developers.openai.com/api/docs/guides/realtime-conversations): audio, transcription and interruption.
- **[R3]** [OpenAI Realtime tools](https://developers.openai.com/api/docs/guides/realtime-conversations): correlated function calls/results.
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
## Appendix A. Presentation Diagrams
@@ -684,7 +684,7 @@ flowchart TD
CHAT <--> TEXT
SESSION -->|"Initialize and Control"| LIVE
UI <-->|"Authenticated audio WSS"| SESSION
SESSION <-->|"Direct Gemini Live WSS"| LIVE
SESSION <-->|"Direct OpenAI Realtime WSS"| LIVE
TOOL <--> SEARCH
SEARCH <--> DB
@@ -704,7 +704,7 @@ No standalone ADR directory or separate requirements specification was found. Th
| --- | --- |
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
| Confirmed provider direction | Direct Gemini Live; Flash vision extraction candidate; OpenRouter comparisons; USD 20 initial allocation and USD 30 planned budget |
| Confirmed provider direction | Direct Gemini Live (historical; superseded for voice by Phase 0); Flash vision extraction candidate; OpenRouter comparisons; historical USD 20 initial allocation and USD 30 planned budget |
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
@@ -719,7 +719,7 @@ See the [Persian sample scenarios](RAG-Phase1-Scenario-Report-FA.md) for local i
| Category | Current baseline |
| --- | --- |
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
| Confirmed framework | LangChain RAG/tools; direct Gemini Live audio loop |
| Confirmed framework | LangChain RAG/tools; direct OpenAI Realtime audio loop |
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |