Workflows and agents: building blocks for agentic systems

Some systems follow a path your code fixed in advance. Others let the model choose its own steps. Knowing which is which, and building up from the simplest piece, is most of the craft.

Workflows and agents in 60 seconds

  • Workflow: the model and tools run along paths that your code fixed in advance. Agent: the model decides its own steps and which tools to use.
  • Start small: one well-prepared model call, with retrieval and good examples, is enough for many products.
  • Add steps only when they measurably help: every step costs latency and money, and errors compound.
  • Five workflow patterns: prompt chaining, routing, parallelisation, orchestrator and workers, and evaluator and optimiser.
  • Agents: a simple loop that takes an action, reads real feedback from the environment, and stops on success or on a limit. The tools and their documentation matter more than the loop.

The problem it solves

Teams often ask whether they need an agent when they are really asking how much freedom to give a model. The answer is a dial, not a switch. At one end sits a single call with a fixed prompt. At the other sits a loop where the model plans, acts and decides when it is finished. The skill is picking the lowest setting that does the job.

Two words help. A workflow is a system where the sequence of model calls and tool calls is written in code. You can draw it before it runs. An agent is a system where the model chooses the sequence at run time. You can only draw it after the fact, from the trace.

Start with the simplest thing

Before any pattern, ask whether one call will do. A single call with a clear prompt, a few good examples and retrieved context solves a surprising number of real tasks. Every extra step buys some quality and pays for it in seconds and money. That trade is only worth making when you can show the gain on your own evaluation set, and not before.

Frameworks can speed up the first week. They also tend to hide the exact prompts and responses, which slows debugging and makes extra layers feel free. Begin with direct calls to the model interface. If you adopt a framework later, read what it does underneath.

The building block: an augmented model

Every pattern below is made from one unit: a model that has been given retrieval, tools and memory. The model can write its own search queries, pick a tool, and decide what to keep. What makes the unit reliable is the interface to each of those, which should be narrow, documented and tested. See tool calling and MCP and working memory.

The basic unit is a model that can search, call tools and keep memory through clear interfaces.

Workflow patterns

Workflows are the predictable end of the dial. You pay for structure up front, and in return you get steady behaviour, easy testing and cheaper models for each step.

Prompt chaining

A chain splits a task into fixed steps, and each call handles the output of the last. Each call has an easier job, so accuracy goes up, and latency goes up with it. Between steps you can put a gate, which is a programmatic check that decides whether to carry on. A good gate is cheap and deterministic: does the draft parse, is it under the length limit, does every citation point to a real source. Only fall back on a model as a gate when no rule can express the check. See pipeline.

Routing

A router classifies the input and sends it to a specialised prompt, tool set or model. A common use is sending easy questions to a small, cheap model and hard ones to a strong model. Routing only works if classification is accurate, so give the classifier a confidence score, set a threshold, and define a safe default route for anything below it. The default route should be the most capable and cautious path, not the cheapest. See router.

A chain adds gates between fixed steps, and a router sends each input to the handler that suits it.

Parallelisation

Parallel work comes in two flavours. In sectioning, independent sub-tasks run at the same time and their results are merged. A typical case is one call that answers the user while another screens the request against policy, so the screen adds no waiting time. In voting, the same task runs several times and the answers are combined, which suits checks where you want confidence, such as reviewing code for a weakness.

Voting needs two numbers: how many votes, and how many must agree. If one vote wrongly flags a safe item 10 percent of the time, three votes with a two out of three rule wrongly flag it about 2.8 percent of the time. A stricter rule of three out of three lowers false flags to 0.1 percent but will miss more real problems. Pick the threshold by the cost of each kind of error, then measure it. See parallel fan-out.

Orchestrator and workers

Here a central model reads the task, decides at run time what sub-tasks exist, hands them to workers and combines the results. It looks like parallelisation, but the difference matters: the sub-tasks are not known in advance. A change that touches an unknown number of files is a fair example. Because the orchestrator can create work, it needs budgets: a maximum number of workers per task, a maximum depth so that workers cannot spawn more workers, and a cap on total tokens. See supervisor with workers.

Evaluator and optimiser

One call drafts, another critiques against stated criteria, and the draft is revised in a loop. It fits when feedback measurably improves the result and the model can give that feedback, as in translation with a style guide. Critics drift: after a few rounds they invent faults, so cap rounds at two or three, and give the critic criteria it can check. See critic loop.

An orchestrator creates work at run time, and an evaluator loop refines a draft until it passes or runs out of rounds.

Agents

An agent begins with a command or a conversation with a person. Once the task is clear, it plans and acts on its own. At every step it gets ground truth from the environment: a tool result, a test run, a page it has fetched. That feedback is what keeps it honest. It can pause at a checkpoint or when blocked to ask a person, and it stops when the work is done or when it hits a step limit.

An agent acts, reads real feedback, and repeats until it succeeds, is blocked, or reaches its step limit.

The loop itself is small, often a few dozen lines. What decides success is the toolset and how well the tools are documented, because the model can only use what it understands. Agents also cost more than workflows, and their errors compound: a small mistake at step three shapes steps four to twenty. So test them in a sandbox with guardrails, and keep their autonomy proportional to the cost of a wrong action. See single agent and human checkpoint.

Three principles carry across all of this. Keep the design simple. Make planning visible, so a person can read what the system intends to do. And invest in the interface between agent and tools, by writing the documentation and testing it as carefully as you would a public interface.

A worked example

Acme Retail has a support assistant that answers refund questions. The single-call version takes 3 seconds, costs 0.4 pence per request and gets 82 percent of 500 test cases right. The team tries a three-step chain: classify the question, draft a reply from the policy text, then check the reply against the policy. Each step takes about 2 seconds with a smaller model, so the total is 6 seconds and 0.9 pence. Accuracy rises to 91 percent.

  • Cost of the gain: 9 points of accuracy for 3 extra seconds and 0.5 pence. At 200,000 requests a month, that is 1,000 pounds extra, and it removes roughly 18,000 wrong answers.
  • Gate: a deterministic check that the reply names a refund window that exists in the policy. It catches 40 percent of the bad drafts for no model cost.
  • Routing: 70 percent of questions are plain order-status queries. Sending them to the one-call path brings the average cost down to 0.6 pence and the average wait to 4.2 seconds.
  • Agent trial: for the 5 percent of cases that need account lookups and a refund action, the team allows an agent with a limit of 8 steps. It resolves 74 percent of them, at an average of 14 seconds and 6 pence, so a person approves each refund over 50 pounds.
  • Result: a router, a chain and a limited agent, each justified by a number.

Building it

A minimal agent loop with explicit limits and a step log (illustrative) (python)
MAX_STEPS = 8            # hard stop on the number of actions
MAX_TOKENS_TOTAL = 40_000  # budget across the whole run
APPROVAL_LIMIT_GBP = 50  # refunds above this need a person

def run_agent(task: str, tools: dict, log) -> dict:
    history = [{"role": "user", "content": task}]
    spent = 0

    for step in range(1, MAX_STEPS + 1):
        # Placeholder: the model returns either a tool request or a final answer.
        reply = llm.next_action(history, tool_specs=[t.spec for t in tools.values()])
        spent += reply.tokens_used
        log.record(step=step, action=reply.action, args=reply.args)  # enables replay

        if spent > MAX_TOKENS_TOTAL:
            return {"status": "stopped", "reason": "token budget"}
        if reply.action == "finish":
            return {"status": "done", "answer": reply.args["answer"]}

        tool = tools.get(reply.action)
        if tool is None:
            history.append({"role": "tool", "content": "Unknown tool. Choose from: " + ", ".join(tools)})
            continue

        # Gate: a deterministic rule decides whether a person must approve.
        if reply.action == "refund" and reply.args.get("amount_gbp", 0) > APPROVAL_LIMIT_GBP:
            return {"status": "needs_approval", "proposed": reply.args}

        result = tool.run(**reply.args)   # real feedback from the environment
        history.append({"role": "tool", "content": str(result)[:2000]})  # cap output size

    return {"status": "stopped", "reason": "step limit"}

llm, tools and log are placeholders. The loop has three exits besides success: a step limit, a token budget and an approval gate. Every action is logged, so a failed run can be replayed step by step.

Moving from a workflow to an agent, gradually

Do not rewrite a working workflow as an agent in one go. Keep the workflow as the default and place the agent behind a feature flag for a slice of traffic. Let it handle only the branch where the workflow gives up, such as cases that previously went to a human. Compare resolution rate, cost and complaints between the two paths. If the agent wins, widen it.

Design decisions

  • Entry point: begin with a single call. Move along the dial only when a measured failure cannot be fixed at the current setting. The matrix below shows the usual order.
  • Gates over judges: use cheap deterministic checks between steps. Reserve model-based checks for what rules cannot express.
  • Routing safety: define a confidence threshold and a safe default route, and log every input that falls to the default.
  • Budgets: every orchestrator needs a maximum worker count, a maximum depth and a token cap. Every agent needs a step limit.
  • Refinement cap: limit evaluator loops to two or three rounds and keep the criteria checkable.
  • Replay: log each step with its inputs, outputs and tool results, so you can replay a run and compare versions.
  • Human placement: add approval where an action is costly or cannot be undone. See critic loop for review shaped as a pattern.

Measuring it

  • Task success by pattern: run the same labelled cases through one call, a chain, a router and an agent, and compare accuracy.
  • Cost and latency: tokens and seconds per request, at the mean and the 95th percentile, per pattern.
  • Gate catch rate: the share of bad drafts stopped by each gate, and how many good drafts it wrongly stopped.
  • Routing accuracy: the share of inputs sent to the right route, and the share that fall to the default.
  • Vote agreement: how often voters disagree. High disagreement points to an unclear task.
  • Agent trace metrics: steps per task, repeated tool calls, tool errors, and the share of runs that end at the step limit.
  • Held-out set: keep some cases unseen while you tune.

When to use it, and when not to

SituationChooseWhy
One well-defined task with good examplesSingle call with retrievalFastest and cheapest. Add steps only if tests show a gap.
Task splits cleanly into fixed stepsPrompt chainEach step is easier, and gates catch errors early. See pipeline.
Mixed inputs with different needsRouterSend easy cases to cheap paths and hard ones to strong paths. See router.
Independent checks or a need for confidenceParallel sections or votingSaves time or lowers error. See parallel fan-out.
Sub-tasks unknown until run timeOrchestrator and workersThe model decides the plan, within budgets.
Clear criteria and feedback that improves outputEvaluator and optimiserWorth it only when each round measurably helps.
Open-ended work with real feedback from toolsAgentNeeds sandboxes, limits and review. See single agent.

Trade-offs

DimensionEffectWhat to do about it
QualityMore steps and feedback usually raise accuracy on hard tasks.Measure on your own cases and stop adding steps when gains flatten.
LatencyChains add the time of every step. Agents add a variable number of steps.Run independent work in parallel, cap steps and use smaller models for easy stages.
CostSpend grows with calls, and agent runs vary a lot in length.Route simple cases cheaply and set a budget per run.
PredictabilityWorkflows behave steadily. Agents can surprise you.Use workflows for regulated steps and agents where flexibility pays.

Choosing between them

Read the table above as a ladder. Known steps and uniform input mean a single call or a chain. Varied input adds a router. Unknown steps within bounded work call for an orchestrator with budgets. A path that depends on what the environment returns, with progress you can verify, calls for an agent. Each rung buys flexibility and spends predictability.

Good early fits for agents are customer support, where success is a resolved case, and coding, where tests can check the work. A person should still review what ships. See the orchestration hub and agent types.

What this means for your role

Common mistakes

Further reading

Start with one call, add structure where the numbers ask for it, and give a model more freedom only when you can verify its work. The best agentic systems are mostly ordinary code with a few well-chosen places where the model decides.

Search topics

↑↓ to move · Enter to open · Esc to close