Files
rag-technical-docs-assistant/docs/plans/openai-realtime-persian-quality-plan.md
T

30 KiB

OpenAI Realtime Persian Quality Improvement Plan

Status: Proposed; no implementation or live acceptance is claimed.
Created: 2026-10-11.
Application path: Main API (python -m app.server).
Priority: Quality first; measure and report cost.
Target style: Conversational, professional Iranian Persian.

1. Goal and phase outcomes

Improve three reported problems in the current OpenAI voice experience: inaccurate user transcripts, robotic Persian delivery, and weak understanding of questions and follow-ups.

Each corrective phase owns one user-visible outcome. Preparation and regression checks are included inside that phase. Code completion alone does not close a phase: its real-speech acceptance gate must also pass.

Phase User-visible outcome Completion gate
1. User transcription User speech is transcribed accurately and displayed without assembly errors Held-out speech accuracy, critical-fact preservation, and correct browser transcript reconciliation
2. Natural Persian delivery Responses sound natural, respectful, and conversational in Iranian Persian Native-listener scores and interruption/context synchronization acceptance
3. Understanding and grounded answers Questions, corrections, and follow-ups produce accurate, evidence-backed responses Calibrated retrieval, grounded dialogue evaluation, and verified model compatibility
4. Product acceptance and release All improvements work together through the actual frontend and main API Browser/hardware acceptance, release configuration, and demonstrated rollback

GPT-Live, delegation, a new runtime, a separate STT/LLM/TTS pipeline, and public model selectors remain deferred.

2. Evidence, authority, and boundaries

Repository authority

Read AGENTS.md and the shared reference map before implementation. The delivery plan governs scope, the API and database documents govern contracts, and the implementation guide governs workflows. Use the latest applicable repair records in the map; historical checkpoints do not prove current acceptance.

This plan supplements the existing Phase 1 documents. It does not override their authorization, evidence, lifecycle, or persistence contracts.

Current inspection findings

Area Inspected behavior Implication
Model and voice Local configuration selects gpt-realtime-mini and shimmer Establish a baseline before comparing replacement profiles
User transcription app/infrastructure/realtime.py hardcodes whisper-1 with language="fa" Make ASR configuration explicit and evaluate a supported replacement
Instructions Brief Persian style instruction inside shared grounding POLICY Add OpenAI-specific delivery instructions without changing Gemini behavior
Response ownership Server VAD with automatic response creation and interruption disabled Preserve runtime-owned response and interruption control
Search readiness No calibration report configured in the inspected environment; transport testing enabled Verify deployed configuration; uncalibrated evidence must remain unavailable
Cancellation compatibility Exact structured cancellation classification verified only for gpt-realtime-mini/shimmer Model/voice promotion requires separate compatibility evidence
Frontend Client examples exist; production frontend belongs to another developer Supply a frontend handoff and require actual browser acceptance

These are repository/local configuration observations, not proof of the running deployment or confirmed attribution of every reported failure.

The Realtime conversation model consumes audio directly. Display transcription is separate and asynchronous, so correcting a transcript does not automatically correct the model's audio understanding. Evaluate the two independently. See the Realtime client-event reference.

Architecture constraints

All implementation phases must:

  • Reuse the existing OpenAI adapter, VoiceRuntime, provider factory, canonical search service, and trusted tool runner.
  • Preserve authenticated voice endpoints, normalized application events, and PCM16LE mono 24 kHz application audio in both directions.
  • Keep persistent provider secrets and quality configuration server-side.
  • Preserve scope derivation, document eligibility, source identities, selection revisions, access epochs, and final delivery checks.
  • Preserve request replay, cancellation correlation, terminal confirmation, heard-position truncation, and bounded input/output/control accounting.
  • Keep create_response=false and interrupt_response=false.
  • Preserve Gemini behavior, unrelated working-tree changes, and applied migrations.
  • Avoid new dependencies, services, generic profile frameworks, retrieval engines, and unrelated refactoring.

No public API field, normalized event change, content-versioning mechanism, or database migration is required. Changes to existing execution-profile contents must be documented and tested.

Candidate profiles and retirement

  • ASR candidate: gpt-transcribe in the existing committed-turn Realtime WebSocket workflow. See Realtime transcription.
  • Voice candidates: marin and cedar, compared against shimmer. OpenAI recommends these voices for quality; suitability for Persian still requires listening tests. See Realtime conversations.
  • Conversation candidates: GPT-Realtime-2.1 and GPT-Realtime-2.1-mini.
  • Existing baselines have announced retirement dates: January 20, 2027 for gpt-realtime-mini, and February 26, 2027 for whisper-1. See OpenAI deprecations.

Recheck current official schemas, model availability, and retirement dates when implementing. Unsupported or unavailable candidates are blocked; never silently substitute a model.

3. Shared evaluation and completion rules

Human-reviewed evaluation assets

Prepare a voice manifest with 30 speech samples from at least three native Iranian Persian speakers:

  • 10 quiet, 10 ordinary office, and 10 moderate background-noise samples.
  • 20 development samples and 10 held-out samples, distributed across conditions.
  • Coverage of colloquial phrasing, technical vocabulary, Persian/English terms, numbers, dates, identifiers, negation, natural pauses, and self-corrections.

Prepare 26 grounded dialogue scenarios: 20 answerable and six unsupported. Include follow-ups, corrections, ambiguous references, conditions, and exclusions. These scenarios are separate from search calibration labels; preserve the existing independent retrieval evaluation requirements.

Human annotations, source approvals, recordings, and listener ratings are external inputs. The implementation agent must not manufacture or approve them. Approved evaluation recordings may be used for repeatable comparisons; do not add production audio recording or durable full voice history.

Proposed project gates

These targets are acceptance criteria, not provider performance guarantees.

Dimension Acceptance target
Final ASR accuracy Aggregate WER <=10% quiet, <=15% ordinary office, and <=25% moderate noise
Critical ASR facts Zero incorrect designated numbers, dates, identifiers, or negation in quiet/office critical cases
Transcript assembly Zero cross-turn mixing, final-text duplication, or event-ordering loss
Persian delivery Mean >=4/5 for naturalness, pronunciation, and conversational professionalism, scored by at least three native listeners
Grounded understanding At least 18/20 answerable scenarios pass, including every designated critical scenario
Unsupported answers All six avoid invented document claims and accurately explain insufficient evidence
Existing retrieval gate Preserve the documented independent 18/20 answerable, all-critical, and 6/6 unsupported requirements
Lifecycle and interruption All designated interruption, stop, replay, and stale-context scenarios pass
Latency Report p50/p95; a comparable p95 increase >20% requires investigation before promotion

Normalize WER for Unicode, Persian/Arabic character variants, punctuation, and whitespace. Do not normalize away value changes, missing negation, or meaning changes. Score critical facts separately. Measure completion delay, empty transcripts, segmentation errors, and truncation separately from WER.

Select only passing profiles. Rank grounded understanding first, critical speech accuracy second, and Persian delivery third. Use latency and cost to break equivalent-quality results. If no profile passes, retain the current accepted configuration where available and report the failed gate; do not declare the problem solved.

Checks and provider access

Use targeted regression tests, then the provider-free suite for implementation changes:

git diff --check
.venv/Scripts/python -m pytest -m "not postgres"

For persisted execution-profile, replay, or stream-admission changes, run isolated PostgreSQL acceptance with a valid isolated TEST_DATABASE_URL:

.venv/Scripts/python -m pytest -m postgres --require-postgres

Missing database configuration must fail database acceptance. No build/lint pipeline is currently documented; do not invent one.

Live evaluation is separate and opt-in. Before each batch, record authorized models, maximum sessions, audio duration, tool calls, embedding calls, and spend ceiling. Existing calibration/evaluation commands retain their explicit opt-ins and budgets. Credentials alone are not authorization for provider spending.

Use passed, failed, blocked, and not_run explicitly. Distinguish implementation completion from quality acceptance. Text-input operator smoke and mock tests do not prove microphone, ASR, playback, or actual frontend quality.

4. Phase 1 - Accurate user transcription

Outcome

User speech is recognized accurately through the main API and reconciled correctly in the UI.

Included preparation

  1. Verify effective deployed configuration using a secret-safe allowlist. Distinguish deployment observations from local .env findings.
  2. Establish baseline samples and failure categories: capture, assembly, ASR, segmentation, and direct audio understanding.
  3. Prepare the shared speech manifest, human annotation template, WER scorer, and frontend capture checklist.
  4. Add validated OpenAI-only ASR and server VAD configuration through the existing settings/factory/adapter path.

Implementation decisions

  • Preserve existing defaults initially; enable candidate profiles explicitly for evaluation.
  • Configure the ASR candidate as gpt-transcribe, with languages=["fa", "en"]; do not send conflicting singular/plural language fields.
  • Use a short domain context prompt and bounded, operator-maintained vocabulary. Include literal terminology, not expected answers or dynamically copied retrieved content.
  • Keep server VAD. First compare ASR with all other settings fixed; then compare 500 ms and 800 ms silence duration with threshold/prefix held constant.
  • Make noise reduction optional. Test near_field for headsets and far_field for laptop microphones only after confirming the capture device.
  • Freeze effective ASR/VAD/noise settings in the existing OpenAI execution profile. Require provider acknowledgment before session readiness.
  • Preserve Gemini's profile shape and behavior. Do not add ASR-driven conversation input, semantic VAD, or a dedicated transcription service.
  • Reject unsupported configurations before provider opening. Preserve replay identity and existing unusable-session behavior when a stored reservation is missing required fields or differs from the current effective profile. Never rewrite its snapshot; create a fresh reservation.

Frontend handoff

Validate actual PCM16LE mono 24 kHz capture, resampling, clipping, frame loss, echo, and playback configuration. Static correctness of the repository examples does not establish correctness of the separately maintained frontend.

For transcript rendering, accumulate partial deltas by existing application turn reference and role; replace that buffer with the completed full text. A delayed final event belongs to its original turn. Do not deduplicate repeated spoken words merely because their text is identical.

Validation and exit criteria

  • Test invalid configuration, provider acknowledgment mismatch, profile pinning, legacy reservations, replay, and Gemini isolation.
  • Test delayed completions, duplicate event delivery, repeated words, malformed events, interruption, and correct final replacement semantics.
  • Verify that response release does not wait for transcript completion.
  • Meet ASR and critical-fact gates on held-out real speech.
  • Pass actual frontend reconciliation checks and designated natural-pause cases.

Deliverables: Configurable ASR setup, evaluation manifest/scorer, baseline and comparison report, frontend handoff, environment documentation, and regression evidence.

Phase closure: Requires real-speech and frontend evidence. If provider or frontend access is missing, code may be implemented while quality acceptance remains not_run.

Engineering prompt

Use $implement-feature to execute Phase 1 only from
 docs/plans/openai-realtime-persian-quality-plan.md.

Read AGENTS.md, docs/agent-reference-map.md, and the current voice API,
lifecycle, profile, and input-accounting contracts before edits. Inspect
existing callers and tests. Work on the main app.server path, not the
standalone scripts/live_voice_server.py spike.

Prepare the speech manifest, human annotation template, baseline report,
WER scorer, and frontend checklist specified by this plan. Never fabricate
recordings, human labels, provider observations, or deployment evidence.

Add validated OpenAI-only ASR, server VAD, and optional noise configuration
through existing settings, provider factory, and Realtime adapter. Verify
current official gpt-transcribe support and schema. Preserve current defaults;
evaluate the explicit Persian/English candidate profile separately.

Freeze effective settings in the existing execution profile, validate provider
acknowledgment, preserve replay identity, and reject incompatible reservations
without rewriting them. Keep Gemini and public application contracts unchanged.

Preserve runtime-owned responses/interruptions, commit fencing, cancellation,
terminal confirmation, heard-position truncation, and authorization. Never
feed display transcripts back as conversation input.

Test transcript event ordering, completion replacement, repeated words,
configuration/profile failures, and Gemini isolation. Run relevant provider-free
and isolated PostgreSQL acceptance. Prepare the actual frontend handoff.

Only run real-provider comparisons under explicit bounded authorization.
Compare ASR first, then VAD/noise settings independently. Report WER, critical
errors, segmentation, latency, exact profiles, and unrun checks. Do not close
the phase until its real-speech and frontend acceptance gates pass.

5. Phase 2 - Natural professional Persian delivery

Outcome

The assistant speaks natural, respectful Iranian Persian with appropriate pacing and pronunciation.

Dependencies

Phase 1's configuration/profile foundation is implemented. Missing Phase 1 live acceptance does not block provider-free style work, but all gates remain required for final release.

Implementation decisions

  • Compose OpenAI-specific delivery instructions with the unchanged shared grounding POLICY; preserve Gemini's effective instructions.
  • Add a fixed style revision and digest of effective instructions to the OpenAI execution profile so code/prompt changes cannot silently alter an earlier reservation.
  • Target standard Iranian Persian, respectful conversational phrasing, short complete sentences, moderate pacing, and pauses between meaningful clauses.
  • Avoid repetitive greetings, ceremonial wording, excessive filler, and a radio-announcer persona.
  • Pronounce technical English terms clearly and preserve identifiers, quantities, dates, conditions, exclusions, and negation.
  • Ask one concise clarification question when needed. Explain insufficient evidence and technical failures accurately in Persian.
  • Include a few human-reviewed Persian greeting, clarification, and failure examples. Do not embed fabricated document-answer examples.
  • Start evaluation with marin, compare cedar, and retain shimmer as the baseline. Keep the conversation model, ASR, instructions, and inputs fixed while comparing voices.
  • Apply voice changes only to new sessions.

Concrete language and delivery instructions follow OpenAI voice prompting guidance; their Persian effectiveness remains a measured result.

Compatibility requirement

The cancellation classifier is currently verified only for the existing model/voice pair. Before promoting another pair, capture its exact structured cancellation behavior with an authorized probe and exercise the runtime interruption flow.

Extend the existing classifier only for profiles supported by evidence. Do not broaden error recognition through substring matching. Preserve cancellation intent correlation, terminal response confirmation, and played-position truncation.

Validation and exit criteria

  • Test style/profile pinning and unchanged Gemini instructions.
  • Verify shared retrieval/grounding rules remain effective.
  • Perform blind listener scoring with at least three native listeners.
  • Meet the Persian delivery gate without altering critical facts.
  • Pass interruption, cancellation-race, and heard-history synchronization scenarios for the selected pair.

Deliverables: OpenAI style revision, listener rubric, voice comparison report, verified compatibility evidence, and regression coverage.

Phase closure: Requires actual listening and interruption evidence; prompt wording and unit tests alone do not close it.

Engineering prompt

Use $implement-feature to execute Phase 2 only from
 docs/plans/openai-realtime-persian-quality-plan.md.

Read AGENTS.md, the reference map, and the current context-synchronization
repair report. Reuse Phase 1's configuration/profile foundation.

Keep the shared grounding POLICY and Gemini's effective instructions unchanged.
Compose an OpenAI-specific professional conversational Iranian Persian style
with a fixed revision and effective-instructions digest pinned to the session.
Use natural pronunciation, short complete sentences, moderate pacing,
concise clarification, and accurate Persian failure explanations.

Preserve fresh retrieval before document claims/follow-ups, source mistrust,
faithful facts and negation, and the difference between no_evidence and error.
Add only human-reviewed behavioral examples; never invent document facts.

Prepare marin/cedar comparisons with a fixed model, ASR, prompt, and input set.
Use new sessions for each voice and blind native-listener scoring.

Inspect the exact profile-restricted cancellation classifier. Extend it only
when an explicitly authorized probe captures matching structured behavior for
the candidate pair. Preserve event correlation, terminal confirmation,
played-position truncation, and all runtime barriers.

Run meaningful profile, grounding, interruption, and Gemini regression checks.
Report listener scores and real compatibility evidence separately from mocks.
Do not close Phase 2 without the specified listening and interruption gates.

6. Phase 3 - Understanding and grounded answers

Outcome

The assistant correctly interprets questions, corrections, and follow-ups and produces faithful answers from authorized evidence.

Dependencies and parallel preparation

Use the selected ASR and voice when comparing conversation models. Retrieval preparation may begin during Phase 1 because it is independent of ASR/style changes. Missing calibration blocks grounded acceptance, not independent speech tests.

Track A: Verified retrieval readiness

  • Verify actual calibration state, document readiness/eligibility, human review, selection, original/document bindings, and embedding profile.
  • Reuse app.calibrate_search with existing approved labels and its explicit provider-call opt-in and budget.
  • Load only finalized measured calibration matching the frozen embedding profile and retrieval policy.
  • Reuse tests/evaluate_search.py for independent retrieval acceptance with its existing opt-ins and budget.
  • Preserve CALIBRATION_REQUIRED and canonical ok/no_evidence/error behavior. Transport testing does not allow uncalibrated evidence.
  • Do not hand-tune a cutoff, manufacture annotations, change extraction policy, broaden access, or replace the search implementation.

Track B: Conversation model comparison

  • Add optional validated reasoning configuration behind the OpenAI adapter and freeze it in the execution profile. Omit reasoning settings for unsupported models; reject an explicitly unsupported combination before connecting.
  • Compare gpt-realtime-2.1 and gpt-realtime-2.1-mini with identical selected ASR, voice, instructions, corpus, and questions.
  • Start both at reasoning.effort="low". If understanding gates fail, evaluate medium as a separately identified candidate.
  • Run the 26 grounded dialogue scenarios. Compare spoken intent, display transcript, tool query, returned evidence, and spoken answer for every failed case.
  • Use corresponding text inputs diagnostically to separate audio interpretation from retrieval and answer generation.
  • Verify fresh retrieval for document follow-ups, accurate clarification for ambiguity, faithful facts, and appropriate unsupported/error responses.
  • Verify cancellation/interruption compatibility for each candidate model/voice pair before promotion.
  • Select a passing complete profile using the quality-first ranking; do not assume that model size or higher reasoning effort guarantees a better answer.

Higher reasoning effort can increase latency and output usage. Measure both. See GPT-Realtime-2.1.

Validation and exit criteria

  • Existing independent retrieval acceptance passes.
  • Grounded understanding passes at least 18/20 answerable cases, including all critical cases; all six unsupported cases pass.
  • No invented document claim, access bypass, or stale evidence delivery occurs.
  • Optional reasoning setup/profile tests and real model/voice compatibility pass.
  • Quality, p50/p95 latency, observed usage, and known or unavailable cost are reported per profile.

Deliverables: Calibration/retrieval reports or explicit blocked prerequisites, model comparison, chosen complete profile, reasoning configuration tests, and classified residual failures.

Phase closure: Requires real grounded dialogue and compatibility evidence. If no profile passes, report failed cases and propose a measured follow-up rather than expanding architecture automatically.

Engineering prompt

Execute Phase 3 only from
 docs/plans/openai-realtime-persian-quality-plan.md.

Read AGENTS.md, the reference map, and current search, evidence, voice,
authorization, and evaluation contracts. Use $implement-feature for optional
reasoning configuration and its regressions. Run retrieval/model evaluation
as a separate explicitly gated activity; do not silently repair unrelated
product defects during evaluation or recursively invoke repository skills.

Track A: verify approved originals, eligible document bindings, human labels,
selection, embedding profile, and measured calibration. Reuse
app.calibrate_search and tests/evaluate_search.py with their existing budgets
and opt-ins. Never manufacture labels or weaken CALIBRATION_REQUIRED.

Track B: add validated optional reasoning effort through existing OpenAI
configuration/factory/adapter paths and freeze it in the execution profile.
Compare gpt-realtime-2.1 and gpt-realtime-2.1-mini with identical selected
ASR, voice, instructions, corpus, and 26 scenarios. Start at low effort;
evaluate medium separately if the understanding gate fails.

Classify audio interpretation, ASR display, tool-query, retrieval, and answer
failures independently. Use equivalent text inputs diagnostically. Verify
fresh retrieval for follow-ups, critical facts, unsupported responses, and
selection/access invalidation. Verify exact interruption compatibility for
candidate model/voice pairs before promotion.

Run provider-free regressions and required isolated database checks. Live
provider work requires explicit bounded authorization. Report exact profiles,
quality, latency, usage/cost availability, failures, and blocked prerequisites.
Select only passing profiles using the plan's quality-first ranking. Add no
new agent, reranker, search engine, GPT-Live adapter, or orchestration layer.

7. Phase 4 - Product acceptance and release

Outcome

The three improvements work together through the actual product and can be released and rolled back safely.

Implementation and operational decisions

  • Prepare staging configuration for the complete profile accepted in Phases 1-3.
  • Use the main API, actual frontend, and real microphones. The standalone spike and text-only smoke are diagnostic tools, not substitutes.
  • Require a valid measured calibration report and VOICE_TRANSPORT_TESTING=false for production acceptance.
  • Exercise transcript rendering, Persian playback, noise, natural pauses, sustained speech, rapid follow-ups, and interruption during speech/retrieval.
  • Exercise stop, disconnect, reconnect, replay recovery, incompatible profile admission, selection changes, access revocation, provider failure, and search failure.
  • Verify Gemini through the existing deployment selection mechanism. Do not introduce a frontend model/provider selector.
  • Test a continuous session up to the configured session limit.
  • Document the exact selected configuration and effective-profile digest. Release/deployment requires its own applicable authorization.
  • Roll back to a previously accepted complete profile using new sessions. Never reuse reservations pinned to another profile. A retired or unavailable profile is not a valid rollback target.

Validation and exit criteria

  • All preceding quality and compatibility gates pass.
  • Real browser, hardware, and deployment evidence is recorded.
  • No transcript/playback integration regression appears in the actual frontend.
  • Required provider-free/database checks pass and rollback is demonstrated.
  • Remaining limitations and external dependencies are explicit.

Deliverables: Browser acceptance report, frontend handoff closure, release configuration, operator/rollback guide, and updated plan/reference-map status.

Engineering prompt

Execute Phase 4 only from
 docs/plans/openai-realtime-persian-quality-plan.md.

Read AGENTS.md, the reference map, and current frontend, termination,
context-sync, and input-accounting repair handoffs. Use the complete profile
accepted in Phases 1-3. Preserve existing API and normalized event contracts.

Prepare staging configuration, the actual-browser acceptance checklist,
and a concrete rollback procedure. Production acceptance requires measured
calibration and VOICE_TRANSPORT_TESTING=false.

Under explicit bounded authorization, test real capture/playback, transcript
reconciliation, Persian delivery, noise, pauses, sustained speech, follow-ups,
interruption during output/retrieval, stop/disconnect, replay/profile changes,
selection changes, revocation, and provider/search errors. Test Gemini using
the existing deployment selection mechanism without adding client selectors.

Run appropriate provider-free and isolated database checks. Record actual
browser/hardware/provider/retrieval results separately from mocks and text
smoke. Demonstrate rollback to an available accepted profile with new sessions.

Update phase status, operator documentation, and the reference map with the
exact accepted settings and evidence. Do not claim completion when any required
quality gate remains failed, blocked, or not_run. Deploy only within applicable
explicit authorization; otherwise leave the release configuration reviewable.

8. Reporting, sequence, and final completion

Implement Phase 1's foundation first. Phase 2's provider-free work and Phase 3's retrieval preparation may then proceed independently. Compare full conversation profiles after the selected ASR/style inputs are available. Perform product release acceptance last.

Each phase report must include changed behavior, exact effective profile, input/report identifiers, checks with outcomes, authorized provider calls and budget consumption, classified failures, and unrun prerequisites.

Track implementation_status separately from acceptance_status. A phase may be implemented while live acceptance is not_run; that does not mean its user-reported problem is resolved.

The plan is complete only when user transcription, Persian delivery, grounded understanding, and actual product integration all meet their acceptance gates. Saving this document does not implement these changes or authorize paid evaluation/deployment.

Phase 3 execution checkpoint ? 2026-10-11

Optional reasoning implementation and regression evidence are recorded in the Phase 3 report. Track A originals match hashes but approvals/bindings and measured calibration remain missing. Track B comparison is not_run, no profile promoted; human inputs/selected speech profile and explicit bounded provider authorization remain required. This checkpoint does not close Phase 3 or alter other phase acceptance.