File size: 3,816 Bytes
09912bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""Reference solver client. It reads only a materialized public task workspace."""
import argparse
import ast
import json
import os
from pathlib import Path
import sys
import urllib.error
import urllib.request

from drb import load, require, sha, task, within

def call(payload,key):
    req=urllib.request.Request("https://api.commonstack.ai/v1/responses",
        data=json.dumps(payload).encode(),headers={"Content-Type":"application/json","Authorization":"Bearer "+key})
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self,*args):return None
    with urllib.request.build_opener(NoRedirect()).open(req,timeout=1800) as res:
        obj=json.load(res)
    require(obj.get("status")=="completed","Missing completed response")
    parts=[p["text"] for x in obj.get("output",[]) if x.get("type")=="message"
           for p in x.get("content",[]) if p.get("type")=="output_text"]
    require(parts,"No answer returned")
    return "".join(parts),obj.get("usage"),obj.get("id")

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("paper");parser.add_argument("--model",required=True);parser.add_argument("--out",type=Path,required=True)
    parser.add_argument("--max-calls",type=int,default=3);parser.add_argument("--output-tokens",type=int,default=8192)
    a=parser.parse_args(); d=task(a.paper);public=d/"workspace/input"; assets=load(d/"inputs/manifest.json")["assets"]
    paths={r["path"]:r for r in assets}
    require(0<a.max_calls<=12 and 0<a.output_tokens<=65536,"Invalid explicit call budget")
    key=os.environ["COMMONSTACK_API_KEY"]
    require(not a.out.exists(),"Choose a fresh independent output directory")
    a.out.mkdir(parents=True)
    state=[{"role":"user","content":json.dumps({"task":load(d/"task.json"),"files":list(paths)},ensure_ascii=False)}]
    system=("You are a computational research solver. Use the supplied task and public input inventory. "
      "Return a JSON object, either {\"action\":\"read\",\"path\":\"...\",\"offset\":0} to inspect UTF-8 text "
      "or {\"action\":\"submit\",\"source\":\"...\"} containing the complete Python program reproducing the task. "
      "The program must accept --input-dir and --output-dir. No access to private tests, author source or prior runs.")
    for n in range(a.max_calls):
        target=a.out/f"request-{n:02}.json"
        target.write_text(json.dumps({"model":a.model,"effort":"xhigh","state":"dispatched"}))
        text,usage,rid=call({"model":a.model,"instructions":system,"input":state,
            "reasoning":{"effort":"xhigh"},"max_output_tokens":a.output_tokens},key)
        (a.out/f"response-{n:02}.json").write_text(json.dumps({"response_id":rid,"usage":usage,"answer":text}))
        action=json.loads(text);state.append({"role":"assistant","content":text})
        if action.get("action")=="submit":
            source=action["source"];ast.parse(source);(a.out/"reproduce.py").write_text(source)
            print(a.out/"reproduce.py");return
        require(action.get("action")=="read" and action.get("path") in paths,"Invalid solver action")
        name=action["path"]; f=within(public,name);ref=paths[name]
        require(f.is_file() and sha(f)==ref["sha256"],"Provision exact public input first: "+name)
        offset=action.get("offset",0);require(type(offset) is int and offset>=0,"Invalid offset")
        with f.open("rb") as stream:
            stream.seek(offset);data=stream.read(8192)
        try: body=data.decode("utf-8")
        except UnicodeDecodeError:body="[binary; read programmatically at execution]"
        state.append({"role":"user","content":json.dumps({"file":name,"offset":offset,"content":body})})
    raise SystemExit("Solver budget exhausted without a submission")
if __name__=="__main__":main()