Lesson 2 of 6 · 2 min
A working core
import json, time
class Budget(Exception): pass
class Run:
def __init__(self, tools, approve, max_steps=10):
self.tools, self.approve, self.max_steps, self.trace = tools, approve, max_steps, []
def call(self, name, args, tries=3):
if len(self.trace) >= self.max_steps:
raise Budget("step limit")
tool = self.tools[name]
if tool["risky"] and not self.approve(name, args):
self.trace.append({"tool": name, "result": "refused by person"})
return None
for attempt in range(1, tries + 1):
try:
result = tool["fn"](**args)
self.trace.append({"tool": name, "args": args, "attempt": attempt, "result": result})
return result
except ConnectionError as e:
error = str(e)
if not tool["safe_to_repeat"]:
break
self.trace.append({"tool": name, "args": args, "error": error})
return None
def execute(self, plan):
done = {}
pending = list(plan)
while pending:
ready = [s for s in pending if all(d in done for d in s["needs"])]
if not ready:
raise ValueError("the plan has a cycle")
for s in ready:
args = {k: done.get(v, v) if isinstance(v, str) else v for k, v in s["args"].items()}
done[s["id"]] = self.call(s["tool"], args)
pending.remove(s)
return done
state = {"fails": 1}
def search(topic):
if state["fails"]:
state["fails"] -= 1
raise ConnectionError("search timed out")
return f"3 notes about {topic}"
tools = {
"search": {"fn": search, "risky": False, "safe_to_repeat": True},
"write": {"fn": lambda text: "draft: " + text, "risky": False, "safe_to_repeat": True},
"send": {"fn": lambda text: "sent", "risky": True, "safe_to_repeat": False},
}
plan = [
{"id": "a", "tool": "search", "args": {"topic": "refunds"}, "needs": []},
{"id": "b", "tool": "write", "args": {"text": "a"}, "needs": ["a"]},
{"id": "c", "tool": "send", "args": {"text": "b"}, "needs": ["b"]},
]
run = Run(tools, approve=lambda name, args: False)
print(run.execute(plan))
print(json.dumps(run.trace, indent=1))
