Build guide8 min read

Agentic workflow architecture: plan, act, evaluate, adapt

A good agentic workflow architecture is a loop with a contract: the model plans, calls tools, gets its output checked by something it can't argue with, and adapts until the check passes or a budget runs out. The loop is the easy part. The architecture is everything around it: typed state, an evaluator that sits outside the model, hard stopping rules and an escalation path that is a designed outcome rather than a crash.

Most explanations stop at the loop diagram. This guide covers the parts that decide whether an agent survives production, with code you can lift, and a decision rule for when you shouldn't build an agent at all.

Agent or pipeline: decide this first

Anthropic's widely cited guide draws the line cleanly. A workflow runs LLM calls and tools along code paths you wrote in advance; an agent decides its own next step and tool use at runtime. Their advice is to start with the simplest thing that works and only reach for an agent when the number of steps can't be predicted up front.

I use three questions before choosing:

Question If yes If no
Can I write the steps down before the input arrives? Fixed pipeline Consider an agent
Can a machine check the output cheaply? An agent can self-correct Keep a human in the loop on every run
Is a wrong step reversible inside the run? Let the agent retry Gate the step behind an approval

A release pipeline with screenshot checks, review routing and approval-gated deploys, like the localization pipeline I built at Netflix, has steps you can write down in advance. It doesn't need runtime planning; it needs good gates. Mentova is the opposite case. Every uploaded chart is a different trade with a different sequence of key moments, so the number and kind of scenes can't be known until the chart has been read. That is the shape of problem where an agent earns its extra cost and latency.

The second question matters most. An agent without a reliable check is a loop that rephrases its own mistakes. If you can't build the evaluator, build the pipeline.

The core loop of an agentic workflow architecture

The loop has four stages, and each one owns a different kind of state.

pass

fail, budget left

fail, budget spent

Input and goal

Plan: ordered steps with success criteria

Act: call tools, store artifacts

Evaluate: deterministic checks, then model judge

Done: ship or hand to review

Adapt: feed failures back into the plan

Escalate to a human with the full trace

Log the trajectory and outcome

Plan. The model turns the goal into an ordered list of steps, each with a success criterion you can check later. Writing criteria at plan time is the single habit that makes the evaluate stage tractable, because the evaluator then checks the plan's own promises instead of guessing what "good" means.

Act. Tools do the work and write artifacts to storage you control. The model gets back a compact observation, not the whole artifact. This is the reason-then-act interleaving described in the ReAct paper, and it keeps the context small as runs get longer.

Evaluate. Something outside the generating call decides whether the step passed. Cheap deterministic checks run first; a model judge runs only on what they can't decide.

Adapt. Failures go back into planning as structured feedback, not as "try again". The Reflexion paper showed that verbal feedback about what went wrong helps an agent on its next attempt. In production the useful version is narrower: a list of failed checks with the evidence for each.

Typed state and a budgeted loop

The loop below is provider-agnostic on purpose. plan, act and evaluate are injected, so you can back them with any model API, and unit-test the control flow with stubs.

type Step = { id: string; instruction: string; criteria: string[] };
type Failure = { stepId: string; check: string; evidence: string };
type Verdict = { pass: boolean; failures: Failure[] };

interface Budget { maxIterations: number; maxCostUsd: number }

interface Deps<A> {
  plan: (goal: string, feedback: Failure[]) => Promise<Step[]>;
  act: (step: Step) => Promise<{ artifact: A; costUsd: number }>;
  evaluate: (steps: Step[], artifacts: A[]) => Promise<Verdict>;
}

type Outcome<A> =
  | { status: 'done'; artifacts: A[]; iterations: number; costUsd: number }
  | { status: 'escalated'; reason: string; failures: Failure[]; costUsd: number };

export async function runAgent<A>(goal: string, deps: Deps<A>, budget: Budget): Promise<Outcome<A>> {
  let feedback: Failure[] = [];
  let costUsd = 0;
  for (let i = 1; i <= budget.maxIterations; i++) {
    const steps = await deps.plan(goal, feedback);
    const artifacts: A[] = [];
    for (const step of steps) {
      const { artifact, costUsd: c } = await deps.act(step);
      costUsd += c;
      if (costUsd > budget.maxCostUsd) {
        return { status: 'escalated', reason: 'cost budget spent', failures: feedback, costUsd };
      }
      artifacts.push(artifact);
    }
    const verdict = await deps.evaluate(steps, artifacts);
    if (verdict.pass) return { status: 'done', artifacts, iterations: i, costUsd };
    feedback = verdict.failures;
  }
  return { status: 'escalated', reason: 'iteration budget spent', failures: feedback, costUsd };
}

Three details carry most of the weight. The budget is checked inside the act loop, not once per iteration, so one expensive plan can't overspend. Escalation returns the last failures, so the human who picks it up starts from evidence. And the return type forces every caller to handle both outcomes, which is how escalation becomes a feature instead of an exception.

For long runs, persist the state after every step. In Mentova the agent runs inside authenticated, stateful async order processing with scheduled orchestration and persistent tracking, from upload to inbox. A run that can resume from its last stored step survives deploys and worker restarts; a run held only in memory doesn't.

Build the evaluator before the agent

The evaluator is the part I'd spend the most time on. Order it from cheapest and most certain to most expensive and least certain.

from dataclasses import dataclass
from typing import Callable, Optional

@dataclass
class Failure:
    check: str
    evidence: str

Check = Callable[[dict], Optional[Failure]]

def evaluate(artifact: dict, rules: list[Check],
             judge: Callable[[dict], list[Failure]]) -> list[Failure]:
    """Deterministic rules first; the model judge only sees what they pass."""
    failures = [f for rule in rules if (f := rule(artifact)) is not None]
    if failures:
        return failures  # don't pay for a judge call on a known failure
    return judge(artifact)

def has_duration(max_s: float) -> Check:
    def check(a: dict) -> Optional[Failure]:
        d = a.get("duration_s")
        if d is None or d > max_s:
            return Failure("duration", f"got {d}, limit {max_s}")
        return None
    return check

print(evaluate({"duration_s": 95.0}, [has_duration(60.0)], lambda a: []))

Deterministic checks are fast, free and never disagree with themselves: schema validity, required fields, lengths, durations, whether a referenced file exists. A model judge is for the questions code can't answer, such as whether a scene actually explains the step it was planned for. Keep the judge's rubric tied to the success criteria written at plan time, and calibrate it against human labels before you trust it to gate anything.

Trading Guard's Research Lab uses the same layering: deterministic rule checks, labeled examples, blind historical replay and an LLM-as-a-judge comparison against the trader's rulebook. The judge is one layer of evidence, never the only one.

Failure modes and the guard for each

Failure What it looks like Guard
Runaway loop The same plan fails the same check every iteration Iteration cap; escalate when two verdicts list identical failures
Cost blowout A plan with many expensive tool calls Per-run cost budget checked per step
Judge drift Pass rate climbs while human spot checks get worse Track judge-versus-human agreement on a sample
Context bloat Each iteration resends every artifact Return compact observations; store artifacts outside the prompt
Tool misuse Wrong arguments, relative paths, silent errors Strict argument schemas and error messages the model can act on
Untrusted input Instructions hidden inside uploaded content Treat tool output as data; gate irreversible actions behind approval

The tool-misuse row deserves more attention than it gets. Anthropic's guide argues for spending as much effort on the agent-computer interface as on a human interface, and gives the example of switching a coding agent to absolute file paths to remove a class of errors. Google Cloud's guide makes a related point about security: content an agent reads can carry instructions, so the reasoning step should be isolated from the actions it can take, with human review on anything high-stakes or irreversible.

How to evaluate the whole agentic workflow

Grading the final answer isn't enough. Record the trajectory of every run (the plan, each tool call, each verdict) and measure at two levels.

  • Outcome: did the run end in done, and did a human reviewer accept the result?
  • Trajectory: how many iterations it took, which checks failed most, how often it escalated, and the cost and wall-clock time per accepted result.

Cost per accepted result is the number I watch most. An agent that passes on its third iteration can still be worth it; one that burns its full budget and escalates half the time is a pipeline in disguise, and an expensive one.

Close the loop at the system level too. Mentova's evaluation harness aggregates failed generations and lessons learned and applies improvements to the pipeline every week, and every clip passes automated checks and owner review before it ships. The runtime loop fixes one run; the weekly loop fixes the agent. You want both, and they're different systems with different owners.

What I'd build first

If I were starting an agentic workflow from scratch tomorrow, I'd build in this order:

  1. The evaluator, with deterministic checks and a small labeled set of good and bad outputs.
  2. A fixed pipeline that passes the evaluator on easy inputs.
  3. The plan and adapt stages, only for the inputs the pipeline fails.
  4. Trajectory logging and the cost-per-accepted-result metric.
  5. The weekly review that turns repeated failures into new checks or better tools.

That order keeps the agent honest. Every bit of autonomy you add has to beat a baseline you've already measured, against a check that already exists.

Sources

  1. Building effective agents (Anthropic)anthropic.com
  2. Agentic workflow patterns (AWS Prescriptive Guidance)docs.aws.amazon.com
  3. What are agentic workflows? (Google Cloud)cloud.google.com
  4. Design Patterns for Building Agentic Workflows (Hugging Face community blog)huggingface.co
  5. ReAct: Synergizing Reasoning and Acting in Language Models (arXiv)arxiv.org
  6. Reflexion: Language Agents with Verbal Reinforcement Learning (arXiv)arxiv.org