okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0b65d593c
main
1"""bench-local/strata_eval2.py - round 2: harder coding, JavaScript, SQL, regex, a tool-using agent loop on a small 2project, fact questions over a ~60K-token file, a long generation. Writes results2.json next to this file.""" 3from __future__import annotations 4 5import json 6import re 7import shutil 8import sqlite3 9import subprocess 10import sys 11import tempfile 12from pathlib import Path 13 14sys .path .insert (0 ,str (Path (__file__ ).parent )) 15import strata_eval as E # noqa: E402 16 17HERE = Path (__file__ ).parent 18OUT = {"hard" : [],"js" : [],"sql" : [],"regex" : [],"agent" : [],"qa" : [],"longgen" : []} 19ASK = "\n\nPython 3, standard library only. Reply with one ```python code block containing the complete solution." 20 21HARD = [ 22 ("topo_sort" ,"Write `topo_sort(edges)`: edges is a list of (a, b) string pairs meaning a must come before b. " 23"Return all nodes in a valid order; among valid orders return the lexicographically smallest one. Raise " 24"ValueError if there is a cycle." , 25"assert topo_sort([('b','c'),('a','c'),('c','d')]) == ['a','b','c','d']\n" 26"assert topo_sort([('x','a'),('b','a')]) == ['b','x','a']\nassert topo_sort([]) == []\n" 27"try:\n topo_sort([('a','b'),('b','a')]); raise AssertionError('cycle')\nexcept ValueError:\n pass\n" ), 28 ("wildcard_match" ,"Write `wildcard_match(s, p)`: '?' matches exactly one character, '*' matches any sequence " 29"(including empty); the whole string must match." , 30"T = [('aa','a',False),('aa','*',True),('cb','?a',False),('adceb','*a*b',True),('acdcb','a*c?b',False)," 31"('','*',True),('','?',False),('abc','a**c',True),('a'*30+'b','*'+'a*'*10+'c',False)]\n" 32"for s, p, w in T:\n assert wildcard_match(s, p) is w, (s, p)\n" ), 33 ("min_window" ,"Write `min_window(s, t)`: the shortest substring of s containing every character of t (with " 34"multiplicity); '' if none." , 35"assert min_window('ADOBECODEBANC','ABC') == 'BANC'\nassert min_window('a','a') == 'a'\n" 36"assert min_window('a','aa') == ''\nassert min_window('aab','aab') == 'aab'\n" ), 37 ("json_pointer" ,"Write `json_pointer(doc, pointer)` implementing RFC 6901 lookup: '' returns the whole document, " 38"'/a/0' descends into dicts and lists, '~1' decodes to '/', '~0' decodes to '~'. Raise KeyError for any path " 39"that does not exist (including a list index out of range)." , 40"d = {'foo': ['bar', 'baz'], '': 0, 'a/b': 1, 'm~n': 8, ' ': 7}\n" 41"assert json_pointer(d, '') == d and json_pointer(d, '/foo') == ['bar','baz'] and json_pointer(d, '/foo/0') == 'bar'\n" 42"assert json_pointer(d, '/') == 0 and json_pointer(d, '/a~1b') == 1 and json_pointer(d, '/m~0n') == 8\n" 43"assert json_pointer(d, '/ ') == 7\n" 44"for bad in ['/foo/5', '/nope', '/foo/x']:\n try:\n json_pointer(d, bad); raise AssertionError(bad)\n" 45" except KeyError:\n pass\n" ), 46 ("nqueens" ,"Write `nqueens(n)`: the number of ways to place n non-attacking queens on an n x n board." , 47"assert [nqueens(n) for n in (1, 4, 6, 8)] == [1, 2, 4, 92]\n" ), 48 ("semver_sort" ,"Write `semver_sort(versions)`: sorts semantic version strings ascending by the SemVer 2.0.0 " 49"precedence rules, including pre-release identifiers (no build metadata)." , 50"v = ['1.0.0','1.0.0-alpha','1.0.0-alpha.1','1.0.0-beta','1.0.0-rc.1','0.9.9','1.0.0-alpha.beta','1.0.0-beta.2'," 51"'1.0.0-beta.11','2.0.0']\n" 52"assert semver_sort(v) == ['0.9.9','1.0.0-alpha','1.0.0-alpha.1','1.0.0-alpha.beta','1.0.0-beta','1.0.0-beta.2'," 53"'1.0.0-beta.11','1.0.0-rc.1','1.0.0','2.0.0'], semver_sort(v)\n" ), 54 ("edit_distance" ,"Write `edit_distance(a, b)`: the Levenshtein distance." , 55"assert edit_distance('kitten','sitting') == 3 and edit_distance('','abc') == 3\n" 56"assert edit_distance('flaw','lawn') == 2 and edit_distance('intention','execution') == 5\n" ), 57 ("gather_limited" ,"Write `async def gather_limited(coro_fns, limit)`: coro_fns is a list of zero-argument " 58"callables that each return a coroutine. Run them with at most `limit` running at the same time and return their " 59"results in the input order." , 60"import asyncio\nasync def _t():\n running = 0; peak = 0\n async def job(i):\n nonlocal running, peak\n" 61" running += 1; peak = max(peak, running)\n await asyncio.sleep(0.01 * (5 - i % 5))\n" 62" running -= 1\n return i * i\n" 63" res = await gather_limited([lambda i=i: job(i) for i in range(12)], 3)\n" 64" assert res == [i * i for i in range(12)], res\n assert 2 <= peak <= 3, peak\nasyncio.run(_t())\n" ), 65 ("trie" ,"Write a class `Trie` with `insert(word)`, `search(word)` (exact word), `starts_with(prefix)` and " 66"`delete(word)`: delete removes the word and prunes nodes no other word uses; deleting a missing word does " 67"nothing." , 68"t = Trie(); t.insert('apple'); t.insert('app')\n" 69"assert t.search('app') and t.search('apple') and not t.search('appl') and t.starts_with('appl')\n" 70"t.delete('apple'); assert not t.search('apple') and t.search('app') and not t.starts_with('appl')\n" 71"t.delete('zzz'); t.delete('app'); assert not t.starts_with('a')\n" ), 72 ("bowling" ,"Write `bowling_score(rolls)`: the total score of a complete ten-pin bowling game given the list of " 73"pins knocked down per roll." , 74"assert bowling_score([10]*12) == 300 and bowling_score([9,1]*10+[9]) == 190 and bowling_score([0]*20) == 0\n" 75"assert bowling_score([3,4]*10) == 70\n" 76"assert bowling_score([10,7,3,9,0,10,0,8,8,2,0,6,10,10,10,8,1]) == 167\n" ), 77 ("palindrome" ,"Write `longest_palindrome(s)`: a longest palindromic substring of s." , 78"assert longest_palindrome('babad') in ('bab','aba') and longest_palindrome('cbbd') == 'bb'\n" 79"assert longest_palindrome('') == '' and longest_palindrome('a') == 'a'\n" 80"assert longest_palindrome('forgeeksskeegfor') == 'geeksskeeg'\n" ), 81 ("normpath" ,"Write `normalize(path)` for POSIX-style paths without using os.path or pathlib: collapse repeated " 82"slashes, resolve '.' and '..', drop a trailing slash. An absolute path never goes above '/'. A relative path " 83"keeps leading '..' parts it cannot resolve. An empty result is '.' for a relative path." , 84"T = {'/a/./b/../../c/': '/c', '/../': '/', '/home//foo/': '/home/foo', 'a/b/../c': 'a/c', '../a': '../a', " 85"'': '.', 'a/..': '.', 'a/../../b': '../b', '/': '/'}\n" 86"for k, w in T.items():\n assert normalize(k) == w, (k, normalize(k))\n" ), 87] 88 89 90def hard (): 91import os 92for effort in os .environ .get ("EFFORTS" ,"none,high" ).split ("," ): 93for name ,task ,tests in HARD : 94r = E .chat ([{"role" :"user" ,"content" :task + ASK }],effort ,12000 ) 95ok ,err = (False ,r ["error" ])if "error" in r else E .run_tests (E .extract_code (r ["content" ]),tests ) 96OUT ["hard" ].append ({"task" :name ,"effort" :effort ,"pass" :ok ,"err" :err , 97** {k :r .get (k )for k in ("wall" ,"out_tokens" ,"tok_s" ,"finish" )}}) 98f"hard { effort :5 } { name :15 } { 'PASS' if ok else 'FAIL' } { r . get ( 'wall' ) } s { r . get ( 'out_tokens' ) } tok { err } " ,flush = True ) 99 100 101JS = [ 102 ("groupBy" ,"Write `groupBy(arr, fn)`: returns an object mapping fn(item) to the array of items with that key, " 103"in input order." , 104"assert.deepStrictEqual(groupBy([1,2,3,4,5], x => x % 2 ? 'odd' : 'even'), {odd: [1,3,5], even: [2,4]});\n" 105"assert.deepStrictEqual(groupBy([], x => x), {});\n" ), 106 ("deepEqual" ,"Write `deepEqual(a, b)`: structural equality for primitives, arrays, plain objects and Date " 107"objects; NaN equals NaN; key order does not matter." , 108"assert.ok(deepEqual({a: [1, {b: NaN}], c: new Date(5)}, {c: new Date(5), a: [1, {b: NaN}]}));\n" 109"assert.ok(!deepEqual({a: 1}, {a: 1, b: undefined}));\nassert.ok(!deepEqual([1, 2], [1, 2, 3]));\n" 110"assert.ok(!deepEqual(new Date(1), new Date(2)));\nassert.ok(deepEqual(null, null) && !deepEqual(null, {}));\n" 111"assert.ok(!deepEqual([1], {0: 1}));\n" ), 112 ("parseQuery" ,"Write `parseQuery(str)`: parses a URL query string (an optional leading '?') into an object; " 113"values are percent-decoded and '+' means space; a key that repeats becomes an array of its values; a key " 114"without '=' gets ''." , 115"assert.deepStrictEqual(parseQuery('?a=1&b=2&a=3&c=%20x+y&d'), {a: ['1','3'], b: '2', c: ' x y', d: ''});\n" 116"assert.deepStrictEqual(parseQuery(''), {});\n" ), 117 ("chunk" ,"Write `chunk(arr, n)`: splits an array into arrays of length n (the last may be shorter); throws " 118"RangeError when n < 1." , 119"assert.deepStrictEqual(chunk([1,2,3,4,5], 2), [[1,2],[3,4],[5]]);\nassert.deepStrictEqual(chunk([], 3), []);\n" 120"assert.throws(() => chunk([1], 0), RangeError);\n" ), 121] 122 123 124def js (): 125node = shutil .which ("node" ) 126for name ,task ,tests in JS : 127r = E .chat ([{"role" :"user" ,"content" :task + "\n\nPlain JavaScript for Node.js, no modules or exports: " 128"define the function at the top level. Reply with one ```javascript code block." }],"none" ,4000 ) 129m = re .findall (r"```(?:javascript|js)?\s*\n(.*?)```" ,r .get ("content" ,"" ),re .S ) 130code = max (m ,key = len )if m else r .get ("content" ,"" ) 131with tempfile .NamedTemporaryFile ("w" ,suffix = ".js" ,delete = False ,encoding = "utf-8" )as f : 132f .write (code + "\nconst assert = require('assert');\n" + tests + "console.log('PASS');\n" ) 133p = subprocess .run ([node ,f .name ],capture_output = True ,text = True ,timeout = 20 ) 134ok = "PASS" in p .stdout 135OUT ["js" ].append ({"task" :name ,"pass" :ok ,"err" : (p .stderr .strip ().splitlines ()or ["" ])[0 ][:160 ],"wall" :r .get ("wall" )}) 136f"js { name :11 } { 'PASS' if ok else 'FAIL' } { r . get ( 'wall' ) } s" ,flush = True ) 137Path (f .name ).unlink (missing_ok = True ) 138 139 140SCHEMA = """CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT); 141CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, amount REAL, created TEXT); 142INSERT INTO customers VALUES (1,'Ann'),(2,'Bob'),(3,'Cid'),(4,'Dee'); 143INSERT INTO orders VALUES (1,1,50,'2026-01-01'),(2,1,70,'2026-02-01'),(3,2,200,'2026-01-15'),(4,3,20,'2026-03-01'), 144(5,3,30,'2026-01-20');""" 145SQL = [ 146 ("Names of customers who have no orders, sorted by name. One column." , [("Dee" ,)]), 147 ("The two customers with the highest total order amount: name and total, highest first." , 148 [("Bob" ,200.0 ), ("Ann" ,120.0 )]), 149 ("For each customer who has orders: name and the amount of their most recent order (by created), sorted by name." , 150 [("Ann" ,70.0 ), ("Bob" ,200.0 ), ("Cid" ,20.0 )]), 151] 152 153 154def sql (): 155for q ,want in SQL : 156r = E .chat ([{"role" :"user" ,"content" :"SQLite schema:\n" + SCHEMA .split ("INSERT" )[0 ]+ "\n" + q + 157"\nReply with one ```sql code block holding a single SELECT statement." }],"none" ,1500 ) 158m = re .findall (r"```(?:sql)?\s*\n(.*?)```" ,r .get ("content" ,"" ),re .S ) 159stmt = (m [- 1 ]if m else r .get ("content" ,"" )).strip () 160db = sqlite3 .connect (":memory:" ) 161db .executescript (SCHEMA ) 162try : 163got = [tuple (float (x )if isinstance (x , (int ,float ))else x for x in row )for row in db .execute (stmt )] 164ok ,err = got == want ,"" 165except sqlite3 .Error as e : 166got ,ok ,err = None ,False ,str (e )[:120 ] 167OUT ["sql" ].append ({"q" :q [:60 ],"pass" :ok ,"got" :got ,"err" :err }) 168f"sql { 'PASS' if ok else 'FAIL' } { q [: 50 ]!r } { got } { err } " ,flush = True ) 169 170 171REGEX = [ 172 ("an IPv4 address in dotted decimal, each part 0-255 (no leading zeros except '0' itself)" , 173 ["0.0.0.0" ,"255.255.255.255" ,"192.168.1.1" ,"10.0.0.1" ], 174 ["256.1.1.1" ,"1.1.1" ,"1.1.1.1.1" ,"a.b.c.d" ,"1.1.1." ,"999.0.0.1" ,"01.1.1.1" ]), 175 ("a CSS hex color: '#' followed by exactly 3 or exactly 6 hex digits" , 176 ["#fff" ,"#FFFFFF" ,"#a1B2c3" ], ["fff" ,"#ffff" ,"#ggg" ,"#12345" ,"#1234567" ]), 177 ("a date YYYY-MM-DD with month 01-12 and day 01-31 (no per-month day check)" , 178 ["2026-10-03" ,"1999-01-31" ,"2000-12-01" ], 179 ["2026-13-01" ,"2026-00-10" ,"2026-10-32" ,"2026-1-1" ,"26-10-03" ,"2026-10-00" ]), 180] 181 182 183def regex (): 184for what ,good ,bad in REGEX : 185r = E .chat ([{"role" :"user" ,"content" :f"Give a Python regular expression for re.fullmatch that matches { what } . " 186"Reply with only the pattern on one line inside single backticks." }],"none" ,800 ) 187m = re .findall (r"`([^`\n]+)`" ,r .get ("content" ,"" )) 188pat = m [- 1 ]if m else r .get ("content" ,"" ).strip () 189try : 190ok = all (re .fullmatch (pat ,g )for g in good )and not any (re .fullmatch (pat ,b )for b in bad ) 191except re .error : 192ok = False 193OUT ["regex" ].append ({"what" :what [:40 ],"pass" :ok ,"pattern" :pat }) 194f"regex { 'PASS' if ok else 'FAIL' } { what [: 35 ]!r } { pat } " ,flush = True ) 195 196 197# ------------------------------------------------------------------------------------------------ agent loop 198PRICING_BUG = '''def discount(total): 199"""10% off for totals of 100 or more, 20% off for 500 or more.""" 200if total > 500: 201return total * 0.2 202if total > 100: 203return total * 0.1 204return 0.0 205 206 207def tax(amount, rate=0.2): 208return round(amount * rate, 2) 209''' 210CART = '''from pricing import discount, tax 211 212 213class Cart: 214def __init__(self): 215self.items = [] 216 217def add(self, name, price, qty=1): 218self.items.append((name, price, qty)) 219 220def subtotal(self): 221return sum(%s for _, price, qty in self.items) 222 223def total(self): 224sub = self.subtotal() 225net = sub - discount(sub) 226return round(net + tax(net), 2) 227''' 228TESTS = '''import unittest 229from cart import Cart 230 231 232class T(unittest.TestCase): 233def test_qty(self): 234c = Cart(); c.add('pen', 2.5, 4); self.assertEqual(c.subtotal(), 10.0) 235 236def test_no_discount(self): 237c = Cart(); c.add('book', 50); self.assertEqual(c.total(), 60.0) 238 239def test_discount_at_100(self): 240c = Cart(); c.add('lamp', 100); self.assertEqual(c.total(), 108.0) 241 242def test_discount_at_500(self): 243c = Cart(); c.add('tv', 250, 2); self.assertEqual(c.total(), 480.0) 244 245 246if __name__ == '__main__': 247unittest.main() 248''' 249HIDDEN_B = '''from cart import Cart 250import coupons 251c = Cart(); c.add('a', 10); c.add('b', 5); c.add('a', 1); assert c.remove('a') == 2 and c.subtotal() == 5 252c = Cart(); c.add('book', 50); c.apply_coupon('SAVE5'); assert c.total() == 54.0, c.total() 253c.apply_coupon('SAVE20'); assert c.total() == 36.0, c.total() 254try: 255c.apply_coupon('NOPE'); raise AssertionError('unknown code') 256except ValueError: 257pass 258c = Cart(); c.add('x', 3); c.apply_coupon('SAVE20'); assert c.total() == 0.0 259assert coupons.COUPONS['SAVE5'] == 5.0 260print('PASS') 261''' 262AGENT_TOOLS = [ 263 {"type" :"function" ,"function" : {"name" :"list_files" ,"description" :"List the project's files." , 264"parameters" : {"type" :"object" ,"properties" : {}}}}, 265 {"type" :"function" ,"function" : {"name" :"read_file" ,"description" :"Read a project file." , 266"parameters" : {"type" :"object" ,"properties" : {"path" : {"type" :"string" }},"required" : ["path" ]}}}, 267 {"type" :"function" ,"function" : {"name" :"write_file" ,"description" :"Write (replace) a project file." , 268"parameters" : {"type" :"object" ,"properties" : {"path" : {"type" :"string" },"content" : {"type" :"string" }}, 269"required" : ["path" ,"content" ]}}}, 270 {"type" :"function" ,"function" : {"name" :"run_tests" ,"description" :"Run the project's unit tests." , 271"parameters" : {"type" :"object" ,"properties" : {}}}}, 272] 273 274 275def run_py (root ,args ): 276p = subprocess .run ([sys .executable ,* args ],cwd = root ,capture_output = True ,text = True ,timeout = 30 ) 277return p .returncode , (p .stdout + p .stderr )[- 1500 :] 278 279 280def agent_run (label ,files ,task ,effort ,check ): 281root = Path (tempfile .mkdtemp (prefix = "strata-agent-" )) 282for n ,c in files .items (): 283 (root / n ).write_text (c ,encoding = "utf-8" ) 284msgs = [{"role" :"system" ,"content" :"You are a coding agent working in a small Python project. Use the tools " 285"to inspect and change files and to run the tests. When the task is done, reply with DONE." }, 286 {"role" :"user" ,"content" :task }] 287steps = calls = 0 288total_wall = 0.0 289for steps in range (1 ,26 ): 290r = E .chat (msgs ,effort ,6000 ,tools = AGENT_TOOLS ) 291total_wall += r .get ("wall" ,0 ) 292if "error" in r : 293break 294tc = r .get ("tool_calls" )or [] 295msgs .append ({"role" :"assistant" ,"content" :r ["content" ],** ({"tool_calls" :tc }if tc else {})}) 296if not tc : 297break 298for c in tc : 299calls += 1 300try : 301a = json .loads (c ["function" ]["arguments" ]or "{}" ) 302except ValueError : 303a = None 304name = c ["function" ]["name" ] 305if a is None : 306res = "error: arguments are not valid JSON" 307elif name == "list_files" : 308res = "\n" .join (sorted (p .name for p in root .iterdir ()if p .is_file ())) 309elif name in ("read_file" ,"write_file" ): 310p = (root / str (a .get ("path" ,"" ))).resolve () 311if root .resolve ()not in p .parents : 312res = "error: path outside the project" 313elif name == "read_file" : 314res = p .read_text (encoding = "utf-8" )if p .exists ()else "error: no such file" 315else : 316p .write_text (str (a .get ("content" ,"" )),encoding = "utf-8" ) 317res = "written" 318elif name == "run_tests" : 319res = run_py (root , ["-m" ,"unittest" ,"-q" ])[1 ] 320else : 321res = "error: unknown tool" 322msgs .append ({"role" :"tool" ,"tool_call_id" :c .get ("id" ,"call" ),"content" :res }) 323ok ,note = check (root ) 324shutil .rmtree (root ,ignore_errors = True ) 325OUT ["agent" ].append ({"scenario" :label ,"effort" :effort ,"pass" :ok ,"note" :note ,"turns" :steps , 326"tool_calls" :calls ,"wall" :round (total_wall ,1 )}) 327f"agent { label :8 } { effort :6 } { 'PASS' if ok else 'FAIL' } { steps } turns, { calls } tool calls, { total_wall :.0f } s { note } " ,flush = True ) 328 329 330def agent (): 331def check_a (root ): 332rc ,out = run_py (root , ["-m" ,"unittest" ,"-q" ]) 333same = (root / "test_cart.py" ).read_text (encoding = "utf-8" )== TESTS 334return rc == 0 and same , ("" if rc == 0 else out .strip ().splitlines ()[- 1 ][:120 ])+ ("" if same else " tests modified" ) 335 336def check_b (root ): 337 (root / "_hidden.py" ).write_text (HIDDEN_B ,encoding = "utf-8" ) 338rc1 ,out1 = run_py (root , ["_hidden.py" ]) 339rc2 ,out2 = run_py (root , ["-m" ,"unittest" ,"-q" ]) 340added = (root / "test_cart.py" ).read_text (encoding = "utf-8" ).count ("def test_" )> 4 341note = ("" if rc1 == 0 else "hidden: " + out1 .strip ().splitlines ()[- 1 ][:100 ])+ \ 342 ("" if rc2 == 0 else " own tests fail" )+ ("" if added else " no tests added" ) 343return rc1 == 0 and rc2 == 0 and added ,note 344 345bug = {"pricing.py" :PRICING_BUG ,"cart.py" :CART % "price" ,"test_cart.py" :TESTS } 346good = {"pricing.py" :PRICING_BUG .replace ("> 500" ,">= 500" ).replace ("> 100" ,">= 100" ), 347"cart.py" :CART % "price * qty" ,"test_cart.py" :TESTS } 348feat = ("Add two things to Cart. 1) `remove(name)`: removes every line with that name and returns how many lines " 349"were removed. 2) `apply_coupon(code)`: coupon codes live in a new module coupons.py as " 350"COUPONS = {'SAVE5': 5.0, 'SAVE20': 20.0}; a valid coupon subtracts its value from the net amount (after " 351"the discount, before tax), never below 0; an unknown code raises ValueError; only one coupon applies, " 352"the latest one. Add tests for both to test_cart.py and make all tests pass." ) 353for effort in ("none" ,"medium" ): 354agent_run ("bugfix" ,bug ,"The unit tests fail. Find and fix the bugs in the code. Do not change the tests." , 355effort ,check_a ) 356agent_run ("feature" ,good ,feat ,effort ,check_b ) 357 358 359# ------------------------------------------------------------------------------------------------ long-file QA 360def qa (): 361src = (HERE .parent / "setup.py" ).read_text (encoding = "utf-8" ) 362msgs = [{"role" :"user" ,"content" :"Here is a Python file, setup.py:\n\n" + src + 363"\n\nI will ask short questions about it. Answer each in one short line. First: what is the value of " 364"the constant DESKTOP_RESERVE_MIB?" }] 365qs = [(None ,"3072" ), 366 ("What is the default value of ROCM_VERSION (when the environment variable is not set)?" ,"7.10.0a20251120" ), 367 ("What is the value of WIN_HIP_ASSET?" ,"strata-windows-x64-hip.zip" ), 368 ("What is the name of the function that compiles the CPU image encoder beside the HIP engine?" ,"build_vision_cpu" ), 369 ("What is the value of the MMPROJ constant?" ,"mmproj-Qwen3.8-Flash-Next-BF16.gguf" ), 370 ("Is there a function named install_vulkan_sdk in the file? Answer yes or no." ,"no" )] 371for q ,want in qs : 372if q : 373msgs .append ({"role" :"user" ,"content" :q }) 374r = E .chat (msgs ,"none" ,300 ) 375a = r .get ("content" ,r .get ("error" ,"" )) 376msgs .append ({"role" :"assistant" ,"content" :a }) 377ok = want .lower ()in a .lower ()and not (want == "no" and "yes" in a .lower ()) 378OUT ["qa" ].append ({"want" :want ,"got" :a [:160 ],"pass" :ok ,** {k :r .get (k )for k in ("prompt_n" ,"cache_n" , 379"prompt_s" ,"tok_s" )}}) 380f"qa { 'PASS' if ok else 'FAIL' } read { r . get ( 'prompt_n' ) } tok in { r . get ( 'prompt_s' ) } s (reused " 381f" { r . get ( 'cache_n' ) } ), { r . get ( 'tok_s' ) } tok/s | want { want !r } got { a [: 90 ]!r } " ,flush = True ) 382 383 384def longgen (): 385r = E .chat ([{"role" :"user" ,"content" :"Write a complete single-file Python command-line todo app, todo.py, " 386"using argparse and a todo.json file in the current directory. Commands: `add <text>`, `list`, " 387"`done <id>`, `remove <id>`, `clear-done`, `stats`. Ids are stable integers. `list` prints one line " 388"per item with its id, a [x] or [ ] mark and the text, and supports `--all` / `--pending` / `--done` " 389"filters. Handle a missing or corrupt todo.json. Include docstrings and type hints. Reply with one " 390"```python code block." }],"none" ,8000 ) 391root = Path (tempfile .mkdtemp (prefix = "strata-todo-" )) 392 (root / "todo.py" ).write_text (E .extract_code (r .get ("content" ,"" )),encoding = "utf-8" ) 393rc1 ,_ = run_py (root , ["todo.py" ,"add" ,"buy milk" ]) 394rc2 ,_ = run_py (root , ["todo.py" ,"add" ,"write report" ]) 395rc3 ,_ = run_py (root , ["todo.py" ,"done" ,"1" ]) 396rc4 ,out = run_py (root , ["todo.py" ,"list" ,"--all" ]) 397ok = rc1 == rc2 == rc3 == rc4 == 0 and "buy milk" in out and "write report" in out and "[x]" in out and "[ ]" in out 398shutil .rmtree (root ,ignore_errors = True ) 399OUT ["longgen" ].append ({"pass" :ok ,** {k :r .get (k )for k in ("wall" ,"out_tokens" ,"tok_s" ,"finish" )},"list" :out [:200 ]}) 400f"longgen { 'PASS' if ok else 'FAIL' } { r . get ( 'out_tokens' ) } tok in { r . get ( 'wall' ) } s ( { r . get ( 'tok_s' ) } tok/s) | { out [: 120 ]!r } " ,flush = True ) 401 402 403if __name__ == "__main__" : 404funcs = {"hard" :hard ,"js" :js ,"sql" :sql ,"regex" :regex ,"agent" :agent ,"qa" :qa ,"longgen" :longgen } 405for name in sys .argv [1 :]or ["js" ,"sql" ,"regex" ,"longgen" ,"agent" ,"qa" ,"hard" ]: 406try : 407funcs [name ]() 408except Exception as e :# one broken section must not lose the others 409f" { name } CRASHED { type ( e ). __name__ } : { e } " ,flush = True ) 410# RESULTS2: another file name, so that a run for another model or engine keeps the earlier results 411 (HERE / __import__ ("os" ).environ .get ("RESULTS2" ,"results2.json" )).write_text ( 412json .dumps (OUT ,ensure_ascii = False ,indent = 1 ),encoding = "utf-8" ) 413"DONE" ,flush = True )