Files
rag-technical-docs-assistant/docs/guides/openai-output-limit-repair.md
T
amirhosein mazaheri 117fda7cc9 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
2026-10-12 17:35:28 +03:30

195 lines
11 KiB
Markdown

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