jfbrown95's picture
Rerun SubQ with full method context (#43)
17924c1
Raw History Blame Contribute Delete
9.95 kB
#!/usr/bin/env python3
"""Benchmark SubQ Snap with native decisions and Perch context sizing.
SubQ documents a 393,216-token window and at most 16 questions per request.
Perch retains full saved context where it fits and batches the questions.
Cost uses API-reported input tokens at the published $0.05 per million rate.
"""
from collections import Counter
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import httpx
import openrouter_decisions as runner
from gliner_decide import PerchSizer, SizeError
MODEL = 'subq-snap-preview'
CONTEXT_LIMIT = 393216
STATE_BUDGET = 360000
REQUEST_BUDGET = 380000
MAX_QUESTIONS = 16
_native_prediction = runner.prediction
_native_report = runner.report
_sizer = None
_sizer_lock = threading.Lock()
_source_revision = None
def prediction(pair, role, domain, pack, response, elapsed, model):
usage = response.get('usage') or {}
tokens = usage.get('input_tokens')
if isinstance(tokens, bool) or not isinstance(tokens, int) or tokens < 0:
raise runner.AnswerError('Missing input-token usage', response, elapsed)
response = dict(response, usage=dict(usage, cost=tokens * .05 / 1_000_000))
return _native_prediction(pair, role, domain, pack, response, elapsed, model)
def sizer():
global _sizer, _source_revision
with _sizer_lock:
if _sizer is None:
source = os.environ.get('PERCH_SOURCE')
if not source:
raise runner.AccountError('Set PERCH_SOURCE to a Perch checkout with npm dependencies installed')
source = Path(source)
_source_revision = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()
_sizer = PerchSizer(source, Path(os.environ.get('SUBQ_SIZING_CACHE', '.subq-sizing')))
return _sizer
def request(key, state, checks, timeout, limiter):
if not hasattr(runner._local, 'client'):
runner._local.client = httpx.Client(headers={'Authorization': 'Bearer ' + key})
payload = {'model': MODEL, 'state': state,
'questions': {c['name']: c['question'] for c in checks}}
for attempt in range(3):
limiter.wait()
response = runner._local.client.post(runner.API, json=payload, timeout=timeout)
if response.status_code >= 400:
try:
detail = response.json().get('detail') or response.json().get('error') or {}
message = detail.get('message', '') if isinstance(detail, dict) else str(detail)
code = detail.get('error_type', response.status_code) if isinstance(detail, dict) else response.status_code
except ValueError:
code, message = response.status_code, ''
error = f'SubQ HTTP {response.status_code}: {code}: {message}'
if response.status_code in (401, 402, 403, 404):
raise runner.AccountError(error)
if response.status_code in (400, 413, 422) and any(text in message.lower() for text in ('maximum model length', 'context length', 'context window', 'too many tokens')):
raise SizeError(error)
if response.status_code == 429 and attempt < 2:
try:
delay = float(response.headers.get('retry-after', 2 ** (attempt + 1)))
except ValueError:
delay = 2 ** (attempt + 1)
time.sleep(min(30, max(1, delay)))
continue
raise RuntimeError(error)
body = response.json()
if body.get('model') != MODEL:
raise runner.AccountError('SubQ returned a different model: ' + str(body.get('model')))
answers = body.get('answers')
if not isinstance(answers, dict) or set(answers) != {c['name'] for c in checks}:
raise runner.AnswerError('Missing or unexpected answers', body, 0)
for name, answer in answers.items():
if not isinstance(answer, dict) or answer.get('type') != 'noul':
raise runner.AnswerError('Unexpected answer type for ' + name, body, 0)
runner.core.probability(answer.get('noul'))
tokens = body.get('usage', {}).get('input_tokens')
if isinstance(tokens, bool) or not isinstance(tokens, int) or tokens < 0:
raise runner.AnswerError('Missing input-token usage', body, 0)
return body
raise AssertionError('unreachable')
def predict(key, pair, role, domain, pack, timeout, limiter, model):
checks = runner.questions_for(pair, domain, pack)
by_name = {c['name']: c for c in checks}
tokens, requests, discarded = 0, 0, 0
started, budget = time.monotonic(), STATE_BUDGET
try:
for attempt in range(9):
probabilities, scores, readings = {}, {}, []
try:
plans = sizer().plan(pair[role], checks, budget, REQUEST_BUDGET, MAX_QUESTIONS)
def ask(plan, names):
nonlocal requests, tokens
requests += 1
try:
body = request(key, plan['state'], [by_name[n] for n in names], timeout, limiter)
except runner.AnswerError as exc:
charged = exc.usage.get('input_tokens', 0)
if isinstance(charged, int) and not isinstance(charged, bool) and charged >= 0:
tokens += charged
raise
except SizeError:
if len(names) == 1:
raise
middle = (len(names) + 1) // 2
ask(plan, names[:middle]); ask(plan, names[middle:])
return
tokens += body['usage']['input_tokens']
for name, answer in body['answers'].items():
probability = runner.core.probability(answer['noul'])
score = runner.core.raised_score(by_name[name], probability)
if name not in scores or score > scores[name]:
scores[name], probabilities[name] = score, probability
reading = {k: v for k, v in plan.items() if k not in ('state', 'question_names')}
reading.update(question_names=names, answers=body['answers'], usage=body['usage'],
state_sha256=hashlib.sha256(json.dumps(plan['state'], sort_keys=True).encode()).hexdigest())
readings.append(reading)
for plan in plans:
names = plan['question_names']
for start in range(0, len(names), MAX_QUESTIONS):
ask(plan, names[start:start+MAX_QUESTIONS])
break
except SizeError:
discarded += len(readings)
budget //= 2
if attempt == 8 or budget < 128:
raise
if set(probabilities) != set(by_name):
raise RuntimeError('Not every question received a score')
body = {'model': MODEL, 'answers': {n: {'type': 'noul', 'noul': p} for n, p in probabilities.items()},
'usage': {'input_tokens': tokens, 'output_tokens': 0}}
row = prediction(pair, role, domain, pack, body, time.monotonic()-started, model)
row.update(readings=readings, api_requests=requests, discarded_readings=discarded,
final_state_budget=budget, perch_revision=_source_revision,
sizing={'state_budget': STATE_BUDGET, 'request_budget': REQUEST_BUDGET, 'max_questions': MAX_QUESTIONS,
'adapter_sha256': hashlib.sha256((runner.ROOT/'perch-sizing.mjs').read_bytes()).hexdigest()})
return row
except Exception as exc:
exc.usage = {'input_tokens': tokens, 'output_tokens': 0, 'cost': tokens * .05 / 1_000_000}
raise
def report(group, pack, model):
result = _native_report(group, pack, model)
# Aggregate failures without exposing private method names from sizing errors.
failures = Counter()
for row in group['failures'].values():
message = row.get('error', '')
if 'Check incomplete:' in message:
category = 'Context sizing failed'
elif message.startswith('SubQ HTTP '):
category = ':'.join(message.split(':')[:2]).strip()
elif 'timeout' in message.lower() or 'timed out' in message.lower():
category = 'Request timed out'
else:
category = 'Invalid or incomplete decision'
failures[category] += 1
result['failure_counts'] = dict(failures)
result.update(context_limit_basis='SubQ Decisions API documentation: 393216 tokens; prior 8547-token rejection now succeeds',
sizing={'state_budget': STATE_BUDGET, 'request_budget': REQUEST_BUDGET, 'max_questions': MAX_QUESTIONS},
perch_revision=next((row.get('perch_revision') for row in group['predictions'].values()
if row.get('perch_revision')), _source_revision))
return result
def configure():
runner.API = 'https://api.subq.ai/v1/systemone'
runner.API_LABEL = 'SubQ'
runner.KEY_ENV = 'SUBQ_API_KEY'
runner.COST_BASIS = 'API-reported input tokens at SubQ published $0.05 per million input tokens'
runner.HOST_PREFIX = ''
runner.CATALOG = {MODEL: ('subq-snap', MODEL, 'subq-snap-perch-full-context-systemone-v1',
'subq-snap-20261013', 'SubQ', CONTEXT_LIMIT, .05)}
runner.MODELS = (MODEL,)
runner.prediction = prediction
runner.predict = predict
runner.report = report
if __name__ == '__main__':
configure()
if '--score-saved' not in sys.argv:
sizer()
try:
runner.main()
finally:
if _sizer is not None:
_sizer.close()