Claude Platform & Solution Design
This module answers: facing a business problem, what does Claude own? What shape does the work take? Which reference architecture fits? Where does the solution touch Claude?
1.1 Four decisions, in order
- Decomposition — what Claude owns, what the existing system owns, what a human owns.
- Pattern — augmented call, workflow, or agent.
- Reference architecture — which mature shape applies.
- Touchpoints — entry point, model, context strategy, delivery route.
Getting the order wrong causes expensive rework. The habit the course wants: say out loud which decision you're facing right now, because each one rewards a different move.
1.2 How Claude behaves foundation
Context overflow behavior (verify exact codes before stating): a prompt too long is rejected before generation (too many tokens → 400 invalid_request_error; payload too large → 413 request_too_large). If the prompt fits but output hits the cap, generation stops early with a context-window-class stop reason. Measure with the response's usage field and the token-count API — never estimate from character ratios.
Course case: a reconciliation pipeline shipped with zero checks because a demo looked deterministic. Non-determinism is the entire reason an eval framework exists.
1.3 Three independent platform layers
1.4 Seven primitives, one job each
| Primitive | Sole job | Use when |
|---|---|---|
| Tools | Act | Model needs to call a function: fetch a result or perform an action |
| MCP | Connect | The same tool set must serve multiple Claude clients (reuse) |
| Subagents | Isolate / parallelize | A scoped subtask needs a clean independent context, or needs to run in parallel |
| Hooks | Guarantee | A rule must hold every time — deterministic code on lifecycle events the model cannot skip |
| Skills | Package a procedure | A repeatable process needs versioning, sharing, governance (SKILL.md + optional scripts) |
| Agent Teams | Coordinate peers | Several agents each own part of the goal |
| Dynamic Workflows | Compose at runtime | Steps must assemble at runtime; they can't be fixed in advance |
Rule: use the fewest primitives the requirement needs. Every added one adds latency, tokens, and a surface that needs observability and governance. Patterns (augmented call, workflow, agent, multi-agent) are assemblies of these primitives.
Tool vs. MCP vs. Skill vs. Hook — four dimensions, not four alternatives
| Dimension | Answers | Finance analogy |
|---|---|---|
| Tool | What the model can do (capability; model decides whether to call it) | A transaction code |
| MCP | How tools/resources/prompts are shared across clients (protocol) | A standard interface opening a transaction to multiple systems |
| Skill | How to do a procedure well (packaged expertise; can specify which tools to use) | An SOP or desk procedure |
| Hook | What must happen (enforcement outside the model) | An automatic preventive edit check that blocks posting |
A Skill sits on top of tools; tools are never built on top of a Skill. Packaging (Skill) and sharing (MCP) change distribution, not enforcement.
1.5 Decomposition and delegation D1
- Claude: language understanding, summarizing, drafting, planning, acting through tools, perception (reading a label photo).
- Existing system: anything already reliable — rules engine, system-of-record database, policy table, computation, email/payment systems.
- Human: judgment, exceptions, approvals, safety decisions, unrecoverable money.
Three ownership tests: reversibility, stakes, accountability. The output is a delegation map (AI owns / human owns / Claude drafts + human decides).
Reframe: don't ask "where can Claude help?" Ask "where do the four model properties make Claude more suitable than a system that already does this correctly?" Claude can attempt every step — that is not the test.
Practice: the three-question sort
- Is it a system-of-record fact, a calculation, or an eligibility rule? → Existing system. Claude can call it as a tool and narrate the result.
- Is it high-consequence, irreversible, over a threshold, or safety-related? → Human. Claude can draft or flag.
- Is it language or perception work with a human or system checking the next step? → Claude.
- Split compound steps: "tell the engineer whether warranty applies" = system decides, Claude narrates. "Issue the refund" = system determines eligibility, human approves payment.
Exam trap
Stuffing a deterministic business rule (threshold, eligibility, priority, coverage) into the prompt to "simplify" the design. It works cleanly in a demo and fails quietly on messy input, surfacing later through an audit rather than monitoring. Rules stay in code; Claude extracts, the system decides.
1.6 Pattern selection D1
| Pattern | Control flow lives in | Use when |
|---|---|---|
| Augmented LLM | One call, your code around it | Scoped, verifiable task; can add tools, retrieval, thinking |
| Workflow | Your code (named steps) | Steps are known in advance; error cost and observability matter |
| Agent | The model | The path genuinely can't be enumerated; errors are acceptable and recoverable |
Workflow sub-patterns: chaining (sequential handoff), routing (classifier picks a path), parallelization (independent units run together, then merge or vote), evaluator-optimizer (generate, score, revise until it passes or hits a retry cap). Combine freely; start with the simplest.
Five deciding factors, in order — the first one that excludes a pattern wins: predictability, error cost, observability, latency budget, cost.
Production agents need: a lean tool set, a per-turn budget, explicit permissions, and stop conditions.
Quality-fix order: improve the prompt → add tools or retrieval → a stronger pattern (evaluator-optimizer) → fine-tuning last. Fine-tune only when volume is huge and inference cost is the binding constraint, or there's a hard latency ceiling, or a formatting-consistency problem the prompt can't solve — it locks you to a model version, and Claude fine-tuning access is limited and needs confirming with your account team.
Packaging spectrum: prompt-only → direct tool call → Skill. Pick Skill when the process repeats, crosses teams, and needs versioning and rollback.
Exam trap
"The task feels open-ended, so pick agent" — wrong if the real paths are enumerable. Agents create an audit gap: compliance can't find one deterministic approval step. An unpinned model version with no re-validation gate is a governance gap in any pattern. Agents are not necessarily more expensive — accumulated context and call count drive cost, not the pattern label.
1.7 Multi-agent orchestration D1
- Orchestrator: owns the goal, decomposition, delegation, aggregation. Does not do subtask work itself.
- Subagents: each owns one scoped unit, runs in a clean context, returns a structured result.
- Design explicitly: how you decompose, the result schema, conflict rules, gap rules.
- Failure asymmetry: a subagent failure is usually recoverable; an orchestrator failure usually isn't. Make subagent work idempotent and retryable (unit IDs; retries don't duplicate writes). Checkpoint orchestrator state.
- Cost: every subagent carries its own context, and the orchestrator pays again to aggregate. Use multi-agent only when the work truly exceeds one context.
| Failure | Lands in | Design response |
|---|---|---|
| Subagent returns malformed or empty result | Subagent boundary (recoverable) | Validate every result; retry or reassign that unit; log the gap, don't fail the whole run |
| Two subagents conflict | Aggregation stage (recoverable) | Explicit conflict rule, or escalate to a human |
| Orchestrator loses goal or state | Orchestrator (usually unrecoverable) | Protect state; checkpoint so a failure can resume |
| Fragmented trace | Observability (cuts across layers) | One shared trace ID across orchestrator and subagents |
Practice: multi-agent design review checklist
- Coverage check at aggregation: returned result count must equal dispatched unit count; call out gaps explicitly ("9,850 of 10,000 classified, 150 missing"). The most dangerous failure is a confident, complete-looking summary built on missing units.
- Validate every subagent result; retry or flag failed units.
- Explicit conflict-resolution rule, or escalate to a human.
- One shared trace ID.
- HITL gate before anything irreversible; sample low-risk operations.
- Fix where the failure happened — don't paper over it upstream.
1.8 Reference architectures D1
| Architecture | Done well | Typical failure |
|---|---|---|
| Agent | Goal + bounded tools + turn budget + success criteria | State-changing tools, unbounded autonomy, no human review |
| RAG | Stable corpus, chunked and indexed, relevant chunks placed in context | Used for live state (order status, inventory, queue, balance) |
| Document pipeline (evaluator-optimizer) | OCR → schema extraction → validation → exception routing | No exception path; low-confidence extractions with no human gate |
| Ticket triage (routing) | Detect intent → docs retrieval / transactional API / human approval | Retrieval used for live state; no human escalation; agent shipped before measuring a routed workflow |
| Coding agent | Agentic exploration, then deterministic edit/test/review steps | Edits and commits with no review gate; no language-specific regression eval |
#1 mistake: letting retrieval do a tool call's job. Symptoms: stale chunks, answers that change on every reindex, answers that contradict the database. A better embedding model, faster refresh, or a tuned similarity threshold won't fix it. Call the system of record. Similar is not the same as true.
Only combine two architectures when their failure modes differ. Each needs its own eval set — a healthy overall score can hide one failing component.
1.9 RAG pipeline design D3
Two independent decisions. Chunking looks at the corpus itself (its structure). Indexing looks at how queries are phrased (the query mix the whole corpus faces).
| Decision | Option | Use when |
|---|---|---|
| Chunking | Fixed-size + overlap | Homogeneous, weakly structured text; simplest |
| Chunking | Semantic | Each chunk must stand alone as coherent prose |
| Chunking | Hierarchical | Numbered-section documents (contracts, manuals, policy, FMR) where section context carries meaning — keep a section-path on each chunk |
| Indexing | Dense (embedding) | Paraphrase, concept, intent matching |
| Indexing | Sparse (BM25 / keyword) | Exact tokens: part numbers, citations, error codes, TAS/SFIS codes |
| Indexing | Hybrid + reciprocal rank fusion (RRF) | Mixed query patterns — the common production case. RRF sums 1/(k+rank) across lists; needs only rank, no score calibration; the lowest-tuning default |
Always state the three-way tradeoff: retrieval quality vs. latency vs. maintenance cost. Smaller chunks + hybrid indexing raise quality and latency together. Larger chunks + dense-only is cheaper and faster but misses exact codes. An answer that skips the tradeoff is incomplete.
Risk: a confident answer built on the wrong chunk looks identical to a correct one. Measure retrieval with a labeled set; a pipeline that's correct at launch quietly degrades as documents grow.
Retrieval routing (live vs. static): a router can be keyword rules (cheap, brittle), a classifier step (testable), or agent-chosen (flexible, hardest to audit). Misrouting: a query that sounds static but needs live data gets sent to RAG and returns a stale answer; a query needing both gets single-label routed and half-answered. Fix: multi-label routing; default to the database with a data-as-of note when uncertain; log routing; score routing accuracy separately in the eval set.
1.10 Model and context strategy D2 D3
Four terms to keep separate: context window (what the model sees this call), retrieval (knowledge fetched and placed in the window), persistent application state (owned by your system, reached through tools), summaries/memory (managed by the application; the model has no native memory).
Model-tier rule: default Sonnet. Move up to Opus only when eval shows Sonnet falls short. Move down to Haiku only when eval shows the loss is acceptable. Not choosing a tier means you chose the most expensive one.
Per-step model selection (Haiku for classification, Sonnet for summarization, Opus only where proven necessary) is the standard fix for cost and latency overruns.
Context capacity planning: the window is a ceiling, not a target. Budget by the largest realistic conversation plus retrieval content, system prompt, scratch space, and growth margin.
| Strategy | Fits | Failure point / cost |
|---|---|---|
| Monolithic | Scoped tasks, stable cacheable prefixes, reasoning that genuinely needs everything visible at once | Context accumulates per turn; cost grows linearly; quality drops before the hard limit; irrelevant entries cause wrong picks |
| Progressive (default) | Most production work: carry only what the next step needs; discover tools/docs on demand | Long-range coherence weakens; harder to cache; harder to reconstruct step-N inputs when debugging |
| Retrieval | Corpus bigger than the window, fast-changing sources, citations needed | Cross-document synthesis, chunking that splits a table or code block, recall misses |
| Compaction | Long-running sessions | Summaries drop identifiers, numbers, one-time decisions; mostly irreversible; fidelity is hard to evaluate |
Practice: progressive discovery vs. monolithic — a logged weak spot
- Ask first: what share of the loaded context is relevant to a typical request? If most of it isn't (60 tools loaded, 3–5 used), reduce what's loaded: keep a small core set, discover the rest on demand. This lowers cost, latency, and mis-selection together.
- Don't answer by "stacking another instruction on top of what's loaded." That adds tokens while the confusing entries stay in front of the model.
- Caching lowers the cost of a repeated prefix — it doesn't fix mis-selection.
- Monolithic wins only when the set is small and almost every call uses all of it.
- Four design questions: what's needed at the start (monolithic baseline)? what's needed in the next few steps (progressive window)? what's needed on demand (retrieval)? what can be safely compacted (compaction policy)?
Extended thinking verify current docs
Reasoning in separate thinking tokens. Thinking tokens bill as output tokens and add latency. Current models use adaptive thinking: the model decides per-request whether and how much to think, steered by an effort level (low / medium / high / xhigh / max); max_tokens caps thinking plus answer together. A fixed budget_tokens is the older control. Raise effort only when eval shows a gap the prompt can't close; never turn it on for a routing classifier. Effort is the knob, eval is the gate.
Swapping models is a release
Gate every swap with: (1) a curated, tiered test set, (2) a scoring function, (3) a pass/fail threshold set before the run. Segment-level thresholds enable partial migration — easy segments move to the cheaper model, hard segments stay on the strong one.
1.11 Prompting as architecture D2
A reusable system prompt needs: role and scope, must-do/must-not constraints, and an output contract. Vagueness at scale is a defect repeated on every request.
Templates: parameterized slots inside a fixed frame. Guardrails live in the frame, so filling slots can't remove the constraint.
An underspecified guardrail is worse than none — it looks like a control. Prefer structural enforcement (an output contract/schema, a deterministic check) over prose.
What actually ships is the prompt-plus-model pair. Any model swap requires re-evaluating the prompt.
| Technique | Use when | Stem signal |
|---|---|---|
| Zero-shot | Clear, scoped task; try this first | Categories already listed; standard summarization |
| Few-shot | Format or judgment criteria are easier shown than described | Receipts in varying layouts |
| Chain-of-thought | The answer depends on a reasoning path with several interacting conditions | A liability call with three interacting conditions |
Every tier up adds tokens and latency. Few-shot examples need maintenance and can introduce bias if unbalanced. Distractor: adding examples or CoT to a simple task.
Prompt caching Sample Q2 pattern
The cache saves a prefix — it hits only when everything before the breakpoint is identical. Order rule: static first, dynamic last. Putting a per-request document before fixed content breaks the prefix.
Prefix byte order is tools → system → messages. A change at one layer invalidates that layer and everything after it. CLAUDE.md text lives inside messages.
Up to 4 breakpoints you place; each one caches everything before it. Below the model's minimum cacheable length, nothing caches — and no error is raised.
Only worthwhile when the same prefix repeats within the TTL (default 5 min, refreshed on hit; a 1-hour option also exists). Writes cost more than normal input; reads cost a small fraction. Verify before use: cache write ≈1.25× base input price (5-min TTL) or 2× (1-hour); cache read ≈0.1×; minimum cacheable length 512–4,096 tokens depending on model. Changing thinking/effort settings invalidates the message-layer cache. Confirm with cache_creation_input_tokens / cache_read_input_tokens in usage.
Two enablement paths: a top-level cache_control (automatic), or cache_control on the last stable content block (you choose the breakpoint).
Distractors: truncating the document, downgrading blindly, moving content into few-shot, raising max_tokens.
Practice: reusable prompt assets
- Cost follows prefix order: role, tone, output contract, guardrails = stable prefix; ticket + manual section go after the breakpoint.
- Safety follows structure: guardrails written into the output contract (fields the reply must satisfy), ideally plus a deterministic output check.
- Governance follows packaging: a stable, high-frequency, org-wide process becomes a versioned Skill. Copy-pasted prompts drift.
- Prompt library vs. Skill: a library suits fragments a team assembles itself; a Skill suits a stable process needing approval and rollback, distributed across teams.
1.12 Entry points, interfaces, routes, governance D3 D5 D7
Selection order: entry point (fits user and work) → build-time interface (fits team) → delivery route (fits cloud and compliance). Governance constraints exclude options before cost or convenience.
| Entry point | Fits | Notes |
|---|---|---|
| Claude.ai (Team/Enterprise) | Knowledge workers, no dev needed | Team: admin console, SSO, no training on customer content. Enterprise: SCIM, retention controls, audit logs, Compliance API, HIPAA-ready with BAA. Cannot embed into other products |
| Claude Code | Engineers | Not for non-engineering workflows; never a product backend |
| Cowork / Chrome / Excel | Non-devs working files, web apps, spreadsheets | Permission scope and review matter more here |
| Your own API/SDK app | Your product, or governed internal tooling | Retries, streaming, observability, UI, audit are all on you |
| Build-time interface | Pick when |
|---|---|
| Direct API | Maximum control, maximum responsibility |
| SDK | Same capability, more ergonomic per language; default for embedding |
| MCP | A tool server must serve multiple Claude clients. One client only → an extra protocol hop and a server to build/secure for no payoff. MCP tools are still invoked via tool use — MCP and tool use are different layers, not alternatives |
| Agent SDK | Running a managed multi-turn agent loop inside your product (Claude Code's engine). Not for single request/response; you lose per-turn control |
| Agent-to-agent | Delegating to a peer agent with its own goals and reasoning. Reading data needs one tool, not another agent |
Shortcut: single request/response → API or SDK. Tools shared across clients → MCP. Multi-turn agent inside a product → Agent SDK.
Claude Code's layers
Skill as an integration mechanism added: mounted via a container's skills parameter, managed through the Skills endpoint, versioned like any other asset. A Skill needs the code-execution tool, which adds a sandbox dependency — weigh it against MCP and direct tool calls.
CLAUDE.md is not a system prompt. Claude Code puts Anthropic's system prompt in the system field and inserts CLAUDE.md into messages. Analogy: system prompt = the published regulation, same for everyone; CLAUDE.md = your office's desk guide. Neither is enforced. "Write it into CLAUDE.md" is a distractor for a "never allowed" rule.
Delivery routes and regulated constraints
The model behaves the same on every route. What differs: billing, identity (API key / IAM / Google credential / Entra ID), region, contract, model ID strings, and feature lag (cloud-provider routes often trail first-party).
Default to first-party with no cloud commitment or when you need the newest features; otherwise follow the partner's existing cloud agreement.
| Constraint | What it decides |
|---|---|
| Privilege (law firm) | The firm must own the audit trail: API/SDK behind the firm's own app, SSO, and approved gateway. Enterprise logs living on Anthropic's infrastructure = an audit trail exists, not that the firm owns it |
| HIPAA | BAA must cover the exact config/features (beta features often excluded); minimize PHI; use reference IDs |
| GDPR / residency | Each request is pinned to a region. Direct API region is US or global only, so EU residency points to a cloud-provider route. GDPR itself doesn't mandate EU residency |
| FedRAMP / DoD | Claude for Government (FedRAMP High), Bedrock GovCloud (FedRAMP High, IL4/5), Vertex Assured Workloads. Claude Enterprise / Direct API have no FedRAMP authorization. Government environments trail on model availability |
| Internal policy | CIO-approved route beats engineering convenience; reuse existing SSO, data classification, logging |
Stack and request lifecycle
Bottom-up: model (reads the request, writes text or tool requests) → Claude API (contract + server features: caching, tool protocol, thinking, batching, billing) → client SDK (HTTP, auth, retries; adds no model capability) → Agent SDK runtime (run loop, executes tools, checks permissions, fires hooks, loads CLAUDE.md) → application.
The model only requests a tool call; the runtime executes it. That's why hooks and permissions live in the runtime.
The API is stateless; every turn resends the whole conversation. That's why caching matters. One user message can cost several API calls.
Loop control: stop_reason of tool_use means the runtime executes the tool and continues; end_turn means the loop ends.
Exam traps — Module 1
- Picking Claude Code before knowing who the user is (a bank teller won't use a terminal).
- Adding MCP for a single client "because it's on the menu."
- Putting a high-consequence check (compliance) on the least deterministic component (subagent, prompt) instead of server-side code.
- Right entry point, wrong reason (Bedrock "for residency" when the actual reason is BAA coverage) — graded as entry-point-plus-reason pairs.
- Decision order: (1) who is the user? (2) any hard governance/contract constraint? (3) real-time system integration needed? (4) latency and infrastructure. The first constraint that excludes options wins.
1.13 Assembly: five decisions every architecture answer needs
| Decision | Law-firm contract review: correct answer |
|---|---|
| 1. Entry point | Direct API/SDK in a lean internal web app, behind SSO and an approved gateway (privilege excludes Claude.ai) |
| 2. Pattern | Workflow, parallel by section + a strict-schema eval step (work splits cleanly — no open-ended agent) |
| 3. Decomposition | Claude extracts, classifies against the playbook, drafts edits. Playbook is versioned in the firm's system, retrieved by clause (not pasted into the system prompt). Pulling docs from iManage = a tool |
| 4. Model + context | Default Sonnet, progressive context, extended thinking only on clauses eval proves need it (not Opus everywhere) |
| 5. HITL | A senior lawyer signs off every output; low-confidence clauses are flagged |
Each wrong option misses exactly one decision. Always check all five.
Module 1 self-test
- A partner wants Claude to enforce a fixed dollar threshold. Who should own the threshold, and why does failure surface late if it doesn't?
- Name the five pattern-selection factors, in order.
- A parallel review run reports "all sections reviewed" but two subagents timed out. Which control is missing?
- A user asks both "find clause 14.2" and "how do we usually handle Y?" Which index type, and how are results merged?
- Caching isn't saving money because a per-request document sits above the fixed instructions. How do you fix it?
- Only one internal app will ever call these tools. MCP or direct tool call? State the tradeoff.
中文要点
模块 1 的核心是四个按顺序做的决策:工作分解、模式选择、参考架构、接入点与模型/上下文策略。
确定性规则、实时数据、计算交给现有系统;语言工作交给 Claude;高风险决定交给人。
能列举路径就用 workflow;只有路径确实无法预知时才用 agent。多 agent 汇总要做覆盖率检查。
RAG 只用于稳定知识,实时状态用 tool 查询系统记录。分块看文档结构,索引看查询组合,并说明取舍。
默认 Sonnet,换模型要用事先定好阈值的 eval 把关。渐进式发现减少加载量,不要叠加指令。
只有一个客户端不需要 MCP。CLAUDE.md 和 Skill 都是指导,不是强制执行。合规先于成本筛选路线。