Break the task into stages: Look for natural handoffs, such as extract, analyze, draft, and review.
Give each stage one job: A stage that does two things is usually two stages.
Define the input and output of each stage: Decide exactly what each step receives and what shape its answer should take.
Pass results forward: The output of one step is placed into the next prompt, ideally in a structured form.
Add checks: Use LLM guardrails to validate outputs between steps and stop or retry when something looks wrong.
Return the final result: The last step assembles the pieces into the finished output.
A support-ticket chain, for example, looks like this:
Customer email
-> Step 1: Extract key facts (name, order, issue)
-> Step 2: Classify category and urgency
-> Step 3: Draft a reply from the facts
-> Step 4: Check the draft against policy
-> Approved reply (or flag for a human)
Put simply, what is prompt chaining at run time? It's a loop of build a prompt, call the model, read the answer, and decide what to do next. The only things that change from chain to chain are the prompts and the rules for connecting them.
Passing Data Between Steps
The weak point of most chains is the handoff. If step 1 returns a chatty paragraph, step 2 has to guess what matters. It's far more reliable to ask early steps for structured output, such as JSON with named fields, and to feed later steps only the fields they need. That keeps each prompt short, reduces the chance of confusion, and makes outputs easy to validate with ordinary code.
Validate external inputs and intermediate outputs to reduce the risk of prompt injection affecting later stages of the chain.
Different Types of Prompt Chaining
Knowing the types is the second half of answering what is prompt chaining. Prompt chains differ in how the steps connect.
The table below covers the common patterns, with an example and the kind of problem each one suits.
Type | Working Principle | Example | Suitable Use Case |
Linear (sequential) | Steps run one after another, each using the previous output | Summarize a report, then extract action items, then write an email | Tasks with a clear order of stages, such as content drafting or report building |
Conditional (branching) | A routing step picks the next prompt based on an earlier result | A classifier labels a ticket as billing or technical and sends it to a matching prompt | Inputs of different kinds that need different handling |
Iterative (loop) | A draft is checked and revised repeatedly until it passes or hits a limit | Generate code, run a review prompt, fix the issues, and repeat | Quality-sensitive outputs such as code, legal text, or policy answers |
Gated (validated) | A check sits between steps and blocks bad output from moving forward | Verify that extracted JSON has all required fields before drafting | Production workflows where mistakes are costly |
Parallel (fan-out and merge) | Independent prompts run at the same time, then a final step combines them | Analyze sentiment, extract facts, and detect language at once, then merge | Speeding up workflows whose steps don't depend on each other |
Tool-augmented | Some steps call outside tools or data before the next prompt | Use retrieval augmented generation (RAG) to search a knowledge base and answer questions using retrieved passages. | Questions that need fresh or private data |
Human-in-the-loop | A person approves or edits at chosen points | A manager reviews a refund decision before the final message goes out | High-stakes actions and regulated settings |
When people ask what is prompt chaining beyond the simple linear case, prompt chaining is one of several agentic design patterns used alongside routing, reflection, and parallelization to structure AI workflows.
Chains vs Agents
A chain follows a path you designed in advance. An AI agent chooses its own next step at run time, deciding which tool to call and when to stop.
Chains are more predictable, cheaper, and easier to test, while agents handle open-ended tasks better. In the debate between chains and agents, what is prompt chaining best at? Predictable, repeatable work. A sensible approach is to start with a chain and move to an agent only when the path can't be known ahead of time.
Prompt Chaining With a Practical Example
To make what is prompt chaining concrete, the best prompt chaining example is one you could run today. Say a small online shop wants to answer customer emails faster, without sending anything wrong. Here is the email:
"Hi, my order A1001 arrived with a cracked screen. This is the second time. Please send a new one. - Priya"
A single prompt might say "read this email and write a perfect reply following our policies." It might work, but when it fails, you can't tell whether it misread the email, misapplied the policy, or just wrote badly. A chain splits those jobs.
Prompt 1 (extract): "From the email below, extract the customer name, order ID, the problem, and what the customer wants. Return JSON only." Output: customer Priya, order A1001, issue "item arrived damaged," wants "replacement."
Prompt 2 (classify): "Using these facts, classify the category and urgency. Return JSON only." Output: category "damaged_item," urgency "high."
Prompt 3 (sentiment, run in parallel with Prompt 2): "In one word, what is the customer's sentiment?" Output: "frustrated."
Prompt 4 (draft): "Write a short, polite reply using these facts, this triage result, and the customer's mood. Apologize, confirm the order ID, and offer the replacement." Output: a three-sentence apology that names order A1001 and promises a replacement.
Prompt 5 (check): "Does this reply mention the order ID and offer a fix? Answer PASS or FAIL." Output: PASS, so the reply is marked ready to send. A FAIL would send the draft to a human.
The Same Prompt Chaining Example in Plain Language
This prompt chaining example is easier to see without the prompts.
First, a reader pulls out the facts.
Next, a sorter decides how urgent the case is, while a second reader gauges the mood.
Then a writer drafts the reply, and a checker confirms it names the right order and offers a fix. Five small jobs replace one big one, and each can be improved on its own.
That's the practical prompt chaining meaning for a business: a process you can inspect, instead of a single request you hope will work.
Building a Prompt Chain in Python
The code below is what is prompt chaining written as code, using the chain from the example above.
It has five steps, including a parallel pair and a final check, and it runs with only the standard library.
Python Code Example
import json
from concurrent.futures import ThreadPoolExecutor
# ---- 1. The model call ----------------------------------------------------
# A stand-in so the chain runs offline. Swap this one function for a real
# model call and nothing else in the chain has to change.
def call_llm(prompt: str) -> str:
if "Extract" in prompt:
return json.dumps({"customer": "Priya", "order_id": "A1001",
"issue": "item arrived damaged", "wants": "replacement"})
if "Classify" in prompt:
return json.dumps({"category": "damaged_item", "urgency": "high"})
if "sentiment" in prompt:
return "frustrated"
if "Draft" in prompt:
return ("Hi Priya, I'm sorry order A1001 arrived damaged. "
"We're sending a replacement today at no cost.")
if "Check" in prompt:
return "PASS"
return ""
# ---- 2. The chain -----------------------------------------------------------
def run_chain(email: str) -> dict:
# Step 1: extract facts into a fixed structure
facts = json.loads(call_llm(f"Extract customer, order_id, issue, wants as JSON.\n\n{email}"))
# Steps 2 and 3 do not depend on each other, so run them in parallel
with ThreadPoolExecutor() as pool:
triage_job = pool.submit(call_llm, f"Classify category and urgency as JSON.\n\n{json.dumps(facts)}")
mood_job = pool.submit(call_llm, f"Give the customer's sentiment in one word.\n\n{email}")
triage, mood = json.loads(triage_job.result()), mood_job.result()
# Step 4: draft a reply using only what earlier steps produced
draft = call_llm(
f"Draft a short, polite reply.\nFacts: {json.dumps(facts)}\n"
f"Triage: {json.dumps(triage)}\nCustomer mood: {mood}"
)
# Step 5: a gate, so a bad draft never goes out unchecked
verdict = call_llm(f"Check this reply mentions the order id and offers a fix. Answer PASS or FAIL.\n\n{draft}")
if verdict.strip() != "PASS":
return {"status": "needs_human_review", "draft": draft}
return {"status": "ready_to_send", "facts": facts, "triage": triage, "mood": mood, "reply": draft}
email = "Hi, my order A1001 arrived with a cracked screen. This is the second time. Please send a new one. - Priya"
print(json.dumps(run_chain(email), indent=2))
Sample Output:
{
"status": "ready_to_send",
"facts": {
"customer": "Priya",
"order_id": "A1001",
"issue": "item arrived damaged",
"wants": "replacement"
},
"triage": {
"category": "damaged_item",
"urgency": "high"
},
"mood": "frustrated",
"reply": "Hi Priya, I'm sorry order A1001 arrived damaged. We're sending a replacement today at no cost."
}
Swapping in a Real Model
The call_llm function is the only place a model is involved, and the stand-in simply returns fixed text so the example can run without an account. Replace it with a real call. With the Anthropic Python SDK, for example, it looks like this:
import anthropic
client = anthropic.Anthropic() # reads the API key from the environment
MODEL = "your-model-name" # choose a current model from the provider's docs
def call_llm(prompt: str) -> str:
response = client.messages.create(
model=MODEL, max_tokens=500,
messages=[{"role": "user", "content": prompt}],
)
return response.content[0].text
Sample Output:
Hi Priya, I'm sorry your order A1001 arrived damaged.
We're sending a replacement today at no additional cost.
Other providers' SDKs follow the same pattern: send a prompt, return text. With a real model, expect to handle messier output. Ask for JSON explicitly, wrap json.loads in error handling, and retry once or twice when parsing fails. Also add timeouts, and log every prompt and response so you can trace a bad result back to the step that caused it.
Tools and Frameworks for Building Prompt Chains
Most tools are just different ways of answering what is prompt chaining in code or on a visual canvas.
You don't need a framework to chain prompts, and the plain Python above is often enough. Frameworks help once chains get long, branch, or need monitoring.
Tool | Type | Best For |
Plain Python with a provider SDK | Code | Small chains and learning |
LangChain and LangGraph | Open-source framework | Chains, branches, loops, and stateful workflows |
LlamaIndex | Open-source framework | Chains built around documents and retrieval |
Haystack | Open-source framework | Pipelines made of connected components |
DSPy | Open-source framework | Defining steps as modules and tuning prompts automatically |
n8n, Zapier, Make | No-code automation | Chaining AI steps with email, spreadsheets, and apps |
Flowise, Langflow, Dify | Visual builders | Drag-and-drop chains with model and tool nodes |
Tracing tools such as LangSmith and Langfuse | Observability | Seeing every prompt, output, cost, and failure |
How to Choose a Tool
If you're a developer who wants to understand what is prompt chaining at the code level, start with plain Python and a provider SDK, like the example above.
If your chain involves documents and search, a retrieval-focused framework saves effort.
If a non-developer will own the workflow, a no-code tool is the faster route.
In every case, favor tools that show you each step's input and output, because a chain you can't inspect is hard to fix.
Conclusion
The true benefit of prompt chaining is in simplifying the process of handling, assessing, and optimizing AI tasks. Chaining tasks into prompts provides you with more control over the results and helps to detect mistakes.
Begin with basic chaining, verify intermediate results, and add advanced techniques if necessary. The goal is to create solid workflows, not to complicate them.