Skip to main content

03 - Designing Agentic Workflows: Decomposing Problems for AI

How to break a task down for an agent: every step with input, output and check. A program that was run rejects a VAT error and restores the state.

What do you think about this article?

03 - Designing Agentic Workflows: Decomposing Problems for AI
Vibe CodingPhoto:Ruben BoekelooPexels

At a Glance

How to break a task down for an agent: every step with input, output and check. A program that was run rejects a VAT error and restores the state.

03 - Agentic Workflows: Decomposing Problems for AI

An agentic workflow works when every step has a mechanical check that says whether it succeeded, and it stops working when the check is missing. Decomposing a problem for an AI does not mean breaking it into small pieces: it means deciding where to put the checks, because that is where your judgment enters the process. Asking "refactor this codebase" and hoping for the best is the version without checks, and its defect is not that the agent makes mistakes, but that nobody notices until it is too late.

In this article you start from the distinction Anthropic draws between workflows and agents, apply it to a small but complete task (adding VAT to a price list, with tests written first), and run a small program that rejects a wrong step, restores the state and tries again. No model is called: the program's "worker" is a script with preset answers, because what is being studied is the scaffolding around the model and not the model. If you lack context on the tools, start from Claude Code: agentic development from the terminal.

Workflow and agent: who decides the path

In the text Building effective agents (December 2024) Anthropic sets out the distinction: workflows are systems where LLMs and tools are orchestrated through predefined code paths; agents are systems where the LLM dynamically directs its own process and tool usage. The practical consequence is about who owns the path: in a workflow you wrote the order of the steps, and you can read it; in an agent the model decides it at every turn, and you see it only afterwards. The same text recommends finding the simplest solution possible and increasing complexity only when needed, because agentic systems trade latency and cost for better task performance.

The page describes five workflow patterns, and it helps to read them as a catalogue of where to place a check:

  • Prompt chaining: the task is decomposed into fixed steps, each processes the output of the previous one, and between one step and the next you can insert a programmatic check (the "gate" of the original text).
  • Routing: an input is classified and sent to the step specialized for that category.
  • Parallelization: independent sections run together, or the same task is repeated several times to have the outcomes vote.
  • Orchestrator-workers: a central model decides the sub-tasks on the fly, delegates them and gathers the results; Anthropic cites changes across several files as the typical case.
  • Evaluator-optimizer: one model produces, another judges and gives feedback, in a loop.

The criterion that separates the five is how much of the path is known in advance. Chaining and routing require you to already know the steps; parallelization requires the parts to be truly independent; the orchestrator is for when sub-tasks are not predictable, and for that reason it costs more and is harder to control. A good order of work is to start from the most rigid pattern that holds up the task, and move to a more flexible one only when a step you predicted turns out to be impossible to predict.

What a step needs in order to be decomposed well

The rule I use is that every step declares three things: what it receives, what it produces and how you check that it succeeded. If you cannot write the third point as a command that returns success or failure, the step is too vague to be delegated, and the fix is to rephrase it, not to try a longer prompt. An example task: "add the VAT calculation to the price list". It becomes: analyze how prices are represented; write the tests and verify that they fail; implement and verify that they pass; update the documentation; reread the diff. The documentation depends only on the analysis, and this says it can proceed in parallel with the tests.

The first program represents the plan as a dependency graph and turns it into waves with graphlib, the Python standard library module for topological sorting. A wave is the set of steps that can start together, because everything they depend on has already finished. The second use of waves, with a cycle introduced on purpose (the analysis depending on the review), shows why it pays to write the plan as data: a circular plan is rejected before starting, instead of making the agent run in circles.

plan.py - the plan as a graph, sorted into waves
from graphlib import CycleError, TopologicalSorter

# step -> steps it depends on
PLAN = {
    "analysis": [],
    "tests": ["analysis"],
    "docs": ["analysis"],
    "implement": ["tests"],
    "review": ["implement", "docs"],
}


def waves(plan):
    """Group the steps into waves: inside a wave no step depends on another."""
    order = TopologicalSorter(plan)
    order.prepare()
    result = []
    while order.is_active():
        ready = sorted(order.get_ready())
        result.append(ready)
        order.done(*ready)
    return result


for number, wave in enumerate(waves(PLAN), start=1):
    print(f"wave {number}: {', '.join(wave)}")

try:
    waves({**PLAN, "analysis": ["review"]})
except CycleError as error:
    print("plan rejected, cycle among:", ", ".join(sorted(set(error.args[1]))))

# Output (python3 plan.py, two identical runs):
# wave 1: analysis
# wave 2: docs, tests
# wave 3: implement
# wave 4: review
# plan rejected, cycle among: analysis, implement, review, tests

The output says that docs and tests can start together after the analysis, and that implement cannot begin before tests: the order is a property of the plan, not a hope about the model's behavior. The alphabetical order inside the wave (sorted) makes the output reproducible: I do not want it to depend on the order in which the module returns the ready steps. The limit is that the plan here is static: if the steps depend on what the analysis discovers, you need the orchestrator pattern, and the plan is built while you work.

Every step is checked, restored and has a finite number of attempts

The second program runs the "tests, then implementation" chain with three mechanisms: a check per step, a restore of the state if the check fails, and a cap on attempts after which it stops and calls a person. The "worker" is a list of ready-made contents, two versions of vat.py: the first truncates the result (int(...)), the second works with integers and rounds half up (+ 50) // 100). I chose a realistic error: it is money, and a model willingly writes the version that truncates. The checks are real: they launch check.py in a separate process.

run.py - check, restore and cap on attempts
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

CHECK = '''from vat import vat
for net, expected in [(1000, 1220), (999, 1219), (1, 1)]:
    r = vat(net, 22)
    assert r == expected, f"vat({net}, 22) = {r}, expected {expected}"
'''
VAT_TRUNCATED = "def vat(net, rate):\n    return int(net * (100 + rate) / 100)\n"
VAT_ROUNDED = "def vat(net, rate):\n    return (net * (100 + rate) + 50) // 100\n"


def launch(folder):
    r = subprocess.run([sys.executable, "-B", "check.py"], cwd=folder, capture_output=True, text=True)
    last = r.stderr.strip().splitlines()[-1] if r.stderr.strip() else ""
    return r.returncode, last


def verify_tests(folder):
    code, error = launch(folder)      # the tests must fail, and for the right reason
    return code != 0 and "ModuleNotFoundError" in error, error


def verify_implementation(folder):
    code, error = launch(folder)
    return code == 0, error


def step(name, attempts, verify, folder):
    """attempts: the contents the 'worker' writes, one per attempt."""
    for n, (file, text) in enumerate(attempts, start=1):
        before = {p.name: p.read_text() for p in folder.glob("*.py")}
        (folder / file).write_text(text)
        ok, error = verify(folder)
        if ok:
            print(f"{name}: attempt {n} verified")
            return True
        print(f"{name}: attempt {n} rejected ({error or 'no message'})")
        for p in folder.glob("*.py"):        # restore the previous state
            p.unlink()
        for file_name, content in before.items():
            (folder / file_name).write_text(content)
    print(f"{name}: attempts exhausted, stopping and calling a person")
    return False


with tempfile.TemporaryDirectory() as tmp:
    folder = Path(tmp)
    ok = step("tests", [("check.py", CHECK)], verify_tests, folder)
    ok = ok and step(
        "implement",
        [("vat.py", VAT_TRUNCATED), ("vat.py", VAT_ROUNDED)],
        verify_implementation,
        folder,
    )
    print("files in the folder:", sorted(p.name for p in folder.glob("*.py")))

# Output (python3 run.py, two identical runs):
# tests: attempt 1 verified
# implement: attempt 1 rejected (AssertionError: vat(999, 22) = 1218, expected 1219)
# implement: attempt 2 verified
# files in the folder: ['check.py', 'vat.py']

Look at how the check for the tests step is built: it does not ask that the tests pass, it asks that they fail with a ModuleNotFoundError, that is, because vat.py does not exist yet. A test that fails for another reason (a syntax error, a wrong name) would give the same "red" and would prove nothing. In the implement step the first attempt is rejected with a message that names the case (vat(999, 22) = 1218, expected 1219), the state goes back to the previous one (vat.py removed, check.py kept) and the second attempt passes. With a message that precise, a real model would have the information to fix it; without the check, 1218 would have ended up in the price list.

Two choices in the code deserve a comment. The restore rewrites only the *.py files: the first draft touched every entry in the folder and broke on __pycache__, so the test process starts with -B, which avoids writing bytecode. And the program does not use git stash as a restore: in a real project the safe point is a commit on a dedicated branch for each verified step, because a commit can be read in the log, whereas a hidden stash gets forgotten. Anthropic reaches the same conclusion in its text on long-running agents: it asks the model to save progress in git with descriptive messages and to note it in a file, so as to be able to undo wrong changes and recover a working state.

Where workflows really break

The first breaking point is the missing check. In the same text on long-running agents, Anthropic observes that Claude tended to declare a feature complete without having tested it adequately: it made changes and even some unit tests, but did not notice that the feature did not work end to end, and performance improved when it was given tools to test like a user. The method translates into a rule: the success criterion of the step is written by you, beforehand, and it is not "the agent says it has finished".

The second is context. Claude Code compacts the conversation when it fills up, and the documentation warns that instructions given at the beginning can be lost: rules that must always hold go in CLAUDE.md, not in the chat. For the state of a long job, Anthropic's initializer agent creates a claude-progress.txt file with the log of what has been done and an initial commit, and every following session works in small steps leaving structured updates: the new session understands where it stands by reading that file and the git history. Research on long context (Liu et al., "Lost in the Middle") goes in the same direction: performance can degrade significantly when the position of the relevant information in the text changes, so a long and confused context is not a rich context.

The third is over-decomposition. I have no measurement to cite for the number of agents beyond which things get worse, and I distrust the figures that circulate: the reasoning, though, can be done. Every handoff loses some context and adds a chance to misunderstand, so a step that costs less than explaining it should not be delegated to a separate agent. Fifteen sub-agents for fifteen functions in a two-hundred-line file are almost always worse than one agent that handles them in sequence with a test after each. Reserve sub-agents for truly independent parts, on different files and without shared state.

Where you put the person

Anthropic's text describes agents as systems that can pause for human feedback at checkpoints or when they hit blockers, and that usually have a stopping condition, for example a maximum number of iterations. In the program above, the maximum number of attempts is exactly that condition. An order of choice that works for a task on code: the person approves the plan before the work starts, because that is where a mistake costs little; reads the diff after the steps that touch data, security or public interfaces; is not needed for steps that a test closes on its own.

When not to build an agentic workflow: if the task takes five minutes by hand and you know it, if you have no automatic way to say the result is right, or if the error cannot be undone. In that last case the choice is not between agent and workflow but between delegating and not delegating, and the answer is a matter of permissions before it is one of prompts, as the previous article shows. The work on generated code, its checking, is the topic of Testing AI-generated code.

Frequently asked questions

What is the difference between a workflow and an agent?

According to Anthropic, in a workflow LLMs and tools are orchestrated through predefined code paths; in an agent it is the model that directs its own process. In the first case you write the order of the steps, in the second the model decides it at every step.

How many steps should a workflow have?

As many as it takes for each to have a result that an automatic check can verify, and no more. A step that you cannot check on its own or that costs less to do than to explain should be merged with the one next to it.

Why isn't a very detailed prompt enough?

A detailed prompt describes the result but does not verify it. With a checked step, an error such as truncating the cents is rejected with a precise message, instead of reaching the final result.

What you can do now

You can tell a workflow from an agent and choose among the five patterns according to how much of the path you know in advance. You can write a step with input, output and check, sort steps into waves and reject a circular plan, and you have seen a check reject a realistic error, restore the state and stop after a finite number of attempts. You know where to put the person and when not to build the workflow. To use several agents together continue with multi-agent coding, and for the verification setup with testing generated code. The starting point of the series is the first article on vibe coding.

For prompts and persistent instruction files see Prompt Engineering for IDEs and Code Generation; for the security risks of what the agent writes, Security in vibe coding; for the close of the series, The future of agentic software development.

Sources

The two programs were run with Python 3.14, each twice with identical output (cmp). The "worker" is a script with preset answers: no model was called, and the behavior of a real model was not measured.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects