Inferensys

Prompt

Input/Output Contract Definition Prompt for Sub-Agents

A practical prompt playbook for using Input/Output Contract Definition Prompt for Sub-Agents in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the reader, and the constraints for using the Input/Output Contract Definition Prompt for Sub-Agents.

This prompt is for integration engineers and platform developers who need to define strict, machine-readable contracts between an orchestrator agent and its sub-agents. The job-to-be-done is converting a natural language task description into a typed schema that a sub-agent must satisfy, eliminating ambiguity about required fields, data types, enum constraints, and error handling expectations. Use this when you are building a multi-agent system where downstream agents consume structured output from upstream agents, and a parsing failure or missing field would break the entire workflow.

The ideal user has already decomposed a complex task into sub-tasks and assigned them to specialized agents. They now need to lock down the data contract for a specific sub-agent before it executes. Required context includes the sub-agent's assigned task description, the expected output schema (even if rough), any known constraints (e.g., date formats, allowed enum values), and the risk level of the workflow. Do not use this prompt for open-ended creative generation, for agents that return unstructured natural language, or when the contract is so simple that a one-line JSON schema would suffice. It is overkill for trivial data shapes and underkill for workflows that require legal or clinical review—those should always include a human-in-the-loop step.

The prompt produces a complete contract definition: required fields with types and descriptions, optional fields with defaults, enum constraints, validation rules, and explicit error handling expectations for the sub-agent. It also generates schema validation tests and contract compliance checks that you can wire directly into your agent harness. Before using the output, verify that the contract does not over-constrain the sub-agent to the point of brittleness—every required field should have a clear downstream consumer. If a field exists only for hypothetical future use, mark it optional. The next step is to feed this contract into your sub-agent's system prompt and pair it with the Sub-Task Output Validation Contract Prompt Template to build an automated acceptance gate.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if a strict Input/Output Contract Definition is the right tool before wiring it into your multi-agent orchestration.

01

Good Fit: Strict Sub-Agent Pipelines

Use when: you are building a deterministic multi-agent system where one agent's output is another agent's structured input. Guardrail: define the contract before writing the agent prompt. The contract is the interface; the prompt is the implementation.

02

Bad Fit: Open-Ended Exploration

Avoid when: the sub-agent's task is creative, exploratory, or the output shape is unknown at design time. Guardrail: use a looser schema with optional fields and a notes catch-all. Strict contracts on ambiguous tasks cause brittle failures and lost insight.

03

Required Inputs

What you need: a clear task description, the downstream consumer's exact field requirements, enum lists for constrained values, and example valid payloads. Guardrail: if you cannot write a passing test case by hand, the contract is underspecified. Do not ask the model to invent the schema.

04

Operational Risk: Silent Schema Drift

What to watch: the orchestrator evolves but the contract prompt does not, causing parsing failures downstream. Guardrail: version your contract prompts alongside your agent code. Run contract compliance tests in CI that validate the sub-agent's output against the current schema on every deploy.

05

Operational Risk: Over-Constraint Paralysis

What to watch: a contract so strict that the sub-agent refuses to produce output or hallucinates values to satisfy required fields. Guardrail: distinguish between required (blocking) and preferred (best-effort) fields. Allow explicit null or "UNAVAILABLE" sentinel values with a required absence_reason field.

06

When to Use Code Instead

What to watch: using an LLM to enforce a schema that a simple JSON Schema validator in code can handle more reliably and cheaply. Guardrail: the prompt's job is to produce structured data. Validation, type coercion, and retry logic belong in the application harness, not the prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating strict input/output contracts that sub-agents must satisfy before execution.

This prompt template produces a typed contract definition that a sub-agent must fulfill. The contract specifies required fields, optional fields, enum constraints, data types, validation rules, and error handling expectations. Use this template when you need to define the exact shape of data that a sub-agent will receive and must return, ensuring that orchestrators can validate outputs programmatically before passing results to downstream agents or systems.

code
You are defining a strict input/output contract for a sub-agent that will execute a specific task. The contract must be machine-validatable and unambiguous.

## Task Description
[TASK_DESCRIPTION]

## Required Inputs
Define every input the sub-agent needs to execute this task. For each input, specify:
- Field name
- Data type (string, integer, float, boolean, array, object)
- Whether it is required or optional
- Valid values, ranges, or regex patterns
- Default value if optional and omitted
- Example value

## Required Outputs
Define every output the sub-agent must produce. For each output, specify:
- Field name
- Data type
- Whether it is required or optional
- Valid values, ranges, or regex patterns
- Null handling rules (when can this field be null?)
- Example value

## Constraints
[CONSTRAINTS]

## Validation Rules
Define rules that the orchestrator will use to validate the sub-agent's output before accepting it:
- Schema compliance checks
- Business logic rules (e.g., start_date must be before end_date)
- Cross-field validation rules
- Completeness checks (all required fields present and non-null)

## Error Handling Contract
Define how the sub-agent must signal errors:
- Error code field and valid error codes
- Error message format
- Partial result rules (can the agent return partial results with errors?)
- Retry eligibility (which errors are retryable?)

## Output Schema
Produce the contract as a JSON Schema object with the following structure:
{
  "contract_version": "1.0",
  "task_type": "string identifying the task",
  "inputs": { ... JSON Schema for inputs ... },
  "outputs": { ... JSON Schema for outputs ... },
  "validation_rules": [
    {
      "rule_id": "string",
      "description": "human-readable rule",
      "field_path": "jsonpath to field(s)",
      "condition": "expression or predicate",
      "severity": "error | warning"
    }
  ],
  "error_contract": {
    "error_field": "field name for error codes",
    "valid_error_codes": ["list of codes"],
    "partial_results_allowed": true/false,
    "retryable_errors": ["list of retryable codes"]
  }
}

## Risk Level
[RISK_LEVEL]

## Examples
[EXAMPLES]

Adapt this template by replacing the square-bracket placeholders with concrete values. For [TASK_DESCRIPTION], provide a clear statement of what the sub-agent must accomplish. For [CONSTRAINTS], list any domain-specific rules, such as regulatory requirements, data residency restrictions, or latency budgets. For [RISK_LEVEL], specify whether the task is low-risk (automated validation sufficient), medium-risk (require human spot-checking), or high-risk (require full human review before downstream consumption). For [EXAMPLES], provide one or two valid input/output pairs that demonstrate correct contract fulfillment. After generating the contract, validate it against your actual sub-agent implementations by running schema compliance tests and checking that all required fields are populated in representative outputs.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Input/Output Contract Definition Prompt. Each placeholder must be populated before the prompt is sent to a sub-agent or orchestrator. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[TASK_DESCRIPTION]

Natural language description of the sub-task the agent must perform

Extract all invoice line items from the provided document and return them as a structured list

Must be a non-empty string. Check for ambiguous verbs like 'handle' or 'process' that lack concrete output expectations

[INPUT_SCHEMA]

JSON Schema or TypeScript interface defining the exact shape of data the sub-agent will receive

{"type": "object", "properties": {"document_text": {"type": "string"}}, "required": ["document_text"]}

Must be valid JSON Schema draft-07 or later. Parse with ajv or zod before use. Reject if $ref pointers are unresolvable

[OUTPUT_SCHEMA]

JSON Schema or TypeScript interface defining the exact shape the sub-agent must return

{"type": "object", "properties": {"line_items": {"type": "array", "items": {"$ref": "#/definitions/LineItem"}}}, "required": ["line_items"]}

Must be valid JSON Schema. Every field must have a type and description. Enum fields must list all allowed values. Reject schemas with only 'object' type and no properties

[FIELD_CONSTRAINTS]

Per-field rules for format, ranges, nullability, uniqueness, and cross-field dependencies

line_items[].unit_price must be a positive number with max 2 decimal places; line_items[].quantity must be an integer >= 1; total must equal sum of unit_price * quantity

Each constraint must reference a specific field path. Constraints must be executable as code checks. Reject constraints that say 'should be reasonable' or similar vague language

[ERROR_CONTRACT]

Specification for how the sub-agent must signal partial failures, missing data, or low-confidence results

If a line item has a missing unit_price, set confidence to 0.0 and include in errors array with code 'MISSING_PRICE'. Never hallucinate prices.

Must define at least 3 error codes with conditions. Each code must have a unique string identifier. Reject error contracts that only say 'return an error if something goes wrong'

[CONFIDENCE_THRESHOLD]

Minimum confidence score (0.0 to 1.0) the sub-agent must meet per output field or for the entire response

0.85 for line_items array; 0.95 for total field; if below threshold, include in low_confidence_fields array with reason

Must be a float between 0.0 and 1.0. If per-field thresholds exist, every required output field must have a threshold. Reject if threshold is 0.0 without explicit justification

[CONTEXT_WINDOW_LIMIT]

Maximum token budget the sub-agent can consume for this task, including input and output

4096 tokens total; input context must not exceed 3000 tokens; reserve 1096 tokens for output

Must be a positive integer. Check against model's actual context window. Reject if output reservation is less than 256 tokens for structured tasks

[TIMEOUT_SECONDS]

Maximum wall-clock time the sub-agent has to complete the task before the orchestrator considers it failed

30

Must be a positive integer. Set lower than the orchestrator's own timeout. Reject if timeout exceeds 300 without explicit justification for long-running tasks

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the contract definition prompt into an agent orchestration pipeline with validation, retries, and structured output enforcement.

The contract definition prompt is not a standalone utility; it is a pre-execution gate inside an agent orchestration layer. Before any sub-agent receives a task, the orchestrator calls this prompt to produce a typed contract—a machine-readable schema that defines required fields, optional fields, enum constraints, data types, and validation rules. The output of this prompt becomes the input to two downstream systems: the sub-agent that must satisfy the contract, and the validation harness that will reject non-conforming outputs. Wire this prompt into your orchestration framework as a synchronous step after task decomposition and before sub-agent dispatch. If the contract generation fails or produces an invalid schema, do not proceed to execution—re-prompt with more context or escalate to a human operator.

Model choice and structured output enforcement. Use a model that supports strict structured output modes (e.g., GPT-4o with response_format set to json_schema, or Claude 3.5 Sonnet with tool-use mode for schema generation). Pass the contract definition prompt with a pre-registered JSON Schema that describes the contract object itself: task_id, agent_role, input_schema, output_schema, validation_rules, error_handling, and example_valid_output. This ensures the model returns a parseable contract, not free text. On the application side, validate the returned contract against this meta-schema immediately. If validation fails, retry once with the validation error injected into the prompt as additional [CONSTRAINTS]. After two failures, log the full prompt and response, then route to a human reviewer or a fallback default contract template.

Validation, logging, and contract compliance checks. Once a sub-agent completes its task, the orchestrator must validate its output against the contract's output_schema and validation_rules fields. Implement this as a two-stage check: first, structural validation (does the JSON match the schema? are required fields present? do enum values match allowed sets?); second, semantic validation using the contract's custom rules (e.g., 'confidence must be between 0 and 1', 'citations must reference document IDs present in the input context'). Log every contract generation, every sub-agent output, and every validation result with the task_id as the correlation key. This traceability is essential for debugging multi-agent failures—when a downstream agent produces garbage, you need to know whether the contract was ambiguous, the sub-agent violated it, or the validation rules were too strict. For high-risk domains (legal, healthcare, finance), add a human approval step before any contract is used to gate a sub-agent that will take a destructive or irreversible action.

Retry and escalation wiring. When a sub-agent output fails contract validation, do not silently discard it. Implement a retry loop: send the sub-agent its original task, the contract, and the specific validation errors with a repair prompt. Limit retries to 2–3 attempts. If the sub-agent still cannot satisfy the contract, the orchestrator should invoke the Dynamic Re-Decomposition Prompt for Failed Sub-Tasks to re-plan the work, or escalate to a human with the full trace: original task, generated contract, sub-agent outputs, and validation failure details. Avoid the trap of loosening validation rules to reduce failures—that masks contract ambiguity and produces unreliable downstream behavior. Instead, treat persistent validation failures as a signal that the contract itself may need revision, and feed that signal back into your prompt improvement cycle.

IMPLEMENTATION TABLE

Expected Output Contract

Validation rules and field definitions for the contract produced by the Input/Output Contract Definition Prompt. Use this table to build automated acceptance checks before a sub-agent output is accepted by the orchestrator.

Field or ElementType or FormatRequiredValidation Rule

[CONTRACT_ID]

string (UUID v4)

Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

[REQUIRED_FIELDS]

array of objects

Each object must contain name, type, and description keys; array must not be empty

[OPTIONAL_FIELDS]

array of objects

If present, each object must contain name, type, and description keys; null allowed

[ENUM_CONSTRAINTS]

object

If present, keys must match field names in REQUIRED_FIELDS or OPTIONAL_FIELDS; each value must be a non-empty array of strings

[OUTPUT_SCHEMA]

string (JSON Schema draft-07)

Must parse as valid JSON; must pass ajv.compile() without errors; must include $schema, type, and properties keys

[ERROR_HANDLING]

object

Must contain on_validation_failure and on_missing_required keys; each value must be one of retry, skip, escalate, or use_default

[CONFIDENCE_THRESHOLD]

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive; sub-agent output with confidence below this value triggers escalation

[EXAMPLE_VALID_OUTPUT]

object

Must validate against [OUTPUT_SCHEMA] using ajv; must include all [REQUIRED_FIELDS]; must not include fields outside schema

PRACTICAL GUARDRAILS

Common Failure Modes

When sub-agents operate on loosely defined contracts, the orchestrator inherits the mess. These are the most common failures in input/output contract definitions and how to prevent them before execution.

01

Schema Drift Between Agents

What to watch: Agent A produces user_id as a string, but Agent B expects it as an integer. The orchestrator passes the payload without validation, causing silent failures or hallucinated fallbacks downstream. Guardrail: Define a single source-of-truth schema per contract and validate every sub-agent output against it before the orchestrator forwards the payload. Reject non-conforming outputs with a structured error the agent can repair.

02

Missing Required Fields in Partial Results

What to watch: A sub-agent completes its task but omits a required field because the instruction didn't mark it as mandatory. The orchestrator accepts the incomplete output and propagates nulls that break downstream logic. Guardrail: Explicitly enumerate required vs. optional fields in the contract prompt. Use a post-execution validator that checks for nulls in required fields and triggers a repair loop before the handoff.

03

Enum Value Sprawl

What to watch: A sub-agent returns status: "in_progress" when the contract specifies IN_PROGRESS. Downstream agents fail to match the string, default to unknown states, or hallucinate behavior. Guardrail: Define closed enums with exact allowed values in the contract. Validate enum membership at the output gate and reject non-matching values with the list of valid options included in the error message.

04

Overloaded Output with Irrelevant Context

What to watch: A sub-agent returns its full reasoning trace, intermediate calculations, and debug logs alongside the requested output. The orchestrator's context window fills with noise, starving downstream agents of token budget. Guardrail: Separate the contract into a required output object and an optional debug or reasoning field. Instruct the orchestrator to strip optional fields before forwarding to the next agent.

05

Ambiguous Null Semantics

What to watch: A sub-agent returns null for a field, but it's unclear whether the value is unknown, not applicable, or the agent failed to extract it. Downstream agents treat all nulls the same way, producing incorrect results. Guardrail: Require explicit null-reason markers such as "value": null, "null_reason": "NOT_FOUND" in the contract. Validate that every null field includes a reason code before the orchestrator accepts the output.

06

Contract Bypass via Free-Text Fallback

What to watch: A sub-agent fails to produce structured output and instead returns a natural-language summary like "I couldn't find the data, but here's what I think." The orchestrator parses this as valid JSON and injects hallucinated content into the pipeline. Guardrail: Require strict JSON-only output with a schema validation gate. If parsing fails, reject the entire response and trigger a retry with the original contract and the parse error. Never accept unstructured fallback from a contracted sub-agent.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing whether a generated sub-agent contract is production-ready before it is deployed into a multi-agent pipeline.

CriterionPass StandardFailure SignalTest Method

Schema Completeness

All required fields defined with type, format, and nullability constraints. Optional fields explicitly marked.

Missing field definitions, ambiguous types, or undocumented null handling.

Parse the contract as JSON Schema. Assert all [REQUIRED_FIELDS] are present and all fields have a type property.

Enum Constraint Validity

All enum fields list complete, non-overlapping values. No placeholder values like 'other' without explicit definition.

Enum contains 'etc.', 'misc', or undefined catch-all values. Overlapping string values.

Extract all enum arrays. Assert uniqueness. Check for forbidden catch-all tokens using a blocklist.

Error Handling Specification

Contract defines required behavior for parse failures, missing fields, and out-of-schema values. Specifies retry or escalate path.

No error handling section. Vague instruction like 'handle errors gracefully'.

Search contract text for error handling keywords. Assert presence of a structured error object or escalation rule.

Input/Output Boundary Clarity

Contract clearly separates inputs consumed by the sub-agent from outputs produced. No circular dependencies.

Output schema references input fields as outputs. Input requires data the orchestrator cannot provide.

Trace data flow from orchestrator to sub-agent. Assert no field appears in both input and output sections without explicit transformation.

Confidence Score Requirement

Contract mandates a structured confidence score for each output field or the entire payload, with a defined scale.

No confidence field in output schema. Confidence is a free-text string.

Validate output schema contains a numeric confidence field with min/max constraints. Assert type is number, not string.

Validation Gate Definition

Contract defines specific pass/fail checks the orchestrator must run before accepting the output. Includes threshold values.

Validation rules are missing or purely descriptive ('output should be good').

Extract validation rules section. Assert at least one rule contains a measurable condition (regex, range, enum check).

Context Budget Constraint

Contract estimates maximum token or character length for the output payload. Specifies truncation behavior if exceeded.

No size limit defined. Output can grow unbounded and overflow downstream context windows.

Assert presence of max_length or max_tokens property in output constraints. Check for truncation or overflow handling instruction.

Idempotency Key Handling

Contract specifies whether repeated calls with the same input produce the same output. Defines idempotency key if required.

No mention of idempotency for a task that may be retried. Duplicate side effects possible.

Search contract for 'idempotent' or 'idempotency'. If task is retryable, assert a key field or deduplication strategy is defined.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base contract template but replace strict JSON schema validation with natural-language field descriptions. Use a single example contract instead of a full test suite. Focus on getting the shape right before hardening.

code
Define the input/output contract for [SUB_AGENT_NAME].
Required inputs: [LIST_FIELDS]
Expected outputs: [LIST_FIELDS]
Constraints: [NATURAL_LANGUAGE_RULES]

Watch for

  • Missing optional fields that downstream agents depend on
  • Ambiguous field descriptions that produce inconsistent output shapes
  • No error handling instructions, so sub-agents return unstructured failure messages
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.