On this page · 13 sections

Here is a request the assistant has to act on, not just answer:

I was charged twice for my October invoice. Can you refund the extra charge?

The pieces exist already. “Function Calling and Tool Use in LLMs (opens in a new tab)” gave a model an issue_refund tool, and the agent articles since then gave it the payment records to read. Look up the payments, see two $25 charges for the same invoice on October 29, refund one of them, tell the customer. Four steps, and one of them moves money.

Now ask three questions about that conversation while it’s running:

  • Has the refund been made yet?
  • If the process dies right now, what should happen when it comes back?
  • If the customer writes again tomorrow, “Did you refund it? If not, please do it now,” what stops a second refund?

In the agent loops this series has built, the message history is the working record for the agent’s context and progress. It holds what the customer said, what the model said, which tools it called, and what they returned, all as entries in the same conversation history. But the conversation history isn’t an independently governed record of what the business actually did. A tool result can report a successful refund; the payment service’s ledger is what confirms it. This article is about why that isn’t enough once an agent acts, and about what to build instead: explicit state that code owns, and a workflow that decides which steps are allowed.

The companion demo builds the refund assistant both ways and measures them on the same scenarios, including a payment service that fails once and a process that dies right after the refund. The biggest difference wasn’t in the wording of the replies. It was in what the two designs did to the ledger.

Try to Understand It This Way

Think about how a bank handles a disputed card charge.

The conversation happens at the counter: the customer explains, the clerk asks questions, looks things up, and talks it through. But the dispute itself lives in a case file. The file is a form with fixed boxes: which charge, whether it was verified as a duplicate, the refund reference. A box is filled in when its step is done, and the form only lets the boxes be filled in an order that makes sense: there’s no filling in “refund reference” until “duplicate verified” has been ticked.

If the clerk goes home halfway through, the next clerk doesn’t need the conversation replayed. They open the file and continue from the last box that was filled in. And neither the file nor the conversation is the final word on whether money moved. The bank’s ledger is.

Three things, then, with three different jobs:

  • the conversation: what was said, and what the clerk needed in front of them to think;
  • the case file: where the dispute stands, what the workflow has recorded as done, and what is allowed next;
  • the ledger: what actually happened to the money.

An agent loop, as most of this series has built it, has the first and can read or write the third through its tools, but it has no case file. Everything it knows about the task’s progress is carried in the message list or has to be rediscovered from the ledger.

Three Kinds of State

The bank’s three things map onto three kinds of state in an agent system. They’re easy to blur, because in a simple agent loop the message list often stands in for workflow state as well as being the agent’s working context.

kind              what it holds                          how long it lives
agent state       instructions, messages, tool results,  one model request; rebuilt for
                  and context assembled for a model call each call as the loop continues
workflow state    the current node, completed steps and  the whole task, across pauses,
                  their results, attempts, and recovery  crashes, and restarts
                  information
application data  payments, refunds, tickets, and other  owned by the application's
                  business records                       services, independently of tasks

Agent state is the working context of a model call, assembled by the code that builds each request. In “What Is an AI Agent? (opens in a new tab)”, it was the messages list; keeping that list within its limits was the subject of “Managing Conversation State in AI Applications (opens in a new tab)”, and “Memory in AI Agents: What Does an Agent Actually Need to Remember? (opens in a new tab)” separated it from what lasts between conversations.

Workflow state is the case file, written by the workflow’s code. It answers “where is this task, and what’s allowed next?” without reading any text. In the demo below, it’s a JSON record with fields like node, verification, and refund.status.

Application data is the ledger. A refund isn’t real because a message says so, or because the workflow state says so. It’s real because the payment service recorded it. When the workflow state and the application data disagree, the application data wins, and the workflow has to find out what it says.

Why the message list isn’t enough

A message list can hold everything an agent needs to think. As the record of a task, it has three problems.

It mixes what was said with what happened. “I’ve issued the refund” from the model and {"refund_id": "PAY-5008", "status": "succeeded"} from a tool are entries in the same list. The tool call and its result may be structured, but nothing marks one entry as the record of what the business did. To answer “was the refund made?”, you have to read the conversation, and trust that the model’s sentences match the tool results.

It doesn’t say what’s allowed next. Nothing in a message list stops the model from calling issue_refund a second time, or for the wrong charge. Whether a step is valid depends on what has happened, and the list doesn’t hold that in a form code can check.

It doesn’t know what a crash interrupted. If the process dies after the model asked for a refund and before the result was appended, the saved list ends with a request and no answer. Did the refund happen? The list can’t tell you.

From a Loop to a State Machine

A workflow is a sequence of steps. A state machine makes it precise: a fixed set of states (here called nodes, as LangGraph calls them), the transitions allowed between them, and guards: conditions a transition must meet before it’s taken. Each node does some work, writes what it found into the workflow state, and names the next node. The machine checks that the move is allowed.

The states and the allowed transitions are defined in advance; the path through them isn’t. A conditional transition picks the next node from what the run has found, so decisions still happen at runtime, including the model’s, but only among the moves the table allows. The StateFlow paper (Wu et al., COLM 2024) describes the same arrangement for LLM task-solving: “The transitions between states are controlled by heuristic rules or decisions made by the LLM.”

For the refund:

  intake ──► verify ──► refund ──► reply ──► done
     │          │  └──────────────► reply
     │          └──────► handoff ──────────► done
     └─────────────────► handoff
                refund ─► handoff
  • intake is a model call: classify the customer’s message as JSON (a duplicate charge, another refund request, or something else), with the invoice or month it names.
  • verify is code: read the customer’s invoices and payments, and decide whether one invoice was charged successfully more than once, and whether that was already refunded.
  • refund is code: call the payment service, with a retry policy.
  • reply is a model call: write the reply from facts that code took from the workflow state.
  • handoff is code: pass the case to the billing team.

The transition table and the guards are a few lines. This is an excerpt of the demo’s workflow.py, shortened for reading:

TRANSITIONS = {
    "intake": {"verify", "handoff"},
    "verify": {"refund", "reply", "handoff"},
    "refund": {"reply", "handoff"},
    "reply": {"done"},
    "handoff": {"done"},
}

def guard(case, src, dst):
    """Why src -> dst isn't allowed for this case, or None if it is."""
    if dst not in TRANSITIONS.get(src, set()):
        return f"no transition {src} -> {dst}"
    if (src, dst) == ("verify", "refund"):
        v = case["verification"]
        if v["outcome"] != "refund" or v["refunded_by"]:
            return "needs one duplicate charge that isn't refunded"
        if case["refund"] is not None:
            return "this case already has a refund"
    if (src, dst) == ("refund", "reply") and case["refund"]["status"] != "succeeded":
        return "needs a succeeded refund"
    return None

def transition(case, dst):
    problem = guard(case, case["node"], dst)
    if problem:
        raise InvalidTransition(problem)
    case["log"].append(f"{case['node']} -> {dst}")
    case["node"] = dst

Three things change compared with a loop.

Where the task stands is a field, not an interpretation. case["node"] == "refund" and case["refund"]["status"] == "requested" say exactly where the task stopped. Nobody parses a sentence.

Invalid moves are refused in code. There’s no path from intake to refund. A second refund fails a guard, whatever the model wrote. The model can still be wrong, but only where you gave it a decision. (transition() itself only rejects the move. The runner around it catches the error, records it in the case, and routes the case to handoff.)

The state is saved after every transition, so a new process can load it and continue at the node where the old one stopped: the case file, picked up by the next clerk.

LangGraph’s Graph API uses the same vocabulary. State is “a shared snapshot of the application,” nodes are “functions that read state, do work, and return updates,” and edges are “fixed or conditional transitions that determine the next node.” The demo doesn’t use a framework. “LangGraph in Practice: A Text-to-SQL Agent You Can Measure (opens in a new tab)” shows what one adds on top of the same ideas.

The Experiment

The companion demo, 06-state-and-workflows, builds the refund assistant both ways, with the model, customer-facing prompt, and account data of the earlier demos. What’s new is a simulated payment service with a ledger, so a refund really changes something:

  • It enforces its own data rules, as a real payment API would: a refund must name an existing, successful charge of this customer that hasn’t been refunded already.
  • It doesn’t know the refund policy. It would refund September’s perfectly ordinary charge if asked. Which charges should be refunded is the support system’s decision.
  • It accepts an optional idempotency key: a repeated request with the same key gets the first request’s saved result instead of a second refund. Stripe’s API documentation describes the idea as “a unique key that the server uses to recognize subsequent retries of the same request.”

The two designs:

design             state                        who decides the next step
L  agent loop      the message list, saved to   the model, with five tools: help-center
                   a file after every message   search, invoices, payments,
                                                issue_refund(payment_id), and
                                                hand_off_to_billing; the refund policy
                                                is in its system prompt
S  state machine   a case record owned by       code, through the transition table and
                   code, saved after every      guards; the model classifies the message
                   transition and before the    and writes the reply, and sees no tools
                   refund is sent

Both follow the same policy: refund a duplicate charge, only the extra charge, only once; hand every other refund request to the billing team. L reads the policy as an instruction. S implements it in verify and the guards.

Six scenarios, each a new conversation against a fresh copy of the ledger:

D1  "I was charged twice for my October invoice. Can you refund the extra charge?"
D2  "I think you charged me twice recently. Please sort it out."
N1  "I was charged twice in November. Please refund one of the charges."
        (November's one charge went through once: no refund is allowed)
O1  "Please refund my September invoice. I didn't use the product that month."
        (not a duplicate: hand it to the billing team)
R1  "Did you refund the double charge on my October invoice? If you haven't, please
    do it now."  (it was refunded on 2026-11-05: no new refund)
T1  same as D1, but the payment service fails the first refund request with a
    retryable error

And a crash scenario, C1: the D1 message, with the payment service ending the process right after the refund is written to the ledger, before the caller sees the result. A second process then recovers from what’s on disk.

The model is qwen2.5:3b, as in the earlier agent demos. Each scenario ran with three seeds per design: 36 conversations, plus 6 in the crash run. The data, prompts, tool definitions, scenarios, design specifications, and grading rules (the files in data/) were frozen by hash before any implementation code in python/ was written. Three rules decide what counts:

  • The action is graded from the ledger, not the reply: a wrong or extra refund is a policy violation; no refund when one was due is a safe miss, counted separately because no money moved wrongly.
  • The reply is labeled by hand for what it claims (refunded, already refunded, no duplicate, handed off, failed or pending), and the claim is checked against the ledger.
  • A success is the right action, plus a reply whose claim is accepted for the scenario, matches the ledger, and contains no false statement.
Implementation note: the exact setup
Runtime:    Ollama 0.40.17 on an Apple M4 Pro (24 GiB, on battery), /api/chat
Model:      qwen2.5:3b (357c53fb659c), Q4_K_M; chat template saved with the run
Settings:   default sampling, seed = run number (1-3) for every model call; L at most
            6 model calls; 1,000 tokens per call (100 for S's intake); model
            unloaded before the run, loaded with one throwaway request, unloaded
            after
Runs:       6 scenarios x 2 designs x 3 seeds = 36 conversations, then C1 x 2
            designs x 3 seeds, each in two processes; 2026-11-24, 06:27:55 to
            06:29:47 UTC for both
Frozen:     data/ hashed at 2026-11-24 06:12:56 UTC, before any code in python/
Isolation:  the run held a shared lock and waited for 60 s with no model loaded and
            no connection open; before and after every conversation, no other
            model was loaded and no other connection to Ollama was open
Repeat:     a second complete run (06:33:08 to 06:35:00 UTC, same code and data)
            gave byte-identical replies, the same tool calls, and the same ledger
            in all 42 conversations; only timings differed (L median 3.38 s,
            slowest 7.36 s; S median 1.29 s, slowest 2.09 s)

Identical replies across two runs were observed in this setup (same Ollama version, model digest, seeds, and machine); they aren’t guaranteed elsewhere. Expect the same shape of results with other setups, not the same digits.

S’s retry policy: at most three attempts, only for errors the service marks retryable, waiting 0.2 s and then 0.4 s, always with the same idempotency key. L’s resume: load the saved message list and, following this demo’s recovery policy, run any tool call in the last assistant message that has no recorded result, then continue the loop. A message list doesn’t require that policy; an implementation chooses it. S’s resume: load the case record and run its current node again from the start.

Labels. Every reply was read and labeled against the written rules; the labels are stored with a SHA-256 of each reply. One field was added after reading the replies and isn’t part of the frozen grading: whether a reply announced an action the run never took.

What the Numbers Say

                                            L agent loop   S state machine
successes, all six scenarios (of 18)               7              18
  D1 duplicate, named by month (of 3)              2               3
  D2 duplicate, not named (of 3)                   3               3
  N1 no duplicate in November (of 3)               0               3
  O1 not a duplicate: hand off (of 3)              1               3
  R1 already refunded (of 3)                       1               3
  T1 one retryable failure (of 3)                  0               3
conversations with a wrong or extra refund         6               0
wrong or extra refund actions                      7               0
safe misses: refund due, none made (of 9)          4               0
replies inconsistent with the ledger               1               0
replies with a false statement                     2               0
model calls, mean per conversation              3.28            1.83
input tokens, median per conversation          2,560             422
seconds, median / slowest                  3.37 / 7.71     1.31 / 1.98

Every row counts conversations, 18 per design, except the refund-actions row. With three seeds per scenario, a difference of one or two conversations is noise, so the important finding isn’t a precise failure rate. It’s the nature of the failures: L made seven wrong refund actions across six conversations; S made none. And S’s 18 of 18 needs reading carefully before it means anything; there’s a section on that below.

A refund nobody asked for

N1 is a complaint about November: “I was charged twice in November.” The records show one November charge, which went through once. In all three runs, L called get_payments, found October’s duplicate instead, and refunded it:

One of the duplicate charges was for invoice INV-1002 on 2026-10-29. I will refund
the extra charge to ensure you only pay once. I will use issue_refund to do this.

It’s not a crazy thing to do. October’s charge really was a duplicate. But the customer asked about November, and the agent moved money on something they never mentioned. S’s verify node looked only at the month the customer named, found one charge, and replied that there was nothing to refund, in all three runs.

R1 is worse. The duplicate was refunded two weeks earlier, and get_payments shows it: PAY-5006, refunded as PAY-5008. In two of three runs, with that refund in the tool result in front of it, L refunded the other October charge as well. One run said what it was doing first:

The invoice "INV-1002" had a duplicate charge which was successfully refunded.
Specifically, the charge with ID "PAY-5006" was refunded with the ID "PAY-5008".
However, the charge "PAY-5005" and "PAY-5007" from the October invoice are still
outstanding as they have not been refunded. I will now attempt to refund the
outstanding charges.

PAY-5007 is November’s seat charge, not October’s; the run then refunded only PAY-5005. After that, both of October’s charges were refunded, and the customer had paid nothing for the month. One O1 run refunded October’s PAY-5005 and then September’s ordinary charge, PAY-5003, and told the customer:

We have successfully processed the refund for the duplicate charge (PAY-5003) of the
October invoice (INV-1001).

PAY-5003 and INV-1001 are September’s.

Data rules aren’t business rules

The payment service turned some of L’s mistakes away: a refund of October’s declined attempt (PAY-5004), a refund of a refund (PAY-5008), and, in the one R1 run that got it right, two attempts at the already-refunded PAY-5006. Every one of those breaks a data rule.

None of the seven wrong refunds did. Refunding PAY-5005 is valid as data: it’s a successful charge of this customer that hasn’t been refunded. It’s wrong as policy, because its invoice’s other charge was refunded already, or because the customer asked about a different month; September’s PAY-5003 wasn’t a duplicate at all. That rule involves two records and the customer’s request, and the payment service sees one charge at a time.

That’s the job of the guard on verify -> refund. It can say “this invoice already has a refund” because the workflow state holds what verify found about the whole invoice. L’s system prompt said it too: refund “only the extra charge, and only once.” A rule in a prompt is a request; a rule in a guard is a check.

A retryable error, and no retry

In T1, the payment service answers the first refund request with:

{"error": "The payment service is temporarily unavailable (HTTP 503). No refund was
made. The request can be retried.", "retryable": true}

L made one refund request in each of its three runs, and never a second. Two replies told the customer it would try again:

There was an issue attempting to process the refund. The payment service is
temporarily unavailable. I will retry this request later. In the meantime, I will
hand off this request to the billing team for further assistance.

Nothing retried later, and in that run nothing was handed off either: the conversation ended there. “I will retry later” is a sentence, not a scheduled retry. A promise in a reply has no owner once the loop ends. A retry needs to be recorded somewhere that something will read again.

S’s refund node retried once, after 0.2 seconds, with the same idempotency key, and the refund went through in all three runs. Its replies were word for word the same as D1’s for the same seed, because the case facts were the same: the reply node never knew there had been an error.

Announcing isn’t doing

The same pattern ran through L’s replies. Six of its 18 announced a step that never happened: “I will now hand this issue over to the billing team” with no handoff recorded, “I will now call the function issue_refund again” with no call. Here, the announcement went to a customer as a description of what the system was doing. One of them counts as inconsistent with the ledger: an O1 reply telling the customer their request was going to the billing team, when no handoff had been recorded. In S, a handoff is a node that records the handoff and then replies with fixed text, not model output, so that reply can’t claim a handoff that wasn’t recorded. S’s other replies are model-generated from the recorded outcome, which gives them a reliable source but doesn’t make them infallible.

After the crash

C1 is D1 with a crash. The payment service writes the refund to the ledger and then ends the process before anyone sees the result. A second process recovers from what’s on disk.

L crashed in two of three runs. The third never got as far as a refund: its first process tried the declined attempt PAY-5004, was rejected, and ended (that run is the same conversation as D1’s second run). In the two that crashed, the saved message list ended with the model’s issue_refund(PAY-5005) call and no result. The resumed process followed the demo’s recovery policy for L and ran the unanswered call again. (Another policy could ask the model what to do next instead, but no policy can learn from the transcript whether the refund happened.) The payment service answered:

{"error": "PAY-5005 was already refunded on 2026-11-12 (PAY-5008).", "retryable": false}

That refund was L’s own, made seconds earlier by the process that crashed. Nothing in the message list could say so. One run tried again, got the same answer, and told the customer:

The attempt to issue a refund for the duplicate charge (PAY-5005) was unsuccessful
due to it already having been refunded previously. I will now hand off this request
to the billing team for further assistance.

The customer was refunded and told the refund had failed; no handoff was made. The other run’s reply quoted the right refund and date, but presented it as one made before this conversation, and announced a handoff that didn’t happen either. Neither run refunded twice. What prevented that was the payment service’s rule against refunding the same charge twice, not anything in the agent; R1 already showed that the rule doesn’t cover a refund of the other charge.

S crashed in all three runs, at the same point. Its record, saved before the request went out, said (abridged, seed 1):

node: refund
refund: {payment_id: PAY-5006, idempotency_key: C1-S-s1:PAY-5006,
         status: requested, attempts: []}

The resumed process ran the refund node again, from its first line, and sent the same request with the same key. The payment service recognized the key and returned the saved result of the first request, marked replayed, instead of refunding again. That protection covers a repeated request with the same key; a refund request with a new key, or none, would have been a new request. The case moved to reply, and in each run the reply was byte for byte the one the uninterrupted D1 run wrote for that seed. One refund in the ledger, and nothing in the customer’s reply showed there had been a crash.

What 18 of 18 does and doesn’t show

What the experiment establishes is narrower than “state machines beat agent loops”: in this implementation, the state machine enforced the refund policy because the decisions the policy covers were in code. S’s result is mostly a statement about where the policy lives. Verify, refund, and handoff are code written for exactly these cases; given a correct classification, they do what they were written to do. The model’s part in S was small: classify the message into one of three kinds (it did, correctly, in all 21 conversations including the crash run), and write a reply from facts it was handed.

Three things this run doesn’t show:

  • No transition was refused at runtime. S’s own code never attempted an invalid move, so the guards never fired. They’re tested in the demo’s unit tests, with a scripted model, not by this run.
  • No message fell outside the three kinds. A request S has no node for goes to handoff. That’s safe, but it’s not an answer, and the router in “Agentic Workflows: When Should an LLM Control the Flow? (opens in a new tab)” showed how a classifier can force a request into the wrong kind without a sign that anything went wrong.
  • What a stronger model would do. This run used one small model, and a stronger one may follow L’s policy more often. The structural differences don’t depend on the model: a transcript can’t say what a crash interrupted, a sentence isn’t a scheduled retry, and the payment service can’t check a rule that spans two records.

S was also cheaper here, with a median of 422 input tokens per conversation against L’s 2,560, mostly because its model calls carried no tool definitions and no tool results. That’s a consequence of moving work into code, not a property of state machines.

Failure, Retries, and Where a Run Resumes

The crash and the retry are the two places where explicit state did the most work, and they’re different problems. A retry runs an operation again because it failed. Recovery rebuilds a task after an interruption and works out what’s left to do. A crash can come after the side effect succeeded, so recovery isn’t retrying failed work: T1 needed a retry, C1 needed recovery. A few rules cover both, and the frameworks built for long-running workflows state them in their documentation.

A resumed node runs again from the start. S’s refund node ran twice for one refund: once before the crash, once after. LangGraph documents the same behaviour for its nodes: a retry “re-runs the entire node function from the start. That gives at-least-once semantics for node execution,” and “the same re-execution model applies after an interrupt or a crash resume.” Saving state makes a task resumable. It doesn’t make a side effect happen exactly once; LangGraph’s page says so directly: “It does not make external side effects happen exactly once.”

So the side effect carries a key that already exists. S’s key is made from the case id and the payment id, both in the record before the request goes out. If the key were generated inside the node and saved only afterwards, the crash would lose it, and the resumed node would send a new one. LangGraph’s fault-tolerance guide makes the same point: “The key must already be durable before the side effect runs.”

And the provider has to honor it. The demo’s payment service saves only successful results, so a request that failed can be retried with the same key. Real providers differ. Stripe’s v1 documentation says it “saves the status code and body of the first request made with a given idempotency key,” and that “retries with the same key return the saved response, including 500 errors.” The protection also depends on what a key is scoped to, how long it’s kept, and whether a repeat with different parameters is rejected. Stripe, for example, documents removing keys “after they’re at least 24 hours old” and says it “compares incoming parameters to those of the original request and errors if they’re not the same.” Check your provider’s semantics before building a retry or a recovery on a key.

A missing result means “unknown”, not “didn’t happen.” L’s resumed run treated an unanswered tool call as something to do again. The safer reading, in LangGraph’s words: “Treat missing local state as unknown, not as proof the effect did not happen.” When the key isn’t enough, ask the provider for the operation’s status before deciding.

Retries belong to the workflow, with limits. S retries only errors marked retryable, at most three attempts, with a short wait in between, and a third failure moves the case to handoff (a unit test covers that path; this run didn’t reach it). Workflow engines make the policy explicit, and their defaults differ: AWS Step Functions’ Retry field defaults to 3 retry attempts, a 1-second first interval, and a backoff rate of 2.0; Temporal retries a failed Activity by default, with unlimited attempts, while “Workflow Executions do not retry by default.” Whichever you use, a retry policy is a decision about what’s worth trying again, and it needs a destination for what still fails.

Failed transitions go somewhere on purpose. In S, the runner catches a rejected transition, records it in the case, and routes the case to handoff, so a failure never leaves the task in an unnamed state.

Want to go deeper? What the frameworks call these pieces

The demo writes the state machine by hand, in one file of about 250 lines, so every piece is visible. Workflow frameworks provide the same pieces under their own names:

in the demo                 LangGraph                    Temporal
case record (case.json)     graph state, saved by a      workflow state, rebuilt by
                            checkpointer per thread      replaying the event history
node                        node                         workflow code / activity
transition table, guards    edges, conditional edges,    ordinary control flow in
                            Command                      workflow code
checkpoint after a step     checkpoint at each           event history recorded by
                            super-step                   the service
retry policy in the node    retry policy per node        activity retry policy
idempotency key             the guide's recommended      not automatic: the activity's
                            pattern; not automatic       code and the provider

Two framework rules are worth knowing even if you never use one. Temporal requires that “a Workflow Definition must be deterministic to support replay,” and tells you to put “API calls, LLM/AI invocations, database queries, and other external interactions” in Activities. A model call isn’t deterministic, so in Temporal it goes in an Activity, outside the workflow code that gets replayed. LangGraph’s Graph API adds Command for the case where a node decides the next step itself: use it “when a single step must both update state and choose what runs next.”

None of this is required. The demo’s state machine is a dictionary, a JSON file, and a loop. What the frameworks add is durable storage, scheduling, timers, and the operational tooling around them.

Where the Model Should Still Decide

None of this means taking the model out. It means deciding, per step, who decides.

“Agentic Workflows” measured that question with read-only tools, and fixed steps won where the steps were known. With an action in the mix, a useful way to split the work:

  • Understanding the request is the model’s: what’s being asked, which invoice or month. In S, it’s one model call with a schema, and the output is checked before anything uses it.
  • Facts that code can compute are code’s: whether an invoice was charged twice, whether a refund already exists. A model can read a payment list; code reads it the same way every time.
  • Actions are code’s, behind a guard: the model can propose, the workflow decides whether the proposal is allowed in the current state.
  • Open-ended investigation can be the model’s, inside a node: an agent loop with read-only tools, a step budget, and an output schema, whose result is written into the workflow state and checked before any transition uses it. The loop decides how to look; the workflow decides what happens with what it found.
  • The reply is the model’s, grounded in facts the workflow hands it. That makes it easier to keep the reply aligned with recorded outcomes, but it doesn’t make the text true by construction: one of S’s replies here added “we are working on a correction for your account,” which isn’t in its facts. Generated claims still need checking.

StateFlow draws the same line, between “process grounding” (via state and state transitions) and “sub-task solving” (through actions within a state), and reports better results than ReAct on its own benchmarks; the separation, not the numbers, is what carries over here.

A plan is state too

“Planning, Reasoning, and Execution in AI Agents: Who Decides the Steps, and When?”, the article before this one in the series, is about how an agent breaks a task into steps and works through them. In a stateful design, the plan doesn’t live in the conversation either. It goes in the workflow state, as data that code advances:

# Illustrative: a plan held in the workflow state, not as text in the messages.
case["plan"] = {
    "version": 2,
    "steps": [
        {"id": "find_duplicate", "kind": "read", "status": "done",
         "result": {"invoice": "INV-1002", "charge": "PAY-5006"}},
        {"id": "refund", "kind": "write", "status": "pending",
         "idempotency_key": "case-0412:PAY-5006"},
        {"id": "reply", "kind": "model", "status": "pending"},
    ],
}

Whatever produced the plan, a model or a developer, the same rules apply: the executor runs the first pending step and records its result before moving on; a step marked done is never run again on resume; a write step goes through the same guards as any other action; and replanning creates a new version that keeps the finished steps’ results instead of starting over. That’s what turns a plan from a paragraph the model wrote into something a crashed process can continue.

What Breaks

The demo produced five failures, each covered above: a refund the customer didn’t ask for, refunds valid as data and wrong as policy, a retryable error with no retry, announced actions that never happened, and a resumed transcript that misreported its own refund. Two more need planning even though this run didn’t show them:

  • A request outside the workflow. S sends anything it can’t classify to handoff. A classifier that confidently picks the wrong kind sends it down the wrong path instead.
  • State and data that drift apart. If the payment service’s result is lost and the key isn’t honored, the case record can say requested forever. Something has to look up the operation’s status rather than assume.

Engineering Decisions

1. Name the three kinds of state, and give each an owner

Decide what the model sees on a call, what records where the task stands, and which service owns the business data. Don’t let the message list be all three.

The workflow record says what the task has recorded and what should happen next. The payment service remains authoritative about whether the refund happened. After a crash, the two can disagree (S’s record said requested while the ledger already held the refund); when they do, reconcile them, and treat neither the conversation nor the workflow record as proof of the side effect.

2. Put the rules that protect money, data, or customers in guards

A policy in a prompt is followed when the model follows it. Here, L broke it in six of its 18 runs. A guard is checked every time. Write guards for the rules that span records (“this invoice already has a refund”), because the service that owns one record can’t see them.

3. Save the intent before the side effect, with a key that already exists

Record “refund requested, with this key” before sending the request, and derive the key from data that’s already saved. Then a resumed node can safely send the request again, provided the provider honors keys the way you’ve checked it does.

4. Let the workflow own retries and promises

A retry is a decision with a policy (which errors, how many times, how far apart) and a destination for what still fails. Anything a reply promises (“we’ll retry”, “the billing team will contact you”) should exist as a record before the reply says it.

5. Keep the model where its judgment is needed

Give the model understanding, investigation, and replies. Keep facts that code can compute, and every action, out of its hands (see “Where the Model Should Still Decide”).

What to Take Away

  • A message list records a conversation, not a task. It mixes what the model said with what happened, and after a crash it can’t say whether a pending action ran.
  • Workflow state answers “where is this task?” without reading text, and the application data answers “what actually happened?” Reconcile them after a failure.
  • Data rules aren’t business rules. The payment service stopped refunds that were invalid as data; all seven wrong refunds were valid as data and wrong as policy. Guards in the workflow are where cross-record rules belong.
  • Saving state makes a run resumable, not a side effect exactly-once. The resumed node runs again; an idempotency key that existed before the side effect is what keeps the second run from refunding twice.
  • A promise in a reply isn’t a scheduled action. “I will retry later” did nothing. Retries and handoffs need records.
  • Code can enforce an action and record its outcome; it can’t make a model describe that outcome truthfully. Ground replies in recorded facts, and still check what they claim.

Think About These Use Cases

  • An order-cancellation agent: It can cancel orders and issue refunds. Which states does a cancellation pass through, and which transitions need a guard that looks at more than one record?

  • An IT agent that resets passwords and unlocks accounts: The process dies after the reset and before the confirmation email. What must be in the workflow state for the restart to send the email, without resetting the password again?

  • A provider without idempotency keys: Your payment provider doesn’t support them. How would you avoid a double refund after a crash: a status lookup before every retry, a reference you store with the provider, or moving the side effect out of the retried step?

  • An agent with a plan: The agent writes a six-step plan, completes three steps, and the process restarts. What does the stored plan need for the restart to skip the first three, and what should happen if the agent wants to replan?

  • An audit question: Six months later, someone asks why a customer was refunded twice. What would you want to find in the workflow state, and what can you not reconstruct from a conversation transcript alone?

If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️

What’s Next?

The state machine here paused only when something went wrong: a failed request, or a crash. Its record made it possible to stop and continue later without losing the task.

Some pauses are on purpose. A refund above a limit, an exception to the policy, an action that can’t be undone: a person should decide before the workflow continues. In the next article, we’ll look at Human-in-the-Loop AI Agents: When Should an Agent Stop and Ask?: when people should stay part of the execution loop, and what changes when a workflow has to wait for one.

← All articles