›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Architecture Patterns in Practice

AI Workflows and Agents in Practice: Chaining, Routing, Parallel Calls, Orchestrators and the Agent Loop

October 20, 2026 · 25 min read

Software Architecture, Design Patterns, AI, Agentic AI, C#, Python

This post is part of Architecture Patterns in Practice, the series that puts runnable code behind every pattern in my map of the architecture patterns worth knowing in 2026. This one covers the "Workflows and agents" table from the AI bonus section.

The names come from Anthropic's Building effective agents. That piece splits the space in two. Workflows are systems where your code decides the path and calls the model at fixed points. Agents are systems where the model decides the path, picking tools in a loop. Five of the patterns below are workflows. The last one is the agent.

The most useful advice in that piece is also the shortest: start with the simplest thing that works. A single well-written prompt beats a chain. A chain beats an agent. You add moving parts only when the simpler version measurably fails. I'd treat that as the rule for this whole post.

About the code. Every snippet runs offline. Wherever a real app would call a model, these call a fake: a few lines of scripted rules or a fixed list of replies. That keeps the output deterministic, so what you see below is exactly what the programs printed. C# snippets are .NET 10 file-based apps (dotnet run file.cs). Python snippets run on 3.12 with the standard library only. Swap the fake for a real client and the structure stays the same, which is the point: the patterns live in the code around the model, not in the model.

Prompt chaining

The idea

Split one task into fixed steps. Each model call gets the previous step's output as its input. Between steps you can put a gate: plain code that checks the output and stops the chain if it's wrong.

Release notes are a good example. Step one pulls the user-facing changes out of a commit list. Step two writes the notes. If step one finds nothing user-facing, there's no point running step two.

The old idea underneath: a pipeline, and a close cousin of Chain of Responsibility. Each link either passes the work on or stops it. The Pattern Map post on Command, Chain and Mediator covers the GoF version.

C#

// Prompt chaining: fixed steps, each model call feeds the next, with a gate between them.
// FakeModel is scripted rules, not a real API call, so the output is deterministic.
var steps = new List<Step>
{
    new("extract", c => FakeModel($"List user-facing changes, or NONE:\n{c}"),
        output => output == "NONE" ? "no user-facing changes, skip release notes" : null),
    new("draft", list => FakeModel($"Write release notes for:\n{list}"),
        output => output.Length > 80 ? $"draft is {output.Length} chars, limit 80" : null),
};

Console.WriteLine(RunChain(steps, "feat: dark mode\nchore: bump deps\nfeat: faster sync"));
Console.WriteLine(RunChain(steps, "chore: bump deps\nrefactor: logging"));

static string RunChain(List<Step> steps, string input)
{
    var current = input;
    foreach (var step in steps)
    {
        current = step.Run(current);
        // The gate is plain code. It stops the chain before a bad output reaches the next step.
        if (step.Gate(current) is string problem)
            return $"stopped at '{step.Name}': {problem}";
    }
    return $"done: {current}";
}

static string FakeModel(string prompt)
{
    if (prompt.StartsWith("List user-facing changes"))
    {
        var feats = prompt.Split('\n').Where(l => l.StartsWith("feat: ")).Select(l => "- " + l[6..]).ToList();
        return feats.Count == 0 ? "NONE" : string.Join("\n", feats);
    }
    if (prompt.StartsWith("Write release notes"))
        return prompt.Contains("dark mode") ? "New: dark mode, and sync is faster." : "Small fixes.";
    throw new InvalidOperationException("unscripted prompt");
}

record Step(string Name, Func<string, string> Run, Func<string, string?> Gate);

Python

# Prompt chaining: fixed steps, each model call feeds the next, with a gate between them.
# fake_model is scripted rules, not a real API call, so the output is deterministic.
from typing import Callable, NamedTuple, Optional


def fake_model(prompt: str) -> str:
    if prompt.startswith("List user-facing changes"):
        feats = ["- " + l[6:] for l in prompt.splitlines() if l.startswith("feat: ")]
        return "\n".join(feats) if feats else "NONE"
    if prompt.startswith("Write release notes"):
        return "New: dark mode, and sync is faster." if "dark mode" in prompt else "Small fixes."
    raise ValueError("unscripted prompt")


class Step(NamedTuple):
    name: str
    run: Callable[[str], str]
    gate: Callable[[str], Optional[str]]   # returns a problem, or None to pass


STEPS = [
    Step("extract", lambda c: fake_model(f"List user-facing changes, or NONE:\n{c}"),
         lambda out: "no user-facing changes, skip release notes" if out == "NONE" else None),
    Step("draft", lambda changes: fake_model(f"Write release notes for:\n{changes}"),
         lambda out: f"draft is {len(out)} chars, limit 80" if len(out) > 80 else None),
]


def run_chain(steps: list[Step], text: str) -> str:
    for step in steps:
        text = step.run(text)
        if (problem := step.gate(text)) is not None:
            return f"stopped at '{step.name}': {problem}"
    return f"done: {text}"


print(run_chain(STEPS, "feat: dark mode\nchore: bump deps\nfeat: faster sync"))
print(run_chain(STEPS, "chore: bump deps\nrefactor: logging"))

Both print:

done: New: dark mode, and sync is faster.
stopped at 'extract': no user-facing changes, skip release notes

Trade-off

Each step is a smaller, easier prompt, and each gate is a place to catch errors cheaply. You pay in latency (calls run one after another) and in cost (more calls). When not to use it: if one prompt already does the job reliably, a chain only adds hops. Split when you can name the step that keeps going wrong.

Routing

The idea

Classify the input first, then send it to a handler built for that kind of input. Billing questions get a prompt with the refund policy and an order lookup tool. Bug reports get a prompt that asks for steps to reproduce, and perhaps a stronger model. Everything else goes to a cheap general handler.

The old idea underneath: Strategy. The router picks one of several interchangeable handlers at run time. The classifier is often a small, fast model. The handlers can use different prompts, tools and models.

C#

// Routing: classify first, then hand the input to a specialised handler (a Strategy).
// Classify is a scripted stand-in for a cheap model call.
var routes = new Dictionary<string, IRoute>
{
    ["billing"] = new BillingRoute(),
    ["bug"] = new BugRoute(),
};
IRoute fallback = new GeneralRoute();

foreach (var ticket in new[]
{
    "I was charged twice for the yearly plan",
    "The app crashes when I export to CSV",
    "Do you have a widget for the lock screen?",
})
{
    var label = Classify(ticket);
    // Unknown labels go to the fallback. Never trust the classifier to stay inside your list.
    var route = routes.GetValueOrDefault(label, fallback);
    Console.WriteLine($"{label,-8} -> {route.Model,-17} {route.Handle(ticket)}");
}

static string Classify(string ticket) => ticket.ToLowerInvariant() switch
{
    var t when t.Contains("charged") || t.Contains("refund") => "billing",
    var t when t.Contains("crash") || t.Contains("error") => "bug",
    _ => "question",   // not a route we have: tests the fallback
};

interface IRoute
{
    string Model { get; }
    string Handle(string ticket);
}

class BillingRoute : IRoute
{
    public string Model => "claude-haiku-5-5";
    public string Handle(string t) => "prompt: refund policy + order lookup tool";
}

class BugRoute : IRoute
{
    public string Model => "claude-sonnet-5-5";
    public string Handle(string t) => "prompt: ask for device, OS and steps to reproduce";
}

class GeneralRoute : IRoute
{
    public string Model => "claude-haiku-5-5";
    public string Handle(string t) => "prompt: FAQ answers, offer a human";
}

Python

# Routing: classify first, then hand the input to a specialised handler (a Strategy).
# classify is a scripted stand-in for a cheap model call.
from dataclasses import dataclass


@dataclass(frozen=True)
class Route:
    model: str
    prompt: str


ROUTES = {
    "billing": Route("claude-haiku-5-5", "refund policy + order lookup tool"),
    "bug": Route("claude-sonnet-5-5", "ask for device, OS and steps to reproduce"),
}
FALLBACK = Route("claude-haiku-5-5", "FAQ answers, offer a human")


def classify(ticket: str) -> str:
    t = ticket.lower()
    if "charged" in t or "refund" in t:
        return "billing"
    if "crash" in t or "error" in t:
        return "bug"
    return "question"   # not a route we have: tests the fallback


for ticket in ["I was charged twice for the yearly plan",
               "The app crashes when I export to CSV",
               "Do you have a widget for the lock screen?"]:
    label = classify(ticket)
    route = ROUTES.get(label, FALLBACK)   # unknown labels go to the fallback
    print(f"{label:<8} -> {route.model:<17} prompt: {route.prompt}")

Both print:

billing  -> claude-haiku-5-5  prompt: refund policy + order lookup tool
bug      -> claude-sonnet-5-5 prompt: ask for device, OS and steps to reproduce
question -> claude-haiku-5-5  prompt: FAQ answers, offer a human

The third ticket matters most. The classifier returned a label you didn't plan for, and the code didn't crash. A real classifier will do this. Always have a fallback route.

Trade-off

Routing lets each handler stay focused, and it's the easiest way to save money: send the easy majority to a small model and keep the expensive one for the hard cases. The cost is a classification step that can be wrong. A misrouted ticket gets a confident answer to the wrong question. When not to use it: when the categories don't really need different handling. If every route ends up with the same prompt, you've added a step for nothing.

Parallelization

The idea

Run model calls at the same time instead of one after another. Anthropic names two flavours:

  • Sectioning: split a task into independent parts and run them in parallel. Checking an App Store listing for tone, claims and length are three independent checks.
  • Voting: run the same task several times and combine the answers. Three "should we approve this listing?" calls, majority wins.

The old idea underneath: fan-out/fan-in, or scatter-gather. In code it's Task.WhenAll in C# and asyncio.gather in Python.

C#

using System.Diagnostics;

// Parallelization, two flavours. The fake checks just wait, then return scripted answers.
var listing = "Track habits. The #1 habit app, guaranteed results!";
Console.WriteLine($"checking: {listing}");

// 1. Sectioning: independent checks run at the same time.
var clock = Stopwatch.StartNew();
string[] findings = await Task.WhenAll(
    FakeCheck("tone", 300, "ok"),
    FakeCheck("claims", 200, "'#1' and 'guaranteed' need proof"),
    FakeCheck("length", 100, "ok"));
clock.Stop();
foreach (var f in findings) Console.WriteLine(f);
Console.WriteLine($"took about the slowest check, not the sum: {clock.ElapsedMilliseconds < 450}");

// 2. Voting: ask the same question several times, take the majority.
string[] votes = await Task.WhenAll(
    FakeVote(0, "reject"), FakeVote(1, "approve"), FakeVote(2, "reject"));
var winner = votes.GroupBy(v => v).OrderByDescending(g => g.Count()).First();
Console.WriteLine($"votes: {string.Join(", ", votes)} -> {winner.Key} ({winner.Count()}/{votes.Length})");

static async Task<string> FakeCheck(string name, int ms, string verdict)
{
    await Task.Delay(ms);          // stands in for a model call's latency
    return $"{name,-6}: {verdict}";
}

static async Task<string> FakeVote(int sample, string scripted)
{
    await Task.Delay(50);
    return scripted;               // a real model at temperature > 0 would vary per sample
}

Python

# Parallelization, two flavours. The fake checks just sleep, then return scripted answers.
import asyncio
import time
from collections import Counter


async def fake_check(name: str, seconds: float, verdict: str) -> str:
    await asyncio.sleep(seconds)   # stands in for a model call's latency
    return f"{name:<6}: {verdict}"


async def fake_vote(sample: int, scripted: str) -> str:
    await asyncio.sleep(0.05)
    return scripted                # a real model at temperature > 0 would vary per sample


async def main():
    listing = "Track habits. The #1 habit app, guaranteed results!"
    print(f"checking: {listing}")

    # 1. Sectioning: independent checks run at the same time.
    start = time.perf_counter()
    findings = await asyncio.gather(
        fake_check("tone", 0.3, "ok"),
        fake_check("claims", 0.2, "'#1' and 'guaranteed' need proof"),
        fake_check("length", 0.1, "ok"))
    elapsed = time.perf_counter() - start
    print(*findings, sep="\n")
    print("took about the slowest check, not the sum:", elapsed < 0.45)

    # 2. Voting: ask the same question several times, take the majority.
    votes = await asyncio.gather(fake_vote(0, "reject"), fake_vote(1, "approve"),
                                 fake_vote(2, "reject"))
    label, count = Counter(votes).most_common(1)[0]
    print(f"votes: {', '.join(votes)} -> {label} ({count}/{len(votes)})")


asyncio.run(main())

Both print:

checking: Track habits. The #1 habit app, guaranteed results!
tone  : ok
claims: '#1' and 'guaranteed' need proof
length: ok
took about the slowest check, not the sum: True
votes: reject, approve, reject -> reject (2/3)

Trade-off

Sectioning cuts wall-clock time to roughly the slowest call, and each call gets a narrower prompt that tends to do better than one prompt juggling every concern. Voting buys confidence on decisions where a single sample is noisy. Both cost more tokens, and you hit rate limits faster because the calls land together. When not to use it: when the parts depend on each other (that's a chain), or when the decision is cheap to get wrong and a single call is good enough. Voting three times on a low-stakes label is just paying triple.

Orchestrator-workers

The idea

One model call (the orchestrator) looks at the task and decides what subtasks it needs. Workers do the subtasks. The orchestrator combines the results.

This looks like parallelization, but the difference is important. In parallelization, you fixed the subtasks when you wrote the code. In orchestrator-workers, the model picks them at run time, based on the input. "Add export to CSV" needs model, UI and test changes. "Fix a typo" needs a docs change. You couldn't hard-code both.

The old idea underneath: Mediator. Workers never talk to each other. Everything goes through the orchestrator, which owns the plan and the combined result. The Pattern Map post has the GoF version and makes the same connection.

C#

// Orchestrator-workers: the orchestrator plans at run time, delegates, then combines.
// Workers never call each other; everything goes through the orchestrator (a Mediator).
// FakePlanner and the workers are scripted stand-ins for model calls.
var orchestrator = new Orchestrator(new Dictionary<string, Func<string, string>>
{
    ["model"] = task => $"[model] added field for '{task}'",
    ["ui"] = task => $"[ui] added button for '{task}'",
    ["tests"] = task => $"[tests] 3 tests for '{task}'",
    ["docs"] = task => $"[docs] updated help page for '{task}'",
});

Console.WriteLine(orchestrator.Run("Add export to CSV"));
Console.WriteLine();
Console.WriteLine(orchestrator.Run("Fix typo in onboarding"));

class Orchestrator(Dictionary<string, Func<string, string>> workers)
{
    public string Run(string request)
    {
        var plan = FakePlanner(request);   // the subtasks are decided now, not in advance
        Console.WriteLine($"plan for '{request}': {string.Join(", ", plan.Select(p => p.Worker))}");

        var results = new List<string>();
        foreach (var (worker, task) in plan)
        {
            if (!workers.TryGetValue(worker, out var run))
            {
                results.Add($"[skipped] no worker called '{worker}'");
                continue;
            }
            results.Add(run(task));
        }
        return string.Join("\n", results);   // a real orchestrator would ask the model to synthesize
    }

    static List<(string Worker, string Task)> FakePlanner(string request) =>
        request.Contains("export", StringComparison.OrdinalIgnoreCase)
            ? [("model", "csv export"), ("ui", "Export button"), ("tests", "csv export")]
            : [("docs", request), ("deploy", request)];   // 'deploy' doesn't exist
}

Python

# Orchestrator-workers: the orchestrator plans at run time, delegates, then combines.
# Workers never call each other; everything goes through the orchestrator (a Mediator).
# fake_planner and the workers are scripted stand-ins for model calls.
from typing import Callable

WORKERS: dict[str, Callable[[str], str]] = {
    "model": lambda task: f"[model] added field for '{task}'",
    "ui": lambda task: f"[ui] added button for '{task}'",
    "tests": lambda task: f"[tests] 3 tests for '{task}'",
    "docs": lambda task: f"[docs] updated help page for '{task}'",
}


def fake_planner(request: str) -> list[tuple[str, str]]:
    if "export" in request.lower():
        return [("model", "csv export"), ("ui", "Export button"), ("tests", "csv export")]
    return [("docs", request), ("deploy", request)]   # 'deploy' doesn't exist


def orchestrate(request: str) -> str:
    plan = fake_planner(request)   # the subtasks are decided now, not in advance
    print(f"plan for '{request}': {', '.join(w for w, _ in plan)}")
    results = []
    for worker, task in plan:
        run = WORKERS.get(worker)
        results.append(run(task) if run else f"[skipped] no worker called '{worker}'")
    return "\n".join(results)   # a real orchestrator would ask the model to synthesize


print(orchestrate("Add export to CSV"))
print()
print(orchestrate("Fix typo in onboarding"))

Both print:

plan for 'Add export to CSV': model, ui, tests
[model] added field for 'csv export'
[ui] added button for 'Export button'
[tests] 3 tests for 'csv export'

plan for 'Fix typo in onboarding': docs, deploy
[docs] updated help page for 'Fix typo in onboarding'
[skipped] no worker called 'deploy'

Notice the second plan. The planner asked for a deploy worker that doesn't exist. Plans come from a model, so treat them as untrusted input: check every step against the workers you actually have, and refuse what isn't there.

Trade-off

You get flexibility: one system handles tasks whose shape you can't predict. You lose predictability. Two similar requests can produce different plans, which makes testing and cost estimation harder. When not to use it: when the subtasks are the same every time. Then a fixed chain or a parallel fan-out is cheaper, faster and much easier to debug.

Evaluator-optimizer

The idea

One call generates a draft. Another call (or plain code) evaluates it and returns feedback. The feedback goes into the next draft. Loop until the draft passes, or until you run out of rounds.

It works best when you can state clear criteria and when feedback actually helps. Push notification copy is a good fit: a length limit, a tone rule and "name the habit" are all easy to check and easy to act on.

The old idea underneath: Template Method for the fixed loop, with Strategy for the generator and evaluator. The Pattern Map post builds this same loop as a Template Method subclass in C# and as passed-in functions in Python. Here both languages pass functions.

C#

// Evaluator-optimizer: one call generates, another critiques, loop until it passes or we give up.
// Both "models" are scripted so the run is repeatable.
string[] drafts =
[
    "Don't lose your streak!!! Open the app NOW",
    "Your 30-day streak ends at midnight",
    "Keep your 30-day reading streak alive",
];

var result = Optimize(maxRounds: 3,
    generate: (round, feedback) => drafts[round - 1],
    evaluate: FakeJudge);
Console.WriteLine(result);
Console.WriteLine(Optimize(3, (round, feedback) => drafts[0], FakeJudge));   // never improves

static string Optimize(int maxRounds, Func<int, string?, string> generate, Func<string, Verdict> evaluate)
{
    string? feedback = null;
    for (var round = 1; round <= maxRounds; round++)
    {
        var draft = generate(round, feedback);
        var verdict = evaluate(draft);
        Console.WriteLine($"round {round}: \"{draft}\" -> {(verdict.Pass ? "pass" : verdict.Feedback)}");
        if (verdict.Pass) return $"ship: {draft}";
        feedback = verdict.Feedback;   // the critique goes into the next generation prompt
    }
    return "gave up: send to a human";   // the round limit is the stop condition
}

static Verdict FakeJudge(string draft)
{
    // Plain-code checks first: they're free and never wrong.
    if (draft.Length > 40) return new(false, $"{draft.Length} chars, limit is 40");
    if (draft.Contains("!!!") || draft.Contains("NOW")) return new(false, "too pushy");
    // A real judge model would score tone here. Scripted: it wants the habit named.
    if (!draft.Contains("reading")) return new(false, "name the habit");
    return new(true, "");
}

record Verdict(bool Pass, string Feedback);

Python

# Evaluator-optimizer: one call generates, another critiques, loop until it passes or we give up.
# Both "models" are scripted so the run is repeatable.
from typing import Callable, NamedTuple, Optional


class Verdict(NamedTuple):
    passed: bool
    feedback: str = ""


DRAFTS = ["Don't lose your streak!!! Open the app NOW",
          "Your 30-day streak ends at midnight",
          "Keep your 30-day reading streak alive"]


def fake_judge(draft: str) -> Verdict:
    # Plain-code checks first: they're free and never wrong.
    if len(draft) > 40:
        return Verdict(False, f"{len(draft)} chars, limit is 40")
    if "!!!" in draft or "NOW" in draft:
        return Verdict(False, "too pushy")
    # A real judge model would score tone here. Scripted: it wants the habit named.
    if "reading" not in draft:
        return Verdict(False, "name the habit")
    return Verdict(True)


def optimize(generate: Callable[[int, Optional[str]], str],
             evaluate: Callable[[str], Verdict], max_rounds: int = 3) -> str:
    feedback = None
    for round_no in range(1, max_rounds + 1):
        draft = generate(round_no, feedback)
        verdict = evaluate(draft)
        print(f'round {round_no}: "{draft}" -> {"pass" if verdict.passed else verdict.feedback}')
        if verdict.passed:
            return f"ship: {draft}"
        feedback = verdict.feedback   # the critique goes into the next generation prompt
    return "gave up: send to a human"   # the round limit is the stop condition


print(optimize(lambda n, fb: DRAFTS[n - 1], fake_judge))
print(optimize(lambda n, fb: DRAFTS[0], fake_judge))   # a generator that never improves

Both print:

round 1: "Don't lose your streak!!! Open the app NOW" -> 42 chars, limit is 40
round 2: "Your 30-day streak ends at midnight" -> name the habit
round 3: "Keep your 30-day reading streak alive" -> pass
ship: Keep your 30-day reading streak alive
round 1: "Don't lose your streak!!! Open the app NOW" -> 42 chars, limit is 40
round 2: "Don't lose your streak!!! Open the app NOW" -> 42 chars, limit is 40
round 3: "Don't lose your streak!!! Open the app NOW" -> 42 chars, limit is 40
gave up: send to a human

The second run is the one to remember. The generator never improves, and the loop ends after three rounds with a clear "send to a human" instead of spinning forever. Put the cheap code checks before the model judge, too: a length check is free and never hallucinates.

Trade-off

You get measurably better output on tasks with clear criteria. You pay for at least two calls per round, and a model judge has its own blind spots. Two models can happily agree on something wrong. When not to use it: when you can't write the criteria down. If the evaluator can't say what's wrong, the generator can't fix it, and the loop just burns rounds.

The agent loop

The idea

Give the model a goal and a set of tools. It picks a tool, your code runs it, the result goes back to the model, and it picks again. It stops when the model says it's done.

That last sentence is the dangerous one. "When the model says it's done" is not a stop condition you control. A real agent loop needs at least two more:

  • A step limit. The model might keep calling the same tool forever.
  • A budget. Tokens, money or wall-clock time. Long runs get expensive quietly.

The old idea underneath: each tool call is a Command: a request turned into an object that your loop can log, approve, refuse or retry. The loop is the invoker. The tiny coding agent I wrote about earlier is this same loop with file and shell tools.

C#

// Agent loop: the model picks the next tool call until it says it's done.
// The loop owns the stop conditions: a step limit and a token budget.
// The "model" replays a script of turns. No network.
var tools = new Dictionary<string, Func<string, string>>
{
    ["lookup_order"] = id => $"order {id}: yearly plan, charged twice on Oct 3",
    ["check_policy"] = _ => "duplicate charges are refunded in full",
};

ModelTurn[] solves =
[
    new("tool_use", "lookup_order", "A-1042", 900),
    new("tool_use", "check_policy", "duplicate", 700),
    new("end_turn", null, "You were charged twice. A full refund is on its way.", 400),
];
ModelTurn[] wanders = Enumerable.Repeat(new ModelTurn("tool_use", "lookup_order", "A-1042", 600), 10).ToArray();
ModelTurn[] rambles = [new("tool_use", "check_policy", "x", 2500), new("tool_use", "check_policy", "x", 2500)];

Console.WriteLine(RunAgent(solves, tools));
Console.WriteLine(RunAgent(wanders, tools));
Console.WriteLine(RunAgent(rambles, tools));

static string RunAgent(ModelTurn[] script, Dictionary<string, Func<string, string>> tools,
                       int maxSteps = 5, int tokenBudget = 4000)
{
    var tokens = 0;
    for (var step = 1; step <= maxSteps; step++)
    {
        var turn = script[step - 1];              // stand-in for a model call with the history so far
        tokens += turn.Tokens;
        if (tokens > tokenBudget) return $"stopped: token budget ({tokens}/{tokenBudget}) at step {step}";
        if (turn.StopReason == "end_turn") return $"done in {step} steps, {tokens} tokens: {turn.Input}";

        // The tool call is a Command: the loop decides whether and how to run it.
        var result = tools.TryGetValue(turn.Tool!, out var run) ? run(turn.Input) : $"error: no tool {turn.Tool}";
        Console.WriteLine($"  step {step}: {turn.Tool}({turn.Input}) -> {result}");
        // A real loop appends the tool_result to the history here.
    }
    return $"stopped: hit {maxSteps} steps without finishing";
}

record ModelTurn(string StopReason, string? Tool, string Input, int Tokens);

Python

# Agent loop: the model picks the next tool call until it says it's done.
# The loop owns the stop conditions: a step limit and a token budget.
# The "model" replays a script of turns. No network.
from typing import NamedTuple, Optional

TOOLS = {
    "lookup_order": lambda order_id: f"order {order_id}: yearly plan, charged twice on Oct 3",
    "check_policy": lambda _: "duplicate charges are refunded in full",
}


class Turn(NamedTuple):
    stop_reason: str
    tool: Optional[str]
    input: str
    tokens: int


def run_agent(script: list[Turn], max_steps: int = 5, token_budget: int = 4000) -> str:
    tokens = 0
    for step in range(1, max_steps + 1):
        turn = script[step - 1]   # stand-in for a model call with the history so far
        tokens += turn.tokens
        if tokens > token_budget:
            return f"stopped: token budget ({tokens}/{token_budget}) at step {step}"
        if turn.stop_reason == "end_turn":
            return f"done in {step} steps, {tokens} tokens: {turn.input}"
        # The tool call is a Command: the loop decides whether and how to run it.
        tool = TOOLS.get(turn.tool)
        result = tool(turn.input) if tool else f"error: no tool {turn.tool}"
        print(f"  step {step}: {turn.tool}({turn.input}) -> {result}")
        # A real loop appends the tool_result to the history here.
    return f"stopped: hit {max_steps} steps without finishing"


solves = [Turn("tool_use", "lookup_order", "A-1042", 900),
          Turn("tool_use", "check_policy", "duplicate", 700),
          Turn("end_turn", None, "You were charged twice. A full refund is on its way.", 400)]
wanders = [Turn("tool_use", "lookup_order", "A-1042", 600)] * 10
rambles = [Turn("tool_use", "check_policy", "x", 2500)] * 2

print(run_agent(solves))
print(run_agent(wanders))
print(run_agent(rambles))

Both print:

  step 1: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
  step 2: check_policy(duplicate) -> duplicate charges are refunded in full
done in 3 steps, 2000 tokens: You were charged twice. A full refund is on its way.
  step 1: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
  step 2: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
  step 3: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
  step 4: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
  step 5: lookup_order(A-1042) -> order A-1042: yearly plan, charged twice on Oct 3
stopped: hit 5 steps without finishing
  step 1: check_policy(x) -> duplicate charges are refunded in full
stopped: token budget (5000/4000) at step 2

Three runs, three different endings. The first finishes on its own. The second wanders and hits the step limit. The third burns through the token budget in two steps. In each case the loop, not the model, had the last word.

Trade-off

An agent can solve open-ended problems that no fixed workflow can, because it decides the path as it learns. You pay with cost, latency and unpredictability, and errors compound: a wrong step early sends every later step the wrong way. Anthropic's advice is to use agents for open-ended tasks where you can't predict the steps, and to test them heavily in a sandbox first. When not to use it: whenever you can draw the flowchart. If you know the steps, write them down as a workflow. The agent framework security issues covered in The Decode are another reason to keep the tool list short and the loop strict.

Picking one

You know...Reach for
The exact steps, in orderPrompt chaining
The categories of input, each needing different handlingRouting
Independent subtasks, or a decision worth sampling more than onceParallelization
That subtasks exist, but not which ones until you see the inputOrchestrator-workers
Clear criteria the output must meetEvaluator-optimizer
Only the goalAgent loop, with a step limit and a budget

Read the table top to bottom and you're reading it in order of increasing cost and decreasing predictability. Start at the top. Move down only when the row above fails.

Check yourself: questions and answers

What's the difference between a workflow and an agent?

In a workflow, your code decides the sequence of steps and calls the model at fixed points. In an agent, the model decides the next step, usually by choosing a tool, in a loop. Workflows are more predictable and cheaper. Agents handle problems where you can't predict the steps.

Parallelization and orchestrator-workers both run several model calls. How do they differ?

In parallelization, the subtasks are fixed when you write the code. In orchestrator-workers, a model decides the subtasks at run time based on the input. If you can list the subtasks in advance, you don't need an orchestrator.

Which GoF pattern sits under routing, and why does it matter?

Strategy. The router picks one of several interchangeable handlers. Thinking of it that way pushes you to give every handler the same interface and to always have a default, which is what saves you when the classifier returns a label you didn't expect.

What stop conditions does an agent loop need?

The model's own "I'm done", plus a hard step limit and a budget in tokens, money or time. I'd also stop on repeated identical tool calls. The model's stop signal is a hint. The limits are the guarantee.

When would you not use evaluator-optimizer?

When you can't write down what "good" means. The loop only converges if the evaluator gives specific, actionable feedback. Vague criteria give vague feedback, and you pay for rounds that don't improve anything.

Why treat an orchestrator's plan as untrusted input?

Because it came from a model. It can ask for workers that don't exist, steps in the wrong order, or actions you never meant to allow. Validate every step against what you actually support, the same way you'd validate a request from a client.

Further reading

  • Anthropic, Building effective agents, the source of every workflow name in this post
  • Anthropic, Effective context engineering for AI agents, on keeping long agent runs focused
  • Anthropic, Writing effective tools for agents, for the tool side of the agent loop
  • Anthropic docs, Tool use overview, for the real tool_use and tool_result round trip the fake model imitates
  • Microsoft Learn, Cloud design patterns, for the messaging and resilience patterns these workflows lean on
  • The Pattern Map: Command, Chain of Responsibility, Mediator and Template Method and State, Iterator, Memento, Visitor and Interpreter
  • My earlier posts: a 300-line coding agent for local models and Loop engineering

Previous in the series: AI: reliable output. Next: AI in production, where these loops meet MCP, gateways, guardrails and crashes.

← Previous

Caching in Depth, Part 2: Frontend or Backend? Every Layer, with Examples You Can Use

Next →

Command, Chain of Responsibility, Mediator and Template Method in the Agent Era

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.