← Back to learning path
Chapter · Published

Planning and state machines: split long agent tasks into recoverable steps

Compare one-shot plans, staged execution, and state machines for replayable agent orchestration.

Source: knowledge/p24-b/collection_8023a8d754046b6c2ae7220f/tutorials/agent-planning-and-state-machines.mdAI agent engineering
Chapter progress 0%Learning path progress 0% · 0/10 chapters completedContinue learning path →

Long tasks fail through context growth, duplicate actions, and interruptions. Treat the plan as mutable data and execution as a finite state machine so a restart can continue from the last successful node.

Core concepts

Each plan item should have an id, prerequisites, input references, status, and retry count. The state machine should allow only declared transitions, such as pending -> running -> succeeded or running -> failed. Do not let a model change state through arbitrary strings.

from enum import StrEnum

class Status(StrEnum):
    PENDING = 'pending'
    RUNNING = 'running'
    SUCCEEDED = 'succeeded'
    FAILED = 'failed'

TRANSITIONS = {(Status.PENDING, Status.RUNNING), (Status.RUNNING, Status.SUCCEEDED), (Status.RUNNING, Status.FAILED)}

def transition(old: Status, new: Status) -> Status:
    if (old, new) not in TRANSITIONS:
        raise ValueError('invalid transition')
    return new

Steps

  1. Draw the business flow as nodes and edges, marking parallel and serial work.
  2. Store input references for each node instead of copying large context, which lowers retry cost.
  3. Write running before execution, then commit succeeded and a result summary in one transaction.
  4. On restart, scan running nodes and use idempotency rules to choose recovery, retry, or human handoff.

When to use it

It suits report generation, data synchronization, and multi-step approvals. A real-time chat normally does not need a complex state machine.

Common questions

Does the model still need to create the full plan? It may, but the server must validate node types, dependencies, and budget.

How do I aggregate parallel work? Track every child status and advance only when the required conditions are met.

Should failures be deleted? No. Keep the failure reason and the human resolution.

Official references

OpenAI Agents guide; OpenAI Evals.

Last checked: 2026-11-16. Use the linked official documentation for current behavior.

Related practical cases

KnowledgeCase study: an auditable support-ticket triage agentKnowledgeCase study: a deployment-advice agent with human approvalKnowledgeCase study: an evidence package and human handoff after an agent failure

Further reading

KnowledgeAI Agents: From Core Concepts to ProductionKnowledgeDesigning Reliable AI Automation Workflows
Product Hub Demo · V0.3