GyaanStack. Blog

Articles / agentspython

Build a task planning AI agent in Python: plan, validate, run in parallel, replan

A plan-and-execute agent in plain Python with a JSON plan, cycle and tool checks, parallel steps, replanning on failure, a budget, and a real local model run.

By Raghunath · · 21 min read

A task planning agent takes a messy request, such as "sort out my morning: tickets, the prod alert, my 2 PM prep", and turns it into a list of tool calls with dependencies between them. Code then runs that list. The model plans once, your code executes, and the model comes back only when something breaks.

The usual tutorial version asks a model for a JSON to-do list, calls json.loads, and prints it. That works until the model names a tool you do not have, points step 4 at a step that does not exist, or writes a plan where two steps wait on each other forever. This post builds the version that survives those cases, in about 200 lines of standard-library Python:

  • a planner that returns a JSON plan with depends_on edges
  • a validator that rejects unknown tools, wrong arguments, missing dependencies and cycles before anything runs
  • an executor that runs independent steps in parallel waves, in topological order
  • a replanner that gets the error and the finished steps when a step fails
  • a budget on model calls, steps and replans

All of it runs with a scripted stub model and no API key. At the end the same code runs against a local qwen3:4b-instruct through Ollama, and the real model's mistakes are shown as they happened.

If you want the theory first, AI agent architectures explained compares plan-and-execute with ReAct, reflection and routers, with call counts and the ReWOO and LLMCompiler results. For storing plans across crashes, approvals and days-long runs, see Designing long-running AI agents. This post does not repeat either; it is the build.

The shape of the agent#

 task ──> [ planner LLM ] ──> JSON plan
                                 │
                          [ validate ]──invalid──> error text back to planner (1 retry)
                                 │ ok
                    ┌────────────┴─────────────┐
                    │ executor (graphlib)       │
                    │  wave 1: s1  s2  s3       │  independent steps, in parallel
                    │  wave 2: s4 (needs 1,2,3) │
                    └────────────┬─────────────┘
                                 │ step raised?
                      yes ───────┤
                       │         │ no
                       v         v
       [ replanner LLM ]       answer = result of last step
   (goal + finished steps + error;
    finished steps are frozen)

Two choices in this diagram do most of the work. The plan is data, so code can check it before running it. Finished steps are frozen during a replan, so a second plan cannot quietly redo or change work that already succeeded.

The plan format#

One step is one tool call:

{"id": "s4", "tool": "prioritize",
 "args": {"tickets": "$s1", "incidents": "$s2", "meetings": "$s3"},
 "depends_on": ["s1", "s2", "s3"]}

An argument written as "$s1" means "the result of step s1". This is the same placeholder idea ReWOO uses for its evidence variables (Xu et al., 2023). It lets the planner wire steps together without seeing any results, which is why one planner call is enough.

The prioritize tool is plain Python, not a model call. The P0 to P3 rules (production incidents first, blocking reviews next, routine work after) are fixed business logic, and fixed logic belongs in code where you can test it. The model's job is to decide which data to fetch and how the pieces connect.

The full agent#

ScriptedModel plays back canned replies so the code runs offline. Any object with a complete(system, user) -> str method and a calls counter can replace it; the docstring marks where the real client call goes. LLM_S and TOOL_S are simulated latencies (1.5 s per model call, 0.4 s per tool call), round figures for comparing shapes, not measurements.

"""Plan-and-execute agent: JSON plan, validation, parallel waves, replanning, budget.

Standard library only (Python 3.9+ for graphlib). No API key: ScriptedModel
returns the JSON a model would return. Swap it for any class with the same
complete(system, user) -> str method to run against a real model.
"""
import json
import re
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from graphlib import TopologicalSorter, CycleError

LLM_S, TOOL_S = 1.5, 0.4          # simulated seconds per model call / tool call

# ---- tools: fake data sources for a morning triage -------------------------
DATA = {
    "jira": [{"key": "WEB-412", "title": "Review login page PR", "blocking": True},
             {"key": "MKT-88", "title": "Reply on analytics tracking", "blocking": False}],
    "alerts": {"reporting-dashboard": [{"code": 500, "count": 212}]},
    "calendar": [{"time": "14:00", "title": "1:1 with manager", "prep_minutes": 20}],
}

def jira_open(project):
    return [t for t in DATA["jira"] if t["key"].startswith(project) or project == "ALL"]

def alerts(service):
    if service not in DATA["alerts"]:
        raise LookupError(f"unknown service '{service}', known: {sorted(DATA['alerts'])}")
    return DATA["alerts"][service]

def calendar_today():
    return DATA["calendar"]

def prioritize(tickets, incidents, meetings):
    """Plain code, not a model call: the P0-P3 rules live here."""
    out = []
    for i in incidents:
        out.append(("P0", f"Fix {i['count']} x HTTP {i['code']} on prod dashboard", 90))
    for t in tickets:
        out.append(("P1" if t["blocking"] else "P2", t["title"], 45 if t["blocking"] else 15))
    for m in meetings:
        out.append(("P2", f"Prep for {m['title']} ({m['time']})", m["prep_minutes"]))
    return sorted(out)

def runbook(incidents):
    return {"team": "data-platform", "first_step": "check DB connection pool"} if incidents else {}

def oncall(runbook):
    return {"data-platform": "dp-oncall-1"}.get(runbook.get("team"), "nobody")

TOOLS = {  # name -> (function, required args)
    "jira_open": (jira_open, {"project"}),
    "alerts": (alerts, {"service"}),
    "calendar_today": (calendar_today, set()),
    "prioritize": (prioritize, {"tickets", "incidents", "meetings"}),
    "runbook": (runbook, {"incidents"}),
    "oncall": (oncall, {"runbook"}),
}

# ---- the model interface ---------------------------------------------------
class ScriptedModel:
    """Plays back canned replies in order. Replace complete() with a real call,
    e.g. client.messages.create(...) or an Ollama /api/chat request."""
    def __init__(self, replies):
        self.replies, self.calls = list(replies), 0
    def complete(self, system, user):
        self.calls += 1
        return self.replies.pop(0)

# ---- plan validation -------------------------------------------------------
REF = re.compile(r"^\$(\w+)$")   # "$s1" means "the result of step s1"

class PlanError(ValueError):
    pass

def validate(plan, max_steps):
    steps = plan.get("steps")
    if not isinstance(steps, list) or not steps:
        raise PlanError("plan has no steps")
    if len(steps) > max_steps:
        raise PlanError(f"{len(steps)} steps exceeds budget of {max_steps}")
    ids = [s.get("id") for s in steps]
    if len(set(ids)) != len(ids):
        raise PlanError("duplicate step ids")
    graph = {}
    for s in steps:
        if s.get("tool") not in TOOLS:
            raise PlanError(f"{s['id']}: unknown tool '{s.get('tool')}'")
        given, needed = set(s.get("args", {})), TOOLS[s["tool"]][1]
        if given != needed:
            raise PlanError(f"{s['id']}: {s['tool']} takes args {sorted(needed)}, got {sorted(given)}")
        deps = set(s.get("depends_on", []))
        for d in deps:
            if d not in ids:
                raise PlanError(f"{s['id']}: depends on unknown step '{d}'")
        for v in s.get("args", {}).values():
            m = REF.match(str(v))
            if m and m.group(1) not in deps:
                raise PlanError(f"{s['id']}: uses ${m.group(1)} without depending on it")
        graph[s["id"]] = deps
    try:
        TopologicalSorter(graph).prepare()
    except CycleError as e:
        raise PlanError(f"cycle: {' -> '.join(e.args[1])}")
    return graph

# ---- executor --------------------------------------------------------------
@dataclass
class Budget:
    model_calls: int = 6
    steps: int = 8
    replans: int = 2

class BudgetExceeded(RuntimeError):
    pass

PLANNER_SYS = """You plan tool calls. Reply with JSON only:
{"steps":[{"id":"s1","tool":"...","args":{},"depends_on":[]}]}
To pass the result of step sN into an arg, write the string "$sN" and list sN in depends_on.
Steps with no dependency between them run in parallel. The last step's result is the answer.
Use the fewest steps that answer the task. Tools:
- jira_open(project) -> list of tickets
- alerts(service) -> list of incidents
- calendar_today() -> list of meetings
- prioritize(tickets, incidents, meetings) -> the schedule
- runbook(incidents) -> runbook for the owning team
- oncall(runbook) -> who is on call"""

def run_step(step, results):
    fn = TOOLS[step["tool"]][0]
    args = {k: results[REF.match(str(v)).group(1)] if REF.match(str(v)) else v
            for k, v in step.get("args", {}).items()}
    return fn(**args)

def plan_and_execute(task, model, budget=Budget(), log=print):
    results, done, replans, sim_s = {}, set(), 0, 0.0

    def ask(user):
        nonlocal sim_s
        if model.calls >= budget.model_calls:
            raise BudgetExceeded(f"model call budget {budget.model_calls} used up")
        sim_s += LLM_S
        return model.complete(PLANNER_SYS, user)

    def get_plan(user, frozen=None):
        # One retry on an invalid plan; the error text goes back to the model.
        for _ in range(2):
            raw = ask(user)
            try:
                plan = json.loads(raw)
                graph = validate(plan, budget.steps)
                steps = {s["id"]: s for s in plan["steps"]}
                for sid, old in (frozen or {}).items():   # done steps may not change
                    new = steps.get(sid, {})
                    if (new.get("tool"), new.get("args")) != (old["tool"], old["args"]):
                        raise PlanError(f"replan changed finished step {sid}")
                return steps, graph
            except (json.JSONDecodeError, PlanError) as e:
                log(f"  plan rejected: {e}")
                user += f"\nYour last plan was invalid: {e}. Fix it."
        raise PlanError("planner failed twice")

    steps, graph = get_plan(f"Task: {task}")
    while True:
        ts = TopologicalSorter(graph)
        ts.prepare()
        failed = None
        while ts.is_active() and not failed:
            ready = ts.get_ready()
            todo = [steps[i] for i in ready if i not in done]
            if todo:
                log("  wave: " + ", ".join(f"{s['id']}:{s['tool']}" for s in todo))
                sim_s += TOOL_S            # one wave = one tool latency, in parallel
                with ThreadPoolExecutor() as pool:
                    futs = {s["id"]: pool.submit(run_step, s, results) for s in todo}
                errors = []
                for sid, f in futs.items():
                    try:
                        results[sid] = f.result()
                        done.add(sid)
                    except Exception as e:
                        errors.append(f"{sid} {type(e).__name__}: {e}")
                failed = "; ".join(errors) or None
            for sid in ready:
                if sid in done:
                    ts.done(sid)
        if not failed:
            last = list(steps)[-1]          # convention: the last step is the answer
            return results[last], model.calls, sim_s
        replans += 1
        if replans > budget.replans:
            raise BudgetExceeded(f"replan budget {budget.replans} used up")
        log(f"  failed: {failed} -> replanning")
        kept = {k: steps[k] for k in done}
        steps, graph = get_plan(
            f"Task: {task}\nFinished steps, keep them unchanged: {json.dumps(list(kept.values()))}\n"
            f"Failed: {failed}\nReturn the full plan.", frozen=kept)

A few decisions in that code are worth defending.

graphlib does the scheduling. Python has shipped a topological sorter in the standard library since 3.9 (docs). prepare() raises CycleError with the cycle in args[1], so cycle detection costs one line. get_ready() returns every node whose dependencies are done, and that set is exactly one parallel wave. You call done() on finished nodes and ask again.

Validation is strict on arguments. The check is given != needed, not "are the required ones present". Extra arguments are a real failure, as the local model run below shows: a plan that passes service to jira_open would crash with a TypeError at run time, after other steps have already done work.

Every failure in a wave is reported. If two steps in the same wave fail, the replanner sees both errors. Keep only the last one and the replanner fixes one bug per round trip.

Tool errors must say how to fix them. alerts raises unknown service 'reporting-db', known: ['reporting-dashboard']. Without the list of known services, the replanner has nothing new to work with and tends to write the same plan again. The error message is part of the prompt, so write it for the model.

Threads, not asyncio. The tools here are blocking functions, and ThreadPoolExecutor runs them in parallel without rewriting them as coroutines (docs). If your tools are already async HTTP calls, asyncio.gather over each wave does the same job.

Running it: validation, a failed step, a replan#

The demo script builds plans with a small helper and feeds them through the agent. Here are the plans for the main task:

P = lambda *steps: json.dumps({"steps": [
    {"id": i, "tool": t, "args": a, "depends_on": d} for i, t, a, d in steps]})

TRIAGE = P(("s1", "jira_open", {"project": "ALL"}, []),
           ("s2", "alerts", {"service": "reporting-dashboard"}, []),
           ("s3", "calendar_today", {}, []),
           ("s4", "prioritize", {"tickets": "$s1", "incidents": "$s2", "meetings": "$s3"},
            ["s1", "s2", "s3"]))
TRIAGE_BAD_NAME = TRIAGE.replace("reporting-dashboard", "reporting-db")

Scenario 1 feeds four broken plans to validate. Scenario 2 scripts the planner to use the wrong service name first and the right one on the replan. Scenario 3 has the planner reply with chatty text instead of JSON. Scenario 4 gives a planner that never learns and a replan budget of one. This is the real output:

== 1. validation catches bad plans before anything runs
  unknown tool             -> s1: unknown tool 'send_slack'
  cycle                    -> cycle: s1 -> s2 -> s1
  ref without dependency   -> s2: uses $s1 without depending on it
  over budget              -> 9 steps exceeds budget of 8

== 2. step failure triggers a replan
  wave: s1:jira_open, s2:alerts, s3:calendar_today
  failed: s2 LookupError: unknown service 'reporting-db', known: ['reporting-dashboard'] -> replanning
  wave: s2:alerts
  wave: s4:prioritize
  [P0] Fix 212 x HTTP 500 on prod dashboard (90 min)
  [P1] Review login page PR (45 min)
  [P2] Prep for 1:1 with manager (14:00) (20 min)
  [P2] Reply on analytics tracking (15 min)
  model calls: 2, simulated latency: 4.2 s

== 3. planner returns garbage, then a valid plan
  plan rejected: Expecting value: line 1 column 1 (char 0)
  wave: s1:alerts
  result: [{'code': 500, 'count': 212}], model calls: 2

== 4. budget stops a planner that keeps failing
  wave: s1:jira_open, s2:alerts, s3:calendar_today
  failed: s2 LookupError: unknown service 'reporting-db', known: ['reporting-dashboard'] -> replanning
  wave: s2:alerts
  BudgetExceeded: replan budget 1 used up (model calls: 2)

Look at scenario 2 after the replan. The second plan contains all four steps, but only s2 runs again. s1 and s3 finished in the first wave, the frozen check confirmed the new plan left them alone, and the executor skipped them. The simulated 4.2 s is two model calls (3.0 s) plus three tool waves (1.2 s).

ReAct vs plan-and-execute on four toy tasks#

For the comparison, a minimal ReAct loop makes one model call per tool step and one more to finish. It resolves the same $sN references against its own observation list, so both agents use identical tools:

def react(model, max_calls=10):
    obs, sim_s = {}, 0.0
    while model.calls < max_calls:
        sim_s += LLM_S
        reply = json.loads(model.complete("ReAct system prompt", json.dumps(obs, default=str)))
        if "final" in reply:
            return reply["final"], model.calls, sim_s
        args = {k: obs[REF.match(str(v)).group(1)] if REF.match(str(v)) else v
                for k, v in reply["args"].items()}
        sim_s += TOOL_S                          # strictly one tool at a time
        key = f"s{len(obs) + 1}"
        try:
            obs[key] = TOOLS[reply["tool"]][0](**args)
        except Exception as e:
            obs[key] = f"ERROR {type(e).__name__}: {e}"
    raise RuntimeError("call budget used up")

Both agents get scripted replies that solve each task correctly, so the numbers compare structure, not model quality:

== 5. ReAct vs plan-and-execute on four toy tasks
  task                               ReAct calls  ReAct s  P&E calls  P&E s
  single lookup                                2      3.4          1    1.9
  morning triage (3 parallel + 1)              5      9.1          1    2.3
  triage, wrong service name                   6     11.0          2    4.2
  sequential chain (3 levels)                  4      7.2          1    2.7

What the table says:

  • The gap grows with independent steps. On the triage task ReAct pays five model calls and four sequential tool calls (5 x 1.5 + 4 x 0.4 = 9.1 s). Plan-and-execute pays one call and two waves (1.5 + 2 x 0.4 = 2.3 s).
  • A failure costs each pattern one extra call here. ReAct reads the error and retries inline; plan-and-execute replans. The difference is that the replan also rewires downstream steps, while ReAct has to carry the new $s3 reference through by itself.
  • Sequential chains still favour planning on call count, 4 to 1, but parallelism gives nothing: three levels means three tool waves either way.
  • The single lookup is close. For one tool call, the planning machinery is overhead you do not need.

Two caveats keep this honest. First, this plan-and-execute version has no final "solver" call, because the last step (prioritize) is code that returns the answer. If you want a prose summary, add one model call (1.5 s) to every P&E row. Second, these are scripted replies. ReAct's real advantage, reading a result before deciding the next step, never shows up when every task is plannable up front. A task like "open the file the search returns and fix the bug in it" cannot be planned before the search runs. The architectures post covers when each pattern breaks.

The same agent with a real local model#

The stub proves the plumbing. To see what a small real model does with the prompt, this class sends the planner calls to Ollama's /api/chat endpoint with a JSON schema in the format field, which constrains the reply to that schema (Ollama structured outputs, chat API). The model is qwen3:4b-instruct, a 2.5 GB download, at temperature 0:

class OllamaModel:
    def __init__(self, model="qwen3:4b-instruct"):
        self.model, self.calls = model, 0
    def complete(self, system, user):
        self.calls += 1
        body = {"model": self.model, "stream": False, "format": SCHEMA,
                "options": {"temperature": 0},
                "messages": [{"role": "system", "content": system},
                             {"role": "user", "content": user}]}
        req = urllib.request.Request("http://localhost:11434/api/chat",
                                     json.dumps(body).encode(), {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=300) as r:
            text = json.loads(r.read())["message"]["content"]
        print("  model said:", text.replace("\n", " ")[:400])
        return text

The task deliberately names the wrong service, reporting-db, so the run has to recover. Output on Ollama 0.40.16, on a laptop CPU:

  model said: {"steps":[{"args":{"project":"ALL"},"depends_on":[],"id":"s1","tool":"jira_open"},{"args":{"service":"reporting-db"},"depends_on":[],"id":"s2","tool":"alerts"},{"args":{},"depends_on":[],"id":"s3","tool":"calendar_today"},{"args":{"tickets":"$s1","incidents":"$s2","meetings":"$s3"},"depends_on":["s1","s2","s3"],"id":"s4","tool":"prioritize"}]}
  wave: s1:jira_open, s2:alerts, s3:calendar_today
  failed: s2 LookupError: unknown service 'reporting-db', known: ['reporting-dashboard'] -> replanning
  model said: {"steps":[{"args":{"project":"ALL"},"depends_on":[],"id":"s1","tool":"jira_open"},{"args":{"service":"reporting-dashboard"},"depends_on":[],"id":"s2","tool":"alerts"},{"args":{},"depends_on":[],"id":"s3","tool":"calendar_today"},{"args":{"tickets":"$s1","incidents":"$s2","meetings":"$s3"},"depends_on":["s1","s2","s3"],"id":"s4","tool":"prioritize"}]}
  wave: s2:alerts
  wave: s4:prioritize
   ('P0', 'Fix 212 x HTTP 500 on prod dashboard', 90)
   ('P1', 'Review login page PR', 45)
   ('P2', 'Prep for 1:1 with manager (14:00)', 20)
   ('P2', 'Reply on analytics tracking', 15)
  model calls: 2, wall clock: 189.7 s

The 4B model wrote the same graph the scripted planner did, read the list of known services from the error, and fixed only the broken argument. The 189.7 s wall clock is this laptop's CPU, not a number to plan around.

That was the second attempt. The first run used a shorter system prompt (tool signatures only, nothing about what each returns) and a looser validator that checked for missing arguments but not extra ones. The run stopped after four model calls and 121.9 s with planner failed twice. The plans it wrote:

  • passed service to jira_open, an argument it does not take (the old validator let this through, which is why the check is now given != needed)
  • appended steps s5 and s6 the task never asked for, with arguments that did not match their tools
  • wired $s1 (tickets) into incidents and $s3 into tickets
  • wrote "$s3" inside depends_on instead of "s3"

Adding one line per tool saying what it returns, the rule "list sN in depends_on", and "use the fewest steps" fixed all four on the next run. JSON-schema output alone did not help, because every one of those plans was valid JSON matching the schema. Schema enforcement checks shape. Your validator checks meaning.

Failure modes and what catches them#

Failure Caught by Cost
Reply is not JSON json.loads + one retry with the parse error 1 model call
Unknown tool, wrong args validate, before any tool runs 1 model call
Dangling depends_on, $sN without the edge validate 1 model call
Cycle graphlib CycleError in validate 1 model call
Plan too long step budget in validate 1 model call
Tool raises at run time executor, then replan with the error 1 model call per replan
Replan rewrites finished work frozen-step check 1 model call
Planner never converges replan and model-call budgets run stops, you get the exception
Step succeeds with useless output (empty list) not caught here wrong answer

The last row is the one to fix next. alerts returning [] for a real outage looks like success to this executor. Add per-tool result checks (non-empty, expected keys) that raise, and the existing replan path handles them. The two budget numbers also need real values: count model calls and tokens per run with something like the LLM cost and latency tracker, then set the caps a little above your p95.

Testing the planner#

The scripted model makes the executor testable with plain asserts: feed a plan, check which waves ran and in what order. The planner needs its own eval. A small set works:

  1. Write 20 to 30 tasks with a known correct plan graph (tools, arguments, edges).
  2. Run the real planner on each at temperature 0.
  3. Score three things per task: valid on first try, graph matches the reference (same tools, same edges, step ids ignored), and solved within budget.
  4. Re-run the set when you change the prompt, the model or the tool list.

The two Ollama runs above are that eval with one task. With 30 tasks, you can tell whether a prompt change helped or got lucky. Evaluating an AI agent in Python builds that eval step by step, and function calling covers the single-call tool schema the planner prompt borrows from.

When to use this pattern#

Use plan-and-execute when the steps can be known from the request: triage across several sources, report assembly, batch lookups. Independent steps run together, the plan is a JSON object you can log or show to a human for approval, and the model is called once or twice per task instead of once per step. If the next step depends on reading the last result closely, use a ReAct loop or let the replanner run after every wave. If the run lasts hours and must survive restarts, store the plan and step status as described in the long-running agents post.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.