02 Reference 5 min read 986 words

AI Design Patterns Quick Reference

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

referencepatternsanti-patternsragcore
01patterns

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
02patterns

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
03patterns

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
04coding patterns

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

When to use which tool:

Texttext · 4 lines
1234
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
05patterns

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
Pythonpython · 7 lines
1234567
# 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)
06patterns

Caching Patterns

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

Security Patterns

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

Evaluation Patterns

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

Cost Optimization Patterns

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

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
11selection guide

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

summary · added by this rebuild

Key takeaways

01

A lookup table, not a tutorial

Nine pattern families — retrieval, generation, agent, agentic coding, reliability, caching, security, evaluation and cost — each a table of pattern, use case and the tradeoff bought.

02

Every cost pattern carries a price

Model routing saves 50-70 percent, batch processing 30-50, caching 20-40 and prompt compression 10-30, each against a named cost such as staleness, latency or quality risk.

03

Reliability stacks as decorators

The example composes a circuit breaker at five failures, three retries with exponential backoff, a 30-second timeout and a gpt-4o-mini fallback onto one generate call.

04

Agentic coding is its own pattern family

Scaffold-implement-verify, read-plan-edit, test-driven agent, shadow review, the CLAUDE.md manifest and sub-agent parallelism are listed as file-system-level patterns distinct from orchestration.

05

Start basic, add precision later

The selection guide sequences work: basic RAG first, reranking when precision matters, hybrid search for keyword-heavy content; for cost, semantic caching before model routing.