my-homelab-configs/scripts/doctor-context-lab.py

196 lines
10 KiB
Python

#!/usr/bin/env python3
"""Replay a frozen Holmes decision without executing any proposed tools."""
import argparse
import copy
import fcntl
import hashlib
import importlib.metadata
import importlib.util
import io
import json
import os
from pathlib import Path
import statistics
import subprocess
import sys
import time
import uuid
from urllib.parse import urlsplit
from datetime import datetime, timezone
from unittest.mock import patch
ROOT = Path(os.environ.get('JEANNIE_AI_LAB_DIR', Path.home() / '.local/share/homelab/ai-lab'))
VERSION = '0.45.0'
TOOLS = [{'type': 'function', 'function': {'name': 'bash', 'parameters': {
'type': 'object', 'properties': {'command': {'type': 'string'},
'suggested_prefixes': {'type': 'array', 'items': {'type': 'string'}}, 'timeout': {'type': 'integer'}},
'required': ['command', 'suggested_prefixes']}}}]
def private_json(path, data):
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as stream:
json.dump(data, stream, indent=2)
def request_from_conversation(data):
messages = copy.deepcopy(data['messages'])
if messages and messages[-1].get('role') == 'assistant' and not messages[-1].get('tool_calls'):
messages.pop()
if not messages or not any(m.get('role') == 'user' for m in messages):
raise ValueError('Conversation has no user evidence')
return {'model': 'qwen2.5-coder:7b', 'messages': messages, 'tools': TOOLS,
'temperature': 0, 'seed': 42, 'stream': False}
def compress_request(request):
os.environ['HEADROOM_OFFLINE'] = '1'
from headroom import compress
before = copy.deepcopy(request['messages'])
# Use a supported lightweight estimator; actual tokens come from Ollama.
# Selecting Qwen here makes Headroom require Transformers/model downloads.
result = compress(copy.deepcopy(before), model='gpt-4o', mode='agent',
compress_user_messages=False, compress_system_messages=False,
kompress_model='disabled')
after = result.messages
if len(before) != len(after):
raise ValueError('Compression changed message count')
for old, new in zip(before, after):
# Only tool content may change. Instructions and tool-call pairing stay exact.
if old.get('role') != 'tool' and old != new:
raise ValueError('Compression changed protected message')
if {k: v for k, v in old.items() if k != 'content'} != {k: v for k, v in new.items() if k != 'content'}:
raise ValueError('Compression changed tool metadata')
if result.lossless is not True:
raise ValueError('Headroom did not verify lossless compression')
output = copy.deepcopy(request)
output['messages'] = after
return output, {'tokens_before_estimated': result.tokens_before,
'tokens_after_estimated': result.tokens_after, 'lossless': result.lossless,
'token_estimator': 'gpt-4o (not the inference model)'}
def run(request, repeats, compressed):
spec = importlib.util.spec_from_file_location('doctor_proxy', Path(__file__).with_name('ollama-tool-proxy.py'))
proxy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(proxy)
original_query = proxy.query_ollama
original_open = proxy.urllib.request.urlopen
results = []
for index in range(repeats):
upstream = []
transforms = []
def capture(*args, **kwargs):
with original_open(*args, **kwargs) as response:
raw = response.read()
data = json.loads(raw)
upstream.append({k: data.get(k) for k in ('model', 'prompt_eval_count', 'eval_count',
'total_duration', 'load_duration', 'prompt_eval_duration', 'eval_duration', 'done_reason', 'usage')})
return io.BytesIO(raw)
def query(payload):
if compressed:
start = time.monotonic()
payload, metrics = compress_request(payload)
metrics['elapsed_seconds'] = time.monotonic() - start
transforms.append(metrics)
return original_query(payload)
start = time.monotonic()
row = {'repeat': index + 1}
try:
with patch.object(proxy.urllib.request, 'urlopen', side_effect=capture), patch.object(proxy, 'query_ollama', side_effect=query):
response = proxy.complete(copy.deepcopy(request), True)
row['response'] = response
calls = response['choices'][0]['message'].get('tool_calls', [])
content = response['choices'][0]['message'].get('content')
row['response_kind'] = 'tool_call' if calls else ('text' if isinstance(content, str) and content.strip() else 'empty')
row['proposed_tool_calls'] = len(calls)
row['schema_valid'] = bool(calls) and all(proxy.adapter.convert(json.dumps({
'name': c['function']['name'], 'arguments': json.loads(c['function']['arguments'])}), request['tools']) for c in calls)
except Exception as exc:
row['error'] = type(exc).__name__ + ': ' + str(exc)[:300]
row.update(elapsed_seconds=time.monotonic() - start, upstream=upstream, compression=transforms)
results.append(row)
print(f"Repeat {index + 1}/{repeats}: {row['elapsed_seconds']:.2f}s; error={row.get('error', 'none')}", flush=True)
return results
def summarize(rows):
calls = [call for row in rows for call in row['upstream']]
def total(key):
values = [call.get(key) for call in calls]
return sum(values) if values and all(isinstance(v, int) for v in values) else None
reasons = {}
for call in calls:
reason = call.get('done_reason') or 'unknown'
reasons[reason] = reasons.get(reason, 0) + 1
return {'median_seconds': statistics.median(row['elapsed_seconds'] for row in rows),
'requests': len(calls), 'errors': sum('error' in row for row in rows),
'schema_valid_decisions': sum(row.get('schema_valid', False) for row in rows),
'empty_responses': sum(row.get('response_kind') == 'empty' or
(not row.get('error') and not row.get('response', {}).get('choices', [{}])[0].get('message', {}).get('tool_calls') and
not (row.get('response', {}).get('choices', [{}])[0].get('message', {}).get('content') or '').strip()) for row in rows),
'prompt_tokens_total': total('prompt_eval_count'), 'completion_tokens_total': total('eval_count'),
'ollama_total_seconds': total('total_duration') / 1e9 if total('total_duration') is not None else None,
'stop_reasons': reasons}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['install', 'baseline', 'compare'])
parser.add_argument('source', nargs='?')
parser.add_argument('repeats', nargs='?', type=int, default=3, choices=range(1, 6))
args = parser.parse_args()
venv = ROOT / 'headroom-venv'
if args.action == 'install':
ROOT.mkdir(parents=True, exist_ok=True)
subprocess.run([sys.executable, '-m', 'venv', str(venv)], check=True)
subprocess.run([str(venv / 'bin/python'), '-m', 'pip', 'install', f'headroom-ai=={VERSION}', 'jsonschema'], check=True)
return
if args.action == 'compare' and os.environ.get('JEANNIE_HEADROOM_VENV') != '1':
if not (venv / 'bin/python').is_file():
raise SystemExit('Run ./jeannie ai-lab headroom-install first')
env = dict(os.environ, JEANNIE_HEADROOM_VENV='1')
os.execve(str(venv / 'bin/python'), [str(venv / 'bin/python'), __file__, *sys.argv[1:]], env)
if not args.source:
parser.error('A conversation JSON (baseline) or baseline report JSON (compare) is required')
if args.action == 'compare' and len(sys.argv) != 3:
parser.error('compare reuses the baseline repeat count; no repeat override is accepted')
endpoint = urlsplit(os.environ.get('OLLAMA_API_BASE', 'http://127.0.0.1:11434'))
if endpoint.scheme != 'http' or endpoint.hostname not in ('127.0.0.1', 'localhost', '::1') or endpoint.username or endpoint.password:
raise ValueError('Context benchmarks require a local Ollama endpoint')
ROOT.mkdir(parents=True, exist_ok=True)
lock = (ROOT / 'doctor-context.lock').open('w')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
data = json.loads(Path(args.source).read_text())
request = request_from_conversation(data) if args.action == 'baseline' else data['request']
repeats = args.repeats if args.action == 'baseline' else data['repeats']
directory = ROOT / 'reports' / (datetime.now(timezone.utc).strftime('doctor-context-%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8])
directory.mkdir(parents=True, mode=0o700)
report = {'action': args.action, 'request': request, 'repeats': repeats,
'request_sha256': hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest(),
'proxy_sha256': hashlib.sha256(Path(__file__).with_name('ollama-tool-proxy.py').read_bytes()).hexdigest(),
'interpretation': 'Single recorded Holmes decision replay with a compatible Bash schema; no tools executed. Schema validity is not diagnostic correctness or repair success. Times include retries, compression and model loading. Warm prompt caches and stochastic sampling may affect comparisons. Existing native Doctor proxy does not forward temperature/seed fields.'}
if args.action == 'compare':
if data.get('action') != 'baseline':
raise ValueError('Compare requires an uncompressed baseline report')
if report['request_sha256'] != data['request_sha256']:
raise ValueError('Baseline request hash mismatch')
report.update(baseline_report=str(Path(args.source).resolve()), baseline_proxy_sha256=data['proxy_sha256'],
baseline_results=data['results'], headroom_version=importlib.metadata.version('headroom-ai'))
if report['headroom_version'] != VERSION:
raise ValueError('Unexpected Headroom version; rerun headroom-install')
try:
report['results'] = run(request, repeats, args.action == 'compare')
report['summary'] = summarize(report['results'])
print(json.dumps(report['summary'], indent=2), flush=True)
if args.action == 'compare':
report['baseline_summary'] = summarize(data['results'])
finally:
private_json(directory / 'report.json', report)
print('Private report: ' + str(directory / 'report.json'))
if any('error' in row for row in report['results']):
raise SystemExit(1)
if __name__ == '__main__':
main()