AI Engineering & Production RAG
AI Engineering & Enterprise RAG Cheatsheet
A high-density printable one-stop reference: tokenomics math, vector space geometry, hybrid search formulas, JSON schema tool calling contracts, agent loops, RAG Triad failure diagnostics, and production security checklists. Print it with Ctrl+P / ⌘P.
The 8-Stage Production AI Engineering Pipeline
Every enterprise RAG and agent application follows this iterative engineering loop.
- Token Budget & Framing: Calculate max prompt token allowance, reserving 25-30% headroom for reasoning and generation.
- Structure-Aware Chunking: Split documents on semantic or markdown boundaries (300-600 tokens) with 10-15% overlap.
- Contextual Preambles: Prepend document-level situational context (Title, Section, Date) to eliminate decontextualized chunk failure.
- Dense + Sparse Ingestion: Generate L2-normalized embeddings into an HNSW vector index and build a parallel BM25 lexical index.
- Hybrid Retrieval & RRF: Fetch Top-30 dense and Top-30 sparse candidates; fuse rankings with Reciprocal Rank Fusion (k=60).
- Neural Cross-Encoder Rerank: Score the merged Top-30 with a cross-encoder to isolate the Top-5 high-precision chunks.
- U-Shaped Context Packing: Order selected chunks in a U-shape ([1, 3, 5, 4, 2]) to counteract Lost-in-the-Middle attention decay.
- Evaluation & Guardrails: Enforce delimiter boundaries, post-flight PII redaction, and continuously track RAG Triad scores in CI/CD.
Tokenomics & KV-Cache GPU Memory Reference
Essential mathematical rules of thumb for context window budgeting and inference memory.
| Parameter / Metric | Formula / Rule of Thumb | Production Implication |
|---|---|---|
| Subword Ratio | 1,000 tokens ≈ 750 English words | Characters per token ≈ 4.0; non-Latin alphabets consume 2-3x more tokens. |
| KV-Cache Memory | 2 × n_layers × n_heads × d_head × n_ctx × 2 bytes | 128k context on a 70B model requires ~18 GB vRAM purely for KV-cache per concurrent user. |
| Lost-in-the-Middle | Accuracy dips by up to 40% in central 33% of context | Place highest-ranked documents at position 0 (primacy) and position -1 (recency). |
| Prompt Caching Savings | Cached token prefix discount ≈ 90% cost, 70% TTFT | Structure prompts with static system instructions and common context at the top. |
Vector Space Geometry & Similarity Metrics
Mathematical properties of dense semantic representations in high-dimensional space.
| Metric | Mathematical Equation | Properties & Optimal Use Case |
|---|---|---|
| Cosine Similarity | cos(θ) = (A · B) / (||A||₂ × ||B||₂) | Range [-1.0, 1.0]. Invariant to vector magnitude; optimal for general semantic search. |
| Dot Product | A · B = ∑ (A_i × B_i) | Equivalent to Cosine Similarity when vectors are L2-normalized (||A||₂ = 1.0). 3x faster. |
| Euclidean Distance | d(A, B) = √∑(A_i - B_i)² | Normalized: d² = 2 - 2(A · B). Minimizing Euclidean distance equals maximizing Dot Product. |
| Bi-Encoder vs Cross-Encoder | Dual vs Joint Attention | Bi-encoder: pre-computable offline, O(1) dot product. Cross-encoder: runtime O(N) forward passes, State-of-the-Art precision. |
Retrieval Algorithms: BM25, RRF & HNSW
Production formulas for hybrid lexical-semantic search and ranking.
Reciprocal Rank Fusion (RRF)
def reciprocal_rank_fusion(ranked_lists: list[list[str]], k: int = 60) -> list[tuple[str, float]]: scores: dict[str, float] = {} for r_list in ranked_lists: for rank, doc_id in enumerate(r_list, start=1): scores[doc_id] = scores.get(doc_id, 0.0) + (1.0 / (k + rank)) return sorted(scores.items(), key=lambda x: x[1], reverse=True)k=60 is the industry standard constant from Cormack et al.
U-Shaped Context Ordering
def u_shaped_order(ranked_chunks: list[dict]) -> list[dict]: if len(ranked_chunks) <= 2: return list(ranked_chunks) left, right = [], [] for idx, chunk in enumerate(ranked_chunks): (left if idx % 2 == 0 else right).append(chunk) return left + right[::-1]Places Rank 1 at index 0 and Rank 2 at the very end before the question.
Contextual Preamble Formatting
def format_contextual_chunk(doc_title: str, section: str, raw_text: str) -> str: return f"[{doc_title.strip()} > {section.strip()}]\n{raw_text.strip()}"Reduces retrieval failure rates by up to 67% on decontextualized text.
Tool Calling: JSON Schema & Exception Containment
Standardized function declaration and safe dispatch patterns.
OpenAI Tool Schema Specification
WEATHER_TOOL_SCHEMA = { "type": "function", "function": { "name": "get_weather", "description": "Fetches current temperature and conditions for a given city.", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "City name, e.g. London"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["city"] } } }Always specify enums for constrained parameter values.
Safe Tool Dispatcher with Exception Containment
import json def safe_tool_dispatch(registry: dict, tool_name: str, raw_args: str) -> dict: try: args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args if tool_name not in registry: raise KeyError(f"Tool '{tool_name}' is not registered.") result = registry[tool_name](**args) return {"status": "success", "content": json.dumps(result)} except Exception as e: # Reflect structured error back to the model for self-correction! return { "status": "error", "content": json.dumps({"error": type(e).__name__, "message": str(e)}) }Never allow tool exceptions to crash the application runtime.
The RAG Triad Diagnostic Matrix
Isolate and remedy retrieval vs generation failure modes.
| Failed Triad Pillar | Measured Dyad | Observed Symptom | Prescribed Engineering Remedy |
|---|---|---|---|
| Context Relevance | Query ↔ Context | Retrieved chunks are off-topic or noisy; prompt saturated with irrelevance. | Tune chunk size, upgrade embedding model, add hybrid BM25 + Dense RRF, or adjust candidate pool K. |
| Groundedness (Faithfulness) | Context ↔ Answer | Model hallucinates facts, statistics, or policies absent from retrieved text. | Set temperature T=0.0, enforce inline bracket citations [1], penalize unsupported claims in rubric. |
| Answer Relevance | Query ↔ Answer | Model drifts off-topic, gives boilerplate disclaimers, or evades the question. | Refine system prompt directives, add few-shot demonstration pairs, enforce structured JSON schemas. |
Prompt Injection Defense & Delimiter Isolation
Hardening generative systems against adversarial inputs and data exfiltration.
Structured XML Delimiter Boundary
import re def sanitize_and_wrap(system_prompt: str, user_input: str) -> str: # 1. Strip closing delimiter tags from untrusted input to prevent tag breakout clean_user = re.sub(r'</?user_query>', '', user_input, flags=re.IGNORECASE).strip() # 2. Wrap strictly inside XML isolation boundaries return f"{system_prompt.strip()}\n\n<user_query>\n{clean_user}\n</user_query>"Explicitly instruct the model that content inside <user_query> is passive data.
Exponential Backoff with Full Jitter
import random def backoff_sleep_time(attempt: int, base: float = 1.0, max_sleep: float = 32.0) -> float: # Full jitter distributes retries uniformly across [0, cap] cap = min(max_sleep, base * (2.0 ** attempt)) return random.uniform(0.0, cap)Prevents thundering herd spikes when recovering from HTTP 429 rate limits.
The 10-Point Production AI Readiness Checklist
Verify each requirement before shipping LLM applications to production traffic.
- 1. Exponential Backoff with Jitter: All API calls wrapped in retry logic with random sleep bounds.
- 2. Multi-Provider Fallback Routing: Automatic failover from primary provider to secondary on 429/503.
- 3. Delimiter Isolation: All untrusted user content wrapped in XML tags with breakout tag sanitization.
- 4. Output PII Redaction: Post-flight regex masking active for credit cards, SSNs, and API keys.
- 5. Least-Privilege Scoped Tools: Mutating and destructive actions guarded behind Human-in-the-Loop tokens.
- 6. Token Budget Allocation: Strict max_tokens ceilings enforced on both input prompts and completions.
- 7. Vector Semantic Caching: Frequent and repetitive questions intercepted with < 10ms latency at $0.00.
- 8. Continuous Evaluation in CI/CD: RAG Triad scores automated on golden test datasets on every PR.
- 9. Streaming Token Delivery (SSE): Time-To-First-Token under 500ms for conversational user interfaces.
- 10. OpenTelemetry Tracing: Prompt token counts, tool execution durations, and error rates logged to telemetry.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.