AdvancedLesson 21 of 306 min read

Reliable Workflows and Prompt Chains

Replace one long prompt with a short chain of steps, put a check between the links, and use templates with blanks, with a real program that stops at the first bad step.

In this lesson you will

  • Break a big task into a short chain of steps
  • Decide what each step hands on
  • Check every hand-over and stop at the first failure
  • Use templates with blanks safely

About 24 minutes

Tom’s newsletter keeps losing things

Tom writes a monthly newsletter for the market stall holders. Every month he pastes the committee notes into Claude with one long prompt: pull out the facts, decide which section each fact belongs in, write the email, keep it friendly, keep it short, and do not forget the stall fees. Some months the result is perfect. Other months the stall fees vanish, or the tone slips, and he cannot tell which part of the long prompt went wrong. This lesson is about replacing one long prompt with a short chain, and putting a small check between the links, so that when something goes wrong you can see exactly where.

Why chains work

Anthropic’s prompt guidance describes prompt chaining as breaking a complex task into smaller subtasks, where the output of one prompt becomes the input of the next. Its stated benefits are accuracy, because each subtask gets full attention, clarity, because each instruction is simpler, and traceability, because you can pinpoint the step that failed. It also notes that subtasks which do not depend on each other, such as analysing several separate documents, can be run in parallel for speed. Nothing here is magic. A short, single-purpose instruction is easier to follow and easier to check than a paragraph with eight demands.

Designing a chain

  1. Write the job as one sentence per step. Tom’s chain is: extract the facts, label the section, write the email.
  2. Decide what each step hands on. A list of facts, then a single label, then the final text. Ask for a fixed format, such as JSON, so the next step can read it.
  3. Write a check for each hand-over. Is the list non-empty? Is the label one of the allowed words? Is the email long enough and does it include the key facts?
  4. Stop at the first failure. Do not feed a bad answer into the next step, because errors compound: a wrong label in step 2 produces a confident but wrong email in step 3.
  5. Keep the chain short. Add a step only when it removes a real problem.

Templates keep the steps steady

A template is a prompt with blanks, filled in for each run. It stops you rewriting the instruction from memory, which is how details get lost. The danger is a blank that is never filled, so the program below refuses to build a prompt if any blank is empty. Here is the kind of template Tom uses for step 3, with the blanks shown in curly brackets.

Write a friendly email of about {words} words to {audience} about {topic}. Use only these facts: {facts}. If a fact is missing, write "not stated" rather than guessing.

A chain you can run

The program below builds a prompt from a template, and then checks three saved example replies, one for each step, in three different runs. These replies are written by hand as examples, not produced by Claude, because the point here is the checking, not the wording. The checker reads each reply as JSON, tests it, and stops at the first step that fails.

import json, re

TEMPLATE = "Summarise {topic} for {audience} in {words} words. Use only: {source}"

def fill(template, values):
    needed = re.findall(r"\{(\w+)\}", template)
    missing = [k for k in needed if not str(values.get(k, "")).strip()]
    if missing:
        raise ValueError("missing " + ", ".join(missing))
    return template.format(**values)

# Saved EXAMPLE replies for a three-step chain (not real Claude replies)
RUNS = {
    "good": ['{"facts": ["Fair on 17 June", "Budget 400 pounds"]}',
             '{"label": "logistics"}',
             '{"email": "Hi team, the fair is on 17 June and the budget is 400 pounds. Thanks, Meera"}'],
    "typo": ['{"facts": ["Fair on 17 June"]}',
             '{"label": "logistcs"}',
             '{"email": "Hi team"}'],
    "thin": ['{"facts": ["Fair on 17 June"]}',
             '{"label": "money"}',
             '{"email": "Hi team"}'],
}
ALLOWED = {"logistics", "money", "people"}

def check1(d):
    f = d.get("facts")
    return isinstance(f, list) and len(f) > 0 and all(str(x).strip() for x in f), "facts missing"
def check2(d):
    return d.get("label") in ALLOWED, "label not allowed"
def check3(d):
    return len(d.get("email", "").split()) >= 10, "email too short"
CHECKS = [check1, check2, check3]

def run_chain(replies):
    for i, (raw, check) in enumerate(zip(replies, CHECKS), 1):
        try:
            d = json.loads(raw)
        except json.JSONDecodeError:
            return f"stopped at step {i}: not JSON"
        good, msg = check(d)
        if not good:
            return f"stopped at step {i}: {msg}"
    return "all 3 steps passed"

try:
    fill(TEMPLATE, {"topic": "the fair", "audience": "volunteers", "words": 50})
except ValueError as e:
    print("template:", e)
values = {"topic": "the fair", "audience": "volunteers", "words": 50, "source": "notes"}
print("filled prompt words:", len(fill(TEMPLATE, values).split()))
for name, replies in RUNS.items():
    print(name + ":", run_chain(replies))
template: missing source
filled prompt words: 11
good: all 3 steps passed
typo: stopped at step 2: label not allowed
thin: stopped at step 3: email too short

The first line shows that the template refused to build, because the blank for the source was empty. Once the blank is filled, the prompt has 11 words. The run called good passes all three steps. The run called typo stops at step 2, because the label was misspelled and so is not in the allowed list. The run called thin gets through steps 1 and 2 and stops at step 3, because the email is only two words long. In each case you know exactly which link to repair, and you never waste time reading an email built on a bad label. That is traceability in practice.

Common mistake: trusting every link

Chaining without checking. If you just paste each reply into the next prompt, a mistake in the first link travels all the way to the end and looks more confident each time. The check between links is what makes a chain more reliable than one long prompt.

You can chain by hand

Some chat apps let you do this by hand in one conversation: do step 1, read it, correct it, then ask for step 2. That is a chain too, with you as the checker, and it is a good way to design one before you automate anything.

Take a task you do every month. Write it as three one-sentence steps. Decide what the first step must hand over, and write one rule that would catch a bad hand-over. Run it by hand next time.

Practice for this lesson

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does prompt chaining mean?

  1. Writing one very long prompt
  2. Splitting a task into steps, each output feeding the next
  3. Asking the same thing twice
  4. Using several chats at once

Chaining breaks a task into subtasks where one output becomes the next input.

Why check between steps?

  1. Checks make Claude faster
  2. Chains need no checks
  3. It shortens the prompts
  4. A mistake early on would travel to the end

Errors compound along a chain, so catch them at the first failing link.

When can subtasks be run in parallel?

  1. When they do not depend on each other
  2. When they depend on each other
  3. Never
  4. Only for short tasks

Independent subtasks, such as separate documents, can run side by side.

In the run called typo, which step stopped the chain?

  1. Step 1, the facts
  2. Step 3, the email
  3. Step 2, the label check
  4. No step stopped it

The label was misspelled, so the allowed-list check failed at step 2.

What is a template for?

  1. A way to hide the prompt
  2. A chat setting
  3. A kind of file
  4. A prompt with blanks so details are not forgotten

Templates keep the instruction steady and make missing inputs easy to catch.

Summary

  • A chain splits a task into steps, each output feeding the next.
  • Ask for a fixed format so the next step can read it.
  • Check every hand-over and stop at the first failure.
  • Templates keep instructions steady, but empty blanks must be caught.

Next lesson

Lesson 22 covers long documents and summarising at scale.

Questions

How many steps should a chain have?

As few as solve the problem. Add a step only when it removes a real error. Short chains are easier to check and cheaper to run.

Do I need to write code to chain prompts?

No. You can chain by hand in a chat: do one step, check it, then ask for the next. Code only matters when you want to repeat the chain many times.

Are the replies in the program real Claude replies?

No. They are saved examples written by hand, so the lesson can show the checking clearly. Your own replies will differ.

Progress is saved in this browser.