feat(voice): implement local S2S retained history and provider selection
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.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
"""Offline paired scorecard. Reads observations; never calls or switches a provider."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
PROVIDERS = ('openai', 'local_s2s')
|
||||
|
||||
|
||||
def number(value):
|
||||
if isinstance(value, bool):
|
||||
raise ValueError('Boolean is not a measurement')
|
||||
try:
|
||||
result = Decimal(str(value))
|
||||
except InvalidOperation:
|
||||
raise ValueError('Invalid measurement') from None
|
||||
if not result.is_finite() or result < 0:
|
||||
raise ValueError('Measurements must be finite and nonnegative')
|
||||
return result
|
||||
|
||||
|
||||
def p95(values):
|
||||
return sorted(values)[math.ceil(.95 * len(values)) - 1] if values else None
|
||||
|
||||
|
||||
def scorecard(data):
|
||||
samples, charges = data['samples'], data['charges']
|
||||
if len(samples) > 10000 or len(charges) > 10000:
|
||||
raise ValueError('Evaluation input bound exceeded')
|
||||
blockers, results, ids = [], {}, set()
|
||||
for sample in samples:
|
||||
if sample['provider'] not in PROVIDERS or not isinstance(sample['case_id'], str) or not sample['case_id']:
|
||||
raise ValueError('Invalid paired case identity')
|
||||
for flag in ('success', 'critical_error', 'persistent_underrun', 'duplicate', 'disconnected'):
|
||||
if type(sample[flag]) is not bool:
|
||||
raise ValueError('Observation flags must be boolean')
|
||||
for field in ('first_audible_ms', 'tool_ms', 'interruption_stop_ms'):
|
||||
if sample.get(field) is not None:
|
||||
number(sample[field])
|
||||
if sample['success'] and sample.get('first_audible_ms') is None:
|
||||
raise ValueError('Successful sample needs audible latency')
|
||||
for charge in charges:
|
||||
if charge['provider'] not in PROVIDERS or charge['kind'] not in ('startup', 'request', 'failed', 'abandoned', 'session'):
|
||||
raise ValueError('Invalid charge classification')
|
||||
if not isinstance(charge['id'], str) or not charge['id'] or charge['id'] in ids:
|
||||
raise ValueError('Charge identity missing or duplicated')
|
||||
ids.add(charge['id'])
|
||||
if charge['cost_usd'] is not None:
|
||||
number(charge['cost_usd'])
|
||||
counts = {}
|
||||
minimum = data.get('minimum_samples_per_provider')
|
||||
if type(minimum) is not int or minimum < 1:
|
||||
blockers.append('sample_threshold_not_set')
|
||||
for provider in PROVIDERS:
|
||||
rows = [r for r in samples if r['provider'] == provider]
|
||||
counts[provider] = Counter(r['case_id'] for r in rows)
|
||||
costs = [r for r in charges if r['provider'] == provider]
|
||||
complete = bool(costs) and data.get('billing_complete', {}).get(provider) is True and all(r['cost_usd'] is not None for r in costs)
|
||||
total = sum((number(r['cost_usd']) for r in costs), Decimal(0)) if complete else None
|
||||
successes = sum(r['success'] for r in rows)
|
||||
results[provider] = dict(samples=len(rows), successful_tasks=successes,
|
||||
p95_first_audible_ms=p95([float(number(r['first_audible_ms'])) for r in rows if r['success']]),
|
||||
p95_tool_ms=p95([float(number(r['tool_ms'])) for r in rows if r.get('tool_ms') is not None]),
|
||||
p95_interruption_stop_ms=p95([float(number(r['interruption_stop_ms'])) for r in rows if r.get('interruption_stop_ms') is not None]),
|
||||
total_cost_usd=str(total) if total is not None else None,
|
||||
cost_per_success_usd=str(total / successes) if total is not None and successes else None)
|
||||
if not rows or (type(minimum) is int and len(rows) < minimum):blockers.append(provider + ':insufficient_samples')
|
||||
if not complete:blockers.append(provider + ':billing_incomplete')
|
||||
if any(not r['success'] or r['critical_error'] or r['persistent_underrun'] or r['duplicate'] or r['disconnected'] for r in rows):
|
||||
blockers.append(provider + ':task_or_quality_failure')
|
||||
if counts['openai'] != counts['local_s2s']:blockers.append('cases_not_paired')
|
||||
base, local = results['openai'], results['local_s2s']
|
||||
if base['p95_first_audible_ms'] is not None and local['p95_first_audible_ms'] is not None:
|
||||
if local['p95_first_audible_ms'] > base['p95_first_audible_ms'] + 1000:blockers.append('latency_target_failed')
|
||||
if base['cost_per_success_usd'] is not None and local['cost_per_success_usd'] is not None:
|
||||
if number(base['cost_per_success_usd']) == 0:blockers.append('baseline_cost_not_positive')
|
||||
if number(local['cost_per_success_usd']) > number(base['cost_per_success_usd']) * Decimal('.70'):
|
||||
blockers.append('cost_target_failed')
|
||||
for gate in ('thresholds_accepted', 'real_provider_observations', 'human_quality_accepted', 'rollback_verified'):
|
||||
if data.get(gate) is not True:blockers.append(gate + ':pending')
|
||||
profiles = data.get('profile_sha256', {})
|
||||
if any(not isinstance(profiles.get(p), str) or len(profiles[p]) != 64 or any(c not in '0123456789abcdef' for c in profiles[p]) for p in PROVIDERS):
|
||||
blockers.append('profile_identity_missing')
|
||||
return dict(status='criteria_met' if not blockers else 'not_accepted', providers=results,
|
||||
blockers=blockers, thresholds=dict(latency_delta_ms=1000,cost_ratio='.70',minimum_samples_per_provider=minimum),
|
||||
percentile_method='nearest-rank', cost_method='sum_all_supplied_charges_including_startup_failure_abandoned',
|
||||
authorization_to_switch=False)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--input', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.input.stat().st_size > 10 * 1024 * 1024:
|
||||
parser.error('Evaluation input exceeds 10MiB')
|
||||
result = scorecard(json.loads(args.input.read_text()))
|
||||
with args.output.open('x') as output:
|
||||
json.dump(result, output, ensure_ascii=False, indent=2, allow_nan=False)
|
||||
output.write('\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user