AI Applications
Building Reliable LLM Pipelines
When one model call becomes several in a row, the system needs state, checks, retries, and a plan for failure. A measured look at how errors compound, what checks between steps catch and miss, what retries fix, and what a crash costs.
On this page · 13 sections
The last three articles built a retrieval pipeline one stage at a time. “Chunking Strategies for RAG: What Actually Matters? (opens in a new tab)” split the documents into chunks, “Retrieval Strategies: Vector Search, Keyword Search, and Hybrid Search (opens in a new tab)” compared ways to search them, and “Reranking: Improving Retrieval Quality (opens in a new tab)” reordered what the search found. Each stage was measured on its own.
A real feature rarely stops at one stage. Take a support inbox, where a customer writes:
We’re on Pro, billed monthly, and want to move to Basic to save money. We currently have 4 members and 3 pending invitations, 2 active projects, and about 3 GB of files. What do we need to sort out before we can downgrade, and when would it take effect?
Also, if we stay on Pro instead, is there a discount for paying three years upfront?
Answering that takes several steps: find the questions in the email, look each one up, write a reply, and send it. Each step’s output is the next step’s input, and two of the steps are model calls.
This article is about what changes when one model call becomes several in a row:
- Errors compound: a step can only work with what the step before it handed over.
- Mistakes have to be caught between steps, before they become the next step’s input.
- Some failures can be retried, and some can’t.
- A crash in the middle leaves a half-finished job, and part of it may already have reached the customer.
The companion demo builds that pipeline and measures all four.
Try to Understand It This Way
Think of a restaurant kitchen. The order taker writes a ticket, the cooks work from the ticket, and the plate goes out through the pass.
If the ticket says the wrong dish, a perfect cook makes the wrong dish perfectly. A check at the pass catches a burnt plate, but not a well-cooked plate of the wrong food. A plate that comes back can be remade, but making it again from the same ticket may give you the same plate. If the power fails mid-service, the tickets on the rail tell you what was cooked and what wasn’t. A plate that has already gone out can’t be taken back.
An LLM pipeline has the same parts:
- handoffs: each step works from the previous step’s output;
- checks: they sit between steps;
- retries: a step is redone;
- state: a record of what is finished;
- side effects: a step that changes something outside the system and can’t be undone.
The Pipeline
The demo answers emails sent to the support team of a fictional project-management app, using the same five documents as Articles #15 to #17.
email ──► 1 extract ──► 2 retrieve ──► 3 draft ──► 4 send
model call hybrid search model call the reply is written to the outbox,
questions, over the docs a reply that or the email goes to a review queue
identifiers cites what
it used
- Extract. The model reads the email and returns JSON:
- the questions it asks, each rewritten to stand on its own;
- the product identifiers it mentions, such as
SSO-103,429, orPro.
- Retrieve. Each question gets up to 1,000 tokens of excerpts from the five documents, found with the RRF hybrid retrieval described in Article #16. An email gets at most 3,000.
- Draft. The model writes the reply from the numbered excerpts and returns it as JSON, with the numbers of the excerpts it used.
- Send. The reply is written to an outbox. Nothing is actually emailed: the outbox stands for the external side effect. Once a reply is written there, the pipeline treats it as delivered and never tries to undo it.
Two things surround the steps. After every step, the email’s state (the output of each finished step) is saved to a file. And an email the pipeline won’t answer goes to a review queue for a person.
The checks between steps are deliberately cheap and mechanical. They are code, not a second model, so they can run on every email:
| After | The check |
|---|---|
| Extract | Valid JSON; at least one question; every identifier appears in the email |
| Retrieve | Every identifier from the extraction (except plan names) that appears in the documentation also appears in the retrieved excerpts |
| Draft | Valid JSON; the cited excerpts exist; every value in the reply (numbers, codes such as SSO-101, snake_case names, email addresses) appears in the cited excerpts or in the customer’s email |
When a model step fails its check, it is called again with its previous output and the list of problems, at most twice. If it still fails, the email goes to the review queue. Retrieval has no model call to retry: if it fails its check, the email goes to review straight away.
The Experiment
The test material was written and committed before any pipeline code:
- Emails: 40 fictional customer emails, each asking one to three questions. Six of the questions aren’t answered anywhere in the documentation.
- Labels for each email: its questions, the facts a correct reply must contain, and the passages in the documents that support each fact.
- Split: half of the emails are for developing the prompts and the other half for measuring. Every number below comes from the 20 test emails, unless it is marked as coming from development.
A reply is correct when it states every labelled fact correctly, says that an unanswered question isn’t covered, and states nothing false. Every test reply was read and judged by hand against that definition, with a note on each one that is wrong. Anything a correct reply says beyond the labelled facts was checked against the documents.
The model is a small local one, llama3.2:3b. Its replies are often wrong, and that makes the pipeline’s behaviour around them easy to see. The numbers describe this pipeline with this model, not what a larger model would do.
Implementation note: the exact setup
Machine: Apple M4 Pro (24 GB), macOS 26.6.2
Runtime: Ollama 0.40.16; /api/chat with "format" set to a JSON schema, and /api/embed
Chat model: llama3.2:3b, ID a80c4f17acd5 (Q4_K_M), temperature 0, seed 1, num_ctx 8192,
at most 400 output tokens for extraction and 700 for a draft
Retrieval: structure-headings chunks (98) and RRF (k = 60) of nomic-embed-text
(ID 0a109f422b47) and BM25, as in Article #16; 1,000 tokens per question,
3,000 per email, in Llama 3.2 tokens
Retries: at most 2 per model step, each with the previous output and the problems
Test set: 20 emails, 38 questions, 3 of them not covered by the documentation
Prompts: v3, developed on the 20 development emails (v1 and v2 are described below)
Languages: Python 3.12.13 and Node.js 24.16.0: the same requests, the same outputs,
and identical reports
Date: 2026-11-15
The settings, the checks, the retry limit, and the crash point were written down before the first run. The prompts describe the JSON fields in words; Ollama’s documentation also suggests passing the schema itself in the prompt, which the demo doesn’t do.
Errors Compound
The first question is the simplest. If each step mostly works, how often does the whole chain work?
To find out, each step was measured on its own, given correct input:
- Extraction got the email.
- Retrieval got the labelled questions instead of the extracted ones.
- Drafting got the labelled questions and gold excerpts: the retrieved excerpts, plus any chunk holding a missing piece of evidence.
Then the chain ran end to end, with each step working from the previous step’s output.
| Step, given correct input | Emails where it did its job |
|---|---|
| Extraction: found the questions | 18 of 20 |
| Retrieval: found evidence for every fact | 20 of 20 |
| Drafting: wrote a correct reply | 10 of 20 |
If the steps failed independently, the chain would get 0.9 × 1.0 × 0.5 of the emails right: 9.0 of 20. It got 7 of 20. Of the 13 it got wrong, 1 first went wrong at extraction, 1 at retrieval, and 11 at drafting; one of those 13 got no reply at all.
Twenty emails are too few to say how much of the gap between 9 and 7 is real. The email-by-email results show why the independence assumption doesn’t hold, though: a step’s result depends on what it is given.
- Five emails got a correct draft from perfect input but no correct reply in the chain; one of them got no reply at all.
- Two went the other way: wrong from perfect input, correct in the chain.
The drafting step isn’t a coin that lands right half the time. Its result changes with the exact questions and excerpts it is handed.
One email shows the handoff going wrong. A customer asked two questions: whether a page size of limit=500 would fail, and when version 1 of the API stops working.
- Extraction rewrote the first question as “Will limit=500 fail?”. The labels count that as a success, because it is the right question.
- Retrieval, searching for “Will limit=500 fail?”, didn’t find the pagination section. It returned the rate limits instead.
- The draft answered from what it was given: “Yes, limit=500 will fail because the Basic plan has a requests per minute limit of 100.” In fact, a larger page size is treated as 200, and the rate limit has nothing to do with it.
Each step did something reasonable with its input, and the reply was still wrong. The extracted question passed its own score but didn’t carry enough for the next step to search with.
Checks Between Steps
The second question: does checking each step’s output before passing it on keep bad replies out of the outbox? The same 20 emails went through three versions of the pipeline:
| Pipeline | Sent | Correct | Wrong | Not sent / held back | Of those, unchecked reply wrong or missing | Of those, unchecked reply correct |
|---|---|---|---|---|---|---|
| No checks | 19 | 7 | 12 | 1 (an error) | 1 | 0 |
| Checks, no retries | 15 | 5 | 10 | 5 | 3 | 2 |
| Checks and retries | 18 | 6 | 12 | 2 | 1 | 1 |
The last two columns say what the unchecked pipeline did with each email that wasn’t sent: sent a wrong reply or none at all, or sent a correct one.
With retries, the checks kept none of the 12 wrong replies out of the outbox. Both pipelines wrote the same 12 wrong replies, word for word. The checked pipeline differed on only two emails:
- one was the looping draft described below, for which neither pipeline had a reply to send;
- the other had a correct reply, which the checks held back.
The 12 wrong replies were wrong in ways the checks don’t look at:
- Invented answers: confident answers to all 3 test questions the documentation doesn’t cover, such as “If you stay on Pro, there is no discount for paying three years upfront” and “The mobile app does not work offline”.
- False claims: “The app is available in Italian.” The documentation lists English, German, French, and Spanish.
- Missing facts: a reply that answered one question and quietly skipped another.
None of them contained a number or code missing from the excerpts the reply cited. That is all the value check looks for.
Without retries, the checks did keep two of the wrong replies out, but by accident. In both emails, extraction had also listed an identifier that wasn’t in the email (“nonprofit pricing plan”, “3 years upfront”). With retries, the retry fixed the identifier, and the same wrong reply went out.
What the checks did catch was malformed output:
- A runaway draft: one draft repeated
5,in its list of sources until it hit the 700-token limit, so the JSON was never closed. The unchecked pipeline couldn’t use it either; it ended with an error instead of a review entry. - Unfounded identifiers: four extractions listed identifiers that aren’t in the email, such as “Admin role” and “3 years upfront”.
They also held back a correct reply. A retried extraction listed “API key” as an identifier. The excerpt that answers the question says “their API keys stop working”. The check compares whole words, so the plural didn’t count, and an email whose unchecked reply was correct went to review.
During development, the value check did catch invented values. These examples are not counted in the table:
- One reply put the cost of an upgrade at “$15”. The documentation’s worked example says “(25 - 10) / 2 = $7.50”, and the model copied it without the “/ 2”. The check flagged “15”, and the retry, given that problem, wrote $7.50.
- Another reply promised “99.99% uptime, with a maximum of 1 minute of downtime per year”. The check flagged “99.99”, and the retry dropped the claim. It didn’t flag the “1”: a “1” appears in “TLS 1.2” in a cited excerpt, and the check sees values, not what they mean.
So these checks test form and provenance: is the output well formed, and did each value come from somewhere? They don’t test truth: is the answer right? A reply can be well formed, cite real excerpts, and still be wrong.
Under the hood: what the value check reads
The check pulls values out of the reply text in this order, removing each match before the next pattern runs:
- email addresses;
- codes such as
SSO-101orAES-256; snake_casenames such ascursor_expired;- any word that contains digits, taken whole:
16th,SHA256,v2,7.50,1,000(compared as1000).
Citation markers like [2] and list numbers at the start of a line are skipped. Each value must appear as a whole word in a cited excerpt or in the customer’s email, after lowercasing and the normalization the labels use.
Two of these rules came from development runs:
- The first version split “1st” and “HMAC-SHA256” into the numbers “1” and “256”, and flagged both.
- Taking a word with digits whole fixed that. It also means “100MB” won’t match “100 MB”.
Every rule like this trades false alarms against missed errors. What the check can’t do at all is notice that a value sits in the wrong sentence.
Retries
When a check fails, the pipeline calls the step again with its previous output and the problems:
| Step | First attempts that failed | Fixed by the first retry | Fixed by the second | Still failing | Extra calls |
|---|---|---|---|---|---|
| Extract | 4 | 4 | 0 | 0 | 4 |
| Draft | 1 | 0 | 0 | 1 | 2 |
Retrying the four extractions fixed what the check complained about, the identifiers. But the identifiers don’t go into the draft, and the questions didn’t change. For three of the four emails, the reply came out word for word the same as without the retry, and two of those three replies were wrong. The fourth was the email held back by the plural “API keys”. The retries did what they were asked to do and changed nothing that reached the outbox.
The draft that looped looped again on both retries, and the email went to review.
Sending the same request again doesn’t help. Each of the five failed first requests was also sent again unchanged, without the problems, after reloading the model. All five came back identical to the first attempt. With temperature 0, as here, a retry of a model’s wrong answer needs something new: the error message, different input, or different settings. That is different from retrying a timeout or a dropped connection, where the same request may well succeed.
The cost, in model calls for the 20 emails:
- no checks: 40;
- checks, no retries: 36, because emails that stop early skip the draft;
- checks and retries: 45.
When the Process Dies
The last question is what happens when the process dies in the middle of a run. The demo makes that happen for real. The checked pipeline runs over the 20 test emails as a separate process, which exits at one chosen moment: right after the reply to one email is written to the outbox, and before that email’s state records the send.
By then the process had started 12 of the 20 emails and made 29 model calls. The outbox held 11 replies, and one email was in the review queue. Each way of recovering then started from its own copy of what the crash left behind. The outbox survives in every case, because it stands for email that has already been delivered.
| Recovery | Model calls | Outbox entries | Emails sent twice |
|---|---|---|---|
| Restart: run every email again, ignoring the saved state | 45 | 29 | 11 |
| Resume from the saved state | 16 | 19 | 1 |
| Resume, and check the outbox before writing | 16 | 18 | 0 |
Restarting costs a full run, 45 calls, because none of the work already done can be reused. It also sends every one of the 11 replies a second time; the review entry is written twice too.
Resuming from the saved state makes only the 16 calls that the 8 unstarted emails need. It still sends one email twice, the one the crash interrupted. That email’s state ends before the send, because the crash came between writing the reply and recording it. No ordering of those two writes removes the gap:
- Record the send first: a crash in between leaves a reply that was recorded as sent but never written.
- Write the reply first: a crash in between leaves a reply that was written but not recorded, and that one is sent again.
Checking the outbox before writing closes the gap in this demo, because the outbox is one local file with one writer. With several workers, or an outbox that is someone else’s email service, a lookup like this isn’t enough. The usual answers are idempotency keys and a transactional outbox, and the series plans them for Article #38, Designing Reliable LLM Workflows.
Every duplicate reply was identical to the first copy, because each model call returned the same output as in the earlier run. That was observed in this setup, not guaranteed. Article #17 found that the model’s scores changed slightly when Ollama served part of a repeated request from its prompt cache. A saved step result doesn’t depend on that. It is the one copy of the answer that every later step uses.
What Breaks
All of these happened in the demo:
- A step passes its own score but starves the next step. “Will limit=500 fail?” counts as the right question, but it doesn’t carry enough for retrieval to find the answer.
- A check of form passes a wrong answer. All 12 wrong replies were valid JSON, cited real excerpts, and contained no unsupported value.
- A check inherits another step’s mistakes. The retrieval check trusts extraction’s identifiers. During development, extraction listed “EU”, “SSO”, and even “Tuesday”, and two emails were held back over identifiers that had nothing to do with their questions.
- Exact matching rejects correct text. “API key” didn’t match “API keys”, and a correct reply was held back.
- Constrained output can still be unusable. A JSON schema doesn’t stop a model from repeating itself until the token limit cuts it off.
- Examples in a prompt become output. The first extraction prompt gave “SSO-104” and “rate_limited” as examples of identifiers, and the model listed them for emails that never mentioned them. The second listed “Basic” and “Pro” as plan names, and the model returned them for 11 of the 20 development emails, which don’t mention them.
- A retry without new information repeats the failure. Five of five unchanged requests returned the same output.
- Recovery without state repeats side effects, and recovery with state still repeats the one the crash interrupted.
Engineering Decisions
1. Measure the chain, not only the steps
Each step’s own score said little about the chain. Retrieval scored 20 of 20 on the labelled questions, but one email still failed at retrieval in the chain, because extraction phrased the question differently. Measure each step with the input it will really get, and measure the whole chain end to end.
2. Decide what each check is for, and count its false alarms
Each check should guard against a specific failure, and you should know which failures it doesn’t guard against. Count both directions: the bad outputs it stops, and the good ones it holds back. Here, with retries, the checks held back one correct reply and kept none of the 12 wrong replies from going out. A check that only ever looks at what it stopped will look better than it is.
3. Retry only when something changes
A retry is useful when the next attempt differs from the last:
- the error message is added to the request;
- the input or the settings are different;
- the failure was transient, such as a timeout.
Here, the same request at temperature 0 returned the same output every time, so sending it again just cost a second call. Cap the number of retries, and send what still fails somewhere a person will see it.
4. Save each step’s result before starting the next
Saved state turned a crash that would have cost 45 calls into one that cost 16. It also gives you a record of what each step produced, so a wrong reply can be traced back to the step where it started.
5. Treat the side effect as the boundary
Sending the reply is the one step that can’t be undone, so it comes last, after every check. Before repeating it, check whether it already happened. Know where the gap between doing it and recording it is, because some crash will eventually land there.
6. Send failures to people, and read what passes
A review queue makes failures visible instead of silent. But the replies that pass the checks are where most of the wrong answers were. Read a sample of them regularly.
What to Take Away
- A chain is not as good as its best step. Here it got 7 of 20 emails right, while extraction and retrieval each did their job for at least 18 of 20 on their own.
- Steps don’t fail independently. A step’s result depends on the exact input it is handed, so measure the chain end to end.
- Cheap checks catch malformed output and invented values, not wrong answers. With retries, the same 12 wrong replies went out as with no checks, and one correct reply was held back.
- A retry needs new information. The same request at temperature 0 returned the same output five times out of five.
- Save state, and treat the side effect as the boundary. Resuming cost 16 calls instead of 45, and checking the outbox before writing removed the last duplicate.
Think About These Use Cases
-
An invoice-processing pipeline: It extracts fields from a PDF, looks up the supplier, and posts a payment. Which step is the side effect, and what would you check before it?
-
A check that never fires: Your pipeline’s validation step has passed every output for a month. How would you find out whether that means the outputs are good or the check is blind?
-
A model that returns invalid JSON one time in fifty: Would you retry, change the prompt, raise the token limit, or send those cases to review? What would you measure to decide?
-
A nightly batch of 10,000 emails: The process dies at email 6,000. What must have been saved, and when, for the rerun to cost only the remaining 4,000?
-
Two workers reading the same queue: Both pick up the same email after a timeout. What stops the customer from getting two replies?
If you want to work through one of these, take it to GPT along with this article. Ask GPT ↗️
Related Sources
- 01-reliable-llm-pipeline: The companion demo. It has the four-step pipeline, the checks and retries, the saved state and outbox, and the crash and recovery experiment, with the frozen test emails and hand labels (Python and JavaScript).
- Building effective agents (Anthropic, 2024): Describes “prompt chaining”, a sequence of model calls with programmatic checks between steps.
- Ollama: Structured outputs: Constraining a model’s output with a JSON schema in the
formatfield. Its examples still validate the output after the call. - Timeouts, retries, and backoff with jitter (Amazon Builders’ Library): When retries help, when they make things worse, and how to space them out.
- Making retries safe with idempotent APIs (Amazon Builders’ Library): Why a repeated request must not repeat its side effect, and how an API can recognize a repeat.
- Pattern: Transactional outbox (microservices.io): Recording a state change and the message that announces it in one transaction, so neither happens without the other.
What’s Next?
This pipeline answers an email and writes the reply in one piece. For a person waiting at a screen, the wait itself becomes part of the problem: several model calls in a row can take many seconds before anything appears.
In the next article, we’ll look at Streaming LLM Responses: Why and How: what changes when a reply is shown as it is generated, starting from what the user sees and working back into the architecture.