Files
rag-technical-docs-assistant/docs/evaluation/local-s2s/phase4-browser-budget.py
amirhosein mazaheri 628aec8def feat(voice): implement local S2S responsiveness candidate and direct TTS routing
Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
2026-10-17 13:02:41 +03:30

121 lines
7.7 KiB
Python

"""Exclusive Phase3/4 guard carrying every prior billed/unknown reservation."""
import importlib.util
import json
from decimal import Decimal
from pathlib import Path
import httpx
from services.local_s2s.components import EvaluationBudgetExhausted
path=Path('/checks/browser-budget.py')
if not path.exists():path=Path(__file__).with_name('browser-budget.py')
spec=importlib.util.spec_from_file_location('previous_browser_budget',path)
previous=importlib.util.module_from_spec(spec);spec.loader.exec_module(previous)
class BrowserBudget(previous.BrowserBudget):
def __init__(self,root,*,upstream=None):
previous.native.validate_prices(root)
checkpoint=root/'carried-budget-preparation.json'
if checkpoint.exists():
# Migration from another host: documentary carry, never invented bills.
prior=json.loads(checkpoint.read_text())
previous.require(prior['prior_conservative_exposure_usd']=='0.704504399' and
prior['total_cap_usd']=='1' and prior['paid_calls_on_this_host']==0 and
prior['prior_private_ledgers_available'] is False and
prior['source']=='docs/evaluation/local-s2s/phase-04-interruption-incident.md' and
prior['status']=='preparation_only_not_a_live_admission_ledger' and
not (root/'previous-phase4-ledger.json').exists() and
not (root/'prior-final-billing.json').exists())
carried=Decimal(prior['prior_conservative_exposure_usd'])
self.maximum_attempts={'speech':4,'transcriptions':4,'completions':4}
runs_path=root/'previous-windows-runs.json'
old_ledger=root/'previous-windows-ledger.json'
old_billing=root/'previous-windows-billing.json'
previous.require(old_ledger.exists()==old_billing.exists())
if runs_path.exists():
previous.require(not old_ledger.exists())
runs=json.loads(runs_path.read_text())
previous.require(isinstance(runs,list) and 0<len(runs)<=16)
files=[]
for run in runs:
previous.require(set(run)=={'ledger','billing'} and
all(Path(run[key]).name==run[key] for key in run))
files.append((root/run['ledger'],root/run['billing']))
self.maximum_attempts={'speech':5,'transcriptions':4,'completions':4}
else:
files=[(old_ledger,old_billing)] if old_ledger.exists() else []
generation_ids=set()
for ledger_file,billing_file in files:
ledger=json.loads(ledger_file.read_text())
bills=json.loads(billing_file.read_text())
attempts=ledger['attempts']
previous.require(ledger['previous_reserved_and_billed_usd']==str(carried) and
0<len(attempts)==len(bills) and
len({row['generation_id'] for row in bills})==len(bills))
reserved=Decimal(0)
billed=Decimal(0)
for attempt in attempts:
stage=attempt['stage']
previous.require(stage in previous.RESERVES and
sum(row['stage']==stage for row in attempts)<=ledger.get('maximum_attempts',{}).get(stage,4))
reserve=Decimal(attempt['reserved_usd'])
previous.require(reserve==previous.RESERVES[stage] and
attempt['status']=='headers_received' and attempt['http_status']==200 and
attempt['generation_id'] not in generation_ids)
generation_ids.add(attempt['generation_id'])
matches=[row for row in bills if row['generation_id']==attempt['generation_id']]
previous.require(len(matches)==1)
bill=matches[0]
previous.require(bill['stage']==stage and bill['http_status']==200)
cost=Decimal(str(bill['billing']['total_cost']))
previous.require(cost.is_finite() and 0<=cost<=reserve)
reserved+=reserve
billed+=cost
previous.require(Decimal(ledger['reserved_usd'])==carried+reserved)
carried+=billed # Release only exact-ID, successful, individually billed attempts.
else:
report=json.loads((root/'prior-final-billing.json').read_text())
reconciliation=report['reconciliation']
previous.require(reconciliation['confirmed_cost_usd']=='0.003504399' and
reconciliation['unknown_reservations_usd']=='0.417' and
reconciliation['conservative_exposure_usd']=='0.420504399')
carried=Decimal(reconciliation['confirmed_cost_usd'])+Decimal(reconciliation['unknown_reservations_usd'])
self.maximum_attempts={'speech':6,'transcriptions':6,'completions':6}
carry_path=root/'previous-phase4-ledger.json'
if carry_path.exists():
carry=json.loads(carry_path.read_text())
previous.require(Decimal(carry['previous_reserved_and_billed_usd'])==carried)
attempts=carry['attempts']
previous.require(all(row['stage'] in previous.RESERVES and
Decimal(row['reserved_usd'])==previous.RESERVES[row['stage']] for row in attempts))
used=sum((Decimal(row['reserved_usd']) for row in attempts),Decimal(0))
previous.require(carried+used==Decimal(carry['reserved_usd']))
carried+=used # Includes cancelled, failed and unknown invoices; no releases.
self.maximum_attempts={'speech':4,'transcriptions':4,'completions':4}
maximum=carried+sum(previous.RESERVES[k]*v for k,v in self.maximum_attempts.items())
previous.require(maximum<1)
endpoints=json.loads((root/'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
self.tags=[e['tag'] for e in endpoints]
previous.require(set(self.tags)=={'google-ai-studio','google-vertex/global'})
bound=sum(Decimal(e['pricing']['prompt'])*8192+Decimal(e['pricing']['completion'])*2048 for e in endpoints)
previous.require(bound<previous.RESERVES['speech'])
self.path=root/'browser-paid-ledger.json'
self.state={'previous_reserved_and_billed_usd':str(carried),'reserved_usd':str(carried),
'maximum_cumulative_usd':str(maximum),'maximum_attempts':self.maximum_attempts,
'unknown_prior_reservations_usd':'0.417','attempts':[],
'carry_basis':('documentary_checkpoint_with_local_bills' if (root/'previous-windows-ledger.json').exists() or (root/'previous-windows-runs.json').exists() else 'documentary_checkpoint') if checkpoint.exists() else 'private_ledgers',
'purpose':'phase3_4_local_browser_only_no_openai_inference'}
with self.path.open('x') as output:json.dump(self.state,output,indent=2)
self.upstream=upstream or httpx.AsyncHTTPTransport(retries=0,trust_env=False)
async def handle_async_request(self, request):
stage=request.url.path.rsplit('/',1)[-1]
# Budget exhaustion is distinct from malformed requests or a broken stream.
if stage in self.maximum_attempts:
used=sum(row['stage']==stage for row in self.state['attempts'])
if used >= self.maximum_attempts[stage]:
self.state['last_denial']={'stage':stage,'reason':'attempt_limit',
'admitted_attempts':used}
self.save()
raise EvaluationBudgetExhausted('Evaluation attempt limit reached')
return await super().handle_async_request(request)