fix(openai): prompt engineering and transcript model

This commit is contained in:
amirhosein mazaheri
2026-10-11 17:28:22 +03:30
parent 21a0ea076a
commit f14166a89f
35 changed files with 12882 additions and 46 deletions
+20
View File
@@ -91,6 +91,26 @@ GEMINI_VOICE=Aoede
OPENAI_REALTIME_API_KEY= OPENAI_REALTIME_API_KEY=
OPENAI_REALTIME_MODEL=gpt-realtime-mini OPENAI_REALTIME_MODEL=gpt-realtime-mini
OPENAI_REALTIME_VOICE=shimmer OPENAI_REALTIME_VOICE=shimmer
# Phase 3: optional; low/medium only for gpt-realtime-2.1 or gpt-realtime-2.1-mini.
# Keep omitted for baseline models. Candidate promotion requires quality/compatibility evidence.
OPENAI_REALTIME_REASONING_EFFORT=null
# Phase 1 input quality settings. Keep baseline; candidates require separate evaluation.
OPENAI_REALTIME_ASR_MODEL=whisper-1
OPENAI_REALTIME_ASR_LANGUAGE=fa
OPENAI_REALTIME_ASR_LANGUAGES=[]
OPENAI_REALTIME_ASR_PROMPT=""
OPENAI_REALTIME_ASR_KEYWORDS=[]
OPENAI_REALTIME_VAD_THRESHOLD=0.5
OPENAI_REALTIME_VAD_PREFIX_PADDING_MS=300
OPENAI_REALTIME_VAD_SILENCE_DURATION_MS=500
OPENAI_REALTIME_NOISE_REDUCTION=null
# Explicit candidate (replace the baseline values; do not add conflicting fields):
# OPENAI_REALTIME_ASR_MODEL=gpt-transcribe
# OPENAI_REALTIME_ASR_LANGUAGE=null
# OPENAI_REALTIME_ASR_LANGUAGES=["fa","en"]
# OPENAI_REALTIME_ASR_PROMPT="Iranian Persian technical support with English terminology."
# OPENAI_REALTIME_ASR_KEYWORDS=["PCM16LE","API"]
# Compare ASR first, then VAD 500/800 ms, then device-appropriate noise independently.
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443 # OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
TRUSTED_ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"] TRUSTED_ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"]
TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"] TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"]
+28 -7
View File
@@ -4,7 +4,9 @@ from urllib.parse import quote
from app.modules.knowledge.service import SearchInput from app.modules.knowledge.service import SearchInput
from app.modules.voice.settings import RuntimeSettings from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.configuration import OpenAIInputSettings
from app.modules.voice.serialization import bounded_json from app.modules.voice.serialization import bounded_json
from app.modules.voice.openai_style import effective_instructions
class ProviderProtocolError(ValueError): class ProviderProtocolError(ValueError):
pass pass
@@ -35,10 +37,17 @@ def strict_json(raw):
class RealtimeAdapter: class RealtimeAdapter:
def __init__(self, transport, *, model="gpt-realtime-mini", voice="shimmer", def __init__(self, transport, *, model="gpt-realtime-mini", voice="shimmer",
no_active_classifier=None, settings=None): no_active_classifier=None, settings=None, input_settings=None):
self.settings = settings or RuntimeSettings() self.settings = settings or RuntimeSettings()
if not isinstance(self.settings, RuntimeSettings): if not isinstance(self.settings, RuntimeSettings):
raise ValueError("Validated runtime settings required") raise ValueError("Validated runtime settings required")
input_settings = input_settings if input_settings is not None else OpenAIInputSettings()
if not isinstance(input_settings, OpenAIInputSettings):
raise ValueError('Validated OpenAI input settings required')
# Revalidate copies too: Pydantic model_copy deliberately bypasses validation.
self.input_settings = OpenAIInputSettings.model_validate({
key: getattr(input_settings, key) for key in OpenAIInputSettings.model_fields})
self.reasoning = self.input_settings.reasoning(model)
self.transport, self.model, self.voice = transport, model, voice self.transport, self.model, self.voice = transport, model, voice
# The default classifier is restricted to the empirically verified # The default classifier is restricted to the empirically verified
# OpenAI profile below. Other profiles require separate acceptance. # OpenAI profile below. Other profiles require separate acceptance.
@@ -46,12 +55,10 @@ class RealtimeAdapter:
def setup(self): def setup(self):
return dict(type="session.update", session=dict( return dict(type="session.update", session=dict(
type="realtime", model=self.model, instructions=POLICY, type="realtime", model=self.model, instructions=effective_instructions(POLICY),
**({"reasoning": self.reasoning.copy()} if self.reasoning is not None else {}),
output_modalities=["audio"], tool_choice="auto", output_modalities=["audio"], tool_choice="auto",
audio=dict(input=dict(format=dict(type="audio/pcm", rate=24000), audio=dict(input=self.input_settings.audio_input(),
transcription=dict(model="whisper-1", language="fa"),
turn_detection=dict(type="server_vad", create_response=False,
interrupt_response=False)),
output=dict(format=dict(type="audio/pcm", rate=24000), voice=self.voice)), output=dict(format=dict(type="audio/pcm", rate=24000), voice=self.voice)),
tools=[dict(type="function", name="search_knowledge", tools=[dict(type="function", name="search_knowledge",
description="Retrieve evidence from authorized selected documents.", description="Retrieve evidence from authorized selected documents.",
@@ -67,8 +74,22 @@ class RealtimeAdapter:
if isinstance(wanted, list): if isinstance(wanted, list):
return isinstance(actual, list) and len(actual) == len(wanted) and all( return isinstance(actual, list) and len(actual) == len(wanted) and all(
contains(a, w) for a, w in zip(actual, wanted)) contains(a, w) for a, w in zip(actual, wanted))
if type(wanted) is float:
return type(actual) in (int, float) and actual == wanted
return type(actual) is type(wanted) and actual == wanted return type(actual) is type(wanted) and actual == wanted
return contains(session, expected) if not contains(session, expected):
return False
if self.reasoning is None and session.get('reasoning') is not None:
return False
if session['audio']['input']['turn_detection'].get('idle_timeout_ms') is not None:
return False
transcription = session['audio']['input']['transcription']
# The provider must not silently enable a conflicting language mode.
empty_defaults = dict(language=(None,), languages=(None, []),
prompt=(None, ''), keywords=(None, []))
return all(key not in transcription or transcription[key] in empty_defaults[key]
for key in empty_defaults
if key not in expected['audio']['input']['transcription'])
def serialize(self, event): def serialize(self, event):
return bounded_json(event, self.settings.max_provider_message_bytes, ensure_ascii=False) return bounded_json(event, self.settings.max_provider_message_bytes, ensure_ascii=False)
+8 -1
View File
@@ -6,12 +6,19 @@ from app.infrastructure.realtime import RealtimeAdapter, connect as connect_open
async def create_adapter(config, limits): async def create_adapter(config, limits):
config.require_voice() config.require_voice()
input_settings = None
if config.provider == 'openai':
from app.modules.voice.configuration import OpenAIInputSettings
input_settings = OpenAIInputSettings.model_validate({
key: getattr(config, key) for key in OpenAIInputSettings.model_fields})
input_settings.reasoning(config.selected_model)
connect = connect_gemini if config.provider == 'gemini' else connect_openai connect = connect_gemini if config.provider == 'gemini' else connect_openai
transport = await asyncio.wait_for(connect(config.selected_key.get_secret_value(), transport = await asyncio.wait_for(connect(config.selected_key.get_secret_value(),
config.selected_model, config.selected_proxy, limits), limits.connect_timeout_seconds) config.selected_model, config.selected_proxy, limits), limits.connect_timeout_seconds)
try: try:
adapter = GeminiLiveAdapter if config.provider == 'gemini' else RealtimeAdapter adapter = GeminiLiveAdapter if config.provider == 'gemini' else RealtimeAdapter
return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits) return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits,
**({'input_settings': input_settings} if config.provider == 'openai' else {}))
except BaseException: except BaseException:
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds) await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
raise raise
+83 -3
View File
@@ -3,11 +3,82 @@ import ipaddress
from pathlib import Path from pathlib import Path
from typing import Literal from typing import Literal
from urllib.parse import urlsplit from urllib.parse import urlsplit
from pydantic import AliasChoices, Field, SecretStr, field_validator, model_validator from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
class VoiceSettings(BaseSettings): class OpenAIInputSettings(BaseModel):
"""Bounded operator configuration for committed-turn ASR and server VAD."""
model_config = dict(frozen=True, extra='forbid', hide_input_in_errors=True)
openai_realtime_reasoning_effort: Literal['low', 'medium'] | None = None
openai_realtime_asr_model: Literal['whisper-1', 'gpt-transcribe'] = 'whisper-1'
openai_realtime_asr_language: Literal['fa', 'en'] | None = 'fa'
openai_realtime_asr_languages: tuple[Literal['fa', 'en'], ...] = ()
openai_realtime_asr_prompt: str = Field(default='', max_length=1024)
openai_realtime_asr_keywords: tuple[str, ...] = Field(default=(), max_length=64)
openai_realtime_vad_threshold: float = Field(default=0.5, ge=0, le=1, allow_inf_nan=False)
openai_realtime_vad_prefix_padding_ms: int = Field(default=300, ge=0, le=2000)
openai_realtime_vad_silence_duration_ms: int = Field(default=500, ge=100, le=2000)
openai_realtime_noise_reduction: Literal['near_field', 'far_field'] | None = None
@field_validator('openai_realtime_asr_language', 'openai_realtime_noise_reduction',
'openai_realtime_reasoning_effort', mode='before')
@classmethod
def optional_input_setting(cls, value):
return None if value == 'null' else value
@field_validator('openai_realtime_asr_keywords')
@classmethod
def vocabulary(cls, values):
if len(set(values)) != len(values):
raise ValueError('Duplicate ASR keywords')
for word in values:
if not word.strip() or len(word) > 100 or any(c in word for c in '<>\r\n'):
raise ValueError('Invalid ASR keyword')
return values
@model_validator(mode='after')
def asr_combination(self):
languages = self.openai_realtime_asr_languages
if len(set(languages)) != len(languages):
raise ValueError('Duplicate ASR languages')
if self.openai_realtime_asr_model == 'whisper-1':
if languages or self.openai_realtime_asr_keywords:
raise ValueError('Plural languages and keywords require gpt-transcribe')
elif self.openai_realtime_asr_language is not None:
raise ValueError('gpt-transcribe requires plural languages; set singular language to null')
if self.openai_realtime_asr_language is not None and languages:
raise ValueError('Conflicting ASR language fields')
return self
def reasoning(self, model):
effort = self.openai_realtime_reasoning_effort
if effort is not None and effort not in ('low', 'medium'):
raise ValueError('Unsupported reasoning effort')
if effort is not None and model not in ('gpt-realtime-2.1', 'gpt-realtime-2.1-mini'):
raise ValueError('Reasoning effort requires a supported OpenAI Realtime model')
return None if effort is None else dict(effort=effort)
def audio_input(self):
transcription = dict(model=self.openai_realtime_asr_model)
if self.openai_realtime_asr_language is not None:
transcription['language'] = self.openai_realtime_asr_language
if self.openai_realtime_asr_languages:
transcription['languages'] = list(self.openai_realtime_asr_languages)
if self.openai_realtime_asr_prompt:
transcription['prompt'] = self.openai_realtime_asr_prompt
if self.openai_realtime_asr_keywords:
transcription['keywords'] = list(self.openai_realtime_asr_keywords)
return dict(format=dict(type='audio/pcm', rate=24000), transcription=transcription,
turn_detection=dict(type='server_vad', create_response=False, interrupt_response=False,
threshold=self.openai_realtime_vad_threshold,
prefix_padding_ms=self.openai_realtime_vad_prefix_padding_ms,
silence_duration_ms=self.openai_realtime_vad_silence_duration_ms),
noise_reduction=None if self.openai_realtime_noise_reduction is None else
dict(type=self.openai_realtime_noise_reduction))
class VoiceSettings(OpenAIInputSettings, BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True) model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider')) provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
gemini_api_key: SecretStr = SecretStr('') gemini_api_key: SecretStr = SecretStr('')
@@ -64,6 +135,8 @@ class VoiceSettings(BaseSettings):
@model_validator(mode='after') @model_validator(mode='after')
def cookie_policy(self): def cookie_policy(self):
if self.provider == 'openai':
self.reasoning(self.openai_realtime_model)
for o in self.trusted_origins: for o in self.trusted_origins:
h = urlsplit(o).hostname h = urlsplit(o).hostname
if not self.cookie_secure: if not self.cookie_secure:
@@ -122,5 +195,12 @@ class VoiceSettings(BaseSettings):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE') raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
def profile(self): def profile(self):
return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice, profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000) input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
if self.provider == 'openai':
profile['audio_input'] = self.audio_input()
profile['reasoning'] = self.reasoning(self.selected_model)
from app.infrastructure.realtime import POLICY
from app.modules.voice.openai_style import instruction_profile
profile.update(instruction_profile(POLICY))
return profile
+28
View File
@@ -0,0 +1,28 @@
"""Fixed OpenAI delivery revision; no document facts or unreviewed examples."""
from hashlib import sha256
STYLE_REVISION = 'iranian-persian-professional-v1'
STYLE = """Delivery style (subordinate to the grounding policy above):
Speak standard Iranian Persian in a respectful, professional conversational tone.
Use natural pronunciation, short complete sentences, moderate pacing, and brief
pauses between meaningful clauses. Avoid repeated greetings, ceremonial wording,
excessive filler, and a radio-announcer persona.
Pronounce technical English terms clearly. Preserve exact identifiers, quantities,
dates, conditions, exclusions, and negation; never simplify away material meaning.
When clarification is needed, ask one concise question in Persian.
For no_evidence, explain in Persian that the available document evidence is
insufficient; do not claim that the fact is false or that a technical failure occurred.
For error, explain in Persian that a technical problem prevented checking the
documents; do not describe it as absence of evidence or supply a fallback answer.
Explain conflicting evidence faithfully and briefly. Delivery never overrides
fresh retrieval, source mistrust, authorization, or faithful grounding."""
def effective_instructions(policy):
return policy + '\n\n' + STYLE
def instruction_profile(policy):
return dict(style_revision=STYLE_REVISION,
effective_instructions_digest=sha256(
effective_instructions(policy).encode('utf-8')).hexdigest())
+6
View File
@@ -1483,6 +1483,10 @@ class VoiceRuntime:
audio.done = True audio.done = True
self.wake.set() self.wake.set()
elif kind.startswith("conversation.item.input_audio_transcription."): elif kind.startswith("conversation.item.input_audio_transcription."):
if kind not in ("conversation.item.input_audio_transcription.delta",
"conversation.item.input_audio_transcription.completed",
"conversation.item.input_audio_transcription.failed"):
raise ValueError("Unknown input transcription event")
turn = self.inputs[event["item_id"]] turn = self.inputs[event["item_id"]]
if type(event["content_index"]) is not int or event["content_index"] != 0: if type(event["content_index"]) is not int or event["content_index"] != 0:
raise ValueError("Input transcript layout") raise ValueError("Input transcript layout")
@@ -1499,6 +1503,8 @@ class VoiceRuntime:
# Only index zero is supported: one fixed-size completion # Only index zero is supported: one fixed-size completion
# per retained input mapping, bounded by max_input_turns. # per retained input mapping, bounded by max_input_turns.
turn.transcript_parts[index] = fingerprint turn.transcript_parts[index] = fingerprint
elif event['content_index'] in turn.transcript_parts:
raise ValueError('Input transcript delta after completion')
self.control(dict(type="transcript", turn_ref=turn.ref, role="user", self.control(dict(type="transcript", turn_ref=turn.ref, role="user",
text=text, status="completed" if kind.endswith("completed") else "partial")) text=text, status="completed" if kind.endswith("completed") else "partial"))
elif kind.endswith("failed"): elif kind.endswith("failed"):
+173
View File
@@ -0,0 +1,173 @@
"""Offline, provider-free scoring of human-reviewed Phase 1 speech observations."""
import argparse
from collections import Counter
import hashlib
import json
import math
from pathlib import Path
import unicodedata
NORMALIZATION = 'persian-wer-v1'
def tokens(text):
if not isinstance(text,str):
raise ValueError('Transcript must be a string')
text=unicodedata.normalize('NFC',text).translate(str.maketrans({'ي':'ی','ك':'ک','\u200c':' '}))
chars=[]
for i,char in enumerate(text):
if char.isdecimal():
char=str(unicodedata.decimal(char))
# Preserve identifier separators and numeric punctuation: AC-42, 1.5, 1405/07.
internal=(char in '-_/.:,٫٬' and i>0 and i+1<len(text)
and text[i-1].isalnum() and text[i+1].isalnum())
value_symbol = char in '%٪+−' or (char == '-' and i+1<len(text) and text[i+1].isdecimal())
chars.append(' ' if unicodedata.category(char).startswith('P') and not internal and not value_symbol else char)
return ''.join(chars).split()
def word_errors(reference,hypothesis):
"""Return substitutions/deletions/insertions, with a deterministic minimum edit alignment."""
ref,hyp=tokens(reference),tokens(hypothesis)
if not ref:
raise ValueError('A nonempty human reference is required')
if max(len(ref),len(hyp))>4096:
raise ValueError('Speech token bound exceeded')
previous=[(j,0,0,j) for j in range(len(hyp)+1)]
for i,word in enumerate(ref,1):
current=[(i,0,i,0)]
for j,heard in enumerate(hyp,1):
if word==heard:
current.append(previous[j-1])
else:
cost,s,d,ins=previous[j-1];sub=(cost+1,s+1,d,ins)
cost,s,d,ins=previous[j];delete=(cost+1,s,d+1,ins)
cost,s,d,ins=current[-1];insert=(cost+1,s,d,ins+1)
current.append(min((sub,delete,insert),key=lambda x:x[0]))
previous=current
cost,s,d,ins=previous[-1]
return dict(reference_words=len(ref),substitutions=s,deletions=d,insertions=ins,
errors=cost,wer=cost/len(ref))
def percentile(values,p):
if not values:return None
values=sorted(values);position=(len(values)-1)*p
low=math.floor(position);high=math.ceil(position)
return values[low]+(values[high]-values[low])*(position-low)
def finite_metric(value):
if type(value) not in (int,float) or not math.isfinite(value) or value<0:
raise ValueError('Nonnegative measured metric required')
return value
def indexed(rows):
result={}
for row in rows:
key=row['sample_id']
if key in result:raise ValueError('Duplicate sample identity')
result[key]=row
return result
def score(manifest,annotations,observations,*,split='held_out',root=Path('.')):
"""Score only supplied observations. Null prerequisites never become passing evidence."""
planned=indexed(manifest['samples']);labels=indexed(annotations['annotations'])
measured=indexed(observations['observations'])
profile=observations['effective_profile']
digest=hashlib.sha256(json.dumps(profile,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()
if observations['effective_profile_sha256']!=digest:
raise ValueError('Effective profile digest mismatch')
if any(key not in planned for key in measured) or any(key not in planned for key in labels):
raise ValueError('Unknown sample identity')
selected=[s for s in planned.values() if s['split']==split]
rows=[];missing=[];speakers=set();groups={}
thresholds={'quiet':.10,'office':.15,'moderate_noise':.25}
for sample in selected:
key=sample['sample_id'];label=labels.get(key);observation=measured.get(key)
if not label or not observation or label.get('review_status')!='approved' or not label.get('reviewed_by'):
missing.append(key);continue
if not sample.get('consent_reference') or not sample.get('speaker_id') or sample.get('native_iranian_persian') is not True:
missing.append(key);continue
path=sample.get('recording_path');expected=sample.get('recording_sha256')
if not path or not expected or not sample.get('duration_seconds'):
missing.append(key);continue
recording=root/path
if not recording.is_file() or hashlib.sha256(recording.read_bytes()).hexdigest()!=expected:
raise ValueError('Recording missing or digest mismatch: '+key)
finite_metric(sample['duration_seconds'])
if observation.get('effective_profile_sha256')!=digest or not observation.get('session_reference'):
raise ValueError('Observation profile/session identity required')
result=word_errors(label['reference_text'],observation['final_transcript'])
critical=label.get('critical_facts',[])
ids=[fact['fact_id'] for fact in critical]
if len(set(ids))!=len(ids) or any(f.get('kind') not in ('number','date','identifier','negation') or not f.get('literal') for f in critical):
raise ValueError('Invalid designated critical facts')
judgments=observation.get('critical_fact_results')
if judgments is None or set(judgments)!=set(ids) or any(type(v) is not bool for v in judgments.values()):
raise ValueError('Human critical fact judgments required')
if critical and not observation.get('critical_reviewed_by'):
raise ValueError('Critical fact reviewer required')
critical_errors=sum(not value for value in judgments.values())
completion=finite_metric(observation['completion_delay_ms'])
response=finite_metric(observation['response_latency_ms'])
for name in ('segmentation_errors','truncated_transcripts'):
if type(observation.get(name)) is not int or observation[name]<0:
raise ValueError('Measured error count required')
result.update(sample_id=key,condition=sample['condition'],critical_errors=critical_errors,
completion_delay_ms=completion,response_latency_ms=response,
empty_transcripts=int(not observation['final_transcript'].strip()),
segmentation_errors=observation['segmentation_errors'],
truncated_transcripts=observation['truncated_transcripts'])
rows.append(result);speakers.add(sample['speaker_id'])
group=groups.setdefault(sample['condition'],Counter())
for name in ('reference_words','errors','critical_errors','empty_transcripts','segmentation_errors','truncated_transcripts'):
group[name]+=result[name]
group['samples']+=1
for condition,group in groups.items():
group['wer']=group['errors']/group['reference_words']
group['wer_gate']='passed' if group['wer']<=thresholds[condition] else 'failed'
group['critical_gate']='passed' if group['critical_errors']==0 else 'failed'
# Full planned cohort prerequisites must hold even when scoring held-out speech.
cohort=Counter(s.get('condition') for s in planned.values())
splits=Counter(s.get('split') for s in planned.values())
all_speakers={s['speaker_id'] for s in planned.values() if s.get('speaker_id')}
cohort_ready=(len(planned)==30 and cohort==Counter(quiet=10,office=10,moderate_noise=10)
and splits==Counter(development=20,held_out=10) and len(all_speakers)>=3
and all(s.get('native_iranian_persian') is True and s.get('consent_reference')
and s.get('recording_path') and s.get('recording_sha256') and s.get('duration_seconds')
and labels.get(s['sample_id'],{}).get('review_status')=='approved'
and labels.get(s['sample_id'],{}).get('reviewed_by')
and labels.get(s['sample_id'],{}).get('reference_text')
for s in planned.values())
and all(any(s['condition']==condition and s['split']==split
and labels.get(s['sample_id'],{}).get('critical_facts') for s in planned.values())
for condition in ('quiet','office'))
and all(any(s['split']==part and s['condition']==condition for s in planned.values())
for part in ('development','held_out') for condition in thresholds))
failed=any(g['wer_gate']=='failed' or (c!='moderate_noise' and g['critical_gate']=='failed') for c,g in groups.items())
status='failed' if failed else 'blocked' if missing or not cohort_ready or not selected else 'passed'
return dict(normalization=NORMALIZATION,split=split,effective_profile=profile,effective_profile_sha256=digest,
asr_accuracy_status=status,phase_acceptance_status='not_run', # frontend/pause evidence is separate
cohort_ready=cohort_ready,missing_samples=missing,scored_samples=len(rows),
groups=groups,rows=rows,
completion_delay_ms=dict(p50=percentile([r['completion_delay_ms'] for r in rows],.5),
p95=percentile([r['completion_delay_ms'] for r in rows],.95)),
response_latency_ms=dict(p50=percentile([r['response_latency_ms'] for r in rows],.5),
p95=percentile([r['response_latency_ms'] for r in rows],.95)),
usage=observations.get('usage'),cost=observations.get('cost'),
provider_authorization=observations.get('provider_authorization'))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manifest',type=Path,required=True)
parser.add_argument('--annotations',type=Path,required=True)
parser.add_argument('--observations',type=Path,required=True)
parser.add_argument('--split',choices=('development','held_out'),default='held_out')
args=parser.parse_args()
try:
documents=[json.loads(p.read_text(encoding='utf-8')) for p in (args.manifest,args.annotations,args.observations)]
result=score(*documents,split=args.split,root=args.manifest.parent)
except (ValueError,KeyError,TypeError,OSError) as exc:
parser.exit(2,'Speech scoring failed: '+str(exc)+'\n')
print(json.dumps(result,ensure_ascii=False,indent=2))
return 0 if result['asr_accuracy_status']=='passed' else 1
if __name__=='__main__':
raise SystemExit(main())
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"artifact_schema":1,"document_id":"aa4f291c-8808-497f-975f-ce0f7f6f838a","title":"Approved search calibration sample","original_sha256":"7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f","extraction_profile_sha256":"43aeee78ad2c20b6f892dd031d7797aa1775c3769a7872edca3662d66526fec3","normalization_policy":"unicode-line-endings-v1","complete":true,"quality_decision":"passed","warnings":[],"review_annotations":[],"blocks":[{"ordinal":0,"block_id":"text/paragraph/1","text":"ماده ۱: فشار پمپ ۲۵ بار است فقط وقتی دما کمتر از ۶۰ درجه باشد. شیر کنارگذر را باز نکنید مگر هنگام خاموشی.\n","search_text":"ماده ۱: فشار پمپ ۲۵ بار است فقط وقتی دما کمتر از ۶۰ درجه باشد. شیر کنارگذر را باز نکنید مگر هنگام خاموشی.\n","page":null,"section":"ماده ۱: فشار پمپ ۲۵ بار است فقط وقتی دما کمتر از ۶۰ درجه باشد. شیر کنارگذر را باز نکنید مگر هنگام خاموشی.","source_locator":"text/paragraph/1","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]},{"ordinal":1,"block_id":"text/paragraph/2","text":"\nماده ۲: دبی ۴۰ لیتر در دقیقه است مگر ورودی مسدود باشد. آب‌بندها را هر ۳۰ روز بازرسی کنید.\n","search_text":"\nماده ۲: دبی ۴۰ لیتر در دقیقه است مگر ورودی مسدود باشد. آب‌بندها را هر ۳۰ روز بازرسی کنید.\n","page":null,"section":"text/paragraph/2","source_locator":"text/paragraph/2","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]},{"ordinal":2,"block_id":"text/paragraph/3","text":"\nماده ۳: گشتاور ۱۵ نیوتن‌متر است. در صورت نشتی دستگاه را راه‌اندازی نکنید مگر پس از بازرسی.\n","search_text":"\nماده ۳: گشتاور ۱۵ نیوتن‌متر است. در صورت نشتی دستگاه را راه‌اندازی نکنید مگر پس از بازرسی.\n","page":null,"section":"text/paragraph/3","source_locator":"text/paragraph/3","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]},{"ordinal":3,"block_id":"text/paragraph/4","text":"\nبخشنامه ۱۴۰۳/۰۷: شناسه K-1403/07 است و در تاریخ ۱۴۰۳/۰۷/۰۱ صادر شد. مهلت درخواست ۱۰ روز است فقط برای متقاضی دارای مجوز معتبر.\n","search_text":"\nبخشنامه ۱۴۰۳/۰۷: شناسه K-1403/07 است و در تاریخ ۱۴۰۳/۰۷/۰۱ صادر شد. مهلت درخواست ۱۰ روز است فقط برای متقاضی دارای مجوز معتبر.\n","page":null,"section":"text/paragraph/4","source_locator":"text/paragraph/4","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]},{"ordinal":4,"block_id":"text/paragraph/5","text":"\nماده ۴: تخفیف ۱۲ درصد است برای درخواست‌های ثبت‌شده تا ۱۴۰۳/۰۸/۰۱. درخواست بدون مجوز مشمول نیست.\n","search_text":"\nماده ۴: تخفیف ۱۲ درصد است برای درخواست‌های ثبت‌شده تا ۱۴۰۳/۰۸/۰۱. درخواست بدون مجوز مشمول نیست.\n","page":null,"section":"text/paragraph/5","source_locator":"text/paragraph/5","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]},{"ordinal":5,"block_id":"text/paragraph/6","text":"\nماده ۵: نگهداری تجهیز.\nتبصره ۲: شناسه تجهیز PUMP-7 است. تعویض فیلتر فقط پس از قطع برق مجاز است؛ تجهیزات دارای نشتی مستثنا هستند.\n","search_text":"\nماده ۵: نگهداری تجهیز.\nتبصره ۲: شناسه تجهیز PUMP-7 است. تعویض فیلتر فقط پس از قطع برق مجاز است؛ تجهیزات دارای نشتی مستثنا هستند.\n","page":null,"section":"text/paragraph/6","source_locator":"text/paragraph/6","block_type":"paragraph","heading":null,"group_id":null,"parent_block_id":null,"method":"readable_text","actual_model":null,"warnings":[]}]}
+1
View File
@@ -61,6 +61,7 @@ services:
- ./data/vector_db:/app/data/vector_db - ./data/vector_db:/app/data/vector_db
- ./data/originals:/app/data/originals - ./data/originals:/app/data/originals
- ./data/extractions:/app/data/extractions - ./data/extractions:/app/data/extractions
- ./docs/calibration:/app/docs/calibration:ro
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
+78 -8
View File
@@ -42,7 +42,7 @@ Section numbers and heading names below are verified against these files; no inf
| --- | --- | --- | | --- | --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script | | `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation | | `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract — OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping | | `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract أ¢â‚¬â€‌ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping |
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation | | `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation | | `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions | | `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
@@ -301,11 +301,11 @@ Persian, ZWNJ, CJK and emoji metadata. No real provider checks were run; these
repairs introduce no provider behavior. Original-store power-loss guarantees and repairs introduce no provider behavior. Original-store power-loss guarantees and
unavailable Windows symlink creation remain outside the verified evidence. unavailable Windows symlink creation remain outside the verified evidence.
## Persian document and voice MVP documentation — 2026-10-06 ## Persian document and voice MVP documentation أ¢â‚¬â€‌ 2026-10-06
The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged. The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged.
[Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14–15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01–P1-12, add P1-13–P1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18–22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples. [Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14أ¢â‚¬â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01أ¢â‚¬â€œP1-12, add P1-13أ¢â‚¬â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18أ¢â‚¬â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples.
All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run. All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run.
@@ -757,7 +757,7 @@ Executed evidence for these four semantic repairs (2026-10-06):
An intermediate corrected targeted run had one compatibility failure: An intermediate corrected targeted run had one compatibility failure:
`Decision dated 1403/01/02` was being treated as an identifier. The final parser `Decision dated 1403/01/02` was being treated as an identifier. The final parser
recognizes the explicit dated/مورخ metadata qualifier; the existing control passes. recognizes the explicit dated/ط¸â€¦ط¸ث†ط·آ±ط·آ® metadata qualifier; the existing control passes.
Real-provider extraction quality and manual Persian fidelity acceptance remain Real-provider extraction quality and manual Persian fidelity acceptance remain
**unverified**. These generated fixtures and fake providers do not establish **unverified**. These generated fixtures and fake providers do not establish
@@ -791,7 +791,7 @@ changes, immutable originals, frozen profiles, normalization and applied migrati
Active position/case/hiding semantics fail safely; resets, harmless formatting Active position/case/hiding semantics fail safely; resets, harmless formatting
and unused styles pass. Deeper DOCX answer headings/table continuations stay and unused styles pass. Deeper DOCX answer headings/table continuations stay
atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and
Persian ماده/مواد targets support explicit conjunction/comma lists and simple Persian ط¸â€¦ط·آ§ط·آ¯ط¸â€،/ط¸â€¦ط¸ث†ط·آ§ط·آ¯ targets support explicit conjunction/comma lists and simple
integer ranges; unsupported malformed/complex identifiers fail. Incidental integer ranges; unsupported malformed/complex identifiers fail. Incidental
citations and ordinary decision prose remain accepted. See the setup guide for citations and ordinary decision prose remain accepted. See the setup guide for
exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated; exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated;
@@ -1899,8 +1899,8 @@ Exactly one API process owns media guards; ingestion runs separately. Fake tests
are not real provider/Persian speech/browser hardware or frontend readiness proof. are not real provider/Persian speech/browser hardware or frontend readiness proof.
Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short` Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` أ¢â‚¬â€‌ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **372 passed**, zero skips, using only the isolated task-created test database. أ¢â‚¬â€‌ **372 passed**, zero skips, using only the isolated task-created test database.
Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the
required prerequisite failure. Executable JS, syntax/compile, diff and baseline required prerequisite failure. Executable JS, syntax/compile, diff and baseline
preservation checks passed. See the report for exact durations, failed/interrupted preservation checks passed. See the report for exact durations, failed/interrupted
@@ -1917,7 +1917,7 @@ intake/review/worker/selection services, with bounded streaming
prior pending-HTTP statements above. The standalone frontend developer handoff is prior pending-HTTP statements above. The standalone frontend developer handoff is
[Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable [Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable
DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet, DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet,
Gemini/OpenAI selection, canonical search and migrations 0001–0005 are preserved. Gemini/OpenAI selection, canonical search and migrations 0001أ¢â‚¬â€œ0005 are preserved.
`INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job `INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job
profiles; false admits only automatically validated OCR. Legacy profiles retain profiles; false admits only automatically validated OCR. Legacy profiles retain
@@ -2100,3 +2100,73 @@ and deployment are unverified; the currently inspected API selected Gemini.
## Continuous microphone input accounting repair (2026-10-10) ## Continuous microphone input accounting repair (2026-10-10)
The [scoped repair report](guides/voice-input-accounting-repair.md) supersedes the historical 10-second silence overflow requirement. API 7.1.3 now bounds detected uncommitted speech independently of queued/in-flight transport; absolute positions and commitment fencing remain. Fixed speech-stop and existing commit/send deadlines protect missing events. Stable overflow diagnostics distinguish input, output, playback and control branches. Verification: 1834 provider-free passed (three existing Windows symlink skips); final adapter/diagnostic follow-up 80 passed. No database behavior or migration changed; no deployment or paid provider calls. Real-provider/browser acceptance remains unverified. See the report for exact commands, intermediate failures, counter definitions and provider evidence. The [scoped repair report](guides/voice-input-accounting-repair.md) supersedes the historical 10-second silence overflow requirement. API 7.1.3 now bounds detected uncommitted speech independently of queued/in-flight transport; absolute positions and commitment fencing remain. Fixed speech-stop and existing commit/send deadlines protect missing events. Stable overflow diagnostics distinguish input, output, playback and control branches. Verification: 1834 provider-free passed (three existing Windows symlink skips); final adapter/diagnostic follow-up 80 passed. No database behavior or migration changed; no deployment or paid provider calls. Real-provider/browser acceptance remains unverified. See the report for exact commands, intermediate failures, counter definitions and provider evidence.
## OpenAI Persian speech Phase 1 foundation (2026-10-11)
The [scoped implementation/frontend handoff](guides/openai-persian-speech-phase1.md)
and [baseline/check report](evaluation/openai-persian-speech-baseline.json) track
Phase 1 of the Persian quality plan only. OpenAI input ASR/VAD/noise settings
flow through existing configuration/factory/adapter paths and freeze in
execution_profile.audio_input. Existing replay/stream admission rejects missing
or mismatched snapshots without rewriting them; Gemini/public contracts remain.
User transcription now rejects malformed types/post-completion deltas.
New offline command: .venv/Scripts/python -m app.score_speech --help.
The scorer, 30-slot manifest, blank human annotation/observation templates and
runnable examples/voice-transcripts.js are preparation, not real quality evidence.
Actual live comparisons, human speech/critical facts, natural pauses and actual
frontend/browser reconciliation remain not_run; Phase 1 is not closed.
Read-only rag-api inspection selected OpenAI gpt-realtime-mini/shimmer,
transport testing true and no calibration report. No rebuild/restart or provider
evaluation was performed. Final checks are recorded in the linked report.
Phase 1 affected checks: 361 provider-free regressions and 82 isolated PostgreSQL
cases passed, no database skips. Broader database acceptance is incomplete after
a reported failure and stalled progress; ordinary-suite attempts have timing
failures. See the report for all attempts and final outcomes. No assertions were
weakened, no operational containers were restarted, and test storage was removed.
Final full provider-free run: 1874 passed, three Windows symlink skips, one
existing GeminiVision extraction deadline failure; isolated retest 2 passed.
The full suite remains non-green. Phase 1 live/frontend acceptance remains not_run.
## OpenAI Persian delivery Phase 2 ? 2026-10-11
Fixed OpenAI-only style and instruction digest now reuse the existing execution
profile; shared POLICY/Gemini instructions and cancellation classifier are unchanged.
See [Phase 2 handoff](guides/openai-persian-delivery-phase2.md),
[comparison manifest](evaluation/openai-persian-delivery-comparison.json), and
[style source](../app/modules/voice/openai_style.py). Human examples/listening and
real candidate interruption acceptance remain pending; Phase 2 is not closed.
Phase 2 actual checks: 338 focused checks and 10 isolated PostgreSQL profile cases
passed. Broad provider-free run excluding the duplicate-suite driver: 1880 passed,
3 symlink skips, 1 unchanged JSON responsiveness failure; isolated JSON rerun also
failed its timing bound (different parameter). See the handoff for exact commands
and outcomes. No clean full-suite or real-speech acceptance claim.
## Persian quality Phase 3 (2026-10-11)
[Phase 3 report](guides/openai-persian-understanding-phase3.md) and
[comparison status](evaluation/openai-persian-understanding-comparison.json)
record optional OpenAI low/medium reasoning through existing configuration,
factory and adapter, frozen private execution profiles and acknowledgment/replay
regressions. Gemini and canonical search remain unchanged. Real retrieval/model
acceptance is blocked by approval/bindings, measured calibration, selected speech
profile, human scenarios and explicit bounded authorization. No provider calls or
candidate promotion. Consult the report for actual checks and unresolved failures.
## Measured calibration activation (2026-10-11)
[Operational handoff](guides/search-calibration-activation-2026-10-11.md) records
actual approved sample intake, six ready chunks, selection revision 9 with existing
documents preserved, and ten local bge-m3 query embedding calls. Measured support
is 6/6, unsupported false positives 0/4. The successful environment-specific
report is mounted read-only into rag-api; SEARCH_CALIBRATION_REPORT selects it
and VOICE_TRANSPORT_TESTING is false. Read-only capability checks report calibrated;
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.
+3
View File
@@ -0,0 +1,3 @@
{
"7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f": "aa4f291c-8808-497f-975f-ce0f7f6f838a"
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,16 @@
{
"approval_basis": "Explicit user approval in this conversation of the calibration original and ten frozen labels, followed by authorization to execute the workflow.",
"live_openai_calls": 0,
"recorded_at_utc": "2026-10-11T10:48:06.5648396Z",
"access_epoch": 3,
"organization_id": "37439088-523c-4403-899f-47e3f809123c",
"document_id": "aa4f291c-8808-497f-975f-ce0f7f6f838a",
"original_file": "data/calibration/phase2-source.md",
"scope": "Approved sample intake, selection union, at most ten local bge-m3 query embeddings, and activation only after successful measured calibration.",
"administrator_id": "aec70b67-db27-4696-b2b9-49435a99a3b1",
"annotation_file": "docs/calibration/phase2-cases.json",
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f",
"knowledge_revision": 9,
"annotation_sha256": "b6bd922a0f17a1425d2cf06a3ed801fe0e2a892ec7c069e1e540288b9b2cad8f",
"independent_26_case_evaluation": "not_approved_or_run"
}
@@ -0,0 +1,82 @@
{
"report_id": "persian-delivery-phase2-20261011",
"implementation_status": "implemented_pending_reviewed_examples",
"acceptance_status": "not_run",
"fixed_profile": {
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "whisper-1",
"language": "fa"
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"voices": [
"marin",
"cedar",
"shimmer"
],
"input_set": {
"status": "awaiting_human_review",
"id": null,
"sha256": null,
"items": []
},
"reviewed_behavioral_examples": [],
"blind_mapping": "operator-private; not supplied to listeners",
"ratings": [],
"listener_scores": {
"marin": null,
"cedar": null,
"shimmer": null
},
"compatibility": {
"marin": "not_run",
"cedar": "not_run",
"shimmer": "historical_limited_probe_only"
},
"provider_calls": 0,
"budget_consumed": 0,
"selected_voice": null,
"regression_evidence": {
"focused": {
"passed": 338,
"failed": 0
},
"isolated_postgres": {
"passed": 10,
"failed": 0,
"skipped": 0
},
"broad_excluding_duplicate_suite_driver": {
"passed": 1880,
"failed": 1,
"skipped": 3,
"deselected": 426
},
"isolated_json_responsiveness": {
"passed": 8,
"failed": 1
},
"report": "../guides/openai-persian-delivery-phase2.md"
}
}
@@ -0,0 +1 @@
listener_id,native_iranian_persian,blind_clip_id,input_id,naturalness,pronunciation,professionalism,critical_fact_review,pacing_comments,failure_accuracy_comments
1 listener_id native_iranian_persian blind_clip_id input_id naturalness pronunciation professionalism critical_fact_review pacing_comments failure_accuracy_comments
@@ -0,0 +1,337 @@
{
"manifest_id": "openai-persian-speech-v1",
"status": "human_template_unannotated",
"instructions": "A native human must transcribe actual approved recordings, designate critical literals, and approve references before provider evaluation. Do not generate references from ASR output.",
"annotations": [
{
"sample_id": "speech-01",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-02",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-03",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-04",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-05",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-06",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-07",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-08",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-09",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-10",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-11",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-12",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-13",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-14",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-15",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-16",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-17",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-18",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-19",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-20",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-21",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-22",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-23",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-24",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-25",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-26",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-27",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-28",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-29",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
},
{
"sample_id": "speech-30",
"reference_text": null,
"critical_facts": [],
"natural_pause_intervals_ms": [],
"expected_utterance_boundaries_ms": [],
"reviewed_by": null,
"review_status": "not_run",
"reviewed_at": null,
"notes": null
}
]
}
@@ -0,0 +1,420 @@
{
"report_id": "openai-persian-speech-phase1-20261011",
"date": "2026-10-11",
"implementation_status": "implemented",
"acceptance_status": "not_run",
"phase_closed": false,
"scope": "Phase 1 only, main app.server path",
"manifest_id": "openai-persian-speech-v1",
"recordings_supplied": 0,
"human_labels_supplied": 0,
"provider_evaluation": {
"status": "not_run",
"authorization": null,
"sessions": 0,
"audio_seconds": 0,
"tool_calls": 0,
"embedding_calls": 0,
"spend": 0
},
"deployment_observation": {
"status": "passed",
"method": "Read-only docker exec of VoiceSettings and adapter setup in existing rag-api; allowlisted values only",
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"voice_transport_testing": true,
"calibration_report_configured": false,
"adapter_requested_audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "whisper-1",
"language": "fa"
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false
}
},
"provider_effective_audio_input": null,
"provider_acknowledgment_observed": false,
"new_code_deployed": false,
"hardware_frontend_observed": false
},
"local_observation": {
"status": "passed",
"method": "VoiceSettings from local environment after implementation, allowlisted values only",
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"voice_transport_testing": true,
"calibration_report_configured": false,
"requested_audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "whisper-1",
"language": "fa"
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
}
},
"official_schema": {
"status": "passed",
"checked_date": "2026-10-11",
"gpt_transcribe_committed_websocket": true,
"languages": [
"fa",
"en"
],
"keywords_supported": true,
"sources": [
"https://developers.openai.com/api/docs/guides/realtime-transcription",
"https://developers.openai.com/api/reference/resources/realtime/client-events",
"https://developers.openai.com/api/docs/deprecations"
],
"baseline_shutdown_dates": {
"gpt-realtime-mini": "2027-01-20",
"whisper-1": "2027-02-26"
}
},
"profiles": [
{
"profile_id": "baseline",
"configuration_status": "prepared_not_evaluated",
"voice_profile_without_search": {
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "whisper-1",
"language": "fa"
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
}
},
"voice_profile_without_search_sha256": "9410d136e1b9a0f4f5997a3fba78f0ba40a9586237affab72bfa0dfae5b75f38",
"measured_full_execution_profile": null,
"measured_full_execution_profile_sha256": null,
"provider_acknowledgment_status": "not_run",
"wer": {
"quiet": null,
"office": null,
"moderate_noise": null
},
"critical_errors": null,
"empty_transcripts": null,
"segmentation_errors": null,
"truncated_transcripts": null,
"completion_delay_ms": {
"p50": null,
"p95": null
},
"response_latency_ms": {
"p50": null,
"p95": null
},
"usage": null,
"cost": null
},
{
"profile_id": "asr-candidate",
"configuration_status": "prepared_not_evaluated",
"voice_profile_without_search": {
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
],
"prompt": "Iranian Persian technical support with English terminology.",
"keywords": [
"PCM16LE",
"API"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
}
},
"voice_profile_without_search_sha256": "d570b5051c3a1c8a434408ab2d78c0e65bc44e8386d804d2d82dbe1dceac167b",
"measured_full_execution_profile": null,
"measured_full_execution_profile_sha256": null,
"provider_acknowledgment_status": "not_run",
"wer": {
"quiet": null,
"office": null,
"moderate_noise": null
},
"critical_errors": null,
"empty_transcripts": null,
"segmentation_errors": null,
"truncated_transcripts": null,
"completion_delay_ms": {
"p50": null,
"p95": null
},
"response_latency_ms": {
"p50": null,
"p95": null
},
"usage": null,
"cost": null
}
],
"comparisons": [
{
"dimension": "ASR",
"profiles": [
"baseline",
"asr-candidate"
],
"status": "not_run"
},
{
"dimension": "VAD silence 500 versus 800 ms",
"profiles": [],
"status": "not_run"
},
{
"dimension": "Device-specific noise reduction",
"profiles": [],
"status": "not_run"
}
],
"failure_categories": [
{
"category": "capture",
"status": "not_run",
"observed_failures": null
},
{
"category": "assembly",
"status": "not_run",
"observed_failures": null
},
{
"category": "ASR",
"status": "not_run",
"observed_failures": null
},
{
"category": "segmentation",
"status": "not_run",
"observed_failures": null
},
{
"category": "direct_audio_understanding",
"status": "not_run",
"observed_failures": null
}
],
"acceptance_gates": {
"held_out_wer": "not_run",
"quiet_office_critical_facts": "not_run",
"actual_frontend_transcript_reconciliation": "not_run",
"actual_pcm_capture_playback": "not_run",
"natural_pauses": "not_run",
"latency_comparison": "not_run"
},
"checks": [
{
"command": ".venv/Scripts/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_realtime_phase1.py -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 81,
"seconds": 28.07
},
{
"command": ".venv/Scripts/python -m pytest tests/unit/test_speech_scorer.py tests/unit/test_openai_speech_configuration.py -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 37,
"seconds": 2.86,
"note": "Before two final acknowledgment/malformed-event regressions; full suite includes final files"
},
{
"command": ".venv/Scripts/python -m pytest tests/integration/test_openai_speech_profile.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 8,
"seconds": 55.17
},
{
"command": ".venv/Scripts/python -m pytest -m \"not postgres\" -q -p no:cacheprovider --tb=short",
"status": "failed",
"note": "Existing 50-ms search runner deadline failed; nested ordinary-suite regression also failed from search deadline and 103.80-ms JSON heartbeat gap against 100 ms. Concurrent PostgreSQL run; no causal attribution established. Retest pending.",
"passed": 1871,
"failed": 2,
"skipped": 3,
"deselected": 423,
"seconds": 418.08
},
{
"command": ".venv/Scripts/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short",
"status": "failed",
"note": "Interrupted after a reported failure and several minutes without further results, beyond 68 percent progress. Test database sessions were idle; no traceback was available after tool interruption. Full 423-case acceptance is not established; no causal attribution.",
"completed": false,
"reported_failures_at_least": 1
},
{
"command": "git diff --check",
"status": "passed"
},
{
"command": ".venv/Scripts/python -m pytest tests/unit/test_openai_speech_configuration.py tests/unit/test_speech_scorer.py tests/unit/test_phase2_provider_selection.py tests/unit/test_search_phase3.py tests/unit/test_json_processing.py -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 111,
"seconds": 28.66,
"note": "Includes focused retest of initial timing-sensitive failures"
},
{
"command": ".venv/Scripts/python -m pytest tests/unit/test_openai_speech_configuration.py tests/unit/test_speech_scorer.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_live_context_sync.py tests/unit/test_voice_input_accounting.py tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 361,
"seconds": 100.0,
"note": "Final implementation including unexpected provider guidance rejection"
},
{
"command": ".venv/Scripts/python -m app.score_speech --help",
"status": "passed"
},
{
"command": "New-file whitespace / ast.parse / json.loads / relative handoff links inspection",
"status": "passed"
},
{
"command": "Offline scorer against empty supplied templates",
"status": "passed",
"note": "Correctly rejected missing effective-profile digest; no quality score claimed"
},
{
"command": ".venv/Scripts/python -m pytest -m \"not postgres\" -q -p no:cacheprovider --tb=short",
"attempt": 2,
"status": "failed",
"passed": 1871,
"failed": 2,
"skipped": 3,
"deselected": 423,
"seconds": 474.64,
"note": "JSON responsiveness 148.52 ms versus 100 ms; nested suite failed JSON responsiveness 215.70 ms and existing GeminiVision blocked-read deadline. Concurrent task suites ran; no cause established. Final acknowledgment follow-up validated separately."
},
{
"command": ".venv/Scripts/python -m pytest tests/integration/test_openai_speech_profile.py tests/integration/test_phase2_postgres.py tests/integration/test_voice_session_incident.py tests/integration/test_realtime_phase3_http.py::test_authenticated_selection_removal_closes_active_voice_and_redacts_polling -m postgres --require-postgres -x -vv -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 82,
"skipped": 0,
"seconds": 361.58,
"note": "Final affected PostgreSQL acceptance, without another task test suite running"
},
{
"command": "docker rm -f -v <verified task-owned container ID>",
"status": "passed",
"note": "Only rag-speech-phase1-20261011-test and its anonymous test storage removed"
},
{
"command": ".venv/Scripts/python -m pytest -m \"not postgres\" -q -p no:cacheprovider --tb=short",
"attempt": 3,
"status": "failed",
"passed": 1874,
"failed": 1,
"skipped": 3,
"deselected": 423,
"seconds": 362.63,
"note": "Final code, no concurrent task test suite. Existing GeminiVision extraction test test_transport_capacity_survives_timeout_and_recovers_without_late_results[False] failed because its mock opener was not entered within the 0.1-second deadline. Nested full-suite driver passed. No causal attribution."
},
{
"command": ".venv/Scripts/python -m pytest tests/unit/test_phase3_context_repairs.py::test_transport_capacity_survives_timeout_and_recovers_without_late_results -q -p no:cacheprovider --tb=short",
"status": "passed",
"passed": 2,
"seconds": 1.34,
"note": "Final broader failure isolated; both parameter variants passed without changing code or assertions."
}
],
"database_isolation": {
"container": "rag-speech-phase1-20261011-test",
"port": 55441,
"database": "rag_speech_phase1_test",
"schemas": "Disposable per-test schemas; test_vector namespace; no operational database access",
"cleanup_status": "passed"
},
"frontend_handoff": "docs/guides/openai-persian-speech-phase1.md",
"unrun_prerequisites": [
"Approved real recordings from at least three native Iranian Persian speakers",
"Native human reference annotations and critical fact designations",
"Explicit bounded real-provider evaluation authorization",
"Actual production frontend workspace, developer signoff and browser/hardware evidence",
"Deployed source update and real provider acknowledgment of new settings",
"Unqualified full PostgreSQL acceptance and resolution of broader ordinary-suite timing failures"
],
"affected_files": [
".env.example",
"app/modules/voice/configuration.py",
"app/infrastructure/voice_provider.py",
"app/infrastructure/realtime.py",
"app/modules/voice/runtime.py",
"app/score_speech.py",
"examples/voice-transcripts.js",
"tests/unit/test_openai_speech_configuration.py",
"tests/unit/test_speech_scorer.py",
"tests/support/voice_transcripts.mjs",
"tests/integration/test_openai_speech_profile.py",
"docs/guides/openai-persian-speech-phase1.md",
"docs/evaluation/openai-persian-speech-manifest.json",
"docs/evaluation/openai-persian-speech-annotations.json",
"docs/evaluation/openai-persian-speech-observations.template.json",
"docs/evaluation/openai-persian-speech-baseline.json",
"docs/agent-reference-map.md",
"docs/specifications/RAG-Phase1-API-Catalog.md"
],
"preserved_files": [
"docs/plans/openai-realtime-persian-quality-plan.md (pre-existing untracked user plan)",
"scripts/live_voice_server.py",
"all applied migrations",
"Gemini adapter and shared POLICY"
],
"validation_status": "affected_checks_passed_broader_acceptance_incomplete"
}
@@ -0,0 +1,616 @@
{
"manifest_id": "openai-persian-speech-v1",
"status": "template_no_recordings",
"required_native_speakers": 3,
"samples": [
{
"sample_id": "speech-01",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-02",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-03",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-04",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-05",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-06",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-07",
"condition": "quiet",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-08",
"condition": "quiet",
"split": "held_out",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-09",
"condition": "quiet",
"split": "held_out",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-10",
"condition": "quiet",
"split": "held_out",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-11",
"condition": "office",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-12",
"condition": "office",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-13",
"condition": "office",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-14",
"condition": "office",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-15",
"condition": "office",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-16",
"condition": "office",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-17",
"condition": "office",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-18",
"condition": "office",
"split": "held_out",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-19",
"condition": "office",
"split": "held_out",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-20",
"condition": "office",
"split": "held_out",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-21",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-22",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-23",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-24",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-25",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-26",
"condition": "moderate_noise",
"split": "development",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-27",
"condition": "moderate_noise",
"split": "held_out",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-28",
"condition": "moderate_noise",
"split": "held_out",
"planned_speaker_slot": 1,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"numbers",
"dates",
"identifiers",
"negation"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-29",
"condition": "moderate_noise",
"split": "held_out",
"planned_speaker_slot": 2,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"natural_pause",
"self_correction",
"repeated_words"
],
"recording_status": "not_run"
},
{
"sample_id": "speech-30",
"condition": "moderate_noise",
"split": "held_out",
"planned_speaker_slot": 3,
"speaker_id": null,
"native_iranian_persian": null,
"consent_reference": null,
"recording_path": null,
"recording_sha256": null,
"duration_seconds": null,
"capture_device": null,
"capture_browser": null,
"coverage_required": [
"colloquial",
"technical",
"code_switching"
],
"recording_status": "not_run"
}
]
}
@@ -0,0 +1,40 @@
{
"manifest_id": "openai-persian-speech-v1",
"status": "template_no_provider_observations",
"effective_profile": null,
"effective_profile_sha256": null,
"provider_authorization": {
"authorized_by": null,
"models": [],
"maximum_sessions": null,
"maximum_audio_seconds": null,
"maximum_tool_calls": null,
"maximum_embedding_calls": null,
"spend_ceiling": null,
"currency": null,
"actual_sessions": null,
"actual_audio_seconds": null,
"actual_tool_calls": null,
"actual_embedding_calls": null,
"actual_spend": null
},
"usage": null,
"cost": null,
"observations": [],
"observation_template": {
"sample_id": null,
"effective_profile_sha256": null,
"session_reference": null,
"final_transcript": null,
"critical_fact_results": {},
"critical_reviewed_by": null,
"completion_delay_ms": null,
"response_latency_ms": null,
"segmentation_errors": null,
"truncated_transcripts": null,
"capture_errors": null,
"assembly_errors": null,
"audio_understanding_errors": null,
"notes": null
}
}
@@ -0,0 +1,376 @@
{
"report_id": "persian-understanding-phase3-20261011",
"implementation_status": "implemented",
"acceptance_status": "blocked",
"local_profile": {
"provider": "openai",
"model": "gpt-realtime-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"reasoning": null,
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"deployment_verified": false,
"transport_testing": true,
"calibration_report_configured": false,
"embedding_profile_local": {
"provider": "ollama",
"endpoint": "http://localhost:11434/v1",
"model": "bge-m3",
"dimensions": 1024,
"preprocessing_version": "v1"
},
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2",
"originals": [
{
"name": "letter",
"path": "data/documents/5905170444656189186_13450510740952.pdf",
"expected_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"hash_matches": true,
"approval": "pending",
"document_id": null
},
{
"name": "regulation",
"path": "data/documents/7364346504113364738_13450847753183.pdf",
"expected_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"hash_matches": true,
"approval": "pending",
"document_id": null
},
{
"name": "infographic",
"path": "data/documents/photo_1_2026-10-06_09-05-11.jpg",
"expected_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"hash_matches": true,
"approval": "pending",
"document_id": null
},
{
"name": "docx",
"path": "data/documents/-2348240626507047168_13449360743721.docx",
"expected_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"hash_matches": true,
"approval": "pending",
"document_id": null
}
],
"calibration_cutoff": null,
"retrieval_status": "blocked",
"scenario_count_required": 26,
"scenario_set_id": null,
"scenario_set_sha256": null,
"scenarios": [],
"candidates": [
{
"candidate_id": "gpt-realtime-2.1-low",
"profile": {
"provider": "openai",
"model": "gpt-realtime-2.1",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"reasoning": {
"effort": "low"
},
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"profile_basis": "local settings held fixed for preparation; ASR/voice not human-selected",
"status": "not_run",
"gate": "blocked",
"scenario_set_id": null,
"quality": null,
"latency_p50_seconds": null,
"latency_p95_seconds": null,
"usage": "unavailable",
"cost": "unavailable",
"compatibility": "not_run",
"provider_sessions": 0,
"tool_calls": 0,
"embedding_calls": 0
},
{
"candidate_id": "gpt-realtime-2.1-medium",
"profile": {
"provider": "openai",
"model": "gpt-realtime-2.1",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"reasoning": {
"effort": "medium"
},
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"profile_basis": "local settings held fixed for preparation; ASR/voice not human-selected",
"status": "not_run",
"gate": "blocked_pending_failed_low_gate",
"scenario_set_id": null,
"quality": null,
"latency_p50_seconds": null,
"latency_p95_seconds": null,
"usage": "unavailable",
"cost": "unavailable",
"compatibility": "not_run",
"provider_sessions": 0,
"tool_calls": 0,
"embedding_calls": 0
},
{
"candidate_id": "gpt-realtime-2.1-mini-low",
"profile": {
"provider": "openai",
"model": "gpt-realtime-2.1-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"reasoning": {
"effort": "low"
},
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"profile_basis": "local settings held fixed for preparation; ASR/voice not human-selected",
"status": "not_run",
"gate": "blocked",
"scenario_set_id": null,
"quality": null,
"latency_p50_seconds": null,
"latency_p95_seconds": null,
"usage": "unavailable",
"cost": "unavailable",
"compatibility": "not_run",
"provider_sessions": 0,
"tool_calls": 0,
"embedding_calls": 0
},
{
"candidate_id": "gpt-realtime-2.1-mini-medium",
"profile": {
"provider": "openai",
"model": "gpt-realtime-2.1-mini",
"voice": "shimmer",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"audio_input": {
"format": {
"type": "audio/pcm",
"rate": 24000
},
"transcription": {
"model": "gpt-transcribe",
"languages": [
"fa",
"en"
]
},
"turn_detection": {
"type": "server_vad",
"create_response": false,
"interrupt_response": false,
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
"noise_reduction": null
},
"reasoning": {
"effort": "medium"
},
"style_revision": "iranian-persian-professional-v1",
"effective_instructions_digest": "18183a0cc2aff0ffb33e4b10a9dc54250563c758f1b849d56b555ed7eba3c9bd"
},
"profile_basis": "local settings held fixed for preparation; ASR/voice not human-selected",
"status": "not_run",
"gate": "blocked_pending_failed_low_gate",
"scenario_set_id": null,
"quality": null,
"latency_p50_seconds": null,
"latency_p95_seconds": null,
"usage": "unavailable",
"cost": "unavailable",
"compatibility": "not_run",
"provider_sessions": 0,
"tool_calls": 0,
"embedding_calls": 0
}
],
"selected_profile": null,
"authorized_provider_batch": null,
"provider_calls": 0,
"spend_consumed": 0,
"failures": [
{
"test": "tests/unit/test_json_processing.py::test_real_large_escaped_json_keeps_concurrent_loop_active[4499]",
"category": "unrelated product responsiveness regression",
"observed_gap_ms": 132.03,
"limit_ms": 100,
"focused_rerun": "9 passed",
"cause": "undetermined; timing instability observed in preceding Phase 2 evidence",
"repaired": false
}
],
"blocked_prerequisites": [
"Explicit bounded authorization: models, sessions, audio seconds, tool/embedding calls, spend ceiling.",
"Approved original/document bindings and human factual DOCX inclusion; authorized actor and verified exact selected ready/active/undeleted corpus.",
"Measured finalized calibration matching embedding/retrieval profile; independent retrieval labels approved with four unseen cases completed.",
"Human-reviewed 20 answerable/all-critical + six unsupported grounded dialogue scenarios and approved recordings/text equivalents.",
"Selected ASR/voice and reviewed instructions; Phase 1/2 live acceptance remains not_run.",
"Exact candidate cancellation/interruption compatibility and native listener evidence."
],
"checks": {
"focused_asr_style_reasoning": {
"status": "passed",
"passed": 51
},
"affected_grounding_interruption_calibration_reasoning": {
"status": "passed",
"passed": 351
},
"provider_free_full": {
"status": "failed",
"passed": 1892,
"failed": 1,
"skipped": 3,
"deselected": 429,
"duration_seconds": 326.47
},
"json_responsiveness_focused_rerun": {
"status": "passed",
"passed": 9,
"duration_seconds": 11.13
},
"persisted_profile_focused": {
"status": "passed",
"passed": 18,
"skipped": 0,
"duration_seconds": 126.16
},
"isolated_postgres_full": {
"status": "passed",
"passed": 429,
"skipped": 0,
"deselected": 1896,
"duration_seconds": 1647.7,
"database": "rag_persian_phase3_test",
"postgresql": "16.15",
"pgvector": "0.8.7"
},
"static": {
"status": "passed",
"checks": [
"AST/JSON",
"git diff --check",
"shared POLICY unchanged",
"Gemini adapter unchanged",
"applied migrations byte-identical"
]
},
"retrieval_manifest_preflight": {
"status": "blocked",
"reason": "Frozen 20 answerable / 6 unsupported with four unseen cases required"
},
"calibration_label_structure": {
"status": "passed",
"quality_acceptance": false
},
"isolated_cleanup": {
"status": "passed",
"remaining_test_schemas": 0,
"public_tables": 0,
"task_container_removed": true
}
}
}
@@ -0,0 +1,29 @@
{
"scenario_id": null,
"critical": null,
"input_audio_id": null,
"equivalent_text": null,
"human_expected_intent": null,
"expected_document_chunks": [],
"spoken_intent": null,
"display_transcript": null,
"tool_query": null,
"retrieval_result": null,
"spoken_answer": null,
"diagnostic_text_result": null,
"failure_categories": {
"audio_interpretation": null,
"asr_display": null,
"tool_query": null,
"retrieval": null,
"answer": null
},
"fresh_followup_retrieval": null,
"selection_access_invalidation": null,
"interruption_compatibility": null,
"latency_seconds": null,
"usage": null,
"cost": null,
"human_reviewer": null,
"status": "not_run"
}
@@ -0,0 +1,106 @@
# OpenAI Persian delivery Phase 2 ? 2026-10-11
Implementation: fixed OpenAI delivery revision `iranian-persian-professional-v1`
composed after the unchanged shared POLICY. Gemini uses exactly POLICY as before.
OpenAI reservations freeze `style_revision` and `effective_instructions_digest`
(SHA-256 of exact UTF-8 effective instructions) alongside Phase 1 audio settings.
Missing or changed fields make an old reservation unusable before provider opening;
replay retains its identity and stored snapshot. Use a fresh reservation after a
prompt, revision, or voice change. No public event/DTO or migration changes.
Style asks for respectful conversational Iranian Persian, clear technical terms,
short complete sentences, moderate pacing and clause pauses. It distinguishes
insufficient evidence from technical failure, preserves facts and negation, and
remains subordinate to fresh retrieval and untrusted-source rules. No behavioral
examples were added: reviewer-approved examples and attribution are unavailable.
This is prompt configuration, not measured speech quality or model compliance.
## Fixed comparison protocol and listener rubric
Use `docs/evaluation/openai-persian-delivery-comparison.json` as the locked run
manifest. Model is `gpt-realtime-mini`; ASR is Phase 1 default whisper-1/fa,
VAD .5/300/500 ms, no noise reduction, runtime-owned responses/interruptions.
Compare marin first, then cedar, with shimmer as control. All three use the same
exact effective instructions and approved input set. This is a voice-only
experiment; ASR/model comparisons belong to other phases. Do not silently
substitute unavailable models or inputs. Capture the full execution profile,
prompt digest, input hashes, run/session IDs, and environment for every run.
Before any calls, a human freezes approved recordings/dialogue inputs, binds
any document questions to authorized ready selected originals and reviewed
critical facts, and records an input-set identifier and digest. Include greetings,
ambiguity, no_evidence, error, technical terms, numbers, dates, conditions,
exclusions, negation, and fresh-retrieval follow-ups. Do not invent expected facts.
Every voice uses new sessions with identical inputs/order and reset context;
record session readiness acknowledgment and exact profile. Keep recordings only
as approved evaluation assets, never production recording/history.
An operator keeps a separate voice-to-clip mapping, strips voice names from
listener filenames and metadata, randomizes presentation order independently for
at least three native Iranian Persian listeners, and collects independent scores
before revealing mappings. Score naturalness, pronunciation, and conversational
professionalism separately: 1 unusable; 2 frequent distracting problems; 3
understandable with noticeable problems; 4 natural with minor issues; 5 consistently
natural and professional. Record pacing and clarification/failure accuracy comments.
Require each dimension mean >=4/5 for the selected voice, with all three listeners
covering the same clips. Report sample/listener counts, missing ratings and means
per voice; missing scores are not zero and cannot establish passage. A separate
human fact review must find no changed critical values, conditions, or negation.
Report p50/p95 latency and observed usage/cost availability separately.
## Compatibility and interruption gate
The classifier is unchanged: only gpt-realtime-mini/shimmer with structured
invalid_request_error/response_cancel_not_active and absent/null param is verified.
Marin/cedar are unverified. Never accept them by substring or inferred similarity.
An explicit bounded probe authorization must specify pairs, connection/response
limits, timeouts and spend budget before any compatibility provider calls.
Capture sanitized structured type/code/param and cancellation event correlation,
terminal status ordering and matching item/content/played-position truncation ack.
Never log raw audio, transcripts, credentials or document/provider payloads.
Only matching actual candidate evidence authorizes a classifier extension.
Then exercise the main application runtime: interruption during generation and
retrieval, completed generation with undrained playback, terminal-before-error
and terminal-after-error races, rapid repeated speech starts, final played-position
updates (including zero), duplicate/late acknowledgments, missing terminal/incorrect
truncation failures, stop/disconnect, replay/profile rejection and stale selection/
access barriers. Require correlated cancellation, independent terminal confirmation,
frozen played position and exact truncation acknowledgment before next response.
Synthetic fixtures establish regression behavior only, not real compatibility.
## Acceptance report
Implementation status: implemented except pending human-reviewed examples.
Acceptance status: not_run; Phase 2 remains open. Listener scores for all voices:
not_run. Candidate cancellation probes/runtime interruption evidence: not_run.
New provider connections/calls: 0; paid evaluation budget consumed: 0.
Historical shimmer evidence remains limited to the context-sync repair report;
it does not prove Persian delivery or every active interruption scenario.
Missing prerequisites: approved examples, frozen human inputs, three native
listeners, explicit bounded provider authorization, and actual application/browser
interruption evidence. No selected voice promotion, deployment or defaults change.
Prompt structure follows [official voice prompting guidance](https://developers.openai.com/api/docs/guides/voice-prompting).
Use [Realtime voice guidance](https://developers.openai.com/api/docs/guides/realtime-conversations)
when checking candidate availability; documentation is not empirical compatibility.
## Executed regression evidence
- `.venv/Scripts/python -m pytest tests/unit/test_openai_persian_style.py tests/unit/test_openai_speech_configuration.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short`: final 338 passed in 50.27 s. Initial 337 passed/1 failed was a new test's incorrect Gemini setup-shape assumption, corrected to inspect emitted instructions.
- `.venv/Scripts/python -m pytest tests/integration/test_openai_speech_profile.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`: 10 passed in 107.86 s, zero skips. Isolated task-created pgvector container `rag-persian-phase2-20261011-test`, loopback 55441, dedicated `rag_persian_phase2_test`; existing immutable migrations applied by fixtures. Container and anonymous storage removed afterward. No full PostgreSQL suite claim.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: stopped before completion while the existing environment-isolation driver ran a captured second full suite. No pass claim.
- `.venv/Scripts/python -m pytest -m "not postgres" -k "not test_ordinary_suite_ignores_ambient_ingestion_configuration" -q -p no:cacheprovider --tb=short`: 1880 passed, 3 Windows symlink skips, 426 deselected (PostgreSQL plus the duplicate-suite driver), 1 failed, 25 deprecation warnings, 189.36 s. Unchanged `test_real_large_escaped_json_keeps_concurrent_loop_active[4499]` measured 187.67 ms against its 100 ms heartbeat bound.
- `.venv/Scripts/python -m pytest tests/unit/test_json_processing.py -q -p no:cacheprovider --tb=short`: 8 passed, 1 failed in 11.53 s. The 4499 case passed; the 10000 case measured 234.46 ms against 100 ms. Timing instability remains unresolved; no limits or ingestion code were changed and no definitive cause is claimed.
- Static checks: shared POLICY equals HEAD byte-for-byte as a Python string; Gemini adapter diff is empty; cancellation classifier AST equals HEAD; manifest matches effective configuration; new/extended Python files parse; `git diff --check` passed.
Affected Phase 2 sources: `app/modules/voice/openai_style.py`,
`app/infrastructure/realtime.py`, `app/modules/voice/configuration.py`,
`tests/unit/test_openai_persian_style.py`, and the existing working-tree
`tests/integration/test_openai_speech_profile.py`. Documentation: this handoff,
comparison JSON/rating CSV, API catalog and reference map. Existing Phase 1
configuration/transcript/runtime edits were preserved; no Phase 3/4 work added.
These results establish deterministic adapter/runtime coverage and targeted
persistence behavior, not listener scores, actual model grounding compliance,
marin/cedar cancellation compatibility, or release readiness.
+224
View File
@@ -0,0 +1,224 @@
# OpenAI Persian speech Phase 1 implementation and frontend handoff
Date: 2026-10-11. Scope: Phase 1 of [the quality plan](../plans/openai-realtime-persian-quality-plan.md).
Implementation and acceptance are tracked separately in the [baseline report](../evaluation/openai-persian-speech-baseline.json).
No Phase 2 style/voice or Phase 3 conversation/retrieval change is included.
## Configuration and frozen admission
The main `python -m app.server` path uses VoiceSettings, the selected provider
factory and RealtimeAdapter. Gemini's profile, setup and instructions remain
unchanged. The standalone live_voice_server.py spike is untouched.
No public DTO, normalized event, database schema or migration changes.
OpenAI reservations now include `execution_profile.audio_input`: exact requested
PCM format, transcription model/language mode/prompt/keywords, server VAD
threshold/prefix/silence settings and noise reduction. The same validated settings
produce the adapter session.update. Both VAD ownership flags remain false.
Readiness requires matching provider acknowledgment, including all configured
audio fields; conflicting language modes or an automatic idle timeout fail closed.
Configuration copies are revalidated before the factory opens a connection.
The baseline remains whisper-1/fa, no prompt/keywords, VAD threshold 0.5,
prefix padding 300 ms and silence duration 500 ms, no noise reduction.
The VAD values previously omitted from the wire are now explicit documented
defaults. Noise off is explicit null. These are requested settings; the
deployment's historical acknowledgment/default noise value was not observed.
No baseline speech accuracy or release acceptance is inferred from defaults.
| Setting | Default | Validation |
| --- | --- | --- |
| OPENAI_REALTIME_ASR_MODEL | whisper-1 | whisper-1 or gpt-transcribe; no silent substitution |
| OPENAI_REALTIME_ASR_LANGUAGE | fa | fa/en/null; must be null for gpt-transcribe |
| OPENAI_REALTIME_ASR_LANGUAGES | [] | Unique fa/en list; gpt-transcribe only |
| OPENAI_REALTIME_ASR_PROMPT | empty | At most 1024 characters |
| OPENAI_REALTIME_ASR_KEYWORDS | [] | At most 64 unique, nonblank terms, 100 characters each; no angle brackets or line breaks; gpt-transcribe only |
| OPENAI_REALTIME_VAD_THRESHOLD | 0.5 | Finite 0..1 |
| OPENAI_REALTIME_VAD_PREFIX_PADDING_MS | 300 | Integer 0..2000 |
| OPENAI_REALTIME_VAD_SILENCE_DURATION_MS | 500 | Integer 100..2000 |
| OPENAI_REALTIME_NOISE_REDUCTION | null | null, near_field or far_field |
The integer ranges and text/list caps are local engineering limits, not provider
performance guarantees. These fields are server configuration; no client selectors.
Environment `null` parses as Python None only for the new optional ASR language/noise fields. JSON arrays are required for list settings.
Explicit ASR candidate, without changing any defaults:
```dotenv
OPENAI_REALTIME_ASR_MODEL=gpt-transcribe
OPENAI_REALTIME_ASR_LANGUAGE=null
OPENAI_REALTIME_ASR_LANGUAGES=["fa","en"]
OPENAI_REALTIME_ASR_PROMPT="Iranian Persian technical support with English terminology."
OPENAI_REALTIME_ASR_KEYWORDS=["PCM16LE","API"]
OPENAI_REALTIME_VAD_THRESHOLD=0.5
OPENAI_REALTIME_VAD_PREFIX_PADDING_MS=300
OPENAI_REALTIME_VAD_SILENCE_DURATION_MS=500
OPENAI_REALTIME_NOISE_REDUCTION=null
```
Operators must maintain literal vocabulary and a short context description.
Never insert expected answers, retrieved document text or display transcripts.
The transcription stream is display guidance; the conversation model consumes
audio independently. The runtime never turns display transcripts into input.
Official schema verified on 2026-10-11:
[Realtime transcription](https://developers.openai.com/api/docs/guides/realtime-transcription)
supports gpt-transcribe after committed turns over WebSocket.
[Client-event schema](https://developers.openai.com/api/reference/resources/realtime/client-events)
supports gpt-transcribe, plural languages, keywords, server VAD and near/far-field
noise reduction. Do not send singular and plural language fields together.
This verifies documented schema support, not account availability or real quality.
No transcription delay, semantic VAD or separate transcription service was added.
The [deprecation notice](https://developers.openai.com/api/docs/deprecations) still
lists gpt-realtime-mini retirement on January 20, 2027 and whisper-1 on February
26, 2027. Defaults were retained for a controlled baseline; no replacement was
promoted or assumed available.
Replay still returns the original session/request identity after configuration
changes. Stream admission compares the frozen snapshot before opening the
provider. OpenAI reservations missing audio_input or differing from today's
effective profile are unusable; no snapshot is repaired or rewritten. Reconcile
and close the old reservation, then create a fresh reservation/request ID.
The existing active-session busy rule and ownership checks still apply.
## Speech assets and scoring
The [manifest](../evaluation/openai-persian-speech-manifest.json) contains 30
planning slots: ten each quiet/office/moderate noise, split 20 development and
ten held-out, with three planned speaker slots and coverage requirements.
Every recording, speaker identity, consent, duration and device field is empty.
Speaker slots are assignments to collect, not claims of actual participants.
A native human must fill the [annotation template](../evaluation/openai-persian-speech-annotations.json)
from approved real recordings, including reference text, reviewer identity,
critical number/date/identifier/negation literals, pause and utterance boundaries.
Critical facts have objects `{fact_id, kind, literal}`. Approve labels before
comparison; do not derive them from provider transcripts. Keep held-out samples
out of tuning and prompt/vocabulary construction.
Copy the [observation template](../evaluation/openai-persian-speech-observations.template.json)
to a separate measured report. Record the exact full execution profile and its
SHA256 using sorted-key, compact, UTF-8 JSON. Each observation repeats that digest
and supplies its session reference, final transcript, human critical-fact results,
completion delay (speech end to final transcript), response latency (speech end
to first output audio), segmentation/truncation counts, usage/cost availability
and classified failure notes. Critical results map fact_id to a human boolean;
provide critical_reviewed_by. Never fabricate absent observations or zero latency.
Use relative recording paths from the manifest directory and hashes of originals.
```powershell
.venv/Scripts/python -m app.score_speech --manifest docs/evaluation/openai-persian-speech-manifest.json --annotations docs/evaluation/openai-persian-speech-annotations.json --observations path/to/measured-observations.json --split held_out
```
The scorer is offline and makes no provider calls. It emits JSON to stdout;
exit 0 means its ASR gate passed, 1 means failed/blocked, 2 means invalid evidence.
It normalizes NFC, Arabic/Persian ya/kaf, decimal digit forms, punctuation and
whitespace/ZWNJ. It preserves numeric/identifier separators, signs, percentages,
repeated words and negation. It reports edit counts and condition-weighted WER,
empty/truncated transcripts, segmentation errors and p50/p95 completion/response
latency. Critical facts use separate human judgments, not substring heuristics.
Incomplete references/recordings/review/cohort prerequisites cannot pass.
A scorer pass never closes frontend or real-speech product acceptance.
No real-provider work is authorized by this handoff. Before each batch record
explicit authorized models, maximum sessions, total audio duration, tool calls,
embedding calls and currency/spend ceiling, then track actual consumption.
First compare baseline ASR versus candidate with identical recordings,
conversation model, voice, instructions, VAD and noise. Freeze the chosen short
prompt/vocabulary before held-out evaluation. Next compare 500 versus 800 ms
silence with threshold/prefix and selected ASR fixed. Finally compare noise
off/near_field for confirmed headsets or off/far_field for confirmed laptop
microphones. Use fresh sessions and the same utterance order/context each time:
gpt-transcribe uses earlier transcribed turns as context.
Report WER <=10% quiet, <=15% office, <=25% moderate noise; zero designated
quiet/office critical errors; segmentation, empty/truncated transcripts,
completion delay, response latency, exact full profiles/digests and unavailable
usage/cost. Investigate >20% comparable p95 latency regression before promotion.
Classify capture, assembly, ASR, segmentation and direct audio understanding
independently; improved ASR does not establish improved model understanding.
## Actual frontend handoff and acceptance checklist
The repository contains developer examples, not the separately maintained
production frontend. No actual browser/hardware acceptance or frontend repair is
claimed. The receiving developer must record frontend build/commit, backend
build/commit, browser/version, OS, capture device and all observed results.
Use the runnable [VoiceTranscripts helper](../../examples/voice-transcripts.js)
with existing VoiceClient onEvent callbacks:
```javascript
import {VoiceTranscripts} from './voice-transcripts.js';
import {VoiceClient} from './voice-client.js';
const display = new VoiceTranscripts();
const client = new VoiceClient(event => {
const row = display.apply(event);
if (row) renderTranscript(row.turn_ref, row.role, row.text, row.status);
// Handle other existing events as before.
});
// At the start of each fresh session: display.reset().
```
The callback retains the unchanged application events. Partial text appends by
turn_ref AND role; a completed full text replaces that row. Never append finals
or assign late finals to the latest active turn. Identical words in distinct
deltas are real content. Provider identity replay is handled by the backend; the
public transcript has no replay ID, so clients must not deduplicate by text.
Interruption retains assistant text marked interrupted; delayed user finals
remain displayable on their original turn. An absent transcript stays unavailable.
The helper is bounded to 512 rows/65536 characters per row and resets between
sessions. Adapt capacity to the actual renderer without retaining production
recordings or durable full voice history.
All items below are **not_run** until the receiving frontend records evidence:
- [ ] Capture PCM16LE, mono, 24000 Hz; verify bytes with an approved test fixture,
device native rate and actual resampling. Reject mismatches before capture.
- [ ] Verify positive/negative sample endian/sign, clipping and gain with actual
devices. Record browser echoCancellation/noiseSuppression/autoGainControl.
- [ ] Verify frame sizes <=9600 bytes, queue <=96000 bytes/100 messages, capture
frame loss/gaps and sustained sending, including at least 30 seconds silence.
- [ ] Verify output PCM format, sample-based playback progress per audio_ref,
queued versus heard audio, flush final progress and cleanup during stop.
- [ ] Verify repeated words, distinct equal partial deltas, full-final replacement,
T1 completion after T2 partial, role separation and unavailable transcripts.
- [ ] Verify interrupted assistant text stays interrupted; late user completion
updates only its original turn; revoked/closed sessions deliver no text.
- [ ] Verify response audio starts without waiting for ASR completion.
- [ ] For each device, collect designated natural-pause cases (including pauses
around numbers, negation, self-corrections and English terms) at 500/800 ms;
mark actual split/merge errors against human utterance boundaries.
- [ ] Exercise interruption during generation/retrieval and after generation with
queued playback; accurate heard-position truncation, terminal confirmation,
no stale output and one durable close remain required.
- [ ] Exercise fresh reservation, configuration change/replay, legacy rejection,
stop/disconnect/reconciliation, selection/access revocation and provider error.
- [ ] Record held-out condition WER/critical gates and capture/assembly failures
separately, with exact frozen profiles and latency comparisons.
- [ ] Record receiving developer and human reviewer signoff. Only then mark
frontend acceptance passed; Phase 1 remains open while any gate is unrun.
## Verification record
Exact executed checks and limitations are maintained in the baseline report.
Unit/mock/scorer fixtures are synthetic regression inputs, not quality evidence.
Applied revisions, retrieval/calibration policy, cancellation classifier,
commit fencing, response-release barriers and heard-position truncation remain.
The only runtime tightening rejects malformed transcription event types or
post-completion user deltas; display text is never a response-release condition.
Final affected validation: 361 provider-free voice/configuration/scorer/frontend
regressions passed; 82 isolated PostgreSQL profile/replay/authorization/terminal
and revocation cases passed with zero skips. The broader database run reported a
failure and was interrupted after sustained lack of progress; its full acceptance
is unverified. Broad ordinary-suite attempts also failed existing deadline and
responsiveness assertions. No assertion was weakened and no unrelated product
repair was made. Exact attempts and final results are in the baseline report.
The task-owned database container and anonymous storage were removed.
Final full provider-free attempt: 1874 passed, three existing Windows symlink
skips, one existing GeminiVision extraction 100-ms deadline failure. Both
parameter variants passed afterward in isolation (2 passed); no cause is
established and the full run is not represented as green. These checks do not
establish real microphone, ASR, hardware, frontend or deployment acceptance.
@@ -0,0 +1,143 @@
# Persian understanding Phase 3 ? implementation and gated acceptance
2026-10-11. Scope: Phase 3 only of the [quality plan](../plans/openai-realtime-persian-quality-plan.md).
Implementation and empirical acceptance are separate. No provider calls, promotion,
new agent, retrieval engine, GPT-Live adapter, migrations or dependencies.
## Optional reasoning
`OPENAI_REALTIME_REASONING_EFFORT=null` preserves omission on the provider wire.
Only `low` and `medium` are accepted for the exact `gpt-realtime-2.1` and
`gpt-realtime-2.1-mini` identifiers. Other explicit combinations fail before
provider opening, including settings copies that bypass initial validation.
Settings, factory and adapter use the existing paths. OpenAI execution profiles
freeze `reasoning` as null or an effort object. Enabled reasoning requires matching
provider acknowledgment before readiness; unrequested non-null reasoning fails.
Model/effort changes or missing enabled snapshots reject stream admission before
opening. Replay preserves identity, request hash and the original snapshot.
Use fresh reservations after changes. Gemini profiles and instructions are unchanged.
The [official Realtime session schema](https://developers.openai.com/api/reference/resources/realtime/client-events)
defines session reasoning effort. The [2.1 model](https://developers.openai.com/api/docs/models/gpt-realtime-2.1)
and [2.1 mini model](https://developers.openai.com/api/docs/models/gpt-realtime-2.1-mini)
are reasoning-capable Realtime candidates. The project restricts effort to its
planned low/medium comparison; documentation does not establish account access
or empirical cancellation compatibility. No classifier extension is authorized
without exact structured candidate evidence; the existing baseline restriction stays.
## Track A preflight
[Comparison report](../evaluation/openai-persian-understanding-comparison.json)
records exact secret-safe local profiles. Local deployment observation is unverified.
Local settings: OpenAI gpt-realtime-mini/shimmer; gpt-transcribe languages fa,en;
server VAD threshold 0.5, prefix 300 ms, silence 500 ms, both automatic flags false;
noise reduction null; style iranian-persian-professional-v1 and recorded digest.
Transport testing is true; no calibration report is configured.
All four Phase 4 originals and the Phase 2 calibration original match recorded
SHA-256 hashes. Hash identity does not approve originals. The four approvals are
pending, document bindings null, factual DOCX inclusion unapproved, four unseen
annotations empty. Phase 2 status has cutoff null and a historical configured
embedding profile; the report separately records current local embedding identity.
No approved actor/binding set exists to verify actual persisted document eligibility,
selection, access epoch or embedding compatibility. Those checks remain blocked;
no deployment corpus or access is changed. CALIBRATION_REQUIRED remains closed.
Reuse existing commands only after approvals, identity/bindings and budget exist:
```powershell
.venv/Scripts/python -m app.calibrate_search --user-id <authorized-actor> --bindings <approved-bindings.json> --output <new-measured-report.json> --allow-provider-calls
.venv/Scripts/python -m tests.evaluate_search --cases <approved-independent-cases.json> --bindings <approved-bindings.json> --calibration <measured-report.json> --user-id <authorized-actor> --output <new-report.jsonl> --allow-provider-calls --provider-call-budget 26
```
Calibration retains its ten-call cap. Retrieval acceptance retains its 1?26 call
budget, original bindings, human review, exact selected corpus, frozen embedding
and retrieval policy, final authorization and independent question checks.
The CLIs' help was executed without provider calls. Neither calibration nor
retrieval evaluation was run. Do not treat draft/status files as measured reports.
## Track B comparison protocol
The report contains exact prospective low/medium profiles for both candidates,
with all other local settings fixed. These are preparation, not selected ASR/voice
or passing profiles. Freeze the human-selected ASR/voice, effective instructions,
26 approved dialogue scenarios (20 answerable including every critical case,
six unsupported), corpus/bindings, selection and embedding/calibration profile
before each comparison. Keep scenarios independent from retrieval labels.
No scenarios, labels, speech, listener scores or human approvals were fabricated.
Each live batch requires explicit authorized models, maximum sessions, audio
seconds, tool calls, embedding calls and spend ceiling; credentials are insufficient.
Run low first for both models. Only a measured failed understanding gate permits
separately identified medium evaluation. Use the same approved recordings and
corresponding text inputs diagnostically through existing operator/runtime paths.
No automatic evaluation runner or new orchestration was introduced.
Use the [observation template](../evaluation/openai-persian-understanding-observation.template.json)
for each case: independently classify audio interpretation, ASR display, tool query,
retrieval and answer failures. Compare human spoken intent, displayed transcript,
actual query, returned document/chunk evidence and spoken answer. A transcript
error alone is not proof of direct audio misunderstanding. Text success with audio
failure supports an audio-stage diagnosis; matching failures require inspecting
query/evidence/answer stages. Retain multiple categories when justified.
Check fresh retrieval before each document follow-up/correction/critical claim,
clarification for ambiguous references, exact numbers/dates/conditions/exclusions/
negation, all six unsupported responses and technical-error explanations.
Exercise selection removal, access revocation, late evidence suppression and fresh
sessions. Existing provider-free regressions establish runtime barriers, not model
instruction adherence. For each candidate model/voice pair, collect exact structured
cancel type/code/param with intent correlation, terminal ordering and matching
played-position item/content truncation acknowledgments. Exercise interruption
while generating, retrieving and draining completed playback, rapid follow-ups,
stop/disconnect and stale-context invalidation. Never widen error matching by text.
Select only complete passing profiles: independent retrieval gate; >=18/20 answers,
all critical, 6/6 unsupported; no invented/stale/unauthorized claims; speech/delivery
and lifecycle compatibility gates. Rank understanding, critical speech accuracy,
then delivery; latency/cost break equivalent quality. Report p50/p95 on comparable
samples; investigate p95 increase >20%. Report observed token/audio usage and
known cost or explicit unavailable status. No passing profile exists here; selection
is null, live quality/latency/usage/cost unavailable, calls/spend zero.
## Regression evidence
Checks and classified failures are recorded in the comparison JSON and appended
below after completion. No unrelated evaluation defect is silently repaired.
- Focused ASR/style/reasoning command: `.venv/Scripts/python -m pytest tests/unit/test_openai_reasoning.py tests/unit/test_openai_speech_configuration.py tests/unit/test_openai_persian_style.py -q -p no:cacheprovider --tb=short`: **51 passed**.
- Affected final regression command: `.venv/Scripts/python -m pytest tests/unit/test_openai_reasoning.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_live_context_sync.py tests/unit/test_search_phase4_gate.py tests/unit/test_search_phase4_repairs.py -q -p no:cacheprovider --tb=short`: **351 passed**, 39.30 s.
- Full provider-free command: `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: **1 failed, 1892 passed, 3 existing Windows symlink skips, 429 deselected**, 326.47 s. Existing `test_real_large_escaped_json_keeps_concurrent_loop_active[4499]` measured 132.03 ms against 100 ms. No related production or test limit was changed.
- Focused failure investigation: `.venv/Scripts/python -m pytest tests/unit/test_json_processing.py -q -p no:cacheprovider --tb=short`: **9 passed**, 11.13 s. Full-suite failure remains reported; no definitive cause or all-green regression claim.
- Final persisted profile command: `.venv/Scripts/python -m pytest tests/integration/test_openai_speech_profile.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`: **18 passed**, zero skips, 126.16 s. Includes four acknowledgment cases added after broad suite collection. Fresh task-created loopback database `rag_persian_phase3_test` in container `rag-persian-phase3-20261011-test`, port 55442, PostgreSQL 16.15 / pgvector 0.8.7. Only disposable schemas, no deployment DB writes.
- Existing label validators: calibration case structure passed; independent draft retrieval manifest failed closed with `Frozen 20 answerable / 6 unsupported with four unseen cases required` before database/provider setup.
- Python AST, report JSON, tracked whitespace, unchanged shared POLICY/Gemini adapter and applied migration byte comparisons passed.
Phase 3 affected files: configuration.py, voice_provider.py, realtime.py,
.env.example, new test_openai_reasoning.py, extended test_openai_speech_profile.py,
API catalog, this guide, comparison JSON and observation template, reference map
and Phase 3 checkpoint in the plan. Pre-existing speech/style/runtime/transcript
and evaluation edits were preserved. No public API/normalized event fields changed.
- Required broad database command: `.venv/Scripts/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` with process-local isolated TEST_DATABASE_URL: **429 passed, zero skips, 1896 deselected**, 1647.70 s. The final targeted 18-test profile run additionally covered acknowledgment tests added after this collection; counts overlap and must not be summed. No real providers.
Implementation status: implemented. Acceptance status: blocked. The unrelated
provider-free full-suite failure remains unresolved; real calibrated retrieval,
26-case dialogue quality, native speech scores and exact candidate interruption
compatibility remain not_run. Quality/latency/usage/cost cannot be inferred from
these regressions. Phase 3 is not closed and no complete profile is promoted.
Cleanup confirmed zero disposable test schemas and zero public tables. The task-created container and its anonymous volume were removed; pre-existing containers were preserved.
## Operational calibration checkpoint — 2026-10-11
After the implementation checkpoint above, the user approved the ten-case sample
and authorized execution. [The activation handoff](search-calibration-activation-2026-10-11.md)
records actual intake, selection, measured 6/6 complete support and zero unsupported
false positives across four cases, ten local embedding queries, and activation of
the measured report in the main API with transport-testing bypass disabled.
The calibration prerequisite is now satisfied in this environment. Independent
26-case acceptance, real OpenAI voice quality and candidate interruption evidence
remain pending; this operational result does not close Phase 3 or promote a fully
validated speech profile. Earlier zero-provider-call statements describe the
implementation checkpoint, not this subsequent calibration workflow.
@@ -0,0 +1,87 @@
# Measured search calibration activation — 2026-10-11
The approved ten-case calibration was executed against the PostgreSQL database used by the running `app.server` API. The successful report is now mounted read-only and selected by the API. Transport-testing bypass is disabled. This is a measured retrieval configuration for frontend testing, not completion of the independent Persian voice quality gates.
## Approval and input identity
The user explicitly approved the sample original and its ten frozen labels in this conversation, then authorized execution of the workflow.
- Original: `data/calibration/phase2-source.md`
- Original SHA-256: `7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f`
- Frozen annotations: [phase2-cases.json](../calibration/phase2-cases.json), six answerable and four unsupported cases.
- Actual document: `aa4f291c-8808-497f-975f-ce0f7f6f838a`
- Organization: `37439088-523c-4403-899f-47e3f809123c`
- Enabled administrator: `aec70b67-db27-4696-b2b9-49435a99a3b1`
- [Actual bindings](../calibration/approved-bindings.json)
- [Scoped operator approval](../calibration/operator-approval-2026-10-11.json)
The original and labels were preserved. Intake used `app.ingest import` with request ID `872d6761-e74b-4492-9e54-f3a1d5d9f066`, not direct database publication. The existing worker completed its first attempt and atomically published six chunks. Extracted block text was checked against the approved original; this deterministic check does not invent a human review. Markdown used readable-text extraction without vision inference.
Selection was changed through `app.knowledge selection replace`, fenced at revision 8. The resulting knowledge revision is 9 and access epoch remains 3. All three previously active documents remain selected; the approved calibration document was added. The queue contained no pending unrelated jobs before import.
## Actual measurement
[Measured report](../calibration/measured-search-2026-10-11.json):
| Item | Observed result |
| --- | --- |
| Status | `calibrated` |
| Complete support | 6/6 answerable cases |
| Unsupported false positives | 0/4 unsupported cases |
| Calibration query embedding calls | 10, within the authorized budget of 10 |
| Embedding profile | Ollama / bge-m3 / 1024 dimensions / preprocessing v1 |
| Canonical embedding endpoint | `http://localhost:11434/v1` |
| Selected cosine distance | `0.33686461167069426` |
| Calibration ID | `baec206d-3e5c-477c-9290-fd84f706fa28` |
| Final authorization check | Confirmed |
| OpenAI voice calls by this workflow | 0 |
| Billing and token usage | Not reported by the calibration harness |
The adapter translates the local embedding endpoint to `host.docker.internal` for container transport while preserving canonical profile identity. Ingestion embedding work is separate from the ten counted calibration query calls.
The cutoff was selected by the existing calibration algorithm from measured candidate distances. No manually chosen threshold, edited label, fabricated recording, or unsupported successful result was substituted.
Execution used the existing API image and service configuration:
```powershell
$taskRepo = (Get-Location).Path
docker compose run --rm --no-deps --volume "${taskRepo}/docs/calibration:/app/docs/calibration" --volume "${taskRepo}/data/calibration:/app/data/calibration:ro" api python -m app.calibrate_search --user-id aec70b67-db27-4696-b2b9-49435a99a3b1 --bindings /app/docs/calibration/approved-bindings.json --output /app/docs/calibration/measured-search-2026-10-11.json --allow-provider-calls
```
The report path is immutable for this run: rerunning requires a new output filename. The measured report can contain retrieved text from selected documents; retain it as an environment-specific evaluation artifact and review its contents before sharing.
## Activated runtime
Only the API service received the new read-only Compose mount:
```yaml
- ./docs/calibration:/app/docs/calibration:ro
```
The ignored local `.env` now selects:
```dotenv
SEARCH_CALIBRATION_REPORT=/app/docs/calibration/measured-search-2026-10-11.json
VOICE_TRANSPORT_TESTING=false
```
The API was recreated with `docker compose up -d --no-deps api`. Its candidate voice settings remain OpenAI `gpt-realtime-2.1`, reasoning `low`, voice `shimmer`, and user ASR `gpt-transcribe`. Gemini, applied database migrations, model cancellation classification, and existing runtime code were not edited by this operational calibration workflow.
## Verification
- All ten measured case results passed: A1–A6 returned complete evidence; U1–U4 returned `no_evidence`.
- Report annotation hash, successful status, final authorization, call budget, and embedding-profile equality passed.
- Container-side execution of the existing configuration handler with the actual administrator ID returned `voice=true`, `captions=true`, `calibration_status=calibrated`, and `voice_transport_testing=false`. This was a trusted read-only handler check, not a browser login or an authenticated HTTP acceptance test.
- The existing voice capability loader accepted the mounted report and produced the expected calibration ID, distance, profile, and retrieval policy without opening a voice-provider connection.
- HTTP `GET http://localhost:8080/health/ready`: 200, ready.
- HTTP CORS preflight for `http://localhost:4200` to `/api/v1/configuration`: 200 with the matching allowed origin.
- `git diff --check`: passed before the documentation checkpoint; rerun after final documentation.
- Broad regression suites were not rerun for this configuration/data-only workflow. Previously reported suite limitations remain.
## Frontend test and remaining acceptance
Connect the frontend to `http://localhost:8080` and create a fresh voice session. Existing session reservations keep their frozen profiles and are not upgraded by this restart.
For a direct calibration smoke check, ask about the sample pump pressure and temperature condition, or the application discount and permit exclusion. An unsupported question such as the land price should yield a lack-of-evidence answer rather than an invented value. Then test actual uploaded documents and record displayed user transcript, tool query, returned evidence, spoken answer, pauses, and interruptions separately.
The independent 26-case corpus still lacks complete approvals, bindings, and human labels. No independent retrieval gate, real OpenAI dialogue evaluation, listening score, or candidate interruption compatibility was run here. The sample's 10/10 result does not prove accuracy on every uploaded document and does not establish ASR or Persian delivery quality. Phase 3 quality acceptance remains open.
@@ -0,0 +1,437 @@
# 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](../../AGENTS.md) and [the shared reference map](../agent-reference-map.md) 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](https://developers.openai.com/api/reference/resources/realtime/client-events).
### 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](https://developers.openai.com/api/docs/guides/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](https://developers.openai.com/api/docs/guides/realtime-conversations).
- Conversation candidates: [GPT-Realtime-2.1](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) and [GPT-Realtime-2.1-mini](https://developers.openai.com/api/docs/models/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](https://developers.openai.com/api/docs/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:
```powershell
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`:
```powershell
.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
```text
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](https://developers.openai.com/api/docs/guides/voice-prompting); 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
```text
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](https://developers.openai.com/api/docs/models/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
```text
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
```text
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](../guides/openai-persian-understanding-phase3.md). 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.
+55 -26
View File
@@ -1,4 +1,4 @@
# RAG Assistant — Phase 1 API Catalog # RAG Assistant — Phase 1 API Catalog
Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
one backend adapter. Gemini remains the temporary default because an OpenAI one backend adapter. Gemini remains the temporary default because an OpenAI
@@ -14,7 +14,7 @@ its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged. documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational. Version 1.3 آ· 2026-10-07 آ· Current Live document MVP contract; planned endpoints are not claimed operational.
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1. Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
@@ -70,7 +70,7 @@ Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` be
## 3. Authentication ## 3. Authentication
### A01 — Login ### A01 — Login
```json ```json
{"username":"demo.admin","password":"<password>"} {"username":"demo.admin","password":"<password>"}
@@ -82,17 +82,17 @@ Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` be
Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login. Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.
### A02 — Logout ### A02 — Logout
No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation. No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.
### A03 — Current identity ### A03 — Current identity
No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`. No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`.
## 4. Documents and selected knowledge ## 4. Documents and selected knowledge
### D01 — Upload ### D01 — Upload
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive. `multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
@@ -104,11 +104,11 @@ Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PN
202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload. 202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.
### D02 — List ### D02 — List
Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list. Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list.
### D03 — Detail / processing polling ### D03 — Detail / processing polling
```json ```json
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}} {"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
@@ -116,7 +116,7 @@ Query: common pagination; optional `status=queued|processing|ready|failed`, `is_
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail includes `review_required`, `review_state`, frozen `ocr_review_required` and `extraction_quality_decision` (null before complete extraction). D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID. `searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail includes `review_required`, `review_state`, frozen `ocr_review_required` and `extraction_quality_decision` (null before complete extraction). D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
### D04 — Retry failed processing ### D04 — Retry failed processing
No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice. No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.
@@ -183,7 +183,7 @@ paths, models or reviewer fields. Rejecting keeps zero publication and a safe
failure reason. Lost worker ownership cannot attach candidates; an admin cannot failure reason. Lost worker ownership cannot attach candidates; an admin cannot
approve a fresh OCR response using an old digest. approve a fresh OCR response using an old digest.
### D05 — Delete (deferred HTTP/UI) ### D05 — Delete (deferred HTTP/UI)
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response. Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
@@ -193,13 +193,13 @@ Required `expected_revision` is the current knowledge revision; required idempot
202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility. 202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.
### K01 — Get selection ### K01 — Get selection
```json ```json
{"revision":1,"access_epoch":1,"document_ids":[]} {"revision":1,"access_epoch":1,"document_ids":[]}
``` ```
### K02 — Replace selected set ### K02 — Replace selected set
This replaces the entire set, not a delta. UI reads current selection before toggling a document. This replaces the entire set, not a delta. UI reads current selection before toggling a document.
@@ -215,7 +215,7 @@ Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected ID
## 5. Configuration (read-only in MVP) ## 5. Configuration (read-only in MVP)
### F01 — Read ### F01 — Read
```json ```json
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":20971520,"ocr_review_required":true}} {"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":20971520,"ocr_review_required":true}}
@@ -223,7 +223,7 @@ Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected ID
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities. Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
### F02 — Update (deferred) ### F02 — Update (deferred)
```json ```json
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."} {"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."}
@@ -233,7 +233,7 @@ Runtime must replace illustrative capability placeholders with actual configurat
## 6. Conversations and deferred text ## 6. Conversations and deferred text
### C01 — Create ### C01 — Create
```json ```json
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","title":"Working hours"} {"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","title":"Working hours"}
@@ -245,11 +245,11 @@ Runtime must replace illustrative capability placeholders with actual configurat
The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1. The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.
### C02 — List own conversations (deferred history UI) ### C02 — List own conversations (deferred history UI)
Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role. Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.
### C03 — Read messages (deferred) ### C03 — Read messages (deferred)
Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. Old text history remains viewable even when stale. Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. Old text history remains viewable even when stale.
@@ -259,7 +259,7 @@ Common pagination, ascending sequence. Voice can return no durable messages: cur
Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status. Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.
### T01 — Submit text turn (deferred) ### T01 — Submit text turn (deferred)
```json ```json
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"} {"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"}
@@ -275,11 +275,11 @@ Assistant items also expose `turn_status` and source objects. Failed turns remai
Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID. Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.
### T02 — Recover/poll turn (deferred) ### T02 — Recover/poll turn (deferred)
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost. Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — backend-selected provider; frozen application audio/events ## 7. Voice contract — backend-selected provider; frozen application audio/events
The selected provider is backend-managed Gemini Live or OpenAI Realtime. The The selected provider is backend-managed Gemini Live or OpenAI Realtime. The
OpenAI-specific mechanisms below describe the preserved Realtime adapter; the Gemini OpenAI-specific mechanisms below describe the preserved Realtime adapter; the Gemini
@@ -289,7 +289,36 @@ requiring unheard-audio context repair closes the session rather than inventing
a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono
PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. Phase 0 freezes the application audio/event fields below. Technical implementation evidence and remaining live acceptance prerequisites are recorded in the Phase 2 repair report. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID. PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. Phase 0 freezes the application audio/event fields below. Technical implementation evidence and remaining live acceptance prerequisites are recorded in the Phase 2 repair report. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP) OpenAI Phase 1 speech configuration is server-only. New reservations freeze
the exact requested transcription/language mode/prompt/vocabulary, server VAD
parameters and optional noise reduction under execution_profile.audio_input.
The same values must be acknowledged before readiness. Existing defaults remain;
both automatic response/interrupt flags stay false. A missing or mismatched
OpenAI audio snapshot is unusable at stream admission before provider opening.
Replay retains the original identity and snapshot; never backfill it. Gemini
profiles and all public fields/events remain unchanged. See the
[Phase 1 handoff](../guides/openai-persian-speech-phase1.md) for settings and
unrun real-speech/browser gates.
OpenAI Phase 2 additionally freezes `style_revision` and
`effective_instructions_digest` (SHA-256 of exact UTF-8 composed instructions).
Missing/mismatched style fields reject stream admission before provider opening;
replay never rewrites snapshots. Effective instructions require provider
acknowledgment. Gemini instructions remain unchanged. Voice changes require fresh
sessions; candidate voices remain unverified until listening/interruption acceptance.
See [Phase 2 handoff](../guides/openai-persian-delivery-phase2.md).
OpenAI Phase 3 freezes optional `execution_profile.reasoning`: null when omitted,
or `{"effort":"low"}` / `{"effort":"medium"}` for the explicitly supported
`gpt-realtime-2.1` and `gpt-realtime-2.1-mini` candidates. Unsupported explicit
combinations reject configuration before connection. Enabled reasoning is sent as
private session reasoning and must be acknowledged before readiness. Disabled
reasoning is omitted on the wire; provider-enabled reasoning is rejected when
unrequested. Missing enabled snapshots and changed effort/model reject admission;
replay retains identity and never rewrites snapshots. Gemini/public contracts are
unchanged. See [Phase 3 report](../guides/openai-persian-understanding-phase3.md).
### V01 — Create session (HTTP)
```json ```json
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"} {"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"}
@@ -303,7 +332,7 @@ Voice conversation must be owned and current-epoch. Reserve session before provi
No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio. No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio.
### V02 — Poll state, diagnostics and recent retrieved sources (HTTP) ### V02 — Poll state, diagnostics and recent retrieved sources (HTTP)
```json ```json
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"<verified source passage>","location":{"page":1,"section":"<verified clause>"},"available":true}]}]} {"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"<verified source passage>","location":{"page":1,"section":"<verified clause>"},"available":true}]}]}
@@ -311,11 +340,11 @@ No persistent provider secret or provider credential is returned. Backend adapte
Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result. Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result.
### V03 — Recover creation by request ID (HTTP) ### V03 — Recover creation by request ID (HTTP)
200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context. 200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context.
### V04 — Close (HTTP) ### V04 — Close (HTTP)
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session. No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session.
@@ -478,7 +507,7 @@ Transcript status is partial, completed or interrupted. The backend assigns turn
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. 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.
### 7.2 Internal model tool — `search_knowledge` ### 7.2 Internal model tool — `search_knowledge`
Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority: Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority:
@@ -486,7 +515,7 @@ Model arguments, identical for the internal text-query harness, later text chat
{"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."} {"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."}
``` ```
`query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs. `query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs.
Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders: Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders:
+37
View File
@@ -0,0 +1,37 @@
/* Current-session display only. Never send these buffers back as model input. */
export class VoiceTranscripts {
constructor() { this.rows = new Map(); }
reset() { this.rows.clear(); }
apply(event) {
if (event.type === 'turn_interrupted') {
if (typeof event.turn_ref !== 'string' || !event.turn_ref) throw new Error('INVALID_TRANSCRIPT');
const key = event.turn_ref + ':assistant';
const row = this.rows.get(key) || {turn_ref: event.turn_ref, role: 'assistant', text: ''};
this.store(key, {...row, status: 'interrupted'});
return this.rows.get(key);
}
if (event.type !== 'transcript') return null;
const {turn_ref, role, text, status} = event;
if (typeof turn_ref !== 'string' || !turn_ref || !['user', 'assistant'].includes(role)
|| typeof text !== 'string' || !['partial', 'completed', 'interrupted'].includes(status)) {
throw new Error('INVALID_TRANSCRIPT');
}
const key = turn_ref + ':' + role, previous = this.rows.get(key);
if (previous?.status === 'interrupted') return previous;
if (previous?.status === 'completed') {
if (status === 'completed' && text === previous.text) return previous;
throw new Error('TRANSCRIPT_AFTER_COMPLETION');
}
// Different provider events may contain identical words. The backend deduplicates
// event identities; comparing text here would delete legitimately repeated speech.
const row = {turn_ref, role, text: status === 'partial' ? (previous?.text || '') + text : text, status};
this.store(key, row);
return row;
}
store(key, row) {
if ((!this.rows.has(key) && this.rows.size >= 512) || row.text.length > 65536) {
throw new Error('TRANSCRIPT_DISPLAY_CAPACITY');
}
this.rows.set(key, Object.freeze(row));
}
}
@@ -0,0 +1,148 @@
"""Persisted Phase 1 quality profiles exercised through authenticated HTTP/ASGI."""
from copy import deepcopy
import json
from uuid import UUID
import pytest
from sqlalchemy import text
from starlette.websockets import WebSocketDisconnect
from app.api.v1 import dependencies
from app.infrastructure.realtime import RealtimeAdapter
from tests.integration.test_phase2_postgres import seeded_env,api,login,session
from tests.unit.test_realtime_phase1 import until
from tests.unit.test_openai_speech_configuration import CANDIDATE
pytestmark=pytest.mark.postgres
@pytest.mark.parametrize('api',['openai'],indirect=True)
@pytest.mark.parametrize('change',['legacy','asr','vad','noise','prompt','keywords','style_revision','effective_instructions_digest'])
def test_incompatible_profile_replay_retains_identity_and_rejects_before_open(api,change):
client,wire,runner,e=api
headers,result,body=session(client,e);sid=UUID(result['session_id'])
with e.engine.connect() as conn:
original=conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'),{'id':sid}).one()
pinned=deepcopy(original.execution_profile)
if change in ('legacy','style_revision','effective_instructions_digest'):
if change=='legacy':
pinned.pop('audio_input')
else:
pinned[change]='obsolete'
with e.engine.begin() as conn:
conn.execute(text('UPDATE live_sessions SET execution_profile=CAST(:profile AS jsonb) WHERE id=:id'),
{'id':sid,'profile':json.dumps(pinned)})
config=e.voice_config
else:
updates={'asr':CANDIDATE,'vad':dict(openai_realtime_vad_silence_duration_ms=800),
'noise':dict(openai_realtime_noise_reduction='far_field'),
'prompt':dict(openai_realtime_asr_prompt='Technical support.'),
'keywords':dict(CANDIDATE,openai_realtime_asr_keywords=('new-term',))}[change]
config=e.voice_config.model_copy(update=updates)
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
assert replay.status_code==202 and replay.json()['session_id']==str(sid)
assert replay.headers['Idempotency-Replayed']=='true'
recovery=client.get('/api/v1/voice/sessions/by-request/'+body['client_request_id'])
assert recovery.json()['session_id']==str(sid)
with pytest.raises(WebSocketDisconnect) as lost:
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}):pass
assert lost.value.code==1008 and not e.connections and not wire.sent
with e.engine.connect() as conn:
saved=conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'),{'id':sid}).one()
assert saved.execution_profile==pinned and saved.request_hash==original.request_hash
@pytest.mark.parametrize('api',['openai'],indirect=True)
@pytest.mark.parametrize('mismatch',[False,True])
def test_candidate_profile_is_frozen_and_readiness_requires_provider_ack(api,mismatch):
client,wire,runner,e=api
config=e.voice_config.model_copy(update=dict(CANDIDATE,openai_realtime_noise_reduction='near_field'))
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
headers,result,body=session(client,e);sid=UUID(result['session_id'])
with e.engine.connect() as conn:
frozen=conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()
assert frozen['audio_input']==config.audio_input()
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}) as ws:
ack=RealtimeAdapter(wire,input_settings=config).setup()['session']
if mismatch:ack['audio']['input']['turn_detection']['silence_duration_ms']=800
client.portal.call(wire.inbound.put,dict(type='session.updated',session=ack))
event=ws.receive_json()
if mismatch:
assert event['type']=='error' and event['error']['code']=='LIVE_PROVIDER_PROTOCOL_ERROR'
else:
assert event['type']=='session_ready'
client.portal.call(until,lambda:bool(wire.sent))
assert wire.sent[0]['session']['audio']['input']==frozen['audio_input']
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
try:
while True:ws.receive_json()
except WebSocketDisconnect:pass
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
with e.engine.connect() as conn:
saved=conn.execute(text('SELECT execution_profile,status FROM live_sessions WHERE id=:id'),{'id':sid}).one()
assert saved.execution_profile==frozen
assert saved.status==('failed' if mismatch else 'closed')
@pytest.mark.parametrize('api',['openai'],indirect=True)
@pytest.mark.parametrize('change', ['missing', 'effort', 'disabled', 'model'])
def test_reasoning_snapshot_replay_rejected_before_open(api, change):
client, wire, runner, e = api
config = e.voice_config.model_copy(update=dict(openai_realtime_model='gpt-realtime-2.1',
openai_realtime_reasoning_effort='low'))
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
headers, result, body = session(client, e); sid = UUID(result['session_id'])
with e.engine.connect() as conn:
original = conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'), {'id':sid}).one()
pinned = deepcopy(original.execution_profile)
assert pinned['reasoning'] == {'effort':'low'}
if change == 'missing':
del pinned['reasoning']
with e.engine.begin() as conn:
conn.execute(text('UPDATE live_sessions SET execution_profile=CAST(:profile AS jsonb) WHERE id=:id'),
{'id':sid,'profile':json.dumps(pinned)})
else:
updates = {'effort':dict(openai_realtime_reasoning_effort='medium'),
'disabled':dict(openai_realtime_reasoning_effort=None),
'model':dict(openai_realtime_model='gpt-realtime-2.1-mini')}[change]
config = config.model_copy(update=updates)
replay = client.post('/api/v1/voice/sessions', json=body, headers=headers)
assert replay.status_code == 202 and replay.json()['session_id'] == str(sid)
assert replay.headers['Idempotency-Replayed'] == 'true'
with pytest.raises(WebSocketDisconnect) as lost:
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}): pass
assert lost.value.code == 1008 and not e.connections and not wire.sent
with e.engine.connect() as conn:
saved = conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'), {'id':sid}).one()
assert saved.execution_profile == pinned and saved.request_hash == original.request_hash
@pytest.mark.parametrize('api',['openai'],indirect=True)
@pytest.mark.parametrize('model', ['gpt-realtime-2.1', 'gpt-realtime-2.1-mini'])
@pytest.mark.parametrize('mismatch', [False, True])
def test_reasoning_readiness_requires_matching_ack(api, model, mismatch):
client, wire, runner, e = api
config = e.voice_config.model_copy(update=dict(openai_realtime_model=model, openai_realtime_reasoning_effort='low'))
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
headers, result, body = session(client, e); sid = UUID(result['session_id'])
with e.engine.connect() as conn:
frozen = conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'), {'id':sid}).scalar_one()
assert frozen['reasoning'] == {'effort':'low'}
with client.websocket_connect('ws://localhost:8000'+result['stream_path'], headers={'Origin':headers['Origin']}) as ws:
ack = RealtimeAdapter(wire, model=model, input_settings=config).setup()['session']
if mismatch: ack['reasoning']['effort'] = 'medium'
client.portal.call(wire.inbound.put, dict(type='session.updated',session=ack))
event = ws.receive_json()
if mismatch:
assert event['type']=='error' and event['error']['code']=='LIVE_PROVIDER_PROTOCOL_ERROR'
else:
assert event['type']=='session_ready'
assert wire.sent[0]['session']['reasoning'] == frozen['reasoning']
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
try:
while True: ws.receive_json()
except WebSocketDisconnect: pass
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
client.portal.call(until, lambda:sid not in ACTIVE_MEDIA_SESSIONS)
with e.engine.connect() as conn:
saved = conn.execute(text('SELECT execution_profile,status FROM live_sessions WHERE id=:id'), {'id':sid}).one()
assert saved.execution_profile == frozen
assert saved.status == ('failed' if mismatch else 'closed')
+24
View File
@@ -0,0 +1,24 @@
import fs from 'node:fs';
import assert from 'node:assert/strict';
const source = fs.readFileSync(new URL('../../examples/voice-transcripts.js', import.meta.url), 'utf8');
const {VoiceTranscripts} = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));
const display = new VoiceTranscripts();
const event = (turn_ref, role, text, status='partial') => ({type:'transcript',turn_ref,role,text,status});
assert.equal(display.apply(event('t1','user','نه ')).text, 'نه ');
assert.equal(display.apply(event('t1','user','نه ')).text, 'نه نه ');
display.apply(event('t2','user','بعدی'));
assert.equal(display.apply(event('t1','user','نه نه، فردا','completed')).text,'نه نه، فردا');
assert.equal(display.rows.get('t2:user').text,'بعدی');
assert.equal(display.apply(event('t1','user','نه نه، فردا','completed')).text,'نه نه، فردا');
assert.throws(()=>display.apply(event('t1','user','late')),/AFTER_COMPLETION/);
display.apply(event('t3','assistant','پاسخ'));
assert.equal(display.apply({type:'turn_interrupted',turn_ref:'t3'}).status,'interrupted');
assert.equal(display.apply(event('t3','assistant','late','completed')).text,'پاسخ');
display.apply(event('t3','user','اصل','completed'));
assert.equal(display.rows.get('t3:user').status,'completed');
display.apply({type:'turn_interrupted',turn_ref:'t4'});
assert.equal(display.apply(event('t4','assistant','late','completed')).text,'');
assert.throws(()=>display.apply({...event('t5','user','x'),text:7}),/INVALID/);
display.reset(); assert.equal(display.rows.size,0);
for(let n=0;n<512;n++) display.apply(event('t'+n,'user','x'));
assert.throws(()=>display.apply(event('overflow','user','x')),/CAPACITY/);
+57
View File
@@ -0,0 +1,57 @@
"""Prompt transport/profile invariants; these do not measure Persian delivery."""
import asyncio
from copy import deepcopy
from hashlib import sha256
import pytest
from app.infrastructure.realtime import POLICY, RealtimeAdapter
from app.infrastructure.gemini_live import GeminiLiveAdapter
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.openai_style import STYLE_REVISION
from tests.unit.test_realtime_phase1 import Transport
@pytest.mark.parametrize('voice', ['shimmer', 'marin', 'cedar'])
def test_setup_and_profile_pin_exact_effective_instructions(voice):
config = VoiceSettings(_env_file=None, provider='openai', openai_realtime_voice=voice)
adapter = RealtimeAdapter(Transport(), model=config.selected_model, voice=voice)
setup = adapter.setup()['session']
assert setup['instructions'].startswith(POLICY + '\n\n')
assert config.profile()['style_revision'] == STYLE_REVISION
assert config.profile()['effective_instructions_digest'] == sha256(
setup['instructions'].encode('utf-8')).hexdigest()
assert adapter.acknowledged(deepcopy(setup))
changed = deepcopy(setup)
changed['instructions'] = POLICY
assert not adapter.acknowledged(changed)
assert setup['audio']['input']['turn_detection']['create_response'] is False
assert setup['audio']['input']['turn_detection']['interrupt_response'] is False
assert setup['tools'][0]['name'] == 'search_knowledge'
def test_voice_only_comparison_keeps_all_other_setup_fields_fixed():
setups = []
for voice in ('shimmer', 'marin', 'cedar'):
session = RealtimeAdapter(Transport(), voice=voice).setup()['session']
assert session['audio']['output'].pop('voice') == voice
setups.append(session)
assert setups[0] == setups[1] == setups[2]
def test_gemini_effective_policy_and_profile_are_unchanged():
async def scenario():
wire = Transport()
adapter = GeminiLiveAdapter(wire)
try:
await adapter.send(adapter.setup())
assert wire.sent[0]['setup']['systemInstruction']['parts'] == [{'text': POLICY}]
finally:
await adapter.close()
asyncio.run(scenario())
profile = VoiceSettings(_env_file=None, provider='gemini').profile()
assert set(profile) == {'provider','model','voice','input_sample_rate','output_sample_rate'}
@pytest.mark.parametrize('voice', ['marin', 'cedar'])
def test_unverified_pairs_do_not_accept_baseline_cancellation_error(voice):
assert not RealtimeAdapter(Transport(), voice=voice).is_no_active(dict(
type='invalid_request_error', code='response_cancel_not_active', param=None))
+71
View File
@@ -0,0 +1,71 @@
"""Optional reasoning remains private, pinned, and validated before remote opening."""
import asyncio
from copy import deepcopy
import pytest
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.settings import RuntimeSettings
from app.infrastructure.realtime import RealtimeAdapter
from app.infrastructure import voice_provider
from tests.unit.test_realtime_phase1 import Transport
@pytest.mark.parametrize('model', ['gpt-realtime-2.1', 'gpt-realtime-2.1-mini'])
@pytest.mark.parametrize('effort', ['low', 'medium'])
def test_candidate_setup_profile_and_ack(model, effort):
config = VoiceSettings(_env_file=None, provider='openai', openai_realtime_model=model,
openai_realtime_reasoning_effort=effort)
adapter = RealtimeAdapter(Transport(), model=model, input_settings=config)
session = adapter.setup()['session']
assert session['reasoning'] == config.profile()['reasoning'] == {'effort': effort}
assert adapter.acknowledged(deepcopy(session))
for value in (None, {}, {'effort': 'high'}, {'effort': 1}):
ack = deepcopy(session); ack['reasoning'] = value
assert not adapter.acknowledged(ack)
ack = deepcopy(session); del ack['reasoning']
assert not adapter.acknowledged(ack)
session['reasoning']['effort'] = 'high'
assert adapter.setup()['session']['reasoning']['effort'] == effort
@pytest.mark.parametrize('values', [
{'openai_realtime_reasoning_effort': 'high'},
{'openai_realtime_reasoning_effort': ''},
{'openai_realtime_reasoning_effort': True},
{'openai_realtime_reasoning_effort': 'low'},
{'openai_realtime_model': 'gpt-realtime-2.1-other', 'openai_realtime_reasoning_effort': 'low'},
])
def test_invalid_configuration(values):
with pytest.raises(ValueError): VoiceSettings(_env_file=None, provider='openai', **values)
def test_optional_environment_and_gemini_isolation(monkeypatch):
baseline = VoiceSettings(_env_file=None, provider='openai')
adapter = RealtimeAdapter(Transport(), input_settings=baseline)
assert baseline.profile()['reasoning'] is None
assert 'reasoning' not in adapter.setup()['session']
ack = deepcopy(adapter.setup()['session']); ack['reasoning'] = {'effort': 'low'}
assert not adapter.acknowledged(ack)
monkeypatch.setenv('OPENAI_REALTIME_MODEL', 'gpt-realtime-2.1')
monkeypatch.setenv('OPENAI_REALTIME_REASONING_EFFORT', 'low')
assert VoiceSettings(_env_file=None, provider='openai').profile()['reasoning'] == {'effort': 'low'}
monkeypatch.setenv('OPENAI_REALTIME_REASONING_EFFORT', 'null')
assert VoiceSettings(_env_file=None, provider='openai').profile()['reasoning'] is None
gemini = VoiceSettings(_env_file=None, provider='gemini')
assert gemini.model_copy(update={'openai_realtime_reasoning_effort': 'low'}).profile() == gemini.profile()
assert 'reasoning' not in gemini.profile()
def test_factory_revalidates_before_open(monkeypatch):
opened = []
async def connect(*args): opened.append(args); return Transport()
monkeypatch.setattr(voice_provider, 'connect_openai', connect)
async def scenario():
base = VoiceSettings(_env_file=None, provider='openai', openai_realtime_api_key='fake-only')
for updates in ({'openai_realtime_reasoning_effort': 'low'},
{'openai_realtime_model': 'gpt-realtime-2.1', 'openai_realtime_reasoning_effort': 'high'}):
with pytest.raises(ValueError):
await voice_provider.create_adapter(base.model_copy(update=updates), RuntimeSettings())
assert not opened
config = base.model_copy(update={'openai_realtime_model': 'gpt-realtime-2.1',
'openai_realtime_reasoning_effort': 'low'})
adapter = await voice_provider.create_adapter(config, RuntimeSettings())
assert len(opened) == 1
assert adapter.setup()['session']['reasoning'] == config.profile()['reasoning']
await adapter.close()
asyncio.run(scenario())
@@ -0,0 +1,168 @@
"""Phase 1 private quality configuration and normalized transcript invariants."""
import asyncio
from copy import deepcopy
from types import SimpleNamespace
from pathlib import Path
import shutil
import subprocess
import pytest
from app.modules.voice.configuration import VoiceSettings, OpenAIInputSettings
from app.modules.voice.settings import RuntimeSettings
from app.infrastructure.realtime import RealtimeAdapter
from app.infrastructure import voice_provider
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, commands, until, Transport
from tests.unit.test_realtime_remaining import user_asr
CANDIDATE = dict(openai_realtime_asr_model='gpt-transcribe',
openai_realtime_asr_language=None, openai_realtime_asr_languages=('fa','en'),
openai_realtime_asr_prompt='Iranian Persian technical support with English terminology.',
openai_realtime_asr_keywords=('PCM16LE','API'))
def test_defaults_and_candidate_profile():
baseline = VoiceSettings(_env_file=None, provider='openai')
candidate = VoiceSettings(_env_file=None, provider='openai', **CANDIDATE)
for config in (baseline,candidate):
adapter=RealtimeAdapter(Transport(), input_settings=config)
assert adapter.setup()['session']['audio']['input'] == config.profile()['audio_input']
assert adapter.acknowledged(deepcopy(adapter.setup()['session']))
assert baseline.audio_input()['transcription'] == dict(model='whisper-1',language='fa')
assert candidate.audio_input()['transcription']['languages'] == ['fa','en']
assert 'language' not in candidate.audio_input()['transcription']
assert baseline.audio_input()['turn_detection'] == dict(type='server_vad',create_response=False,
interrupt_response=False,threshold=.5,prefix_padding_ms=300,silence_duration_ms=500)
assert baseline.audio_input()['noise_reduction'] is None
profile=candidate.profile();profile['audio_input']['transcription']['languages'].clear()
assert candidate.profile()['audio_input']['transcription']['languages']==['fa','en']
@pytest.mark.parametrize('values', [
dict(openai_realtime_asr_model='gpt-live-transcribe'),
dict(openai_realtime_asr_model='gpt-transcribe'),
dict(openai_realtime_asr_languages=('fa','en')),
dict(openai_realtime_asr_keywords=('API',)),
dict(CANDIDATE,openai_realtime_asr_languages=('fa','fa')),
dict(CANDIDATE,openai_realtime_asr_languages=('xx',)),
dict(CANDIDATE,openai_realtime_asr_keywords=('bad\nword',)),
dict(CANDIDATE,openai_realtime_asr_keywords=('<answer>',)),
dict(CANDIDATE,openai_realtime_asr_keywords=('x'*101,)),
dict(CANDIDATE,openai_realtime_asr_keywords=tuple(str(n) for n in range(65))),
dict(openai_realtime_asr_prompt='x'*1025),
dict(openai_realtime_vad_threshold=float('nan')),
dict(openai_realtime_vad_threshold=1.1),
dict(openai_realtime_vad_prefix_padding_ms=-1),
dict(openai_realtime_vad_silence_duration_ms=99),
dict(openai_realtime_noise_reduction='automatic'),
])
def test_invalid_configuration(values):
with pytest.raises(ValueError): VoiceSettings(_env_file=None,**values)
def test_environment_candidate(monkeypatch):
monkeypatch.setenv('OPENAI_REALTIME_ASR_MODEL','gpt-transcribe')
monkeypatch.setenv('OPENAI_REALTIME_ASR_LANGUAGE','null')
monkeypatch.setenv('OPENAI_REALTIME_ASR_LANGUAGES','["fa","en"]')
monkeypatch.setenv('OPENAI_REALTIME_ASR_KEYWORDS','["PCM16LE","API"]')
monkeypatch.setenv('OPENAI_REALTIME_VAD_SILENCE_DURATION_MS','800')
config=VoiceSettings(_env_file=None,provider='openai')
assert config.audio_input()['transcription']['languages']==['fa','en']
assert config.audio_input()['turn_detection']['silence_duration_ms']==800
@pytest.mark.parametrize('field,value',[
('transcription',dict(model='whisper-1',language='fa')),
('noise_reduction',None),
('turn_detection',dict(type='server_vad',create_response=True,interrupt_response=False)),
])
def test_acknowledgment_mismatch(field,value):
config=OpenAIInputSettings(**CANDIDATE,openai_realtime_noise_reduction='near_field')
adapter=RealtimeAdapter(Transport(),input_settings=config)
ack=deepcopy(adapter.setup()['session']);ack['audio']['input'][field]=value
assert not adapter.acknowledged(ack)
def test_conflicting_language_acknowledgment():
adapter=RealtimeAdapter(Transport(),input_settings=OpenAIInputSettings(**CANDIDATE))
ack=deepcopy(adapter.setup()['session']);ack['audio']['input']['transcription']['language']='fa'
assert not adapter.acknowledged(ack)
def test_factory_validation_precedes_remote_open_and_gemini_isolation(monkeypatch):
opened=[]
async def connect(*args): opened.append(args);return Transport()
monkeypatch.setattr(voice_provider,'connect_openai',connect)
monkeypatch.setattr(voice_provider,'connect_gemini',connect)
async def scenario():
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only',**CANDIDATE)
adapter=await voice_provider.create_adapter(config,RuntimeSettings())
assert adapter.setup()['session']['audio']['input']==config.profile()['audio_input']
await adapter.close()
bad=config.model_copy(update={'openai_realtime_asr_model':'unsupported'})
with pytest.raises(ValueError): await voice_provider.create_adapter(bad,RuntimeSettings())
assert len(opened)==1
gemini=VoiceSettings(_env_file=None,provider='gemini',gemini_api_key='fake-only')
changed=gemini.model_copy(update={'openai_realtime_vad_silence_duration_ms':800})
assert changed.profile()==gemini.profile()
assert set(gemini.profile())=={'provider','model','voice','input_sample_rate','output_sample_rate'}
a=await voice_provider.create_adapter(gemini,RuntimeSettings())
b=await voice_provider.create_adapter(changed,RuntimeSettings())
assert a.setup()==b.setup()
await a.close();await b.close()
asyncio.run(scenario())
def test_transcript_ordering_repeated_words_delayed_completion_and_release(runner,persisted):
async def scenario():
r,wire,out=await make(SimpleNamespace(engine=None),runner,persisted)
try:
first=await input_turn(r,'u1',commit=False)
await r.handle(user_asr('u1','نه ','delta-a',completed=False))
await r.handle(user_asr('u1','نه ','delta-a',completed=False)) # identity replay
await r.handle(user_asr('u1','نه ','delta-b',completed=False)) # legitimate repetition
await until(lambda:sum(e.get('role')=='user' for e in out)==2)
second=await input_turn(r,'u2',200)
await until(lambda:bool(commands(wire,'response.create')))
assert not second.transcript_parts # release never waits for ASR
await r.handle(user_asr('u1','نه نه، فردا','final'))
await until(lambda:any(e.get('status')=='completed' and e.get('role')=='user' for e in out))
assert [(e['turn_ref'],e['text']) for e in out if e.get('role')=='user']==[
(first.ref,'نه '),(first.ref,'نه '),(first.ref,'نه نه، فردا')]
assert r.current is second and r.usable
assert not commands(wire,'conversation.item.create')
finally: await r.close()
asyncio.run(scenario())
@pytest.mark.parametrize('mutation',['late_delta','unknown_item','bad_index','bad_text','unknown_type'])
def test_malformed_or_post_completion_transcript_fails_closed(runner,persisted,mutation):
async def scenario():
r,wire,out=await make(SimpleNamespace(engine=None),runner,persisted)
try:
await input_turn(r,commit=False)
await r.handle(user_asr('u1','final','final'))
event=user_asr('u1','late','next',completed=False)
if mutation=='unknown_item':event['item_id']='unknown'
if mutation=='bad_index':event['content_index']=True
if mutation=='bad_text':event['delta']={}
if mutation=='unknown_type':event['type']='conversation.item.input_audio_transcription.fake.delta'
await r.handle(event)
assert r.failure=='LIVE_PROVIDER_PROTOCOL_ERROR'
assert not commands(wire,'response.create')
finally: await r.close()
asyncio.run(scenario())
def test_delivered_transcript_display():
node=shutil.which('node')
assert node,'Node required for frontend handoff validation'
root=Path(__file__).resolve().parents[2]
result=subprocess.run([node,str(root/'tests/support/voice_transcripts.mjs')],capture_output=True,text=True,timeout=20)
assert result.returncode==0,result.stdout+result.stderr
def test_ack_rejects_automatic_idle_response_and_accepts_numeric_threshold():
adapter=RealtimeAdapter(Transport())
ack=deepcopy(adapter.setup()['session'])
ack['audio']['input']['turn_detection']['idle_timeout_ms']=5000
assert not adapter.acknowledged(ack)
adapter=RealtimeAdapter(Transport(),input_settings=OpenAIInputSettings(openai_realtime_vad_threshold=1))
ack=deepcopy(adapter.setup()['session'])
ack['audio']['input']['turn_detection']['threshold']=1
assert adapter.acknowledged(ack)
@pytest.mark.parametrize('field,value',[('prompt','unexpected context'),('keywords',['unexpected'])])
def test_baseline_ack_rejects_unrequested_asr_guidance(field,value):
adapter=RealtimeAdapter(Transport())
ack=deepcopy(adapter.setup()['session'])
ack['audio']['input']['transcription'][field]=value
assert not adapter.acknowledged(ack)
+74
View File
@@ -0,0 +1,74 @@
"""Deterministic synthetic scorer tests; these are never speech-quality evidence."""
from copy import deepcopy
import hashlib
import json
from pathlib import Path
import pytest
from app.score_speech import tokens,word_errors,percentile,score
def test_conservative_normalization():
assert tokens('عربي، ۱۲۳ كیف؟')==tokens('عربی 123 کیف')
assert tokens('می\u200cروم')==['می','روم']
assert tokens('AC-42 1.5 1405/07')!=tokens('AC42 15 140507')
assert tokens('-5 15%')!=tokens('5 15')
assert word_errors('نه نه 42','نه 43')['errors']==2
assert word_errors('a b','a b b')['insertions']==1
assert word_errors('a b','')['deletions']==2
with pytest.raises(ValueError):word_errors('','anything')
assert percentile([10,20,30],.5)==20
assert percentile([], .95) is None
def fixture(tmp_path):
root=Path(__file__).resolve().parents[2]/'docs/evaluation'
manifest=json.loads((root/'openai-persian-speech-manifest.json').read_text())
labels=json.loads((root/'openai-persian-speech-annotations.json').read_text())
recording=tmp_path/'synthetic-fixture.bin';recording.write_bytes(b'synthetic-test-only')
profile={'provider':'openai','model':'fixture-only','voice':'fixture-only','audio_input':{}}
digest=hashlib.sha256(json.dumps(profile,sort_keys=True,separators=(',',':')).encode()).hexdigest()
observations={'effective_profile':profile,'effective_profile_sha256':digest,'observations':[]}
for sample,label in zip(manifest['samples'],labels['annotations']):
sample.update(speaker_id='synthetic-'+str(sample['planned_speaker_slot']),native_iranian_persian=True,
consent_reference='test-only',recording_path=recording.name,recording_sha256=hashlib.sha256(recording.read_bytes()).hexdigest(),duration_seconds=1)
label.update(reviewed_by='synthetic-test-only',review_status='approved',reference_text='fee 42',
critical_facts=[{'fact_id':'fee','kind':'number','literal':'42'}])
observations['observations'].append(dict(sample_id=sample['sample_id'],effective_profile_sha256=digest,
session_reference='test-only',final_transcript='fee 42',critical_fact_results={'fee':True},
critical_reviewed_by='synthetic-test-only',completion_delay_ms=100,response_latency_ms=200,
segmentation_errors=0,truncated_transcripts=0))
return manifest,labels,observations
def test_weighted_scores_missing_data_and_critical_gate(tmp_path):
m,a,o=fixture(tmp_path)
result=score(m,a,o,root=tmp_path)
assert result['scored_samples']==10 and result['asr_accuracy_status']=='passed'
assert result['phase_acceptance_status']=='not_run'
assert result['groups']['quiet']['wer']==0
held=next(s for s in m['samples'] if s['split']=='held_out' and s['condition']=='quiet')
obs=next(r for r in o['observations'] if r['sample_id']==held['sample_id'])
obs['critical_fact_results']['fee']=False
assert score(m,a,o,root=tmp_path)['asr_accuracy_status']=='failed'
obs['critical_fact_results']['fee']=True
o['observations'].remove(obs)
result=score(m,a,o,root=tmp_path)
assert result['asr_accuracy_status']=='blocked' and held['sample_id'] in result['missing_samples']
@pytest.mark.parametrize('problem',['digest','reference','critical','recording','duplicate'])
def test_refuses_invalid_evidence(tmp_path,problem):
m,a,o=fixture(tmp_path)
held=next(s for s in m['samples'] if s['split']=='held_out')
obs=next(r for r in o['observations'] if r['sample_id']==held['sample_id'])
label=next(r for r in a['annotations'] if r['sample_id']==held['sample_id'])
if problem=='digest':o['effective_profile_sha256']='wrong'
if problem=='reference':label['reference_text']=''
if problem=='critical':obs['critical_fact_results']={}
if problem=='recording':held['recording_sha256']='wrong'
if problem=='duplicate':o['observations'].append(deepcopy(obs))
with pytest.raises(ValueError):score(m,a,o,root=tmp_path)
def test_blank_assets_cannot_pass():
root=Path(__file__).resolve().parents[2]/'docs/evaluation'
m=json.loads((root/'openai-persian-speech-manifest.json').read_text())
a=json.loads((root/'openai-persian-speech-annotations.json').read_text())
o={'effective_profile':{},'effective_profile_sha256':hashlib.sha256(b'{}').hexdigest(),'observations':[]}
result=score(m,a,o,root=root)
assert result['asr_accuracy_status']=='blocked' and result['scored_samples']==0