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
+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.