"""Compact op schemas for Needle's context window. Import `tool_entry(op)` / `count_tokens(text)`; run as a script for the budget report.""" import json,os,re,sys,glob ROOT=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOK_PATH=glob.glob(os.path.expanduser('~/.cache/huggingface/hub/models--Cactus-Compute--needle3/snapshots/*/tokenizer/tokenizer.model'))[0] _sp=None def count_tokens(text): global _sp if _sp is None: import sentencepiece as spm _sp=spm.SentencePieceProcessor(); _sp.Load(TOK_PATH) return len(_sp.Encode(text)) # B1 shipped with DESC_DEPTH=1, which (because compact() starts at depth 1) silently dropped EVERY property description. v2 (default) keeps them. DESC_DEPTH=1 if os.environ.get('COMPACT_V')=='1' else 2 TOP_DESC=200; PROP_DESC=70; MAX_DEPTH=2; MAX_NESTED_PROPS=14; MAX_ENUM=16 BOILER={'clip':'Clip UUID','track':'Track index','index':'Clip index on its track'} def cut(s,n): s=re.sub(r'\s+',' ',s or '').strip() if s.startswith('When: '): s=s[6:] if len(s)<=n: return s t=s[:n]; k=max(t.rfind('. '),t.rfind('; '),t.rfind(', '),t.rfind(' ')) return (t[:k] if k>n//2 else t).rstrip(' ,;.') def compact(s,depth=0,name=None): if not isinstance(s,dict): return s out={} t=s.get('type') if t: out['type']=t if 'enum' in s: out['enum']=s['enum'][:MAX_ENUM] for k in ('minimum','maximum'): if k in s: out[k]=s[k] d=s.get('description') if depth==DESC_DEPTH and name in BOILER and d and d.startswith(('Clip UUID','Clip index','Track index')): out['description']=BOILER[name] elif d and depth<=DESC_DEPTH: out['description']=cut(d,PROP_DESC) if t=='array' and 'items' in s: out['items']=compact(s['items'],depth+1) if depth=MAX_DEPTH+1: return {'type':'object'} props=s['properties']; req=s.get('required',[]) keys=list(props) if depth>=2 and len(keys)>MAX_NESTED_PROPS: keys=sorted(keys,key=lambda k:(k not in req))[:MAX_NESTED_PROPS] out['properties']={k:compact(props[k],depth+1,k) for k in keys} if req: out['required']=[r for r in req if r in out['properties']] return out def tool_entry(op,full=False): params=op['schema'] if full else compact(op['schema'],1) params.setdefault('type','object') desc=op['description'] if full else cut(op['description'],TOP_DESC) return {'name':op['name'],'description':desc,'parameters':params} def js(x): return json.dumps(x,separators=(',',':'),ensure_ascii=False) if __name__=='__main__': import statistics ops=json.load(open(os.path.join(ROOT,'data/ops.json'))) full=[count_tokens(js(tool_entry(o,True))) for o in ops] comp=[count_tokens(js(tool_entry(o))) for o in ops] def dist(a): a=sorted(a);q=lambda p:a[min(len(a)-1,int(p*len(a)))] return dict(mean=round(statistics.mean(a)),median=q(.5),p90=q(.9),p99=q(.99),max=a[-1],total=sum(a)) print('full ',dist(full));print('compact',dist(comp)) print('ops >2000 tok full:',sum(x>2000 for x in full),' compact:',sum(x>2000 for x in comp)) big=sorted(zip(comp,[o['name'] for o in ops]),reverse=True)[:8];print('largest compact',big) rk=json.load(open(os.path.join(ROOT,'data/rankings.json')))['BM25 + synonyms'] idx={o['name']:i for i,o in enumerate(ops)} for k in (10,20): tot=[sum(comp[idx[n]] for n in r[:k]) for r in rk]; totf=[sum(full[idx[n]] for n in r[:k]) for r in rk] print(f'k={k}: tools-block tokens compact mean {round(statistics.mean(tot))} max {max(tot)}; >8192: {sum(x>8192 for x in tot)}/{len(tot)}; >4096: {sum(x>4096 for x in tot)}; full mean {round(statistics.mean(totf))} >8192: {sum(x>8192 for x in totf)}') print('ops with compact schema <=1000 tok:',sum(x<=1000 for x in comp),'/',len(comp))