Numbers to have at hand

LLM Fundamentals

Prompting & Context Engineering

  • Anthropic: long docs (~20K+ tokens) on top and the query at the end gave up to ~30% better responses on complex multi-document inputs. Anatomy of a prompt
  • OpenAI GPT-4.1 guide: instructions both above and below long context beat either alone; if only once, put them above. Anatomy of a prompt
  • Anthropic cache reads bill at 10% of the base input price (5% on Opus/Sonnet 5.5, late 2026), for an identical prefix only. Anatomy of a prompt
  • OpenAI caches prompts automatically from 1,024 tokens, also prefix-only. Anatomy of a prompt
  • Start with 3–5 diverse examples (Anthropic's guidance); add more only if your eval improves. Zero-shot vs few-shot prompting
  • Zhao et al. 2021: prompt format, example choice and order alone swung GPT-3 from near chance to near state-of-the-art. Zero-shot vs few-shot prompting
  • Min et al. 2022: random labels in the demos barely hurt classification accuracy; format and label space carry much of the effect. Zero-shot vs few-shot prompting
  • Many-shot ICL (Agarwal et al. 2024): hundreds to thousands of examples in long context gave significant gains across many tasks. Zero-shot vs few-shot prompting
  • DeepSeek-R1 paper: few-shot consistently degraded the reasoning model, so they recommend zero-shot. Zero-shot vs few-shot prompting
  • Zero-shot CoT (Kojima 2022): InstructGPT went 17.7% → 78.7% on MultiArith and 10.4% → 40.7% on GSM8K. Chain-of-thought (CoT)
  • Few-shot CoT (Wei 2022): PaLM 540B on GSM8K 17.9% → 56.9%; gains appeared only at ~100B+ parameters. Chain-of-thought (CoT)
  • Sprague et al. 2024 meta-analysis: CoT's benefit concentrates on math and symbolic reasoning, with much smaller gains elsewhere. Chain-of-thought (CoT)
  • Anthropic 2025: reasoning models mentioned a hint they had used only ~25% (Claude 3.7 Sonnet) and ~39% (DeepSeek-R1) of the time. Chain-of-thought (CoT)
  • Reasoning and thinking tokens bill as output tokens, even when hidden or summarized. On Claude 4.6+, depth is set by adaptive thinking plus effort; budget_tokens is rejected from 4.7 on (late 2026). Chain-of-thought (CoT)
  • OpenAI eval: gpt-4o-2024-08-06 with Structured Outputs scored 100% on complex schema following; gpt-4-0613 scored under 40%. Structured outputs & JSON mode
  • Tam et al. 2024: stricter format constraints generally meant larger drops on reasoning tasks. Structured outputs & JSON mode
  • Rule of thumb: allow 1–2 retries with the validation error; if more than ~1% of calls need one, fix the schema or the prompt. Structured outputs & JSON mode
  • Anthropic reports that putting the question after long documents improves response quality by up to ~30% on complex multi-document inputs. Prompt techniques that matter
  • Anthropic recommends 3–5 diverse, relevant examples for few-shot prompting. Prompt techniques that matter
  • OpenAI's GPT-4.1 guide: in long contexts, repeat key instructions at both the start and the end; XML delimited documents well, JSON poorly. Prompt techniques that matter
  • Anthropic: a sub-agent may explore with tens of thousands of tokens but returns a condensed summary of ~1,000–2,000 tokens. Context engineering
  • Anthropic's multi-agent researcher: ~15× chat tokens; token usage alone explained ~80% of performance variance on BrowseComp. Context engineering
  • Anthropic reported that clearing stale tool results cut token use by 84% in a 100-turn web-search eval. Context engineering
  • Anthropic (late 2026): cache write 1.25× base input (5-minute TTL) or 2× (1-hour TTL); cache read 0.1×, or 0.05× on Opus and Sonnet 5.5. Prompt caching
  • Break-even with a 1.25× write and 0.1× read is the first reuse: two calls cost ~1.35× instead of 2×. Prompt caching
  • OpenAI (late 2026): on by default from 1,024 tokens; older models discount cached input 50–90% with no write fee; GPT-5.6+ charge 1.25× to write and 0.1× to read. Prompt caching
  • Anthropic's 2024 launch benchmark: a 100k-token cached prompt cut time to first token from 11.5 s to 2.4 s and cost by 90%. Prompt caching
  • Minimum cacheable prefix depends on the model: 512–4,096 tokens on Claude, 1,024 on OpenAI, 2,048–4,096 for Gemini implicit caching. Shorter prompts never cache. Prompt caching
  • Anthropic's rule of thumb (2024): under ~200k tokens (~500 pages), consider skipping RAG and putting the whole knowledge base in the prompt, with caching. Long context vs RAG
  • Lost in the Middle (2023): GPT-3.5-Turbo's multi-document QA accuracy fell ~20 points when the answer moved from the start to the middle of 20 documents. Long context vs RAG
  • RULER (2024): only about half of models claiming 32k+ windows held satisfactory performance at 32k. Long context vs RAG
  • Worked example at $3/M input, 150k-token corpus: ~$0.45/query stuffed, ~$0.05 cached, ~$0.015 with 5k-token RAG. Long context vs RAG
  • Liu et al.: ~20-point accuracy drop when the answer moves from the first to the middle position (GPT-3.5-Turbo, 20 documents). Lost in the middle & context rot
  • RULER: of models claiming 32K+ context, only about half held up at 32K. Lost in the middle & context rot
  • NoLiMa (2025): at 32K tokens, 11 of 13 models fell below 50% of their short-context score; GPT-4o went from 99.3% to 69.7%. Lost in the middle & context rot
  • Anthropic: putting the query after long documents improved response quality by up to 30% in its tests. Lost in the middle & context rot
  • Rollout ladder: ~1–5% → 25–50% → 100%, holding at each step long enough to read online metrics. Prompts as code: versioning
  • Start the CI golden set at ~50–200 cases per prompt; it must finish in minutes or people skip it. Prompts as code: versioning
  • Registry fetches: client-side cache (TTL ~60 s, Langfuse's default) plus a bundled fallback, so an outage never blocks requests. Prompts as code: versioning
  • Pinned snapshots still retire: in Oct 2026 OpenAI gave 3 months' notice that gpt-4o and gpt-4.1 snapshots shut down on Jan 14, 2027. Budget a re-eval per migration. Prompts as code: versioning
  • Wang et al.: +17.9 points on GSM8K for PaLM 540B (40 sampled CoT paths vs greedy CoT). Self-consistency & best-of-N
  • OpenAI o1 on AIME 2024: 74% with one sample, 83% with consensus over 64, 93% reranking 1,000 samples with a learned scorer. Self-consistency & best-of-N
  • Cobbe et al.: a trained verifier on GSM8K gave roughly the boost of a 30× larger model. Self-consistency & best-of-N
  • In production, N ≈ 3–10 is the usual range; benchmarks report 32–64+, with diminishing returns. Self-consistency & best-of-N
  • OPRO: optimized prompts beat human-written ones by up to 8% on GSM8K and up to 50% on Big-Bench Hard tasks. Automatic prompt optimization (DSPy)
  • OPRO's top GSM8K instruction for PaLM 2-L, "Take a deep breath and work on this problem step-by-step": 80.2% vs 71.8% for "Let's think step by step". Automatic prompt optimization (DSPy)
  • MIPRO: beat baseline optimizers on 5 of 7 multi-stage programs with Llama-3-8B, by up to 13% accuracy. Automatic prompt optimization (DSPy)
  • TextGrad: lifted GPT-4o zero-shot accuracy on Google-Proof QA from 51% to 55%. Automatic prompt optimization (DSPy)

RAG & Retrieval

Agents & Tool Use

  • Anthropic (2025): agents use ~4× the tokens of a chat interaction; multi-agent systems ~15×. Agents vs workflows
  • Compounding: at 95% per-step reliability a 10-step run succeeds ~60% of the time (0.95¹⁰ ≈ 0.60); at 99%, ~90%. Agents vs workflows
  • Anthropic's 49% on SWE-bench Verified (Claude 3.5 Sonnet, Oct 2024) used a minimal agent: one prompt, a bash tool, an edit tool, a loop. Agents vs workflows
  • τ-bench (2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 (all 8 retries succeed) was <25% in retail. Tool / function calling
  • Anthropic adds a hidden tool-use system prompt whenever tools are passed: ~290–680 tokens depending on the model (e.g. 497 on Sonnet 4.6, 286 on Opus 5.5; docs, Nov 2026). Tool / function calling
  • Rule of thumb: a tool definition costs ~50–300 tokens, so 30 tools add several thousand tokens to every call. Tool / function calling
  • Latency: N sequential tool steps ≈ N model calls; independent calls returned in one parallel turn cost one. Tool / function calling
  • ReAct paper: +34 and +10 points absolute success over imitation and RL baselines on ALFWorld and WebShop, prompted with only 1–2 examples. ReAct: the agent loop
  • On HotpotQA, ReAct alone slightly trailed chain-of-thought; combining it with self-consistent CoT scored best. On FEVER, ReAct beat CoT. ReAct: the agent loop
  • Cost math: step k re-sends k prior steps, so n steps send ~n²/2 step-sized chunks of input; Prompt caching makes the repeated prefix cheap. ReAct: the agent loop
  • Rule of thumb: set the step cap at ~2–3× the steps a typical successful run needs, measured from traces. ReAct: the agent loop
  • Claude Code caps tool responses at 25,000 tokens by default (Anthropic, 2025). Designing tools for agents (ACI)
  • OpenAI guidance: aim for fewer than ~20 functions available at once, a soft limit for accuracy. Designing tools for agents (ACI)
  • SWE-agent (2024): with a purpose-built ACI, GPT-4 Turbo reached 12.5% pass@1 on SWE-bench; ablations showed interface details alone (edit linting, a windowed file viewer) changed the solve rate. Designing tools for agents (ACI)
  • Rule of thumb: keep typical tool outputs in the hundreds of tokens, with a default page limit of ~10–50 items. Designing tools for agents (ACI)
  • Reliability multiplies: five steps at 95% each ≈ 77% end-to-end (0.95⁵). Gates exist to break this math. Pattern: prompt chaining
  • Latency is additive: end-to-end ≈ sum of step latencies, plus any retries the gates trigger. Pattern: prompt chaining
  • A code gate costs microseconds and $0; an LLM-judge gate adds a full call (~0.5–3 s). Prefer code gates where possible. Pattern: prompt chaining
  • The smallest and largest tiers of one vendor often differ 5–20× per token: GPT-4.1 nano launched at $0.10 vs GPT-4.1 at $2.00 per 1M input tokens (Apr 2025 list prices). Pattern: routing
  • RouteLLM (2024): learned routers cut cost by over 2× on some benchmarks without losing response quality. Pattern: routing
  • FrugalGPT (2023): an LLM cascade matched GPT-4's performance with up to 98% lower cost on its benchmarks. Pattern: routing
  • Rule of thumb for router overhead: a small-LLM call adds a few hundred ms; a local embedding or fine-tuned classifier, ~1–20 ms. Pattern: routing
  • Rule of thumb: wall-clock ≈ max(branch latencies); cost ≈ sum of all branches. Pattern: parallelization
  • Self-consistency (Wang et al., 2022): majority vote over ~40 sampled reasoning paths added +17.9 points on GSM8K over single-path chain-of-thought. Pattern: parallelization
  • Independence math: 3 voters each catching 70% of bugs → any-of ~97%, majority ~78%. Only if their errors were independent, which they rarely are. Pattern: parallelization
  • Rule of thumb: 3–5 voters is a common starting point; add more only if the eval curve still rises. Pattern: parallelization
  • Anthropic (2025): an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval. Pattern: orchestrator–workers
  • Same post: agents use ~4× the tokens of chat; multi-agent systems ~15×. Pattern: orchestrator–workers
  • In Anthropic's BrowseComp analysis, token usage alone explained ~80% of the performance variance. Pattern: orchestrator–workers
  • Spinning up 3–5 subagents in parallel (plus parallel tool calls) cut research time by up to 90% on complex queries. Pattern: orchestrator–workers
  • Self-Refine (2023): iterative self-feedback improved task performance by ~20% absolute on average across 7 tasks. Pattern: evaluator–optimizer
  • Reflexion (2023): feedback from test runs lifted HumanEval pass@1 to 91%, versus 80% for GPT-4 alone. Pattern: evaluator–optimizer
  • Huang et al. (2023): without external feedback, self-correction did not improve reasoning benchmarks and sometimes lowered accuracy. Pattern: evaluator–optimizer
  • Rule of thumb: cap at 2–4 rounds; most of the gain usually lands in the first one or two revisions. Pattern: evaluator–optimizer
  • ReWOO (Xu et al., 2023): ~5× token efficiency and +4% accuracy on HotpotQA versus interleaved reasoning. Planning (plan-and-execute)
  • LLMCompiler (Kim et al., 2023): up to 3.7× lower latency and 6.7× lower cost than ReAct by running the plan's DAG in parallel. Planning (plan-and-execute)
  • Rule of thumb: 3–10 steps per plan, each with a "done when" check; cap replans at 2–3, then escalate. Planning (plan-and-execute)
  • Generative Agents (Park et al., 2023): retrieval score = recency + importance + relevance; recency decays by 0.995 per game hour, importance is rated 1–10 by the LLM. Agent memory
  • Rule of thumb: inject ~5–10 memories (a few hundred to ~2k tokens) per turn, never the full transcript. Agent memory
  • GDPR Art. 17 (right to erasure): deletion must reach memory rows, embeddings and derived summaries, not just the chat log. Agent memory
  • Launched Nov 2024; OpenAI, Google and Microsoft announced support between Mar and May 2025. Model Context Protocol (MCP)
  • Two standard transports, stdio and Streamable HTTP (since spec 2025-03-26, replacing the original HTTP+SSE), and still the two in the 2026-07-28 revision. Current spec revision: 2026-07-28, the stateless one with no initialize handshake. Model Context Protocol (MCP)
  • Integration math: 5 apps × 20 systems = 100 bespoke connectors; with MCP, 5 + 20 = 25 implementations. Model Context Protocol (MCP)
  • Anthropic measured 58 tools from 5 servers (GitHub, Slack, Sentry, Grafana, Splunk) at ~55k tokens of definitions before the conversation starts. Model Context Protocol (MCP)
  • Anthropic: calling MCP tools from code execution instead of direct tool calls cut one workflow from ~150k to ~2k tokens (~98.7%). Model Context Protocol (MCP)
  • Launched Apr 2025 by Google with 50+ partners; to the Linux Foundation in Jun 2025 (founding members include AWS, Cisco, Microsoft, Salesforce, SAP, ServiceNow); under its Agentic AI Foundation since Aug 2026. Agent-to-agent protocols (A2A)
  • Bindings: JSON-RPC 2.0, gRPC and HTTP+JSON over HTTPS, SSE streaming, webhook push; v0.3 (Jul 2025) added signed Agent Cards and the agent-card.json path. Agent-to-agent protocols (A2A)
  • v1.0 (12 Mar 2026): PascalCase operations (SendMessage, GetTask, new ListTasks), TASK_STATE_* enums, Parts without kind, supportedInterfaces replacing the card's url, mandatory A2A-Version header. Agent-to-agent protocols (A2A)
  • Rule of thumb: each agent hop is a full LLM loop (seconds to minutes), so keep delegation chains to 1–2 hops. Agent-to-agent protocols (A2A)
  • Anthropic research system: a single agent uses ~4× the tokens of a chat; multi-agent ~15×. Multi-agent systems
  • Anthropic: an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval. Multi-agent systems
  • Anthropic: token usage alone explained ~80% of the performance variance on BrowseComp. Multi-agent systems
  • MAST (Cemri et al., 2025): 14 failure modes in 3 groups — specification, inter-agent misalignment, verification. Multi-agent systems
  • OSWorld: humans ~72%; Claude 3.5 Sonnet ~15% (Oct 2024); OpenAI CUA 38.1% (Jan 2025); Claude Sonnet 4.5 61.4% (Sep 2025, OSWorld-Verified); Claude Opus 4.6 72.7% (Feb 2026, reported). Computer use & browser agents
  • OpenAI CUA (Jan 2025): 58.1% on WebArena and 87% on WebVoyager — curated web tasks are easier than full desktops. Computer use & browser agents
  • Claude image cost = ⌈width/28⌉ × ⌈height/28⌉ visual tokens (28-px patches, ≈ width × height / 750): a 1280×800 screenshot ≈ 1,334 tokens, every step; Claude 4.7+ models take up to 2,576 px and 4,784 tokens per image (docs, Nov 2026). Computer use & browser agents
  • Claude for Chrome pilot (Aug 2025): prompt-injection attack success fell from 23.6% to 11.2% with mitigations — lower, not zero. Computer use & browser agents
  • AWS Step Functions: Standard workflows run up to 1 year; Express workflows up to 5 minutes. Durable execution for agents
  • Step Functions caps each state's input/output at 256 KB: keep transcripts in S3 and pass pointers. Durable execution for agents
  • Temporal: event history caps at 51,200 events or 50 MB per execution; use Continue-As-New for long agents. Durable execution for agents
  • Stripe may drop idempotency keys after 24 hours: a retry window, not a forever guarantee. Durable execution for agents
  • Rule of thumb: tier by blast radius — read-only auto, writes approve, money/deletes/permissions explicit confirm. Human-in-the-loop & approvals
  • Alert-fatigue precedent: clinicians override 49–96% of drug-safety alerts (van der Sijs et al., 2006). Human-in-the-loop & approvals
  • Anthropic: sandboxing cut Claude Code permission prompts by 84% internally — fewer prompts, more attention per prompt. Human-in-the-loop & approvals
  • Rule of thumb: if >95% of an action's approvals pass unchanged, auto-approve it with sampling. Human-in-the-loop & approvals
  • Compounding: 0.95^20 ≈ 36%, 0.99^20 ≈ 82%, 0.90^10 ≈ 35%. Agent reliability: budgets & loops
  • τ-bench (2024): GPT-4o solved <50% of tasks, and pass^8 in retail fell below 25%. Agent reliability: budgets & loops
  • Rule of thumb: cap steps at ~2–3× the median successful run; stop on the 3rd identical tool call. Agent reliability: budgets & loops

Evaluation

Fine-tuning & Adaptation

Inference, Serving & Cost

  • E2E ≈ TTFT + TPOT × (output tokens − 1); per-user speed = 1/TPOT (20 ms → 50 tokens/s). Latency metrics: TTFT, TPOT, throughput
  • People read ~200–300 words/min ≈ ~4–7 tokens/s; streaming at ~10+ tokens/s outpaces them. Latency metrics: TTFT, TPOT, throughput
  • MLPerf Inference Llama-2-70B server limits (p99): TTFT ≤ 2 s, TPOT ≤ 200 ms; the v5.0 interactive scenario tightens them to 450 ms and 40 ms. Latency metrics: TTFT, TPOT, throughput
  • Rule of thumb for chat: p95 TTFT under ~1 s and TPOT under ~50 ms (20+ tokens/s). Latency metrics: TTFT, TPOT, throughput
  • Forward pass ≈ 2 FLOPs per parameter per token: an 8B model prefilling 2k tokens ≈ 32 TFLOPs. Prefill vs decode
  • Batch-1 decode ≈ 1 FLOP per byte of FP16 weights; an H100 needs ~300 (989 TFLOPS ÷ 3.35 TB/s) to be compute-bound. Prefill vs decode
  • Output lists at ~4–8× input (2025 list prices): GPT-4o $2.50 vs $10, Claude Sonnet $3 vs $15 per million tokens. Prefill vs decode
  • DistServe: up to 7.4× more requests or 12.6× tighter SLOs than co-located serving, keeping >90% of requests within SLO. Prefill vs decode
  • Weights: 70B ≈ 140 GB in FP16, ~70 GB in FP8, ~35 GB in INT4 (+ scales). GPU memory math
  • KV per token in FP16: Llama-3-8B 128 KiB, Llama-3-70B 320 KiB. GPU memory math
  • H100 SXM: 80 GB HBM3 at ~3.35 TB/s; H200: 141 GB at ~4.8 TB/s; A100 80 GB: ~2 TB/s. GPU memory math
  • Batch-1 decode ceiling = bandwidth ÷ weight bytes: 7B FP16 on A100 ≈ 140 tokens/s. GPU memory math
  • vLLM default gpu_memory_utilization = 0.9: 90% of each GPU for weights, activations and KV. GPU memory math
  • Orca: 36.9× throughput over NVIDIA FasterTransformer at the same latency (GPT-3 175B). Continuous batching
  • Anyscale benchmark: up to ~23× throughput vs naive static batching (with vLLM), while also lowering p50 latency. Continuous batching
  • vLLM (PagedAttention + continuous batching): 2–4× throughput over FasterTransformer and Orca at the same latency. Continuous batching
  • Static batch cost = longest sequence × batch size: a 50-token answer next to a 1,000-token one wastes ~95% of its slot. Continuous batching
  • Pre-vLLM servers used only 20–38% of KV memory for real tokens; vLLM wastes under 4%. PagedAttention & vLLM
  • 2–4× throughput vs FasterTransformer/Orca at equal latency (paper); up to 24× vs plain HF Transformers (vLLM launch blog). PagedAttention & vLLM
  • Sharing cuts the memory of parallel sampling and beam search by up to 55% (vLLM blog). PagedAttention & vLLM
  • Defaults: 16 tokens per block; gpu_memory_utilization=0.9. PagedAttention & vLLM
  • A100: ~20 MB of on-chip SRAM at ~19 TB/s vs 40–80 GB of HBM at ~1.5–2 TB/s. FlashAttention
  • FA-1: 3× faster GPT-2 training at 1k tokens; 10–20× attention memory saving at 2k–4k. FlashAttention
  • FA-2: ~2× FA-1, reaching 50–73% of A100 peak FLOPs/s. FlashAttention
  • FA-3 on H100: 1.5–2× FA-2, up to ~740 TFLOPs/s in FP16 (~75% utilization), ~1.2 PFLOPs/s in FP8. FlashAttention
  • Bytes per parameter: BF16 2, FP8/INT8 1, INT4 0.5. A 70B model is ~140 / ~70 / ~35 GB, plus ~5–10% for scales. Quantization (INT8, INT4, FP8)
  • Rule of thumb: batch-1 decode ceiling ≈ HBM bandwidth ÷ weight bytes. 8B on an H100 (3.35 TB/s): ~200 tok/s in BF16, roughly 3× that in INT4. Quantization (INT8, INT4, FP8)
  • GPTQ quantized 175B-parameter models to 3–4 bits in ~4 GPU hours. Quantization (INT8, INT4, FP8)
  • QLoRA's double quantization saves ~0.37 bits per parameter (~3 GB on a 65B model). Quantization (INT8, INT4, FP8)
  • Leviathan et al.: 2–3× on T5-XXL with identical outputs; Chen et al.: 2–2.5× on Chinchilla 70B. Speculative decoding
  • Expected tokens per target pass = (1 − α^(k+1)) / (1 − α); acceptance α = 0.8, k = 4 → ~3.4. Speculative decoding
  • Medusa-2: 2.3–3.6×; EAGLE: 2.7–3.5× on LLaMA2-Chat 70B (papers). Speculative decoding
  • DeepSeek-V3's multi-token prediction: 85–90% acceptance of the second token, ~1.8× tokens/s. Speculative decoding
  • Weights ≈ params × bytes: 70B in BF16 ≈ 140 GB → at least 2× 80 GB GPUs, usually 4 for KV-cache headroom. Self-hosted serving stack
  • vLLM pre-allocates 90% of GPU memory by default (--gpu-memory-utilization 0.9), mostly for KV cache. Self-hosted serving stack
  • SGLang paper (2023): up to 6.4× higher throughput than prior systems on structured, prefix-sharing workloads. Self-hosted serving stack
  • H100 NVLink ~900 GB/s vs ~50 GB/s for a 400 Gb/s NIC: why tensor parallelism stays inside a node. Self-hosted serving stack
  • Cold-start floor: 140 GB at ~1 GB/s is ~2.3 minutes for the bytes alone, before node provisioning and warm-up. Self-hosted serving stack
  • A month is ~730 hours: a rented GPU bills all of them, busy or idle. API vs self-hosting
  • Self-host cost per token = GPU $/hour ÷ tokens per hour actually served: halve utilization, double the unit cost. API vs self-hosting
  • Batch APIs cut prices ~50% for results within 24 h (OpenAI, Anthropic, Gemini). API vs self-hosting
  • Worked example (assumptions in the code): ~$0.62/M at 60% utilization vs $0.80/M via API → crossover ~60–90B tokens/month once ops is counted. API vs self-hosting
  • ~4 characters ≈ 1 token ≈ 0.75 English words (OpenAI rule of thumb). Token economics & cost estimation
  • Output ~4–8× input on 2025 list prices per 1M: GPT-4.1 $2/$8, Claude Sonnet 4 $3/$15, GPT-5 $1.25/$10. Token economics & cost estimation
  • Cached input reads: ~0.1× base on Anthropic; 50–90% off on OpenAI depending on the model. Token economics & cost estimation
  • Batch APIs: ~50% off for results within 24 h. Token economics & cost estimation
  • History: if each turn adds k tokens, N turns send ~k·N²/2 input tokens in total. Token economics & cost estimation
  • RouteLLM (LMSYS, 2024): over 2× cost reduction at similar quality; ~85% cheaper than GPT-4-only on MT Bench at 95% of its quality. Model routing & cascades
  • FrugalGPT (2023): cascades matched GPT-4 quality at up to 98% lower cost on its benchmarks. Model routing & cascades
  • Cascade cost = small + P(escalate) × large: a 20× cheaper model with 25% escalation costs ~30% of all-large. Model routing & cascades
  • Price gap to exploit: GPT-4.1 $2 vs GPT-4.1-nano $0.10 per 1M input tokens (20×, 2025 list). Model routing & cascades
  • Typical cosine threshold ~0.90–0.95 on normalized embeddings; tune it on labeled query pairs (rule of thumb). Semantic caching
  • A hit = one embedding call + one vector lookup: tens of ms vs seconds for a generation. Semantic caching
  • text-embedding-3-small: $0.02 per 1M tokens (OpenAI list price, unchanged as of Nov 2026), so lookups are close to free. Semantic caching
  • Savings ≈ hit rate × LLM cost: a 20% hit rate saves ~20%, minus embedding and store costs. Semantic caching
  • Provider limits are two-dimensional: requests/min and tokens/min (Anthropic splits input and output TPM). Your quotas must be too. LLM gateway
  • Retry 429, 500/502/503, 529 (Anthropic overloaded) and timeouts with backoff + jitter; never retry 400/401/403. LLM gateway
  • Rule of thumb: a gateway should add single-digit ms per call, negligible next to hundreds of ms of TTFT. LLM gateway
  • LiteLLM exposes 100+ providers behind the OpenAI API format. LLM gateway
  • Nielsen's response-time limits: ~0.1 s feels instant, ~1 s keeps the flow of thought, ~10 s loses attention. Aim for TTFT under ~1 s. Streaming responses (SSE)
  • Rule of thumb: hosted models decode ~50–100 output tokens/s per stream, so a 500-token answer is 5–10 s unstreamed. Streaming responses (SSE)
  • Browsers allow ~6 HTTP/1.1 connections per origin; open SSE streams count against it, so serve them over HTTP/2. Streaming responses (SSE)
  • AWS ALB's default idle timeout is 60 s: send heartbeat comments during long pauses such as reasoning. Streaming responses (SSE)
  • OpenAI Batch and Anthropic Message Batches: ~50% off standard prices, results within 24 h, often much sooner. Batch inference
  • Per batch: OpenAI up to 50,000 requests and 200 MB; Anthropic up to 100,000 requests or 256 MB. Batch inference
  • Anthropic keeps batch results for 29 days, and its batch discount stacks with prompt caching. Batch inference
  • Cost math: items × (input tokens × input price + output tokens × output price) × 0.5. Output tokens usually cost ~4–8× input. Batch inference
  • OTel GenAI core attributes: gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens. Capturing message content is opt-in. LLM observability & tracing
  • Rule of thumb for sampling: metrics on 100% of requests; full payloads on all errors and negative feedback plus ~1–10% of the rest. LLM observability & tracing
  • Rule of thumb: ~4 characters per English token, so payload storage is ~4 bytes × tokens per span. LLM observability & tracing
  • Four dashboards: cost (per team, feature, model), latency (TTFT and total at p50/p95/p99), errors (429, 5xx, timeouts, refusals), quality (feedback, online eval scores). LLM observability & tracing

Security, Safety & Governance

  • Term coined Sept 2022 (Simon Willison); indirect injection formalized Feb 2023 (Greshake et al.). Prompt injection (direct & indirect)
  • #1 in the OWASP Top 10 for LLM apps in every edition so far: 2023, 2025 and 2026 (LLM01). Prompt injection (direct & indirect)
  • Rule of thumb: a 99%-accurate detector still lets 1 in 100 attempts through, and attackers retry. In security, 99% is a failing grade. Prompt injection (direct & indirect)
  • AgentDojo (2024), a standard benchmark for defenses: 97 agent tasks, 629 injection test cases. Prompt injection (direct & indirect)
  • 3 legs; removing any 1 closes this exfiltration path (not the others). The lethal trifecta
  • 0 clicks: a rendered markdown image fetches its URL automatically, a classic exfiltration channel. The lethal trifecta
  • Rule of Two (Meta, Oct 2025): at most 2 of the 3 properties per session; all 3 needs human supervision. The lethal trifecta
  • EchoLeak (CVE-2025-32711, June 2025): zero-click data exfiltration from Microsoft 365 Copilot via one crafted email. The lethal trifecta
  • Constitutional Classifiers (Anthropic, Feb 2025): automated jailbreak success 86% → 4.4%, with +0.38% refusals and 23.7% compute overhead. Jailbreaks
  • Their 2024 bug bounty: 183 red-teamers, 3,000+ hours, no universal jailbreak; the Feb 2025 public demo (~3,700 hours) produced one. Jailbreaks
  • Many-shot (Anthropic, 2024): success scales with shot count; one prompt-classification mitigation cut attack success from 61% to 2%. Jailbreaks
  • Best-of-N (2024): with 10,000 randomly augmented tries, ~89% success on GPT-4o and ~78% on Claude 3.5 Sonnet. Retries are the attack. Jailbreaks
  • Next-generation Constitutional Classifiers (Anthropic, Jan 2026): ~1% compute overhead, 0.05% refusal rate, 1,700+ red-team hours without a universal jailbreak. Jailbreaks
  • 10 risks, LLM01–LLM10; current edition is 2026 (published Aug 2026); earlier editions 2025 (Nov 2024) and 2023. OWASP Top 10 for LLM apps
  • Prompt Injection is #1 in all three editions; Sensitive Information Disclosure has been #2 since 2025. OWASP Top 10 for LLM apps
  • 2026: 8 of 10 entries changed rank; Excessive Agency rose from #6 to #3, Improper Output Handling fell from #5 to #10. OWASP Top 10 for LLM apps
  • 1 rename in 2026: System Prompt Leakage (LLM07:2025) became Hidden Context Exposure (LLM08:2026). OWASP Top 10 for LLM apps
  • OWASP Top 10 for Agentic Applications: Dec 2025, ASI01–ASI10, with ASI01 Agent Goal Hijack. OWASP Top 10 for LLM apps
  • Llama Guard 3: 8B with 14 MLCommons hazard categories (S1–S14), 1B with 13 (no S14 code-interpreter abuse); Llama Guard 4 (2025): 12B, multimodal, 14 categories. Guardrails: input, output, action
  • Meta's Prompt Guard 2 injection/jailbreak classifier ships at 86M and 22M parameters: cheap enough to run on every request. Guardrails: input, output, action
  • Rule of thumb: regex <1 ms, small classifier ~10–50 ms, LLM-based guard ~0.2–1 s or more if run in series. Guardrails: input, output, action
  • OpenAI's moderation endpoint is free to use. Guardrails: input, output, action
  • GDPR fines: up to €20M or 4% of global annual turnover, whichever is higher. PII & data privacy
  • GDPR: answer an erasure or access request within 1 month; notify the authority of a breach within 72 h. PII & data privacy
  • OpenAI API data isn't used for training by default (since March 2023); abuse-monitoring logs are kept up to 30 days unless you have ZDR. PII & data privacy
  • vec2text recovered 92% of 32-token inputs exactly from their embeddings: treat embeddings as personal data. PII & data privacy
  • ChatGPT, March 2023: a redis-py bug exposed payment details of ~1.2% of Plus subscribers active in a 9-hour window. Multi-tenant isolation in AI apps
  • OpenAI documents that prompt caches are not shared between organizations. Multi-tenant isolation in AI apps
  • Carlini et al. (2021) extracted hundreds of verbatim training sequences from GPT-2, including names, phone numbers and emails. Multi-tenant isolation in AI apps
  • Anthropic released ~39k human red-team attacks (Ganguli et al., 2022), a public seed set for your own suite. Red teaming AI systems
  • PAIR, an attacker LLM refining prompts against a target model, often finds a jailbreak in under 20 queries. Red teaming AI systems
  • Rule of thumb: report attack success rate (ASR) per category per release; any open critical finding blocks launch. Red teaming AI systems
  • Rule of thumb: re-run the automated suite on every model, prompt or tool change; upgrades can reopen fixed holes. Red teaming AI systems
  • ~250 poisoned documents were enough to backdoor models from 600M to 13B parameters, regardless of size (Anthropic, UK AISI, Turing Institute, Oct 2025). Model & data supply chain
  • Poisoning 0.01% of LAION-400M via expired domains would have cost ~$60 (Carlini et al., 2023). Model & data supply chain
  • A 2024 study found ~20% of packages suggested in LLM-generated code did not exist: names an attacker can register. Model & data supply chain
  • PyTorch 2.6 (Jan 2025) made torch.load(weights_only=True) the default. Model & data supply chain
  • OWASP LLM Top 10 (2026): LLM04 Supply Chain, LLM05 Data and Model Poisoning (LLM03 and LLM04 in the 2025 edition). Model & data supply chain
  • InstructGPT (2022): outputs of the 1.3B RLHF model were preferred over those of the 175B GPT-3. Alignment & Constitutional AI
  • Alignment faking (2024): Claude 3 Opus complied with harmful requests ~14% of the time when it believed the chat would be used for training, almost never otherwise. Alignment & Constitutional AI
  • OpenAI rolled back a sycophantic GPT-4o update in April 2025, days after release. Alignment & Constitutional AI
  • Four-fifths rule (US EEOC guidelines, 1978): a group's selection rate below 80% of the top group's signals adverse impact. Responsible AI: bias, fairness, transparency
  • Gender Shades (2018): commercial gender classifiers erred up to 34.7% on darker-skinned women vs 0.8% on lighter-skinned men. Responsible AI: bias, fairness, transparency
  • Model cards: Mitchell et al., 2019. Datasheets for datasets: Gebru et al., 2018. Responsible AI: bias, fairness, transparency
  • In force 1 Aug 2024; bans and AI literacy from 2 Feb 2025; GPAI model obligations from 2 Aug 2025; Art. 50 transparency from 2 Aug 2026. EU AI Act
  • Digital Omnibus (Reg. (EU) 2026/1744, in force 27 Jul 2026): Annex III high-risk from 2 Dec 2027, Annex I products from 2 Aug 2028; new NCII/CSAM bans from 2 Dec 2026. EU AI Act
  • Fines up to €35M or 7% of worldwide annual turnover for banned practices; up to €15M or 3% for most other breaches. EU AI Act
  • GPAI models trained with more than 10²⁵ FLOPs are presumed to carry systemic risk. EU AI Act
  • High-risk system logs: keep them at least 6 months, longer if other law requires. EU AI Act
  • NIST AI RMF 1.0: released 26 Jan 2023; 4 functions, 7 trustworthiness characteristics. NIST AI RMF & ISO/IEC 42001
  • NIST AI 600-1 Generative AI Profile (July 2024): 12 GenAI risk categories. NIST AI RMF & ISO/IEC 42001
  • ISO/IEC 42001 (Dec 2023): Annex A lists 38 reference controls under 9 objectives (A.2–A.10). NIST AI RMF & ISO/IEC 42001
  • ISO certification runs a 3-year cycle with annual surveillance audits. NIST AI RMF & ISO/IEC 42001
  • AI RMF 1.0 is still the current version (Nov 2026); a revision ordered by the July 2025 US AI Action Plan has no public draft yet. NIST AI RMF & ISO/IEC 42001

AI Architecture

AI System Design Cases

ML Foundations

MLOps & ML Systems

  • Google's maturity levels: 0 = manual, 1 = automated continuous training, 2 = CI/CD of the pipeline itself. The ML lifecycle
  • Google's level-0 description: a new model version is deployed only a couple of times per year. The ML lifecycle
  • Sculley et al. (NeurIPS 2015): ML code is only a small fraction of a real-world ML system. The ML lifecycle
  • Rules of ML #1: don't be afraid to launch a product without machine learning. The ML lifecycle
  • Output tokens list at ~4–5× input (Nov 2026 list prices): $2 vs $10 per 1M on Claude Sonnet 5.5, $2.50 vs $10 on GPT-4o. LLMOps vs MLOps
  • Batch APIs (OpenAI, Anthropic) cut price ~50% for jobs that can wait up to 24 h. LLMOps vs MLOps
  • At n = 100 cases and a 50% pass rate, the 95% CI is about ±10 points: small eval sets can't see small regressions. LLMOps vs MLOps
  • Rule of thumb: start a golden set with ~50–200 cases sampled from real traffic, then grow it from failures. LLMOps vs MLOps
  • Rule of thumb: online feature reads should be single-digit ms at p99, since a whole fraud or ranking call often gets ~50–100 ms. Feature stores
  • Point-in-time rule: use the latest value with feature_ts ≤ label_ts, and only if it is within the feature's TTL. Feature stores
  • Uber's Michelangelo (2017) popularized the offline/online feature store split. Feature stores
  • Google's Rules of ML #29: log the features used at serving and train on them; #32: reuse code between training and serving. Training–serving skew
  • Rule of thumb: in a parity check, more than ~1% of rows disagreeing on a feature means a code-path bug, not noise. Training–serving skew
  • TFDV flags categorical skew by L-infinity distance between training and serving distributions (its guide uses a 0.01 threshold); Jensen-Shannon divergence also covers numeric features. Training–serving skew
  • PSI rule of thumb: <0.1 stable, 0.1–0.25 moderate shift, >0.25 significant shift worth acting on. Data drift & concept drift
  • PSI is usually computed on 10 reference bins (deciles); empty bins need a small floor to avoid log(0). Data drift & concept drift
  • Two-sample KS at n = m = 100k: D above ~0.006 is already significant at p < 0.05. Data drift & concept drift
  • JS divergence is bounded in [0, 1] with log base 2; KL is asymmetric and infinite on empty bins. Data drift & concept drift
  • Domain-classifier check: AUC ≈ 0.5 means reference and live data are indistinguishable. Data drift & concept drift
  • MLflow 2.9 (Dec 2023) deprecated the fixed Staging/Production stages in favor of free-form aliases (e.g. @champion, added in 2.8) plus tags. Model registry & versioning
  • Rule of thumb: keep the last 2–3 production versions loadable so rollback is instant. Model registry & versioning
  • Rule of thumb: an LLM release pins ~5 things together: model snapshot, prompt, retrieval index, tool schemas, guardrail config. Model registry & versioning
  • With 100 eval examples at ~80% accuracy, the 95% confidence interval is about ±8 points: a 2-point 'win' is noise. Experiment tracking & reproducibility
  • Rule of thumb: compare model changes across 3–5 seeds and report mean ± std. Experiment tracking & reproducibility
  • A reproducible run pins 4 things: code commit, data snapshot, environment digest, config with seeds. Experiment tracking & reproducibility
  • PSI rule of thumb: < 0.1 stable, 0.1–0.25 moderate shift, > 0.25 significant shift. Monitoring models in production
  • Rule of thumb: run LLM-as-judge on ~1–5% of production traffic, more right after a release. Monitoring models in production
  • Google SRE: page when a 30-day SLO burns 2% of its error budget in 1 hour (14.4× burn rate). Monitoring models in production
  • OpenAI Batch API and Anthropic Message Batches: 50% cheaper than synchronous calls, results within 24 h. Batch vs real-time inference
  • Rule of thumb: an interactive page has ~100–200 ms end to end; the model gets only a slice of it. Batch vs real-time inference
  • Kafka's default retention is 7 days (log.retention.hours=168): your window to replay events into a backfill. Batch vs real-time inference
  • Covington et al. (YouTube, 2016): candidate generation narrows millions of videos to hundreds; ranking scores those to show dozens. Recommendation systems
  • Netflix (Gomez-Uribe & Hunt, 2015): recommendations influence ~80% of hours streamed; the other ~20% comes from search. Recommendation systems
  • Netflix Prize: $1M for a 10% RMSE gain (awarded 2009); the winning ensemble was never fully deployed, as the engineering cost outweighed the gain (Netflix Tech Blog, 2012). Recommendation systems
  • Delta Lake defaults: VACUUM keeps 7 days of old files, the transaction log 30 days; older time travel needs an explicit snapshot. Data platform for AI
  • Target file sizes: Iceberg defaults to 512 MB, open-source Delta OPTIMIZE to 1 GB (Databricks autotunes by table size); thousands of tiny files wreck scan speed. Data platform for AI
  • Origins worth knowing: Delta Lake came from Databricks, Iceberg from Netflix, Hudi from Uber. Data platform for AI

Distributed Systems

System Design Classics

Coding Interview Patterns

Staff/Principal Leadership