Skip to main content

AI Design Patterns Quick Reference

Quick lookup for common patterns. See individual chapters for detailed implementation.


Retrieval Patterns​

PatternUse CaseKey Tradeoff
Basic RAGSimple Q&A over documentsEasy to implement, limited accuracy
Hybrid SearchCombining semantic + keywordBetter recall, more complexity
RerankingHigh-precision retrievalAccuracy vs latency
Query ExpansionAmbiguous queriesBetter recall, more tokens
HyDENo direct matches expectedCreative, but can hallucinate
Parent-Child ChunkingNeed surrounding contextMemory overhead
Query → Embed → Vector Search → Rerank → Top-K → Generate
↓
BM25 Search ─────────┘ (hybrid)

Generation Patterns​

PatternUse CaseKey Tradeoff
Zero-ShotSimple tasksFast, less reliable
Few-ShotNeed format controlToken cost
Chain-of-ThoughtReasoning tasksLatency, shows work
Self-ConsistencyHigh-stakes answers3-5x cost
Structured OutputAPI responsesConstrained creativity

Agent Patterns​

PatternUse CaseComplexity
ReActTool-using agentsMedium
Plan-and-ExecuteMulti-step tasksHigh
Multi-Agent DebateVerificationHigh
Human-in-the-LoopHigh-stakes actionsMedium
Swarm / HandoffSpecialised sub-agentsHigh
Advisor / ExecutorCheap model runs the loop, strong model consulted at decision pointsMedium
Orchestrator + isolated subagentsParallel work without context contentionHigh

Advisor / executor, added in 2026, is the cost-quality lever worth knowing: an inexpensive executor drives the agent loop and calls a stronger advisor model at decision points, passing the transcript and receiving a plan or correction. It is a cost claim rather than a quality claim: pairing a low-effort executor with a stronger advisor can beat the cost-quality line that executor traces by raising its own effort, while the top scores still belong to maximum effort at higher cost. Published figures are vendor-benchmarked, so measure on your own tasks. Consult rate is the metric to watch: if the executor consults on nearly every step you have bought an expensive model with extra latency.

Orchestrator plus isolated subagents is where the single-versus-multi-agent argument landed. Subagents get their own context and return summaries, with no peer-to-peer channel between them. Context is what is isolated, not state: managed platforms typically share one sandbox, filesystem, and credential set across the roster. Vendor platforms enforce the limits that make it work in practice, typically one level of delegation and a cap on roster size, which is a good default even when your framework does not enforce it.

┌─────────────────────────────────────────┐
│ REACT LOOP │
│ │
│ Observe → Think → Act → Observe → ... │
│ ↓ │
│ [Tool Call] │
│ ↓ │
│ [Result] │
└─────────────────────────────────────────┘

Agentic Coding Patterns (2026)​

PatternUse CaseKey Tool
Scaffold → Implement → VerifyFull feature developmentClaude Code / OpenHands
Read-Plan-EditRefactoring existing codeClaude Code text_editor
Test-Driven AgentHigh reliability codeAgent writes tests first
Shadow ReviewPR quality gateAgent reviews diff before merge
CLAUDE.md ManifestProject context injectionClaude Code CLAUDE.md file
Sub-Agent ParallelismLarge codebase changesMultiple agents per module
┌────────────────────────────────────────────────────────┐
│ AGENTIC CODING LOOP │
│ │
│ Understand → Plan → Implement → Run Tests → Fix │
│ ↑ (bash + text_editor tools) │ │
│ └──────────── Iterate until tests pass ────┘ │
│ │
│ [CLAUDE.md injects: coding style, test commands, │
│ forbidden patterns, architecture decisions] │
└────────────────────────────────────────────────────────┘

When to use which tool:

Need full autonomy + CLI → Claude Code
Need open-source + any LLM → OpenHands / Cline
Need tight IDE integration → Cursor / Windsurf
Need reproducible pipelines → OpenHands in Docker CI

Reliability Patterns​

PatternProblem SolvedImplementation
Retry with BackoffTransient failuresExponential backoff
Circuit BreakerCascading failuresFail-fast after threshold
Fallback ModelPrimary unavailableSecondary model
TimeoutSlow responsesCancel + fallback
BulkheadResource isolationSeparate pools
# Reliability stack
@circuit_breaker(failure_threshold=5)
@retry(max_attempts=3, backoff=exponential)
@timeout(seconds=30)
@fallback(model="gpt-4o-mini")
async def generate(prompt):
return await primary_model.generate(prompt)

Caching Patterns​

PatternHit RateUse Case
Exact MatchLowIdentical queries
Semantic CacheMediumSimilar queries
KV CacheHighSame prefix
Response CacheVariesDeterministic outputs

Security Patterns​

PatternThreatImplementation
Input ValidationPrompt injectionSanitize, detect
Output FilteringData leakagePII detection, blocklists
Tenant IsolationCross-tenant accessFilter at query time
Rate LimitingAbusePer-user/tenant limits
Input → Validate → Sanitize → LLM → Filter → Validate → Output

Evaluation Patterns​

PatternUse CaseMetrics
Golden SetRegression testingPass rate
LLM-as-JudgeQuality scoring1-5 scale
Human EvalGround truthAgreement rate
A/B TestingProduction comparisonUser metrics

Cost Optimization Patterns​

PatternSavingsTradeoff
Model Routing50-70%Complexity
Caching20-40%Staleness
Prompt Compression10-30%Quality risk
Batch Processing30-50%Latency
Query → Classify → Route → [Small Model] or [Large Model]
↓
[Cheap: 80%] [Expensive: 20%]

Anti-Patterns to Avoid​

Anti-PatternProblemBetter Approach
Context StuffingToken wasteRetrieve relevant only
Retry ForeverResource exhaustionCircuit breaker
Trust All OutputHallucinationVerify, ground
Single ModelSingle point of failureMulti-provider
No ObservabilityBlind debuggingTrace everything
Infinite Agentic LoopAgent spins without progressMax turns + Critic agent
Over-trusting Computer-UseAgent clicks wrong UI elementsScreenshot validation + HITL
No CLAUDE.md / ManifestAgent lacks project contextAlways provide coding manifest
Thinking Mode Always On3-10x cost with no benefitGate on complexity classifier

Pattern Selection Guide​

Starting a new project?

  1. Begin with Basic RAG
  2. Add reranking when precision matters
  3. Add hybrid search for keyword-heavy content

Need reliability?

  1. Start with retry + timeout
  2. Add circuit breaker for external calls
  3. Add fallback models for critical paths

Cost concerns?

  1. Implement semantic caching first
  2. Add model routing for query complexity
  3. Batch where latency allows

See 15-ai-design-patterns/ for detailed implementations