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.
127 lines
6.0 KiB
Python
127 lines
6.0 KiB
Python
"""Evaluation-only admission guard; never imported by the operational engine.
|
|
|
|
Persistent reservations include failed requests. Exactly two attempts per component
|
|
cover construction probes and one turn. No retries or ledger reset are supported.
|
|
"""
|
|
from decimal import Decimal
|
|
from io import BytesIO
|
|
import json
|
|
from pathlib import Path
|
|
import time
|
|
import wave
|
|
from email.parser import BytesParser
|
|
from email.policy import default
|
|
|
|
import httpx
|
|
|
|
RESERVES = {'speech': Decimal('.205'), 'transcriptions': Decimal('.004'),
|
|
'completions': Decimal('.01')}
|
|
MODELS = {'speech': 'google/gemini-3.8-flash-lite-tts',
|
|
'transcriptions': 'openai/whisper-large-v3',
|
|
'completions': 'openai/gpt-4.1-mini'}
|
|
|
|
|
|
def require(condition):
|
|
if not condition:
|
|
raise ValueError('EVALUATION_BUDGET_ADMISSION_DENIED')
|
|
|
|
|
|
def validate_prices(root):
|
|
tts = json.loads((root/'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
|
|
stt = json.loads((root/'endpoints-openai-whisper-large-v3.json').read_text())['data']['endpoints']
|
|
require(0 < len(tts) <= 2 and 0 < len(stt) <= 3)
|
|
full = Decimal(0)
|
|
for e in tts:
|
|
require(e['max_prompt_tokens'] == 8192 and e['max_completion_tokens'] == 16384)
|
|
require(Decimal(e['pricing']['prompt']) <= Decimal('.0000005') and
|
|
Decimal(e['pricing']['completion']) <= Decimal('.000006'))
|
|
require(Decimal(str(e['pricing'].get('request', 0))) == 0)
|
|
full += Decimal(e['pricing']['prompt'])*8192 + Decimal(e['pricing']['completion'])*16384
|
|
require(full < RESERVES['speech'])
|
|
require(all(Decimal(e['pricing']['prompt']) <= Decimal('.000031') and
|
|
Decimal(str(e['pricing'].get('request', 0))) == 0 for e in stt))
|
|
require(sum(Decimal(e['pricing']['prompt'])*60 for e in stt) < RESERVES['transcriptions'])
|
|
require(Decimal('.000001')*8192 + Decimal('.000002')*128 < RESERVES['completions'])
|
|
return full
|
|
|
|
|
|
def validate_request(request):
|
|
stage = request.url.path.rsplit('/', 1)[-1]
|
|
require(request.method == 'POST' and request.url.host == 'openrouter.ai' and
|
|
request.url.scheme == 'https' and request.url.path in (
|
|
'/api/v1/audio/speech', '/api/v1/audio/transcriptions', '/api/v1/chat/completions'))
|
|
if stage == 'transcriptions':
|
|
message = BytesParser(policy=default).parsebytes(
|
|
('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content)
|
|
fields = {p.get_param('name', header='content-disposition'): p.get_payload(decode=True)
|
|
for p in message.iter_parts()}
|
|
require(fields['model'].decode() == MODELS[stage] and fields['language'] == b'fa')
|
|
with wave.open(BytesIO(fields['file']), 'rb') as audio:
|
|
require(audio.getnchannels() == 1 and audio.getsampwidth() == 2 and
|
|
audio.getcomptype() == 'NONE' and
|
|
0 < audio.getnframes()/audio.getframerate() <= 10)
|
|
else:
|
|
data = json.loads(request.content)
|
|
require(data['model'] == MODELS[stage])
|
|
if stage == 'speech':
|
|
require(data['voice'] == 'Kore' and data['response_format'] == 'pcm' and
|
|
0 < len(data['input'].encode()) <= 4096)
|
|
else:
|
|
require(0 < data['max_tokens'] <= 128 and
|
|
len(json.dumps(data, ensure_ascii=False).encode()) <= 8192)
|
|
# Price caps are enforced on the actual provider-bound request only.
|
|
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())
|
|
return stage, request
|
|
|
|
|
|
class BudgetTransport(httpx.AsyncBaseTransport):
|
|
def __init__(self, root, previous, *, upstream=None):
|
|
validate_prices(root)
|
|
self.path = root/'native-paid-ledger.json'
|
|
prior = json.loads(previous.read_text())
|
|
# Preserve the original run's entire reservation, even unknown TTS cost.
|
|
require(prior['reserved_usd'] == '0.56' and prior['paid_attempts'] == 4)
|
|
self.state = {'previous_reserved_usd': prior['reserved_usd'], 'reserved_usd': '0.56',
|
|
'maximum_cumulative_reserved_usd': '0.998', 'attempts': []}
|
|
require(Decimal('.56') + 2*sum(RESERVES.values()) == Decimal('.998'))
|
|
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)
|
|
|
|
def save(self):
|
|
temporary = self.path.with_suffix('.tmp')
|
|
temporary.write_text(json.dumps(self.state, indent=2)+'\n')
|
|
temporary.replace(self.path)
|
|
|
|
async def handle_async_request(self, request):
|
|
stage, request = validate_request(request)
|
|
require(sum(row['stage'] == stage for row in self.state['attempts']) < 2)
|
|
total = Decimal(self.state['reserved_usd']) + RESERVES[stage]
|
|
require(total <= Decimal('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() # Synchronous admission on the single gateway event loop.
|
|
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()
|
|
|
|
async def aclose(self):
|
|
# One shared transport belongs to the whole test, not each HTTP client.
|
|
pass
|
|
|
|
async def close_owned(self):
|
|
await self.upstream.aclose()
|