"""40 tareas x 5 intentos: ReAct m23-l13 y un agente de llamada única.

El segundo es un adaptador propio de esta lección, no una implementación de
la lección 14. Cada intento recibe un entorno nuevo y semilla documentada.
"""
import importlib.util,json,random,sys,time
from pathlib import Path
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
from transformers import AutoTokenizer

root=Path('agent-bench');root.mkdir(parents=True,exist_ok=True)
def load(name,path):
    spec=importlib.util.spec_from_file_location(name,path)
    module=importlib.util.module_from_spec(spec);sys.modules[name]=module;spec.loader.exec_module(module)
    return module
h=load('own_harness',Path('harness.py'))
engine=load('react_engine','react_engine.py')
model_path=hf_hub_download('Qwen/Qwen2.5-0.5B-Instruct-GGUF','qwen2.5-0.5b-instruct-q4_k_m.gguf',revision='9217f5db79a29953eb74d5343926648285ec7e67')
llm=Llama(model_path=model_path,n_ctx=4096,n_threads=4,verbose=False)
print('modelo GGUF cargado',flush=True)
tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775')
print('tokenizador cargado',flush=True)
def serialize(messages):return tok.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
def count(messages):return len(llm.tokenize(serialize(messages).encode('utf-8'),add_bos=True,special=True))
schema=('Tools: read receives a filename. write receives a JSON string with path and content. '
        'db receives a JSON string with op, id and amount. Example: '
        '{"action":"db","argument":"{\\"op\\":\\"add\\",\\"id\\":2,\\"amount\\":3}"}. '
        'For write, content must be a string. When finished use {"final":"done"}.\n')
def policy(messages,max_new):
    prompt=serialize(messages)
    print('inferencia',count(messages),'tokens de entrada, límite',max_new,flush=True)
    result=llm.create_completion(prompt=prompt,max_tokens=max_new,temperature=.7,top_p=.95)
    usage=result['usage']
    return engine.PolicyResponse(result['choices'][0]['text'].strip(),usage['prompt_tokens'],usage['completion_tokens'],prompt)
def agent(task,tools,variant,seed):
    llm.reset();llm.set_seed(seed)
    question=schema+task.instruction
    if variant=='react':
        return engine.run_agent(question,policy,tools,count,max_steps=6,max_total_tokens=5000,
                                max_context_tokens=2048,max_new_tokens=128,timeout_seconds=600)
    messages=[{'role':'system','content':'Return exactly one JSON object {"action":"tool name","argument":"text"}. You have one tool call only.'},
              {'role':'user','content':question}]
    response=policy(messages,128)
    try:
        action=engine.parse_action(response.text)
        if action['kind']!='action' or action['action'] not in tools:raise ValueError('invalid action')
        observation=tools[action['action']](action['argument']);error=None
    except Exception as exc:observation=None;error=type(exc).__name__
    return {'raw':response.text,'input_tokens':response.input_tokens,'output_tokens':response.output_tokens,
            'observation':observation,'error':error}

path=root/'agent_runs.json'
records=json.loads(path.read_text(encoding='utf-8')) if path.exists() else []
done={(r['task'],r['variant'],r['attempt']) for r in records}
for t in h.tasks():
    for variant in ('react','una_llamada'):
        for attempt in range(5):
            if (t.id,variant,attempt) in done:continue
            seed=270000+t.seed*10+attempt+(1000 if variant=='una_llamada' else 0)
            print('inicio',t.id,variant,attempt,flush=True)
            r=h.run(t,lambda task,tools:agent(task,tools,variant,seed))
            r.update(variant=variant,attempt=attempt,seed=seed)
            records.append(r);path.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf-8')
            print(t.id,variant,attempt,r['success'],r.get('adapter_error'),flush=True)
print('intentos guardados',len(records),flush=True)
