Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design

A workflow is code that fixes the steps; an agent is a model that picks them. Run both on two support tickets, then let three constraint sets (strict audit, low error tolerance, open exploration) pick a workflow, a gated hybrid or an agent.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Tell a workflow from an agent by who chooses the next step
  • Compare the two designs on the same tickets by calls made and checks covered
  • Pick a workflow, a hybrid with a code gate, or an agent from the audit, error-tolerance and openness constraints
  • Decide which work is safe to split across read-only subagents

Before you start

  • Claude tool use: tool_use and tool_result
  • Basic Python

Two tickets land on a support desk. T-201 asks: Where is my refund? That needs one check, the order. T-202 says: I was charged twice and my parcel never came. That needs the order, the parcel and the payments.

Should one design handle both? The question that decides it is short: who picks the next step, your code or the model? In this article we build both designs on these two tickets, compare what they cost and what they cover, and then add the constraints that real teams have, such as audit trails and money that can't be pulled back.

A train or a taxi driver

Think of getting across a city.

  • A train runs on rails. The route is fixed before the trip, same stops every time. That's a workflow.
  • A taxi driver reads the road and picks each turn on the way. That's an agent.

Same destination, two ways to plan the trip. Take the train when the route is known. Hire the driver when it isn't.

Who holds the steering wheel

In a workflow, your code holds the wheel: classify, then find the order, then draft. The order of steps is written in code before the run starts.

In an agent, the model holds it. Claude picks a tool and the reply comes back with stop_reason set to tool_use. Your code runs the tool, sends a tool_result back, and Claude picks again. When it has what it needs, the stop reason is end_turn.

Workflow: steps fixed in code. Agent: the model picks each step. Workflow: our code picks the steps classify model call find_order plain Python draft model call Agent: the model picks the steps Claude picks a tool stop_reason: tool_use our code runs the tool sends a tool_result back stop_reason: end_turn, the reply is ready
A workflow's steps are fixed before the run. An agent's steps are chosen during it.

Workflows come in a few well-known patterns: prompt chaining, routing, parallelization, orchestrator-workers and evaluator-optimizer. They all share one thing: the code paths are defined up front.

The workflow in code

The project is a small slice of SupportDesk. It runs against a stand-in model (the Anthropic SDK on an httpx mock transport), so it needs no API key, and every model reply and tool pick is scripted. Here is the workflow:

"""A workflow: our code fixes the steps."""
from desk import find_order, covered
from stand_in import MODEL, text_of


def ask(client, system, text):
    msg = [{"role": "user", "content": text}]
    r = client.messages.create(
        model=MODEL, max_tokens=256,
        system=system, messages=msg)
    return text_of(r)


def handle(ticket, client):
    text = ticket["text"]
    steps = []
    kind = ask(client, "Classify.", text)
    steps.append("classify")
    facts = find_order(ticket["id"])
    steps.append("find_order")
    note = f"{kind}: {text} {facts}"
    reply = ask(client, "Draft.", note)
    steps.append("draft")
    return {"steps": steps, "reply": reply,
            "covered": covered(steps)}
  • Step one is a model call that classifies the ticket.
  • Step two is plain Python. It finds the order with no model involved.
  • Step three is a model call again, drafting the reply from the facts.
  • The same three steps run for every ticket, whatever it says.

The agent in code

The agent gets three tools (find_order, track_parcel, list_payments) and a loop:

"""An agent: the model picks each next step. We only run its tools."""
import json
from desk import TOOLS, FUNCS, covered
from stand_in import MODEL, text_of

MAX_TURNS = 8


def handle(ticket, client):
    msgs = [{"role": "user", "content": ticket["text"]}]
    steps = []
    for _ in range(MAX_TURNS):
        r = client.messages.create(
            model=MODEL, max_tokens=512,
            tools=TOOLS, messages=msgs)
        if r.stop_reason != "tool_use":
            reply = text_of(r)
            return {"steps": steps, "reply": reply,
                    "covered": covered(steps)}
        msgs.append({"role": "assistant", "content": r.content})
        results = []
        for block in r.content:
            if block.type == "tool_use":
                steps.append(block.name)
                out = FUNCS[block.name](block.input["ticket"])
                results.append({"type": "tool_result",
                                "tool_use_id": block.id,
                                "content": json.dumps(out)})
        msgs.append({"role": "user", "content": results})
    return {"steps": steps, "reply": "stopped at the turn cap",
            "covered": covered(steps)}
  • The loop has a cap of eight turns, so it can't run forever.
  • Each turn, Claude gets the tools and picks what to do.
  • If the stop reason isn't tool_use, the model is finished.
  • Otherwise the code runs the tool Claude picked (that's all it does) and sends a tool_result back. The tool use article covers that round trip, and the agentic loop article covers the stop rule.

Same tickets, two designs

run_all.py sends both tickets through both designs and counts the model calls and the checks each design actually made:

workflow
T-201 classify > find_order > draft | calls 2 | covered 1 of 1
T-202 classify > find_order > draft | calls 2 | covered 1 of 3
agent
T-201 find_order | calls 2 | covered 1 of 1
T-202 find_order > track_parcel > list_payments | calls 4 | covered 3 of 3
calls: workflow 4 | agent 6

The tool picks and call counts come from the stand-in, not a real model, but the shape is the point:

  • The workflow took two calls per ticket and the same path both times. For T-202 it checked only the order: one of three checks.
  • The agent picked one tool for T-201. For T-202 it asked for find_order, then track_parcel, then list_payments, then ended the turn. Four calls, all three checks. Nobody wrote that order; the model chose it.
  • Four calls for the workflow, six for the agent. The agent cost more, and it covered the ticket.

Three questions, one trade-off

  1. Are the steps known before the run starts? If yes, a workflow.
  2. Does the next step depend on what the last one found? If yes, an agent.
  3. Do you need a predictable path and a steady cost? Then a workflow.
WorkflowAgent
PathPredictable, the same every runFlexible, chosen per ticket
Model callsFewer (T-202: 2)More turns (T-202: 4)
TestingEasy: same steps every timeHarder, and errors can compound across turns
Weak spotCan't add a step the ticket needsCosts and variance a fixed task doesn't need

Start with the simplest design that works, and add autonomy only when the task needs it.

When constraints decide the design

Now a harder case. One requirement, review the expense claims, for a finance team (ClaimDesk). The requirement stays the same, but three different sets of rules come with it:

  • Strict audit. An auditor will replay every decision, so each one must be explainable.
  • Low error tolerance. A wrong payout can't be pulled back.
  • Open exploration. Finance asks "what's going on?" with no fixed question to start from.

Think of three jobs. An auditor works from a checklist: same boxes, same order. A pharmacist checks the dose the doctor proposed before handing it over. A researcher in a library follows the trail, and each find decides where to look next. Each job gets a different amount of freedom, and so does each design.

The constraint picks the design Strict audit Workflow 1. model reads receipt 2. code finds the rule 3. code decides 4. audit line returned replay: identical Low error tolerance Hybrid 1. model proposes amount 2. code gate: = receipt? 3. only code pays E-32: 46 vs 460, held Open exploration Agent + subagents orchestrator splits by department read-only subagents short notes come back writes: none
Same requirement, three sets of rules, three designs.

Strict audit: a workflow

One model call reads the receipt. Then your code finds the rule in its own table of limits, makes the decision and returns an audit line that names the rule:

def review(claim_id, client):
    claim = CLAIMS[claim_id]
    text = f"{claim_id}: {claim['receipt']}"
    read = ask(client, "Read the receipt.", text)
    category, amount = read.split()
    limit = LIMITS[category]
    over = float(amount) > limit
    decision = "flag" if over else "approve"
    rule = f"{category} limit {limit}"
    return {"claim": claim_id, "read": read,
            "rule": rule, "decision": decision}

The model reads; the code decides. Because the path is fixed, running it twice gives the same trail, and an auditor can replay any decision.

Low error tolerance: a hybrid with a code gate

The model still does the open step, proposing an amount. But a plain comparison stands between that proposal and the payout, and only your code can pay:

def review(claim_id, client):
    amount = propose(client, claim_id)["amount"]
    problem = gate(claim_id, amount)
    if problem:
        return {"claim": claim_id, "proposed": amount,
                "paid": False, "why": problem}
    PAID.append(claim_id)
    return {"claim": claim_id, "proposed": amount,
            "paid": True, "why": None}


def gate(claim_id, amount):
    total = receipt_total(CLAIMS[claim_id])
    if amount != total:
        return f"not the receipt total {total}"
    return None

Keep the open step, and put a code gate in front of the action that can't be undone. For hard rules inside an agent, the same idea is a hook; see guardrails for LLM agents.

Open exploration: an agent with read-only subagents

Here an orchestrator splits the reading by department (ops, sales, support), one subagent each. Every subagent works in its own context, has only a read tool (SUBAGENT_TOOLS = ["list_claims"], no payout tool), and sends back a short note. The orchestrator merges the notes.

Where must it not split? Not the payout: one decision needs one owner. Not steps that each need the previous answer. And not a short, fixed task, where the split costs more than it saves. The hub-and-spoke article goes deeper into briefs and routing.

What the three designs printed

set 1 strict audit
E-31 read meals 38.00 | rule meals limit 60 | approve
E-32 read lodging 460.00 | rule lodging limit 250 | flag
replay: identical | calls 2
set 2 low error tolerance
E-31 proposed 38.0 | gate ok | paid
E-32 proposed 46.0 | gate blocked | held
gate said: not the receipt total 460.0
paid 1 | held 1 | calls 2
set 3 open exploration
split 3 | ops sales support | writes none
ops: 1 claim, train travel
sales: 2 claims, lodging is the big one
support: 1 claim, a meal
merged: lodging leads the spend | calls 4

The stand-in scripts every reply, including the wrong amount for E-32 (46 instead of 460), so the gate has something to catch. The audit lines name their rule and the replay matched. The gate blocked the wrong amount, so one claim was paid and one held. The explorer split three ways, made four calls and wrote nothing.

Each design runs somewhere

The design also shapes the runtime. The workflow and the hybrid fit a self-hosted harness, where your code runs the steps, keeps the log and stands in front of the payout (see custom agent loops and harnesses). Open exploration fits a managed, sandboxed runtime such as Claude Managed Agents, where Anthropic runs the harness. Self-hosted means you own the loop; managed means the platform does.

Common mistakes

  • Always using an agent. It adds turns and variance to a task whose steps are already known.
  • Always using a workflow. It can't adapt when the path depends on what each check finds, as T-202 showed (one of three checks).
  • Choosing by model power. A bigger model doesn't change who should pick the steps. The shape of the task and the constraints do.
  • Letting the model own an irreversible action. Under low error tolerance, the model proposes and code decides.
  • Splitting everything into subagents. More hand-offs, and nobody owns the decision. Split only independent, read-only work.

Quick recap

SituationDesign
Steps known up frontWorkflow
Next step depends on the last resultAgent (loop on stop_reason)
Every decision must be replayedWorkflow, code decides and logs
A mistake can't be undoneHybrid: model proposes, code gate, code acts
Open question, independent readingAgent with read-only subagents

Try it yourself

Add a fourth ticket: My parcel says delivered but I never got it. Before you run anything, write down which checks it needs. Then predict how many checks the workflow covers and which tools the agent would ask for. If the answer is "the same two every time", you have a case for adding a second fixed workflow branch instead of an agent.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 45 of 89

Previous
Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
Next post
Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

On this page

  • A train or a taxi driver
  • Who holds the steering wheel
  • The workflow in code
  • The agent in code
  • Same tickets, two designs
  • Three questions, one trade-off
  • When constraints decide the design
  • Strict audit: a workflow
  • Low error tolerance: a hybrid with a code gate
  • Open exploration: an agent with read-only subagents
  • What the three designs printed
  • Each design runs somewhere
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.