feat(voice): specialize prompt for Isfahan Industrial Parks, emit source excerpts, and bound generation

- Specialize voice assistant identity and agent system prompt for «شرکت شهرک‌های صنعتی اصفهان» (English instructions with Persian proper names)
- Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events
- Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event
- Handle old-turn search cancellation safely on turn supersession
- Add end-to-end search tracing pipeline and diagnostic CLI
- Add database organization title and settings update script
This commit is contained in:
amirhosein mazaheri
2026-10-12 17:35:28 +03:30
parent f14166a89f
commit 117fda7cc9
29 changed files with 1476 additions and 67 deletions
+23
View File
@@ -2170,3 +2170,26 @@ HTTP readiness and localhost:4200 CORS preflight passed. No OpenAI voice calls.
Independent 26-case evaluation, real speech/delivery and candidate interruption
acceptance remain unrun; Phase 3 is still open. Earlier no-call checkpoints above
are historical and precede this separately approved operational workflow.
## OpenAI bounded voice generation repair (2026-10-12)
The [scoped implementation and frontend handoff](guides/openai-output-limit-repair.md)
records OPENAI_REALTIME_MAX_OUTPUT_TOKENS (default 256), acknowledged session
generation limits and pinned profiles/instruction revision. Validated audio-only
max_output_tokens terminal responses remain incomplete/limited, drain exact
existing credits, and preserve interruption, truncation and next-turn gates.
Incomplete tools fail safely; OpenAI tool execution waits for successful terminal
validation. Gemini setup/policy and all existing audio bounds remain unchanged.
New application answer_limited and assistant transcript status limited are
documented with the example consumer. Old incompatible reservations are replayed
without rewriting but fail stream admission. Per-report VOICE_PLAYBACK logging
was removed; bounded failure diagnostics remain.
Final checks: 385 focused passed plus 40 final limit/authority checks; 1932 full
provider-free passed (three existing Windows symlink skips); 32 profile/incident
and eight existing two-provider ASGI isolated PostgreSQL cases passed, zero
database skips. Missing database configuration failed explicitly. Disposable
schemas/containers/volumes were removed and operational services were untouched.
See the handoff for exact commands, intermediate failures and scoped file list.
No provider calls, actual Angular/browser validation, measured audio-duration
guarantee, deployment or speech-quality acceptance is claimed.
@@ -8,7 +8,7 @@
"dimensions": 1024,
"preprocessing_version": "v1"
},
"distance": 0.33686461167069426,
"distance": 0.65,
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
},
"complete_support": 6,
+194
View File
@@ -0,0 +1,194 @@
# OpenAI output generation limit (2026-10-12)
Long provider responses can fill the 1,440,000-byte aggregate outstanding-audio
reservoir even when playback reports correctly release 48 bytes per millisecond.
This change prevents excessive generation through a server-side token budget;
it does not enlarge the reservoir or alter playback accounting.
## Behavior and configuration
OPENAI_REALTIME_MAX_OUTPUT_TOKENS defaults to 256, validated as an integer from
1 through 4096. The conservative initial budget leaves substantially less room
for generation than the provider's unbounded default. It encourages a short
initial answer; further detail requires a genuine user turn. The budget includes
tool calls and audio/text output. It is not an exact PCM-duration bound, and 256
has not been measured with the selected provider/model/voice. Deployments raising
it need measured healthy-playback acceptance. Genuine overflow remains fatal.
The session.update maximum is acknowledged exactly and inherited by every
backend response.create, including tool continuations. Provider, model, voice,
ASR, VAD and reasoning selection remain unchanged. Gemini receives neither
the setting nor the revised OpenAI delivery instructions.
New OpenAI execution profiles freeze max_output_tokens, style revision
iranian-persian-professional-v2 and the effective instruction digest. Existing
reservations/profiles/request hashes are never rewritten. Replay/recovery returns
the original reservation identity; stream admission rejects absent or mismatched
generation limits/revisions using the existing pinned-profile rule. Start a fresh
session after deploying this change. JSON profile extension needs no migration.
Only an OpenAI incomplete terminal response with status_details.type=incomplete,
reason=max_output_tokens, no error and a matching maximum (if supplied) receives
the limited-audio treatment. Its output layout, identities and audio-done events
must validate. Already generated audio drains through the existing credit window.
The response stays incomplete internally; its application answer is limited.
No automatic continuation, retry, fake speech or interruption is emitted.
Failed, filtered, unknown incomplete, malformed and synchronization outcomes
remain fatal under their applicable policies. A cut-off tool phase also fails
safely: this implementation does not have an acknowledged function-item deletion
barrier for continuing with an incomplete tool in context. OpenAI argument-done
events stage calls; successful terminal validation gates actual retrieval.
Incomplete tool arguments never execute, and limited tools never continue.
Malformed arguments in a successful response retain canonical normalized errors.
Normal retirement of limited audio requires the same exact generated/sent/played
confirmation as completed audio. Rounded tails require acknowledged truncation.
Genuine speech before playback drains interrupts the old output and uses the
unchanged final-progress, terminal/cancel and heard-position truncation barriers.
Next-response creation still requires current commitment, authority, context
cleanup and exactly-once intent admission.
## Application events and frontend integration
New server event:
```json
{"type":"answer_limited","turn_ref":"live-turn-1","reason":"output_token_limit"}
```
It marks a limited initial answer without flushing or stopping playback.
Transcript status now additionally allows limited for assistant final generated
text. OpenAI transcript-done is held within the existing finite control budget
until terminal validation: it becomes completed only for successful generation,
limited for a validated token limit, or is suppressed on interruption/failure.
Transcription completion is still independent of confirmed playback.
examples/voice-client.js forwards answer_limited through onEvent; no playback
change is needed. examples/voice-transcripts.js retains exact final text and the
limited marker, with interruption taking precedence. The actual Angular app is
absent from this repository. Its developer must accept the event/status, show a
partial/limited label and offer a user-invoked continuation, without flushing
audio, reporting invented progress, closing the session or automatically sending
a continuation. Actual Angular reconciliation remains unverified.
The operator smoke acceptance checker deliberately still requires a completed
answer. A limited answer must not become a successful quality-acceptance report.
## Validation and remaining acceptance
Executed commands and final results are recorded below. Tests are synthetic,
provider-free except for the isolated PostgreSQL profile checks. No paid provider
calls, browser hardware tests, application restart or deployment were performed.
Existing unrelated working-tree edits are preserved. Temporary per-report
VOICE_PLAYBACK logging was removed; bounded failure diagnostics remain.
Official references:
- [Realtime server events](https://developers.openai.com/api/reference/resources/realtime/server-events)
- [Realtime client events](https://developers.openai.com/api/reference/resources/realtime/client-events)
## Fresh-session acceptance procedure
1. Deploy the change with the same selected OpenAI model/voice and the default
256-token limit; create a fresh owned voice session.
2. Request a long, grounded explanation with material numbers and exceptions.
3. Confirm a concise initial answer, normal progress, bounded outstanding audio
and a usable session. If the token cap is reached, confirm answer_limited and
limited display rather than completed; verify exact provider outcome privately.
4. After playback drains, say "continue." Confirm fresh retrieval when required
and exactly one response for the new committed turn.
5. Interrupt another response during generation and during limited-answer playback.
Verify final played position, matching truncation acknowledgment, no leaked old
audio, no early response release and a usable subsequent turn.
Record token usage, maximum reservoir occupancy, generation/played duration,
source grounding, critical facts and interruption results. Any funded provider
run needs separate explicit bounded authorization. The conservative default is
implemented and offline tested, not proved by real-provider measurement.
## Changed files
- .env.example
- app/infrastructure/realtime.py
- app/modules/voice/configuration.py
- app/modules/voice/openai_style.py
- app/modules/voice/runtime.py
- examples/voice-transcripts.js
- tests/unit/test_openai_output_limit.py
- tests/unit/test_realtime_phase1.py
- tests/unit/test_realtime_remaining.py
- tests/integration/test_openai_speech_profile.py
- tests/support/voice_transcripts.mjs
- docs/specifications/RAG-Phase1-API-Catalog.md
- docs/specifications/RAG-Phase1-Database-Design.md
- docs/specifications/RAG-Phase1-Implementation-Guide.md
- docs/agent-reference-map.md
- docs/guides/openai-output-limit-repair.md
Existing edits to Dockerfile, Gemini adapter, main, knowledge code, measured
calibration and scripts/search_cli.py were outside this task. Existing shared
POLICY/tool-description edits in realtime.py were retained. The temporary runtime
VOICE_PLAYBACK instrumentation was deliberately removed as requested.
No dependencies, migrations, lifecycle database statuses or operational services
were changed.
## Executed checks
The focused command used the following nine files:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_openai_output_limit.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_remaining.py tests/unit/test_realtime_repairs.py tests/unit/test_openai_speech_configuration.py tests/unit/test_openai_reasoning.py tests/unit/test_openai_persian_style.py tests/unit/test_voice_client_example.py tests/unit/test_voice_session_incident.py -q -p no:cacheprovider --tb=short
```
Result: **385 passed**, 43.33 s. After retaining the original post-retrieval
revocation proof with an explicit continuation authority barrier:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_realtime_phase1.py::test_authority_revocation_gates_continuation tests/unit/test_openai_output_limit.py -q -p no:cacheprovider --tb=short
```
Result: **40 passed**, 6.33 s.
Earlier targeted attempts: 22 failed/295 passed while tests still assumed
preterminal tool execution; those cases now assert no execution before terminal
success. A subsequent run had 3 failed/346 passed due to invalid new fixture
speech coordinates and an incorrect expected stall code; these were corrected
to existing input-ordering and LIVE_BUFFER_OVERFLOW contracts. No product
assertions were relaxed. Intermediate focused runs passed 101 and 378 cases.
The first broad provider-free run passed 1925 cases, three existing Windows
symlink skips, 435 PostgreSQL cases deselected, 293.98 s; it preceded the last
seven additional unit cases and final test refinements.
Final profile/incident database acceptance:
```powershell
# Process-local TEST_DATABASE_URL points exclusively to the task-created database.
.venv/Scripts/python -m pytest tests/integration/test_openai_speech_profile.py tests/integration/test_voice_session_incident.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short
```
Result: **32 passed**, zero skips, 120.84 s. Earlier iteration: 31 passed,
119.39 s. Original VAD mismatch coverage was retained alongside token mismatch.
Additional existing two-provider ASGI acceptance:
```powershell
.venv/Scripts/python -m pytest tests/integration/test_phase2_postgres.py -k 'actual_asgi_tool_dispatch_persistence_and_public_sources or selected_provider_reservation_ready_audio_and_pinned_replay' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
```
Result: **8 passed**, 53 deselected, zero skips, 40.65 s. Verifies actual canonical
retrieval, durable tool outcomes/public sources and pinned stream setup for both
providers, including successful OpenAI execution after terminal validation.
Isolation: fresh PostgreSQL 16.15 / pgvector 0.8.7 container
rag-output-limit-20261012-test, loopback port 55443, database rag_output_limit_test.
It was recreated for the additional ASGI cases. Disposable schemas were removed
by fixtures; both cleanup inspections found zero remaining test schemas and zero
public tables. The task container and anonymous volume were removed after each
run. No operational database was used and unrelated containers were preserved.
With TEST_DATABASE_URL empty, the required legacy_limit profile test produced
one expected prerequisite error: "TEST_DATABASE_URL is required for PostgreSQL
acceptance", 20 cases deselected, 1.38 s. Ordinary suite skips are not database
acceptance. Broader PostgreSQL acceptance beyond the affected cases was not run.
git diff --check passed; only existing CRLF normalization notices were emitted.
No angular.json or package.json application was found in this repository.
Final full provider-free acceptance against the completed code:
```powershell
.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
```
Result: **1932 passed, 3 existing Windows symlink skips, 436 PostgreSQL cases
deselected**, 25 existing WebSocket deprecation warnings, 302.21 s.
The three skips are one intake and two storage-root symlink permission cases;
no new acceptance skip was introduced. No runtime code changed after this run.
+38 -3
View File
@@ -416,7 +416,7 @@ Require provider-confirmed cancellation/terminal generation within 5 seconds of
The backend is the sole cancellation and response-creation owner. Configure private VAD create_response=false AND interrupt_response=false and require provider configuration acknowledgement; VAD still reports speech/commit events. The proof's defaults are not evidence of this configuration. For a known active old response, send at most one response.cancel with that specific private response_id and a unique private event_id mapped to the cancellation intent; never issue a bare cancel that could hit a newer response. Record terminal response.done state by response identity. If completion or provider cancellation was already observed for that response, skip cancellation and proceed to required playback/context cleanup.
A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/incomplete handled as technical failure) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors.
A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/other incomplete handled as technical failure; the validated audio-only output-token limit below is terminal but limited) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors.
Keep both VAD flags disabled throughout the session. Unexpected automatic generation/cancellation is an observable configuration/protocol deviation; correlate any actual terminal event for cleanup, suppress unintended output and fail if the controlled state cannot be established. The independent response-release gate in 7.1.6 applies even after all cleanup acknowledgements arrive. This is a future runtime obligation, not proof-script behavior.
@@ -489,7 +489,7 @@ User transcription is independent ASR of committed input, not assistant response
Assistant transcripts/audio/tool output use private response/item/call-to-turn correlation. An assistant transcript done event is not proof of successful generation or audible completion: it may occur on cancellation. After actual interruption/supersession, suppress late assistant partial/done/completed events and tool outputs; they cannot restore completed display state or output audio. Already visible interrupted assistant text stays marked interrupted, without invented precise truncation. Delayed user transcripts are expressly exempt from that assistant-only suppression rule.
Normal exchange completion requires a terminal successful response, no pending tool/continuation or unsent G/T, and valid progress confirming all whole-millisecond output. An unconfirmed submillisecond tail receives conservative private cleanup before subsequent response release without automatically relabeling an otherwise completed exchange interrupted. For that normal tail, no active response needs cancellation and no interruption/final-report window is restarted; freeze its existing maximum reportable progress, transition the ref to finalizing with its stall timer invalidated, acknowledge private truncation, then retire the ref before subsequent response release. A new user turn after normal completion emits user_speech_started only; completed transcripts/sources retain their state. Actual interruption means unfinished generation/tool work, unsent audio or meaningful unplayed audio existed when genuine new speech started. Emit turn_interrupted only for that affected old turn. A pending request superseded before any assistant output is cancelled internally; do not fabricate an interrupted answer/transcript. Completed generation with queued playback is still interruptible.
Normal exchange closure requires a terminal successful response or the validated limited-audio outcome below (which never means a complete answer), no pending tool/continuation or unsent G/T, and valid progress confirming all whole-millisecond output. An unconfirmed submillisecond tail receives conservative private cleanup before subsequent response release without automatically relabeling an otherwise completed exchange interrupted. For that normal tail, no active response needs cancellation and no interruption/final-report window is restarted; freeze its existing maximum reportable progress, transition the ref to finalizing with its stall timer invalidated, acknowledge private truncation, then retire the ref before subsequent response release. A new user turn after normal completion emits user_speech_started only; completed transcripts/sources retain their state. Actual interruption means unfinished generation/tool work, unsent audio or meaningful unplayed audio existed when genuine new speech started. Emit turn_interrupted only for that affected old turn. A pending request superseded before any assistant output is cancelled internally; do not fabricate an interrupted answer/transcript. Completed generation with queued playback is still interruptible.
Use a private monotonic current-turn generation token independent of access_epoch. A genuine speech start advances it, establishes a speaking input turn, makes older unfinished/pending work ineligible and adds every affected older response to the session cleanup set. Duplicate provider event IDs, or repeated speech-start for the same mapped input item/start position, do not advance it or restart cleanup. Distinct authenticated provider input item/start identities in forward media order are genuine subsequent speech; a known older item or delayed older start is not a new turn. Contradictory identities/ordering fail safely. Replays do not become genuine simply because their event_id differs. None of these private IDs/tokens is sent to the browser.
@@ -503,7 +503,7 @@ If T3 genuinely starts while T1 cleanup is pending and T2 has not been released,
Transcript status is partial, completed or interrupted. The backend assigns turn_ref at trusted user speech start and retains original-turn correlation for delayed events. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Transcript status is partial, completed, interrupted, or limited (assistant only). The backend assigns turn_ref at trusted user speech start and retains original-turn correlation for delayed events. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Interruption, final progress, acknowledged context cleanup and late-output suppression follow 7.1.2; generation completion is not playback completion. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
@@ -629,3 +629,38 @@ false. D06/D07 and same-job D04 approval/retry semantics remain unchanged; no ch
are published while review is pending. Approval attests to exact output, including
completeness; reject missing/inaccurate content rather than approve guesses. Fatal
format/provenance/readability failures still map to EXTRACTION_QUALITY_FAILED.
### OpenAI generation-limit amendment (2026-10-12)
Server-only OPENAI_REALTIME_MAX_OUTPUT_TOKENS defaults to 256 (integer 1..4096).
Session setup must acknowledge it; initial responses and tool continuations inherit
it. New execution_profile snapshots freeze max_output_tokens and revised OpenAI
instruction revision/digest. Missing/mismatched old snapshots fail existing stream
admission without rewriting reservation identities or profiles. Gemini is unchanged.
This budget includes tool calls and is not a measured PCM-duration guarantee.
All existing reservoir, credit, transport/browser and timeout bounds remain.
A validated OpenAI response.done with status=incomplete,
status_details.type=incomplete and reason=max_output_tokens, no error, and matching
max_output_tokens if supplied is an intentional limited answer only when its
audio-only output/identity set and audio-done events validate. Preserve valid audio
and exact counters; drain and retire through 7.1.1/7.1.5. Failed, content-filtered,
other incomplete, malformed and context synchronization errors remain failures.
Incomplete tool phases fail safely, without executing cut-off calls or continuing.
OpenAI argument-done stages calls; validated successful terminal output permits
execution. No automatic retry or response chaining bypasses the budget.
Emit server-only {"type":"answer_limited","turn_ref":"live-turn-1","reason":"output_token_limit"}
once for a current uninterrupted limited answer. It does not seal or flush audio.
Final assistant transcript text uses status=limited rather than completed.
OpenAI transcript-done alone is held within the existing control reservation budget
until successful/limited terminal validation, then released or suppressed on
interruption/failure. Transcript completion never claims playback confirmation.
A limited answer retains that display state after normal exchange closure;
genuine interruption takes precedence. Missing transcripts stay unavailable.
All 7.1.2/7.1.6 input-commitment, current-turn, authority, terminal, final-progress,
cleanup-ack and intent gates still apply. Limited generation alone neither creates
a new user turn nor releases a response. A later genuine user turn after fully
drained/cleaned limited output emits no fabricated turn_interrupted.
See docs/guides/openai-output-limit-repair.md for consumer and acceptance details.
@@ -487,3 +487,13 @@ rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
### OpenAI generation-limit profile amendment (2026-10-12)
New OpenAI live_sessions.execution_profile JSON freezes max_output_tokens (default
256) alongside audio_input, reasoning, style_revision and instruction digest.
Existing reservation profiles/request hashes are immutable: replay returns the
original identity, and missing/mismatched profile fields reject stream admission.
No schema/migration or session status enum changes. A limited audio answer keeps
the session connected; incomplete tool/provider/context failures remain terminal.
Current-session limited transcripts/events are not durable voice history.
@@ -339,3 +339,16 @@ with no evidence; no arbitrary threshold or synthetic calibration is installed.
Current policy/profile must still match the reservation on stream admission; policy
changes cannot silently upgrade, downgrade or switch a reserved provider. Health
remains provider-free. Real voice/retrieval quality acceptance remains separate.
### OpenAI limited-answer workflow (2026-10-12)
Apply the voice API generation-limit amendment to existing Live machinery.
Pin and acknowledge the server per-response budget for new sessions, including
tool continuations. Do not backfill old execution profiles. OpenAI calls stage
until validated successful terminal output; a cut-off tool phase fails safely.
Validated audio-only max_output_tokens termination remains incomplete/limited,
drains existing output credit, and retains normal interruption/truncation and
current-input/authority release gates. No automatic continuation is authorized.
Final OpenAI transcript completion waits for terminal classification within the
existing control budget. Consumer integration and separate funded/browser
acceptance are in docs/guides/openai-output-limit-repair.md.