FORTILABS AI LAB • SYSTEM DESIGN
A multi-agent system can look impressive in a demo and still be unreliable in production. Agents may repeat work, delegate in circles, disagree about task ownership, or continue spending tokens long after a useful answer is possible. The solution is not simply a better model or a longer system prompt. It is an architecture that makes execution explicit, bounded, observable, and recoverable.
THE SHORT ANSWER
Build the workflow as an application-controlled state machine. Let agents propose actions and produce structured results, but keep state transitions, permissions, retry limits, execution budgets, and termination decisions in deterministic application code. Use typed contracts between agents, validate every handoff, and make external side effects safe to retry.
Editorial note: This article explains architecture and implementation patterns. Code examples are illustrative and have not been presented as benchmark results or as evidence of a FortiLabs production deployment. Framework-specific behavior can change; consult the linked official documentation before implementing against a particular version.
1. Why multi-agent workflows become unpredictable
Multi-agent architectures divide a larger task among specialized components. One agent may research, another may analyze, and a third may review the result. A coordinating agent or application process combines their work.
This separation can improve modularity and make complex tasks easier to reason about. It also creates more places where execution can go wrong.
Consider a research workflow:
- A coordinator receives a research request.
- A planner divides it into subtasks.
- Research agents gather evidence.
- An analyst synthesizes the findings.
- A reviewer checks the final result.
- The coordinator returns the answer.
That looks straightforward. But what happens if the reviewer rejects the analysis? Does the analyst revise it once, or repeatedly? Can the analyst send work back to the planner? Can the planner create new research tasks after the budget is exhausted? What happens if a research tool times out after successfully saving its result?
Without explicit answers, the workflow’s behavior is largely determined by model-generated decisions and framework defaults.
Common failure modes
| Failure | What it looks like | Architectural control |
|---|---|---|
| Delegation loop | Agent A delegates to B, which delegates back to A. | Allowed-transition graph and delegation-depth limit. |
| Review loop | Reviewer repeatedly requests revisions without a stopping condition. | Revision budget and explicit acceptance criteria. |
| Duplicate execution | A retry repeats a payment, email, database write, or external action. | Idempotency keys and side-effect controls. |
| State ambiguity | Two agents disagree about whether a task is complete. | Application-owned state and validated transitions. |
| Unbounded tool use | An agent keeps searching, browsing, or calling tools. | Tool-call, time, token, and monetary budgets. |
| Invalid handoff | A specialist returns prose where the next stage expects structured data. | Typed output contracts and schema validation. |
| Lost progress | A process crashes and restarts from the beginning. | Durable checkpoints and resumable execution. |
The central design problem is not that language models are inherently unusable. It is that model-generated reasoning is probabilistic, while production systems often require predictable control over what happens next.
Anthropic’s discussion of agent design makes a useful distinction between predefined workflows and agents that dynamically direct their own processes. That distinction matters: a workflow can use language models without handing the models unrestricted control over the entire execution path. See Building Effective Agents.
2. What deterministic actually means
In this context, deterministic does not mean that every model response will be identical. A model can produce different valid outputs for the same input, even with carefully controlled settings.
Instead, deterministic workflow design means that the application controls the rules governing execution.
- The set of valid workflow states is defined in advance.
- Only permitted transitions can occur.
- Every stage has a defined input and output contract.
- Permissions are enforced outside model-generated instructions.
- Retries and delegation have explicit limits.
- Completion and failure conditions are evaluated by application logic.
- External actions are tracked and protected against accidental repetition.
The model can still make judgments. It may decide that a source is relevant, recommend another research step, or identify a missing requirement. But the application decides whether that recommendation is permitted and what state follows.
A useful distinction
Probabilistic reasoning, deterministic control. Let the model help decide what would be useful. Let ordinary code decide what is allowed to happen next.
Determinism has several layers
It helps to separate the word into different engineering concerns:
- Control-flow determinism: the same valid state and event follow the same transition rules.
- Permission determinism: the same identity, scope, and requested action produce the same authorization decision.
- Budget determinism: execution cannot exceed configured limits simply because an agent requests more work.
- Recovery determinism: failures follow defined retry, compensation, or termination policies.
- Data-contract determinism: downstream stages receive validated data in a known structure.
These controls make the system’s behavior more predictable. They do not guarantee that every model judgment is correct, that external services are always available, or that a workflow will produce the same semantic answer on every run.
3. A reliable multi-agent architecture
A production workflow should separate reasoning from execution control. A useful baseline has five components.
The diagram is conceptual rather than a mandatory sequence. In a real system, validation can occur before and after every agent call, and durable state should be updated throughout execution rather than only at the end.
Component responsibilities
Request boundary
Validate the request before invoking an agent. Check authentication, tenant ownership, input size, permitted operation, and any applicable policy. A model prompt is not an authentication or authorization mechanism.
Workflow orchestrator
This is the control plane. It owns the current state, chooses the next permitted stage, enforces execution budgets, and decides when to retry, pause, fail, or finish.
Specialist agents
Specialists perform bounded tasks. A research agent should not be able to silently change workflow state, grant itself new permissions, or invoke unrelated tools simply because it believes doing so would help.
Validation and policy boundary
Validate agent output before passing it downstream. Independently authorize tool calls and sensitive actions. Treat model-generated arguments as untrusted input.
Durable state and event log
Persist enough information to understand what happened and resume safely: current state, task identifiers, validated outputs, attempt counts, approval status, and external action identifiers.
4. Designing the state machine
A state machine represents a workflow as a finite set of states and explicitly permitted transitions. Instead of allowing an agent to invent the next stage, the application evaluates an event against the current state and transition rules.
Example workflow states
| State | Purpose | Possible next states |
|---|---|---|
RECEIVED | Request accepted by the application. | PLANNING, FAILED |
PLANNING | Task decomposition and scope definition. | RESEARCHING, FAILED |
RESEARCHING | Approved research tasks are executed. | ANALYZING, FAILED |
ANALYZING | Evidence is synthesized into a result. | REVIEWING, FAILED |
REVIEWING | Output is checked against acceptance criteria. | COMPLETED, REVISING, FAILED |
REVISING | A bounded correction is performed. | REVIEWING, FAILED |
WAITING_APPROVAL | A human decision is required. | COMPLETED, FAILED |
COMPLETED | Workflow finished successfully. | Terminal |
FAILED | Workflow stopped without successful completion. | Terminal or explicit recovery path |
Notice that the review stage does not have an unrestricted transition back to planning. A reviewer can request a revision, but the application controls how many revisions are available and which stage may receive the request.
Define transitions as rules
A transition should be more than a state name returned by a model. It should be an application-validated operation with:
- The current state.
- The proposed event or result.
- The identity or component requesting the transition.
- Required preconditions.
- Budget and attempt checks.
- The permitted destination state.
- An audit record explaining the decision.
For example, a review result of needs_revision should not automatically trigger unlimited work. The orchestrator should verify that the current state is REVIEWING, the reviewer is authorized, and the revision budget has not been exhausted.
Make terminal states genuinely terminal
A completed workflow should not accidentally restart because a late agent response arrives. A failed workflow should not continue executing tools because an asynchronous task finishes after cancellation.
Every event handler should check whether the workflow is still active before accepting a state update. Use version numbers or optimistic concurrency controls when multiple workers may update the same workflow.
5. Agent contracts and structured handoffs
Agents should communicate through explicit contracts rather than relying on loosely structured paragraphs. A downstream component should not have to guess whether a sentence means success, failure, a request for more information, or a proposed action.
A useful agent contract defines:
- Purpose: what the agent is responsible for.
- Allowed inputs: the fields and context it may receive.
- Allowed tools: the exact capabilities available to it.
- Output schema: the fields and types it must return.
- Failure behavior: how it reports missing information or inability to complete.
- Boundaries: what it must not do or decide.
Example structured result
{
"task_id": "research-042",
"status": "completed",
"summary": "Three relevant sources were identified.",
"findings": [
{
"claim": "The service supports resumable workflow execution.",
"source_url": "https://example.com/docs",
"confidence": "medium"
}
],
"limitations": [
"One source could not be independently verified."
],
"recommended_next_action": "send_to_analysis"
}
This is an illustrative schema, not a universal agent response format. In a real implementation, validate URLs, enums, maximum array lengths, required fields, and any domain-specific constraints.
Validate before accepting the handoff
Structured output is not automatically trustworthy. A model can return syntactically valid JSON containing unsupported claims, malformed identifiers, unauthorized actions, or misleading status values.
Use several layers of validation:
- Parse the response and reject malformed data.
- Validate it against a strict schema.
- Check that referenced task IDs belong to the current workflow.
- Verify that the requested next action is allowed from the current state.
- Apply domain-specific checks to claims, URLs, permissions, and data.
- Record the accepted result and validation outcome.
Never let a field such as "status": "completed" independently mark the entire workflow complete. It is an agent’s report about its own task. The orchestrator must verify that all required work has actually finished.
6. Choosing an orchestration pattern
Not every multi-agent workflow needs the same control structure. The right pattern depends on task dependencies, the need for centralized ownership, and how much freedom specialists require.
| Pattern | How it works | Best suited to | Main risk |
|---|---|---|---|
| Sequential pipeline | Each stage passes a validated result to the next. | Known, ordered processes. | Later stages inherit earlier mistakes. |
| Parallel workers | Independent subtasks execute concurrently. | Research, extraction, independent analysis. | Conflicting or incomplete results. |
| Manager and specialists | A central manager delegates bounded tasks. | Work requiring coordination and synthesis. | Manager becomes an unbounded bottleneck. |
| Evaluator and reviser | A reviewer checks output and can request revisions. | Drafting, code review, quality checks. | Repeated review cycles without progress. |
| Handoff network | Control moves between agents based on defined conditions. | Tasks with clear specialist ownership. | Unclear ownership and circular handoffs. |
Prefer the simplest pattern that works
A sequential pipeline is often easier to operate than a network of agents that can delegate freely. Parallel execution is useful when tasks are genuinely independent, but it introduces synchronization, aggregation, and partial-failure concerns.
A manager-style architecture is appropriate when one component must remain accountable for the final result. A handoff model is more suitable when a specialist should own the next stage rather than merely return a bounded result to a manager.
OpenAI’s orchestration guide describes this distinction between handoffs and agents used as tools: Orchestration and handoffs.
Do not use multiple agents just to create the appearance of sophistication
If one model call with a well-defined tool can solve the task, adding four agents may increase latency, cost, and failure surface without improving the result.
Use multiple agents when there is a concrete reason to separate responsibilities, such as independent parallel research, different permission boundaries, specialized evaluation, or a task that benefits from independent review.
7. Preventing loops and runaway delegation
Loops are among the most common operational problems in agentic systems. They can happen even when every individual agent appears to be following its instructions.
A reviewer asks for more evidence. The researcher requests clarification from the planner. The planner creates another research task. The reviewer then rejects the revised result for the same reason.
The workflow may be active, but it is not making meaningful progress.
Use multiple independent limits
No single limit is enough. A message-count limit will not necessarily stop expensive tool calls. A token limit will not prevent duplicate external actions. A time limit may terminate a workflow that is still making useful progress.
Use a combined execution budget:
| Budget | What it limits | Example policy |
|---|---|---|
| Wall-clock time | Total execution duration. | Stop or pause after a defined deadline. |
| Model calls | Number of model invocations. | Maximum calls per workflow. |
| Tool calls | External and internal tool usage. | Separate limits by tool or category. |
| Delegation depth | Nested agent handoffs. | Reject requests beyond a fixed depth. |
| Revision count | Review and correction cycles. | Allow a limited number of revisions. |
| Token budget | Model input and output consumption. | Enforce per-stage and workflow ceilings. |
| Monetary budget | Estimated model and tool cost. | Stop before the configured spending ceiling. |
The actual values should be determined by task complexity, service limits, and acceptable cost. There is no universally correct number of retries, tokens, or seconds for every workflow.
Detect repeated work, not only repeated messages
An agent can produce different wording while asking for the same operation. A message-count limit may miss this pattern.
Normalize task requests and record a fingerprint using stable fields such as:
- Task type.
- Target resource or entity.
- Relevant input identifiers.
- Requested operation.
- Workflow stage.
Before scheduling a new task, compare its fingerprint with recent and completed tasks. If an equivalent task already exists, reuse its result, reject the duplicate, or require an explicit reason for repeating it.
Do not rely on a text hash of the entire prompt alone. Small wording changes can defeat that check, while two requests with similar text may legitimately refer to different resources.
Require measurable progress
Every revision should identify what changed and which acceptance criterion it addresses. A reviewer should return structured feedback rather than an open-ended instruction to “improve the result.”
For example:
{
"decision": "revise",
"issues": [
{
"criterion": "source_coverage",
"problem": "Two required claims have no supporting source.",
"required_change": "Attach a verifiable source to each claim."
}
],
"revision_scope": ["source_coverage"],
"severity": "blocking"
}
If the same blocking issue remains after the permitted revision attempts, stop the automated cycle and escalate it. Repeating an unchanged request is not a recovery strategy.
Use a delegation allowlist
Define which agents may call which other agents. For example:
- Planner may create research tasks.
- Researcher may return evidence to the orchestrator.
- Analyst may request a permitted evidence gap to be filled.
- Reviewer may request a bounded revision.
- No specialist may directly restart the entire workflow.
This makes circular delegation impossible unless the application explicitly allows it. A directed acyclic graph is a useful default for workflows with fixed dependencies. Where cycles are genuinely required, make them explicit and place strict iteration limits around them.
Frameworks can provide useful termination primitives, but they should supplement application-level policy. For example, AutoGen documents termination conditions such as maximum message count, token usage, and time limits in its termination guide.
8. Guardrails at the right boundaries
Guardrails should not be treated as a single prompt appended to every agent. Different risks appear at different points in the workflow, and each boundary needs the appropriate control.
Input guardrails
Validate the initial request before expensive or sensitive work begins. Enforce authentication, tenant boundaries, input limits, allowed task categories, and policy restrictions.
Agent output guardrails
Check that an agent’s response conforms to its schema and does not contain prohibited or malformed output. For high-impact decisions, add independent verification rather than trusting a self-assessment from the same model.
Tool guardrails
Validate tool arguments before execution. A model may propose an action, but the application must check the caller’s permissions, target resource, operation, and current workflow state.
Side-effect guardrails
Place strong controls immediately before operations that change external or persistent state: sending messages, publishing content, deleting records, changing account settings, making purchases, or executing commands.
These controls should be enforced in the tool implementation or service boundary, not merely in agent instructions.
Never confuse instructions with permissions
A system prompt saying “do not delete records” is not an authorization system. The delete operation itself must verify the caller, resource, scope, and approval state before it executes.
OpenAI’s guide to guardrails and human review distinguishes automatic checks from approval decisions and describes why sensitive tool calls need controls at the point where the action occurs.
Fail closed for sensitive operations
If an authorization service is unavailable, an approval record cannot be verified, or the target is outside the permitted scope, do not execute the action as a fallback. Return a controlled failure or pause for review.
Read-only operations may have different availability policies. The important point is to classify actions by risk instead of applying one permissive fallback to every tool.
9. Human approval and resumable workflows
Some decisions should not be delegated to an autonomous agent. Human review is appropriate when an action has significant financial, legal, privacy, security, or operational consequences, or when the system cannot confidently establish that the action is within policy.
A human approval step should be a real workflow state, not a message asking someone to reply in a chat that the application cannot reliably track.
A proper approval lifecycle
- The workflow reaches an action requiring approval.
- The application records the proposed action and its exact parameters.
- The workflow enters
WAITING_APPROVAL. - The approval request is delivered to an authorized reviewer.
- The reviewer approves, rejects, or requests changes.
- The application validates the reviewer’s identity and decision.
- The workflow resumes from its saved state or terminates according to policy.
Approval should be bound to the exact action being approved. If the target, amount, destination, permissions, or other material parameters change, the previous approval may no longer be valid.
Persist the pending action
A durable approval record might contain:
{
"approval_id": "approval-1082",
"workflow_id": "workflow-204",
"status": "pending",
"action": {
"type": "publish_document",
"resource_id": "document-77",
"version": 4
},
"requested_by": "workflow-service",
"policy_version": "2026-01",
"created_at": "2026-11-08T10:00:00Z",
"expires_at": "2026-11-09T10:00:00Z"
}
This is an illustrative record. Production systems should also track reviewer identity, decision timestamp, decision rationale, action fingerprint, and any relevant audit metadata.
Resume the same workflow
Do not restart the entire agent conversation after approval if the framework supports durable execution state. Resume the same workflow using its saved checkpoint and validated approval result.
LangGraph’s interrupt documentation describes pausing graph execution for external input and resuming from persisted state. Its persistence documentation covers checkpointing and state recovery.
One implementation detail matters: when a node is re-executed after an interrupt or retry, code before the interruption may run again depending on the framework’s execution semantics. Design those operations to be idempotent, and verify the current framework documentation before relying on a particular resume behavior.
10. Retries, idempotency, and recovery
Retries are essential for distributed systems, but blindly retrying every failure can make a multi-agent workflow less reliable.
First classify failures by whether another attempt is likely to help.
| Failure class | Example | Recommended handling |
|---|---|---|
| Transient | Temporary network error or rate limit. | Bounded retry with backoff and jitter. |
| Timeout | Tool did not return before its deadline. | Check whether the operation completed before retrying. |
| Validation | Agent output fails schema validation. | Reject, optionally request one constrained correction, then stop. |
| Authorization | Caller lacks permission. | Do not retry automatically. |
| Business rule | Requested operation violates policy. | Return a controlled rejection or escalate. |
| Unknown | Unclassified exception. | Record, contain, and avoid unlimited retries. |
Use bounded exponential backoff
For transient failures, exponential backoff can reduce pressure on a struggling service. Jitter helps prevent many workers from retrying simultaneously.
A common policy is:
delay = min(max_delay, base_delay * (2 ** attempt))
wait_time = random_between(0, delay)
The retry count must be finite. Also enforce an overall deadline so a series of individually reasonable waits cannot keep a workflow alive indefinitely.
AWS Step Functions documents retry and catch behavior, including maximum attempts and backoff configuration, in its error-handling guide.
Understand the timeout ambiguity
A timeout does not prove that an operation failed. The remote service may have completed the request while the response was lost.
For example:
- The workflow submits a request to create a resource.
- The remote service creates the resource.
- The response is lost or delayed.
- The workflow records a timeout.
- A naive retry creates a duplicate resource.
For operations with side effects, the recovery path should first determine whether the original action succeeded. Use an idempotency key or query the remote system by a stable operation identifier.
Idempotency keys
An idempotent operation can be repeated without producing additional unintended effects. A practical approach is to derive a stable key from the workflow and logical operation:
idempotency_key =
workflow_id + ":" + operation_type + ":" + operation_id
The receiving service should store the key and the original result. If the same logical operation arrives again, it should return the recorded result rather than perform the action a second time.
Generating a key in the caller is not enough if the downstream service ignores it. When the external API does not support idempotency, use a durable operation ledger, reconciliation process, or read-before-write strategy where appropriate.
Checkpoint the workflow
Persist completed work so a failure does not require repeating every stage. A useful checkpoint can include:
- Workflow ID and state version.
- Current state and pending transition.
- Completed task IDs and validated outputs.
- Attempt counts and remaining budgets.
- Tool execution identifiers and idempotency keys.
- Approval status and pending reviewer decisions.
- Last successful checkpoint and error details.
Checkpointing is not a substitute for transaction design. A database write and an external API call generally cannot be made atomic simply by saving workflow state. Use an outbox pattern, durable operation records, idempotency, and reconciliation to handle the boundary between your database and external systems.
11. A practical implementation example
The following Python example demonstrates the control-plane idea without depending on a particular agent framework. It defines a small state machine, limits review cycles, validates transition requests, and keeps terminal states from being reopened.
The example uses Python 3.11 or later because it uses StrEnum. It is a teaching example, not a complete durable workflow engine: persistence, concurrency control, schema validation, authentication, and tool execution would need to be added for production use.
Define states and events
from enum import StrEnum
from dataclasses import dataclass
class State(StrEnum):
RECEIVED = "received"
RESEARCHING = "researching"
ANALYZING = "analyzing"
REVIEWING = "reviewing"
REVISING = "revising"
COMPLETED = "completed"
FAILED = "failed"
class Event(StrEnum):
START = "start"
RESEARCH_DONE = "research_done"
ANALYSIS_DONE = "analysis_done"
ACCEPT = "accept"
REQUEST_REVISION = "request_revision"
REVISION_DONE = "revision_done"
ABORT = "abort"
TERMINAL_STATES = {
State.COMPLETED,
State.FAILED,
}
Define the allowed transition graph
TRANSITIONS = {
(State.RECEIVED, Event.START):
State.RESEARCHING,
(State.RESEARCHING, Event.RESEARCH_DONE):
State.ANALYZING,
(State.ANALYZING, Event.ANALYSIS_DONE):
State.REVIEWING,
(State.REVIEWING, Event.ACCEPT):
State.COMPLETED,
(State.REVIEWING, Event.REQUEST_REVISION):
State.REVISING,
(State.REVISING, Event.REVISION_DONE):
State.REVIEWING,
}
Keep transition decisions in application code
@dataclass
class Workflow:
workflow_id: str
state: State = State.RECEIVED
revision_count: int = 0
max_revisions: int = 2
version: int = 0
def transition(self, event: Event) -> State:
if self.state in TERMINAL_STATES:
raise ValueError(
f"Workflow is terminal: {self.state}"
)
if event == Event.ABORT:
self.state = State.FAILED
self.version += 1
return self.state
if (
self.state == State.REVIEWING
and event == Event.REQUEST_REVISION
):
if self.revision_count >= self.max_revisions:
self.state = State.FAILED
self.version += 1
return self.state
self.revision_count += 1
key = (self.state, event)
if key not in TRANSITIONS:
raise ValueError(
f"Invalid transition: {self.state} -> {event}"
)
self.state = TRANSITIONS[key]
self.version += 1
return self.state
Run a controlled sequence
workflow = Workflow(
workflow_id="research-204",
max_revisions=2,
)
workflow.transition(Event.START)
workflow.transition(Event.RESEARCH_DONE)
workflow.transition(Event.ANALYSIS_DONE)
# Reviewer requests one correction.
workflow.transition(Event.REQUEST_REVISION)
# The revised result returns for review.
workflow.transition(Event.REVISION_DONE)
# Reviewer accepts the result.
workflow.transition(Event.ACCEPT)
assert workflow.state == State.COMPLETED
The example deliberately does not ask an agent to set workflow.state directly. An agent can return a proposed event, such as REQUEST_REVISION, but the application validates that event against the current state and its policy.
What must be added before production
- Persist workflow state and version in a durable database.
- Use atomic updates or optimistic concurrency checks to prevent conflicting transitions.
- Validate all agent output against explicit schemas.
- Enforce per-agent tool permissions and per-workflow budgets.
- Store an append-only event or audit history.
- Use idempotency keys for external side effects.
- Implement timeout, cancellation, and recovery behavior.
- Protect sensitive transitions with explicit human approval.
- Record model, prompt, tool, and policy versions for reproducibility.
For larger workflows, a graph or workflow engine can provide durable execution, retries, checkpointing, and human-in-the-loop primitives. The important requirement is not which framework you choose; it is that the application retains clear ownership of policy and execution boundaries.
12. Observability and production evaluation
A workflow that finishes successfully is not necessarily a reliable workflow. It may have used excessive tokens, repeated a tool call, ignored a quality requirement, or taken an unnecessarily long route.
Instrument the workflow so operators can understand both the final outcome and the path taken to reach it.
Record workflow-level data
- Workflow ID, tenant, request type, and start/end timestamps.
- Final status and failure classification.
- State transitions and transition rejection reasons.
- Agent invocation counts and duration.
- Token usage and estimated model cost.
- Tool calls, latency, errors, and idempotency outcomes.
- Retry, revision, and delegation counts.
- Approval requests, decisions, and waiting time.
- Schema-validation and policy-check outcomes.
Measure quality, not just activity
Useful operational metrics include:
| Metric | What it reveals |
|---|---|
| Task completion rate | How often workflows reach an accepted terminal state. |
| Revision rate | How often review identifies work that needs correction. |
| Repeated-task rate | Whether the system is scheduling equivalent work unnecessarily. |
| Invalid-transition rate | How often agents propose actions the state machine rejects. |
| Tool failure rate | Where external dependencies are disrupting execution. |
| Cost per accepted result | Whether additional agent complexity produces useful value. |
| Time to completion | How long users wait for an accepted result. |
| Human escalation rate | How often automated execution needs human intervention. |
Track these metrics by workflow type and task complexity. A high revision rate may indicate a weak prompt, poor source quality, unclear acceptance criteria, or a reviewer that is too strict. The metric alone does not identify the cause.
Preserve traceability without leaking sensitive data
Logs should make it possible to reconstruct important decisions, but that does not mean storing every prompt, tool result, and user record indefinitely. Apply data minimization, access controls, retention limits, and redaction to traces and model inputs.
For debugging, record stable identifiers and relevant decision metadata. Where full content is necessary, restrict access and apply an explicit retention policy.
Evaluate the workflow as a system
Test more than the individual agents. Include scenarios that exercise the complete control flow:
- Valid task that completes without revision.
- Invalid agent output.
- Repeated review feedback.
- Agent requesting an unauthorized tool.
- Delegation cycle attempt.
- Tool timeout after a possible successful side effect.
- Concurrent updates to the same workflow.
- Approval rejection or expiration.
- Worker crash and checkpoint recovery.
- Budget exhaustion at different workflow stages.
For each test, verify not only the final response but also the state transitions, tool executions, audit records, and absence of unintended side effects.
13. Production readiness checklist
Before deploying a multi-agent workflow, verify that the following controls are implemented and tested.
CONTROL PLANE
- Every workflow has a defined set of states.
- Every valid transition is explicitly defined.
- Terminal states cannot be reopened by late agent responses.
- Concurrent state updates are protected.
AGENT CONTRACTS
- Each agent has a bounded responsibility.
- Inputs and outputs use validated schemas.
- Tool permissions are assigned outside the model prompt.
- Agent-reported completion is independently verified.
LOOP AND COST CONTROL
- Model and tool calls have finite limits.
- Delegation depth is bounded.
- Revision cycles have explicit limits.
- Repeated logical tasks are detected.
- Time, token, and monetary budgets are enforced.
SAFETY AND RECOVERY
- Sensitive operations are checked at the tool boundary.
- High-impact actions have an approval path.
- Retries are limited to appropriate failure classes.
- External side effects use idempotency or reconciliation.
- Workflow state can be recovered from durable checkpoints.
OBSERVABILITY
- Transitions, tool calls, failures, and approvals are traceable.
- Cost and latency are measured per workflow.
- Logs follow data-retention and privacy policies.
- Failure and recovery scenarios are tested before release.
14. Frequently asked questions
What is a deterministic multi-agent workflow?
It is a multi-agent system in which application code controls workflow state, valid transitions, permissions, retries, budgets, and termination. Agents can still use probabilistic reasoning, but they cannot independently bypass the application’s execution rules.
Are state machines necessary for every AI agent?
No. A simple, low-risk task may only need a single model call and a small amount of validation. State machines become more valuable when a workflow has multiple stages, branching, retries, external side effects, approvals, or durable execution requirements.
How do you stop AI agents from entering infinite loops?
Use several controls together: finite model and tool-call budgets, delegation-depth limits, bounded revision cycles, repeated-task detection, deadlines, and explicit terminal states. Do not rely only on an instruction telling the agent to stop.
Should agents be allowed to call other agents directly?
Only when the architecture explicitly permits it. A safer default is to route delegation through an orchestrator that validates the requested specialist, task scope, budget, and allowed transition.
What is the difference between a retry and a revision?
A retry repeats an operation after a failure, usually because the failure may be transient. A revision changes an output in response to a quality or requirement issue. They need separate limits and policies because repeating a failed network request is not the same as asking an agent to rewrite its analysis.
Why are idempotency keys important in agent workflows?
They help prevent duplicate side effects when a tool call is retried or a workflow resumes after an ambiguous timeout. The downstream service must actually honor the key, or the application needs another reliable deduplication and reconciliation mechanism.
Can LangGraph be used for deterministic agent workflows?
LangGraph provides graph execution, state management, persistence, and interrupt mechanisms that can support controlled workflows. Application code still needs to define its policies, validate agent outputs, enforce permissions, and make side effects safe to repeat.
Does a deterministic workflow guarantee accurate AI output?
No. It makes execution and control flow more predictable; it does not make model reasoning infallible. Accuracy still depends on source quality, evaluation, domain validation, model behavior, and appropriate human review.
Conclusion: Make the application responsible for control
Multi-agent systems become difficult to operate when the same components that generate reasoning are also allowed to control their own permissions, workflow state, retries, and termination.
A more dependable design separates those responsibilities. The orchestrator owns the state machine. Agents operate within narrow contracts. Guardrails validate inputs, outputs, and tool actions. Budgets constrain execution. Idempotency protects side effects. Checkpoints and approval states make long-running work recoverable.
The goal is not to eliminate model flexibility. It is to put that flexibility inside a system with clear boundaries.
Let agents reason. Let application code govern execution.
References and further reading
- Anthropic — Building Effective Agents. A discussion of agentic systems, predefined workflows, and common architecture patterns.
- OpenAI — Orchestration and Handoffs. Manager-style orchestration and specialist handoffs.
- OpenAI — Guardrails and Human Review. Automatic checks and approval boundaries for sensitive tool actions.
- LangGraph — Graph API. Graph-based workflow execution and state management.
- LangGraph — Persistence. Checkpointing and durable graph state.
- LangGraph — Interrupts. Pausing execution for external input and resuming workflows.
- Microsoft AutoGen — Termination. Termination conditions for agent teams.
- AWS Step Functions — Error Handling. Retry, backoff, and catch patterns for state-machine workflows.