Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling. Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
107 lines
6.3 KiB
Python
107 lines
6.3 KiB
Python
"""Paid-request guard exclusively for the isolated Phase2 browser evaluation."""
|
|
import importlib.util
|
|
import json
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
import time
|
|
|
|
import httpx
|
|
|
|
spec = importlib.util.spec_from_file_location('native_budget', '/checks/native-budget-transport.py')
|
|
if not Path(spec.origin).exists():
|
|
spec = importlib.util.spec_from_file_location('native_budget', Path(__file__).with_name('native-budget-transport.py'))
|
|
native = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(native)
|
|
require = native.require
|
|
RESERVES = {'speech': Decimal('.035'), 'transcriptions': Decimal('.004'), 'completions': Decimal('.02')}
|
|
COUNTS = {'speech': 4, 'transcriptions': 3, 'completions': 3}
|
|
|
|
|
|
class BrowserBudget(native.BudgetTransport):
|
|
def __init__(self, root, *, upstream=None):
|
|
native.validate_prices(root)
|
|
prior = json.loads((root/'prior-components.json').read_text())
|
|
previous_native = json.loads((root/'prior-native.json').read_text())
|
|
billing = json.loads((root/'prior-billing.json').read_text())['earlier_components']
|
|
require(prior['reserved_usd'] == '0.56' and prior['paid_attempts'] == 4)
|
|
require(previous_native['reserved_usd'] == '0.998' and len(previous_native['attempts']) == 6)
|
|
# Release only three completed, individually billed old reservations.
|
|
# The first failed WAV and all six unbilled native attempts remain reserved.
|
|
successful = {s['stage']:s['headers']['x-generation-id'] for s in prior['stages'] if s['status']=='received'}
|
|
require(set(successful) == {'tts_pcm','stt','llm'})
|
|
costs = {}
|
|
for row in billing:
|
|
require(row['http_status'] == 200 and row['generation_id'] == successful[row['stage']])
|
|
require(row['stage'] not in costs)
|
|
amount = Decimal(str(row['billing']['total_cost']))
|
|
require(amount.is_finite() and amount >= 0)
|
|
costs[row['stage']] = amount
|
|
require(set(costs) == set(successful))
|
|
previous = Decimal('.25') + Decimal('.438') + sum(costs.values())
|
|
self.maximum_attempts=dict(COUNTS)
|
|
prior_browser=root/'previous-browser-ledger.json'
|
|
if prior_browser.exists():
|
|
earlier=json.loads(prior_browser.read_text())
|
|
require(earlier['previous_reserved_and_billed_usd']==str(previous) and len(earlier['attempts'])==6)
|
|
used=sum(Decimal(row['reserved_usd']) for row in earlier['attempts'])
|
|
require(used==Decimal('.118') and Decimal(earlier['reserved_usd'])==previous+used)
|
|
previous+=used
|
|
self.maximum_attempts={'speech':4,'transcriptions':2,'completions':2}
|
|
maximum = previous + sum(RESERVES[s]*self.maximum_attempts[s] for s in RESERVES)
|
|
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]
|
|
require(set(self.tags) == {'google-ai-studio','google-vertex/global'})
|
|
# Both routes together, full prompt maxima and 2048 audio output tokens.
|
|
# Official TTS docs forward remaining options to Gemini generationConfig.
|
|
bound = sum(Decimal(e['pricing']['prompt'])*8192 + Decimal(e['pricing']['completion'])*2048 for e in endpoints)
|
|
require(bound < RESERVES['speech'])
|
|
require(Decimal('.000001')*16384 + Decimal('.000002')*128 < RESERVES['completions'])
|
|
self.state = {'previous_reserved_and_billed_usd':str(previous),
|
|
'reserved_usd':str(previous), 'maximum_cumulative_usd':str(maximum),
|
|
'reconciled_successful_components_usd':str(sum(costs.values())),
|
|
'failed_wav_retained_usd':'.25', 'unbilled_native_retained_usd':'.438',
|
|
'previous_browser_retained_usd':'.118' if prior_browser.exists() else '0',
|
|
'maximum_attempts':self.maximum_attempts,'attempts':[]}
|
|
self.path = root/'browser-paid-ledger.json'
|
|
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]
|
|
if stage == 'completions':
|
|
require(request.method == 'POST' and str(request.url) == 'https://openrouter.ai/api/v1/chat/completions')
|
|
data=json.loads(request.content)
|
|
require(data['model']==native.MODELS['completions'] and 0 < data['max_tokens'] <= 128 and
|
|
len(json.dumps(data,ensure_ascii=False).encode()) <= 16384)
|
|
data['provider']={'allow_fallbacks':False,'max_price':{'prompt':1,'completion':2}}
|
|
request=httpx.Request('POST',request.url,headers={k:v for k,v in request.headers.items() if k!='content-length'},content=json.dumps(data).encode())
|
|
else:
|
|
stage, request = native.validate_request(request)
|
|
require(sum(row['stage']==stage for row in self.state['attempts']) < self.maximum_attempts[stage])
|
|
if stage == 'speech':
|
|
data = json.loads(request.content)
|
|
data['provider'] = {'options':{tag:{'maxOutputTokens':2048} for tag in self.tags}}
|
|
request = httpx.Request('POST',request.url,
|
|
headers={k:v for k,v in request.headers.items() if k!='content-length'},
|
|
content=json.dumps(data).encode())
|
|
total = Decimal(self.state['reserved_usd']) + RESERVES[stage]
|
|
require(total <= Decimal(self.state['maximum_cumulative_usd']) and total <= 1)
|
|
row = {'stage':stage,'reserved_usd':str(RESERVES[stage]),'status':'in_flight'}
|
|
self.state['attempts'].append(row)
|
|
self.state['reserved_usd']=str(total)
|
|
self.save()
|
|
began=time.monotonic()
|
|
try:
|
|
response=await self.upstream.handle_async_request(request)
|
|
row.update(status='headers_received',http_status=response.status_code,
|
|
generation_id=response.headers.get('x-generation-id'))
|
|
return response
|
|
except BaseException as exc:
|
|
row.update(status='failed',error_type=type(exc).__name__)
|
|
raise
|
|
finally:
|
|
row['headers_elapsed_seconds']=round(time.monotonic()-began,3)
|
|
self.save()
|