Skip to main content

Cheat sheet

Quick-reference entries for last-minute cramming, filterable by blueprint domain. The cross-domain judgment rules are on the Overview.

Domain 1Tiers

Workflow vs agent

Single call → one request. Workflow → several calls on a path your code decides. Agent → the model decides the next tool in a loop. Multi-agent → a manager delegates to isolated subagents.

A fixed sequence of known steps is a workflow, even when every step calls Claude. Four gates before choosing agent: complexity · value · viability · cost of error.

Domain 1Patterns

Workflow pattern names

  • Prompt chaining — step N feeds N+1, gates between.
  • Routing — classify, then dispatch to a specialised prompt/model.
  • Parallelization — sectioning (independent parts) or voting (same task N times).
  • Orchestrator–workers — the model decides the split at runtime.
  • Evaluator–optimizer — generate, critique, iterate against criteria.
Domain 1Loop

The agentic loop, exactly

Continue while stop_reason === "tool_use". Append the assistant turn verbatim. One tool_result per tool_use, matching tool_use_id, all in one user message. Failures return is_error: true, never a dropped block. Parse tool_use.input as JSON — never string-match it.

while (true) {
const r = await client.messages.create({ ...req, messages });
messages.push({ role: "assistant", content: r.content });
if (r.stop_reason !== "tool_use") break; // end_turn -> done
messages.push({ role: "user", content: await runTools(r.content) });
}
Domain 1Build

Four ways to build an agent

Manual loop (you own everything) · Tool runner (client.beta.messages.tool_runner — SDK loop over your tools, per-turn hooks) · Managed Agents (Anthropic runs the loop and hosts a per-session sandbox; persisted versioned agent, session per run) · Claude Agent SDK (Claude Code as a library, built-in tools, you host). Tool runner ≠ Agent SDK. Only Managed Agents supplies deployment.

Domain 1Context

Clear vs compact vs task budget

Context editing clears old tool results/thinking — beta context-management-2025-06-27, {"type": "clear_tool_uses_20250919"}. Compaction summarizes — beta compact-2026-01-12, compact_20260112; you must append response.content verbatim or the compaction state is lost. Task budget = advisory ceiling the model knows about (min 20,000); max_tokens = enforced ceiling it does not.

Domain 2Messages

Request essentials

Everything is POST /v1/messages. model and max_tokens required; system is a top-level parameter, not a message; first message must be user; content is a discriminated union — narrow on type. The API is stateless: full history every turn.

await client.messages.create({
model: "claude-opus-5",
max_tokens: 16000,
system: "…",
thinking: { type: "adaptive" },
output_config: { effort: "high" },
messages: [{ role: "user", content: "…" }],
});
Domain 2Stop reasons

All six stop reasons

  • end_turn — done.
  • tool_use — execute, append, iterate.
  • max_tokens — truncation, not completion.
  • stop_sequence — a custom sequence matched.
  • pause_turn — server-tool pause; send it back to resume.
  • refusal — read stop_details (type, category, explanation); null for every other stop reason.
Domain 2Batch

Message Batches API

50% cost, processed within 24 h. Key results by custom_id — they return in any order. Result types: succeeded / errored / canceled / expired. Poll processing_status until "ended". Choose batch when nobody is waiting; realtime when a human is.

const b = await client.messages.batches.create({
requests: docs.map((d) => ({ custom_id: d.id, params: { model, max_tokens, messages } })),
});
for await (const e of await client.messages.batches.results(b.id)) {
if (e.result.type === "succeeded") store(e.custom_id, e.result.message);
}
Domain 2Streaming

Streaming and timeouts

SSE over the same endpoint. Stream for long input, long output, or large max_tokens — the SDKs require it for very large values. Use finalMessage() / get_final_message() rather than hand-rolling a promise. Client defaults: timeout 10 min (seconds in Python, milliseconds in TypeScript), max_retries 2; worst case is timeout × (retries + 1).

Domain 2Multimodal

Images, PDFs, files, citations

Image: source.type = url or base64 (no newlines in the data). PDF: a document block, before the text block — 32 MB request, 600 pages (100 on 200K-context models). Files API: client.files.upload, then source: {type: "file", file_id}; block type must match the MIME type. Citations: citations: {enabled: true} on every document block — incompatible with output_config.format (400).

Domain 2Caching

Prompt caching mechanics

Prefix match, render order tools → system → messages. Max 4 breakpoints; TTL 5 min default, ttl: "1h" available; minimum cacheable prefix is model-dependent (~512–4096 tokens). Verify with usage.cache_read_input_tokens. Caches are model-scoped.

system: [
{ type: "text", text: FROZEN },
{ type: "text", text: CORPUS, cache_control: { type: "ephemeral" } },
]
Domain 2400s

Parameters that now return 400

budget_tokens · temperature / top_p / top_k · an assistant prefill as the last message · deprecated output_format (use output_config.format) · mcp_servers without a matching mcp_toolset tool · defer_loading on every tool. All are exam distractors.

Domain 2Errors

Retry taxonomy

Retry (bounded, backoff + jitter, honour retry-after): 408, 409, 429, 5xx, 529, connection errors. Fix, do not retry: 400, 401, 403, 404, 413. Chain typed exceptions most-specific-first; never one broad catch, never string-match messages. Retries must be idempotent.

Domain 2Vendors

Third-party platforms

Use the platform client, not a base_url override. Bedrock: AnthropicBedrockMantle, IDs prefixed anthropic.. Vertex: AnthropicVertex with project + region, bare IDs (dated snapshots use @), GCP ADC auth. Foundry: AnthropicFoundry. Feature availability differs per platform — fast mode, Managed Agents and some server tools are first-party only.

Domain 2Design

Where a rule belongs

  • Every request of this app → system (cached prefix).
  • Everyone in this repo → project CLAUDE.md, committed.
  • Only under a path → .claude/rules/ with a glob.
  • One recurring task → a skill or slash command.
  • When to use a capability → the tool description.
  • Must hold every time → a hook or a server-side check.
  • Operator instruction mid-conversation → a system message in messages.
Domain 2Config

Pinning and hierarchy

Pin the exact model ID (no date suffix) in config, store it with every output, treat a bump as a change with evals and a canary. Settings precedence: enterprise managed → project .claude/settings.json → local settings.local.json (gitignored) → user ~/.claude/settings.json. Teammate not getting conventions? They are in ~/.claude/CLAUDE.md — move to project level.

Domain 3Components

Claude Code component map

  • CLAUDE.md + .claude/rules/ — memory and rules; always / path-scoped.
  • .claude/skills/<name>/SKILL.md — procedure, on demand, can restrict tools and fork context.
  • .claude/commands/*.md — slash commands (project) vs ~/.claude/commands/ (user).
  • .claude/agents/*.md — subagents with their own prompt and tools.
  • .claude/settings.json — permissions, env, hooks, model.
  • .mcp.json — project MCP servers.
Domain 3Modes

Sessions and modes

Clear between unrelated tasks; compact to keep the thread; resume/continue to reattach. Plan mode for multi-file or ambiguous work. Auto mode runs autonomously under pre-approved permissions. Headless (claude -p) for CI — allow only the tools the job needs. Streaming mode emits JSON lines. /init drafts CLAUDE.md; edit it down, since it loads every session.

Domain 4Isolation

Integration layer vs model output

Replay the exact request outside the app — same model, system, messages, tools. Reproduces → prompt/model. Does not → your integration layer. Re-run the same input several times: consistent failure = prompt/schema/description; intermittent = sampling, ordering, or a race.

Domain 4Traces

Log this or you cannot debug

Model ID · prompt version · effort · beta headers · request ID · stop_reason (+ stop_details) · full usage · every tool_use name, parsed input and result (or is_error) · validation outcome · per-turn latency. Read a trace by finding the first wrong turn; everything after it is noise.

Domain 5Models

IDs, context, price

ModelIDCtx$/MTok in→out
Fable 5claude-fable-51M10 → 50
Opus 5claude-opus-51M5 → 25
Opus 4.8claude-opus-4-81M5 → 25
Sonnet 5claude-sonnet-51M2 → 10
Haiku 4.5claude-haiku-4-5200K1 → 5
Domain 5Thinking

Adaptive thinking and effort

thinking: {type: "adaptive"} on all current models. Opus 5: thinking is on by default when omitted; on Opus 4.8/4.7 omitting it means no thinking; on Fable 5 it is always on and cannot be configured. Effort lives in output_config: low · medium · high (default) · xhigh · max. display: "summarized" to see reasoning — default is omitted, billing unchanged.

Domain 5Fast mode

Fast mode constraints

Research preview, Opus 5 / Opus 4.8 only, first-party only, ~2.5× output tokens/second at premium pricing. Three requirements on every request: client.beta.messages, beta fast-mode-2026-02-01, and speed: "fast" as a top-level parameter. Not with the Batch API. Switching speed invalidates the cache.

Domain 5Tokens

Tokens and counting

Count with client.messages.count_tokens — never a third-party tokenizer. The window holds system + tools + full history + tool results + documents + thinking. Output is billed several × input. Tokenizers change between model generations — re-baseline after a migration. Capabilities at runtime: client.models.retrieve(id) → max_input_tokens, max_tokens, capabilities (there is no context_window field).

Domain 5Usage

usage fields and relative cost

input_tokens 1× · cache_creation_input_tokens ~1.25× · cache_read_input_tokens ~0.1× · output_tokens several ×. Judge cost per completed task, counting retries and agent turns — not cost per request.

Domain 5Cache misses

Silent cache invalidators

  • A timestamp, UUID, request ID or user name inside the prefix.
  • Non-deterministic JSON key order in tools or serialized results.
  • A tool list that varies per request.
  • Editing top-level system mid-conversation (append a system message instead).
  • A prefix shorter than the model minimum.
  • A model or effort change mid-conversation.
Domain 5Levers

Cost lever order

Free wins first: caching → input hygiene → loop hygiene → output hygiene → batch (50%). Then tradeoffs: lower effort → task budgets → smaller model → cascade (measure single-model-lower-effort first; a cascade forfeits cross-model cache reuse).

Domain 5Migration

What breaks on a model upgrade

Removed parameters (sampling, budget_tokens, prefill) · changed defaults (thinking on/off, display, effort) · new stop reasons (refusal) · tokenizer change · prompts written for the old model now too prescriptive · JSON escaping in tool inputs · longer turns · cold cache. Sequence: evals first → fix API breaks → re-baseline tokens → re-tune effort → prune prompts → canary.

Domain 6Placement

Prompt placement

system = standing rules, role, output contract (cached). messages = this task and its data. Mid-conversation {"role": "system"} = a later operator instruction that preserves the cached prefix (model-gated; cannot be messages[0]). Tool selection guidance goes in the tool description. For a long document, put the task after the document.

Domain 6Clarity

Replace adjectives with criteria

"Be careful with dates" → "YYYY-MM-DD; if ambiguous or absent return null, never infer". "Escalate if needed" → the three enumerated conditions. Positive framing beats prohibition. A criterion you cannot evaluate is one the model cannot reliably satisfy — and an eval you cannot write.

Domain 6Few-shot

Zero-, single-, multi-shot

Zero-shot for common tasks with a constrained format. Single-shot to pin an unusual format. Multi-shot (2–5, diverse, boundary-covering, including the negative case) for fuzzy judgment. Examples are input tokens on every request → put them in the cached prefix and stop when accuracy plateaus. Few-shot fixes judgment, not compliance (hook) and not tool selection (description).

Domain 6Context

Bloat and drift

Bloat: cost climbing turn over turn — prune tool output at the handler, return fields not payloads, externalise big artifacts. Drift: a constraint from 40 turns ago ignored — durable facts belong outside the transcript (memory store, scratchpad, state object). Inconsistent output across many inputs → decompose into focused passes, not a bigger window.

Domain 6Output

Structured output + validation

output_config.format for the response; strict: true (with additionalProperties: false + required) for tool input; messages.parse() validates for you. Then validate anyway: stop_reason → syntax → schema → semantics → business rules → provenance. Retry once with the specific validation error fed back, then fall back or escalate. Make null / "not found" a first-class answer, and never gate on self-reported confidence.

Domain 7Injection

Prompt injection: the one answer

Treat retrieved content as untrusted input, keep it separate from trusted instructions, and use guardrails or hooks so injected instructions cannot trigger sensitive actions. Wrong: raising temperature · asking politely in the system prompt · a bigger, more instruction-following model (often more susceptible) · regex for "ignore previous instructions".

Domain 7Trust

Trust zones

Trusted: system prompt, tool descriptions, hook logic — authority. Semi-trusted: the authenticated user — may act within their permissions, and cannot assert their own role. Untrusted data: retrieved pages, documents, third-party and MCP tool output, uploads, filenames, other users content. Delimit, label, scope the turn to read-only tools, never concatenate into system.

Domain 7Layers

Guardrail layering

Input validation → input classification → prompt scope → tool scoping → pre-action gate → server-side authorization → output validation → output classification → monitoring. "Must never happen" → gate + server-side check. "Must be caught before storing/showing" → output validation. Fail closed, mediate every call.

Domain 7Hooks

Hook events and uses

  • PreToolUse — block/approve: thresholds, deny lists, missing prerequisites.
  • PostToolUse — normalise formats, redact, run formatter/linter.
  • UserPromptSubmit — inject context, screen input.
  • SessionStart/End — load/persist state, audit.
  • Stop / SubagentStop — verify completion, run tests.
  • PreCompact — extract facts before detail is summarised away.
{"hooks": {"PreToolUse": [
{"matcher": "Bash", "hooks": [{"type": "command", "command": ".claude/guard.sh"}]}
]}}
Domain 7Secrets

Keys, identity, least privilege

Credential resolution order: ANTHROPIC_API_KEY → ANTHROPIC_AUTH_TOKEN → CLI profile → workload identity federation → default profile. An unset key does not mean no credentials, and a stray exported key shadows the profile. Never a key in source, a prompt, logs or the browser. Authorize every tool call server-side against the caller — never a model-supplied role (confused deputy).

Domain 8Descriptions

What a tool description must contain

What it does · when to use it (trigger phrasings) · when NOT to use it, naming the sibling tool · input formats with examples · prerequisites · what it returns including error shapes · boundaries and limits. Wrong tool chosen → expand the descriptions. Not few-shot, not a keyword router, not merging the tools.

Domain 8tool_choice

Tool controls

tool_choice: auto (default) · any (some tool) · {type: "tool", name} (that tool) · none. disable_parallel_tool_use: true caps one call per turn. strict: true is a field on the tool definition, not on tool_choice. defer_loading + a tool-search tool for big inventories — never defer every tool or the search tool itself.

Domain 8Errors

Structured tool errors

Return tool_result with is_error: true and a body carrying category (transient · validation · not_found · permission · business_rule), retryable, a human message, and a next step. "Error: 500" gives the agent nothing to act on.

Domain 8MCP

MCP primitives and transports

Tools — the model decides. Resources — the app supplies, identified by URI. Prompts — the user invokes. stdio = subprocess, local, simplest; remote HTTP/SSE = shared deployment with its own auth. API connector needs both mcp_servers and a mcp_toolset tool naming the same server, beta mcp-client-2025-11-20. MCP output is untrusted data.

Domain 8Choice

Built-in vs custom vs Skill vs MCP

Public web / code execution / file editing → built-in. Your data, one app → custom tool. Your data, several apps, independent maintenance → MCP server. A recurring procedure your team performs → Skill (zero tokens until invoked). A tool is a capability; a skill is a procedure. Enforcement is neither — that is a hook.