Article
promptingchainingpipelineorchestrationworkflowpythonopenai-apillm-workflow
Build Multi-Step AI Workflows with Prompt Chaining
Break a complex task into a sequence of smaller prompts. The output of one prompt becomes the input for the next, creating a powerful, modular AI pipeline for sophisticated analysis and generation.
beginner15 min4 steps
The play
- Deconstruct Your TaskStart by breaking your complex goal into a series of smaller, single-purpose steps. For example, to analyze customer feedback, you might first extract topics, then determine sentiment for each topic, and finally summarize the results into an action plan. This is the foundation of Prompt Chaining.
- Craft the First PromptWrite the first prompt in your sequence. It should take the initial raw data (e.g., a customer review) and produce a structured, predictable output. The goal is to create a clean input for the next step. For example, ask the LLM to extract key topics as a comma-separated list.
- Chain the Next PromptCreate the second prompt. This prompt's key feature is a placeholder where the output from the first prompt will be injected. This is the 'chain' in Prompt Chaining. This prompt will perform the next logical step, like analyzing the sentiment of the topics you just extracted.
- Synthesize the Final OutputAdd a final prompt to the chain that synthesizes the information gathered in the previous steps into a useful, final output. This prompt takes the structured data from step 2 (e.g., topic-sentiment pairs) and transforms it into a human-readable summary or a specific format like JSON.
Starter code
import os
from openai import OpenAI
# Make sure to set your OPENAI_API_KEY environment variable
# export OPENAI_API_KEY='your-api-key'
client = OpenAI()
def get_completion(prompt, model="gpt-4o-mini"):
try:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant that provides concise and structured output."},
{"role": "user", "content": prompt}
],
temperature=0
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error: {e}"
# --- Start of Prompt Chaining Workflow ---
# 1. Initial Input
customer_review = "The battery life on this new phone is a huge letdown; it dies before 3 PM with normal use. On the bright side, the OLED screen is incredibly vibrant and the camera system is best-in-class, especially in low light."
print(f"--- Original Review ---\n{customer_review}\n")
# 2. Step 1: Extract Topics
prompt_1 = f"""Extract the main product features discussed in the following customer review. List them as a comma-separated list.
Review: "{customer_review}"
Topics:"""
extracted_topics = get_completion(prompt_1)
print(f"--- Step 1 Output (Extracted Topics) ---\n{extracted_topics}\n")
# 3. Step 2: Analyze Sentiment for Each Topic
prompt_2 = f"""For each topic below, analyze the sentiment (Positive, Negative, Neutral) based on the original review provided. Output as 'Topic: Sentiment'.
Original Review: "{customer_review}"
Topics: {extracted_topics}
Sentiment Analysis:"""
sentiment_analysis = get_completion(prompt_2)
print(f"--- Step 2 Output (Sentiment Analysis) ---\n{sentiment_analysis}\n")
# 4. Step 3: Generate Summary for Product Manager
prompt_3 = f"""Based on the following analysis, write a 3-sentence summary for a product team. The first sentence should state the main negative point. The second should state the main positive points. The third should suggest a priority.
Analysis:
{sentiment_analysis}
Summary:"""
final_summary = get_completion(prompt_3)
print(f"--- Final Output (PM Summary) ---\n{final_summary}")