Production-grade guide to agent prompt chaining covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Prompt Chaining is a technique where an AI agent orchestrates a sequence of prompt-based tasks, each building on the output of the previous, to solve complex, multi-step problems. It matters when a single prompt is insufficient—when responses must be refined, validated, or transformed through iterative processing, and when the agent must maintain state across steps without relying on external orchestration tools.
An agent begins with an initial prompt, processes the response, then uses that output as input to a new prompt—either by embedding it directly, extracting key values, or constructing a new context. The sequence continues until a final output is produced.
For example, an agent tasked with generating a product roadmap begins by extracting high-level features from a user requirement document. It then prompts a second agent to prioritize those features using a weighted scoring model. A third prompt expands the top three features into detailed user stories, and a final prompt synthesizes them into a release plan.
Each step is driven by a prompt template, a task description, and a mechanism to pass data between steps. The agent must be able to:
The most common pattern uses a JSON-based task queue, where each step is a task with:
id: unique identifiertype: e.g., feature_extraction, priority_scoring, user_story_expansioninput: initial data (e.g., raw text, JSON object, file path)state: current progress and metadataoutput: result of the prompt executionstatus: pending, in_progress, completed, failed{
"id": "task-123",
"type": "feature_extraction",
"input": {
"source": "/docs/requirements-v1.md"
},
"state": {
"attempts": 1,
"retry_delay": "PT5M"
},
"output": null,
"status": "pending"
}
The agent’s chaining logic is defined through a configuration object that maps prompt types to their execution behavior. The configuration is loaded at startup and can be updated dynamically.
prompt_chaining:
max_depth: 10
timeout: "PT15M"
retry_policy:
max_attempts: 3
backoff: "exponential"
base_delay: "PT1M"
default_prompt_template: "template.j2"
prompt_mapping:
feature_extraction:
template: "templates/extract-features.j2"
input_transform: "json"
output_parser: "json"
next_step: "priority_scoring"
condition: "if length(output.features) > 0"
priority_scoring:
template: "templates/score-features.j2"
input_transform: "merge"
output_parser: "json"
next_step: "user_story_expansion"
condition: "if output.scores.confidence > 0.7"
user_story_expansion:
template: "templates/generate-stories.j2"
input_transform: "array_of_objects"
output_parser: "list"
next_step: "synthesis"
synthesis:
template: "templates/roadmap-synthesis.j2"
input_transform: "merge"
output_parser: "json"
next_step: null
Each prompt_mapping entry defines how a prompt type behaves:
template: path to a Jinja2 template fileinput_transform: how to prepare input data before sending it to the prompt engineoutput_parser: how to parse the raw response into structured datanext_step: the prompt type to run next, or null to terminatecondition: a JSONPath expression to evaluate before advancingThe agent evaluates condition after each step. If condition evaluates to false, the step is marked failed, and the agent may trigger a fallback or retry.
Transforming input data is crucial. The agent must prepare data from the previous step’s output to match the expected format of the next prompt.
Common transformation patterns:
json: use the output as-is, pass as {"input": output}merge: combine the previous step’s output with the current task’s input objectarray_of_objects: map each item in an array to a separate prompt instanceFor example, after feature_extraction returns:
{
"features": [
{ "title": "Search Bar", "description": "Add a search bar to the homepage" },
{ "title": "Dark Mode", "description": "Enable dark mode toggle" }
]
}
The priority_scoring prompt uses input_transform: "merge" with the current task’s input. The final input becomes:
{
"source": "/docs/requirements-v1.md",
"features": [
{ "title": "Search Bar", "description": "Add a search bar to the homepage" },
{ "title": "Dark Mode", "description": "Enable dark mode toggle" }
],
"context": "Prioritize features based on user impact and implementation cost."
}
State is managed through a key-value store. Each step writes its output and metadata to a state object that persists across runs.
{
"task_id": "task-123",
"step": "priority_scoring",
"started_at": "2024-05-15T12:00:00Z",
"finished_at": "2024-05-15T12:08:30Z",
"metadata": {
"model": "gpt-4-1106-preview",
"tokens_used": 3452,
"latency_ms": 427
}
}
The most frequent failure: the template expects a field that the previous step did not produce.
For example, the user_story_expansion template expects features[].acceptance_criteria, but priority_scoring outputs features[].criteria, leading to empty acceptance criteria in the final user stories.
The agent logs:
ERROR: PromptTemplateError
Template: templates/generate-stories.j2
Expected key: features[0].acceptance_criteria
Found keys: features[0].criteria, features[0].priority
Missing: acceptance_criteria
Conditions are evaluated on the raw output, not the parsed one. A condition: "if output.scores.confidence > 0.7" may fail because scores is a flat object, not a list of scores.
The agent must validate that scores is a list, and use a parser: "json" step to normalize it before evaluation.
When a step fails and retries, the state may be overwritten by a later step. A retry_delay of PT5M means the agent waits before retrying, but if the next step starts while the first is still running, state conflicts arise.
For example:
feature_extraction starts, writes state to state.task-123priority_scoring starts, reads state.task-123, processes, writes new statestate.task-123 with original output, losing priority_scoring's updatesThe solution: use versioned_state with a version field in the state object, and update only if the version matches.
The agent assumes a standard output format, but the LLM returns JSON that deviates from the schema.
Example: expected output has features[].estimated_effort as int, but the LLM returns string like "3.5 days".
The agent logs:
WARNING: OutputParseError
Schema: {
"features": [
{ "title": "string", "estimated_effort": "integer" }
]
}
Received: {
"features": [
{ "title": "Search Bar", "estimated_effort": "3.5 days" }
]
}
Expected type: integer, got string
To mitigate, the agent applies a post_processor step that normalizes data types, formats, and keys.
Instead of a fixed sequence, the agent chooses the next step dynamically using a next_step field in the output.
{
"type": "priority_scoring",
"output": {
"scores": [
{ "title": "Search Bar", "score": 0.92, "confidence": 0.85 },
{ "title": "Dark Mode", "score": 0.78, "confidence": 0.61 }
],
"next_step": "user_story_expansion"
}
}
If confidence is below 0.7, the agent selects user_story_expansion only for high-confidence features, and runs a separate prompt for low-confidence ones.
Multiple prompts run simultaneously, then merged.
For example, after feature_extraction, the agent starts:
priority_scoring for high-impact featurescost_estimation for low-impact featuresuser_feedback_analysis for feature-specific feedbackEach produces a result, and the agent merges them into a single output using a merge_strategy defined in the config:
merge_strategy: "merge_with_conflict_resolution"
conflict_resolution:
strategy: "last_write_wins"
fields: [ "priority", "effort", "risk" ]
When a step fails, the agent can:
max_attempts{
"id": "task-123",
"status": "failed",
"error": {
"type": "PromptExecutionError",
"message": "LLM returned incomplete JSON for user_story_expansion",
"details": {
"received": "{ \"stories\": [ { \"title\": \"Search Bar\" } ] }",
"expected": "{ \"stories\": [ { \"title\": \"string\", \"description\": \"string\", \"acceptance_criteria\": [\"string\"] } ] }",
"traceback": [
"at prompt_engine.execute(123)",
"at template.render(input)",
"at llm.generate(prompt)",
"at response.parse_json()"
]
},
"fallback_prompt": "user_story_expansion_fallback",
"retries_left": 2
}
}
The agent can also trigger a notification via a webhook or message queue when a chain fails.
task_id, step, output, input, state across all stepstemplates/v1/, templates/v2/) and track which version was usedtimeout: "PT10M" in config to prevent long-running steps from blocking the chainPrompt chaining is not just a sequence of prompts—it is a structured, stateful process that evolves through feedback, conditionals, and error recovery. The agent must manage input and output formats, handle failures silently, and adapt dynamically. The pattern is robust, general, and deployable across systems. It requires no special tooling beyond standard JSON, HTTP, and key-value stores. And when it breaks, the logs and state structure reveal the full history of the chain, making debugging fast and reliable.
The key insight: a prompt is not a standalone task, but a node in a network of interdependent operations. The agent orchestrates the network, and the chain is the thread.
This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy