Vai al contenuto

AI Engineering & RAG in Produzione

Cheatsheet di AI Engineering & Production RAG

Riferimento completo e stampabile: matematica della tokenomica, geometria dello spazio vettoriale, formule di ricerca ibrida, contratti JSON schema per tool calling, loop agentici, diagnostica della Triade RAG e checklist di sicurezza per la produzione. Stampa questa guida con Ctrl+P / ⌘P.

La Pipeline in 8 Stadi di AI Engineering di Produzione

Ogni applicazione enterprise RAG o agente autonomo segue questo ciclo ingegneristico.

  1. Token Budget & Framing: Calculate max prompt token allowance, reserving 25-30% headroom for reasoning and generation.
  2. Structure-Aware Chunking: Split documents on semantic or markdown boundaries (300-600 tokens) with 10-15% overlap.
  3. Contextual Preambles: Prepend document-level situational context (Title, Section, Date) to eliminate decontextualized chunk failure.
  4. Dense + Sparse Ingestion: Generate L2-normalized embeddings into an HNSW vector index and build a parallel BM25 lexical index.
  5. Hybrid Retrieval & RRF: Fetch Top-30 dense and Top-30 sparse candidates; fuse rankings with Reciprocal Rank Fusion (k=60).
  6. Neural Cross-Encoder Rerank: Score the merged Top-30 with a cross-encoder to isolate the Top-5 high-precision chunks.
  7. U-Shaped Context Packing: Order selected chunks in a U-shape ([1, 3, 5, 4, 2]) to counteract Lost-in-the-Middle attention decay.
  8. Evaluation & Guardrails: Enforce delimiter boundaries, post-flight PII redaction, and continuously track RAG Triad scores in CI/CD.

Riferimento Tokenomica & Memoria GPU per KV-Cache

Regole matematiche fondamentali per dimensionare il context window e la memoria di inferenza.

Parameter / MetricFormula / Rule of ThumbProduction Implication
Subword Ratio1,000 tokens ≈ 750 English wordsCharacters per token ≈ 4.0; non-Latin alphabets consume 2-3x more tokens.
KV-Cache Memory2 × n_layers × n_heads × d_head × n_ctx × 2 bytes128k context on a 70B model requires ~18 GB vRAM purely for KV-cache per concurrent user.
Lost-in-the-MiddleAccuracy dips by up to 40% in central 33% of contextPlace highest-ranked documents at position 0 (primacy) and position -1 (recency).
Prompt Caching SavingsCached token prefix discount ≈ 90% cost, 70% TTFTStructure 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.

MetricMathematical EquationProperties & Optimal Use Case
Cosine Similaritycos(θ) = (A · B) / (||A||₂ × ||B||₂)Range [-1.0, 1.0]. Invariant to vector magnitude; optimal for general semantic search.
Dot ProductA · B = ∑ (A_i × B_i)Equivalent to Cosine Similarity when vectors are L2-normalized (||A||₂ = 1.0). 3x faster.
Euclidean Distanced(A, B) = √∑(A_i - B_i)²Normalized: d² = 2 - 2(A · B). Minimizing Euclidean distance equals maximizing Dot Product.
Bi-Encoder vs Cross-EncoderDual vs Joint AttentionBi-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 PillarMeasured DyadObserved SymptomPrescribed Engineering Remedy
Context RelevanceQuery ↔ ContextRetrieved 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 ↔ AnswerModel 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 RelevanceQuery ↔ AnswerModel 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. 1. Exponential Backoff with Jitter: All API calls wrapped in retry logic with random sleep bounds.
  2. 2. Multi-Provider Fallback Routing: Automatic failover from primary provider to secondary on 429/503.
  3. 3. Delimiter Isolation: All untrusted user content wrapped in XML tags with breakout tag sanitization.
  4. 4. Output PII Redaction: Post-flight regex masking active for credit cards, SSNs, and API keys.
  5. 5. Least-Privilege Scoped Tools: Mutating and destructive actions guarded behind Human-in-the-Loop tokens.
  6. 6. Token Budget Allocation: Strict max_tokens ceilings enforced on both input prompts and completions.
  7. 7. Vector Semantic Caching: Frequent and repetitive questions intercepted with < 10ms latency at $0.00.
  8. 8. Continuous Evaluation in CI/CD: RAG Triad scores automated on golden test datasets on every PR.
  9. 9. Streaming Token Delivery (SSE): Time-To-First-Token under 500ms for conversational user interfaces.
  10. 10. OpenTelemetry Tracing: Prompt token counts, tool execution durations, and error rates logged to telemetry.
PDF / Print

Salva o stampa questo cheatsheet in PDF

Versione ottimizzata per la stampa: aprila con un clic e salva come PDF dal browser, senza account né email.