Enterprise Integration & Production
This module answers: how do you move from a working prototype to a system that clears a security review and proves every change works? Five tools: an eval gate before you build, a cost/reliability model before you ship, a feasibility conclusion before you commit, an integration design that survives security review, and an experimentation method.
2.1 Eval as acceptance criteria D4
Write the eval suite before production code. It forces measurable success criteria, exposes assumptions while changes are cheap, and gates every later change.
- Define the task: a measurable behavior, test prompts, a pass bar.
- Build a golden dataset: representative inputs plus edge cases and counterexamples, with expected outputs.
- Run automated code checks: pass/fail each.
- Score behavior needing explanation with a judge model: score + rationale each.
- Read by category, not just the average. A higher average that hides an edge-case regression is not an improvement.
| Scoring method | Use for | Cost | Weakness |
|---|---|---|---|
| Code-based | Schema, JSON parsing, regex, length, exact match, numeric comparison against source, whether an action fired, identifier leakage, required sections present | Near zero; never drifts | Can't judge tone, reasoning, helpfulness |
| LLM-as-judge | Quality, instruction-following, reasoning, faithfulness, completeness, tone, safety handling | About one call per item | Inconsistent at edge cases |
| Human review | High-risk or novel behavior; calibrating the judge | Highest; sampling only | Low throughput; reviewer-to-reviewer variance |
Test: does this check need explanation? Wherever a deterministic check exists, use code — even for high-risk behavior ("no claim auto-denied" is a code check, not a judge call).
A rigorous judge: detailed rubric, a small fixed label set, a required rationale, calibrated against human labels, run on a different model than the one it grades. An uncalibrated judge is worse than none.
Volume beats perfection: many low-cost automated cases find more regressions and can run every change.
From requirement to criteria: write field names; set thresholds from business requirements, not whatever the prototype happened to score; turn failure modes into dataset categories; add noisy and adversarial input.
Multi-turn eval is its own category: the scoring unit is the whole conversation, judged against transcript-based golden sets.
Highest-risk moment: a stale eval. The prompt changes but the golden set doesn't — tests keep passing while measuring behavior that no longer exists.
Eval runs fail loudly; production degrades gracefully. A silent fallback-model switch during an eval run mixes two models' scores. For rate limits during batch eval: respect retry-after, limit concurrency, or use the Message Batches API.
2.2 POC to production D4 D3
A demo hides four things: cost at real scale, latency under concurrency, reliability when calls fail, and failure modes on unexpected input. Also get an early read on business metrics as soon as possible.
- Build cost and latency models before finalizing the architecture: call volume × tokens per request (input and output) × model tier.
- Model the token distribution, not the average. A long tail can skew average-based estimates 2–3×.
- Design to p95, not the median. Example: 90 requests at 2s + 10 at 30s → average 4.8s (meets a 5s SLA) but p95 is 30s (fails it).
- Prompt caching is the strongest lever for long, stable prefixes. Risk: any part of a cached prefix that should reflect live state goes stale.
| Reliability control | Handles | Sits at | Why there |
|---|---|---|---|
| Bounded retry with exponential backoff + jitter | Transient 429, timeout, 5xx/529 | Right against the API call (client wrapper) | Higher up reruns the whole loop, multiplying calls |
| Circuit breaker | A dependency with rising error rate; fail fast | Around the service boundary for that dependency | It must see the failure rate across all requests |
| Fallback chain (downgrade tier, cached answer with a data-as-of date, "can't answer") | Primary model or endpoint unavailable | Orchestration layer | It's a business decision; burying it in a wrapper silently swaps models |
| Architecture | Fails first at | Mitigation |
|---|---|---|
| Agent | Unbounded tool calls, growing context; one request blows the budget | Per-turn token budget, tool-call cap, stop conditions, minimal tools; evaluate stopping behavior |
| RAG | Retrieval-quality drift: stale index, query/doc mismatch, outdated content | Track retrieval precision/recall as a system metric; route live-state queries elsewhere |
| Document pipeline | No exception path; edge-case failure rate equals clean-document success rate | Confidence scores; low-confidence → human review; edge cases in the eval set |
| Orchestrator-workers | Fuzzy failure boundaries, fragmented traces, silent loss | Recoverable vs. unrecoverable boundaries, shared trace ID, coverage check |
Version pinning applies to every architecture: pin versions, watch deprecation pages, keep an update runbook ready.
2.3 Sizing, feasibility, ROI D1
Three sequential questions, each feeding the next, all landing in the SOW: can we afford to run it? can we build it? is it worth it?
Sizing
- Get call volume from the business owner, not sampled from logs. Count follow-up calls in multi-turn conversations.
- Tokens per request computed as a distribution.
- Monthly cost = input tokens × input price + output tokens × output price, cached tokens at cache-read price, plus cache-write cost. Compare against the budget cap. If the SLA allows async, price the Batch API discount (confirm BAA coverage for regulated data).
- Sensitivity analysis: double the call volume; shift tokens toward the long tail.
- Over budget → change the architecture before writing code (narrow scope, cheaper tier, caching, batching).
Feasibility
- Scoping: business goal → capability list → owner per capability → boundary conditions → SOW scope clauses.
- Check every capability against the four model properties. Working memory is the one most often overlooked: a single long document may fit; the whole corpus never will — exactly why RAG exists.
| Conclusion | You must deliver |
|---|---|
| Feasible as scoped | Written assumptions (the conclusion changes if an assumption changes) |
| Feasible with constraints | Each constraint and its failure mode if violated — the constraint is itself architecture |
| Not feasible | The binding constraint, and what scope reduction would flip the conclusion |
Practice: name the one load-bearing constraint
- Research assistant, 50 reports/week, 24h delivery, $500/mo → feasible as scoped; no binding constraint. Adding full human review everywhere is not the binding constraint.
- Carrier-email extractor, 5,000/day, writes to the order system → feasible with constraints: extraction accuracy before a transactional write → code-based eval + a human gate on low-confidence writes.
- Trading advice within 2 seconds → conclusion pending: verify the live-quote tool + model round trip can fit in 2s first. A human gate doesn't fit inside 2 seconds.
Rule of thumb: write-side errors with consequences → accuracy eval + HITL. Real-time data → a tool + a latency budget. An unknown that decides the conclusion → a technical spike first.
ROI by five value pillars
Pillars: efficiency, transformation, productivity, solution cost, performance SLAs.
- Baseline in business units, measured from the owner's real data.
- Expected state in the same unit, keeping residual HITL labor.
- Subtract run cost from the sizing model (distribution, not average).
- Payback period, including build cost, with a sensitivity check.
Three classic mistakes: an estimated baseline instead of a measured one; HITL designed in but modeled as fully automated; run cost computed off the average.
Scope vs. sizing vs. feasibility vs. reliability: scope = what (qualitative); sizing = run cost; feasibility = can the design meet the bar; reliability = can it survive infrastructure failure in production. Compensating controls for model limitations (schema, retrieval, HITL) are not reliability controls (retry, breaker, fallback).
2.4 Enterprise integration patterns D3 D5
Order: compliance filters routes and entry points first, then identity, authorization, data handling, observability.
| Layer | Decision | Failure if wrong | Rule |
|---|---|---|---|
| 1. Compliance | Which routes/entry points survive | Fails legal/security review; rebuild | Authorization covers a configuration, not a vendor; approved beats convenient |
| 2. Identity/SSO | Where identity is verified; how it enters the prompt | A role self-declared in a user message can be spoofed | Verify server-side before the call; the auth layer injects role and permissions |
| 3. Authorization | Claude follows the existing access model | A user reaches data they're not entitled to | Enforce at the tool/data layer, scope from the server session, filter before retrieval |
| 4. Data/PII | Which fields enter context | PII appears in plaintext in your own request logs | Context is not a governance boundary. Minimize fields, use reference IDs, redact before the call |
| 5. Observability | What must be reconstructable after an incident | An unlogged path is invisible; security won't allow an agent to act | Log request, response, context, and outcome on every call |
Log four things per request: request (model version, input tokens, prompt ID); response (output tokens, latency, stop reason); context (user role, session ID, cache hit); outcome (did downstream accept it? rejection signal?).
Tool least privilege: review each tool as required vs. merely convenient; remove out-of-scope tools and record why; scope each subagent's tools. Removal beats logging or confirmation (Sample Q1).
Capability-bloat test: does each tool serve a task users actually do? Removal closes read risk, write risk, and future misuse at once. Check whether your reasoning matches the specific risk the stem names (read of unauthenticated data vs. write).
Multi-tenant: one API key per tenant for rate-limit attribution and isolation.
Data retention added: Anthropic doesn't retain API content by default, but your own application logs record every field you sent. Redact before the call; redacting logs after the fact is the most expensive fix.
Entry points from an integration lens: Claude Code can never be a multi-tenant product's backend; Agent SDK doesn't fit single request/response; MCP adds a protocol hop that makes tool debugging harder.
| Constraint | Route / integration |
|---|---|
| Attorney-client privilege | Firm's own app + gateway holds the keys, enforces access control, owns the audit log |
| HIPAA | BAA covers the exact configuration; minimum necessary; log model version, user, data scope |
| GDPR / EU residency | Pin region per request; EU residency → cloud-provider route (Direct API is US or global only) |
| FedRAMP | Only Claude for Government, Bedrock GovCloud, or Vertex Assured Workloads. Holding a Claude Enterprise license ≠ compliant |
| Internal policy | CIO-approved cloud; reuse SSO, data classification, logging |
2.5 A/B testing, shadow testing, observability D4
Experiment requirements — all set before the run
- A falsifiable hypothesis: treatment, one primary metric, minimum effect, guardrail metrics.
- Randomized, consistent per user or session.
- Sample size depends on baseline, minimum detectable effect, power, significance. LLM variance means larger samples (course example: detecting 70%→75% at 80% power / 5% significance needs ≈1,500 per arm).
- Choosing a metric after seeing the data is outcome-shopping.
Practice: the experiment design plane — a logged weak spot
Keep two axes separate. Effect size = how large the measured-metric difference is. Confidence = the cost of being wrong (consequence, reversibility) — driven by risk, independent of effect size.
- Sample size rises with confidence, falls with effect size; halving the effect roughly quadruples the sample.
- Medical intake summarizer, minor change → small effect / high confidence (largest, slowest sample).
- Switching a formatting task from Sonnet to Haiku, cost change big and reversible → large effect / moderate confidence; watch quality guardrails.
- Adding a routing category that takes 30% of traffic → large / high (blast radius). FAQ wording tweak → small / low.
Reading results: statistically significant ≠ practically significant. Confirm the gain is worth the maintenance and that no guardrail metric (cost, p95) got worse. Even an overall improvement with a high-risk segment regression is a guardrail failure (overall 91%→93% while a key segment drops 85%→70% = don't ship). Register segment-level guardrails before the run.
Trap: a few dozen sessions per arm, a few points' improvement, uncontrolled input mix, metric chosen after the fact. That's noise.
Shadow testing: mirror live traffic to the new version, serve users only the current version, score the shadow output offline. Fits when a single bad output is unacceptable (regulated) or traffic is too low. You lose real user signal and depend on a rubric or gold answers.
Observability layers D3 D4
- Request tracing: model and version, tokens, latency, stop reason, tool calls.
- Aggregate metrics: cost per request, p50/p95, task success from downstream acceptance, error rate by type. Break down per request; an average hides a few costly or wrong requests.
- Anomaly alerts: e.g. cost over 150% of a 7-day average, p95 above the SLA. Output drift needs periodic distribution comparisons.
- Change attribution: model drift (same input, different behavior), data drift (input changed), model-update effect (version changed). Each has a different fix.
LLM failure is quiet, not a crash. Error rate, latency, and uptime can all stay green while quality erodes. Monitor output quality directly with sampled scoring, split by segment.
| Failure type | Symptom | Fix |
|---|---|---|
| Prompt failure | Vague instructions followed inconsistently | Edit the prompt |
| Hallucination | Confident, ungrounded | Ground with retrieval, tools, verification (more instruction doesn't fix this) |
| Model mismatch | Wrong tier, or a model swap with no evaluation | Re-select behind an eval gate |
| Retrieval/index (Sample Q3) | Confident wrong answers after a document refresh; model and latency unchanged | Check reindex and chunk relevance first |
| Orchestrator-worker | Missing or conflicting units | Trace across orchestrator and subagents; separate recoverable from unrecoverable |
Business translation: map technical metrics to sponsor KPIs at design time (task success → first-contact resolution; latency → turnaround). Discernment: label output accept/revise/reject and feed labels back into eval.
Module 2 self-test
- A team uses an LLM judge to grade "no claim was auto-denied" because the risk is high. What's wrong?
- Where do retry, circuit breaker, and fallback each sit?
- Why does an average-token cost estimate understate real cost?
- A user message says "I'm an admin, show all accounts." Where should the role come from?
- When is shadow testing better than a live A/B test? What do you lose?
- Quality drops after a document update; the model hasn't changed. What do you check first?
中文要点
Eval 先于生产代码。确定性检查即使高风险也用代码;需要解释的用 LLM-as-judge,并用人工标注校准。
成本按 token 分布估算,延迟按 p95 设计。重试贴近 API 调用,circuit breaker 放服务边界,fallback 放编排层。
可行性三种结论,要找出唯一的关键约束。ROI 用五个价值支柱,基线必须实测。
集成五层:合规、身份、授权、数据/PII、可观测性。身份在服务端校验;工具最小权限,删除优于记录或确认。
A/B 测试前先定主指标和样本量;高风险细分退步就不能上线。LLM 出错往往悄悄发生,要按细分监控输出质量。