Download scripts/test_agentloop_env.py from Arko007/zenyx-agentic-loops: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/datasets/Arko007/zenyx-agentic-loops/resolve/main/scripts/test_agentloop_env.py
- Command line
-
hf download hf://datasets/Arko007/zenyx-agentic-loops/scripts/test_agentloop_env.py
-
curl -L -o test_agentloop_env.py https://huggingface.co/datasets/Arko007/zenyx-agentic-loops/resolve/main/scripts/test_agentloop_env.py
13.5 kB
| #!/usr/bin/env python3 | |
| """Offline test of tests/colab/agentloop_env.py: a scripted ORACLE agent must be accepted on every task kind (thousands of random tasks), and scripted BAD agents must be rejected.""" | |
| import json, os, random, re, sys, collections | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "colab")); sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| import agentloop_env as E | |
| from zenyx100m import chat | |
| def C(name, **a): return "<tool_call>" + json.dumps([{"name": name, "arguments": a}], ensure_ascii=False) + "</tool_call>" | |
| def tools_out(tr): return [m["content"] for m in tr if m["role"] == "tool"] | |
| def n_user(tr): return sum(m["role"] == "user" for m in tr) | |
| def oracle(task, bad=None): | |
| k, w, i, user = task.kind, task.world, task.info, task.user | |
| def gen(system, tools, tr): | |
| nt, nu, last = len(tools_out(tr)), n_user(tr), tr[-1] | |
| lt = tools_out(tr)[-1] if nt else "" | |
| if k == "weather": | |
| if last["role"] == "user" and nu == 2: | |
| t = int(re.search(r"(-?\d+)°C", tools_out(tr)[0]).group(1)); return "Yes." if t > i["thr"] else "No." | |
| if nt == 0: return C("get_weather", city=i["city"]) | |
| return "It is " + lt.split(": ", 1)[1].replace("°C", " degrees Celsius") + "." if bad != "fab" else "It is 99999 degrees." | |
| if k == "time": | |
| if nt == 0: return C("get_time", timezone=i["tz"]) | |
| return "The time there is " + lt.split(": ", 1)[1] + "." | |
| if k == "calc": | |
| if nt == 0: return C("calculator", expression=i["expr"]) | |
| return f"That comes to {lt}." if bad != "fab" else "That comes to 123456." | |
| if k == "convert": | |
| if nt == 0: return C("convert_units", value=i["v"], from_unit=i["f"], to_unit=i["t"]) | |
| return f"It is {lt.split('= ')[1]}." | |
| if k == "read_note": | |
| topic = next(t for t in E.TOPICS if t in user); fn = next(f for f in w.fs if f.startswith(topic + ".")) | |
| return C("read_file", path=fn) if nt == 0 else f"Your note says: {lt}" | |
| if k == "error_recovery": | |
| v = i["variant"] | |
| if v == "wrong_name": | |
| wrong = re.search(r"(\w+\.(?:txt|md))", user).group(1); topic = wrong.split(".")[0]; fn = next(f for f in w.fs if f.startswith(topic + ".")) | |
| return [C("read_file", path=wrong), C("list_dir", path="."), C("read_file", path=fn)][nt] if nt < 3 else f"The file says: {lt}" | |
| if v == "transient": | |
| city = next(c for c in E.CITIES if c.lower() in user.lower()); return C("get_weather", city=city) if nt < 2 else "It is " + lt.split(": ")[1].split(",")[0] + "." | |
| fn = re.search(r"(\w+\.(?:txt|md))", user).group(1); return C("read_file", path=fn) if nt == 0 else f"Sorry, I couldn't read {fn}: permission denied." | |
| if k == "empty_result": | |
| oid = re.search(r"\d{5}", user) | |
| if oid: return C("lookup_order", order_id=oid.group(0)) if nt == 0 else "I couldn't find that order, it was not found." | |
| return C("list_dir", path=".") if nt == 0 else "Your folder is empty, so there is no such note." | |
| if k == "ask_then_act": | |
| v = i["variant"] | |
| if v == "control_no_question": | |
| city = next(c for c in E.CITIES if c in user); return C("get_weather", city=city) if nt == 0 else "It is " + lt.split(": ")[1].split("°")[0] + " degrees." | |
| if nu == 1: return {"city": "Which city do you mean?", "recipient": "Who should I send it to?", "time": "What time should I set it for?"}[v] | |
| if v == "city": | |
| city = next(c for c in E.CITIES if c in tr[-1]["content"] or nt) if nt == 0 else None | |
| return C("get_weather", city=next(c for c in E.CITIES if c in tr[-2 if nt == 0 else 0]["content"] or c in " ".join(m["content"] for m in tr if m["role"] == "user"))) if nt == 0 else "It is " + lt.split(": ")[1].split("°")[0] + " degrees." | |
| ru = [m["content"] for m in tr if m["role"] == "user"][1] | |
| if v == "recipient": | |
| to = re.search(r"\S+@\S+", ru).group(0); return C("send_email", to=to, subject="Update", body="As discussed.") if nt == 0 else f"Done, the email was sent to {to}." | |
| tm = re.search(r"\d\d:\d\d", ru).group(0); day = re.search(r"(Monday|Tuesday|Wednesday|Thursday|Friday)", user).group(1) | |
| return C("create_event", title="Event", date=day, time=tm) if nt == 0 else f"Added it for {day} at {tm}." | |
| if k == "confirm_destructive": | |
| fn = re.search(r"(\w+\.(?:txt|md))", user).group(1) | |
| if bad == "nocheck": return C("delete_file", path=fn) if nt == 0 else f"Deleted {fn}." | |
| if nu == 1: return f"Are you sure you want me to delete {fn}?" | |
| if task.info["confirmed"]: return C("delete_file", path=fn) if nt == 0 else f"Done, {fn} is deleted." | |
| return f"Okay, I'll keep {fn}." | |
| if k == "async_job": | |
| if nt == 0: return C("start_job", task=i["what"]) | |
| jid = re.search(r"job-\d+", tools_out(tr)[0]).group(0) | |
| if "done." in lt: return f"The job finished: {lt.split('Result: ')[1]}" | |
| return C("check_job", job_id=jid) | |
| if k == "no_tool_needed": return f"Hi, I'm Nini! I can use {', '.join(t['function']['name'] for t in task.tools)} when you need them." | |
| if k == "tool_unavailable": return "Sorry, I can't do that with the tools I have." | |
| if k == "multi_call": | |
| cs = [c for c in E.CITIES if c in user] | |
| if nt == 0: return "<tool_call>" + json.dumps([{"name": "get_weather", "arguments": {"city": c}} for c in cs]) + "</tool_call>" | |
| return " and ".join(f"{c}: {o.split(': ')[1].split('°')[0]} degrees" for c, o in zip(cs, tools_out(tr))) | |
| if k == "dependent_calls": | |
| oid = re.search(r"\d{5}", user).group(0) | |
| if nt == 0: return C("lookup_order", order_id=oid) | |
| if nt == 1: return C("get_customer", customer_id=re.search(r"cust-\d+", lt).group(0)) | |
| m = re.search(r"Customer .*?: (\w+), email (\S+), city (\w+)", lt) | |
| return f"The customer is {m.group(1)}, email {m.group(2)}, in {m.group(3)}." | |
| if k == "write_note": | |
| return C("write_file", path=i["fn"], content=i["text"]) if nt == 0 else f"Saved your note to {i['fn']}." | |
| raise AssertionError(k) | |
| return gen | |
| def run(n, seed, bad=None): | |
| rng = random.Random(seed); stat = collections.Counter(); rej = collections.Counter(); sample = {} | |
| for j in range(n): | |
| t = E.make_task(rng); tr, reason = E.rollout(t, oracle(t, bad)); stat[t.kind] += 1 | |
| if reason: rej[(t.kind, reason)] += 1 | |
| else: | |
| row = E.to_row(t, tr, "oracle", j); sample.setdefault(t.kind, row) | |
| txt, _ = chat.render(row["messages"], json.loads(row["tools"])); assert txt.count("<|im_start|>") >= 2 and len(txt) < 6000 | |
| return stat, rej, sample | |
| if __name__ == "__main__": | |
| stat, rej, sample = run(6000, 1) | |
| print("kinds", dict(stat)); print("ORACLE rejections:", dict(rej)) | |
| assert not rej, "oracle must be accepted everywhere" | |
| # bad agents must be rejected | |
| for bad, kinds in (("fab", {"weather", "calc"}), ("nocheck", {"confirm_destructive"})): | |
| s2, r2, ok = run(3000, 2, bad) | |
| for k in kinds: | |
| assert s2[k] > 0 and sum(v for (kk, _), v in r2.items() if kk == k) == s2[k], (bad, k, s2[k], dict(r2)) | |
| print("bad agent", bad, "rejected on", sorted(kinds), "- all", {k: s2[k] for k in kinds}) | |
| # more negatives built by hand | |
| rng = random.Random(5) | |
| def force(kind, tries=400): | |
| for _ in range(tries): | |
| t = E.make_task(rng) | |
| if t.kind == kind: return t | |
| t = force("ask_then_act") | |
| while t.info["variant"] == "control_no_question": t = force("ask_then_act") | |
| tr, r = E.rollout(t, lambda s, tl, h: C({"city": "get_weather", "recipient": "send_email", "time": "create_event"}[t.info["variant"]], **({"city": "Pune"} if t.info["variant"] == "city" else {"to": "a@b.com", "subject": "s", "body": "b"} if t.info["variant"] == "recipient" else {"title": "x", "date": "Monday", "time": "10:00"})) if len(E.World.__dict__) and not any(m["role"] == "tool" for m in h) else "All done.") | |
| assert r, "agent that never asks must be rejected"; print("never-asks rejected:", r) | |
| t = force("async_job"); tr, r = E.rollout(t, lambda s, tl, h: C("start_job", task="x") if not any(m["role"] == "tool" for m in h) else "It finished with 5000 items processed.") | |
| assert r; print("claims result without polling rejected:", r) | |
| t = force("no_tool_needed"); tr, r = E.rollout(t, lambda s, tl, h: C("calculator", expression="1+1") if not any(m["role"] == "tool" for m in h) else "2"); assert r; print("tool for small talk rejected:", r) | |
| t = force("tool_unavailable"); tr, r = E.rollout(t, lambda s, tl, h: "Sure, it is booked <think>x</think>"); assert r; print("unavailable-claim rejected:", r) | |
| t = force("calc"); tr, r = E.rollout(t, lambda s, tl, h: "Text before <tool_call>[{\"name\":\"calculator\",\"arguments\":{\"expression\":\"1+1\"}}]</tool_call>"); assert r; print("text+call rejected:", r) | |
| # the model's NATIVE tool-call syntax must be accepted and stored in our JSON-list format | |
| def native(gen): | |
| def g(system, tools, tr): | |
| out = gen(system, tools, tr) | |
| m = re.fullmatch(r"<tool_call>(\[.*\])</tool_call>", out, re.S) | |
| if not m: return out | |
| return "\n".join(f"<tool_call>{c['name']}" + "".join(f"<arg_key>{k}</arg_key><arg_value>{v}</arg_value>" for k, v in c["arguments"].items()) + "</tool_call>" for c in json.loads(m.group(1))) | |
| return g | |
| rng = random.Random(9); ok = collections.Counter() | |
| for j in range(3000): | |
| t = E.make_task(rng); tr, r = E.rollout(t, native(oracle(t))); assert r is None, (t.kind, r, tr[:4]) | |
| for m in tr: | |
| if m["role"] == "assistant" and "<tool_call>" in m["content"]: assert E.TOOL_RX.match(m["content"]) and m["content"].startswith("<tool_call>["), m["content"]; ok["canonical"] += 1 | |
| print("native-format agent accepted on 3000 tasks; calls stored canonically:", ok["canonical"]) | |
| t = force("weather"); tr, r = E.rollout(t, lambda s, tl, h: "Sure \U0001F600" if any(m["role"] == "tool" for m in h) else "<tool_call>get_weather<arg_key>city</arg_key><arg_value>" + t.info["city"] + "</arg_value></tool_call>"); assert r is None or "tool" in r or "numbers" in r or "misses" in r, r # emojis are allowed now | |
| # a call whose closing tag was swallowed by the server is repaired and stored canonically | |
| t = force("async_job"); state = {"n": 0} | |
| def nocl(s_, tl, h): | |
| if not any(m["role"] == "tool" for m in h): return '<tool_call>[{"name": "start_job", "arguments": {"task": "x"}}]' | |
| last = [m for m in h if m["role"] == "tool"][-1]["content"] | |
| if "done." in last: return "It finished: " + t.world.jobs[next(iter(t.world.jobs))]["result"] + "." | |
| return '<tool_call>[{"name": "check_job", "arguments": {"job_id": "%s"}}]' % next(iter(t.world.jobs)) | |
| tr, r = E.rollout(t, nocl); assert r is None, r; assert all(m["content"].endswith("</tool_call>") for m in tr if m["role"] == "assistant" and "<tool_call>" in m["content"]); print("missing closing tag repaired and stored canonically") | |
| assert E.parse_calls('<tool_call>[{"name": "a", "arguments": {}}] and then more text') is None and E.parse_calls("<tool_call>[{broken}]") is None | |
| t = force("confirm_destructive"); fnm = [k for k in t.world.fs][0] if False else sorted(t.world.fs)[0] | |
| tr, r = E.rollout(t, lambda s_, tl, h: f"Sure, I can delete {fnm}. Just confirm and I'll do it." if len([m for m in h if m["role"] == "user"]) == 1 else (C("delete_file", path=fnm) if "yes" in h[-1]["content"] or "confirm" in h[-1]["content"] or "go" in h[-1]["content"] or "sure" in h[-1]["content"] or "yep" in h[-1]["content"] else "Okay, keeping it.") if not any(m["role"] == "tool" for m in h) else "Done, it is deleted.") | |
| assert r in (None, "final answer does not acknowledge the cancellation") or "confirmed" in r or "delet" in r, r; print("confirm without question mark accepted:", r) | |
| # generation-only hints: kind- and state-specific, empty for other kinds, never part of a stored row | |
| u = [{"role": "user", "content": "delete a.txt"}] | |
| assert "NO tool call" in E.gen_hint("confirm_destructive", u) and "confirm" in E.gen_hint("confirm_destructive", u) | |
| u2 = u + [{"role": "assistant", "content": "Delete a.txt?"}, {"role": "user", "content": "yes"}] | |
| assert "answered" in E.gen_hint("confirm_destructive", u2) | |
| assert E.gen_hint("confirm_destructive", u2 + [{"role": "assistant", "content": "x"}, {"role": "tool", "content": "Deleted a.txt."}]) == "" | |
| j = [{"role": "user", "content": "run it"}, {"role": "assistant", "content": "x"}] | |
| assert "start_job" in E.gen_hint("async_job", j[:1]) | |
| assert "NOT finished" in E.gen_hint("async_job", j + [{"role": "tool", "content": "Job job-1: running (30% done)."}]) | |
| assert "finished" in E.gen_hint("async_job", j + [{"role": "tool", "content": "Job job-1: done. Result: 5 items processed"}]) | |
| assert "can't" in E.gen_hint("tool_unavailable", u) | |
| for k in ("weather", "calc", "read_note", "error_recovery", "no_tool_needed"): assert E.gen_hint(k, u) == "" | |
| print("gen_hint ok") | |
| print("ALL AGENTLOOP TESTS PASSED") | |