Part 2 of 6 · 2 min read
Prompt chaining and routing
Split a task into steps with checks between them, or send each input to a specialised prompt.
Prompt chaining
Break a task into steps. Each step's output feeds the next. Put a gate (a plain code check) between steps so a bad intermediate result stops the run early instead of poisoning everything after it.
outs = chain(llm, [("summarise", "SUMMARISE\n{input}", None),
("extract", "EXTRACT\n{input}", lambda s: "no order id" if "unknown" in s else None)], ticket)
- Use when the task splits cleanly into fixed stages and each stage is easier than the whole.
- Cost: one call per step, and the latency adds up.
- Fails by passing along an early mistake. Gates, and validating each output (Level 2, module 3), are the fix. In the tests a failed gate stops the chain after one call.
Routing
Classify the input, then send it to a specialised prompt (or to a cheaper or stronger model).
label, reply = route(llm, text, "CLASSIFY\n{input}", handlers, default="other")
- Use when inputs fall into distinct kinds that need different instructions or tools.
- Cost: always two calls (classifier plus handler), but each prompt is shorter and focused.
- Fails by misclassification. Always give a
defaultroute, and measure the classifier on its own (module 5). The router tidies the classifier's reply (case, trailing full stop, quotes) before looking it up, because models often answerBilling.when you asked forbilling.
For the curious A bug the first version had in both
Both functions filled the template with str.format. A prompt that contains a JSON example, such as Return {"label": "x"}, then crashes with a KeyError, because Python reads the braces as placeholders. Prompts with JSON examples are exactly what module 1 recommended. The pattern functions now use fill, which replaces only {name} placeholders for names you supply, in one pass, and leaves every other brace alone.
Check yourself
A chain of 4 steps has a gate after step 2 that fails. How many model calls were made? (2. The chain stops at the failed gate, so steps 3 and 4 never run.)