English · 中文
Research date: 2026-05-01 · Revision: 2026-05-01 (v3: each chapter deepened with formulas, code, production configs, and a GitHub reading path)
A technical survey of how to run an LLM in production, organized from lower engineering abstractions to higher ones. Each layer is its own discipline. A production system needs all four.
prompt-engineering.en.md → how to write one LLM call
↓
context-engineering.en.md → what the model can see at the moment it runs
↓
agent-engineering.en.md → how an LLM finishes a multi-step task on its own (goal → loop → memory)
↓
harness-engineering.en.md → what environment the agent runs in, and how a mistake is prevented from happening again
| File | Contents | Length |
|---|---|---|
README.en.md |
This file: contents and how to read | short |
prompt-engineering.en.md |
Transformer / attention / training stack (pretraining / SFT / DPO / GRPO / RLAIF / RLVR / LoRA / QLoRA / distillation) / decoding / CoT / ReAct / ToT / Self-Refine / automatic prompts / evaluation and failure modes | ~10k Chinese characters in the source |
context-engineering.en.md |
Definition and origin / physics of long context / Lost-in-the-Middle / RULER / full-stack RAG choices (parse → chunk → embed → vector store → retrieve → rerank → rewrite → GraphRAG / Self-RAG / CRAG / Agentic RAG / multimodal) / four memory systems compared / context-management tactics / MCP / A2A | ~13k Chinese characters in the source |
agent-engineering.en.md |
Definition and coordinates / how the pattern evolved / four-layer architecture / type taxonomy / matrix of 10 frameworks / 5 multi-agent collaboration modes / benchmarks (SWE-bench / GAIA / WebArena / OSWorld 2026 ranks) / product cases (Claude Code / Cursor / Devin / Manus / Computer Use) / failure modes and real incidents (Amazon Kiro / Replit / Loop of Death) / permission model | ~12k Chinese characters in the source |
harness-engineering.en.md |
Origin (Hashimoto named it in 2026-02) / two laws (strong constraints + self-healing loop) / four pillars (context architecture / agent specialization / persistent memory / structured execution) / §3.3.1–§3.3.3 direct implementations of strong constraints (MCP / sandbox / guardrails) / production-stack diagram / maturity L0–L4 / synthesis / three scenario checklists / limits / full references / methodology | ~13k Chinese characters in the source |
overview.en.md |
v1 merged edition (the draft before the split; kept as a reference; the file was once named article.md) |
~30k Chinese characters in the source |
run_manifest.json |
Research metadata: query / mode / search paths / claim-verification table. Not translated | short |
sources.jsonl |
Citation registry (45 entries). Not translated | short |
Straight through: 01 → 02 → 03 → 04 (abstractions from low to high; the four layers stack).
By role:
| Version | Date | Change |
|---|---|---|
| v1 | 2026-05-01 17:30 | Original merged draft of 3 parts (article.md), about 30k Chinese characters |
| v2 | 2026-05-01 19:00 | Split into 4 documents, plus a new agent-engineering chapter (real incidents, benchmarks, permissions), about 48k Chinese characters |
| v3 | 2026-05-01, later | Each chapter deepened after feedback that the series was not systematic enough: formulas, code, production configs, GitHub tutorials, about 75k Chinese characters |
| Chapter | Added in v3 |
|---|---|
| 01 Prompt engineering | Full attention math (softmax(QK^T/√d_k)V + multi-head formula + PyTorch) / library analogy for Q-K-V / full transformer-block diagram (Pre-Norm + RMSNorm + RoPE + SwiGLU + GQA + MoE) / RLHF objective (4-model table) / full DPO loss derivation / GRPO + RLVR flow and code / DPO variants (IPO/KTO/SimPO/CPO) / three-algorithm comparison / GitHub tutorial section (karpathy nn-zero-to-hero / build-nanogpt / Sebastian Raschka LLMs-from-scratch / HuggingFace TRL / unsloth, 13 items + a paper list) |
| 02 Context engineering | ~100-line Python skeleton of a RAG pipeline (parse → chunk → embed → hybrid retrieve → rewrite → rerank → generate) / GitHub RAG section (NirDiamant RAG_Techniques / RAGFlow / LightRAG / Awesome-RAG, 8 items) |
| 03 Agent engineering | Anthropic’s 6 composable patterns in full (Augmented LLM / Prompt Chaining / Routing / Parallelization / Orchestrator-Workers / Evaluator-Optimizer / Agents, each with a figure, a setting, and when to pick it) + a pattern decision tree / Hello World comparison for LangGraph, CrewAI, and the OpenAI Agents SDK, plus a philosophy table / ~100-line end-to-end agent (RAG + memory + 4 Loop-of-Death gates + checkpoint + observability) / GitHub agent section (microsoft AI agents for beginners / agent-framework / hello-agents / Anthropic essays / 8 frameworks, 12 items + papers) |
| 04 Harness engineering | Two laws + four pillars + direct strong-constraint implementations (MCP / sandbox / guardrails) + the §3.9 appendix of 4 related infrastructure kinds (LLM gateway / inference / observability / evaluation, explicitly marked as not the harness) + config set: LiteLLM config.yaml (routing + fallback + caching) / vLLM vs SGLang launch commands / three ways to attach Langfuse / Promptfoo promptfooconfig.yaml (CI gating) / RAGAS in Python / NeMo Guardrails Colang / E2B sandbox / minimal MCP server / pre-commit hook (strong constraint) / evaluator-optimizer (self-healing loop) / harness maturity L0–L4 / GitHub harness section (7 infrastructure categories, 30+ items) |
| Change | v1 (now overview.md, once article.md) |
v2 / v3 (4 files) |
|---|---|---|
| Chapters | 3 parts | 4 parts |
| Agent material | Scattered | Its own chapter |
| Real incidents | Not covered | Added (Amazon Kiro / Replit / Loop of Death) |
| Formulas and code | Description only | v3 has full formulas and runnable code |
| Production configs | Description only | v3 has yaml/python per component |
| GitHub resources | Very few | v3 has 50+ classified links |
| Length | ~30k Chinese characters | v2 ~48k → v3 ~75k |
The full set of 45 is in each chapter’s bibliography and in sources.jsonl.
# The public copy is this directory. The original deep-research output path lived only on the author's machine and is not in the repo.
wc -m prompt-engineering.md context-engineering.md agent-engineering.md harness-engineering.md overview.md
Concepts marked
[term]in the answers jump to the matching entry in this table and expand it. The table groups 60+ high-frequency terms under 10 topics and is collapsed by default — expand a term only when you don’t know it, and read the short explanation, so you are not buried in information.
Analyze source without actually running it, and flag potential bugs, unused variables, style violations, and suspicious usage. Common tools:
In agent engineering, lint is often used as a hard constraint in the harness — feeding lint errors back to the model to rewrite the code is much more reliable than merely saying “please follow the coding standards” in the prompt (Augment Code calls this a Constraint Harness).
Make sure types are consistent across assignments and function calls:
For an agent: after the agent finishes writing code, force a run of tsc --noEmit / mypy . / cargo check, and feed type errors back to the model to keep fixing. That is much more reliable than letting the agent “claim it checked the types” — a typical practice of harness engineering.
CI (Continuous Integration): on every commit, automatically run tests, builds, lint, type check, and other checks. CD (Continuous Deployment): after the checks pass, automatically deploy to test / staging / production.
Common tools: GitHub Actions, GitLab CI, Jenkins, CircleCI, Buildkite.
In agent engineering, CI is the most important deterministic feedback source — an LLM’s self-assessment is unreliable, but CI pass/fail is a 0/1 signal and can be used directly as ground truth. Hashimoto’s harness engineering stresses that whether a problem gets solved is strongly tied to whether the agent can verify its own work.
Run untrusted code (user uploads, LLM-generated code) in a restricted environment so it cannot damage the host. Isolation strength, from weak to strong:
An agent that runs user- or LLM-generated code must be sandboxed, with defense in depth on top: a network-egress allowlist + a read-only filesystem + time/memory quotas + no host credentials mounted.
The name comes from using canaries in coal mines to detect poison gas. A typical deploy sequence is: shadow (dual-run, do not return the result) → 1% → 5% → 25% → 50% → 100%, and each stage advances only if the core metrics show no regression.
For LLM applications, a new prompt / new model / new agent harness must go out through a canary. If any key metric (resolution rate, CSAT, refusal rate, p99 latency, cost per request) worsens past a threshold, roll back. The non-determinism of LLM applications makes canaries more important than they are for traditional software.
Hash on user_id to split traffic so a given user always lands in the same bucket (avoiding a flickering experience). What to judge:
Prompt changes, model swaps, and RAG changes in an LLM application should all go through an A/B test. Shipping on offline eval alone often fails in production (the live traffic distribution differs a lot from the gold set).
The metrics the business side watches most closely when deciding whether an agent should launch:
What agent engineering watches: put model / prompt / RAG changes into an A/B test and look at these business metrics, not only offline benchmark scores. It is very common for a change to raise the benchmark while GMV / CSAT fall.
Pause an autonomous agent at a critical node and wait for a human:
Design principle: “Humans steer. Agents execute.” (OpenAI Harness Engineering). An agent does not replace a person; it amplifies a person’s judgment — the person sets the plan, sets the constraints, and reviews the result, and the agent does the execution.
Four terms defined by Google’s SRE practice:
1 - SLO. An SLO of 99.9% means 43.2 minutes of “budget” in 30 days during which the target can be missed. Once the budget is spent, non-essential releases are frozen.How to use this for an agent application:
Rule of thumb: a stricter SLO is not automatically better — 99.99% costs 5–10× more than 99.9%, and it is likely past the threshold users can perceive. Google recommends the level that is just high enough that users don’t complain.
It expires automatically. Common uses:
A rule-of-thumb conversion: 1000 English words ≈ 1300 tokens; 1000 Chinese characters ≈ 1500–2000 tokens.
Why it matters: the context window, API billing, and inference speed are all counted in tokens. Controlling the token count = controlling cost and latency. Anthropic, OpenAI, and Google each have their own tokenizer, and a ±20% difference in token count for the same text is common.
Text → a neural network → a vector of 768 / 1024 / 1536 / 3072 floating-point numbers. Vectors for synonyms or same-topic text sit close together in that space (high cosine similarity).
Main uses:
Mainstream models in 2026: OpenAI text-embedding-3-large, Cohere v4, Voyage-3, BGE-M3 (open-source SOTA; Chinese–English bilingual, combining dense / sparse / multi-vector).
It includes the system prompt, conversation history, user input, and model output; all of them count. Mainstream models in 2026:
Note: the advertised window ≠ the effective window. The RULER benchmark shows that most models’ performance drops sharply beyond 1/4 of the window (Lost in the Middle). Engineering guidance sets the threshold for “what should go into context” at 8–32k; anything longer goes through RAG or hierarchical summarization.
The two phases have different bottlenecks, so the tuning strategies differ too — prefill is optimized with parallelism / FlashAttention, and decode is optimized with continuous batching / speculative decoding. Because the two phases have opposite characteristics, engineering also uses two kinds of scheduling optimization: PD disaggregation (Prefill/Decode Disaggregation, handling the phases on different GPU pools, as in DistServe/Mooncake) and chunked prefill (split a long prefill into chunks and interleave them with decode). See A11 for detail.
Generating token t needs the K/V of every earlier token in the attention computation. Caching them so they are not recomputed every time is the most basic optimization in LLM inference.
Memory use: 2 × num_layers × num_heads × head_dim × seq_len × batch × bytes_per_elem. On a 70B model, the KV cache for a 128k context can reach tens of GB, far more than the model weights themselves.
Further optimizations:
How GPT-style decoder-only models generate: P(x_t | x_1, ..., x_{t-1}). Every generated token runs a full forward pass (even though the KV cache can be reused), so output length directly determines latency.
By comparison: BERT is non-autoregressive (masked LM: it predicts every masked position at once), and diffusion models are also non-autoregressive (they denoise the whole span in one shot).
The cost of autoregression produced a large family of speedups: speculative decoding, parallel decoding, Medusa, EAGLE, and others.
The last decoder layer outputs a logit vector of dimension [vocab_size]; after softmax it is the probability distribution of the next token.
Places engineering can get the logits (or top-k logprobs):
Note: commercial OpenAI / Anthropic APIs return only the sampled result by default; you have to turn the logprobs option on explicitly.
P(token) ∝ exp(logit / T):
Turn it up when: Self-Consistency needs diverse paths, creative writing, brainstorming. Turn it down when: code generation, math reasoning, strict formatted output, T=0.1–0.3.
Trap: T=0 is not fully identical to deterministic — non-determinism of floating-point GPU kernels plus concurrent scheduling can still leave tiny differences for the same prompt.
Xiao et al. 2023 found that during long-sequence inference, later tokens often assign a disproportionate share of attention to the first few tokens of the sequence (even when those tokens are semantically unrelated). Those tokens become a “sink” and absorb the normalization mass that softmax is required to distribute.
Why it matters in engineering:
LayerNorm: y = (x - μ) / σ * g + b, mean and variance taken along the hidden dimension. Independent of the batch, so it naturally supports variable-length sequences and single-example inference — which is why Transformers use LayerNorm rather than BatchNorm.
RMSNorm (Zhang & Sennrich 2019): y = x / sqrt(mean(x²)+ε) * g, dropping the mean subtraction and the bias. Modern LLMs such as Llama, PaLM, and Mistral have almost all switched to RMSNorm, saving 7–64% of normalization time without hurting quality.
Pre-LN vs Post-LN: doing LN before the residual (Pre-LN) trains more stably than doing it after the residual (Post-LN), and warmup can be dropped. From GPT-2 onward, Pre-LN is nearly universal.
Su et al. 2021. Represent position m as a rotation matrix R_m applied to Q/K, so that <R_m·q, R_n·k> = f(q, k, m-n) — the attention score depends only on relative distance.
Advantages: (1) no extra parameters; (2) relative position is encoded naturally; (3) compatible with linear attention. It has become the position-encoding scheme of the great majority of modern LLMs, including Llama, Qwen, and Mistral.
The extrapolation problem: naive extrapolation from 2k to 32k collapses — the rotation angles of high-frequency components fall into regions never seen in training. Mitigations:
Naive extrapolation of RoPE collapses — the rotation angles of high-frequency components fall into regions never seen outside the training context. Two engineering schemes:
Where they are used:
Numbers from practice: YaRN is nearly lossless at a 4× context extension (2k→8k or 32k→128k); beyond 8× there is still a performance drop. Extreme long context (1M+) usually needs retraining rather than YaRN alone.
Standard multi-head attention: each of the H heads has its own Q/K/V.
The gain: the KV cache shrinks to 1/8 ~ 1/H, inference throughput rises substantially, and quality is almost unchanged. Llama-2 70B, Llama-3, Mistral, Qwen2, and others use GQA.
Replace the traditional dense FFN with N parallel expert FFNs plus a router. Each token picks the top-k experts through the router (k is usually 1–2) and only those experts are activated for the compute.
Advantage: a large parameter count with little compute. Mixtral 8x7B has 47B total parameters and only 13B activated; DeepSeek-V3 has 671B total parameters and only 37B activated. At the same inference cost, capacity far exceeds a dense model.
Challenges: (1) load balancing during training (so one or two experts are not overused); (2) memory is counted by total parameters, not activated parameters; (3) communication cost is high (expert parallelism).
Single-head attention produces one attention distribution for each pair of tokens — one “relational viewpoint”. Multiple heads (h=8/32/64/128) let the model learn several relations at once: syntactic heads attend to short-range dependencies, and semantic heads attend to coreference and long-range entities.
Why a single head with a larger dimension does not work: multi-head is a mixture of h low-rank attentions and is strictly more expressive; a single head is one high-rank attention and has fewer degrees of freedom.
A further variant: GQA / MQA drops heads on the KV side to save memory, while the Q side stays multi-head.
Dao 2022. Standard attention uses O(N²) memory (it stores an N×N attention matrix), which bottlenecks long sequences. FlashAttention loads Q/K/V in blocks into GPU SRAM for the compute and does not write out the full attention matrix. Memory drops to O(N), and it is also faster — attention is memory-bound, so reading less HBM makes it faster.
The line of work:
Kwon et al. 2023. It addresses three kinds of fragmentation in the traditional inference KV cache:
Mechanism: cut the KV cache into fixed-size blocks (for example 16 tokens), and each sequence keeps a block table (a logical→physical mapping). Memory utilization rises from ~20% to >96%; multiple samples of the same prompt share prefix blocks; together with continuous batching, throughput is 2–4× HuggingFace TGI and 24× FasterTransformer.
The de facto standard open-source inference server since 2023. Core features:
Compared with: TGI (HuggingFace), TensorRT-LLM (NVIDIA; proprietary and faster), SGLang (more thorough prefix reuse), LMDeploy (from OpenCompass).
Also called in-flight batching, proposed by Yu et al., ORCA, 2022. Compared with static batching (wait until the batch is full and then run together; when short and long requests are mixed, GPU utilization is often <30%), continuous batching:
vLLM’s numbers: throughput is 5–23× static batching. It is now the default in every modern inference engine.
Leviathan et al. 2023. The procedure:
Mathematically this guarantees the output distribution matches the original model exactly (rejection sampling).
When it pays off: (1) the draft and target distributions are similar (acceptance rate >60%); (2) the large model is memory-bandwidth bound, so parallel verification does not add latency. Acceptance rate is 70–90% for code generation and 30–50% for open-ended generation. Variants: EAGLE-2/3, Medusa, Llama 3.1 self-speculative.
The KV cache is reuse within a single request; prefix caching is reuse across requests. When many requests share a system prompt / few-shot examples / agent history, compute that KV once, cache it, and later requests hit the cache and skip prefill.
Effect: in agent / RAG / multi-turn settings, the system prompt is usually 1–4k tokens and shared by almost every request, so TTFT can drop 10–100×.
Implementations: vLLM --enable-prefix-caching, SGLang RadixAttention (a radix tree that automatically manages every historical prefix), the Anthropic prompt caching API (5-minute TTL; the cached portion is priced at 0.1×).
Driven mainly by prefill (processing every input token). One of the core metrics for billing and monitoring.
Ways to lower TTFT:
Companion metric: TPOT (time per output token, the gap between tokens, also called TBT/ITL) — determined by decode.
The other core latency metric, paired with TTFT: TTFT measures “how long until the first character appears” (determined by prefill), and TPOT measures “how fast each following character appears” (determined by decode). Perceived speed of streaming ≈ 1/TPOT (tokens/s).
Mixed-precision training: weights and gradients in BF16/FP16, optimizer state still in FP32.
At deployment, quantize weights to low-bit integers and dequantize back to floating point for inference.
INT8 / INT4 quantization usually needs a calibration set (128–512 samples); AWQ is smarter (it protects the 1% salient channels). For extreme memory budgets, use GGUF (the llama.cpp format) plus 3-bit / 2-bit quantization to run on phones.
Lin et al. 2023. The core observation: protecting only ~1% of the “important weight channels” (identified by activation magnitude) is enough to hold accuracy. Scale those channels up per channel, then quantize.
Compared with GPTQ: simpler to implement, lower perplexity on Llama-2, and now the default in vLLM / TensorRT-LLM.
Frantar 2022. Layer-wise minimization of quantization error, inspired by OBQ, with a small calibration set (128 samples). Pros: early, and the ecosystem is complete (exllama / vllm / TGI all support it). Cons: sensitive to the activation distribution; important channels can be crushed.
Deployment choices in 2026: H100/H200 → FP8; A100/3090 → AWQ INT4; phones/edge → INT4 + GGUF.
The most basic form of instruction tuning: treat (input, desired output) pairs as supervised samples and use cross-entropy loss to teach instruction following.
Data volumes from practice:
The LIMA paper: 1000 curated samples can bring a 65B base close to GPT-4 conversation quality — quality >> quantity.
Hu et al. 2021. Factor the weight update into two low-rank matrices ΔW = BA (r=8/16/64) and train only those matrices, cutting trainable parameters by 100–10000×.
Memory:
Advantages: few trainable parameters / multiple adapters can be hot-swapped / mitigates catastrophic forgetting.
Dettmers et al. 2023. Three key pieces:
QLoRA for a 65B model is about 33GB and fits on one A100-48G or two RTX 3090s. Cost: training is 30–40% slower (dequantization overhead).
Three steps: (1) SFT trains a base policy; (2) humans label (chosen, rejected) preference pairs to train a Reward Model; (3) the RM scores policy outputs, and algorithms such as PPO/RLOO/REINFORCE update the policy.
InstructGPT and ChatGPT brought RLHF into the mainstream. Three major pain points:
This produced simplifications and improvements such as DPO, GRPO, and RLVR.
Trained in step two of RLHF. Input: (prompt, response). Output: a scalar reward. The training loss is Bradley-Terry: make the RM score chosen higher than rejected on (chosen, rejected) pairs.
Common weaknesses:
Alternatives: DPO removes the RM entirely, and RLVR uses a programmatically judged reward.
Rafailov et al. 2023. It proves that under a Bradley-Terry preference model plus a KL constraint, the optimal policy has a closed form, so preference pairs (chosen, rejected) can be used directly as a supervised loss:
L_DPO = -log σ(β(log π(y_w)/π_ref(y_w) - log π(y_l)/π_ref(y_l)))
Advantages: (1) no RM / no online sampling / no critic; only the policy and a reference model; (2) uses the same training stack as SFT; (3) hyperparameters are stable.
Disadvantages: depends heavily on preference-data quality; easy to overfit surface patterns of the chosen answers; high reward-hacking risk.
The main post-training path for Llama-3 and Qwen2 is DPO or a variant (IPO, KTO, SimPO).
Schulman 2017. The actor learns the policy, the critic learns a value function to estimate advantage, and clipping limits how far the policy can move each step so it doesn’t collapse.
RLHF must load four models at once — actor / ref / critic / reward — so memory is ≥4× a single model. Hyperparameters are sensitive (KL coefficient, clip ratio, advantage normalization), and training is unstable.
This produced simplifications such as DPO (drop RL), GRPO (drop the critic), and RLOO (use mean reward as the baseline).
Proposed in DeepSeek-Math 2024 and validated by R1. The core change: drop the critic (the value network). Sample G responses for the same prompt (typically G=64), normalize advantage by the within-group mean and standard deviation of the reward: A_i = (r_i - mean(r)) / std(r), then apply a PPO-like clipped objective plus KL regularization.
Effects:
On tasks that can be checked automatically — math, code, formal logic — use a program as the reward: answer match, unit tests passing, a theorem prover verifying.
Advantages:
DeepSeek-R1 and DAPO (ByteDance’s open-source SOTA) are both in this family. Limitation: it applies only to verifiable tasks; open-ended dialogue still needs RLHF / DPO.
Mechanism: parameters are pulled by the new task’s loss, and directions that encoded general knowledge get overwritten.
A mitigation mix (recommended in production):
Advanced: EWC (Fisher-information-weighted L2 regularization), model souping (average the fine-tuned weights with the original model), and extending MoE routing.
Wei et al. 2022. The simplest form: “Let’s think step by step” (Kojima 2022 zero-shot CoT).
Why it works: (1) more effective compute (more forward steps); (2) it turns “System 1” intuitive answers into “System 2” step-by-step reasoning; (3) it exposes faulty reasoning so self-consistency voting can correct it.
It is an emergent ability and is almost useless on models under 10B. Long CoT (trained with RL in R1 / o1, including backtracking and self-verification, thousands of tokens long) is the new paradigm of 2025.
Yao et al. 2023. CoT is a single linear chain and cannot go back once it is wrong. ToT generates several candidate thoughts at each step, the LLM self-evaluates state value (promising / sure / impossible), and BFS/DFS expansion can backtrack and prune.
On Game of 24, GPT-4 CoT scores 4% vs ToT 74%. Cost: LLM calls rise from 1 to 50–200.
Fits: solution spaces that need explicit search (puzzles, planning, theorem proving) where intermediate states can be scored. Does not fit: chitchat, summarization, translation.
Yao et al. 2022. The structure is a Thought → Action → Observation loop: the model first writes “Thought: I need to look up X”, then outputs “Action: search[X]”, the tool result is fed back into the prompt as “Observation: …”, and the next Thought follows.
Three effects:
It is the conceptual prototype of modern agent frameworks (Claude tool use, OpenAI function calling, LangChain, AutoGPT).
Shinn et al. 2023. After a task fails (an external verifier gives a binary reward), the agent uses an LLM to summarize the cause as a natural-language lesson, stores it in episodic memory, and adds that lesson to the prompt on the next task to change behavior.
vs Self-Refine:
On HumanEval, GPT-4 with Reflexion scores 91%, above the GPT-4 baseline of 80%.
Madaan et al. 2023. Loop N rounds inside one trajectory, with no external reward and no cross-task memory. Average gain of 20% across 7 tasks.
Trap: a weak model’s self-critique is inaccurate and revisions can get worse. Production often combines Self-Refine (within an episode) with Reflexion (across episodes).
Wang et al. 2022. With temperature>0, sample N CoT paths and vote on the final answer. On GSM8K this is about 17 percentage points above greedy CoT (PaLM 55%→74%).
Pays off when: (1) the answer space is discrete (numbers, multiple choice); (2) the model’s error rate is <50%; (3) reasoning paths are diverse (temperature 0.7–1.0). Cost: N× (typically N=5–40). It does not apply to open-ended generation.
When to use few-shot: (1) the task format is novel or the output structure is complex (a JSON schema, a specific markdown layout); (2) a classification task has many labels.
When to use zero-shot: modern models are already saturated on general tasks (summarization, translation, QA), and adding examples can introduce bias.
Traps: example order matters a lot (recency bias); accidental regularities get learned; too many examples run into Lost in the Middle. Keep it to ≤8.
The standard pipeline = Ingestion + Retrieval + Generation:
Every stage has a bottleneck: chunk size, embedding choice, insufficient recall, context order, and the model not staying faithful to the context. Production RAG ≠ “embedding + a vector store + an LLM” — it is an engineering system.
Strategies:
Okapi BM25. Relevance of a document to a query is Σ IDF(qi) · f(qi,d) · (k+1) / (f + k·(1-b+b·|d|/avgdl)). Strengths: exact term hits, high weight on rare terms, proper nouns, numbers. Weakness: synonyms don’t match (“医生” vs “doctor”).
It complements dense embeddings — hybrid search fuses the two, and recall is 5–15 percentage points above dense alone.
Dense embeddings are good at semantic similarity; BM25 is good at exact term match; the two complement each other.
Fusion methods:
score(d) = Σ 1/(k + rank_i(d)), k=60. The production default; the two score streams do not need to be normalizedα·dense + (1-α)·bm25. You have to tune α and normalize the scoresAnthropic’s Contextual Retrieval experiment: embedding alone → + contextual embedding → + BM25 → + rerank, with failure rates 5.7% → 4.0% → 3.7% → 1.9%.
Bi-encoder (embedding): encode the query and the doc separately, then compare by cosine. Fast, but there is no interaction. Cross-encoder (reranker): concatenate query + doc and feed them to a transformer; self-attention at every layer lets them interact. Relevance modeling is 20–40% stronger (NDCG@10), and it is 100× slower.
The production standard: bi-encoder recalls top-100 → cross-encoder reranks to top-10 → feed the LLM.
Mainstream: Cohere Rerank v3/v4, BGE-reranker-v2-m3 (open-source SOTA for Chinese and English), Jina Reranker v2, Mixedbread.
Trap: if the relevant document is not in the recalled top-100, reranking cannot save it — a reranker improves what was already recalled and cannot stand in for recall.
A 2026 comparison of mainstream embedding models:
Selection framework:
Key traps:
Mainstream:
ANN algorithms: HNSW (the most common), IVF, ScaNN (Google). Index time vs retrieval accuracy vs memory is a trade-off.
Naive RAG struggles with cross-document, cross-entity reasoning, unstable recall quality, and multi-hop queries. Four common advanced schemes:
Practical choice:
Es et al. 2023. The four metrics:
Production thresholds: all four ≥0.7 counts as passing; if Faithfulness < 0.7, fix that first; if Context Recall < 0.7, tune the retriever.
Named by Mitchell Hashimoto in 2026: “anytime you find an agent makes a mistake, take the time to engineer a solution such that the agent never makes that mistake again.”
This is not model fine-tuning. It is an engineered environment that makes it physically impossible for the model to fail in the same way again.
Two laws:
OpenAI’s formula: Agent = Model + Harness; “Humans steer. Agents execute.”
A comparison of mainstream frameworks, 2024–2026:
Practice: prototype by calling the SDK directly; consider LangGraph once workflow patterns (routing / parallelization / orchestrator-workers) have settled; consider LlamaIndex for pure RAG; don’t start with the LangChain “full suite”.
Released in 2024-11, and moved to an independent Steering Committee in 2025-Q4 (Anthropic / Block / OpenAI / Microsoft). Three core primitives:
It solves the N×M problem of “writing a new adapter for every new tool”. The single fastest-growing skill in 2026, 97M+ monthly downloads, and already an explicit requirement on the Anthropic Applied AI Engineer JD.
The model outputs {"name": "search", "arguments": {"query": "..."}} JSON; the runtime parses it, actually runs the function, and feeds the result back to the model. Anthropic’s Tool Use API and OpenAI function calling are the same idea.
Design principles (Anthropic’s measurements: “agent performance is proportional to how clear the tool descriptions are”):
Anthropic released Computer Use in 2024-Q4. The loop: screenshot → the LLM looks at the image and reasons → it outputs mouse and keyboard actions (click X,Y / type text / scroll) → the system executes them → screenshot again.
Browser Use (an open-source framework) is similar but limited to the browser, based on Playwright plus DOM augmentation (overlay numbered labels on clickable elements in the screenshot).
Useful for: automating sites with no API, automating desktop software, end-to-end e2e tests. Limits: slow, expensive, weak on security, and poor support for canvas-rendered apps. Production advice: if an API exists, use the API.
The main agent hands “read 30 files and research them” to a sub-agent. The sub-agent has its own context window and returns only the final summary to the main agent — the main context is not polluted by intermediate artifacts.
Claude Code’s Task tool, OpenAI Swarm, CrewAI, and others support this. It is one of the key ways to prevent a Loop of Death and a context explosion.
The agent reads it automatically when it enters the project. It usually contains:
Hashimoto’s view: each line of AGENTS.md ≈ one mistake sealed off. It is the implicit-prompt form of harness engineering.
The permission model Claude Code uses. Bash commands are authorized at verb + path granularity:
git status allowgit push --force deny (destructive)rm -rf pops a user confirmationcat ~/.ssh/* deny (sensitive path)The matching security principle: if any one layer fails, the others still catch it. Combine it with a sandbox, a network-egress allowlist, and a read-only filesystem for defense in depth.
A core design from Anthropic’s Effective Harnesses: a long-running agent will inevitably blow the context window, and LLM context alone cannot remember “which step I am on”.
The fix:
The next session runs the 5-step startup protocol and resumes from the breakpoint. Core insight: the context window is “working memory”; the filesystem is “long-term memory”.
Common patterns:
Defense in depth:
Example: a user jokes “I’m a billionaire”, it is stored in semantic memory, and the agent reasons from that assumption from then on.
Defenses:
“Full-trace plus evaluation” tools for LLM apps and agents. Mainstream in 2026:
Capabilities to line up:
How to choose: prefer Langfuse if you self-host; LangSmith for heavy LangChain users; Phoenix for trace monitoring alone; Patronus for safety / real-time blocking.
Grouped by the capability being measured:
In practice: from a 2026 point of view, no single benchmark is trustworthy anymore — you need three layers: cross-checking several benchmarks, your own gold set, and blind human votes on Arena. See E11 and H3.
Eval for an LLM or agent application is not a single action; it is a system. Common layers:
How the eval tool stack splits:
Eval types by how they score:
Rules of thumb: (1) changing a prompt with no eval is changing it blind; (2) the eval model must be ≥ the model being evaluated (the judge principle); (3) the gold set must be versioned and private; (4) every bad case must be regressed into the gold set — the harness-engineering closed loop.
Model “evaluation” as an LLM task: the judge model reads (prompt, response) and outputs a 0–1 score / pass/fail / which side wins pairwise. It parallelizes at large scale, is cheap, and can be automated in CI.
Three major biases:
The judge principle: the judge model’s capability should be ≥ the model being evaluated, or it cannot tell what is good about a stronger model’s answer. The production standard is three layers: your own gold set + an LLM judge + human calibration.
The Liu et al. 2023 experiment: put the gold passage at the start or the end of the prompt and accuracy is high; put it in the middle and accuracy falls in a U-shape. With 10+ documents, the middle position can score below a no-context baseline.
Engineering mitigations:
It is #1 on the OWASP LLM Top 10. Types:
Simon Willison’s conclusion: prompt injection has no 100% solution, and the system must be designed on the assumption that “the LLM is untrusted”. The dual-LLM pattern = a Planner (sees trusted input and decides) + an Executor (sees untrusted input but has no tool permissions).
Sources:
Debug flow: reproduce it and quantify the trigger rate → attribute the cause (RAG recall / whether the model used the context / tool calls) → fix → add a regression → production monitoring (a faithfulness scorer blocks in real time).
Key point: most hallucinations are defects in the prompt / RAG / context engineering, not “the model is sick”.
NVIDIA NeMo Guardrails defines 5 kinds:
Key point: more rails are not automatically better. Turn on 1–2 high-ROI rails per kind, or latency and cost explode.
Common techniques:
Defense: the vendor’s RLHF safety training + application-layer input/output classifiers (Llama Guard) + a cap on max context (against many-shot) + regular red-team exercises.