Patterns
50 patterns across 10 pillars, each with a runnable, tested example. Not sure where to start? Try the decision guide.
Circuit Breaker for LLMs
Stop sending traffic to a degraded provider before your users notice, and count slow or empty answers as failures, not just errors.
Data Contract
An executable agreement about a dataset's schema, null rates, allowed values and freshness, checked by the producer before publishing and by the consumer before ingesting.
GraphRAG
For questions about relationships, find the entities in the question, walk the knowledge graph a few hops, and give the model the facts and paths with their sources.
Human-in-the-Loop
An approval gate in the tool-execution layer. Low-risk actions run, consequential ones wait for a person who can approve, edit or deny, and silence means no.
Hybrid Search
Run keyword (BM25) and vector search side by side and merge the rankings, so exact identifiers and paraphrases both get found.
Input Sanitization
Normalize, bound, redact and score user input before it reaches the model. Redaction is reliable; injection detection is only a speed bump.
LLM Gateway
Put one service between your code and every model provider, and make keys, budgets, routing, retries and logging its job instead of every team's.
Loop Termination
One stop decision checked after every step (goal met, ceiling reached, or stalled), and every non-success exit returns the best result so far with a reason.
Span-Level Tracing
One trace per request, one span per pipeline step, with tokens and cost on every model call, so "why was this slow, expensive or wrong?" has an answer.
Token Budget
Give each part of the prompt its own token budget, always reserve room for the answer, and trim in a fixed, explainable order.
Cascading Context Assembly
Answer with a little context first, and retrieve more only when the model says, with an exact sentinel, that it can't answer from what it has.
Entity Resolution Graph
Decide which records across sources are the same entity using a match graph, and never let one fuzzy link chain two different entities together.
LLM-as-Judge
Use a model to grade outputs against a concrete rubric. Run comparisons in both orders and check the judge against human labels before trusting its scores.
Model Router
Send each query to the cheapest model that can handle it, and escalate when the cheap answer doesn't pass a check.
No-Progress Detection
Notice when an agent loop keeps producing the same thing, or flips between a few things, and stop it before the iteration ceiling, keeping the best attempt.
Prompt Canary Deployment
Ship a prompt change to a small, stable slice of users, compare it with the baseline at each stage, and roll back automatically on any regression.
Request Hedging for LLMs
If the primary hasn't answered by its own p95, send the same request to a backup and take whichever good answer arrives first.
Retrieval Freshness Watermark
Store when each chunk's content became true, drop superseded versions, and show the model how old each source is so it can say so.
Semantic Deduplication
Collapse chunks that say the same thing before indexing, so the retriever doesn't give the model the same answer five times, without merging chunks that differ in a number.
Tool Output Firewall
Treat everything a tool returns as untrusted data. Bound its size, check its shape, scan every text field, and fence it with delimiters it can't forge.
Context Compaction
When an agent's context nears the limit, clear old tool results first, and summarize older messages into a structured note only if that isn't enough.
Embedding Drift Detector
Watch two numbers on live queries, where the average query has moved and how well the index still matches them, to catch RAG degradation before users do.
Graph of Thoughts
Let a program, not the model, run reasoning as a graph. Generate several candidates, score them, merge the best, refine, and stop on a score or a budget.
Guardrails
Checks in code, outside the model, at the input, output and tool boundaries. They run in parallel with a deadline, log every verdict, and fail closed when a safety check breaks.
Maker–Verifier Split
The agent that does the work never decides it's done. An independent verifier checks only the output against the task's criteria and sends back concrete issues.
Model Card
Document each AI feature's intended use, limits, data and evals as data next to the code, and fail CI when the card is incomplete or its evals are stale.
Retrieval Quality Gate
Score retrieved chunks for relevance to this query, drop the ones that don't help, and abstain when nothing does.
Semantic Caching
Answer a query from cache when it means the same as one you've already answered, and stop near-misses from serving the wrong answer.
Uncertainty-Triggered Retry
Treat an unsure answer as a soft failure. Retry once with a stronger setup, and if that's unsure too, tell the user instead of guessing.
Closed-Vocabulary Output
Let the model pick from a fixed list of allowed values and drop anything outside it, so it cannot invent a category, a field or a number your system never defined.
Effort Scaling
Decide up front how much a task deserves (model, tool calls, sub-agents) and enforce it in code, so fact lookups don't get treated like research projects.
Idempotent Tool Calls
Give every side-effecting tool call a key derived from the run and its arguments, so a retried, re-issued or replayed call returns the first result instead of sending, charging or writing twice.
Multi-Agent Orchestration
One agent plans and delegates narrow, non-overlapping subtasks to workers with fresh contexts, then combines their condensed results.
Prompt Mutation Testing
Perturb inputs that already pass (typos, casual tone, synonyms, distractions, injection attempts) and check that the answer still has the right properties.
Reflexion Loop
Actor attempts, evaluator checks, and on failure a reflection step writes one specific lesson to a small memory that the next attempt reads. A repeated lesson means stop.
Reversible Auto-Decision
Decide the clear cases automatically, send only the doubtful middle to a person, and make every automatic decision logged, one-call reversible and never repeated after an undo.
Sliding Context Window with Memory Consolidation
Keep recent turns word for word, summarize older ones, and pin the facts that must never be summarized away.
Durable LLM Job Queue
Run long model work as jobs that are claimed atomically, leased with a timeout, recovered when a worker dies, capped when they keep crashing, and fenced so a stale worker can't overwrite a result.
Extract–Explain Split
Let deterministic code read and validate the facts, let the model only explain them, and rebuild the final answer from the extraction so the model cannot change a number or add an item.
Grounding Verifier
After generation, check every factual sentence against the sources that were in the prompt, and cite, flag or remove what isn't supported.
Prompt Prefix Caching
Build every prompt stable-first so the provider can reuse the processed prefix at a fraction of the price, and catch the one volatile byte that silently turns every request into a miss.
Quota-Aware Model Pool
Treat each model's daily and per-minute allowance as a design constraint. Spend before sending, prefer scarce models for quality work, fall back when one is spent, and fail with a typed error when all are.
Semantic Rollback
Checkpoint a multi-step workflow after each validated step. When a step fails or produces junk, restore the last good state and retry that step with a different strategy.
Shadow Model Evaluation
Send a sample of real traffic to a candidate model in the background with tools disabled, judge it against production, and promote only on a clear, significant win.
Suggest–Edit–Commit
Treat model output that fills a record as an editable draft that only a person commits, and keep every edit as a measurement of where the model is wrong.
Batch Inference
Send work nobody is waiting on through the provider's batch endpoint at about half price, and make the job safe to resume, with results matched by ID and only real failures retried.
Execution-Verified Rewrite
Let a model propose a faster or cheaper version of something you can run, and keep a candidate only if running it gives the same output and a measured gain beyond noise.
Frozen Evaluation Set
Seal an evaluation set before you tune anything, check it shares no records with training data, and enforce a looks budget so a score still means something.
Intent-Only Retrieval
Use the model only to turn a question into filters. The answer is the rows your own data returns, so the model cannot add a result that does not exist.
Provider Behavior Probes
Run a small, fixed suite of rule-scored probes against each provider on a schedule, so "is it us or the provider?" has an answer when tool calls, JSON output, refusals, limits or the model itself change.