0Pricing
AI Prompt Engineering · Lesson

Sequential Transformation Chains

Draft → Review → Polish chains and other multi-stage refinement.

Sequential Transformation Chains is a free AI Prompt Engineering lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Transformation Chains

A transformation chain progressively converts content from one form to another through a sequence of specialized steps. Each step transforms the output of the previous step, gradually refining or enriching the content.

The three most useful transformation chain patterns are:

  • Draft → Review → Polish: Content creation and refinement
  • Brainstorm → Filter → Expand: Idea generation and development
  • Extract → Classify → Route: Data processing and decision making

Draft → Review → Polish

The most common content creation chain. Each step has a distinct role:

  • Draft: Generate raw content quickly — speed over perfection
  • Review: Critique the draft against specific criteria — accuracy, tone, completeness
  • Polish: Apply the review findings to produce the final output

Separating these into distinct steps produces better results than asking the model to draft and polish in one shot.

Draft → Review → Polish: Python Implementation

Full implementation of the Draft → Review → Polish chain:

import anthropic

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def call(prompt):
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=800,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return r.content[0].text

def draft_review_polish(topic, audience, tone):
    # Step 1: Draft
    draft = call(f'Write a 200-word article about: {topic}. Audience: {audience}.')

    # Step 2: Review — produces critique, not final text
    review = call(f'Review this article for tone ({tone}), accuracy, and clarity.\nList specific improvements needed.\n\nArticle:\n{draft}')

    # Step 3: Polish — applies review findings
    final = call(f'Rewrite this article applying all the review feedback.\n\nOriginal:\n{draft}\n\nReview feedback:\n{review}')

    return {'draft': draft, 'review': review, 'final': final}

result = draft_review_polish('prompt engineering', 'software engineers', 'technical but approachable')
print(result['final'][:300])

Brainstorm → Filter → Expand

The idea development chain: generate broadly, then narrow intelligently, then develop deeply.

  • Brainstorm: Generate many ideas without judgment — quantity over quality
  • Filter: Apply selection criteria to identify the best ideas
  • Expand: Develop the selected ideas into detailed proposals

This chain avoids the anchoring bias of starting with a few ideas and staying locked to them.

Brainstorm → Filter → Expand: Python Implementation

Full implementation of the Brainstorm → Filter → Expand chain with JSON passing:

import json

def brainstorm_filter_expand(challenge, criteria, n_final=3):
    # Step 1: Brainstorm — generate many ideas
    raw_ideas = call(
        f'Generate 10 creative ideas for this challenge: {challenge}\n'
        'Return JSON: {"ideas": ["string"]}'
    )
    ideas = json.loads(raw_ideas)['ideas']

    # Step 2: Filter — apply criteria
    ideas_formatted = '\n'.join(f'{i+1}. {idea}' for i, idea in enumerate(ideas))
    filtered_raw = call(
        f'Select the {n_final} best ideas based on these criteria: {criteria}\n'
        f'Ideas:\n{ideas_formatted}\n'
        f'Return JSON: {{"selected": ["string"]}}'
    )
    selected = json.loads(filtered_raw)['selected']

    # Step 3: Expand — develop each selected idea
    expansions = {}
    for idea in selected:
        expansions[idea] = call(f'Write a 100-word expansion of this idea, including implementation steps: {idea}')

    return expansions

result = brainstorm_filter_expand('reduce app churn', 'feasible in 30 days, measurable impact', n_final=2)
print(list(result.keys()))

Extract → Classify → Route

The data processing chain: extract structured data, classify it, then route it to the appropriate handler.

  • Extract: Pull structured information from unstructured text
  • Classify: Assign categories, labels, or priorities
  • Route: Take different actions based on classification

This pattern powers intelligent triage systems, content moderation, and automated customer support routing.

Extract → Classify → Route: Python Implementation

Full implementation of the Extract → Classify → Route chain:

import json

def extract_classify_route(ticket_text):
    # Step 1: Extract structured data
    extracted = json.loads(call(
        f'Extract from this support ticket: {{"issue_summary": str, "product_area": str, "user_emotion": str}}\n\n{ticket_text}'
    ))

    # Step 2: Classify priority and department
    classified = json.loads(call(
        f'Classify this ticket.\nIssue: {extracted["issue_summary"]}\nEmotion: {extracted["user_emotion"]}\n'
        'Return JSON: {"priority": "urgent|high|medium|low", "department": "billing|technical|general"}'
    ))

    # Step 3: Route — generate department-specific response
    dept = classified['department']
    priority = classified['priority']

    route_prompts = {
        'billing': f'You are a billing specialist. Priority: {priority}. Respond to: {extracted["issue_summary"]}',
        'technical': f'You are a senior engineer. Priority: {priority}. Resolve: {extracted["issue_summary"]}',
        'general': f'You are customer support. Priority: {priority}. Help with: {extracted["issue_summary"]}'
    }

    response = call(route_prompts[dept])
    return {'extracted': extracted, 'classified': classified, 'response': response}

result = extract_classify_route('My payment was charged twice and I am furious!')
print(result['classified'])

Choosing the Right Chain Pattern

Matching your use case to the right transformation chain pattern:

  • Draft → Review → Polish: Any content creation — emails, articles, documentation, code
  • Brainstorm → Filter → Expand: Strategy, ideation, product planning, content calendars
  • Extract → Classify → Route: Support tickets, emails, content moderation, data processing

These patterns can also be combined — e.g., Extract → Classify → Brainstorm solutions → Filter → Draft response.

Combining Patterns

Real-world pipelines often combine multiple patterns into longer chains:

def full_content_pipeline(raw_research):
    # Pattern 1: Extract → Classify key insights
    insights = json.loads(call(
        f'Extract top 5 insights. Return JSON: {{"insights": [str]}}\n\n{raw_research}'
    ))

    # Pattern 2: Brainstorm → Filter article angles
    angles_raw = json.loads(call(
        f'Brainstorm 8 article angles based on: {insights["insights"]}\nReturn JSON: {{"angles": [str]}}'
    ))
    best_angle = json.loads(call(
        f'Select the most compelling angle for a developer audience.\nReturn JSON: {{"angle": str}}\n\nAngles: {angles_raw["angles"]}'
    ))

    # Pattern 3: Draft → Review → Polish
    draft = call(f'Write a 300-word technical article on: {best_angle["angle"]}')
    review = call(f'Review for technical accuracy and developer relevance:\n{draft}')
    final = call(f'Polish the article applying this feedback:\n\nDraft:\n{draft}\n\nFeedback:\n{review}')

    return final

print('Combined pipeline defined.')

Logging Intermediate Outputs

In transformation chains, log every intermediate output. This is essential for debugging — if the final output is wrong, you need to know which step produced bad output.

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('chain')

def logged_call(step_name, prompt, **kwargs):
    logger.info(f'[{step_name}] INPUT: {prompt[:100]}...')
    result = call(prompt)
    logger.info(f'[{step_name}] OUTPUT: {result[:100]}...')
    return result

def draft_review_polish_logged(topic):
    draft = logged_call('DRAFT', f'Write 200 words about: {topic}')
    review = logged_call('REVIEW', f'Review for clarity:\n{draft}')
    final = logged_call('POLISH', f'Rewrite applying feedback.\nDraft:\n{draft}\nFeedback:\n{review}')
    return final

print('Logging integrated into chain.')

Measuring Chain Quality

Measure the improvement delivered by each step to validate that the chain is adding value:

def measure_chain_improvement(topic):
    # Baseline: single prompt
    baseline = call(f'Write and polish a 200-word article about {topic} in one step.')

    # Chain: Draft -> Review -> Polish
    draft = call(f'Write a 200-word draft about {topic}.')
    review = call(f'List 3 specific improvements needed:\n{draft}')
    chained = call(f'Rewrite applying these improvements:\nDraft:\n{draft}\nImprovements:\n{review}')

    # Have the model compare quality
    comparison = call(
        f'Which version is higher quality? Rate each 1-10 for clarity and depth.\n'
        f'Version A (single prompt):\n{baseline}\n\nVersion B (chain):\n{chained}\n'
        'Return JSON: {"version_a_score": int, "version_b_score": int, "winner": "A|B", "reason": str}'
    )
    return comparison

print('Quality measurement pipeline defined.')

Quick Check

Which transformation chain pattern is most appropriate for processing incoming support tickets and routing them to the correct team?

Transformation Chains — Key Takeaways

Sequential transformation chains progressively refine content through specialized steps:

  • Draft → Review → Polish: Best for content creation — generates, critiques, then refines
  • Brainstorm → Filter → Expand: Best for ideation — generates broadly, selects wisely, develops deeply
  • Extract → Classify → Route: Best for data processing — extracts structure, assigns labels, routes to handlers
  • Patterns combine into longer pipelines for complex use cases
  • Log intermediate outputs at every step for effective debugging
  • Measure improvement delivered by each step to validate chain value

Frequently asked questions

Is the “Sequential Transformation Chains” lesson free?

Yes — the full text of “Sequential Transformation Chains” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.

What will I learn in “Sequential Transformation Chains”?

Draft → Review → Polish chains and other multi-stage refinement. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Prompt Engineering?

No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Sequential Transformation Chains” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Prompt Engineering lesson?

Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is Prompt Chaining?
  2. Output-to-Input Patterns
  3. Sequential Transformation Chains
  4. Error Handling in Prompt Chains
← Back to AI Prompt Engineering