AlgoMaster Logo

Exercise: Prompt Templates and Pipelines

3 min readUpdated June 22, 2026
Listen to this chapter
Unlock Audio

Exercise 1: Chain Two Prompts into a Pipeline

Build a two-step pipeline where the output of the first prompt becomes the input to the second: summarize a passage, then classify the summary's tone. Each step is its own prompt, and the steps run in sequence.

Real tasks are often too much to ask of a single prompt. Splitting them into a pipeline of focused steps makes each prompt simpler, easier to test, and easier to swap out. The key idea is that the output of one step feeds the next, so you design each prompt around the shape of data it receives and produces.

Requirements

  • Step 1: summarize a passage into one sentence.
  • Step 2: take that summary and classify its tone as positive, negative, or neutral.
  • Pass the first step's output into the second step's prompt.
  • Print the summary and the final tone.
main.py
Loading...

Expected Output

The summary feeds straight into the tone classifier, and the positive passage is labeled positive.

Solution

main.py
Loading...

Each step is a self-contained function with its own prompt and a clear input and output type, which is what makes the pipeline composable. The wiring is just passing summary from the first call into the second. Structuring work this way pays off as pipelines grow: you can reorder steps, cache intermediate results, or replace one step's prompt without touching the others.

Exercise 2: Add a Guard and Retry to a Pipeline

Models do not always honor constraints on the first try. A guarded pipeline checks the output against a rule and re-runs with a firmer prompt when the check fails. Build a summarizer that enforces a word limit: summarize, verify the length, and retry with a stricter instruction if it is too long.

Requirements

  • Write summarize(text, max_words, strict=False) that asks for a summary within a word limit, with a firmer instruction when strict is set.
  • Write within_limit to check the word count.
  • Summarize once; if the result exceeds the limit, re-run with strict=True. Print the final summary and its word count.
main.py
Loading...

Expected Output

If the first summary is over the limit, the guard re-runs with a stricter prompt and the final result fits.

Solution

main.py
Loading...

The guard turns a soft request ("at most 12 words") into an enforced one by checking the output and acting on the result. Re-running with a stricter instruction is the cheapest correction; a production version might also lower max_tokens or fall back to truncation after a couple of tries. This check-and-retry shape generalizes to any constraint you can verify in code, such as valid JSON, a required field, or a banned word, and it is what makes a pipeline reliable rather than hopeful.