π§ AI with Python β π Prompt Chaining
Posted on: October 6, 2026
Description:
A single prompt works well for many tasks, but real-world AI applications often need to perform several operations before producing a useful result. A document may need to be summarised, analysed, classified, and then used to generate another response.
Trying to handle everything inside one large prompt can quickly become difficult to control.
This is where Prompt Chaining becomes useful. Instead of asking the model to complete an entire workflow at once, we divide the task into smaller prompts and connect them together. The output from one prompt becomes the input for the next.
What is Prompt Chaining?
Prompt Chaining is a Prompt Engineering technique where multiple prompts are executed in sequence.
Think of it like an assembly line. Each station performs one specific job before passing its result to the next station.
For example, an AI workflow could look like:
Article β Summary β Main Topic β Question β Answer
The first prompt summarizes an article. The generated summary is then passed to another prompt that identifies the main topic. Another prompt creates a question, and the final prompt generates an answer.
Instead of one model call trying to accomplish everything, each stage has a clear responsibility.
Passing Outputs Between Prompts
The key idea behind Prompt Chaining is that intermediate outputs become new inputs.
For example, the first stage might summarize some content:
summary_prompt = f"""
Summarize the following text in two sentences.
Text:
{article}
"""
After generating the summary, we can use it inside another prompt:
topic_prompt = f"""
Identify the main topic from the following summary.
Return only the topic.
Summary:
{summary}
"""
The second prompt doesn't need to process the entire original document again. It works with the result produced by the previous stage.
This allows complex tasks to be constructed from smaller and more manageable operations.
Why Not Use One Large Prompt?
Technically, we could ask an LLM to summarize a document, identify its topic, generate questions, and answer them all within one prompt.
For simple workflows, that may be perfectly reasonable.
But as tasks become more complex, Prompt Chaining provides greater control. Each stage can be inspected independently, and if something goes wrong, we can identify exactly which part of the workflow caused the problem.
Individual prompts can also be improved without redesigning the entire workflow.
This makes prompt chains easier to debug, test, maintain, and extend.
Building Reusable Prompt Chains
In Python, repeated model calls can be wrapped inside a helper function:
def generate_response(prompt, max_tokens=100):
response = generator(
prompt,
max_new_tokens=max_tokens,
do_sample=False
)
return response[0]["generated_text"]
Each stage can then call the same function with a different prompt.
This keeps the Python code clean while allowing new stages to be added whenever the workflow becomes more sophisticated.
Where Prompt Chaining Is Used
Prompt Chaining becomes especially useful when an AI application needs to perform several related tasks.
For example, a document-processing system might:
Extract information β Classify it β Summarize it β Generate a report
A research assistant might:
Search information β Summarize findings β Compare sources β Generate an answer
Similar workflows appear in RAG systems, AI agents, customer support automation, content pipelines, code generation, and enterprise AI applications.
In these systems, Prompt Chaining helps transform individual LLM calls into complete AI workflows.
When Should You Use Prompt Chaining?
Not every AI task needs a chain.
If a problem can be handled reliably with one clear prompt, adding several model calls may only increase latency, computational cost, and complexity.
Prompt Chaining becomes valuable when a task naturally contains multiple distinct stages, when intermediate results need to be reused, or when developers need greater visibility and control over how the final result is produced.
The goal isn't to create as many prompts as possibleβit's to divide a complex problem only where doing so makes the workflow clearer and more reliable.
Final Thoughts
Prompt Chaining takes Prompt Engineering beyond individual prompts and introduces the idea of building multi-step AI workflows. By dividing a complex task into smaller stages and passing outputs between them, developers gain greater control over how information moves through an LLM application.
In this article, we explored how Prompt Chaining works, why intermediate outputs are useful, when chaining is preferable to a single prompt, and how the technique is used in real-world AI systems. It forms an important foundation for more advanced architectures such as RAG pipelines, AI agents, and automated LLM workflows.
Code Snippet:
from transformers import pipeline
# =========================================================
# Load Instruction-Following Model
# =========================================================
print("=" * 70)
print("Loading Instruction-Following Language Model...")
print("=" * 70)
generator = pipeline(
"text-generation",
model="google/gemma-2b-it"
)
# =========================================================
# Create Input Content
# =========================================================
article = """
Artificial Intelligence is transforming industries by allowing computers to perform tasks that traditionally required human intelligence. Modern AI
systems can analyze data, recognize patterns, generate content, and assist people with increasingly complex tasks.
"""
print("\n" + "=" * 70)
print("Original Article")
print("=" * 70)
print(article.strip())
# =========================================================
# Step 1 - Summarize Content
# =========================================================
summary_prompt = f"""
Summarize the following text in two sentences.
Text:
{article}
"""
summary_response = generator(
summary_prompt,
max_new_tokens=100,
do_sample=False
)
summary = summary_response[0]["generated_text"]
print("\n" + "=" * 70)
print("Step 1 - Generated Summary")
print("=" * 70)
print(summary)
# =========================================================
# Step 2 - Extract Main Topic
# =========================================================
topic_prompt = f"""
Identify the main topic from the following summary.
Return only the topic.
Summary:
{summary}
"""
topic_response = generator(
topic_prompt,
max_new_tokens=40,
do_sample=False
)
topic = topic_response[0]["generated_text"]
print("\n" + "=" * 70)
print("Step 2 - Main Topic")
print("=" * 70)
print(topic)
# =========================================================
# Step 3 - Generate Educational Question
# =========================================================
question_prompt = f"""
Create one educational question based on the following summary.
Summary:
{summary}
"""
question_response = generator(
question_prompt,
max_new_tokens=60,
do_sample=False
)
question = question_response[0]["generated_text"]
print("\n" + "=" * 70)
print("Step 3 - Generated Question")
print("=" * 70)
print(question)
# =========================================================
# Step 4 - Generate Final Answer
# =========================================================
answer_prompt = f"""
Answer the following question using only the provided summary.
Summary:
{summary}
Question:
{question}
"""
answer_response = generator(
answer_prompt,
max_new_tokens=120,
do_sample=False
)
answer = answer_response[0]["generated_text"]
print("\n" + "=" * 70)
print("Step 4 - Generated Answer")
print("=" * 70)
print(answer)
# =========================================================
# Reusable Model Function
# =========================================================
def generate_response(prompt, max_tokens=100):
response = generator(
prompt,
max_new_tokens=max_tokens,
do_sample=False
)
return response[0]["generated_text"]
# =========================================================
# Create Reusable Prompt Chain
# =========================================================
def run_prompt_chain(text):
summary_prompt = f"""
Summarize the following text in two sentences.
Text:
{text}
"""
summary = generate_response(summary_prompt, 100)
topic_prompt = f"""
Identify the main topic from the following summary.
Return only the topic.
Summary:
{summary}
"""
topic = generate_response(topic_prompt, 40)
question_prompt = f"""
Create one educational question based on the following summary.
Summary:
{summary}
"""
question = generate_response(question_prompt, 60)
answer_prompt = f"""
Answer the following question using only the provided summary.
Summary:
{summary}
Question:
{question}
"""
answer = generate_response(answer_prompt, 120)
return {
"summary": summary,
"topic": topic,
"question": question,
"answer": answer
}
# =========================================================
# Run Reusable Prompt Chain
# =========================================================
new_article = """
Machine Learning allows computer systems to learn patterns from data without being explicitly programmed for every possible situation. It powers applications such as recommendation systems, fraud detection, image recognition, and predictive analytics.
"""
print("\n" + "=" * 70)
print("Running Reusable Prompt Chain")
print("=" * 70)
chain_result = run_prompt_chain(new_article)
print("\nSummary:")
print(chain_result["summary"])
print("\nMain Topic:")
print(chain_result["topic"])
print("\nGenerated Question:")
print(chain_result["question"])
print("\nGenerated Answer:")
print(chain_result["answer"])
# =========================================================
# Content Transformation Chain
# =========================================================
content = """
Large Language Models are AI systems trained on large amounts of text. They can understand instructions, generate text, summarize documents, answer questions, and assist with many language-related tasks.
"""
print("\n" + "=" * 70)
print("Content Transformation Chain")
print("=" * 70)
simplify_prompt = f"""
Rewrite the following text in simple language for a beginner.
Text:
{content}
"""
simplified_content = generate_response(simplify_prompt, 100)
headline_prompt = f"""
Create one short educational headline for the following content.
Content:
{simplified_content}
Return only the headline.
"""
headline = generate_response(headline_prompt, 40)
social_prompt = f"""
Create a short educational social media description based on the following content.
Headline:
{headline}
Content:
{simplified_content}
"""
social_description = generate_response(social_prompt, 100)
print("\nSimplified Content:")
print(simplified_content)
print("\nGenerated Headline:")
print(headline)
print("\nSocial Media Description:")
print(social_description)
# =========================================================
# Information Processing Chain
# =========================================================
customer_message = """
I ordered a laptop five days ago and the tracking page still shows that the package has not been dispatched. I need the laptop for work and would like to know when it will arrive.
"""
print("\n" + "=" * 70)
print("Customer Support Prompt Chain")
print("=" * 70)
category_prompt = f"""
Classify the following customer message into one category.
Categories:
Shipping, Payment, Product, Refund, Other
Return only the category.
Message:
{customer_message}
"""
category = generate_response(category_prompt, 30)
summary_prompt = f"""
Summarize the customer's issue in one sentence.
Message:
{customer_message}
"""
issue_summary = generate_response(summary_prompt, 60)
response_prompt = f"""
You are a professional customer support assistant.
Write a concise response using the information below.
Category:
{category}
Customer Issue:
{issue_summary}
"""
support_response = generate_response(response_prompt, 120)
print("\nCategory:")
print(category)
print("\nIssue Summary:")
print(issue_summary)
print("\nSupport Response:")
print(support_response)
# =========================================================
# Display Prompt Chain Workflow
# =========================================================
print("\n" + "=" * 70)
print("Prompt Chaining Workflow")
print("=" * 70)
print("Initial Input")
print(" β")
print("Prompt 1")
print(" β")
print("Intermediate Output")
print(" β")
print("Prompt 2")
print(" β")
print("Intermediate Output")
print(" β")
print("Prompt 3")
print(" β")
print("Final Output")
# =========================================================
# Program Completed
# =========================================================
print("\n" + "=" * 70)
print("Prompt Chaining Demo Completed Successfully!")
print("=" * 70)
No comments yet. Be the first to comment!