Files

106 lines
4.9 KiB
Python

import asyncio
import json
import textwrap
from pipewright import Graph
from pipewright.engine import Engine, RunOptions
from pipewright.harness.base import AgentTask, HarnessContext
from pipewright.harness.builtin_agent import BuiltinAgent
from pipewright.models.base import ModelClient
from pipewright.models.fake import FakeProvider
from pipewright.project import ModelAlias
from pipewright.sandbox.fake import FakeProvider as FakeSandboxes
from pipewright.store import Store
def tool_call(name, args, i=0):
return {"id": f"c{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}
def test_builtin_agent_uses_tools():
def script(payload):
msgs = payload["messages"]
tools = [m for m in msgs if m["role"] == "tool"]
if not tools:
return {"content": "", "tool_calls": [tool_call("write_file", {"path": "a.py", "content": "x=1"})]}
if len(tools) == 1:
return {"content": "", "tool_calls": [tool_call("bash", {"command": "ls"}, 1),
tool_call("bash", {"command": "{bad json"}, 2)]}
return {"content": "", "tool_calls": [tool_call("finish", {"summary": "wrote a.py"}, 3)]}
import sys
import types
mod = types.ModuleType("_pw_test_script")
mod.script = script
sys.modules["_pw_test_script"] = mod
async def main():
prov = FakeProvider("f", {"script": "_pw_test_script:script"})
client = ModelClient("solver", ModelAlias(provider="f", model="m", cache=False), prov)
ctx = HarnessContext(lambda alias, salt: client, None)
sbp = FakeSandboxes("fs", {"rules": [{"match": "ls", "stdout": "a.py\n"}]})
async with sbp.lease() as sb:
traj = await BuiltinAgent("mini", {"model": "solver"}).run(AgentTask(prompt="do it"), sb, ctx)
return traj, sb.files
traj, files = asyncio.run(main())
assert traj.status == "completed" and traj.final == "wrote a.py" and traj.turns == 3
assert files == {"/workspace/a.py": b"x=1"}
assert "a.py" in traj.messages[5]["content"] # bash output fed back
AGENT = textwrap.dedent("""
import json, os, urllib.request, urllib.error
req = urllib.request.Request(os.environ["OPENAI_BASE_URL"] + "/chat/completions",
data=json.dumps({"model": os.environ["PW_MODEL"], "messages": [{"role": "user", "content": open(".pw/prompt.md").read()}]}).encode(),
headers={"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"], "Content-Type": "application/json"})
try:
answer = json.load(urllib.request.urlopen(req))["choices"][0]["message"]["content"]
except urllib.error.HTTPError as e:
print("model call failed", e.code) # a sloppy agent: exits 0 anyway
raise SystemExit(0)
open("answer.txt", "w").write(answer)
""")
def cli_graph():
g = Graph("cli")
src = g.add("src", "source.inline", kind="q", records=[{"id": "q1", "q": "say the magic word"}])
g.add("agent", "agent.run", input=src, harness="ext", pool="local", prompt="{{ payload.q }}",
files={"agent.py": AGENT}, grade={"command": "grep -q abracadabra answer.txt"},
retries={"provider": 0})
return g.to_spec()
def test_cli_harness_through_proxy(make_project):
proj = make_project({
"providers": {"fake": {"type": "fake", "rules": [{"match": "magic", "content": "abracadabra"}]}},
"models": {"m": {"provider": "fake", "model": "fake-m"}},
"sandboxes": {"local": {"type": "local"}},
"harnesses": {"ext": {"type": "cli", "model": "m", "command": "python3 agent.py"}},
})
store = Store(proj.store_dir)
s = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
assert s["funnel"]["nodes"]["agent"]["events"] == {"ok": 1}, s["errors"]
item = store.get_items(store.flow_items(s["run_id"], "agent"))[0]
assert item.labels["passed"] is True and item.labels["agent_status"] == "completed"
traj = json.loads(store.get_blob(item.artifacts["trajectory"]))
assert traj["messages"][-1]["content"] == "abracadabra" and traj["turns"] == 1
def test_cli_harness_last_call_failed_is_provider_error(make_project):
proj = make_project({
"providers": {"fake": {"type": "fake", "fail": {"first": 99, "status": 503}}},
"models": {"m": {"provider": "fake", "model": "fake-m", "max_retries": 0}},
"sandboxes": {"local": {"type": "local"}},
"harnesses": {"ext": {"type": "cli", "model": "m", "command": "python3 agent.py"}},
})
store = Store(proj.store_dir)
s = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
assert s["funnel"]["nodes"]["agent"]["events"] == {"error:provider": 1}
assert "last model call failed" in s["errors"][0]["message"]
# not memoized: the next run executes it again instead of replaying the error
s2 = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
assert s2["funnel"]["nodes"]["agent"]["events"] == {"error:provider": 1}