Inferensys

Prompt

Workflow Error Boundary Agent Prompt

A practical prompt playbook for containing agent failures within a workflow. Produces an error boundary definition with catch scopes, fallback agents, partial-result salvage rules, and escalation paths.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for deploying a Workflow Error Boundary Agent.

This prompt is for reliability engineers and platform builders who need to contain agent failures within a multi-step workflow. The job-to-be-done is defining a structured error boundary that catches exceptions, salvages partial results, routes to fallback agents, and escalates when containment fails. Use it when a single agent's failure should not crash the entire workflow graph, and when you need a programmatic contract—not just a try/catch block—that the orchestrator can execute.

The ideal user has already mapped their agent dependencies and knows which steps are critical versus recoverable. Required context includes the failing agent's role, the exception type or error signature, the state of upstream outputs, and the downstream agents waiting for a result. Do not use this prompt for simple single-agent retry logic or for workflows where every failure should halt execution immediately. It is designed for partial-progress salvage, not for debugging the root cause of the error itself.

Before wiring this into production, ensure you have defined the catch scopes precisely. Ambiguous boundaries cause error propagation leaks where a contained failure silently corrupts downstream state. The prompt template below expects you to supply the error context, available fallback agents, salvage rules, and escalation paths. After generating the boundary definition, validate it against your workflow's directed acyclic graph (DAG) to confirm no unhandled exception types can escape the boundary. For high-risk domains, always include a human review step before executing fallback or salvage logic that modifies persistent state.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Workflow Error Boundary Agent Prompt delivers value and where it introduces unnecessary complexity or false confidence.

01

Good Fit: Multi-Agent Production Pipelines

Use when: you have a graph of specialized agents where one agent's failure should not crash the entire workflow. Guardrail: Define explicit catch scopes per agent step, not a single global catch-all that masks root causes.

02

Bad Fit: Single-Agent Prototypes

Avoid when: you are building a single-agent script or a notebook prototype. Error boundaries add orchestration overhead without benefit. Guardrail: Introduce the boundary agent only when you have at least two agents with independent failure modes.

03

Required Input: Agent Execution Contracts

What to watch: the error boundary agent needs typed contracts per step—expected inputs, outputs, error signatures, and timeout bounds. Without these, fallback logic guesses at recovery. Guardrail: Validate that every agent under the boundary has a documented contract before deploying the boundary prompt.

04

Required Input: Partial-Result Salvage Rules

What to watch: the boundary agent must know which partial results are safe to preserve and which must be discarded. Ambiguous salvage rules produce corrupted downstream state. Guardrail: Define explicit field-level salvage policies per agent output schema, not per workflow.

05

Operational Risk: Error Propagation Leaks

Risk: unhandled exception types or malformed error payloads can bypass the boundary agent and crash the orchestrator. Guardrail: Test the boundary against every error signature in the agent contract, plus malformed JSON, timeout, and authentication failure scenarios.

06

Operational Risk: Escalation Loop Exhaustion

Risk: a fallback agent that also fails can trigger recursive escalation, consuming resources until a hard timeout. Guardrail: Cap escalation depth to one level and define a terminal state that halts the workflow with a structured failure record for human review.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for defining error boundaries, catch scopes, fallback agents, partial-result salvage rules, and escalation paths when an agent fails inside a workflow.

This template produces an error boundary definition for a specific agent step within a multi-agent workflow. It is designed to be used by reliability engineers and platform builders who need to contain failures, prevent cascading errors, and decide what happens to partial work when an agent cannot complete its task. The prompt requires a description of the failing agent's role, the exception or failure mode encountered, the workflow context, and the desired output schema for the boundary definition.

text
You are a Workflow Error Boundary Agent. Your job is to produce a structured error boundary definition that contains a failure, preserves salvageable partial results, and defines a clear escalation path.

## INPUT
- **Failing Agent Role**: [FAILING_AGENT_ROLE]
- **Failure Description**: [FAILURE_DESCRIPTION]
- **Exception Type**: [EXCEPTION_TYPE]
- **Workflow Step ID**: [WORKFLOW_STEP_ID]
- **Upstream Dependencies**: [UPSTREAM_DEPENDENCIES]
- **Downstream Dependencies**: [DOWNSTREAM_DEPENDENCIES]
- **Partial Results Available**: [PARTIAL_RESULTS_AVAILABLE]
- **Workflow State Snapshot**: [WORKFLOW_STATE_SNAPSHOT]

## CONSTRAINTS
- Do not invent recovery steps that require capabilities the system does not have.
- If partial results are present, explicitly state which fields are safe to forward and which must be discarded.
- If the failure is non-retryable, do not suggest a retry loop.
- Escalation paths must include a specific target (agent ID, human queue, or dead-letter topic).
- The boundary definition must be executable by an orchestration engine without human interpretation.

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "error_boundary_id": "string",
  "workflow_step_id": "string",
  "failure_classification": "retryable" | "non_retryable" | "degraded" | "fatal",
  "catch_scope": {
    "exception_types": ["string"],
    "additional_conditions": ["string"]
  },
  "partial_result_salvage_rules": [
    {
      "field_path": "string",
      "action": "forward" | "discard" | "redact" | "replace_with_default",
      "default_value": "any",
      "reason": "string"
    }
  ],
  "fallback_agent": {
    "agent_id": "string | null",
    "fallback_prompt_override": "string | null",
    "max_fallback_attempts": "number"
  },
  "escalation_path": {
    "target": "human_review_queue" | "dead_letter_topic" | "parent_workflow" | "incident_ticket",
    "target_identifier": "string",
    "escalation_payload": {
      "summary": "string",
      "original_error": "string",
      "workflow_context_snapshot": "object"
    },
    "sla_minutes": "number"
  },
  "propagation_policy": {
    "block_downstream": "boolean",
    "notify_upstream": "boolean",
    "affected_step_ids": ["string"]
  },
  "recovery_actions": [
    {
      "action": "string",
      "target": "string",
      "payload": "object",
      "precondition": "string"
    }
  ],
  "test_assertions": [
    {
      "test_case": "string",
      "expected_behavior": "string",
      "failure_mode_if_missing": "string"
    }
  ]
}

## INSTRUCTIONS
1. Classify the failure using the exception type, failure description, and workflow state.
2. Identify which partial results can be salvaged and which must be discarded. Be conservative: when in doubt, discard.
3. Select a fallback agent only if one exists that can handle the degraded input. Otherwise, set fallback_agent to null and escalate.
4. Define the escalation path with enough context that a human reviewer or incident system can act without re-investigating.
5. Set propagation policy to block downstream steps that depend on the failed step's output. Do not block independent parallel branches.
6. Include at least three test assertions that verify the boundary catches error propagation leaks, unhandled exception types, and missing salvage rules.

## EXAMPLES
[EXAMPLES]

## RISK_LEVEL
[RISK_LEVEL]

Adapt this template by replacing each square-bracket placeholder with concrete values from your workflow execution context. The [EXAMPLES] placeholder should contain one or two few-shot examples of correct error boundary definitions for your domain, showing both a retryable transient failure and a fatal unrecoverable failure. The [RISK_LEVEL] placeholder should be set to low, medium, high, or critical and will influence how conservative the salvage rules and escalation paths become. For high-risk or regulated workflows, always require human review on the escalation path and set propagation_policy.block_downstream to true for any step that consumes the failed agent's output. Before deploying, validate the output against the JSON schema and run the generated test assertions against a simulated failure injection harness to confirm the boundary catches the failure modes you expect.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Workflow Error Boundary Agent. Each placeholder must be resolved before the prompt is assembled. Missing or malformed variables will cause the error boundary to fail open or produce incomplete catch scopes.

PlaceholderPurposeExampleValidation Notes

[WORKFLOW_DEFINITION]

Complete DAG or sequence of agent steps with their contracts, expected inputs, and outputs

{"steps":[{"id":"classify","agent":"triage-agent","contract":"..."}]}

Must parse as valid JSON. Reject if missing steps array or any step lacks an id field. Schema check required before prompt assembly.

[FAILURE_MODE_CATALOG]

Known failure modes per agent step including tool timeouts, invalid outputs, schema violations, and model refusals

{"classify":["timeout_30s","low_confidence","refusal"]}

Must be a valid JSON object keyed by step id. Reject if any step in WORKFLOW_DEFINITION has no corresponding entry. Null allowed for steps with no known failure modes.

[ESCALATION_POLICY]

Rules for when to escalate to a human, a supervisor agent, or a dead-letter queue including priority thresholds and SLA

{"max_retries":3,"human_escalation":["PII_detected","policy_violation"],"dead_letter_after":"1h"}

Must parse as valid JSON. Required fields: max_retries, human_escalation, dead_letter_after. Reject if max_retries is not a positive integer.

[FALLBACK_AGENTS]

Mapping of primary agent to fallback agent for each step where graceful degradation is allowed

{"classify":"simple-classifier","extract":"regex-extractor","summarize":null}

Must be a valid JSON object keyed by step id. Value must be a valid agent id string or null. Reject if fallback agent id is not in the available agent registry.

[PARTIAL_RESULT_POLICY]

Rules for salvaging partial results when a step fails: which fields are salvageable, merge strategy, and minimum completeness threshold

{"salvageable_fields":["entities","intent"],"min_completeness":0.6,"merge_strategy":"best_effort"}

Must parse as valid JSON. min_completeness must be a float between 0.0 and 1.0. merge_strategy must be one of: best_effort, strict, discard. Reject unknown merge strategies.

[RETRY_CONFIGURATION]

Per-step retry policy with backoff strategy, max attempts, and retryable error classification

{"default":{"max_attempts":2,"backoff":"exponential","retryable":["timeout","rate_limit"]},"classify":{"max_attempts":1}}

Must parse as valid JSON. Must include a default key. backoff must be one of: none, linear, exponential. Reject if max_attempts exceeds 5 without explicit approval flag.

[ERROR_PROPAGATION_RULES]

Rules for which errors propagate to parent workflow, which are contained, and containment scope boundaries

{"containment_scopes":["classify","extract"],"propagate":["auth_failure","quota_exceeded"],"contain":["timeout","invalid_output"]}

Must parse as valid JSON. containment_scopes must be an array of step ids present in WORKFLOW_DEFINITION. Reject if propagate and contain lists have overlapping error types.

[OUTPUT_SCHEMA]

Expected schema for the error boundary definition output including catch scopes, fallback paths, and salvage instructions

{"type":"object","required":["catch_scopes","fallback_map","salvage_rules","escalation_paths"]}

Must be a valid JSON Schema draft. Reject if required array is empty. Validate that all referenced step ids exist in WORKFLOW_DEFINITION. Schema check required before prompt assembly.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Workflow Error Boundary Agent Prompt into a production agent orchestration system with validation, retries, logging, and safe fallback execution.

The Workflow Error Boundary Agent Prompt is not a standalone prompt—it is a system-level contract that wraps other agent calls. In production, this prompt should be invoked by your orchestrator whenever a workflow step executes a fallible agent. The orchestrator passes the failing agent's context, error signature, and partial results into the error boundary prompt, which then decides whether to retry, fall back to a salvage agent, escalate to a human, or terminate the workflow branch. This harness must be idempotent: calling the error boundary twice with the same failure context should produce the same decision and not duplicate side effects.

Integration pattern: Wrap each agent invocation in a try/catch block at the orchestrator level. On failure, construct the error boundary input payload with [FAILED_AGENT_ID], [ERROR_TYPE], [ERROR_MESSAGE], [PARTIAL_RESULTS], [WORKFLOW_STEP_CONTEXT], and [UPSTREAM_DEPENDENCIES]. Send this payload to the error boundary prompt. The prompt returns a structured decision object containing action (one of retry, fallback, escalate, terminate), fallback_agent_id, retry_strategy (with max_attempts and backoff_seconds), salvageable_fields, and escalation_reason. Your harness must parse this output and execute the chosen path. Validate the output before acting: reject decisions that reference non-existent fallback agents, exceed global retry budgets, or attempt to salvage fields that were never produced.

Retry loop safety: If the error boundary returns retry, your harness must enforce a global retry budget per workflow run (e.g., max 3 retries across all steps) and per-step backoff with jitter. Do not blindly trust the prompt's retry_strategy—clamp max_attempts to your system limit and add randomized jitter to backoff_seconds to avoid thundering herd on downstream services. Log every retry decision with the error boundary's rationale for later trace analysis. Fallback execution: When fallback is selected, route the salvageable partial results to the specified fallback agent. The fallback agent should receive a normalized input that includes only the fields marked salvageable plus the original task context. After fallback completion, compare the fallback output against the original agent's expected output schema and flag any missing required fields for human review.

Escalation and human review: For escalate decisions, your harness must package the error boundary's output alongside the full failure trace into a structured ticket or review queue payload. Include [ERROR_TYPE], [ESCALATION_REASON], [PARTIAL_RESULTS], and a link to the workflow trace. Do not let the workflow silently block—set a deadline escalation timer so that if no human acknowledges the escalation within a configured window, the harness either terminates the branch or invokes a last-resort compensation handler. Termination path: When terminate is returned, execute any registered compensation actions for completed upstream steps (if using a saga pattern) and mark the workflow branch as FAILED_TERMINAL with the error boundary's rationale attached.

Observability requirements: Every error boundary invocation must emit structured logs containing the decision, rationale, retry count, fallback agent used, and whether human review was triggered. These logs feed your workflow trace analysis and error budget monitoring. Track error boundary decision distributions over time—if escalate rates spike, you likely have a systemic agent failure or a prompt that needs updating. Testing the harness: Before production, run the error boundary prompt against a failure injection suite that simulates timeout errors, malformed agent outputs, tool authentication failures, partial result corruption, and upstream dependency failures. Verify that the harness correctly executes each decision path, enforces retry budgets, and never silently swallows errors. A dry-run mode that simulates the error boundary decision without executing side effects is essential for validating new error boundary prompt versions against historical failure traces.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the Workflow Error Boundary Agent output. Use this contract to parse, validate, and route the agent response before downstream consumption.

Field or ElementType or FormatRequiredValidation Rule

error_boundary_id

string (UUID v4)

Must parse as valid UUID v4; reject if null or malformed

catch_scope

object with agent_id (string), step_id (string), error_types (string[])

agent_id and step_id must be non-empty strings; error_types must contain at least one entry from the known error taxonomy

fallback_agent

object with agent_id (string), capability_match (string), priority (integer)

agent_id must be non-empty; priority must be a positive integer; capability_match must be a non-empty rationale string

partial_result_salvage_rules

array of objects with field_path (string), salvage_action (enum: PRESERVE | TRANSFORM | DISCARD), transform_instruction (string | null)

field_path must be valid dot-notation path; salvage_action must be one of the enum values; transform_instruction required when salvage_action is TRANSFORM, null otherwise

escalation_path

object with target (enum: AGENT | HUMAN | QUEUE), target_id (string), condition (string), max_wait_seconds (integer | null)

target must be valid enum; target_id must be non-empty; condition must be non-empty; max_wait_seconds must be positive integer or null for no timeout

error_propagation_policy

object with propagate_to_upstream (boolean), propagate_to_downstream (boolean), suppressed_error_types (string[])

propagate_to_upstream and propagate_to_downstream must be boolean; suppressed_error_types must be array of strings from known error taxonomy, empty array allowed

retry_config

object with max_retries (integer), backoff_strategy (enum: FIXED | EXPONENTIAL | NONE), retryable_error_types (string[])

If present, max_retries must be non-negative integer; backoff_strategy must be valid enum; retryable_error_types must be subset of known error taxonomy

test_assertions

array of objects with test_case_id (string), expected_boundary_behavior (string), leak_detection_check (string)

test_case_id must be non-empty; expected_boundary_behavior must describe expected containment; leak_detection_check must specify how to detect propagation leaks

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when an error boundary agent is deployed in production, and how to prevent cascading failures across agent workflows.

01

Error Propagation Leaks

What to watch: An unhandled exception in one agent silently propagates to downstream agents, corrupting their inputs and producing plausible but incorrect outputs. The error boundary catches the exception but fails to sanitize the partial state before fallback. Guardrail: Require the error boundary to produce a typed ErrorContainmentReport with explicit contaminated_state_keys and a clean_restart_payload before any fallback agent executes.

02

Fallback Agent Mismatch

What to watch: The error boundary routes to a fallback agent that lacks the capability or context to complete the task, producing a degraded result that downstream agents treat as authoritative. Guardrail: Validate fallback agent capability contracts at registration time. Include a capability_gap_flag in the error boundary output when the fallback cannot meet the original agent's output schema, forcing upstream re-evaluation.

03

Partial Result Salvage Corruption

What to watch: The error boundary attempts to salvage partial results from the failed agent but includes stale, inconsistent, or unvalidated data that violates downstream agent input contracts. Guardrail: Implement a salvage_validator that checks each salvaged field against the downstream agent's input schema. Discard any field that fails validation rather than passing unverified data forward.

04

Escalation Path Exhaustion

What to watch: The error boundary retries or escalates through a chain of fallbacks that all fail, eventually hitting a terminal state with no recovery path and a stranded workflow. Guardrail: Define a maximum escalation depth with a terminal dead_letter_handler that persists the full error context, notifies operations, and cleanly terminates the workflow rather than looping indefinitely.

05

Unhandled Exception Type Blindness

What to watch: The error boundary is configured to catch known exception types but misses novel failure modes such as tool authentication expiry, rate-limit backpressure, or model refusal signals, treating them as generic errors with inappropriate fallback logic. Guardrail: Include an unknown_error_classifier step that inspects unclassified exceptions and assigns a provisional error category with conservative fallback behavior, logging the novel type for boundary rule updates.

06

Error Boundary Bypass via Nested Agents

What to watch: A parent agent calls a sub-agent or tool directly without routing through the error boundary, creating an unprotected execution path where failures escape containment. Guardrail: Enforce a workflow-level invariant that all inter-agent calls pass through the error boundary proxy. Validate this at graph construction time by checking for edges that skip the boundary node.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Workflow Error Boundary Agent Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Error containment scope

Output defines a catch scope that explicitly lists handled exception types and unhandled pass-through types

Catch scope is empty, catches generic Exception only, or fails to list unhandled types

Parse output JSON; assert catch_scope.handled_types is non-empty array; assert catch_scope.pass_through_types is defined

Fallback agent assignment

Output assigns a valid fallback agent for each error category with a defined input contract

Fallback agent is null, references a non-existent agent, or omits required input schema

Validate fallback_agent field is non-null per error category; check agent ID exists in known agent registry; assert input_schema is present

Partial-result salvage rules

Output specifies which partial outputs are salvageable and how to transform them for downstream consumers

Salvage rules are absent, mark all results as unsalvageable without justification, or produce invalid downstream schemas

Assert salvage_rules array is non-empty; validate each rule has output_path, transform, and downstream_schema fields; schema-check downstream_schema against consumer contract

Escalation path definition

Output defines escalation path with trigger conditions, target, payload format, and timeout

Escalation path is missing, has no trigger conditions, or references an undefined escalation target

Assert escalation.path is non-null; validate trigger_conditions array is non-empty; check target exists in routing table; assert timeout_seconds > 0

Error propagation leak prevention

Output explicitly blocks error details from leaking to unauthorized downstream agents or user-facing surfaces

Error details appear in fields marked for downstream or user consumption without sanitization

Run propagation leak test case: inject sensitive error; assert user_facing_message contains no stack traces or internal state; assert downstream_payload excludes raw error objects

Unhandled exception type coverage

Output identifies at least 3 unhandled exception types with explicit pass-through or termination behavior

Output claims 100% coverage, lists fewer than 3 unhandled types, or provides no termination behavior for unknowns

Inject unlisted exception type into test harness; assert output produces defined termination or pass-through action, not undefined behavior

Retry policy integration

Output specifies whether the error boundary triggers retry, and if so, defines max retries, backoff, and retryable error classification

Retry policy is undefined, retries non-retryable errors, or lacks backoff configuration

Assert retry_policy field is present; validate max_retries >= 0; check retryable_errors list does not include deterministic failures; assert backoff_strategy is defined

Timeout and deadline handling

Output defines a deadline for the error boundary scope and specifies behavior on timeout

No deadline specified, timeout behavior is undefined, or timeout triggers undefined state

Assert deadline_seconds is present and > 0; validate on_timeout.action is one of [escalate, terminate, fallback]; check timeout payload schema is valid

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a typed error boundary contract with explicit catch scopes, structured fallback agent assignments, partial-result salvage rules, and escalation paths. Include schema validation on the boundary output and wire it into your workflow engine's error handler.

code
You are an error boundary agent. Respond ONLY with valid JSON matching [ERROR_BOUNDARY_SCHEMA].

CATCH SCOPES:
- Agent timeout (> [TIMEOUT_MS]ms)
- Tool call failure (non-2xx, connection refused)
- Invalid output (schema validation failure)
- Policy violation (blocked action)

For each caught error:
1. Classify as: RETRYABLE | FALLBACK | ESCALATE | CIRCUIT_BREAK
2. If RETRYABLE: provide retry strategy (backoff=[BACKOFF_MS]ms, max_attempts=[MAX_RETRIES])
3. If FALLBACK: select fallback agent from [FALLBACK_AGENT_MAP], include context transfer payload
4. If ESCALATE: produce structured handoff with [ESCALATION_CHANNEL], severity, and evidence package
5. If CIRCUIT_BREAK: halt downstream agents, preserve partial results, trigger [CIRCUIT_BREAKER_CONFIG]

SALVAGE RULES:
- Preserve completed upstream agent outputs in [PARTIAL_RESULTS_STORE]
- Mark incomplete agent steps as ABANDONED with last-known state
- Do not re-execute idempotent steps that succeeded

Watch for

  • Silent format drift in the boundary output—validate against schema on every invocation
  • Missing circuit breaker integration—repeated retries on the same failure class should trip the breaker
  • Partial-result corruption when multiple boundaries fire concurrently in parallel agent branches
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.