Chapter DCost optimization labPage 3 of 8

Cost optimization lab

Implement the happy path

Cost optimization lab is production work only when one frozen failure can be reproduced, one measurable gate can stop a release, and one operator can safely reverse it.

~14 minHappy path

Before you start

Why this matters

Read this incident aloud: duplicate shipping questions consume flagship-model tokens even though a cached small-model answer passes quality checks. In two minutes, write the earliest deterministic check that should fail, the telemetry signal you would inspect, and the action that must not happen automatically. Compare your answer with this chapter's boundary: cache keys exclude raw identity and sensitive text; regulated intents always use the approved model path.

1Learn the idea

Read

Implement the controlled happy path

Code begins at the boundary, not at the provider SDK. Parse CostSample with intent, model, input_tokens, output_tokens, cache_hit, latency_ms, quality_pass, and price_version before any model or tool call, and return OptimizationReport with cost_per_success, cache_rate, routed_share, quality_delta, and projected_savings even when the provider times out. Typed records make malformed data a normal error path instead of an exception discovered after a side effect. Inject the model client, clock, action adapter, and telemetry sink so tests can replace each one. That design also prevents a local test from accidentally reaching production.

The important implementation choice is ordering. Authenticate and normalize first; make the controlled call second; validate the response third; commit any state or action last. For this system, cache keys exclude raw identity and sensitive text; regulated intents always use the approved model path. A convenient function that mixes parsing, generation, action, and logging cannot prove that ordering. Keep each stage named so a trace can show which boundary rejected the request.

Use deterministic identifiers derived from stable business inputs when retries are possible. Record the release, fixture version, and policy version with the result. Never derive authorization from generated text. The code path should make the safe behavior easier than bypassing it: callers receive a decision object, not an unrestricted provider response.

For the happy path, run one valid fixture through the real orchestration with fake adapters. Keep the path small: accept, decide, validate, record. A successful response must carry evidence and a trace ID, not merely polished text.

Read

Focused implementation artifact

def run_case(case, *, release, trace_id):
    # Adapters are injected in production; the orchestration owns policy.
    choice = router.choose(intent, complexity=0.18, cache_eligible=True)
    reasons = evaluate(answer if "answer" in locals() else locals().get("result", locals().get("decision", locals().get("job", locals().get("choice")))))
    return {"passed": not reasons, "reasons": reasons,
            "release": release, "trace_id": trace_id}

result = run_case({"intent":"shipping_faq","model":"flagship","input_tokens":2100,"output_tokens":180,"cache_hit":false,"latency_ms":2400,"quality_pass":true,"price_version":"2026-07"}, release="candidate", trace_id="trace-42")
assert result["trace_id"] == "trace-42"

Read

Walk the successful transaction

Trace one accepted fixture through parse, policy lookup, controlled dependency call, output validation, and result recording. At each stage, name the input and output type. The successful transaction must produce evidence for cost per successful answer, a correlation ID for logs and spans, and a release identifier. It must not grant the model authority to choose identity, credentials, network destinations, or approval.

Run the path with recording fakes and inspect their call order. The assertion is not merely “returned 200”: exactly the expected adapter was called, its arguments were normalized, no forbidden adapter ran, and llm_cost_per_success_usd recorded a bounded outcome. Repeat with the same idempotency key or request identifier where retries are relevant; the observable decision should remain stable.

Finally, swap in the known failure cost per call falls after routing, but retries increase and cost per successful answer rises while leaving orchestration unchanged. The happy path must stop at the correct boundary instead of manufacturing a success. The operator-facing consequence is to promote routing by intent, retain a holdout, and automatically disable it if quality or retries breach budget.

Checking tutor…

Continue learning · glossary & guides