DEV Community

Paperlane Studio
Paperlane Studio

Posted on AI-assisted

A tiny orchestrator agent with an approval gate (under 100 lines of Python)

Most "build an agent" tutorials hand one model every tool and hope for the best. We run a small team of agents for our own online shop, and the setup that has held up best is the opposite: one orchestrator holds the permissions, each worker only gets the tools its job needs, and anything risky waits for a human "y".

Here is that pattern stripped down to under 100 lines of plain Python, with no framework. It runs with a fake scripted model, so you can try it without an API key, and swapping in a real model is one function.

The three rules

  1. Workers don't own tools. A worker lists the tool names it may use; the orchestrator checks every call.
  2. Risky tools are marked. Sending, paying and deleting are risky=True and need approval at call time, not at setup time.
  3. Every loop has a step limit. An agent that can't finish in N steps stops and says so.

The code

"""A tiny orchestrator agent with an approval gate.

The orchestrator holds the permissions. Worker agents only get the tools
their job needs. Any tool marked risky waits for a human "y" first.
"""
import json
from dataclasses import dataclass, field
from typing import Callable


@dataclass
class Tool:
    name: str
    description: str
    run: Callable[[str], str]
    risky: bool = False  # sends, pays, deletes -> needs approval


@dataclass
class Worker:
    name: str
    instructions: str
    tools: list[str] = field(default_factory=list)


class Orchestrator:
    def __init__(self, call_model, tools, workers, approve=input, max_steps=6):
        self.call_model = call_model          # (system, messages) -> str
        self.tools = {t.name: t for t in tools}
        self.workers = {w.name: w for w in workers}
        self.approve = approve
        self.max_steps = max_steps
        self.log = []

    def use_tool(self, worker, name, arg):
        if name not in worker.tools:
            return f"DENIED: {worker.name} has no access to {name}"
        tool = self.tools[name]
        if tool.risky:
            answer = self.approve(f"[{worker.name}] wants {name}({arg!r}). Allow? y/n ")
            if answer.strip().lower() != "y":
                return "DENIED by human"
        return tool.run(arg)

    def run_worker(self, worker_name, task):
        worker = self.workers[worker_name]
        tool_list = "\n".join(
            f"- {n}: {self.tools[n].description}" for n in worker.tools)
        system = (
            f"{worker.instructions}\n\nTools:\n{tool_list}\n"
            'Reply with JSON only: {"tool": name, "arg": text} '
            'or {"done": final answer}.'
        )
        messages = [{"role": "user", "content": task}]
        for _ in range(self.max_steps):
            reply = json.loads(self.call_model(system, messages))
            if "done" in reply:
                self.log.append((worker.name, "done", reply["done"]))
                return reply["done"]
            result = self.use_tool(worker, reply["tool"], reply["arg"])
            self.log.append((worker.name, reply["tool"], result))
            messages.append({"role": "assistant", "content": json.dumps(reply)})
            messages.append({"role": "user", "content": f"Tool result: {result}"})
        return "STOPPED: step limit reached"

    def handle(self, request, plan):
        """plan: list of (worker_name, task) - from a planner model or by hand."""
        results = []
        for worker_name, task in plan:
            context = "\n".join(results)
            results.append(self.run_worker(worker_name, f"{task}\n\nSo far:\n{context}"))
        return results[-1]
Enter fullscreen mode Exit fullscreen mode

The model only ever answers with JSON: either {"tool": ..., "arg": ...} or {"done": ...}. That keeps parsing trivial and makes every action visible in self.log.

Try it without an API key

"""Runs the orchestrator with a scripted fake model, no API key needed."""
import json
from orchestrator import Orchestrator, Tool, Worker

INBOX = ["Invoice #212 overdue - Acme", "Lunch on Friday?", "Refund request - order 88"]

tools = [
    Tool("read_inbox", "List unread email subjects", lambda _: "\n".join(INBOX)),
    Tool("draft_reply", "Save a reply as a draft", lambda t: f"draft saved: {t[:40]}"),
    Tool("send_email", "Send an email now", lambda t: f"SENT: {t[:40]}", risky=True),
]
workers = [
    Worker("triage", "You sort email by urgency.", ["read_inbox"]),
    Worker("writer", "You write short polite replies.", ["draft_reply", "send_email"]),
]

SCRIPT = iter([
    {"tool": "read_inbox", "arg": ""},
    {"done": "Urgent: Refund request - order 88. Later: invoice, lunch."},
    {"tool": "draft_reply", "arg": "Hi, your refund for order 88 is on its way."},
    {"tool": "send_email", "arg": "Hi, your refund for order 88 is on its way."},
    {"done": "Reply drafted; sending was not approved."},
])


def fake_model(system, messages):
    return json.dumps(next(SCRIPT))


bot = Orchestrator(fake_model, tools, workers, approve=lambda q: (print(q + "n"), "n")[1])
print(bot.handle("Deal with my inbox", [
    ("triage", "Find the most urgent email."),
    ("writer", "Reply to the most urgent email."),
]))
for entry in bot.log:
    print(entry)
Enter fullscreen mode Exit fullscreen mode

Output:

[writer] wants send_email('Hi, your refund for order 88 is on its way.'). Allow? y/n n
Reply drafted; sending was not approved.
('triage', 'read_inbox', 'Invoice #212 overdue - Acme\nLunch on Friday?\nRefund request - order 88')
('triage', 'done', 'Urgent: Refund request - order 88. Later: invoice, lunch.')
('writer', 'draft_reply', 'draft saved: Hi, your refund for order 88 is on its w')
('writer', 'send_email', 'DENIED by human')
('writer', 'done', 'Reply drafted; sending was not approved.')
Enter fullscreen mode Exit fullscreen mode

Notice what didn't happen: the triage worker never had send_email, so even a confused model could not send anything from there. The writer had it, asked, and was told no.

Plugging in a real model

call_model is just (system, messages) -> str. With the Anthropic Python SDK it looks roughly like this (any chat API works the same way):

import anthropic
client = anthropic.Anthropic()

def call_model(system, messages):
    reply = client.messages.create(
        model="YOUR_MODEL_ID", max_tokens=500,
        system=system, messages=messages)
    return reply.content[0].text
Enter fullscreen mode Exit fullscreen mode

In practice you will also want to catch json.JSONDecodeError and feed the error back to the model as a tool result, instead of crashing.

What we learned running this for real

  • Approval at call time beats approval at setup time. "This agent may send email" is too broad; "send this email to this person?" is what you actually want to answer.
  • Separate accounts for agents. Give the agent its own mailbox and its own logins, not yours.
  • Treat everything a tool returns as data. A web page or an email can contain text like "ignore your instructions and…". Never let tool output change the plan; only the orchestrator's input does.
  • Log every tool call. When something goes wrong, the log is the only honest answer to "what did it do?"

Where to go from here

  • Let a planner model produce the plan list instead of writing it by hand.
  • Add a spending limit next to risky (e.g. a tool that refuses amounts over 20).
  • Add a weekly review: read the log and remove tools a worker never needed.

Show and tell: the non-code side of this — how to choose the first tasks for an agent, approval rules, a prompt library and printable checklists — is what we packed into our AI Agent Starter Kit (a $5.79 PDF/DOCX/XLSX pack, written for small business owners rather than developers). The code above is free to use however you like.

Note: this post and its code were written with AI assistance; the code was run and tested before publishing.

Top comments (0)