[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HA7Y7DGRQ827BED7CK8ZQ":3,"skill-same:01M77HA7Y7DGRQ827BED7CK8ZQ":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":52,"ownerHtmlUrl":53,"ownerBlogUrl":6,"ownerDescription":54,"updatedAt":55,"install":56,"resources":69},"01M77HA7Y7DGRQ827BED7CK8ZQ","greenhelix-agent-cost-optimization",null,"AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality. Practical recipes for reducing AI agent operational costs. Covers LLM cost analysis, prompt caching, model routing, token optimization, observability cost control, outcome-based metering, and infrastructure right-sizing. Includes working Python code and real cost reduction case studies.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-cost-optimization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-cost-optimization\nversion: \"1.3.1\"\ndescription: \"AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality. Practical recipes for reducing AI agent operational costs. Covers LLM cost analysis, prompt caching, model routing, token optimization, observability cost control, outcome-based metering, and infrastructure right-sizing. Includes working Python code and real cost reduction case studies.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [cost-optimization, finops, observability, metering, model-routing, agent-operations, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 29.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [WALLET_ADDRESS]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - WALLET_ADDRESS\n    primaryEnv: WALLET_ADDRESS\n---\n# AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n\n\nA Fortune 100 financial services firm deployed twelve LangChain agents to automate research workflows in January 2026. By March, their monthly AI infrastructure bill had grown from $14,000 to $89,000 -- a 536% increase that no one predicted, no one budgeted for, and no one could explain until a three-week forensic investigation traced the cost explosion to four root causes: unbounded context windows that grew with every conversation turn, a model routing configuration that sent simple classification tasks to GPT-4o instead of a model ten times cheaper, an observability pipeline that generated more telemetry data per agent request than the request itself cost to serve, and a retry loop in one agent that silently reprocessed failed tasks up to fifty times before giving up. Every one of these problems is fixable. Every one of them is preventable. This cookbook shows you how.\nThe numbers are stark. Observability vendors report that AI agent deployments increase telemetry costs by 40-200% over traditional application monitoring. Anthropic's own usage data shows that the median enterprise wastes 35-45% of its LLM inference spend on tokens that contribute nothing to output quality -- system prompt bloat, redundant few-shot examples, uncompressed tool descriptions, and response format overhead. A 2026 survey by the FinOps Foundation found that 80% of Fortune 500 companies are now deploying AI agents in production, with an average of twelve agents per enterprise, and that cost governance for these agents is rated the number one unsolved infrastructure problem by platform engineering teams.\nThis is not a theoretical guide. Every chapter contains working Python code that you can run against your own agent fleet today. The strategies are ordered by impact: Chapter 1 teaches you to measure where money actually goes (you cannot optimize what you cannot see). Chapter 2 covers LLM cost reduction through prompt caching, compression, and context management. Chapter 3 builds a model router that sends each task to the cheapest model that meets quality requirements. Chapter 4 tackles the observability cost explosion with adaptive sampling and cardinality management. Chapter 5 optimizes tokens at the prompt and response level. Chapter 6 introduces outcome-based metering as an alternative to input-based billing. Chapter 7 covers infrastructure right-sizing. Chapter 8 provides a week-by-week optimization playbook with ROI calculations. By the end, you will have a concrete, measurable plan to cut your agent bills by 60% or more.\n\n## What You'll Learn\n- Chapter 1: Where Agent Money Actually Goes\n- Chapter 2: LLM Cost Reduction Strategies\n- Chapter 3: Model Routing -- Right Model for the Job\n- Chapter 4: Observability Cost Control\n- Chapter 5: Token Optimization\n- Chapter 6: Outcome-Based Metering\n- Chapter 7: Infrastructure Right-Sizing\n- Chapter 8: Cost Optimization Playbook\n\n## Full Guide\n\n# AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality\n\nA Fortune 100 financial services firm deployed twelve LangChain agents to automate research workflows in January 2026. By March, their monthly AI infrastructure bill had grown from $14,000 to $89,000 -- a 536% increase that no one predicted, no one budgeted for, and no one could explain until a three-week forensic investigation traced the cost explosion to four root causes: unbounded context windows that grew with every conversation turn, a model routing configuration that sent simple classification tasks to GPT-4o instead of a model ten times cheaper, an observability pipeline that generated more telemetry data per agent request than the request itself cost to serve, and a retry loop in one agent that silently reprocessed failed tasks up to fifty times before giving up. Every one of these problems is fixable. Every one of them is preventable. This cookbook shows you how.\n\nThe numbers are stark. Observability vendors report that AI agent deployments increase telemetry costs by 40-200% over traditional application monitoring. Anthropic's own usage data shows that the median enterprise wastes 35-45% of its LLM inference spend on tokens that contribute nothing to output quality -- system prompt bloat, redundant few-shot examples, uncompressed tool descriptions, and response format overhead. A 2026 survey by the FinOps Foundation found that 80% of Fortune 500 companies are now deploying AI agents in production, with an average of twelve agents per enterprise, and that cost governance for these agents is rated the number one unsolved infrastructure problem by platform engineering teams.\n\nThis is not a theoretical guide. Every chapter contains working Python code that you can run against your own agent fleet today. The strategies are ordered by impact: Chapter 1 teaches you to measure where money actually goes (you cannot optimize what you cannot see). Chapter 2 covers LLM cost reduction through prompt caching, compression, and context management. Chapter 3 builds a model router that sends each task to the cheapest model that meets quality requirements. Chapter 4 tackles the observability cost explosion with adaptive sampling and cardinality management. Chapter 5 optimizes tokens at the prompt and response level. Chapter 6 introduces outcome-based metering as an alternative to input-based billing. Chapter 7 covers infrastructure right-sizing. Chapter 8 provides a week-by-week optimization playbook with ROI calculations. By the end, you will have a concrete, measurable plan to cut your agent bills by 60% or more.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Where Agent Money Actually Goes](#chapter-1-where-agent-money-actually-goes)\n2. [LLM Cost Reduction Strategies](#chapter-2-llm-cost-reduction-strategies)\n3. [Model Routing -- Right Model for the Job](#chapter-3-model-routing----right-model-for-the-job)\n4. [Observability Cost Control](#chapter-4-observability-cost-control)\n5. [Token Optimization](#chapter-5-token-optimization)\n6. [Outcome-Based Metering](#chapter-6-outcome-based-metering)\n7. [Infrastructure Right-Sizing](#chapter-7-infrastructure-right-sizing)\n8. [Cost Optimization Playbook](#chapter-8-cost-optimization-playbook)\n\n---\n\n## Chapter 1: Where Agent Money Actually Goes\n\n### The Five Cost Components\n\nEvery AI agent incurs cost across five categories, and most teams only track one of them. Understanding all five is the prerequisite to optimization.\n\n**1. LLM Inference.** This is the cost most teams focus on because it is the most visible. Every call to GPT-4o, Claude, Llama, or any other language model has a per-token price for input and output. For a typical agent that processes 2,000 input tokens and generates 500 output tokens per request, using GPT-4o at $2.50\u002Fmillion input and $10.00\u002Fmillion output, the per-request inference cost is $0.01. At 10,000 requests per day, that is $100\u002Fday or $3,000\u002Fmonth. This is the floor -- the minimum you pay just for the LLM to think.\n\n**2. Tool Calls.** Agents do not just think; they act. Every tool call -- database query, API request, web search, code execution -- has a cost. Some are direct (the API charges per call), some are indirect (the compute to run the tool, the network egress, the storage for results). A research agent that calls a search API ($0.005\u002Fquery), a document retrieval service ($0.002\u002Fdoc), and a summarization endpoint ($0.008\u002Fsummary) per task adds $0.015 in tool costs on top of inference. At scale, tool costs often exceed inference costs.\n\n**3. Orchestration Overhead.** Multi-agent systems have coordination costs. The orchestrator agent spends tokens deciding which worker to call, parsing worker responses, managing conversation state, and handling errors. In a CrewAI or LangGraph workflow with five agents, the orchestrator may consume 30-40% of total inference tokens just for coordination -- tokens that produce no direct value for the end user.\n\n**4. Observability.** Every agent request generates traces, metrics, and logs. OpenTelemetry spans, custom metric submissions, structured log entries, and distributed trace propagation all consume storage and compute. The observability tax is often invisible because it is billed separately (by Datadog, Grafana Cloud, or your self-hosted stack), but it scales linearly with agent traffic. A single agent request that generates 15 spans, 8 metric data points, and 20 log lines can cost more in observability than the LLM inference itself.\n\n**5. Storage.** Conversation history, agent memory, tool call results, audit logs, and cached responses all require storage. For agents with long-running conversations or persistent memory, storage costs grow monotonically. A conversation that accumulates 50,000 tokens of history over 100 turns, stored in a vector database at $0.10\u002FGB\u002Fmonth, costs pennies per conversation -- but multiplied by thousands of concurrent conversations, it becomes material.\n\n### Instrumenting Cost: The CostTracker Class\n\nBefore optimizing anything, you need to measure everything. This class wraps every agent operation and records its cost.\n\n```python\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List, Any\nfrom contextlib import contextmanager\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass CostEvent:\n    \"\"\"A single cost event from an agent operation.\"\"\"\n    timestamp: str\n    agent_id: str\n    operation: str\n    category: str  # inference, tool_call, orchestration, observability, storage\n    input_tokens: int = 0\n    output_tokens: int = 0\n    cost_usd: float = 0.0\n    duration_ms: float = 0.0\n    metadata: Dict[str, Any] = field(default_factory=dict)\n\n\nclass CostTracker:\n    \"\"\"Tracks all cost events for an agent or fleet of agents.\n\n    Thread-safe. Supports concurrent agent operations.\n    \"\"\"\n\n    # Pricing per million tokens (input\u002Foutput) by model\n    MODEL_PRICING = {\n        \"gpt-4o\":           {\"input\": 2.50,  \"output\": 10.00},\n        \"gpt-4o-mini\":      {\"input\": 0.15,  \"output\": 0.60},\n        \"claude-sonnet-4\":  {\"input\": 3.00,  \"output\": 15.00},\n        \"claude-haiku-3.5\": {\"input\": 0.80,  \"output\": 4.00},\n        \"llama-3-70b\":      {\"input\": 0.70,  \"output\": 0.80},\n        \"llama-3-8b\":       {\"input\": 0.10,  \"output\": 0.10},\n        \"mistral-large\":    {\"input\": 2.00,  \"output\": 6.00},\n        \"mistral-small\":    {\"input\": 0.20,  \"output\": 0.60},\n    }\n\n    def __init__(self):\n        self._events: List[CostEvent] = []\n        self._lock = threading.Lock()\n\n    def record_inference(\n        self,\n        agent_id: str,\n        model: str,\n        input_tokens: int,\n        output_tokens: int,\n        duration_ms: float,\n        operation: str = \"inference\",\n    ) -> CostEvent:\n        \"\"\"Record an LLM inference cost event.\"\"\"\n        pricing = self.MODEL_PRICING.get(model, {\"input\": 0, \"output\": 0})\n        cost = (\n            input_tokens * pricing[\"input\"] \u002F 1_000_000\n            + output_tokens * pricing[\"output\"] \u002F 1_000_000\n        )\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=operation,\n            category=\"inference\",\n            input_tokens=input_tokens,\n            output_tokens=output_tokens,\n            cost_usd=round(cost, 6),\n            duration_ms=duration_ms,\n            metadata={\"model\": model},\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    def record_tool_call(\n        self,\n        agent_id: str,\n        tool_name: str,\n        cost_usd: float,\n        duration_ms: float,\n        metadata: Optional[Dict] = None,\n    ) -> CostEvent:\n        \"\"\"Record a tool call cost event.\"\"\"\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=tool_name,\n            category=\"tool_call\",\n            cost_usd=round(cost_usd, 6),\n            duration_ms=duration_ms,\n            metadata=metadata or {},\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    def record_observability(\n        self,\n        agent_id: str,\n        spans: int,\n        metrics: int,\n        log_lines: int,\n        cost_usd: float,\n    ) -> CostEvent:\n        \"\"\"Record observability cost for a request.\"\"\"\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=\"telemetry\",\n            category=\"observability\",\n            cost_usd=round(cost_usd, 6),\n            metadata={\n                \"spans\": spans,\n                \"metrics\": metrics,\n                \"log_lines\": log_lines,\n            },\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    @contextmanager\n    def track_operation(\n        self,\n        agent_id: str,\n        operation: str,\n        category: str,\n    ):\n        \"\"\"Context manager that tracks duration and yields a cost recorder.\"\"\"\n        start = time.monotonic()\n        result = {\"cost_usd\": 0.0, \"metadata\": {}}\n        try:\n            yield result\n        finally:\n            duration_ms = (time.monotonic() - start) * 1000\n            event = CostEvent(\n                timestamp=datetime.now(timezone.utc).isoformat(),\n                agent_id=agent_id,\n                operation=operation,\n                category=category,\n                cost_usd=round(result[\"cost_usd\"], 6),\n                duration_ms=round(duration_ms, 2),\n                metadata=result.get(\"metadata\", {}),\n            )\n            with self._lock:\n                self._events.append(event)\n\n    def get_summary(\n        self,\n        agent_id: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Get a cost summary, optionally filtered by agent.\"\"\"\n        with self._lock:\n            events = [\n                e for e in self._events\n                if agent_id is None or e.agent_id == agent_id\n            ]\n\n        by_category = {}\n        total_cost = 0.0\n        total_tokens = 0\n\n        for e in events:\n            cat = e.category\n            if cat not in by_category:\n                by_category[cat] = {\n                    \"cost_usd\": 0.0,\n                    \"count\": 0,\n                    \"total_duration_ms\": 0.0,\n                }\n            by_category[cat][\"cost_usd\"] += e.cost_usd\n            by_category[cat][\"count\"] += 1\n            by_category[cat][\"total_duration_ms\"] += e.duration_ms\n            total_cost += e.cost_usd\n            total_tokens += e.input_tokens + e.output_tokens\n\n        return {\n            \"agent_id\": agent_id or \"all\",\n            \"total_cost_usd\": round(total_cost, 4),\n            \"total_tokens\": total_tokens,\n            \"total_events\": len(events),\n            \"by_category\": {\n                k: {\n                    \"cost_usd\": round(v[\"cost_usd\"], 4),\n                    \"count\": v[\"count\"],\n                    \"avg_duration_ms\": round(\n                        v[\"total_duration_ms\"] \u002F v[\"count\"], 2\n                    ) if v[\"count\"] > 0 else 0,\n                    \"pct_of_total\": round(\n                        v[\"cost_usd\"] \u002F total_cost * 100, 1\n                    ) if total_cost > 0 else 0,\n                }\n                for k, v in by_category.items()\n            },\n        }\n\n    def export_jsonl(self, filepath: str):\n        \"\"\"Export all events as JSONL for analysis.\"\"\"\n        with self._lock:\n            events = list(self._events)\n        with open(filepath, \"w\") as f:\n            for e in events:\n                f.write(json.dumps({\n                    \"timestamp\": e.timestamp,\n                    \"agent_id\": e.agent_id,\n                    \"operation\": e.operation,\n                    \"category\": e.category,\n                    \"input_tokens\": e.input_tokens,\n                    \"output_tokens\": e.output_tokens,\n                    \"cost_usd\": e.cost_usd,\n                    \"duration_ms\": e.duration_ms,\n                    \"metadata\": e.metadata,\n                }) + \"\\n\")\n```\n\n### Using the CostTracker\n\n```python\ntracker = CostTracker()\n\n# Track an LLM inference call\ntracker.record_inference(\n    agent_id=\"researcher-01\",\n    model=\"gpt-4o\",\n    input_tokens=1850,\n    output_tokens=420,\n    duration_ms=1230.5,\n    operation=\"analyze_document\",\n)\n\n# Track a tool call\ntracker.record_tool_call(\n    agent_id=\"researcher-01\",\n    tool_name=\"web_search\",\n    cost_usd=0.005,\n    duration_ms=340.2,\n    metadata={\"query\": \"climate data 2026\", \"results\": 10},\n)\n\n# Track observability overhead\ntracker.record_observability(\n    agent_id=\"researcher-01\",\n    spans=12,\n    metrics=6,\n    log_lines=18,\n    cost_usd=0.0003,\n)\n\n# Use the context manager for automatic duration tracking\nwith tracker.track_operation(\"researcher-01\", \"vector_search\", \"storage\") as op:\n    # ... perform the operation ...\n    op[\"cost_usd\"] = 0.0012\n    op[\"metadata\"] = {\"index\": \"documents\", \"results\": 25}\n\n# Print the summary\nsummary = tracker.get_summary(agent_id=\"researcher-01\")\nprint(f\"Total cost: ${summary['total_cost_usd']:.4f}\")\nfor cat, data in summary[\"by_category\"].items():\n    print(\n        f\"  {cat}: ${data['cost_usd']:.4f} \"\n        f\"({data['pct_of_total']}% of total, \"\n        f\"{data['count']} events, \"\n        f\"{data['avg_duration_ms']:.1f}ms avg)\"\n    )\n```\n\n### Real-World Cost Breakdown\n\nHere is what a typical cost breakdown looks like for a production agent fleet running twelve agents processing 50,000 requests per day, before any optimization:\n\n```\nCategory          Daily Cost    % of Total    Notes\n─────────────────────────────────────────────────────────────────\nLLM Inference     $312.00       41.2%         GPT-4o for all tasks\nTool Calls        $187.50       24.8%         Search, retrieval, APIs\nOrchestration     $98.00        12.9%         Coordinator agent tokens\nObservability     $118.00       15.6%         Datadog traces + metrics\nStorage           $41.50         5.5%         Vector DB + conversation logs\n─────────────────────────────────────────────────────────────────\nTotal             $757.00       100.0%        $22,710\u002Fmonth\n```\n\nAfter applying the optimizations in this cookbook:\n\n```\nCategory          Daily Cost    % of Total    Savings    How\n─────────────────────────────────────────────────────────────────\nLLM Inference     $118.00       39.3%         62.2%      Model routing + caching\nTool Calls        $112.50       37.5%         40.0%      Dedup + batching\nOrchestration     $29.40        9.8%          70.0%      Prompt compression\nObservability     $23.60        7.9%          80.0%      Adaptive sampling\nStorage           $16.60        5.5%          60.0%      TTL + compression\n─────────────────────────────────────────────────────────────────\nTotal             $300.10       100.0%        60.4%      $9,003\u002Fmonth\n```\n\nThe savings are $457\u002Fday, $13,707\u002Fmonth, $164,484\u002Fyear. That is the value of systematic cost optimization.\n\n---\n\n## Chapter 2: LLM Cost Reduction Strategies\n\n### Prompt Caching\n\nPrompt caching is the single highest-impact cost reduction technique for agents that use stable system prompts. Both Anthropic and OpenAI support server-side prompt caching that reduces the cost of repeated prompt prefixes by 90% (Anthropic) or 50% (OpenAI). If your agent sends the same 1,500-token system prompt with every request, and it makes 10,000 requests per day, caching that prefix saves thousands of dollars per month with zero code changes.\n\n**Anthropic Prompt Caching:**\n\nAnthropic's prompt caching automatically caches prompt prefixes longer than 1,024 tokens. Cached tokens are billed at 10% of the base input token price. The cache has a 5-minute TTL that resets on each hit, so agents making frequent requests keep the cache warm indefinitely.\n\n```python\nimport anthropic\nfrom cost_tracker import CostTracker\n\ntracker = CostTracker()\nclient = anthropic.Anthropic()\n\n# The system prompt is 1,800 tokens. With caching, only the first\n# request per 5-minute window pays full price. All subsequent\n# requests pay 10% for the cached prefix.\nSYSTEM_PROMPT = \"\"\"You are a financial research analyst agent. Your role is to:\n1. Analyze SEC filings, earnings transcripts, and market data\n2. Produce structured research reports with citations\n3. Flag material changes in financial metrics\n4. Compare performance against sector benchmarks\n... (remaining 1,600 tokens of detailed instructions) ...\"\"\"\n\ndef cached_inference(user_message: str, agent_id: str) -> str:\n    \"\"\"Make an inference call with automatic prompt caching.\"\"\"\n    start = __import__(\"time\").monotonic()\n\n    response = client.messages.create(\n        model=\"claude-sonnet-4-20250514\",\n        max_tokens=1024,\n        system=[{\n            \"type\": \"text\",\n            \"text\": SYSTEM_PROMPT,\n            \"cache_control\": {\"type\": \"ephemeral\"},\n        }],\n        messages=[{\"role\": \"user\", \"content\": user_message}],\n    )\n\n    duration_ms = (__import__(\"time\").monotonic() - start) * 1000\n\n    # Track costs with cache-aware pricing\n    usage = response.usage\n    cache_read_tokens = getattr(usage, \"cache_read_input_tokens\", 0)\n    cache_creation_tokens = getattr(usage, \"cache_creation_input_tokens\", 0)\n    uncached_input = usage.input_tokens - cache_read_tokens - cache_creation_tokens\n\n    # Anthropic Claude Sonnet: $3\u002FM input, $0.30\u002FM cached read, $3.75\u002FM cache write\n    cost = (\n        uncached_input * 3.00 \u002F 1_000_000\n        + cache_read_tokens * 0.30 \u002F 1_000_000\n        + cache_creation_tokens * 3.75 \u002F 1_000_000\n        + usage.output_tokens * 15.00 \u002F 1_000_000\n    )\n\n    tracker.record_inference(\n        agent_id=agent_id,\n        model=\"claude-sonnet-4\",\n        input_tokens=usage.input_tokens,\n        output_tokens=usage.output_tokens,\n        duration_ms=duration_ms,\n        operation=\"cached_inference\",\n    )\n\n    print(\n        f\"Tokens: {usage.input_tokens} in \"\n        f\"({cache_read_tokens} cached, {cache_creation_tokens} cache-write, \"\n        f\"{uncached_input} fresh), {usage.output_tokens} out. \"\n        f\"Cost: ${cost:.6f}\"\n    )\n\n    return response.content[0].text\n```\n\n**OpenAI Prompt Caching:**\n\nOpenAI automatically caches prompt prefixes of 1,024+ tokens. Cached tokens are billed at 50% of the input token price. No code changes required -- the caching happens server-side. You can verify cache hits by checking the `usage.prompt_tokens_details.cached_tokens` field.\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI()\n\ndef openai_cached_inference(\n    system_prompt: str,\n    user_message: str,\n) -> dict:\n    \"\"\"OpenAI inference with cache-aware cost tracking.\"\"\"\n    response = client.chat.completions.create(\n        model=\"gpt-4o\",\n        messages=[\n            {\"role\": \"system\", \"content\": system_prompt},\n            {\"role\": \"user\", \"content\": user_message},\n        ],\n    )\n\n    usage = response.usage\n    cached = getattr(usage, \"prompt_tokens_details\", None)\n    cached_tokens = cached.cached_tokens if cached else 0\n    uncached_tokens = usage.prompt_tokens - cached_tokens\n\n    # GPT-4o: $2.50\u002FM input, $1.25\u002FM cached, $10.00\u002FM output\n    cost = (\n        uncached_tokens * 2.50 \u002F 1_000_000\n        + cached_tokens * 1.25 \u002F 1_000_000\n        + usage.completion_tokens * 10.00 \u002F 1_000_000\n    )\n\n    return {\n        \"content\": response.choices[0].message.content,\n        \"cost_usd\": cost,\n        \"cached_tokens\": cached_tokens,\n        \"total_input_tokens\": usage.prompt_tokens,\n        \"output_tokens\": usage.completion_tokens,\n    }\n```\n\n### Prompt Compression\n\nMany agent system prompts are bloated with verbose instructions, redundant examples, and unnecessary formatting. Compressing prompts reduces input tokens without losing semantic content. The technique: rewrite prompts to be maximally information-dense, remove filler words, use abbreviations where unambiguous, and test that output quality is maintained.\n\n```python\nimport re\nfrom typing import Tuple\n\n\nclass PromptCompressor:\n    \"\"\"Compresses prompts to reduce token count while preserving semantics.\"\"\"\n\n    # Common verbose patterns and their compressed equivalents\n    COMPRESSION_RULES = [\n        # Remove filler phrases\n        (r\"\\bplease note that\\b\", \"\"),\n        (r\"\\bit is important to\\b\", \"\"),\n        (r\"\\bmake sure to\\b\", \"\"),\n        (r\"\\bkeep in mind that\\b\", \"\"),\n        (r\"\\byou should always\\b\", \"always\"),\n        (r\"\\bin order to\\b\", \"to\"),\n        (r\"\\bas well as\\b\", \"and\"),\n        (r\"\\bdue to the fact that\\b\", \"because\"),\n        (r\"\\bin the event that\\b\", \"if\"),\n        (r\"\\bfor the purpose of\\b\", \"to\"),\n        (r\"\\bwith respect to\\b\", \"regarding\"),\n        (r\"\\bat this point in time\\b\", \"now\"),\n        # Collapse whitespace\n        (r\"\\n{3,}\", \"\\n\\n\"),\n        (r\"  +\", \" \"),\n    ]\n\n    def compress(self, prompt: str) -> Tuple[str, dict]:\n        \"\"\"Compress a prompt and return the result with stats.\"\"\"\n        original_len = len(prompt.split())\n        compressed = prompt\n\n        for pattern, replacement in self.COMPRESSION_RULES:\n            compressed = re.sub(pattern, replacement, compressed, flags=re.IGNORECASE)\n\n        # Remove empty lines created by removals\n        compressed = re.sub(r\"\\n\\s*\\n\\s*\\n\", \"\\n\\n\", compressed)\n        compressed = compressed.strip()\n\n        compressed_len = len(compressed.split())\n        reduction = (1 - compressed_len \u002F original_len) * 100 if original_len > 0 else 0\n\n        return compressed, {\n            \"original_words\": original_len,\n            \"compressed_words\": compressed_len,\n            \"reduction_pct\": round(reduction, 1),\n        }\n\n\n# Usage\ncompressor = PromptCompressor()\nverbose_prompt = \"\"\"\nPlease note that you are a research analyst. It is important to always\nprovide accurate information. In order to do this, you should always\nverify facts against multiple sources. Make sure to cite your sources\nas well as provide confidence scores. Due to the fact that accuracy\nis critical, in the event that you are unsure, flag it explicitly.\nFor the purpose of clarity, with respect to formatting, at this point\nin time we require JSON output.\n\"\"\"\n\ncompressed, stats = compressor.compress(verbose_prompt)\nprint(f\"Before: {stats['original_words']} words\")\nprint(f\"After:  {stats['compressed_words']} words\")\nprint(f\"Reduction: {stats['reduction_pct']}%\")\nprint(f\"Compressed:\\n{compressed}\")\n```\n\n### Context Window Management\n\nThe most insidious cost driver in conversational agents is unbounded context growth. Every turn of conversation adds tokens to the context window. A 20-turn conversation that starts with a 2,000-token context can grow to 15,000+ tokens, with the agent paying for all accumulated tokens on every subsequent turn. This is quadratic cost growth -- the total cost of a conversation scales with the square of its length.\n\n```python\nfrom typing import List, Dict\n\n\nclass ContextWindowManager:\n    \"\"\"Manages conversation context to prevent unbounded cost growth.\n\n    Implements three strategies:\n    1. Sliding window: keep only the last N turns\n    2. Summarization: compress old turns into a summary\n    3. Relevance filtering: keep only turns relevant to the current task\n    \"\"\"\n\n    def __init__(\n        self,\n        max_tokens: int = 4000,\n        max_turns: int = 10,\n        summary_threshold: int = 6,\n    ):\n        self.max_tokens = max_tokens\n        self.max_turns = max_turns\n        self.summary_threshold = summary_threshold\n        self._turns: List[Dict[str, str]] = []\n        self._summary: str = \"\"\n        self._total_tokens_saved: int = 0\n\n    def add_turn(self, role: str, content: str, token_count: int):\n        \"\"\"Add a conversation turn.\"\"\"\n        self._turns.append({\n            \"role\": role,\n            \"content\": content,\n            \"tokens\": token_count,\n        })\n        self._maybe_compress()\n\n    def _maybe_compress(self):\n        \"\"\"Compress context if it exceeds limits.\"\"\"\n        total_tokens = sum(t[\"tokens\"] for t in self._turns)\n\n        if len(self._turns) > self.max_turns or total_tokens > self.max_tokens:\n            # Keep the last max_turns\u002F2 turns verbatim\n            keep = self.max_turns \u002F\u002F 2\n            old_turns = self._turns[:-keep]\n            kept_turns = self._turns[-keep:]\n\n            # Summarize old turns\n            old_tokens = sum(t[\"tokens\"] for t in old_turns)\n            old_text = \"\\n\".join(\n                f\"{t['role']}: {t['content'][:200]}\" for t in old_turns\n            )\n            # In production, call an LLM to summarize. Here we truncate.\n            self._summary = f\"[Previous context summary: {len(old_turns)} turns] {old_text[:500]}\"\n            self._total_tokens_saved += old_tokens\n\n            self._turns = kept_turns\n\n    def get_context(self) -> List[Dict[str, str]]:\n        \"\"\"Get the current context for the next LLM call.\"\"\"\n        messages = []\n        if self._summary:\n            messages.append({\n                \"role\": \"system\",\n                \"content\": f\"Context from earlier in the conversation:\\n{self._summary}\",\n            })\n        for turn in self._turns:\n            messages.append({\n                \"role\": turn[\"role\"],\n                \"content\": turn[\"content\"],\n            })\n        return messages\n\n    def get_stats(self) -> dict:\n        \"\"\"Get context management statistics.\"\"\"\n        current_tokens = sum(t[\"tokens\"] for t in self._turns)\n        return {\n            \"current_turns\": len(self._turns),\n            \"current_tokens\": current_tokens,\n            \"tokens_saved\": self._total_tokens_saved,\n            \"has_summary\": bool(self._summary),\n            \"cost_saved_usd\": round(\n                self._total_tokens_saved * 2.50 \u002F 1_000_000, 4\n            ),  # Assuming GPT-4o input pricing\n        }\n\n\n# Usage: 20-turn conversation with context management\nctx = ContextWindowManager(max_tokens=4000, max_turns=8)\n\nfor i in range(20):\n    ctx.add_turn(\"user\", f\"Question {i}: What about topic {i}?\", 50)\n    ctx.add_turn(\"assistant\", f\"Answer {i}: Here is info about topic {i}.\", 150)\n\nstats = ctx.get_stats()\nprint(f\"Current turns: {stats['current_turns']}\")\nprint(f\"Current tokens: {stats['current_tokens']}\")\nprint(f\"Tokens saved: {stats['tokens_saved']}\")\nprint(f\"Estimated cost saved: ${stats['cost_saved_usd']}\")\n```\n\n### Reducing Unnecessary Tool Calls\n\nAgents often make redundant tool calls -- querying for information they already have in context, or calling the same tool with the same parameters multiple times in a single reasoning chain. A tool call deduplication layer eliminates these.\n\n```python\nimport hashlib\nimport json\nimport time\nfrom typing import Any, Callable, Optional\n\n\nclass ToolCallDeduplicator:\n    \"\"\"Deduplicates tool calls within a configurable time window.\n\n    If the same tool is called with the same parameters within the\n    TTL window, the cached result is returned instead of making\n    a new call. This prevents agents from making redundant calls\n    during multi-step reasoning.\n    \"\"\"\n\n    def __init__(self, ttl_seconds: int = 300):\n        self.ttl = ttl_seconds\n        self._cache: dict[str, tuple[float, Any]] = {}\n        self._stats = {\"hits\": 0, \"misses\": 0, \"cost_saved\": 0.0}\n\n    def _cache_key(self, tool_name: str, params: dict) -> str:\n        param_str = json.dumps(params, sort_keys=True)\n        return hashlib.sha256(\n            f\"{tool_name}:{param_str}\".encode()\n        ).hexdigest()\n\n    def call(\n        self,\n        tool_name: str,\n        params: dict,\n        tool_fn: Callable,\n        estimated_cost: float = 0.005,\n    ) -> Any:\n        \"\"\"Call a tool with deduplication.\"\"\"\n        key = self._cache_key(tool_name, params)\n        now = time.monotonic()\n\n        # Check cache\n        if key in self._cache:\n            cached_time, cached_result = self._cache[key]\n            if now - cached_time \u003C self.ttl:\n                self._stats[\"hits\"] += 1\n                self._stats[\"cost_saved\"] += estimated_cost\n                return cached_result\n\n        # Cache miss -- make the actual call\n        result = tool_fn(tool_name, params)\n        self._cache[key] = (now, result)\n        self._stats[\"misses\"] += 1\n        return result\n\n    def get_stats(self) -> dict:\n        hit_rate = (\n            self._stats[\"hits\"]\n            \u002F (self._stats[\"hits\"] + self._stats[\"misses\"])\n            * 100\n            if (self._stats[\"hits\"] + self._stats[\"misses\"]) > 0\n            else 0\n        )\n        return {\n            **self._stats,\n            \"hit_rate_pct\": round(hit_rate, 1),\n            \"cache_size\": len(self._cache),\n        }\n\n\n# Usage\ndedup = ToolCallDeduplicator(ttl_seconds=300)\n\ndef mock_tool_call(tool_name: str, params: dict) -> dict:\n    \"\"\"Simulates an actual tool call.\"\"\"\n    return {\"result\": f\"data for {params}\"}\n\n# First call -- cache miss\nresult1 = dedup.call(\"web_search\", {\"query\": \"AI cost data\"}, mock_tool_call)\n\n# Second call with same params -- cache hit, no actual call made\nresult2 = dedup.call(\"web_search\", {\"query\": \"AI cost data\"}, mock_tool_call)\n\n# Different params -- cache miss\nresult3 = dedup.call(\"web_search\", {\"query\": \"different query\"}, mock_tool_call)\n\nprint(dedup.get_stats())\n# {\"hits\": 1, \"misses\": 2, \"cost_saved\": 0.005, \"hit_rate_pct\": 33.3, \"cache_size\": 2}\n```\n\n### Batch Inference for Non-Urgent Tasks\n\nNot every agent task needs real-time response. Background analysis, periodic reporting, bulk classification, and data enrichment can use batch inference APIs at 50% lower cost. Both Anthropic and OpenAI offer batch APIs with 24-hour turnaround at half the standard price.\n\n```python\nimport json\nimport time\nfrom typing import List, Dict\n\n\nclass BatchInferenceManager:\n    \"\"\"Manages batch inference jobs for non-urgent agent tasks.\n\n    Queues tasks and submits them as batch jobs, which run at 50%\n    of the standard API price with a 24-hour completion window.\n    \"\"\"\n\n    def __init__(self, client, batch_size: int = 100):\n        self.client = client\n        self.batch_size = batch_size\n        self._queue: List[Dict] = []\n        self._completed: Dict[str, Any] = {}\n\n    def enqueue(\n        self,\n        task_id: str,\n        model: str,\n        messages: List[Dict],\n        max_tokens: int = 1024,\n    ):\n        \"\"\"Add a task to the batch queue.\"\"\"\n        self._queue.append({\n            \"custom_id\": task_id,\n            \"method\": \"POST\",\n            \"url\": \"\u002Fv1\u002Fchat\u002Fcompletions\",\n            \"body\": {\n                \"model\": model,\n                \"messages\": messages,\n                \"max_tokens\": max_tokens,\n            },\n        })\n\n        # Auto-submit when batch is full\n        if len(self._queue) >= self.batch_size:\n            return self.submit()\n        return None\n\n    def submit(self) -> str:\n        \"\"\"Submit the current queue as a batch job.\"\"\"\n        if not self._queue:\n            return \"\"\n\n        # Write JSONL file for batch submission\n        batch_file = f\"\u002Ftmp\u002Fbatch_{int(time.time())}.jsonl\"\n        with open(batch_file, \"w\") as f:\n            for task in self._queue:\n                f.write(json.dumps(task) + \"\\n\")\n\n        # Upload and create batch\n        with open(batch_file, \"rb\") as f:\n            uploaded = self.client.files.create(file=f, purpose=\"batch\")\n\n        batch = self.client.batches.create(\n            input_file_id=uploaded.id,\n            endpoint=\"\u002Fv1\u002Fchat\u002Fcompletions\",\n            completion_window=\"24h\",\n        )\n\n        submitted_count = len(self._queue)\n        self._queue = []\n\n        print(\n            f\"Batch {batch.id} submitted: {submitted_count} tasks. \"\n            f\"Estimated savings: 50% vs real-time.\"\n        )\n        return batch.id\n\n    def check_status(self, batch_id: str) -> dict:\n        \"\"\"Check the status of a batch job.\"\"\"\n        batch = self.client.batches.retrieve(batch_id)\n        return {\n            \"id\": batch.id,\n            \"status\": batch.status,\n            \"completed\": batch.request_counts.completed,\n            \"failed\": batch.request_counts.failed,\n            \"total\": batch.request_counts.total,\n        }\n\n    def cost_comparison(self, task_count: int, avg_tokens: int) -> dict:\n        \"\"\"Compare batch vs real-time costs.\"\"\"\n        realtime_cost = task_count * avg_tokens * 2.50 \u002F 1_000_000\n        batch_cost = task_count * avg_tokens * 1.25 \u002F 1_000_000\n        return {\n            \"realtime_cost\": round(realtime_cost, 4),\n            \"batch_cost\": round(batch_cost, 4),\n            \"savings\": round(realtime_cost - batch_cost, 4),\n            \"savings_pct\": 50.0,\n        }\n```\n\n---\n\n## Chapter 3: Model Routing -- Right Model for the Job\n\n### The Case for Tiered Routing\n\nThe single most wasteful pattern in agent deployments is using the same model for every task. A GPT-4o call that classifies sentiment (\"positive\", \"negative\", \"neutral\") costs $0.005-0.01 in tokens. The same classification done by GPT-4o-mini costs $0.0003. The quality difference for this specific task is negligible -- both achieve 95%+ accuracy on sentiment classification. Multiply this across thousands of classification calls per day and the savings are enormous.\n\nTiered routing assigns each task to the cheapest model that meets quality requirements. Simple tasks (classification, extraction, formatting) go to small\u002Fcheap models. Complex tasks (reasoning, analysis, creative generation) go to expensive models. The router decides in real-time based on task characteristics.\n\n### The ModelRouter Implementation\n\n```python\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Callable, Any\nfrom enum import Enum\n\n\nclass TaskComplexity(Enum):\n    SIMPLE = \"simple\"        # Classification, extraction, formatting\n    MODERATE = \"moderate\"    # Summarization, Q&A, translation\n    COMPLEX = \"complex\"      # Reasoning, analysis, code generation\n    CRITICAL = \"critical\"    # High-stakes decisions, complex reasoning chains\n\n\n@dataclass\nclass ModelConfig:\n    \"\"\"Configuration for a model in the routing table.\"\"\"\n    name: str\n    provider: str  # openai, anthropic, local\n    cost_per_1k_input: float\n    cost_per_1k_output: float\n    quality_score: float  # 0.0 to 1.0, measured on your eval suite\n    max_tokens: int\n    latency_p50_ms: float\n    supports_tools: bool = True\n    supports_json_mode: bool = True\n\n\nclass ModelRouter:\n    \"\"\"Routes agent tasks to the optimal model based on complexity,\n    quality requirements, and cost constraints.\n\n    The router uses a combination of heuristic classification and\n    configurable routing rules to pick the cheapest model that meets\n    quality and latency requirements for each task.\n    \"\"\"\n\n    # Default model catalog -- override with your own benchmarks\n    DEFAULT_MODELS = {\n        \"gpt-4o\": ModelConfig(\n            name=\"gpt-4o\",\n            provider=\"openai\",\n            cost_per_1k_input=0.0025,\n            cost_per_1k_output=0.010,\n            quality_score=0.95,\n            max_tokens=128000,\n            latency_p50_ms=800,\n        ),\n        \"gpt-4o-mini\": ModelConfig(\n            name=\"gpt-4o-mini\",\n            provider=\"openai\",\n            cost_per_1k_input=0.00015,\n            cost_per_1k_output=0.0006,\n            quality_score=0.82,\n            max_tokens=128000,\n            latency_p50_ms=400,\n        ),\n        \"claude-sonnet-4\": ModelConfig(\n            name=\"claude-sonnet-4\",\n            provider=\"anthropic\",\n            cost_per_1k_input=0.003,\n            cost_per_1k_output=0.015,\n            quality_score=0.94,\n            max_tokens=200000,\n            latency_p50_ms=900,\n        ),\n        \"claude-haiku-3.5\": ModelConfig(\n            name=\"claude-haiku-3.5\",\n            provider=\"anthropic\",\n            cost_per_1k_input=0.0008,\n            cost_per_1k_output=0.004,\n            quality_score=0.85,\n            max_tokens=200000,\n            latency_p50_ms=350,\n        ),\n        \"llama-3-70b\": ModelConfig(\n            name=\"llama-3-70b\",\n            provider=\"local\",\n            cost_per_1k_input=0.0007,\n            cost_per_1k_output=0.0008,\n            quality_score=0.83,\n            max_tokens=8192,\n            latency_p50_ms=250,\n        ),\n        \"llama-3-8b\": ModelConfig(\n            name=\"llama-3-8b\",\n            provider=\"local\",\n            cost_per_1k_input=0.0001,\n            cost_per_1k_output=0.0001,\n            quality_score=0.72,\n            max_tokens=8192,\n            latency_p50_ms=100,\n        ),\n    }\n\n    # Heuristic complexity signals\n    COMPLEX_SIGNALS = [\n        r\"\\banalyze\\b\", r\"\\bcompare\\b\", r\"\\breason\\b\",\n        r\"\\bexplain why\\b\", r\"\\bwhat are the implications\\b\",\n        r\"\\bcritically evaluate\\b\", r\"\\btrade-?offs?\\b\",\n        r\"\\bstep by step\\b\", r\"\\bmulti-?step\\b\",\n    ]\n    SIMPLE_SIGNALS = [\n        r\"\\bclassify\\b\", r\"\\bextract\\b\", r\"\\bformat\\b\",\n        r\"\\bconvert\\b\", r\"\\btranslate\\b\", r\"\\blabel\\b\",\n        r\"\\byes or no\\b\", r\"\\btrue or false\\b\",\n        r\"\\bsentiment\\b\", r\"\\bcategorize\\b\",\n    ]\n\n    def __init__(\n        self,\n        models: Optional[Dict[str, ModelConfig]] = None,\n        quality_floor: float = 0.80,\n        latency_ceiling_ms: float = 5000,\n    ):\n        self.models = models or self.DEFAULT_MODELS\n        self.quality_floor = quality_floor\n        self.latency_ceiling_ms = latency_ceiling_ms\n        self._routing_log: List[dict] = []\n\n    def classify_complexity(self, prompt: str) -> TaskComplexity:\n        \"\"\"Heuristically classify task complexity from the prompt.\"\"\"\n        prompt_lower = prompt.lower()\n        prompt_tokens = len(prompt.split())\n\n        complex_score = sum(\n            1 for p in self.COMPLEX_SIGNALS\n            if re.search(p, prompt_lower)\n        )\n        simple_score = sum(\n            1 for p in self.SIMPLE_SIGNALS\n            if re.search(p, prompt_lower)\n        )\n\n        # Long prompts with many instructions tend to be complex\n        if prompt_tokens > 500:\n            complex_score += 2\n        elif prompt_tokens \u003C 50:\n            simple_score += 1\n\n        if complex_score >= 3:\n            return TaskComplexity.COMPLEX\n        elif complex_score >= 1 and simple_score == 0:\n            return TaskComplexity.MODERATE\n        elif simple_score >= 1:\n            return TaskComplexity.SIMPLE\n        else:\n            return TaskComplexity.MODERATE  # Default to moderate\n\n    def route(\n        self,\n        prompt: str,\n        min_quality: Optional[float] = None,\n        max_latency_ms: Optional[float] = None,\n        required_features: Optional[List[str]] = None,\n        force_complexity: Optional[TaskComplexity] = None,\n    ) -> ModelConfig:\n        \"\"\"Route a task to the optimal model.\n\n        Returns the cheapest model that meets all constraints.\n        \"\"\"\n        quality_floor = min_quality or self.quality_floor\n        latency_ceiling = max_latency_ms or self.latency_ceiling_ms\n        complexity = force_complexity or self.classify_complexity(prompt)\n\n        # Adjust quality floor based on complexity\n        adjusted_quality = {\n            TaskComplexity.SIMPLE: max(quality_floor - 0.10, 0.65),\n            TaskComplexity.MODERATE: quality_floor,\n            TaskComplexity.COMPLEX: min(quality_floor + 0.05, 0.99),\n            TaskComplexity.CRITICAL: min(quality_floor + 0.10, 0.99),\n        }[complexity]\n\n        # Filter eligible models\n        candidates = []\n        for name, config in self.models.items():\n            if config.quality_score \u003C adjusted_quality:\n                continue\n            if config.latency_p50_ms > latency_ceiling:\n                continue\n            if required_features:\n                if \"tools\" in required_features and not config.supports_tools:\n                    continue\n                if \"json_mode\" in required_features and not config.supports_json_mode:\n                    continue\n\n            # Estimate cost for this prompt\n            est_input_tokens = len(prompt.split()) * 1.3  # rough token estimate\n            est_output_tokens = est_input_tokens * 0.5\n            est_cost = (\n                est_input_tokens * config.cost_per_1k_input \u002F 1000\n                + est_output_tokens * config.cost_per_1k_output \u002F 1000\n            )\n            candidates.append((name, config, est_cost))\n\n        if not candidates:\n            # Fallback to the highest quality model\n            best = max(self.models.values(), key=lambda m: m.quality_score)\n            self._log_routing(prompt, complexity, best.name, \"fallback\")\n            return best\n\n        # Sort by cost (cheapest first), break ties by quality (highest first)\n        candidates.sort(key=lambda c: (c[2], -c[1].quality_score))\n        chosen_name, chosen_config, chosen_cost = candidates[0]\n\n        self._log_routing(prompt, complexity, chosen_name, \"optimal\")\n        return chosen_config\n\n    def _log_routing(\n        self,\n        prompt: str,\n        complexity: TaskComplexity,\n        model: str,\n        reason: str,\n    ):\n        self._routing_log.append({\n            \"timestamp\": time.time(),\n            \"complexity\": complexity.value,\n            \"model\": model,\n            \"reason\": reason,\n            \"prompt_preview\": prompt[:80],\n        })\n\n    def get_routing_stats(self) -> dict:\n        \"\"\"Get statistics on routing decisions.\"\"\"\n        if not self._routing_log:\n            return {\"total_routes\": 0}\n\n        model_counts = {}\n        complexity_counts = {}\n        for entry in self._routing_log:\n            model_counts[entry[\"model\"]] = model_counts.get(entry[\"model\"], 0) + 1\n            complexity_counts[entry[\"complexity\"]] = (\n                complexity_counts.get(entry[\"complexity\"], 0) + 1\n            )\n\n        total = len(self._routing_log)\n        return {\n            \"total_routes\": total,\n            \"by_model\": {\n                k: {\"count\": v, \"pct\": round(v \u002F total * 100, 1)}\n                for k, v in model_counts.items()\n            },\n            \"by_complexity\": {\n                k: {\"count\": v, \"pct\": round(v \u002F total * 100, 1)}\n                for k, v in complexity_counts.items()\n            },\n        }\n\n\n# Usage\nrouter = ModelRouter(quality_floor=0.80)\n\n# Simple task -- routes to cheap model\nsimple = router.route(\"Classify this text as positive, negative, or neutral: 'Great product!'\")\nprint(f\"Simple task -> {simple.name} (${simple.cost_per_1k_input}\u002F1K input)\")\n\n# Complex task -- routes to expensive model\ncomplex_task = router.route(\n    \"Analyze the trade-offs between microservice and monolithic architectures \"\n    \"for a high-frequency trading platform. Explain the implications for \"\n    \"latency, fault tolerance, and deployment complexity step by step.\"\n)\nprint(f\"Complex task -> {complex_task.name} (${complex_task.cost_per_1k_input}\u002F1K input)\")\n\n# Critical task with explicit quality floor\ncritical = router.route(\n    \"Review this legal contract for liability clauses\",\n    min_quality=0.93,\n    force_complexity=TaskComplexity.CRITICAL,\n)\nprint(f\"Critical task -> {critical.name}\")\n\n# Print routing stats\nprint(router.get_routing_stats())\n```\n\n### Fallback Chains\n\nModel APIs have outages. A production router needs fallback chains so that if the primary model is unavailable, the agent automatically tries the next-best option instead of failing.\n\n```python\nimport time\nfrom typing import List, Optional, Callable\n\n\nclass FallbackChain:\n    \"\"\"Executes inference with automatic fallback across model providers.\n\n    If the primary model fails (timeout, rate limit, server error),\n    the chain falls through to the next model. This provides both\n    resilience and cost optimization -- the fallback can be a cheaper\n    model that serves as a degraded-but-functional backup.\n    \"\"\"\n\n    def __init__(self, models: List[dict], timeout_ms: float = 5000):\n        \"\"\"\n        models: [{\"name\": \"gpt-4o\", \"client\": client, \"call_fn\": fn}, ...]\n        \"\"\"\n        self.models = models\n        self.timeout_ms = timeout_ms\n        self._fallback_stats = {\"attempts\": 0, \"fallbacks\": 0, \"failures\": 0}\n\n    def execute(self, messages: List[dict], max_tokens: int = 1024) -> dict:\n        \"\"\"Execute inference with fallback.\"\"\"\n        self._fallback_stats[\"attempts\"] += 1\n        errors = []\n\n        for i, model in enumerate(self.models):\n            try:\n                start = time.monotonic()\n                result = model[\"call_fn\"](\n                    model=model[\"name\"],\n                    messages=messages,\n                    max_tokens=max_tokens,\n                )\n                duration_ms = (time.monotonic() - start) * 1000\n\n                if i > 0:\n                    self._fallback_stats[\"fallbacks\"] += 1\n\n                return {\n                    \"content\": result,\n                    \"model_used\": model[\"name\"],\n                    \"fallback_index\": i,\n                    \"duration_ms\": round(duration_ms, 2),\n                    \"errors_before\": errors,\n                }\n            except Exception as e:\n                errors.append({\n                    \"model\": model[\"name\"],\n                    \"error\": str(e),\n                    \"type\": type(e).__name__,\n                })\n                continue\n\n        self._fallback_stats[\"failures\"] += 1\n        raise RuntimeError(\n            f\"All {len(self.models)} models failed. Errors: {errors}\"\n        )\n\n    def get_stats(self) -> dict:\n        total = self._fallback_stats[\"attempts\"]\n        return {\n            **self._fallback_stats,\n            \"fallback_rate_pct\": round(\n                self._fallback_stats[\"fallbacks\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n            \"failure_rate_pct\": round(\n                self._fallback_stats[\"failures\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n        }\n```\n\n### A\u002FB Testing Model Configurations\n\nBefore committing to a routing change, A\u002FB test it. Route a percentage of traffic to the new configuration and compare cost and quality metrics.\n\n```python\nimport random\nimport hashlib\nfrom typing import Dict\n\n\nclass ModelABTest:\n    \"\"\"A\u002FB tests model routing configurations.\n\n    Deterministically assigns requests to variants based on a\n    hash of the request ID, ensuring consistent assignment for\n    the same request across retries.\n    \"\"\"\n\n    def __init__(\n        self,\n        control_model: str,\n        treatment_model: str,\n        treatment_pct: float = 10.0,\n    ):\n        self.control = control_model\n        self.treatment = treatment_model\n        self.treatment_pct = treatment_pct\n        self._results: Dict[str, list] = {\"control\": [], \"treatment\": []}\n\n    def assign(self, request_id: str) -> str:\n        \"\"\"Deterministically assign a request to a variant.\"\"\"\n        hash_val = int(hashlib.md5(request_id.encode()).hexdigest(), 16)\n        bucket = hash_val % 1000\n        if bucket \u003C self.treatment_pct * 10:\n            return self.treatment\n        return self.control\n\n    def record_result(\n        self,\n        variant: str,\n        cost_usd: float,\n        quality_score: float,\n        latency_ms: float,\n    ):\n        \"\"\"Record the result of a request for analysis.\"\"\"\n        group = \"treatment\" if variant == self.treatment else \"control\"\n        self._results[group].append({\n            \"cost_usd\": cost_usd,\n            \"quality_score\": quality_score,\n            \"latency_ms\": latency_ms,\n        })\n\n    def analyze(self) -> dict:\n        \"\"\"Analyze A\u002FB test results.\"\"\"\n        analysis = {}\n        for group in [\"control\", \"treatment\"]:\n            results = self._results[group]\n            if not results:\n                analysis[group] = {\"count\": 0}\n                continue\n            analysis[group] = {\n                \"count\": len(results),\n                \"avg_cost\": round(\n                    sum(r[\"cost_usd\"] for r in results) \u002F len(results), 6\n                ),\n                \"avg_quality\": round(\n                    sum(r[\"quality_score\"] for r in results) \u002F len(results), 4\n                ),\n                \"avg_latency_ms\": round(\n                    sum(r[\"latency_ms\"] for r in results) \u002F len(results), 1\n                ),\n            }\n\n        # Compute lift\n        if analysis[\"control\"][\"count\"] > 0 and analysis[\"treatment\"][\"count\"] > 0:\n            cost_lift = (\n                (analysis[\"treatment\"][\"avg_cost\"] - analysis[\"control\"][\"avg_cost\"])\n                \u002F analysis[\"control\"][\"avg_cost\"] * 100\n            )\n            quality_lift = (\n                (analysis[\"treatment\"][\"avg_quality\"] - analysis[\"control\"][\"avg_quality\"])\n                \u002F analysis[\"control\"][\"avg_quality\"] * 100\n            )\n            analysis[\"lift\"] = {\n                \"cost_change_pct\": round(cost_lift, 1),\n                \"quality_change_pct\": round(quality_lift, 1),\n                \"recommendation\": (\n                    \"ADOPT treatment\"\n                    if cost_lift \u003C -10 and quality_lift > -2\n                    else \"KEEP control\"\n                    if quality_lift \u003C -5\n                    else \"CONTINUE testing\"\n                ),\n            }\n\n        return analysis\n\n\n# Usage\nab_test = ModelABTest(\n    control_model=\"gpt-4o\",\n    treatment_model=\"claude-haiku-3.5\",\n    treatment_pct=20.0,\n)\n\n# Simulate 1000 requests\nfor i in range(1000):\n    request_id = f\"req_{i}\"\n    model = ab_test.assign(request_id)\n\n    if model == \"gpt-4o\":\n        ab_test.record_result(\"gpt-4o\", cost_usd=0.008, quality_score=0.94, latency_ms=820)\n    else:\n        ab_test.record_result(\"claude-haiku-3.5\", cost_usd=0.001, quality_score=0.86, latency_ms=310)\n\nresults = ab_test.analyze()\nprint(f\"Control ({results['control']['count']} reqs): \"\n      f\"${results['control']['avg_cost']:.6f}\u002Freq, \"\n      f\"quality={results['control']['avg_quality']}\")\nprint(f\"Treatment ({results['treatment']['count']} reqs): \"\n      f\"${results['treatment']['avg_cost']:.6f}\u002Freq, \"\n      f\"quality={results['treatment']['avg_quality']}\")\nprint(f\"Recommendation: {results['lift']['recommendation']}\")\n```\n\n---\n\n## Chapter 4: Observability Cost Control\n\n### The Observability Bill Explosion\n\nWhen you deploy AI agents, your observability costs do not increase linearly -- they explode. A traditional web service generates one trace per HTTP request with 3-5 spans. An AI agent request generates 10-30 spans: the initial request, the LLM inference call, each tool call, each tool response parsing step, the orchestration decisions, and the final response assembly. Each span carries attributes for tokens, cost, model, latency, and agent-specific metadata. A single agent request that costs $0.01 in LLM inference can generate $0.005-0.02 in observability costs.\n\nThe math is brutal. A fleet of 12 agents handling 50,000 requests per day generates 500,000-1,500,000 spans per day. At Datadog's pricing of $1.70 per million spans, that is $0.85-2.55\u002Fday just for traces. Add custom metrics ($0.05 per custom metric per host), log management ($0.10 per GB ingested), and you are looking at $100-400\u002Fday in observability costs for a fleet that generates $300-500\u002Fday in direct AI costs. Observability becomes 20-80% of total operational cost.\n\nThe solution is not to stop observing. The solution is to observe intelligently: sample traces adaptively, manage metric cardinality, optimize log levels, and separate AI-specific telemetry from infrastructure telemetry.\n\n### Adaptive Sampling Middleware\n\nUniform sampling (e.g., \"sample 10% of all traces\") throws away valuable data. Errors, slow requests, and high-cost operations should always be sampled. Normal, fast, cheap operations can be sampled aggressively. Adaptive sampling adjusts the sampling rate based on the characteristics of each request.\n\n```python\nimport random\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Optional, Callable\n\n\n@dataclass\nclass SamplingConfig:\n    \"\"\"Configuration for adaptive sampling.\"\"\"\n    base_rate: float = 0.10       # Sample 10% of normal traffic\n    error_rate: float = 1.0       # Sample 100% of errors\n    slow_rate: float = 1.0        # Sample 100% of slow requests\n    expensive_rate: float = 0.50  # Sample 50% of expensive requests\n    slow_threshold_ms: float = 2000.0\n    expensive_threshold_usd: float = 0.05\n    min_rate: float = 0.01        # Never go below 1%\n    max_rate: float = 1.0         # Never exceed 100%\n\n\nclass AdaptiveSampler:\n    \"\"\"Adaptive trace sampler for AI agent observability.\n\n    Dynamically adjusts sampling rates based on request characteristics:\n    - Errors: always sampled\n    - Slow requests: always sampled\n    - Expensive operations: sampled at 50%\n    - Normal operations: sampled at configurable base rate\n    - Under high load: base rate decreases to control costs\n\n    The sampler also implements head-based sampling with consistent\n    hashing, so all spans for a given trace are either all sampled\n    or all dropped.\n    \"\"\"\n\n    def __init__(self, config: Optional[SamplingConfig] = None):\n        self.config = config or SamplingConfig()\n        self._stats = {\n            \"total\": 0,\n            \"sampled\": 0,\n            \"dropped\": 0,\n            \"by_reason\": {},\n        }\n        self._load_window: list = []  # (timestamp, count) for load tracking\n        self._current_rate = self.config.base_rate\n\n    def should_sample(\n        self,\n        trace_id: str,\n        is_error: bool = False,\n        duration_ms: Optional[float] = None,\n        cost_usd: Optional[float] = None,\n        metadata: Optional[Dict] = None,\n    ) -> bool:\n        \"\"\"Decide whether to sample a trace.\"\"\"\n        self._stats[\"total\"] += 1\n\n        # Determine the sampling rate for this request\n        rate, reason = self._compute_rate(is_error, duration_ms, cost_usd)\n\n        # Consistent hashing: same trace_id always gets same decision\n        hash_val = int(hashlib.md5(trace_id.encode()).hexdigest()[:8], 16)\n        threshold = int(rate * 0xFFFFFFFF)\n        sampled = hash_val \u003C= threshold\n\n        if sampled:\n            self._stats[\"sampled\"] += 1\n        else:\n            self._stats[\"dropped\"] += 1\n\n        self._stats[\"by_reason\"][reason] = (\n            self._stats[\"by_reason\"].get(reason, 0) + 1\n        )\n\n        return sampled\n\n    def _compute_rate(\n        self,\n        is_error: bool,\n        duration_ms: Optional[float],\n        cost_usd: Optional[float],\n    ) -> tuple:\n        \"\"\"Compute the sampling rate and reason for this request.\"\"\"\n        if is_error:\n            return self.config.error_rate, \"error\"\n\n        if duration_ms is not None and duration_ms > self.config.slow_threshold_ms:\n            return self.config.slow_rate, \"slow\"\n\n        if cost_usd is not None and cost_usd > self.config.expensive_threshold_usd:\n            return self.config.expensive_rate, \"expensive\"\n\n        # Adjust base rate based on load\n        self._update_load()\n        return self._current_rate, \"normal\"\n\n    def _update_load(self):\n        \"\"\"Reduce sampling rate under high load to control costs.\"\"\"\n        now = time.monotonic()\n        self._load_window.append(now)\n\n        # Keep only the last 60 seconds\n        cutoff = now - 60\n        self._load_window = [t for t in self._load_window if t > cutoff]\n\n        requests_per_minute = len(self._load_window)\n\n        # Scale down base rate as load increases\n        if requests_per_minute > 10000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.1)\n        elif requests_per_minute > 5000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.25)\n        elif requests_per_minute > 1000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.5)\n        else:\n            self._current_rate = self.config.base_rate\n\n    def get_stats(self) -> dict:\n        total = self._stats[\"total\"]\n        return {\n            \"total_decisions\": total,\n            \"sampled\": self._stats[\"sampled\"],\n            \"dropped\": self._stats[\"dropped\"],\n            \"effective_rate_pct\": round(\n                self._stats[\"sampled\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n            \"current_base_rate\": round(self._current_rate, 4),\n            \"by_reason\": self._stats[\"by_reason\"],\n        }\n\n    def estimate_cost_savings(\n        self,\n        cost_per_span: float = 0.0000017,  # $1.70 per million spans\n        avg_spans_per_trace: int = 15,\n    ) -> dict:\n        \"\"\"Estimate observability cost savings from sampling.\"\"\"\n        total = self._stats[\"total\"]\n        dropped = self._stats[\"dropped\"]\n\n        full_cost = total * avg_spans_per_trace * cost_per_span\n        actual_cost = (total - dropped) * avg_spans_per_trace * cost_per_span\n\n        return {\n            \"full_cost_usd\": round(full_cost, 4),\n            \"sampled_cost_usd\": round(actual_cost, 4),\n            \"savings_usd\": round(full_cost - actual_cost, 4),\n            \"savings_pct\": round(\n                (full_cost - actual_cost) \u002F full_cost * 100, 1\n            ) if full_cost > 0 else 0,\n        }\n\n\n# Usage\nsampler = AdaptiveSampler(SamplingConfig(\n    base_rate=0.10,\n    error_rate=1.0,\n    slow_rate=1.0,\n    expensive_rate=0.50,\n    slow_threshold_ms=2000,\n    expensive_threshold_usd=0.05,\n))\n\n# Simulate 10,000 requests with realistic distributions\nimport uuid\nfor i in range(10000):\n    trace_id = uuid.uuid4().hex\n    is_error = random.random() \u003C 0.02  # 2% error rate\n    duration = random.gauss(500, 300)  # Mean 500ms, some slow outliers\n    cost = random.gauss(0.01, 0.02)    # Mean $0.01, some expensive outliers\n\n    sampler.should_sample(\n        trace_id=trace_id,\n        is_error=is_error,\n        duration_ms=max(50, duration),\n        cost_usd=max(0.001, cost),\n    )\n\nstats = sampler.get_stats()\nprint(f\"Effective sampling rate: {stats['effective_rate_pct']}%\")\nprint(f\"Sampled: {stats['sampled']}, Dropped: {stats['dropped']}\")\nprint(f\"By reason: {stats['by_reason']}\")\n\nsavings = sampler.estimate_cost_savings()\nprint(f\"Observability cost savings: ${savings['savings_usd']:.4f} \"\n      f\"({savings['savings_pct']}%)\")\n```\n\n### Metrics Cardinality Management\n\nMetric cardinality -- the number of unique time series -- is the silent killer of observability budgets. Every unique combination of metric name and label values creates a new time series. If you have a metric `agent.request.duration` with labels `agent_id` (50 values), `model` (6 values), `status` (3 values), and `endpoint` (20 values), the cardinality is 50 * 6 * 3 * 20 = 18,000 time series. Add a `request_id` label by accident and cardinality becomes infinite.\n\n```python\nfrom typing import Set, Dict, List, Optional\nfrom collections import defaultdict\n\n\nclass CardinalityGuard:\n    \"\"\"Prevents metric cardinality explosion by enforcing limits\n    on label values and dropping high-cardinality dimensions.\n\n    Typical cost: Prometheus\u002FGrafana charges ~$8 per 1000 active\n    time series per month. Uncontrolled cardinality can create\n    millions of series, costing thousands of dollars per month\n    for metrics alone.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_cardinality_per_metric: int = 5000,\n        max_label_values: int = 100,\n        blocked_labels: Optional[Set[str]] = None,\n    ):\n        self.max_cardinality = max_cardinality_per_metric\n        self.max_label_values = max_label_values\n        self.blocked_labels = blocked_labels or {\n            \"request_id\", \"trace_id\", \"session_id\",\n            \"user_id\", \"conversation_id\", \"message_id\",\n        }\n        self._label_value_counts: Dict[str, Dict[str, int]] = defaultdict(dict)\n        self._series_counts: Dict[str, int] = defaultdict(int)\n        self._dropped: int = 0\n\n    def sanitize_labels(\n        self,\n        metric_name: str,\n        labels: Dict[str, str],\n    ) -> Optional[Dict[str, str]]:\n        \"\"\"Sanitize labels to prevent cardinality explosion.\n\n        Returns sanitized labels, or None if the metric should be dropped.\n        \"\"\"\n        # Remove blocked high-cardinality labels\n        sanitized = {\n            k: v for k, v in labels.items()\n            if k not in self.blocked_labels\n        }\n\n        # Check per-label cardinality\n        for key, value in list(sanitized.items()):\n            if key not in self._label_value_counts[metric_name]:\n                self._label_value_counts[metric_name][key] = {}\n            values = self._label_value_counts[metric_name][key]\n\n            if value not in values:\n                if len(values) >= self.max_label_values:\n                    # Replace with \"other\" to cap cardinality\n                    sanitized[key] = \"__other__\"\n                else:\n                    values[value] = 0\n            values.get(value, None)\n\n        # Check total series cardinality for this metric\n        series_key = f\"{metric_name}:{sorted(sanitized.items())}\"\n        self._series_counts[metric_name] += 1\n\n        if len(set(\n            str(sorted(labels.items()))\n            for labels in [sanitized]\n        )) > self.max_cardinality:\n            self._dropped += 1\n            return None\n\n        return sanitized\n\n    def get_stats(self) -> dict:\n        return {\n            \"tracked_metrics\": len(self._series_counts),\n            \"dropped_points\": self._dropped,\n            \"label_cardinality\": {\n                metric: {\n                    label: len(values)\n                    for label, values in labels.items()\n                }\n                for metric, labels in self._label_value_counts.items()\n            },\n        }\n\n\n# Usage\nguard = CardinalityGuard(\n    max_cardinality_per_metric=5000,\n    max_label_values=50,\n    blocked_labels={\"request_id\", \"trace_id\", \"session_id\"},\n)\n\n# This label set is safe\nsafe = guard.sanitize_labels(\"agent.duration\", {\n    \"agent_id\": \"researcher-01\",\n    \"model\": \"gpt-4o\",\n    \"status\": \"success\",\n})\nprint(f\"Safe labels: {safe}\")\n\n# This would cause cardinality explosion -- request_id is blocked\ndangerous = guard.sanitize_labels(\"agent.duration\", {\n    \"agent_id\": \"researcher-01\",\n    \"request_id\": \"req_abc123\",  # Blocked -- infinite cardinality\n    \"model\": \"gpt-4o\",\n})\nprint(f\"Sanitized labels: {dangerous}\")  # request_id removed\n```\n\n### Log Level Optimization\n\nAgent systems produce massive log volumes. A single LLM call can generate DEBUG-level logs for the full prompt, the full response, token counts, timing breakdowns, cache hits, and model metadata. At INFO level, you get the operation, model, token count, and duration. At WARN level, you get only slow requests and errors.\n\nThe optimization: use structured logging with dynamic level control per agent, and route AI-specific logs to a cheaper storage tier.\n\n```python\nimport logging\nimport json\nfrom typing import Dict, Optional\n\n\nclass CostAwareLogger:\n    \"\"\"Logger that optimizes log volume based on cost impact.\n\n    Routes logs to different backends based on category:\n    - AI inference logs: sampled, stored in cheap tier\n    - Error logs: always stored, stored in hot tier\n    - Debug logs: only in development, never in production\n\n    Estimated savings: 60-80% of log ingestion costs.\n    \"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        production: bool = True,\n        sample_rate: float = 0.10,\n    ):\n        self.agent_id = agent_id\n        self.production = production\n        self.sample_rate = sample_rate\n        self._log_counts: Dict[str, int] = {}\n\n        self.logger = logging.getLogger(f\"agent.{agent_id}\")\n        if production:\n            self.logger.setLevel(logging.WARNING)\n        else:\n            self.logger.setLevel(logging.DEBUG)\n\n    def inference(\n        self,\n        model: str,\n        input_tokens: int,\n        output_tokens: int,\n        duration_ms: float,\n        cost_usd: float,\n    ):\n        \"\"\"Log an inference event. Sampled in production.\"\"\"\n        self._count(\"inference\")\n\n        if self.production and __import__(\"random\").random() > self.sample_rate:\n            return  # Drop this log in production (sampled)\n\n        self.logger.info(json.dumps({\n            \"event\": \"inference\",\n            \"agent_id\": self.agent_id,\n            \"model\": model,\n            \"input_tokens\": input_tokens,\n            \"output_tokens\": output_tokens,\n            \"duration_ms\": round(duration_ms, 1),\n            \"cost_usd\": round(cost_usd, 6),\n        }))\n\n    def tool_call(self, tool: str, duration_ms: float, status: str):\n        \"\"\"Log a tool call. Always logged (low volume).\"\"\"\n        self._count(\"tool_call\")\n        self.logger.info(json.dumps({\n            \"event\": \"tool_call\",\n            \"agent_id\": self.agent_id,\n            \"tool\": tool,\n            \"duration_ms\": round(duration_ms, 1),\n            \"status\": status,\n        }))\n\n    def error(self, operation: str, error: str, context: Optional[Dict] = None):\n        \"\"\"Log an error. Always logged, never sampled.\"\"\"\n        self._count(\"error\")\n        self.logger.error(json.dumps({\n            \"event\": \"error\",\n            \"agent_id\": self.agent_id,\n            \"operation\": operation,\n            \"error\": error,\n            \"context\": context or {},\n        }))\n\n    def _count(self, event_type: str):\n        self._log_counts[event_type] = self._log_counts.get(event_type, 0) + 1\n\n    def get_log_volume_stats(self) -> dict:\n        total = sum(self._log_counts.values())\n        return {\n            \"total_events\": total,\n            \"by_type\": self._log_counts.copy(),\n            \"estimated_bytes\": total * 200,  # ~200 bytes per structured log\n            \"estimated_monthly_gb\": round(total * 200 * 30 \u002F 1e9, 3),\n        }\n```\n\n---\n\n## Chapter 5: Token Optimization\n\n### Measuring Token Waste\n\nBefore optimizing tokens, quantify the waste. Token waste is the difference between the tokens you send and the minimum tokens required to achieve the same output quality. Most agent systems waste 30-50% of input tokens on redundant system prompt content, verbose tool descriptions, unnecessary few-shot examples, and suboptimal response formatting instructions.\n\n```python\nimport re\nfrom typing import Dict, List, Tuple\n\n\nclass TokenWasteAnalyzer:\n    \"\"\"Analyzes an agent's prompts for token waste opportunities.\n\n    Identifies: redundant instructions, verbose phrasing, unnecessary\n    few-shot examples, bloated tool descriptions, and suboptimal\n    response format specifications.\n    \"\"\"\n\n    def __init__(self, tokens_per_word: float = 1.3):\n        self.tokens_per_word = tokens_per_word\n\n    def estimate_tokens(self, text: str) -> int:\n        return int(len(text.split()) * self.tokens_per_word)\n\n    def analyze_system_prompt(self, prompt: str) -> Dict:\n        \"\"\"Analyze a system prompt for waste.\"\"\"\n        total_tokens = self.estimate_tokens(prompt)\n        findings = []\n\n        # Check for redundant phrases\n        redundant = self._find_redundant_phrases(prompt)\n        if redundant:\n            findings.append({\n                \"type\": \"redundant_phrases\",\n                \"count\": len(redundant),\n                \"examples\": redundant[:5],\n                \"estimated_waste_tokens\": sum(\n                    self.estimate_tokens(phrase) for phrase in redundant\n                ),\n            })\n\n        # Check for verbose instructions\n        verbose = self._find_verbose_instructions(prompt)\n        if verbose:\n            findings.append({\n                \"type\": \"verbose_instructions\",\n                \"count\": len(verbose),\n                \"examples\": verbose[:3],\n                \"estimated_waste_tokens\": int(\n                    sum(self.estimate_tokens(v[0]) - self.estimate_tokens(v[1])\n                        for v in verbose)\n                ),\n            })\n\n        # Check for unnecessary few-shot examples\n        examples = self._count_examples(prompt)\n        if examples > 3:\n            waste = (examples - 2) * 150  # ~150 tokens per extra example\n            findings.append({\n                \"type\": \"excessive_examples\",\n                \"count\": examples,\n                \"recommended\": 2,\n                \"estimated_waste_tokens\": waste,\n            })\n\n        total_waste = sum(f.get(\"estimated_waste_tokens\", 0) for f in findings)\n        return {\n            \"total_tokens\": total_tokens,\n            \"estimated_waste_tokens\": total_waste,\n            \"waste_pct\": round(total_waste \u002F total_tokens * 100, 1) if total_tokens > 0 else 0,\n            \"findings\": findings,\n            \"potential_savings_per_1k_calls\": round(\n                total_waste * 2.50 \u002F 1_000_000 * 1000, 4\n            ),\n        }\n\n    def _find_redundant_phrases(self, text: str) -> List[str]:\n        \"\"\"Find phrases that appear multiple times.\"\"\"\n        # Split into sentences\n        sentences = re.split(r'[.!?]\\s+', text)\n        seen_concepts = {}\n        redundant = []\n        for s in sentences:\n            key = \" \".join(sorted(s.lower().split())[:5])\n            if key in seen_concepts and len(s.split()) > 5:\n                redundant.append(s.strip()[:100])\n            seen_concepts[key] = s\n        return redundant\n\n    def _find_verbose_instructions(self, text: str) -> List[Tuple[str, str]]:\n        \"\"\"Find verbose phrasings and suggest concise alternatives.\"\"\"\n        patterns = [\n            (r\"You must always make sure to (.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n            (r\"It is (?:very |extremely )?important (?:that you |to )(.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n            (r\"Please (?:make sure to |ensure that you )(.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n        ]\n        verbose = []\n        for pattern, fix in patterns:\n            for match in re.finditer(pattern, text, re.IGNORECASE):\n                verbose.append((match.group(0), fix(match)))\n        return verbose\n\n    def _count_examples(self, text: str) -> int:\n        \"\"\"Count few-shot examples in the prompt.\"\"\"\n        example_markers = [\n            r\"Example \\d+:\", r\"For example:\", r\"E\\.g\\.:\",\n            r\"Input:.*Output:\", r\"User:.*Assistant:\",\n            r\"```\\n.*?\\n```\",\n        ]\n        count = 0\n        for marker in example_markers:\n            count += len(re.findall(marker, text, re.IGNORECASE | re.DOTALL))\n        return count\n\n\n# Usage\nanalyzer = TokenWasteAnalyzer()\n\nbloated_prompt = \"\"\"\nYou are a helpful financial analysis assistant. You must always make sure to\nprovide accurate financial data. It is very important that you cite your sources.\nPlease make sure to format all numbers with two decimal places.\n\nYou must always make sure to check your calculations twice. It is extremely\nimportant to verify all financial figures. Please ensure that you provide\ncontext for every number you present.\n\nExample 1:\nUser: What is AAPL's P\u002FE ratio?\nAssistant: Apple's P\u002FE ratio is 28.5 as of April 2026.\n\nExample 2:\nUser: Compare AAPL and MSFT revenue.\nAssistant: Apple revenue: $394B. Microsoft revenue: $245B.\n\nExample 3:\nUser: What is the S&P 500 YTD return?\nAssistant: The S&P 500 YTD return is 8.2% as of April 2026.\n\nExample 4:\nUser: Calculate compound interest.\nAssistant: Using the formula A = P(1 + r\u002Fn)^(nt)...\n\nExample 5:\nUser: What is a good debt-to-equity ratio?\nAssistant: Generally, a D\u002FE ratio below 2.0 is considered healthy.\n\"\"\"\n\nanalysis = analyzer.analyze_system_prompt(bloated_prompt)\nprint(f\"Total tokens: {analysis['total_tokens']}\")\nprint(f\"Waste tokens: {analysis['estimated_waste_tokens']} ({analysis['waste_pct']}%)\")\nprint(f\"Savings per 1K calls: ${analysis['potential_savings_per_1k_calls']}\")\nfor finding in analysis[\"findings\"]:\n    print(f\"  {finding['type']}: {finding.get('estimated_waste_tokens', 0)} tokens\")\n```\n\n### System Prompt Optimization\n\nThe single largest token waste source is the system prompt. It is sent with every request, so even small reductions compound dramatically. Here is a systematic optimization process.\n\n```python\nclass SystemPromptOptimizer:\n    \"\"\"Optimizes system prompts through progressive compression.\n\n    Process:\n    1. Remove filler words and phrases\n    2. Consolidate duplicate instructions\n    3. Convert verbose rules to terse directives\n    4. Reduce few-shot examples to minimum effective set\n    5. Validate output quality is maintained\n    \"\"\"\n\n    def optimize(self, prompt: str) -> Tuple[str, dict]:\n        \"\"\"Optimize a system prompt. Returns (optimized, stats).\"\"\"\n        original_words = len(prompt.split())\n        result = prompt\n\n        # Step 1: Remove filler\n        result = self._remove_filler(result)\n\n        # Step 2: Consolidate duplicates\n        result = self._consolidate_duplicates(result)\n\n        # Step 3: Terse directives\n        result = self._to_terse_directives(result)\n\n        # Step 4: Clean up whitespace\n        result = re.sub(r'\\n{3,}', '\\n\\n', result)\n        result = re.sub(r'  +', ' ', result)\n        result = result.strip()\n\n        optimized_words = len(result.split())\n        reduction = (1 - optimized_words \u002F original_words) * 100\n\n        return result, {\n            \"original_words\": original_words,\n            \"optimized_words\": optimized_words,\n            \"reduction_pct\": round(reduction, 1),\n            \"estimated_token_savings\": int(\n                (original_words - optimized_words) * 1.3\n            ),\n        }\n\n    def _remove_filler(self, text: str) -> str:\n        fillers = [\n            r'\\bplease\\b', r'\\bkindly\\b', r'\\bmake sure to\\b',\n            r'\\bit is (?:very |extremely )?important (?:that |to )',\n            r'\\byou must always\\b', r'\\byou should always\\b',\n            r'\\bensure that you\\b', r'\\bremember to\\b',\n            r'\\bkeep in mind (?:that )?\\b', r'\\bnote that\\b',\n        ]\n        for filler in fillers:\n            text = re.sub(filler, '', text, flags=re.IGNORECASE)\n        return text\n\n    def _consolidate_duplicates(self, text: str) -> str:\n        sentences = re.split(r'(?\u003C=[.!?])\\s+', text)\n        seen = set()\n        unique = []\n        for s in sentences:\n            normalized = ' '.join(s.lower().split())\n            if normalized not in seen and len(normalized) > 10:\n                seen.add(normalized)\n                unique.append(s)\n        return ' '.join(unique)\n\n    def _to_terse_directives(self, text: str) -> str:\n        replacements = [\n            (r'When the user asks you to (.+?), you should (.+?)\\.', r'\\1: \\2.'),\n            (r'If (?:the user |a user |someone )(.+?), then (.+?)\\.', r'\\1 -> \\2.'),\n            (r'Always provide (.+?) in your responses', r'Include \\1'),\n            (r'You are a (.+?) assistant', r'Role: \\1'),\n        ]\n        for pattern, replacement in replacements:\n            text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)\n        return text\n\n\noptimizer = SystemPromptOptimizer()\noptimized, stats = optimizer.optimize(bloated_prompt)\nprint(f\"Before: {stats['original_words']} words\")\nprint(f\"After: {stats['optimized_words']} words\")\nprint(f\"Reduction: {stats['reduction_pct']}%\")\nprint(f\"Token savings: {stats['estimated_token_savings']}\")\n```\n\n### Response Format Optimization\n\nJSON output is often 30-50% more tokens than equivalent structured text. If your downstream consumer can parse structured text, switch from JSON to a compact text format.\n\n```python\nclass ResponseFormatOptimizer:\n    \"\"\"Optimizes response format instructions to minimize output tokens.\n\n    JSON: ~1.5x tokens vs structured text for the same information.\n    Markdown tables: ~1.2x tokens vs TSV.\n    Verbose JSON with descriptions: ~2.5x tokens vs compact JSON.\n    \"\"\"\n\n    FORMAT_COSTS = {\n        \"verbose_json\": 2.5,   # {\"name\": \"John\", \"age\": 30, \"city\": \"NYC\"}\n        \"compact_json\": 1.5,   # {\"n\":\"John\",\"a\":30,\"c\":\"NYC\"}\n        \"structured_text\": 1.0, # John|30|NYC\n        \"markdown_table\": 1.2,  # | John | 30 | NYC |\n        \"tsv\": 0.9,            # John\\t30\\tNYC\n    }\n\n    @staticmethod\n    def json_to_compact_instruction() -> str:\n        \"\"\"Generate a prompt instruction for compact JSON output.\"\"\"\n        return (\n            \"Output: JSON. No whitespace. Short keys. \"\n            \"Example: {\\\"n\\\":\\\"val\\\",\\\"s\\\":1} not {\\\"name\\\": \\\"val\\\", \\\"score\\\": 1}\"\n        )\n\n    @staticmethod\n    def estimate_format_savings(\n        records: int,\n        fields: int,\n        avg_value_length: int = 10,\n        from_format: str = \"verbose_json\",\n        to_format: str = \"compact_json\",\n    ) -> dict:\n        \"\"\"Estimate token savings from format change.\"\"\"\n        base_tokens = records * fields * (avg_value_length + 5)\n        from_tokens = base_tokens * ResponseFormatOptimizer.FORMAT_COSTS[from_format]\n        to_tokens = base_tokens * ResponseFormatOptimizer.FORMAT_COSTS[to_format]\n\n        savings = from_tokens - to_tokens\n        savings_pct = savings \u002F from_tokens * 100\n\n        return {\n            \"from_format\": from_format,\n            \"to_format\": to_format,\n            \"from_tokens\": int(from_tokens),\n            \"to_tokens\": int(to_tokens),\n            \"savings_tokens\": int(savings),\n            \"savings_pct\": round(savings_pct, 1),\n            \"savings_per_1k_calls_usd\": round(\n                savings * 10.00 \u002F 1_000_000 * 1000, 4  # Output token pricing\n            ),\n        }\n\n\n# Example: 50 records, 5 fields each\nsavings = ResponseFormatOptimizer.estimate_format_savings(\n    records=50, fields=5, from_format=\"verbose_json\", to_format=\"compact_json\"\n)\nprint(f\"Format change: {savings['from_format']} -> {savings['to_format']}\")\nprint(f\"Token savings: {savings['savings_tokens']} ({savings['savings_pct']}%)\")\nprint(f\"Savings per 1K calls: ${savings['savings_per_1k_calls_usd']}\")\n```\n\n### Tool Description Compression\n\nAgent tool descriptions are sent as part of the system prompt on every request. Twelve tools with verbose descriptions can add 3,000-5,000 tokens to every call. Compressing tool descriptions to the minimum needed for the model to use them correctly saves tokens on every single request.\n\n```python\nclass ToolDescriptionCompressor:\n    \"\"\"Compresses tool descriptions to minimize system prompt tokens.\n\n    A typical tool description with full parameter docs is 200-400 tokens.\n    Compressed to essential info only, it drops to 50-100 tokens.\n    With 12 tools, that is 1,800-3,600 tokens saved per request.\n    \"\"\"\n\n    def compress_tool(self, tool: dict) -> dict:\n        \"\"\"Compress a tool description.\"\"\"\n        compressed = {\n            \"name\": tool[\"name\"],\n            \"description\": self._shorten_description(\n                tool.get(\"description\", \"\")\n            ),\n            \"parameters\": self._compress_parameters(\n                tool.get(\"parameters\", {})\n            ),\n        }\n        return compressed\n\n    def _shorten_description(self, desc: str) -> str:\n        \"\"\"Shorten description to first sentence + key constraints.\"\"\"\n        sentences = desc.split(\". \")\n        if sentences:\n            short = sentences[0]\n            # Keep constraint sentences (containing \"must\", \"required\", \"max\")\n            for s in sentences[1:]:\n                if any(w in s.lower() for w in [\"must\", \"required\", \"max\", \"min\", \"limit\"]):\n                    short += \". \" + s\n            return short + \".\"\n        return desc\n\n    def _compress_parameters(self, params: dict) -> dict:\n        \"\"\"Remove verbose parameter descriptions, keep type and required.\"\"\"\n        if \"properties\" not in params:\n            return params\n        compressed = {\n            \"type\": params.get(\"type\", \"object\"),\n            \"properties\": {},\n            \"required\": params.get(\"required\", []),\n        }\n        for name, prop in params[\"properties\"].items():\n            compressed[\"properties\"][name] = {\n                \"type\": prop.get(\"type\", \"string\"),\n            }\n            if \"enum\" in prop:\n                compressed[\"properties\"][name][\"enum\"] = prop[\"enum\"]\n        return compressed\n\n    def compress_toolkit(self, tools: list) -> tuple:\n        \"\"\"Compress all tools and report savings.\"\"\"\n        import json\n        original_tokens = sum(\n            len(json.dumps(t).split()) * 1.3 for t in tools\n        )\n        compressed = [self.compress_tool(t) for t in tools]\n        compressed_tokens = sum(\n            len(json.dumps(t).split()) * 1.3 for t in compressed\n        )\n        savings = original_tokens - compressed_tokens\n\n        return compressed, {\n            \"original_tokens\": int(original_tokens),\n            \"compressed_tokens\": int(compressed_tokens),\n            \"savings_tokens\": int(savings),\n            \"savings_pct\": round(savings \u002F original_tokens * 100, 1),\n            \"savings_per_1k_calls_usd\": round(\n                savings * 2.50 \u002F 1_000_000 * 1000, 4\n            ),\n        }\n\n\n# Example: compress a verbose tool description\ncompressor = ToolDescriptionCompressor()\nverbose_tool = {\n    \"name\": \"search_documents\",\n    \"description\": (\n        \"Search the document database for relevant documents matching \"\n        \"the given query. This tool searches across all indexed documents \"\n        \"including PDFs, Word documents, and plain text files. The search \"\n        \"uses semantic similarity matching powered by embeddings. Results \"\n        \"are returned in order of relevance. You must provide a query \"\n        \"parameter. Maximum 50 results per query.\"\n    ),\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\n                \"type\": \"string\",\n                \"description\": \"The search query to match against documents. \"\n                               \"Should be a natural language description of what \"\n                               \"you are looking for. More specific queries produce \"\n                               \"better results.\",\n            },\n            \"max_results\": {\n                \"type\": \"integer\",\n                \"description\": \"The maximum number of results to return. \"\n                               \"Defaults to 10. Maximum allowed value is 50.\",\n            },\n            \"file_type\": {\n                \"type\": \"string\",\n                \"enum\": [\"pdf\", \"docx\", \"txt\", \"all\"],\n                \"description\": \"Filter results by file type. Use 'all' to \"\n                               \"search across all file types.\",\n            },\n        },\n        \"required\": [\"query\"],\n    },\n}\n\ncompressed = compressor.compress_tool(verbose_tool)\nprint(f\"Original description: {len(verbose_tool['description'].split())} words\")\nprint(f\"Compressed description: {len(compressed['description'].split())} words\")\n```\n\n---\n\n## Chapter 6: Outcome-Based Metering\n\n### The Problem with Input-Based Billing\n\nEvery cost optimization strategy in the previous chapters shares a blind spot: they measure cost in terms of inputs consumed -- tokens processed, API calls made, spans recorded, bytes stored. Input-based billing tells you what you spent, but it tells you nothing about what you got for that spending. A research agent that burns $4.20 in tokens and produces a report that saves the user three hours of manual work is wildly profitable. The same agent burning $0.80 and producing a hallucinated report that the user discards is infinitely expensive -- the cost-per-useful-outcome is undefined because the outcome was worthless.\n\nOutcome-based metering flips the equation. Instead of asking \"how much did we spend?\", it asks \"how much did we spend per successful outcome?\" This reframing changes every optimization decision. A model upgrade that increases token cost by 40% but doubles the success rate from 45% to 90% actually cuts cost-per-outcome by 30%. A prompt compression that saves 20% on tokens but drops success rate by 15% is a net loss. Without outcome metering, you would celebrate the token savings and never notice the quality degradation until customer complaints arrived weeks later.\n\nThe shift requires three capabilities: defining what constitutes a successful outcome, attributing outcomes across multi-step agent pipelines, and building the metering infrastructure to track cost-per-outcome in real time.\n\n### Defining Outcomes\n\nNot every agent invocation has a binary success\u002Ffailure. Outcomes exist on a spectrum, and your metering system must capture that nuance. Here is a taxonomy that works across most agent use cases.\n\n**1. Task Completion.** Did the agent finish the requested task? A code generation agent that produces compilable code has completed its task. One that errors out mid-generation has not. Completion rate is the baseline metric -- if your agents are not completing tasks, nothing else matters.\n\n**2. Quality Score.** Given that the task completed, how good was the output? Quality is domain-specific: for a summarization agent, it might be a ROUGE score against human summaries. For a classification agent, it is accuracy against labeled data. For a research agent, it might be the percentage of cited claims that are verifiable. Quality scores should be normalized to 0.0-1.0.\n\n**3. User Acceptance.** Did the end user accept the agent's output? This is the ultimate arbiter. An agent that produces technically correct output that the user rewrites from scratch has a zero acceptance rate. Track explicit signals (user clicked \"accept\", \"reject\", \"edit\") and implicit signals (user copied the output, user ignored it, user asked a follow-up that implies the first answer was wrong).\n\n**4. Business Value.** What was the downstream impact? A lead qualification agent that correctly identifies a $500K deal opportunity delivers more value than one that correctly classifies a $5K opportunity, even though both are \"correct.\" Business value metering connects agent cost to revenue impact.\n\n```python\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List, Any\nfrom enum import Enum\nfrom datetime import datetime, timezone\n\n\nclass OutcomeStatus(Enum):\n    SUCCESS = \"success\"\n    PARTIAL = \"partial\"        # Task completed but with quality issues\n    FAILURE = \"failure\"        # Task did not complete\n    REJECTED = \"rejected\"      # User explicitly rejected the output\n    PENDING = \"pending\"        # Awaiting user feedback\n\n\n@dataclass\nclass OutcomeEvent:\n    \"\"\"Records the outcome of an agent task alongside its cost.\"\"\"\n    outcome_id: str\n    agent_id: str\n    task_type: str\n    status: OutcomeStatus\n    cost_usd: float\n    quality_score: float           # 0.0 to 1.0\n    user_accepted: Optional[bool] = None\n    business_value_usd: float = 0.0\n    input_tokens: int = 0\n    output_tokens: int = 0\n    latency_ms: float = 0.0\n    retries: int = 0\n    timestamp: str = field(\n        default_factory=lambda: datetime.now(timezone.utc).isoformat()\n    )\n    metadata: Dict[str, Any] = field(default_factory=dict)\n\n\nclass OutcomeMeter:\n    \"\"\"Tracks cost-per-outcome across agent operations.\n\n    Thread-safe. Computes real-time cost efficiency metrics\n    including cost-per-success, cost-per-quality-point, and\n    ROI based on business value attribution.\n    \"\"\"\n\n    def __init__(self):\n        self._outcomes: List[OutcomeEvent] = []\n\n    def record(self, outcome: OutcomeEvent):\n        \"\"\"Record an outcome event.\"\"\"\n        self._outcomes.append(outcome)\n\n    def cost_per_success(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate cost per successful outcome.\n\n        This is the core metric. Total cost divided by number of\n        successful outcomes gives you the true unit economics of\n        your agent fleet.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        successes = [e for e in events if e.status == OutcomeStatus.SUCCESS]\n        failures = [e for e in events if e.status == OutcomeStatus.FAILURE]\n        partials = [e for e in events if e.status == OutcomeStatus.PARTIAL]\n\n        success_count = len(successes)\n        cost_per_success = total_cost \u002F success_count if success_count > 0 else float(\"inf\")\n\n        # Cost wasted on failures\n        wasted_cost = sum(e.cost_usd for e in failures)\n\n        # Cost of retries (successful outcomes that required retries)\n        retry_overhead = sum(\n            e.cost_usd * (e.retries \u002F (e.retries + 1))\n            for e in successes if e.retries > 0\n        )\n\n        return {\n            \"total_outcomes\": len(events),\n            \"successes\": success_count,\n            \"failures\": len(failures),\n            \"partials\": len(partials),\n            \"success_rate_pct\": round(success_count \u002F len(events) * 100, 1),\n            \"total_cost_usd\": round(total_cost, 4),\n            \"cost_per_success_usd\": round(cost_per_success, 4),\n            \"wasted_cost_usd\": round(wasted_cost, 4),\n            \"wasted_pct\": round(wasted_cost \u002F total_cost * 100, 1) if total_cost > 0 else 0,\n            \"retry_overhead_usd\": round(retry_overhead, 4),\n        }\n\n    def quality_adjusted_cost(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate quality-adjusted cost per outcome.\n\n        Weights each outcome by its quality score. A $0.05 outcome\n        with quality 0.9 costs $0.056 per quality point. A $0.03\n        outcome with quality 0.5 costs $0.060 per quality point.\n        The cheaper outcome is actually more expensive when adjusted\n        for quality.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        total_quality = sum(e.quality_score for e in events)\n        avg_quality = total_quality \u002F len(events)\n        quality_adjusted = total_cost \u002F total_quality if total_quality > 0 else float(\"inf\")\n\n        # Segment by quality tier\n        high_quality = [e for e in events if e.quality_score >= 0.8]\n        mid_quality = [e for e in events if 0.5 \u003C= e.quality_score \u003C 0.8]\n        low_quality = [e for e in events if e.quality_score \u003C 0.5]\n\n        return {\n            \"total_outcomes\": len(events),\n            \"avg_quality_score\": round(avg_quality, 3),\n            \"total_cost_usd\": round(total_cost, 4),\n            \"cost_per_quality_point_usd\": round(quality_adjusted, 4),\n            \"high_quality_count\": len(high_quality),\n            \"high_quality_avg_cost\": round(\n                sum(e.cost_usd for e in high_quality) \u002F len(high_quality), 4\n            ) if high_quality else 0,\n            \"mid_quality_count\": len(mid_quality),\n            \"mid_quality_avg_cost\": round(\n                sum(e.cost_usd for e in mid_quality) \u002F len(mid_quality), 4\n            ) if mid_quality else 0,\n            \"low_quality_count\": len(low_quality),\n            \"low_quality_avg_cost\": round(\n                sum(e.cost_usd for e in low_quality) \u002F len(low_quality), 4\n            ) if low_quality else 0,\n        }\n\n    def roi_analysis(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate ROI based on business value attribution.\n\n        Compares the total cost of agent operations against the\n        business value generated by successful outcomes.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        total_value = sum(e.business_value_usd for e in events if e.status == OutcomeStatus.SUCCESS)\n        roi = ((total_value - total_cost) \u002F total_cost * 100) if total_cost > 0 else 0\n\n        return {\n            \"total_cost_usd\": round(total_cost, 2),\n            \"total_business_value_usd\": round(total_value, 2),\n            \"net_value_usd\": round(total_value - total_cost, 2),\n            \"roi_pct\": round(roi, 1),\n            \"cost_to_value_ratio\": round(\n                total_cost \u002F total_value, 4\n            ) if total_value > 0 else float(\"inf\"),\n        }\n\n    def _filter(\n        self,\n        agent_id: Optional[str],\n        task_type: Optional[str],\n    ) -> List[OutcomeEvent]:\n        events = self._outcomes\n        if agent_id:\n            events = [e for e in events if e.agent_id == agent_id]\n        if task_type:\n            events = [e for e in events if e.task_type == task_type]\n        return events\n\n\n# Usage: track outcomes for a research agent fleet\nmeter = OutcomeMeter()\n\n# Simulate 500 research tasks across two agents\nimport random\nrandom.seed(42)\n\nfor i in range(500):\n    agent = random.choice([\"researcher-01\", \"researcher-02\"])\n    quality = random.gauss(0.78, 0.15)\n    quality = max(0.0, min(1.0, quality))\n    failed = quality \u003C 0.3\n    retries = random.randint(0, 3) if not failed else 0\n    base_cost = random.gauss(0.04, 0.015)\n    cost = base_cost * (1 + retries * 0.8)\n\n    meter.record(OutcomeEvent(\n        outcome_id=f\"task_{i:04d}\",\n        agent_id=agent,\n        task_type=\"research_report\",\n        status=OutcomeStatus.FAILURE if failed else OutcomeStatus.SUCCESS,\n        cost_usd=max(0.005, cost),\n        quality_score=quality,\n        business_value_usd=0 if failed else random.uniform(2.0, 15.0),\n        retries=retries,\n    ))\n\ncps = meter.cost_per_success()\nprint(f\"Success rate: {cps['success_rate_pct']}%\")\nprint(f\"Cost per success: ${cps['cost_per_success_usd']}\")\nprint(f\"Wasted on failures: ${cps['wasted_cost_usd']} ({cps['wasted_pct']}%)\")\n\nqac = meter.quality_adjusted_cost()\nprint(f\"Cost per quality point: ${qac['cost_per_quality_point_usd']}\")\n\nroi = meter.roi_analysis()\nprint(f\"ROI: {roi['roi_pct']}%\")\nprint(f\"Cost-to-value ratio: {roi['cost_to_value_ratio']}\")\n```\n\n### Outcome Attribution in Multi-Agent Pipelines\n\nIn a single-agent system, attribution is trivial: the agent either succeeded or it did not. Multi-agent pipelines break this simplicity. A research pipeline with an intake agent, a search agent, a synthesis agent, and a review agent involves four cost centers. When the pipeline produces a high-quality report, which agent gets credit? When it produces garbage, which agent is at fault?\n\nThe answer is proportional attribution with failure isolation. Each agent in the pipeline gets a share of the outcome value proportional to its cost contribution, but failure attribution is localized to the specific agent that caused the failure.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass PipelineStep:\n    \"\"\"A single step in a multi-agent pipeline.\"\"\"\n    agent_id: str\n    step_name: str\n    cost_usd: float\n    quality_score: float        # Quality of this step's output\n    duration_ms: float\n    input_tokens: int = 0\n    output_tokens: int = 0\n    passed_quality_gate: bool = True\n    failure_reason: Optional[str] = None\n\n\n@dataclass\nclass PipelineOutcome:\n    \"\"\"Complete outcome of a multi-agent pipeline execution.\"\"\"\n    pipeline_id: str\n    steps: List[PipelineStep]\n    final_status: OutcomeStatus\n    final_quality: float\n    business_value_usd: float = 0.0\n\n\nclass PipelineAttributor:\n    \"\"\"Attributes costs and outcomes across multi-agent pipelines.\n\n    Uses proportional cost attribution for successes and\n    root-cause isolation for failures. Each step has a quality\n    gate -- if a step's output quality falls below threshold,\n    downstream costs are attributed to the failing step.\n    \"\"\"\n\n    def __init__(self, quality_gate_threshold: float = 0.5):\n        self.quality_gate = quality_gate_threshold\n        self._pipelines: List[PipelineOutcome] = []\n\n    def record_pipeline(self, outcome: PipelineOutcome):\n        self._pipelines.append(outcome)\n\n    def attribute(self, pipeline: PipelineOutcome) -> Dict[str, Any]:\n        \"\"\"Attribute outcome value and waste across pipeline steps.\"\"\"\n        total_cost = sum(s.cost_usd for s in pipeline.steps)\n        attribution = {}\n\n        if pipeline.final_status == OutcomeStatus.SUCCESS:\n            # Proportional attribution: each step gets value\n            # proportional to its cost share, weighted by quality\n            quality_weighted_costs = {\n                s.step_name: s.cost_usd * s.quality_score\n                for s in pipeline.steps\n            }\n            total_weighted = sum(quality_weighted_costs.values())\n\n            for step in pipeline.steps:\n                weight = (\n                    quality_weighted_costs[step.step_name] \u002F total_weighted\n                    if total_weighted > 0 else 1.0 \u002F len(pipeline.steps)\n                )\n                attribution[step.step_name] = {\n                    \"agent_id\": step.agent_id,\n                    \"cost_usd\": round(step.cost_usd, 4),\n                    \"cost_share_pct\": round(step.cost_usd \u002F total_cost * 100, 1),\n                    \"value_share_pct\": round(weight * 100, 1),\n                    \"attributed_value_usd\": round(\n                        pipeline.business_value_usd * weight, 2\n                    ),\n                    \"quality_score\": round(step.quality_score, 3),\n                    \"status\": \"contributing\",\n                }\n        else:\n            # Failure attribution: find the root cause step\n            root_cause = None\n            for step in pipeline.steps:\n                if not step.passed_quality_gate or step.failure_reason:\n                    root_cause = step.step_name\n                    break\n\n            wasted_downstream = 0.0\n            past_failure = False\n            for step in pipeline.steps:\n                if step.step_name == root_cause:\n                    past_failure = True\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"root_cause\",\n                        \"failure_reason\": step.failure_reason or \"below quality gate\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n                elif past_failure:\n                    wasted_downstream += step.cost_usd\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"wasted_downstream\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n                else:\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"completed_before_failure\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n\n            attribution[\"_failure_summary\"] = {\n                \"root_cause_step\": root_cause,\n                \"wasted_downstream_usd\": round(wasted_downstream, 4),\n                \"wasted_pct\": round(\n                    wasted_downstream \u002F total_cost * 100, 1\n                ) if total_cost > 0 else 0,\n            }\n\n        return {\n            \"pipeline_id\": pipeline.pipeline_id,\n            \"total_cost_usd\": round(total_cost, 4),\n            \"final_status\": pipeline.final_status.value,\n            \"attribution\": attribution,\n        }\n\n    def fleet_summary(self) -> Dict[str, Any]:\n        \"\"\"Summarize attribution across all recorded pipelines.\"\"\"\n        agent_stats: Dict[str, Dict[str, float]] = {}\n\n        for pipeline in self._pipelines:\n            attr = self.attribute(pipeline)\n            for step_name, data in attr[\"attribution\"].items():\n                if step_name.startswith(\"_\"):\n                    continue\n                aid = data[\"agent_id\"]\n                if aid not in agent_stats:\n                    agent_stats[aid] = {\n                        \"total_cost\": 0.0,\n                        \"attributed_value\": 0.0,\n                        \"root_cause_failures\": 0,\n                        \"wasted_downstream_cost\": 0.0,\n                    }\n                agent_stats[aid][\"total_cost\"] += data[\"cost_usd\"]\n                agent_stats[aid][\"attributed_value\"] += data.get(\n                    \"attributed_value_usd\", 0.0\n                )\n                if data.get(\"status\") == \"root_cause\":\n                    agent_stats[aid][\"root_cause_failures\"] += 1\n                if data.get(\"status\") == \"wasted_downstream\":\n                    agent_stats[aid][\"wasted_downstream_cost\"] += data[\"cost_usd\"]\n\n        return {\n            agent_id: {\n                \"total_cost_usd\": round(stats[\"total_cost\"], 2),\n                \"attributed_value_usd\": round(stats[\"attributed_value\"], 2),\n                \"root_cause_failures\": stats[\"root_cause_failures\"],\n                \"wasted_downstream_usd\": round(stats[\"wasted_downstream_cost\"], 2),\n                \"efficiency_ratio\": round(\n                    stats[\"attributed_value\"] \u002F stats[\"total_cost\"], 2\n                ) if stats[\"total_cost\"] > 0 else 0,\n            }\n            for agent_id, stats in agent_stats.items()\n        }\n\n\n# Example: a 4-step research pipeline\nattributor = PipelineAttributor(quality_gate_threshold=0.5)\n\n# Successful pipeline\nattributor.record_pipeline(PipelineOutcome(\n    pipeline_id=\"pipe_001\",\n    steps=[\n        PipelineStep(\"intake-agent\", \"intake\", 0.008, 0.95, 320),\n        PipelineStep(\"search-agent\", \"search\", 0.025, 0.88, 1200),\n        PipelineStep(\"synthesis-agent\", \"synthesis\", 0.045, 0.82, 2100),\n        PipelineStep(\"review-agent\", \"review\", 0.015, 0.91, 800),\n    ],\n    final_status=OutcomeStatus.SUCCESS,\n    final_quality=0.88,\n    business_value_usd=12.50,\n))\n\n# Failed pipeline -- search agent returned low-quality results\nattributor.record_pipeline(PipelineOutcome(\n    pipeline_id=\"pipe_002\",\n    steps=[\n        PipelineStep(\"intake-agent\", \"intake\", 0.008, 0.93, 310),\n        PipelineStep(\"search-agent\", \"search\", 0.022, 0.30, 900,\n                     passed_quality_gate=False,\n                     failure_reason=\"insufficient relevant sources\"),\n        PipelineStep(\"synthesis-agent\", \"synthesis\", 0.040, 0.25, 1800),\n        PipelineStep(\"review-agent\", \"review\", 0.012, 0.20, 600),\n    ],\n    final_status=OutcomeStatus.FAILURE,\n    final_quality=0.20,\n))\n\n# Analyze the failed pipeline\nresult = attributor.attribute(attributor._pipelines[1])\nprint(f\"Pipeline {result['pipeline_id']}: {result['final_status']}\")\nprint(f\"Total cost: ${result['total_cost_usd']}\")\nsummary = result[\"attribution\"][\"_failure_summary\"]\nprint(f\"Root cause: {summary['root_cause_step']}\")\nprint(f\"Wasted downstream: ${summary['wasted_downstream_usd']} ({summary['wasted_pct']}%)\")\n```\n\n### Pricing Strategies Tied to Value Delivered\n\nOutcome-based metering enables outcome-based pricing -- charging customers based on results rather than consumption. This aligns incentives: you only earn when your agents deliver value. Four pricing models work in practice.\n\n| Pricing Model | How It Works | Best For | Example |\n|---|---|---|---|\n| Per-successful-outcome | Flat fee per completed task | High-volume, uniform tasks | $0.15 per classified document |\n| Quality-tiered | Price varies by output quality | Tasks with measurable quality | $0.05 (draft) \u002F $0.20 (polished) |\n| Value-share | Percentage of business value generated | High-value, variable outcomes | 2% of deal value identified |\n| Guaranteed SLA | Fixed price with quality guarantee, refund on failure | Enterprise contracts | $0.25\u002Ftask, 95% quality SLA |\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any, Optional\nfrom enum import Enum\n\n\nclass PricingModel(Enum):\n    PER_SUCCESS = \"per_success\"\n    QUALITY_TIERED = \"quality_tiered\"\n    VALUE_SHARE = \"value_share\"\n    GUARANTEED_SLA = \"guaranteed_sla\"\n\n\n@dataclass\nclass PricingConfig:\n    model: PricingModel\n    # Per-success pricing\n    price_per_success: float = 0.0\n    # Quality-tiered pricing\n    quality_tiers: Dict[str, float] = None  # {\"high\": 0.20, \"medium\": 0.10, \"low\": 0.05}\n    quality_thresholds: Dict[str, float] = None  # {\"high\": 0.85, \"medium\": 0.60}\n    # Value-share pricing\n    value_share_pct: float = 0.0\n    minimum_fee: float = 0.0\n    # Guaranteed SLA\n    sla_price: float = 0.0\n    sla_quality_threshold: float = 0.0\n    sla_refund_pct: float = 100.0\n\n    def __post_init__(self):\n        if self.quality_tiers is None:\n            self.quality_tiers = {\"high\": 0.20, \"medium\": 0.10, \"low\": 0.05}\n        if self.quality_thresholds is None:\n            self.quality_thresholds = {\"high\": 0.85, \"medium\": 0.60}\n\n\nclass OutcomePricer:\n    \"\"\"Calculates charges based on outcome-based pricing models.\n\n    Replaces input-based billing (per-token, per-call) with\n    value-aligned pricing that charges based on results delivered.\n    \"\"\"\n\n    def __init__(self, config: PricingConfig):\n        self.config = config\n\n    def calculate_charge(\n        self,\n        status: OutcomeStatus,\n        quality_score: float,\n        business_value_usd: float = 0.0,\n        actual_cost_usd: float = 0.0,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate the charge for an outcome.\"\"\"\n        if self.config.model == PricingModel.PER_SUCCESS:\n            return self._per_success(status, actual_cost_usd)\n        elif self.config.model == PricingModel.QUALITY_TIERED:\n            return self._quality_tiered(status, quality_score, actual_cost_usd)\n        elif self.config.model == PricingModel.VALUE_SHARE:\n            return self._value_share(status, business_value_usd, actual_cost_usd)\n        elif self.config.model == PricingModel.GUARANTEED_SLA:\n            return self._guaranteed_sla(status, quality_score, actual_cost_usd)\n        return {\"error\": \"unknown pricing model\"}\n\n    def _per_success(self, status: OutcomeStatus, cost: float) -> Dict[str, Any]:\n        charge = self.config.price_per_success if status == OutcomeStatus.SUCCESS else 0.0\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"margin_pct\": round((charge - cost) \u002F charge * 100, 1) if charge > 0 else -100.0,\n            \"pricing_model\": \"per_success\",\n        }\n\n    def _quality_tiered(\n        self, status: OutcomeStatus, quality: float, cost: float,\n    ) -> Dict[str, Any]:\n        if status == OutcomeStatus.FAILURE:\n            tier, charge = \"failed\", 0.0\n        elif quality >= self.config.quality_thresholds[\"high\"]:\n            tier = \"high\"\n            charge = self.config.quality_tiers[\"high\"]\n        elif quality >= self.config.quality_thresholds[\"medium\"]:\n            tier = \"medium\"\n            charge = self.config.quality_tiers[\"medium\"]\n        else:\n            tier = \"low\"\n            charge = self.config.quality_tiers[\"low\"]\n\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"quality_tier\": tier,\n            \"quality_score\": round(quality, 3),\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"quality_tiered\",\n        }\n\n    def _value_share(\n        self, status: OutcomeStatus, value: float, cost: float,\n    ) -> Dict[str, Any]:\n        if status == OutcomeStatus.FAILURE:\n            charge = 0.0\n        else:\n            charge = max(\n                value * self.config.value_share_pct \u002F 100,\n                self.config.minimum_fee,\n            )\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"business_value_usd\": round(value, 2),\n            \"value_share_pct\": self.config.value_share_pct,\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"value_share\",\n        }\n\n    def _guaranteed_sla(\n        self, status: OutcomeStatus, quality: float, cost: float,\n    ) -> Dict[str, Any]:\n        charge = self.config.sla_price\n        refund = 0.0\n        if status == OutcomeStatus.FAILURE or quality \u003C self.config.sla_quality_threshold:\n            refund = charge * self.config.sla_refund_pct \u002F 100\n            charge -= refund\n\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"refund_usd\": round(refund, 4),\n            \"met_sla\": status == OutcomeStatus.SUCCESS and quality >= self.config.sla_quality_threshold,\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"guaranteed_sla\",\n        }\n\n\n# Compare pricing models on same workload\nconfigs = {\n    \"per_success\": PricingConfig(\n        model=PricingModel.PER_SUCCESS,\n        price_per_success=0.15,\n    ),\n    \"quality_tiered\": PricingConfig(\n        model=PricingModel.QUALITY_TIERED,\n        quality_tiers={\"high\": 0.20, \"medium\": 0.10, \"low\": 0.03},\n        quality_thresholds={\"high\": 0.85, \"medium\": 0.60},\n    ),\n    \"value_share\": PricingConfig(\n        model=PricingModel.VALUE_SHARE,\n        value_share_pct=2.0,\n        minimum_fee=0.05,\n    ),\n    \"guaranteed_sla\": PricingConfig(\n        model=PricingModel.GUARANTEED_SLA,\n        sla_price=0.25,\n        sla_quality_threshold=0.80,\n        sla_refund_pct=100.0,\n    ),\n}\n\n# Simulate: 1000 tasks, 85% success, avg quality 0.78, avg value $8\nrandom.seed(99)\nfor name, config in configs.items():\n    pricer = OutcomePricer(config)\n    total_charge = 0.0\n    total_cost = 0.0\n    for _ in range(1000):\n        succeeded = random.random() \u003C 0.85\n        quality = random.gauss(0.78, 0.12)\n        quality = max(0.0, min(1.0, quality))\n        cost = random.gauss(0.04, 0.01)\n        value = random.uniform(3.0, 15.0) if succeeded else 0.0\n\n        result = pricer.calculate_charge(\n            status=OutcomeStatus.SUCCESS if succeeded else OutcomeStatus.FAILURE,\n            quality_score=quality,\n            business_value_usd=value,\n            actual_cost_usd=cost,\n        )\n        total_charge += result[\"charge_usd\"]\n        total_cost += result[\"cost_usd\"]\n\n    print(f\"{name:20s}: revenue=${total_charge:7.2f}  \"\n          f\"cost=${total_cost:6.2f}  \"\n          f\"margin=${total_charge - total_cost:7.2f}  \"\n          f\"margin%={((total_charge - total_cost) \u002F total_charge * 100) if total_charge > 0 else 0:5.1f}%\")\n```\n\nThe output reveals the tradeoffs clearly. Per-success pricing is predictable but ignores quality variation. Quality-tiered pricing rewards investment in output quality. Value-share pricing has the highest upside but the widest variance. Guaranteed-SLA pricing commands premium prices but exposes you to refund risk if quality drops. Most production deployments use quality-tiered pricing for high-volume tasks and value-share pricing for high-value, low-volume workflows.\n\n---\n\n## Chapter 7: Infrastructure Right-Sizing\n\n### The Infrastructure Cost Iceberg\n\nLLM inference costs dominate the conversation, but infrastructure costs are the iceberg beneath the surface. A production agent fleet requires compute for inference serving, batch processing queues, cache layers, persistent storage for agent memory, network bandwidth for inter-service communication, and orchestration overhead for container management. For teams running self-hosted models or hybrid architectures (some calls to API providers, some to local models), infrastructure can account for 40-60% of total agent cost. Even teams using only API providers pay infrastructure costs for the application layer, caching, observability, and storage.\n\nThe core principle of right-sizing is matching resource allocation to actual workload characteristics. Agent workloads are bursty, heterogeneous, and latency-sensitive in unpredictable ways. A customer-facing chat agent needs sub-second responses during business hours and near-zero traffic at 3 AM. A batch analysis pipeline needs maximum throughput for four hours and nothing for the other twenty. A background research agent needs moderate throughput with tolerance for multi-second latency. One infrastructure configuration cannot serve all three efficiently.\n\n### GPU vs CPU Sizing for Inference\n\nSelf-hosted model inference is the largest infrastructure cost decision. The wrong GPU choice wastes thousands of dollars per month. The right choice depends on three factors: model size, throughput requirement, and latency target.\n\n| Model Size | Recommended GPU | On-Demand $\u002Fhr | Throughput (tokens\u002Fs) | Cost per 1M Tokens |\n|---|---|---|---|---|\n| 7-8B params | NVIDIA T4 (16GB) | $0.526 | 80-120 | $1.22-1.83 |\n| 7-8B params | NVIDIA L4 (24GB) | $0.810 | 140-180 | $1.25-1.61 |\n| 13B params | NVIDIA A10G (24GB) | $1.212 | 60-90 | $3.74-5.61 |\n| 34B params | NVIDIA A100 40GB | $3.673 | 40-65 | $15.69-25.51 |\n| 70B params | NVIDIA A100 80GB | $4.234 | 20-35 | $33.60-58.81 |\n| 70B params | 2x NVIDIA A100 80GB | $8.468 | 45-70 | $33.60-52.27 |\n| 8B (quantized INT4) | NVIDIA T4 (16GB) | $0.526 | 150-220 | $0.66-0.97 |\n\nThe table reveals a critical insight: quantized small models on cheap GPUs often beat large models on expensive GPUs in cost-per-token by 10-30x. A quantized Llama 3 8B on a T4 at $0.97 per million tokens undercuts GPT-4o's API price of $2.50 per million input tokens -- and you control the hardware.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass GPUConfig:\n    \"\"\"Configuration for a GPU instance used for model inference.\"\"\"\n    name: str\n    gpu_type: str\n    vram_gb: int\n    hourly_cost: float\n    throughput_tokens_per_sec: float  # Sustained output throughput\n    max_batch_size: int\n    power_watts: int\n\n\n@dataclass\nclass InferenceWorkload:\n    \"\"\"Describes an inference workload's requirements.\"\"\"\n    model_size_b: float              # Model size in billions of params\n    avg_input_tokens: int\n    avg_output_tokens: int\n    requests_per_hour: int\n    latency_target_ms: float         # p95 target\n    hours_per_day: float = 24.0\n    quantized: bool = False\n\n\nclass InfrastructureSizer:\n    \"\"\"Calculates optimal GPU configuration for inference workloads.\n\n    Compares self-hosted inference costs against API provider costs\n    and recommends the most cost-effective deployment strategy.\n    \"\"\"\n\n    GPU_CATALOG = {\n        \"t4\": GPUConfig(\"t4\", \"NVIDIA T4\", 16, 0.526, 100, 32, 70),\n        \"l4\": GPUConfig(\"l4\", \"NVIDIA L4\", 24, 0.810, 160, 64, 72),\n        \"a10g\": GPUConfig(\"a10g\", \"NVIDIA A10G\", 24, 1.212, 75, 48, 150),\n        \"a100-40\": GPUConfig(\"a100-40\", \"NVIDIA A100 40GB\", 40, 3.673, 52, 64, 250),\n        \"a100-80\": GPUConfig(\"a100-80\", \"NVIDIA A100 80GB\", 80, 4.234, 28, 128, 300),\n    }\n\n    API_PRICING = {\n        \"gpt-4o\":           {\"input\": 2.50, \"output\": 10.00},\n        \"gpt-4o-mini\":      {\"input\": 0.15, \"output\": 0.60},\n        \"claude-sonnet-4\":  {\"input\": 3.00, \"output\": 15.00},\n        \"claude-haiku-3.5\": {\"input\": 0.80, \"output\": 4.00},\n    }\n\n    # Approximate VRAM requirement: ~2 bytes per param (FP16), ~0.5 bytes (INT4)\n    BYTES_PER_PARAM_FP16 = 2.0\n    BYTES_PER_PARAM_INT4 = 0.5\n\n    def size_gpu(self, workload: InferenceWorkload) -> Dict[str, Any]:\n        \"\"\"Find the cheapest GPU config that meets workload requirements.\"\"\"\n        bytes_per_param = (\n            self.BYTES_PER_PARAM_INT4 if workload.quantized\n            else self.BYTES_PER_PARAM_FP16\n        )\n        required_vram_gb = workload.model_size_b * bytes_per_param\n\n        # Filter GPUs that have enough VRAM (with 20% headroom for KV cache)\n        viable_gpus = [\n            gpu for gpu in self.GPU_CATALOG.values()\n            if gpu.vram_gb >= required_vram_gb * 1.2\n        ]\n\n        if not viable_gpus:\n            return {\"error\": f\"No single GPU has enough VRAM for {required_vram_gb:.1f}GB model\"}\n\n        # Check throughput requirements\n        tokens_per_hour = workload.requests_per_hour * (\n            workload.avg_input_tokens + workload.avg_output_tokens\n        )\n        tokens_per_sec_needed = tokens_per_hour \u002F 3600\n\n        results = []\n        for gpu in viable_gpus:\n            # Throughput scales with quantization\n            effective_throughput = (\n                gpu.throughput_tokens_per_sec * 1.8 if workload.quantized\n                else gpu.throughput_tokens_per_sec\n            )\n\n            gpus_needed = max(1, int(\n                tokens_per_sec_needed \u002F effective_throughput + 0.99\n            ))\n\n            # Cost calculation\n            hourly_cost = gpu.hourly_cost * gpus_needed\n            daily_cost = hourly_cost * workload.hours_per_day\n            monthly_cost = daily_cost * 30\n            cost_per_1m_tokens = (\n                hourly_cost \u002F (effective_throughput * gpus_needed * 3600) * 1_000_000\n            )\n\n            # Latency estimate (simplified: output tokens \u002F throughput * 1000)\n            latency_est_ms = (\n                workload.avg_output_tokens \u002F effective_throughput * 1000\n            )\n\n            results.append({\n                \"gpu_type\": gpu.name,\n                \"gpu_name\": gpu.gpu_type,\n                \"gpus_needed\": gpus_needed,\n                \"monthly_cost_usd\": round(monthly_cost, 2),\n                \"cost_per_1m_tokens_usd\": round(cost_per_1m_tokens, 4),\n                \"estimated_latency_ms\": round(latency_est_ms, 1),\n                \"meets_latency_target\": latency_est_ms \u003C= workload.latency_target_ms,\n                \"utilization_pct\": round(\n                    tokens_per_sec_needed \u002F (effective_throughput * gpus_needed) * 100, 1\n                ),\n            })\n\n        results.sort(key=lambda r: r[\"monthly_cost_usd\"])\n        return {\n            \"workload\": {\n                \"model_size_b\": workload.model_size_b,\n                \"requests_per_hour\": workload.requests_per_hour,\n                \"tokens_per_sec_needed\": round(tokens_per_sec_needed, 1),\n                \"quantized\": workload.quantized,\n            },\n            \"options\": results,\n            \"recommended\": next(\n                (r for r in results if r[\"meets_latency_target\"]),\n                results[0] if results else None,\n            ),\n        }\n\n    def compare_self_hosted_vs_api(\n        self,\n        workload: InferenceWorkload,\n        api_model: str = \"gpt-4o-mini\",\n    ) -> Dict[str, Any]:\n        \"\"\"Compare self-hosted inference cost against API provider.\"\"\"\n        gpu_result = self.size_gpu(workload)\n        if \"error\" in gpu_result:\n            return gpu_result\n\n        recommended = gpu_result[\"recommended\"]\n        self_hosted_monthly = recommended[\"monthly_cost_usd\"]\n\n        # API cost\n        pricing = self.API_PRICING.get(api_model, {\"input\": 2.50, \"output\": 10.00})\n        requests_per_month = workload.requests_per_hour * workload.hours_per_day * 30\n        api_monthly = requests_per_month * (\n            workload.avg_input_tokens * pricing[\"input\"] \u002F 1_000_000\n            + workload.avg_output_tokens * pricing[\"output\"] \u002F 1_000_000\n        )\n\n        savings = api_monthly - self_hosted_monthly\n        savings_pct = (savings \u002F api_monthly * 100) if api_monthly > 0 else 0\n\n        return {\n            \"self_hosted\": {\n                \"gpu\": recommended[\"gpu_name\"],\n                \"gpus_needed\": recommended[\"gpus_needed\"],\n                \"monthly_cost_usd\": round(self_hosted_monthly, 2),\n                \"cost_per_1m_tokens\": recommended[\"cost_per_1m_tokens_usd\"],\n            },\n            \"api\": {\n                \"model\": api_model,\n                \"monthly_cost_usd\": round(api_monthly, 2),\n                \"cost_per_1m_tokens\": round(\n                    (pricing[\"input\"] + pricing[\"output\"]) \u002F 2, 2\n                ),\n            },\n            \"savings_usd\": round(savings, 2),\n            \"savings_pct\": round(savings_pct, 1),\n            \"recommendation\": (\n                \"SELF-HOST\" if savings > 200 and savings_pct > 20\n                else \"USE API\" if savings \u003C -100\n                else \"EVALUATE FURTHER\"\n            ),\n            \"breakeven_requests_per_hour\": round(\n                self_hosted_monthly \u002F 30 \u002F workload.hours_per_day \u002F (\n                    workload.avg_input_tokens * pricing[\"input\"] \u002F 1_000_000\n                    + workload.avg_output_tokens * pricing[\"output\"] \u002F 1_000_000\n                ), 0\n            ) if api_monthly > 0 else 0,\n        }\n\n\n# Example: Size infrastructure for a classification agent fleet\nsizer = InfrastructureSizer()\n\n# Workload: 8B quantized model, 5000 req\u002Fhr, 500ms latency target\nclassification_workload = InferenceWorkload(\n    model_size_b=8.0,\n    avg_input_tokens=500,\n    avg_output_tokens=50,\n    requests_per_hour=5000,\n    latency_target_ms=500,\n    hours_per_day=16,  # Business hours only\n    quantized=True,\n)\n\nresult = sizer.size_gpu(classification_workload)\nrec = result[\"recommended\"]\nprint(f\"Recommended: {rec['gpus_needed']}x {rec['gpu_name']}\")\nprint(f\"Monthly cost: ${rec['monthly_cost_usd']}\")\nprint(f\"Cost per 1M tokens: ${rec['cost_per_1m_tokens_usd']}\")\nprint(f\"Estimated latency: {rec['estimated_latency_ms']}ms\")\n\n# Compare against API\ncomparison = sizer.compare_self_hosted_vs_api(classification_workload, \"gpt-4o-mini\")\nprint(f\"\\nSelf-hosted: ${comparison['self_hosted']['monthly_cost_usd']}\u002Fmo\")\nprint(f\"API ({comparison['api']['model']}): ${comparison['api']['monthly_cost_usd']}\u002Fmo\")\nprint(f\"Savings: ${comparison['savings_usd']}\u002Fmo ({comparison['savings_pct']}%)\")\nprint(f\"Recommendation: {comparison['recommendation']}\")\n```\n\n### Batch Processing vs Real-Time\n\nNot every agent task requires real-time response. Batch processing is 50% cheaper on both OpenAI and Anthropic APIs, and self-hosted batch processing achieves higher GPU utilization (90%+ vs 30-50% for real-time serving). The key is identifying which tasks can tolerate latency.\n\n| Task Type | Latency Tolerance | Processing Mode | Cost Multiplier |\n|---|---|---|---|\n| Customer chat responses | \u003C 2 seconds | Real-time | 1.0x |\n| Email draft generation | \u003C 30 seconds | Near-real-time | 0.8x |\n| Document classification | \u003C 5 minutes | Micro-batch | 0.6x |\n| Nightly report generation | \u003C 4 hours | Batch | 0.5x |\n| Training data labeling | \u003C 24 hours | Batch (off-peak) | 0.35x |\n| Embedding generation | \u003C 12 hours | Batch (spot instances) | 0.25x |\n\n```python\nimport time\nimport heapq\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Any, Optional, Callable\nfrom enum import Enum\nfrom datetime import datetime, timezone\n\n\nclass ProcessingMode(Enum):\n    REALTIME = \"realtime\"\n    NEAR_REALTIME = \"near_realtime\"\n    MICRO_BATCH = \"micro_batch\"\n    BATCH = \"batch\"\n\n\n@dataclass\nclass AgentTask:\n    \"\"\"A task to be processed by an agent.\"\"\"\n    task_id: str\n    task_type: str\n    payload: Dict[str, Any]\n    priority: int = 0                     # Lower is higher priority\n    max_latency_ms: float = 2000.0\n    created_at: float = field(default_factory=time.time)\n    estimated_tokens: int = 1000\n\n\nclass WorkloadScheduler:\n    \"\"\"Schedules agent tasks across processing modes for cost optimization.\n\n    Routes tasks to the cheapest processing mode that meets their\n    latency requirements. Accumulates batch-eligible tasks and\n    flushes them at configurable intervals.\n    \"\"\"\n\n    MODE_COST_MULTIPLIERS = {\n        ProcessingMode.REALTIME: 1.0,\n        ProcessingMode.NEAR_REALTIME: 0.8,\n        ProcessingMode.MICRO_BATCH: 0.6,\n        ProcessingMode.BATCH: 0.5,\n    }\n\n    # Latency thresholds for mode assignment (milliseconds)\n    MODE_THRESHOLDS = {\n        ProcessingMode.REALTIME: 2_000,\n        ProcessingMode.NEAR_REALTIME: 30_000,\n        ProcessingMode.MICRO_BATCH: 300_000,\n        ProcessingMode.BATCH: 14_400_000,   # 4 hours\n    }\n\n    def __init__(\n        self,\n        micro_batch_size: int = 20,\n        micro_batch_interval_sec: float = 60.0,\n        batch_flush_interval_sec: float = 3600.0,\n    ):\n        self.micro_batch_size = micro_batch_size\n        self.micro_batch_interval = micro_batch_interval_sec\n        self.batch_flush_interval = batch_flush_interval_sec\n\n        self._realtime_queue: List[AgentTask] = []\n        self._micro_batch_queue: List[AgentTask] = []\n        self._batch_queue: List[AgentTask] = []\n        self._stats = {mode.value: {\"count\": 0, \"tokens\": 0} for mode in ProcessingMode}\n\n    def classify_and_enqueue(self, task: AgentTask) -> ProcessingMode:\n        \"\"\"Classify a task's processing mode and add it to the right queue.\"\"\"\n        mode = self._classify(task)\n        self._stats[mode.value][\"count\"] += 1\n        self._stats[mode.value][\"tokens\"] += task.estimated_tokens\n\n        if mode == ProcessingMode.REALTIME or mode == ProcessingMode.NEAR_REALTIME:\n            self._realtime_queue.append(task)\n        elif mode == ProcessingMode.MICRO_BATCH:\n            self._micro_batch_queue.append(task)\n        else:\n            self._batch_queue.append(task)\n\n        return mode\n\n    def _classify(self, task: AgentTask) -> ProcessingMode:\n        \"\"\"Assign the cheapest processing mode that meets latency requirements.\"\"\"\n        for mode in [ProcessingMode.BATCH, ProcessingMode.MICRO_BATCH,\n                     ProcessingMode.NEAR_REALTIME, ProcessingMode.REALTIME]:\n            if task.max_latency_ms >= self.MODE_THRESHOLDS[mode]:\n                return mode\n        return ProcessingMode.REALTIME\n\n    def get_micro_batch(self) -> Optional[List[AgentTask]]:\n        \"\"\"Get a micro-batch if enough tasks are queued.\"\"\"\n        if len(self._micro_batch_queue) >= self.micro_batch_size:\n            batch = self._micro_batch_queue[:self.micro_batch_size]\n            self._micro_batch_queue = self._micro_batch_queue[self.micro_batch_size:]\n            return batch\n        return None\n\n    def flush_batch_queue(self) -> List[AgentTask]:\n        \"\"\"Flush all accumulated batch tasks for processing.\"\"\"\n        tasks = list(self._batch_queue)\n        self._batch_queue = []\n        return tasks\n\n    def cost_savings_report(self, base_cost_per_1m_tokens: float = 2.50) -> Dict[str, Any]:\n        \"\"\"Calculate savings from workload scheduling.\"\"\"\n        total_tokens = sum(s[\"tokens\"] for s in self._stats.values())\n        realtime_cost = total_tokens * base_cost_per_1m_tokens \u002F 1_000_000\n\n        actual_cost = 0.0\n        mode_breakdown = {}\n        for mode in ProcessingMode:\n            stats = self._stats[mode.value]\n            multiplier = self.MODE_COST_MULTIPLIERS[mode]\n            mode_cost = stats[\"tokens\"] * base_cost_per_1m_tokens * multiplier \u002F 1_000_000\n            actual_cost += mode_cost\n            mode_breakdown[mode.value] = {\n                \"task_count\": stats[\"count\"],\n                \"tokens\": stats[\"tokens\"],\n                \"cost_usd\": round(mode_cost, 4),\n                \"cost_multiplier\": multiplier,\n            }\n\n        return {\n            \"total_tokens\": total_tokens,\n            \"all_realtime_cost_usd\": round(realtime_cost, 4),\n            \"actual_cost_usd\": round(actual_cost, 4),\n            \"savings_usd\": round(realtime_cost - actual_cost, 4),\n            \"savings_pct\": round(\n                (realtime_cost - actual_cost) \u002F realtime_cost * 100, 1\n            ) if realtime_cost > 0 else 0,\n            \"by_mode\": mode_breakdown,\n        }\n\n\n# Example: Schedule 1000 mixed tasks\nscheduler = WorkloadScheduler(micro_batch_size=20)\nimport random\nrandom.seed(42)\n\ntask_profiles = [\n    (\"chat_response\", 1500, 500),       # Must be fast\n    (\"email_draft\", 20000, 2000),        # Can wait 20 seconds\n    (\"document_classify\", 300000, 800),  # Can wait 5 minutes\n    (\"nightly_report\", 14400000, 5000),  # Can wait 4 hours\n    (\"embedding_gen\", 43200000, 300),    # Can wait 12 hours\n]\n\nfor i in range(1000):\n    task_type, max_latency, tokens = random.choice(task_profiles)\n    task = AgentTask(\n        task_id=f\"task_{i:04d}\",\n        task_type=task_type,\n        payload={\"content\": f\"task content {i}\"},\n        max_latency_ms=max_latency,\n        estimated_tokens=tokens,\n    )\n    scheduler.classify_and_enqueue(task)\n\nreport = scheduler.cost_savings_report(base_cost_per_1m_tokens=2.50)\nprint(f\"All real-time cost: ${report['all_realtime_cost_usd']}\")\nprint(f\"Scheduled cost:     ${report['actual_cost_usd']}\")\nprint(f\"Savings:            ${report['savings_usd']} ({report['savings_pct']}%)\")\nfor mode, data in report[\"by_mode\"].items():\n    print(f\"  {mode:20s}: {data['task_count']:4d} tasks, ${data['cost_usd']:.4f}\")\n```\n\n### Autoscaling Patterns for Agent Workloads\n\nAgent traffic is bursty. A customer support fleet might handle 200 requests per minute during business hours and 5 requests per minute overnight. Paying for peak capacity 24\u002F7 wastes 70-80% of off-peak compute. Autoscaling solves this -- but standard autoscaling policies designed for web servers perform poorly for agent workloads because agent requests are long-running (5-30 seconds vs 50-200ms for web requests) and resource-intensive.\n\n```python\nimport time\nimport math\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass ScalingConfig:\n    \"\"\"Autoscaling configuration for an agent inference fleet.\"\"\"\n    min_replicas: int = 1\n    max_replicas: int = 20\n    target_utilization_pct: float = 70.0\n    scale_up_threshold_pct: float = 80.0\n    scale_down_threshold_pct: float = 40.0\n    scale_up_cooldown_sec: float = 60.0\n    scale_down_cooldown_sec: float = 300.0\n    requests_per_replica: float = 10.0     # Max concurrent requests per replica\n    cost_per_replica_hour: float = 1.212   # A10G on-demand\n\n\nclass AgentAutoscaler:\n    \"\"\"Autoscaler optimized for AI agent workloads.\n\n    Key differences from standard web autoscalers:\n    1. Predictive scaling: uses time-of-day patterns to pre-scale\n    2. Request-duration-aware: accounts for long-running agent requests\n    3. Cost-aware: factors in cost when deciding scale-down speed\n    4. Warm pool: keeps a minimum warm pool to handle burst arrivals\n    \"\"\"\n\n    def __init__(self, config: ScalingConfig):\n        self.config = config\n        self.current_replicas = config.min_replicas\n        self._last_scale_up = 0.0\n        self._last_scale_down = 0.0\n        self._history: List[Dict[str, Any]] = []\n        self._hourly_patterns: Dict[int, float] = {}  # hour -> avg requests\n\n    def record_traffic(self, hour: int, requests_per_minute: float):\n        \"\"\"Record traffic pattern for predictive scaling.\"\"\"\n        if hour not in self._hourly_patterns:\n            self._hourly_patterns[hour] = requests_per_minute\n        else:\n            # Exponential moving average\n            self._hourly_patterns[hour] = (\n                0.7 * self._hourly_patterns[hour] + 0.3 * requests_per_minute\n            )\n\n    def evaluate(\n        self,\n        current_requests_per_minute: float,\n        avg_request_duration_sec: float,\n        current_hour: int,\n    ) -> Dict[str, Any]:\n        \"\"\"Evaluate whether to scale up, down, or hold.\n\n        Returns scaling decision with cost impact analysis.\n        \"\"\"\n        now = time.time()\n\n        # Calculate current utilization\n        concurrent_requests = current_requests_per_minute \u002F 60 * avg_request_duration_sec\n        capacity = self.current_replicas * self.config.requests_per_replica\n        utilization = (concurrent_requests \u002F capacity * 100) if capacity > 0 else 100\n\n        # Predictive component: look ahead 1 hour\n        next_hour = (current_hour + 1) % 24\n        predicted_rpm = self._hourly_patterns.get(next_hour, current_requests_per_minute)\n        predicted_concurrent = predicted_rpm \u002F 60 * avg_request_duration_sec\n\n        # Desired replicas based on current load\n        desired_current = math.ceil(\n            concurrent_requests \u002F (self.config.requests_per_replica\n                                   * self.config.target_utilization_pct \u002F 100)\n        )\n        # Desired replicas based on predicted load\n        desired_predicted = math.ceil(\n            predicted_concurrent \u002F (self.config.requests_per_replica\n                                    * self.config.target_utilization_pct \u002F 100)\n        )\n        # Take the higher of current and predicted (pre-scale for upcoming load)\n        desired = max(desired_current, desired_predicted)\n        desired = max(self.config.min_replicas, min(self.config.max_replicas, desired))\n\n        action = \"hold\"\n        new_replicas = self.current_replicas\n\n        if desired > self.current_replicas:\n            if now - self._last_scale_up >= self.config.scale_up_cooldown_sec:\n                new_replicas = desired\n                action = \"scale_up\"\n                self._last_scale_up = now\n        elif desired \u003C self.current_replicas:\n            if now - self._last_scale_down >= self.config.scale_down_cooldown_sec:\n                # Scale down gradually (max 25% at a time to avoid thrashing)\n                max_reduction = max(1, self.current_replicas \u002F\u002F 4)\n                new_replicas = max(desired, self.current_replicas - max_reduction)\n                action = \"scale_down\"\n                self._last_scale_down = now\n\n        cost_before = self.current_replicas * self.config.cost_per_replica_hour\n        cost_after = new_replicas * self.config.cost_per_replica_hour\n        old_replicas = self.current_replicas\n        self.current_replicas = new_replicas\n\n        decision = {\n            \"action\": action,\n            \"replicas_before\": old_replicas,\n            \"replicas_after\": new_replicas,\n            \"utilization_pct\": round(utilization, 1),\n            \"concurrent_requests\": round(concurrent_requests, 1),\n            \"predicted_next_hour_rpm\": round(predicted_rpm, 1),\n            \"hourly_cost_before\": round(cost_before, 2),\n            \"hourly_cost_after\": round(cost_after, 2),\n            \"hourly_savings\": round(cost_before - cost_after, 2),\n        }\n        self._history.append(decision)\n        return decision\n\n    def daily_cost_report(self) -> Dict[str, Any]:\n        \"\"\"Summarize daily scaling behavior and costs.\"\"\"\n        if not self._history:\n            return {\"error\": \"no scaling history\"}\n\n        total_replica_hours = sum(\n            d[\"replicas_after\"] for d in self._history\n        )  # Approximation: 1 evaluation per hour\n        max_cost = (\n            self.config.max_replicas * self.config.cost_per_replica_hour * len(self._history)\n        )\n        actual_cost = total_replica_hours * self.config.cost_per_replica_hour\n        always_on_cost = (\n            self._history[0][\"replicas_after\"] * self.config.cost_per_replica_hour\n            * len(self._history)\n        ) if self._history else 0\n\n        peak_replicas = max(d[\"replicas_after\"] for d in self._history)\n        min_replicas = min(d[\"replicas_after\"] for d in self._history)\n\n        return {\n            \"evaluations\": len(self._history),\n            \"peak_replicas\": peak_replicas,\n            \"min_replicas\": min_replicas,\n            \"avg_replicas\": round(total_replica_hours \u002F len(self._history), 1),\n            \"actual_cost_usd\": round(actual_cost, 2),\n            \"max_capacity_cost_usd\": round(max_cost, 2),\n            \"savings_vs_max_usd\": round(max_cost - actual_cost, 2),\n            \"savings_vs_max_pct\": round(\n                (max_cost - actual_cost) \u002F max_cost * 100, 1\n            ) if max_cost > 0 else 0,\n            \"scale_up_events\": sum(1 for d in self._history if d[\"action\"] == \"scale_up\"),\n            \"scale_down_events\": sum(1 for d in self._history if d[\"action\"] == \"scale_down\"),\n        }\n\n\n# Simulate a 24-hour traffic pattern\nautoscaler = AgentAutoscaler(ScalingConfig(\n    min_replicas=2,\n    max_replicas=20,\n    target_utilization_pct=70,\n    cost_per_replica_hour=1.212,\n    requests_per_replica=10,\n    scale_up_cooldown_sec=0,    # Disable cooldown for simulation\n    scale_down_cooldown_sec=0,\n))\n\n# Typical business-hours traffic pattern (requests per minute)\nhourly_traffic = {\n    0: 3, 1: 2, 2: 2, 3: 2, 4: 3, 5: 5,\n    6: 15, 7: 40, 8: 80, 9: 120, 10: 150, 11: 140,\n    12: 100, 13: 130, 14: 145, 15: 135, 16: 110, 17: 70,\n    18: 30, 19: 15, 20: 10, 21: 8, 22: 5, 23: 4,\n}\n\n# Train the predictor\nfor hour, rpm in hourly_traffic.items():\n    autoscaler.record_traffic(hour, rpm)\n\n# Simulate\nfor hour in range(24):\n    rpm = hourly_traffic[hour]\n    decision = autoscaler.evaluate(\n        current_requests_per_minute=rpm,\n        avg_request_duration_sec=8.0,\n        current_hour=hour,\n    )\n    print(\n        f\"Hour {hour:2d}: {rpm:3.0f} rpm, \"\n        f\"{decision['action']:10s} -> {decision['replicas_after']:2d} replicas, \"\n        f\"${decision['hourly_cost_after']:.2f}\u002Fhr, \"\n        f\"util={decision['utilization_pct']:.0f}%\"\n    )\n\nreport = autoscaler.daily_cost_report()\nprint(f\"\\nDaily cost: ${report['actual_cost_usd']}\")\nprint(f\"Max capacity cost: ${report['max_capacity_cost_usd']}\")\nprint(f\"Savings: ${report['savings_vs_max_usd']} ({report['savings_vs_max_pct']}%)\")\n```\n\n### Cache Layer Optimization\n\nCaching is the highest-ROI infrastructure investment for agent fleets. A semantic cache that stores responses for similar (not identical) queries can achieve 20-40% hit rates on typical agent workloads, eliminating those inference calls entirely. The cost of the cache infrastructure is a fraction of the inference cost it displaces.\n\n```python\nimport hashlib\nimport json\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any, Tuple\n\n\n@dataclass\nclass CacheEntry:\n    \"\"\"A cached agent response.\"\"\"\n    key: str\n    response: str\n    embedding: List[float]        # For semantic similarity matching\n    cost_avoided_usd: float       # What this call would have cost\n    created_at: float\n    ttl_seconds: float\n    hit_count: int = 0\n    last_hit_at: float = 0.0\n\n\nclass AgentResponseCache:\n    \"\"\"Multi-tier cache for agent responses.\n\n    Tier 1: Exact match (hash-based, O(1) lookup).\n    Tier 2: Semantic similarity (embedding-based, approximate).\n\n    Exact match handles repeated identical queries (common in\n    automated pipelines). Semantic match handles paraphrased\n    queries from different users asking the same thing.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_entries: int = 10_000,\n        semantic_threshold: float = 0.92,\n        default_ttl_sec: float = 3600.0,\n    ):\n        self.max_entries = max_entries\n        self.semantic_threshold = semantic_threshold\n        self.default_ttl = default_ttl_sec\n        self._exact_cache: Dict[str, CacheEntry] = {}\n        self._semantic_entries: List[CacheEntry] = []\n        self._stats = {\n            \"exact_hits\": 0,\n            \"semantic_hits\": 0,\n            \"misses\": 0,\n            \"total_cost_avoided_usd\": 0.0,\n            \"evictions\": 0,\n        }\n\n    def _hash_key(self, query: str, context: str = \"\") -> str:\n        \"\"\"Create an exact-match cache key.\"\"\"\n        content = f\"{query}|{context}\"\n        return hashlib.sha256(content.encode()).hexdigest()\n\n    def _cosine_similarity(self, a: List[float], b: List[float]) -> float:\n        \"\"\"Compute cosine similarity between two embedding vectors.\"\"\"\n        dot = sum(x * y for x, y in zip(a, b))\n        norm_a = sum(x * x for x in a) ** 0.5\n        norm_b = sum(x * x for x in b) ** 0.5\n        if norm_a == 0 or norm_b == 0:\n            return 0.0\n        return dot \u002F (norm_a * norm_b)\n\n    def get(\n        self,\n        query: str,\n        context: str = \"\",\n        query_embedding: Optional[List[float]] = None,\n    ) -> Optional[Tuple[str, str]]:\n        \"\"\"Look up a cached response.\n\n        Returns (response, cache_tier) or None.\n        \"\"\"\n        now = time.time()\n\n        # Tier 1: Exact match\n        key = self._hash_key(query, context)\n        if key in self._exact_cache:\n            entry = self._exact_cache[key]\n            if now - entry.created_at \u003C entry.ttl_seconds:\n                entry.hit_count += 1\n                entry.last_hit_at = now\n                self._stats[\"exact_hits\"] += 1\n                self._stats[\"total_cost_avoided_usd\"] += entry.cost_avoided_usd\n                return entry.response, \"exact\"\n            else:\n                del self._exact_cache[key]\n\n        # Tier 2: Semantic match\n        if query_embedding:\n            best_match = None\n            best_score = 0.0\n            for entry in self._semantic_entries:\n                if now - entry.created_at >= entry.ttl_seconds:\n                    continue\n                score = self._cosine_similarity(query_embedding, entry.embedding)\n                if score > best_score and score >= self.semantic_threshold:\n                    best_score = score\n                    best_match = entry\n\n            if best_match:\n                best_match.hit_count += 1\n                best_match.last_hit_at = now\n                self._stats[\"semantic_hits\"] += 1\n                self._stats[\"total_cost_avoided_usd\"] += best_match.cost_avoided_usd\n                return best_match.response, \"semantic\"\n\n        self._stats[\"misses\"] += 1\n        return None\n\n    def put(\n        self,\n        query: str,\n        response: str,\n        cost_usd: float,\n        context: str = \"\",\n        embedding: Optional[List[float]] = None,\n        ttl_seconds: Optional[float] = None,\n    ):\n        \"\"\"Store a response in the cache.\"\"\"\n        now = time.time()\n        ttl = ttl_seconds or self.default_ttl\n        key = self._hash_key(query, context)\n\n        entry = CacheEntry(\n            key=key,\n            response=response,\n            embedding=embedding or [],\n            cost_avoided_usd=cost_usd,\n            created_at=now,\n            ttl_seconds=ttl,\n        )\n\n        # Store in exact cache\n        self._exact_cache[key] = entry\n\n        # Store in semantic cache if embedding provided\n        if embedding:\n            self._semantic_entries.append(entry)\n\n        # Evict if over capacity (LRU by last_hit_at)\n        self._evict_if_needed()\n\n    def _evict_if_needed(self):\n        \"\"\"Evict least-recently-used entries if over capacity.\"\"\"\n        while len(self._exact_cache) > self.max_entries:\n            oldest_key = min(\n                self._exact_cache,\n                key=lambda k: self._exact_cache[k].last_hit_at,\n            )\n            del self._exact_cache[oldest_key]\n            self._stats[\"evictions\"] += 1\n\n        while len(self._semantic_entries) > self.max_entries:\n            self._semantic_entries.sort(key=lambda e: e.last_hit_at)\n            self._semantic_entries.pop(0)\n            self._stats[\"evictions\"] += 1\n\n    def cost_report(self) -> Dict[str, Any]:\n        \"\"\"Report cache performance and cost savings.\"\"\"\n        total_lookups = (\n            self._stats[\"exact_hits\"]\n            + self._stats[\"semantic_hits\"]\n            + self._stats[\"misses\"]\n        )\n        hit_rate = (\n            (self._stats[\"exact_hits\"] + self._stats[\"semantic_hits\"])\n            \u002F total_lookups * 100\n        ) if total_lookups > 0 else 0\n\n        # Estimate cache infrastructure cost\n        # Redis\u002FElastiCache: ~$0.017\u002FGB\u002Fhour, assume 1GB for 10K entries\n        cache_infra_monthly = 0.017 * 24 * 30  # ~$12.24\u002Fmo for 1GB\n\n        return {\n            \"total_lookups\": total_lookups,\n            \"exact_hits\": self._stats[\"exact_hits\"],\n            \"semantic_hits\": self._stats[\"semantic_hits\"],\n            \"misses\": self._stats[\"misses\"],\n            \"hit_rate_pct\": round(hit_rate, 1),\n            \"total_cost_avoided_usd\": round(self._stats[\"total_cost_avoided_usd\"], 2),\n            \"cache_infra_monthly_usd\": round(cache_infra_monthly, 2),\n            \"net_savings_usd\": round(\n                self._stats[\"total_cost_avoided_usd\"] - cache_infra_monthly \u002F 30, 2\n            ),\n            \"cached_entries\": len(self._exact_cache),\n            \"evictions\": self._stats[\"evictions\"],\n        }\n\n\n# Simulate cache usage\ncache = AgentResponseCache(\n    max_entries=5000,\n    semantic_threshold=0.92,\n    default_ttl_sec=3600,\n)\n\n# Simulate 10,000 queries with 30% repetition rate\nrandom.seed(42)\nunique_queries = [f\"What is the status of order {i}?\" for i in range(700)]\nunique_queries += [f\"Explain the return policy for item {i}\" for i in range(300)]\n\nfor i in range(10000):\n    query = random.choice(unique_queries)\n    # Simple fake embedding: hash-based deterministic vector\n    embedding = [\n        float(int(hashlib.md5(f\"{query}_{d}\".encode()).hexdigest()[:4], 16)) \u002F 65535\n        for d in range(64)\n    ]\n\n    result = cache.get(query, query_embedding=embedding)\n    if result is None:\n        # Cache miss: \"call\" the LLM and cache the response\n        cache.put(\n            query=query,\n            response=f\"Response for: {query}\",\n            cost_usd=0.008,\n            embedding=embedding,\n        )\n\nreport = cache.cost_report()\nprint(f\"Hit rate: {report['hit_rate_pct']}%\")\nprint(f\"Cost avoided: ${report['total_cost_avoided_usd']}\")\nprint(f\"Cache infra cost: ${report['cache_infra_monthly_usd']}\u002Fmo\")\n```\n\n### Storage Tiering for Agent Memory\n\nAgent memory -- conversation history, tool call results, learned preferences, and vector embeddings -- grows monotonically and never self-prunes. A single long-running agent conversation can accumulate 200,000+ tokens of history. Multiply by thousands of concurrent conversations, and storage costs become material. The solution is tiered storage that moves data between cost tiers based on access patterns.\n\n| Storage Tier | Cost ($\u002FGB\u002Fmonth) | Access Latency | Use Case |\n|---|---|---|---|\n| In-memory (Redis) | $12.24 | \u003C 1ms | Active conversation context, hot cache |\n| SSD (EBS gp3) | $0.08 | 1-5ms | Recent conversation history (\u003C 24hr) |\n| Object storage (S3) | $0.023 | 50-100ms | Archived conversations, audit logs |\n| Cold archive (S3 Glacier) | $0.004 | 3-5 hours | Compliance retention, training data |\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass StorageTier:\n    name: str\n    cost_per_gb_month: float\n    access_latency_ms: float\n    max_access_latency_ms: float\n\n\n@dataclass\nclass MemoryObject:\n    \"\"\"A piece of agent memory (conversation, embedding, etc.).\"\"\"\n    object_id: str\n    agent_id: str\n    size_bytes: int\n    created_at: float\n    last_accessed_at: float\n    access_count: int = 0\n    current_tier: str = \"hot\"\n\n\nclass StorageTierManager:\n    \"\"\"Manages automatic tiering of agent memory across storage tiers.\n\n    Implements time-based and access-based policies to move data\n    from expensive, fast tiers to cheap, slow tiers as it ages.\n    \"\"\"\n\n    TIERS = {\n        \"hot\": StorageTier(\"hot\", 12.24, 0.5, 1.0),\n        \"warm\": StorageTier(\"warm\", 0.08, 3.0, 5.0),\n        \"cold\": StorageTier(\"cold\", 0.023, 75.0, 100.0),\n        \"archive\": StorageTier(\"archive\", 0.004, 18_000_000.0, 18_000_000.0),\n    }\n\n    # Tier transition rules (seconds since last access)\n    TIER_RULES = {\n        \"hot\": {\"max_idle_sec\": 3600, \"demote_to\": \"warm\"},          # 1 hour\n        \"warm\": {\"max_idle_sec\": 86400, \"demote_to\": \"cold\"},        # 24 hours\n        \"cold\": {\"max_idle_sec\": 2592000, \"demote_to\": \"archive\"},   # 30 days\n    }\n\n    def __init__(self):\n        self._objects: Dict[str, MemoryObject] = {}\n        self._tier_sizes: Dict[str, int] = {tier: 0 for tier in self.TIERS}\n        self._transitions: List[Dict[str, Any]] = []\n\n    def store(self, obj: MemoryObject):\n        \"\"\"Store a new memory object in the hot tier.\"\"\"\n        self._objects[obj.object_id] = obj\n        self._tier_sizes[obj.current_tier] += obj.size_bytes\n\n    def access(self, object_id: str) -> Optional[MemoryObject]:\n        \"\"\"Access a memory object. Promotes to hot tier if needed.\"\"\"\n        obj = self._objects.get(object_id)\n        if obj is None:\n            return None\n\n        obj.last_accessed_at = time.time()\n        obj.access_count += 1\n\n        # Promote to hot if accessed from a lower tier\n        if obj.current_tier != \"hot\":\n            self._transition(obj, \"hot\")\n\n        return obj\n\n    def run_tiering(self):\n        \"\"\"Evaluate all objects and demote idle ones to lower tiers.\"\"\"\n        now = time.time()\n        for obj in list(self._objects.values()):\n            rule = self.TIER_RULES.get(obj.current_tier)\n            if rule is None:\n                continue  # Archive tier has no demotion\n\n            idle_seconds = now - obj.last_accessed_at\n            if idle_seconds > rule[\"max_idle_sec\"]:\n                self._transition(obj, rule[\"demote_to\"])\n\n    def _transition(self, obj: MemoryObject, new_tier: str):\n        \"\"\"Move an object between tiers.\"\"\"\n        old_tier = obj.current_tier\n        self._tier_sizes[old_tier] -= obj.size_bytes\n        self._tier_sizes[new_tier] += obj.size_bytes\n        obj.current_tier = new_tier\n\n        self._transitions.append({\n            \"object_id\": obj.object_id,\n            \"from_tier\": old_tier,\n            \"to_tier\": new_tier,\n            \"size_bytes\": obj.size_bytes,\n        })\n\n    def cost_report(self) -> Dict[str, Any]:\n        \"\"\"Calculate monthly storage costs by tier.\"\"\"\n        tier_costs = {}\n        total_cost = 0.0\n        total_bytes = 0\n\n        for tier_name, tier in self.TIERS.items():\n            size_gb = self._tier_sizes[tier_name] \u002F (1024 ** 3)\n            cost = size_gb * tier.cost_per_gb_month\n            tier_costs[tier_name] = {\n                \"size_gb\": round(size_gb, 4),\n                \"monthly_cost_usd\": round(cost, 4),\n                \"object_count\": sum(\n                    1 for o in self._objects.values() if o.current_tier == tier_name\n                ),\n            }\n            total_cost += cost\n            total_bytes += self._tier_sizes[tier_name]\n\n        # Calculate what it would cost if everything were in hot tier\n        all_hot_cost = (total_bytes \u002F (1024 ** 3)) * self.TIERS[\"hot\"].cost_per_gb_month\n\n        return {\n            \"total_size_gb\": round(total_bytes \u002F (1024 ** 3), 4),\n            \"total_monthly_cost_usd\": round(total_cost, 4),\n            \"all_hot_cost_usd\": round(all_hot_cost, 4),\n            \"savings_usd\": round(all_hot_cost - total_cost, 4),\n            \"savings_pct\": round(\n                (all_hot_cost - total_cost) \u002F all_hot_cost * 100, 1\n            ) if all_hot_cost > 0 else 0,\n            \"tiers\": tier_costs,\n            \"total_transitions\": len(self._transitions),\n        }\n\n\n# Simulate 30 days of agent memory accumulation and tiering\nmanager = StorageTierManager()\n\nnow = time.time()\nrandom.seed(42)\n\n# Create 5000 conversation memory objects over 30 days\nfor i in range(5000):\n    days_ago = random.uniform(0, 30)\n    created = now - (days_ago * 86400)\n    # More recent objects are more likely to be accessed recently\n    last_access_offset = random.expovariate(1.0 \u002F (days_ago * 86400 + 3600))\n    last_accessed = min(now, created + last_access_offset)\n\n    obj = MemoryObject(\n        object_id=f\"conv_{i:05d}\",\n        agent_id=f\"agent_{i % 12:02d}\",\n        size_bytes=random.randint(50_000, 500_000),  # 50KB-500KB per conversation\n        created_at=created,\n        last_accessed_at=last_accessed,\n        access_count=random.randint(1, 50),\n        current_tier=\"hot\",\n    )\n    manager.store(obj)\n\n# Run tiering\nmanager.run_tiering()\n\nreport = manager.cost_report()\nprint(f\"Total storage: {report['total_size_gb']:.2f} GB\")\nprint(f\"Tiered cost: ${report['total_monthly_cost_usd']:.2f}\u002Fmo\")\nprint(f\"All-hot cost: ${report['all_hot_cost_usd']:.2f}\u002Fmo\")\nprint(f\"Savings: ${report['savings_usd']:.2f}\u002Fmo ({report['savings_pct']}%)\")\nfor tier, data in report[\"tiers\"].items():\n    print(f\"  {tier:8s}: {data['object_count']:5d} objects, \"\n          f\"{data['size_gb']:.3f} GB, ${data['monthly_cost_usd']:.4f}\u002Fmo\")\n```\n\n### Network Cost Reduction\n\nNetwork egress is the silent cost killer in distributed agent architectures. Every API call to an LLM provider sends tokens out and receives tokens back. Every inter-service call between agents in a pipeline crosses a network boundary. At AWS's standard egress rate of $0.09\u002FGB, a fleet sending 50GB\u002Fmonth of prompt data to external APIs pays $4.50 in egress alone -- modest. But add inter-service traffic between agents, observability data shipped to external collectors, and embedding vectors transferred between services, and network costs can reach $200-500\u002Fmonth for a medium fleet.\n\nThree strategies reduce network costs significantly. First, co-locate communicating services. Agents that frequently call each other should run in the same availability zone ($0.00\u002FGB intra-AZ vs $0.01\u002FGB inter-AZ). Second, compress payloads. gzip compression reduces JSON payloads by 70-85%, and agent payloads (mostly text) compress extremely well. Third, use regional endpoints. If your agents serve global users but call a single LLM API region, deploy regional proxy caches that batch and deduplicate requests before forwarding to the provider.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any\n\n\n@dataclass\nclass NetworkCostModel:\n    \"\"\"Models network costs for an agent fleet.\"\"\"\n    egress_per_gb: float = 0.09           # AWS standard\n    inter_az_per_gb: float = 0.01\n    intra_az_per_gb: float = 0.00\n    compression_ratio: float = 0.20       # Compressed size as fraction of original\n\n    def monthly_cost(\n        self,\n        api_calls_per_day: int,\n        avg_payload_kb: float,\n        inter_service_calls_per_day: int,\n        inter_service_payload_kb: float,\n        observability_gb_per_day: float,\n        cross_az_pct: float = 0.30,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate monthly network costs with and without optimization.\"\"\"\n        days = 30\n\n        # API egress (uncompressed)\n        api_gb = api_calls_per_day * avg_payload_kb \u002F (1024 * 1024) * days\n        api_cost = api_gb * self.egress_per_gb\n\n        # Inter-service traffic\n        inter_gb = (\n            inter_service_calls_per_day * inter_service_payload_kb\n            \u002F (1024 * 1024) * days\n        )\n        inter_cost = (\n            inter_gb * cross_az_pct * self.inter_az_per_gb\n            + inter_gb * (1 - cross_az_pct) * self.intra_az_per_gb\n        )\n\n        # Observability egress\n        obs_gb = observability_gb_per_day * days\n        obs_cost = obs_gb * self.egress_per_gb\n\n        total_unoptimized = api_cost + inter_cost + obs_cost\n\n        # Optimized: compression + co-location\n        api_cost_opt = api_gb * self.compression_ratio * self.egress_per_gb\n        inter_cost_opt = inter_gb * 0.05 * self.inter_az_per_gb  # 95% co-located\n        obs_cost_opt = obs_gb * self.compression_ratio * self.egress_per_gb\n\n        total_optimized = api_cost_opt + inter_cost_opt + obs_cost_opt\n\n        return {\n            \"unoptimized\": {\n                \"api_egress_usd\": round(api_cost, 2),\n                \"inter_service_usd\": round(inter_cost, 2),\n                \"observability_usd\": round(obs_cost, 2),\n                \"total_usd\": round(total_unoptimized, 2),\n            },\n            \"optimized\": {\n                \"api_egress_usd\": round(api_cost_opt, 2),\n                \"inter_service_usd\": round(inter_cost_opt, 2),\n                \"observability_usd\": round(obs_cost_opt, 2),\n                \"total_usd\": round(total_optimized, 2),\n            },\n            \"savings_usd\": round(total_unoptimized - total_optimized, 2),\n            \"savings_pct\": round(\n                (total_unoptimized - total_optimized) \u002F total_unoptimized * 100, 1\n            ) if total_unoptimized > 0 else 0,\n        }\n\n\n# Example: medium-sized agent fleet\nnetwork = NetworkCostModel()\nresult = network.monthly_cost(\n    api_calls_per_day=50_000,\n    avg_payload_kb=12.0,\n    inter_service_calls_per_day=200_000,\n    inter_service_payload_kb=4.0,\n    observability_gb_per_day=2.5,\n    cross_az_pct=0.30,\n)\nprint(f\"Unoptimized: ${result['unoptimized']['total_usd']}\u002Fmo\")\nprint(f\"Optimized:   ${result['optimized']['total_usd']}\u002Fmo\")\nprint(f\"Savings:     ${result['savings_usd']}\u002Fmo ({result['savings_pct']}%)\")\n```\n\n---\n\n## Chapter 8: Cost Optimization Playbook\n\n### The Eight-Week Plan\n\nThe strategies in Chapters 1-7 are individually powerful but collectively overwhelming. This chapter turns them into a sequenced execution plan. The order is deliberate: early weeks focus on measurement and quick wins that fund later investments. Later weeks tackle structural changes that deliver compounding returns. Each week has a defined owner, deliverable, and expected savings.\n\n**Baseline assumptions.** This playbook is calibrated for a team running 8-15 agents in production with a monthly AI infrastructure bill of $8,000-25,000. If your bill is smaller, the absolute savings shrink but the percentages hold. If your bill is larger, the savings are proportionally bigger and the ROI on engineering time is even higher.\n\n| Week | Focus Area | Owner | Expected Savings | Cumulative Savings |\n|---|---|---|---|---|\n| 1 | Instrumentation and cost visibility | Platform engineer | 0% (measurement) | 0% |\n| 2 | Prompt compression and system prompt optimization | ML engineer | 8-12% | 8-12% |\n| 3 | Model routing (tiered model assignment) | ML engineer | 15-25% | 23-37% |\n| 4 | Observability cost control | Platform engineer | 5-10% | 28-47% |\n| 5 | Caching layer deployment | Backend engineer | 8-15% | 36-62% |\n| 6 | Batch processing for async workloads | Backend engineer | 5-10% | 41-72% |\n| 7 | Infrastructure right-sizing and autoscaling | DevOps engineer | 5-12% | 46-84% |\n| 8 | Outcome-based metering and governance framework | Engineering manager | 3-5% (+ ongoing gains) | 49-89% |\n\n### Week 1: Instrumentation and Cost Visibility\n\nYou cannot optimize what you cannot see. Week 1 deploys the `CostTracker` from Chapter 1 across every agent in production. Every LLM call, tool invocation, and storage operation gets a cost tag. By end of week, you have a dashboard showing cost-per-agent, cost-per-operation, and cost-per-category breakdown.\n\n**Deliverables:**\n- CostTracker integrated into all agent entry points\n- Daily cost report emailed to engineering and finance\n- Top-5 cost drivers identified with specific dollar amounts\n\n**Common findings from Week 1 instrumentation:**\n- One agent consuming 40-60% of total budget (the \"cost hog\")\n- System prompt bloat adding $500-2,000\u002Fmonth in unnecessary tokens\n- Retry storms on a single flaky tool doubling that agent's cost\n- Observability costs 15-30% of inference costs\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass WeeklyTarget:\n    \"\"\"A single week's optimization target.\"\"\"\n    week: int\n    focus: str\n    owner: str\n    tasks: List[str]\n    expected_savings_pct_low: float\n    expected_savings_pct_high: float\n    dependencies: List[int] = field(default_factory=list)\n    completed: bool = False\n    actual_savings_pct: float = 0.0\n\n\nclass OptimizationPlaybook:\n    \"\"\"Manages an 8-week cost optimization program.\n\n    Tracks progress, calculates cumulative savings, and generates\n    executive reports showing ROI on engineering investment.\n    \"\"\"\n\n    def __init__(self, monthly_baseline_usd: float):\n        self.baseline = monthly_baseline_usd\n        self.weeks: List[WeeklyTarget] = self._build_plan()\n        self._weekly_spend: Dict[int, float] = {}\n\n    def _build_plan(self) -> List[WeeklyTarget]:\n        return [\n            WeeklyTarget(\n                week=1,\n                focus=\"Instrumentation and cost visibility\",\n                owner=\"Platform engineer\",\n                tasks=[\n                    \"Deploy CostTracker to all agents\",\n                    \"Set up daily cost report pipeline\",\n                    \"Identify top-5 cost drivers\",\n                    \"Baseline cost-per-agent metrics\",\n                ],\n                expected_savings_pct_low=0,\n                expected_savings_pct_high=0,\n            ),\n            WeeklyTarget(\n                week=2,\n                focus=\"Prompt compression and optimization\",\n                owner=\"ML engineer\",\n                tasks=[\n                    \"Audit all system prompts with TokenWasteAnalyzer\",\n                    \"Compress top-3 highest-cost prompts\",\n                    \"Remove redundant few-shot examples\",\n                    \"Optimize tool descriptions\",\n                    \"A\u002FB test compressed vs original prompts\",\n                ],\n                expected_savings_pct_low=8,\n                expected_savings_pct_high=12,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=3,\n                focus=\"Model routing\",\n                owner=\"ML engineer\",\n                tasks=[\n                    \"Classify all agent tasks by complexity tier\",\n                    \"Deploy ModelRouter with conservative routing rules\",\n                    \"Route SIMPLE tasks to cheap models (GPT-4o-mini\u002FHaiku)\",\n                    \"Monitor quality metrics for routed tasks\",\n                    \"Expand routing to MODERATE tasks if quality holds\",\n                ],\n                expected_savings_pct_low=15,\n                expected_savings_pct_high=25,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=4,\n                focus=\"Observability cost control\",\n                owner=\"Platform engineer\",\n                tasks=[\n                    \"Deploy AdaptiveSampler for trace sampling\",\n                    \"Implement metric cardinality limits\",\n                    \"Switch to structured logging with level optimization\",\n                    \"Separate AI telemetry from infra telemetry\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=10,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=5,\n                focus=\"Caching layer deployment\",\n                owner=\"Backend engineer\",\n                tasks=[\n                    \"Deploy AgentResponseCache with exact matching\",\n                    \"Add semantic similarity matching\",\n                    \"Tune cache TTL based on content type\",\n                    \"Monitor hit rates and quality of cached responses\",\n                ],\n                expected_savings_pct_low=8,\n                expected_savings_pct_high=15,\n                dependencies=[1, 2],\n            ),\n            WeeklyTarget(\n                week=6,\n                focus=\"Batch processing for async workloads\",\n                owner=\"Backend engineer\",\n                tasks=[\n                    \"Identify tasks tolerant of >5 minute latency\",\n                    \"Deploy WorkloadScheduler with micro-batch queues\",\n                    \"Migrate nightly\u002Fweekly report generation to batch API\",\n                    \"Set up batch job monitoring\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=10,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=7,\n                focus=\"Infrastructure right-sizing and autoscaling\",\n                owner=\"DevOps engineer\",\n                tasks=[\n                    \"Analyze GPU utilization and right-size instances\",\n                    \"Deploy AgentAutoscaler with predictive scaling\",\n                    \"Implement storage tiering for agent memory\",\n                    \"Optimize network costs (co-location, compression)\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=12,\n                dependencies=[1, 6],\n            ),\n            WeeklyTarget(\n                week=8,\n                focus=\"Outcome metering and governance\",\n                owner=\"Engineering manager\",\n                tasks=[\n                    \"Deploy OutcomeMeter for cost-per-success tracking\",\n                    \"Define quality gates for each agent\",\n                    \"Set up cost governance alerts and budgets\",\n                    \"Establish monthly cost review cadence\",\n                    \"Create executive cost report template\",\n                ],\n                expected_savings_pct_low=3,\n                expected_savings_pct_high=5,\n                dependencies=[1, 2, 3],\n            ),\n        ]\n\n    def record_week(self, week: int, actual_spend_usd: float, savings_pct: float):\n        \"\"\"Record actual results for a completed week.\"\"\"\n        self._weekly_spend[week] = actual_spend_usd\n        target = self.weeks[week - 1]\n        target.completed = True\n        target.actual_savings_pct = savings_pct\n\n    def progress_report(self) -> Dict[str, Any]:\n        \"\"\"Generate a progress report across all weeks.\"\"\"\n        completed = [w for w in self.weeks if w.completed]\n        cumulative_savings_pct = sum(w.actual_savings_pct for w in completed)\n        monthly_savings_usd = self.baseline * cumulative_savings_pct \u002F 100\n        projected_annual_savings = monthly_savings_usd * 12\n\n        return {\n            \"baseline_monthly_usd\": self.baseline,\n            \"weeks_completed\": len(completed),\n            \"weeks_remaining\": len(self.weeks) - len(completed),\n            \"cumulative_savings_pct\": round(cumulative_savings_pct, 1),\n            \"monthly_savings_usd\": round(monthly_savings_usd, 2),\n            \"projected_annual_savings_usd\": round(projected_annual_savings, 2),\n            \"current_monthly_spend_usd\": round(\n                self.baseline - monthly_savings_usd, 2\n            ),\n            \"week_details\": [\n                {\n                    \"week\": w.week,\n                    \"focus\": w.focus,\n                    \"status\": \"completed\" if w.completed else \"pending\",\n                    \"actual_savings_pct\": w.actual_savings_pct if w.completed else None,\n                    \"expected_range\": f\"{w.expected_savings_pct_low}-{w.expected_savings_pct_high}%\",\n                }\n                for w in self.weeks\n            ],\n        }\n\n    def roi_calculation(\n        self,\n        engineer_hours_per_week: float = 30.0,\n        engineer_hourly_rate: float = 95.0,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate ROI of the optimization program.\n\n        Compares engineering investment against realized savings.\n        Assumes savings compound monthly (each month benefits from\n        all previous optimizations).\n        \"\"\"\n        completed = [w for w in self.weeks if w.completed]\n        total_eng_hours = len(completed) * engineer_hours_per_week\n        total_eng_cost = total_eng_hours * engineer_hourly_rate\n\n        # Monthly savings grow as each week's optimization is deployed\n        total_savings_12mo = 0.0\n        cumulative_pct = 0.0\n        for w in self.weeks:\n            if w.completed:\n                cumulative_pct += w.actual_savings_pct\n            monthly_saving = self.baseline * cumulative_pct \u002F 100\n            # This week's savings apply for (12 - week_number) months\n            remaining_months = max(0, 12 - w.week + 1)\n            total_savings_12mo += monthly_saving * (remaining_months \u002F 12)\n\n        annual_savings = total_savings_12mo * 12 \u002F max(1, len(self.weeks))\n        roi = ((annual_savings - total_eng_cost) \u002F total_eng_cost * 100) if total_eng_cost > 0 else 0\n\n        return {\n            \"engineering_investment\": {\n                \"total_hours\": total_eng_hours,\n                \"hourly_rate_usd\": engineer_hourly_rate,\n                \"total_cost_usd\": round(total_eng_cost, 2),\n            },\n            \"savings\": {\n                \"monthly_recurring_usd\": round(\n                    self.baseline * cumulative_pct \u002F 100, 2\n                ),\n                \"projected_annual_usd\": round(annual_savings, 2),\n            },\n            \"roi_pct\": round(roi, 1),\n            \"payback_period_weeks\": round(\n                total_eng_cost \u002F (self.baseline * cumulative_pct \u002F 100 \u002F 4.33), 1\n            ) if cumulative_pct > 0 else float(\"inf\"),\n        }\n\n\n# Example: Run the playbook for a $15,000\u002Fmonth fleet\nplaybook = OptimizationPlaybook(monthly_baseline_usd=15_000)\n\n# Simulate completing all 8 weeks with realistic savings\nactual_results = [\n    (1, 15000, 0),     # Week 1: measurement only\n    (2, 13650, 9),     # Week 2: prompt compression saved 9%\n    (3, 10920, 18),    # Week 3: model routing saved 18%\n    (4, 9828, 7),      # Week 4: observability saved 7%\n    (5, 8356, 10),     # Week 5: caching saved 10%\n    (6, 7521, 6),      # Week 6: batch processing saved 6%\n    (7, 6394, 8),      # Week 7: infrastructure saved 8%\n    (8, 6074, 2),      # Week 8: governance saved 2%\n]\n\nfor week, spend, savings in actual_results:\n    playbook.record_week(week, spend, savings)\n\nreport = playbook.progress_report()\nprint(f\"Baseline: ${report['baseline_monthly_usd']:,.0f}\u002Fmo\")\nprint(f\"Current:  ${report['current_monthly_spend_usd']:,.0f}\u002Fmo\")\nprint(f\"Savings:  {report['cumulative_savings_pct']}% \"\n      f\"(${report['monthly_savings_usd']:,.0f}\u002Fmo)\")\nprint(f\"Annual:   ${report['projected_annual_savings_usd']:,.0f}\")\n\nroi = playbook.roi_calculation(engineer_hours_per_week=30, engineer_hourly_rate=95)\nprint(f\"\\nEngineering investment: ${roi['engineering_investment']['total_cost_usd']:,.0f}\")\nprint(f\"Annual savings: ${roi['savings']['projected_annual_usd']:,.0f}\")\nprint(f\"ROI: {roi['roi_pct']}%\")\nprint(f\"Payback period: {roi['payback_period_weeks']} weeks\")\n```\n\n### Quick Wins vs Long-Term Investments\n\nNot all optimizations have the same effort-to-impact ratio. The following matrix categorizes every strategy from this cookbook by implementation effort and expected savings magnitude. Start with the upper-left quadrant (low effort, high impact) and work toward the lower-right.\n\n| Strategy | Effort (days) | Monthly Savings | Payback Period | Category |\n|---|---|---|---|---|\n| Prompt compression | 1-2 | 8-12% | Immediate | Quick win |\n| Tool description compression | 0.5-1 | 2-4% | Immediate | Quick win |\n| Batch API for async tasks | 1-2 | 5-10% | Immediate | Quick win |\n| Response format optimization | 0.5-1 | 2-5% | Immediate | Quick win |\n| Model routing (simple tasks) | 3-5 | 15-25% | 1-2 weeks | High-impact investment |\n| Semantic caching | 5-8 | 8-15% | 2-3 weeks | High-impact investment |\n| Adaptive trace sampling | 2-3 | 5-10% | 1 week | High-impact investment |\n| Autoscaling (predictive) | 5-10 | 5-12% | 3-4 weeks | Long-term investment |\n| Self-hosted inference | 10-20 | 20-50% | 4-8 weeks | Long-term investment |\n| Storage tiering | 3-5 | 2-5% | 2-3 weeks | Long-term investment |\n| Outcome-based metering | 5-8 | 3-5% ongoing | 3-4 weeks | Strategic investment |\n| Full cost governance framework | 8-15 | 5-10% ongoing | 6-8 weeks | Strategic investment |\n\n```python\nfrom dataclasses import dataclass\nfrom typing import List, Dict, Any\n\n\n@dataclass\nclass OptimizationStrategy:\n    \"\"\"A single cost optimization strategy with effort and impact.\"\"\"\n    name: str\n    effort_days_low: float\n    effort_days_high: float\n    savings_pct_low: float\n    savings_pct_high: float\n    category: str  # quick_win, high_impact, long_term, strategic\n    chapter: int\n    recurring: bool = False  # True if savings compound over time\n\n\nclass OptimizationPrioritizer:\n    \"\"\"Prioritizes optimization strategies by ROI.\n\n    Ranks strategies by savings-per-engineering-day, helping teams\n    decide what to tackle first given limited engineering bandwidth.\n    \"\"\"\n\n    STRATEGIES = [\n        OptimizationStrategy(\"Prompt compression\", 1, 2, 8, 12, \"quick_win\", 5),\n        OptimizationStrategy(\"Tool description compression\", 0.5, 1, 2, 4, \"quick_win\", 5),\n        OptimizationStrategy(\"Batch API for async tasks\", 1, 2, 5, 10, \"quick_win\", 7),\n        OptimizationStrategy(\"Response format optimization\", 0.5, 1, 2, 5, \"quick_win\", 5),\n        OptimizationStrategy(\"Model routing\", 3, 5, 15, 25, \"high_impact\", 3),\n        OptimizationStrategy(\"Semantic caching\", 5, 8, 8, 15, \"high_impact\", 7),\n        OptimizationStrategy(\"Adaptive trace sampling\", 2, 3, 5, 10, \"high_impact\", 4),\n        OptimizationStrategy(\"Predictive autoscaling\", 5, 10, 5, 12, \"long_term\", 7),\n        OptimizationStrategy(\"Self-hosted inference\", 10, 20, 20, 50, \"long_term\", 7),\n        OptimizationStrategy(\"Storage tiering\", 3, 5, 2, 5, \"long_term\", 7),\n        OptimizationStrategy(\"Outcome-based metering\", 5, 8, 3, 5, \"strategic\", 6, True),\n        OptimizationStrategy(\"Cost governance framework\", 8, 15, 5, 10, \"strategic\", 8, True),\n    ]\n\n    def __init__(self, monthly_spend_usd: float, engineer_daily_rate: float = 760.0):\n        self.monthly_spend = monthly_spend_usd\n        self.daily_rate = engineer_daily_rate  # $95\u002Fhr * 8hr\n\n    def prioritize(self) -> List[Dict[str, Any]]:\n        \"\"\"Rank strategies by ROI (savings per engineering dollar).\"\"\"\n        ranked = []\n        for s in self.STRATEGIES:\n            avg_effort = (s.effort_days_low + s.effort_days_high) \u002F 2\n            avg_savings_pct = (s.savings_pct_low + s.savings_pct_high) \u002F 2\n            monthly_savings = self.monthly_spend * avg_savings_pct \u002F 100\n            annual_savings = monthly_savings * 12\n            eng_cost = avg_effort * self.daily_rate\n\n            roi = ((annual_savings - eng_cost) \u002F eng_cost * 100) if eng_cost > 0 else 0\n            savings_per_eng_day = monthly_savings \u002F avg_effort if avg_effort > 0 else 0\n\n            ranked.append({\n                \"strategy\": s.name,\n                \"category\": s.category,\n                \"chapter\": s.chapter,\n                \"effort_days\": f\"{s.effort_days_low}-{s.effort_days_high}\",\n                \"savings_pct\": f\"{s.savings_pct_low}-{s.savings_pct_high}%\",\n                \"monthly_savings_usd\": round(monthly_savings, 2),\n                \"annual_savings_usd\": round(annual_savings, 2),\n                \"engineering_cost_usd\": round(eng_cost, 2),\n                \"roi_pct\": round(roi, 1),\n                \"savings_per_eng_day_usd\": round(savings_per_eng_day, 2),\n            })\n\n        ranked.sort(key=lambda r: r[\"savings_per_eng_day_usd\"], reverse=True)\n        return ranked\n\n    def print_priority_report(self):\n        \"\"\"Print a formatted priority report.\"\"\"\n        ranked = self.prioritize()\n        print(f\"{'Strategy':\u003C35} {'Effort':>8} {'Savings\u002Fmo':>12} \"\n              f\"{'Eng Cost':>10} {'ROI':>8} {'$\u002Feng-day':>10}\")\n        print(\"-\" * 85)\n        for r in ranked:\n            print(f\"{r['strategy']:\u003C35} {r['effort_days']:>8} \"\n                  f\"${r['monthly_savings_usd']:>10,.0f} \"\n                  f\"${r['engineering_cost_usd']:>8,.0f} \"\n                  f\"{r['roi_pct']:>7.0f}% \"\n                  f\"${r['savings_per_eng_day_usd']:>8,.0f}\")\n\n\n# Example: Prioritize for a $15,000\u002Fmonth fleet\nprioritizer = OptimizationPrioritizer(monthly_spend_usd=15_000)\nprioritizer.print_priority_report()\n```\n\n### Monitoring Dashboard Design\n\nSustained optimization requires continuous monitoring. A single dashboard with four panels gives your team real-time visibility into cost health.\n\n**Panel 1: Cost Burn Rate.** A time-series chart showing hourly cost across all agents, stacked by category (inference, tools, observability, storage, orchestration). The burn rate line should have an overlay showing the budget line -- if the burn rate consistently exceeds budget, an alert fires.\n\n**Panel 2: Cost Per Outcome.** A time-series showing cost-per-successful-outcome for each agent. This is the single most important metric. If cost-per-outcome rises while total cost stays flat, your agents are getting less efficient. If cost-per-outcome drops while total cost rises, you are scaling efficiently.\n\n**Panel 3: Model Router Performance.** A breakdown showing which model handles what percentage of requests, cost per model tier, and quality scores per tier. A stacked bar chart with SIMPLE\u002FMODERATE\u002FCOMPLEX\u002FCRITICAL tiers lets you see if routing is working.\n\n**Panel 4: Waste Tracker.** A gauge showing three waste metrics: token waste percentage (from TokenWasteAnalyzer), failure waste (cost of failed outcomes), and retry waste (cost of retries that eventually succeeded). Each gauge should have a target zone (green), warning zone (yellow), and critical zone (red).\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass DashboardMetric:\n    \"\"\"A single metric for the cost monitoring dashboard.\"\"\"\n    name: str\n    value: float\n    unit: str\n    threshold_warning: float\n    threshold_critical: float\n    trend: str = \"stable\"  # improving, degrading, stable\n\n\nclass CostDashboard:\n    \"\"\"Generates cost monitoring dashboard data.\n\n    Produces structured data suitable for rendering in Grafana,\n    Datadog, or any dashboard tool that accepts JSON metrics.\n    \"\"\"\n\n    def __init__(self, monthly_budget_usd: float):\n        self.budget = monthly_budget_usd\n        self._hourly_costs: List[Dict[str, float]] = []\n        self._outcome_costs: List[Dict[str, float]] = []\n\n    def record_hourly_snapshot(\n        self,\n        inference_usd: float,\n        tools_usd: float,\n        observability_usd: float,\n        storage_usd: float,\n        orchestration_usd: float,\n    ):\n        \"\"\"Record an hourly cost snapshot.\"\"\"\n        self._hourly_costs.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"inference\": inference_usd,\n            \"tools\": tools_usd,\n            \"observability\": observability_usd,\n            \"storage\": storage_usd,\n            \"orchestration\": orchestration_usd,\n            \"total\": (\n                inference_usd + tools_usd + observability_usd\n                + storage_usd + orchestration_usd\n            ),\n        })\n\n    def record_outcome_snapshot(\n        self,\n        agent_id: str,\n        cost_per_success: float,\n        success_rate: float,\n        quality_score: float,\n    ):\n        self._outcome_costs.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"agent_id\": agent_id,\n            \"cost_per_success\": cost_per_success,\n            \"success_rate\": success_rate,\n            \"quality_score\": quality_score,\n        })\n\n    def generate_panels(self) -> Dict[str, Any]:\n        \"\"\"Generate dashboard panel data.\"\"\"\n        panels = {}\n\n        # Panel 1: Burn rate\n        if self._hourly_costs:\n            recent = self._hourly_costs[-24:]  # Last 24 hours\n            daily_total = sum(h[\"total\"] for h in recent)\n            hourly_budget = self.budget \u002F 30 \u002F 24\n            daily_budget = self.budget \u002F 30\n\n            panels[\"burn_rate\"] = {\n                \"daily_spend_usd\": round(daily_total, 2),\n                \"daily_budget_usd\": round(daily_budget, 2),\n                \"burn_rate_pct\": round(daily_total \u002F daily_budget * 100, 1) if daily_budget > 0 else 0,\n                \"projected_monthly_usd\": round(daily_total * 30, 2),\n                \"over_budget\": daily_total > daily_budget * 1.1,\n                \"breakdown\": {\n                    cat: round(sum(h[cat] for h in recent), 2)\n                    for cat in [\"inference\", \"tools\", \"observability\", \"storage\", \"orchestration\"]\n                },\n            }\n\n        # Panel 2: Cost per outcome\n        if self._outcome_costs:\n            by_agent: Dict[str, list] = {}\n            for o in self._outcome_costs:\n                by_agent.setdefault(o[\"agent_id\"], []).append(o)\n\n            panels[\"cost_per_outcome\"] = {\n                agent: {\n                    \"avg_cost_per_success\": round(\n                        sum(o[\"cost_per_success\"] for o in entries) \u002F len(entries), 4\n                    ),\n                    \"avg_success_rate\": round(\n                        sum(o[\"success_rate\"] for o in entries) \u002F len(entries), 3\n                    ),\n                    \"avg_quality\": round(\n                        sum(o[\"quality_score\"] for o in entries) \u002F len(entries), 3\n                    ),\n                    \"data_points\": len(entries),\n                }\n                for agent, entries in by_agent.items()\n            }\n\n        # Panel 4: Waste metrics\n        panels[\"waste_tracker\"] = self._compute_waste_metrics()\n\n        return panels\n\n    def _compute_waste_metrics(self) -> Dict[str, DashboardMetric]:\n        \"\"\"Compute waste metrics for the waste tracker panel.\"\"\"\n        metrics = {}\n\n        if self._hourly_costs:\n            recent = self._hourly_costs[-24:]\n            total = sum(h[\"total\"] for h in recent)\n            obs = sum(h[\"observability\"] for h in recent)\n            obs_pct = (obs \u002F total * 100) if total > 0 else 0\n\n            metrics[\"observability_overhead\"] = {\n                \"value\": round(obs_pct, 1),\n                \"unit\": \"%\",\n                \"status\": (\n                    \"critical\" if obs_pct > 25\n                    else \"warning\" if obs_pct > 15\n                    else \"healthy\"\n                ),\n            }\n\n        if self._outcome_costs:\n            failed = [o for o in self._outcome_costs if o[\"success_rate\"] \u003C 0.5]\n            failure_rate = len(failed) \u002F len(self._outcome_costs) * 100\n\n            metrics[\"failure_waste\"] = {\n                \"value\": round(failure_rate, 1),\n                \"unit\": \"%\",\n                \"status\": (\n                    \"critical\" if failure_rate > 20\n                    else \"warning\" if failure_rate > 10\n                    else \"healthy\"\n                ),\n            }\n\n        return metrics\n\n    def executive_summary(self) -> str:\n        \"\"\"Generate an executive-level cost summary as formatted text.\"\"\"\n        panels = self.generate_panels()\n        lines = []\n        lines.append(\"=\" * 60)\n        lines.append(\"AI AGENT COST OPTIMIZATION - EXECUTIVE SUMMARY\")\n        lines.append(\"=\" * 60)\n\n        if \"burn_rate\" in panels:\n            br = panels[\"burn_rate\"]\n            lines.append(f\"\\nMonthly Budget:     ${self.budget:>12,.2f}\")\n            lines.append(f\"Projected Spend:    ${br['projected_monthly_usd']:>12,.2f}\")\n            variance = br[\"projected_monthly_usd\"] - self.budget\n            status = \"OVER BUDGET\" if variance > 0 else \"UNDER BUDGET\"\n            lines.append(f\"Variance:           ${abs(variance):>12,.2f} ({status})\")\n            lines.append(f\"\\nDaily Breakdown:\")\n            for cat, val in br[\"breakdown\"].items():\n                pct = val \u002F br[\"daily_spend_usd\"] * 100 if br[\"daily_spend_usd\"] > 0 else 0\n                lines.append(f\"  {cat:\u003C20s} ${val:>8,.2f}  ({pct:>5.1f}%)\")\n\n        if \"cost_per_outcome\" in panels:\n            lines.append(f\"\\nAgent Efficiency:\")\n            for agent, data in panels[\"cost_per_outcome\"].items():\n                lines.append(\n                    f\"  {agent:\u003C20s} ${data['avg_cost_per_success']:.4f}\u002Fsuccess  \"\n                    f\"rate={data['avg_success_rate']:.1%}  \"\n                    f\"quality={data['avg_quality']:.2f}\"\n                )\n\n        lines.append(\"\\n\" + \"=\" * 60)\n        return \"\\n\".join(lines)\n\n\n# Example: Generate dashboard data\ndashboard = CostDashboard(monthly_budget_usd=15_000)\n\n# Simulate 24 hours of data\nimport random\nrandom.seed(42)\nfor hour in range(24):\n    # Cost varies by time of day (higher during business hours)\n    multiplier = 2.5 if 8 \u003C= hour \u003C= 17 else 0.5\n    dashboard.record_hourly_snapshot(\n        inference_usd=random.gauss(12.0, 3.0) * multiplier,\n        tools_usd=random.gauss(3.0, 1.0) * multiplier,\n        observability_usd=random.gauss(2.5, 0.8) * multiplier,\n        storage_usd=random.gauss(0.8, 0.2),\n        orchestration_usd=random.gauss(1.5, 0.5) * multiplier,\n    )\n\n# Simulate outcome data for 3 agents\nfor agent in [\"researcher-01\", \"classifier-02\", \"support-03\"]:\n    for _ in range(50):\n        dashboard.record_outcome_snapshot(\n            agent_id=agent,\n            cost_per_success=random.gauss(0.05, 0.02),\n            success_rate=random.gauss(0.85, 0.08),\n            quality_score=random.gauss(0.82, 0.10),\n        )\n\nprint(dashboard.executive_summary())\n```\n\n### Team Roles and Responsibilities\n\nCost optimization is not a one-person job. It requires sustained attention from four roles, each owning a specific piece of the cost stack.\n\n**Platform Engineer** owns instrumentation, observability cost control, and the cost tracking infrastructure. They deploy and maintain the CostTracker, AdaptiveSampler, and cost dashboards. They are the first responder when cost alerts fire. Weekly time commitment: 4-6 hours after initial setup.\n\n**ML Engineer** owns prompt optimization, model routing, and quality measurement. They run the TokenWasteAnalyzer against production prompts, configure the ModelRouter, and monitor quality metrics to ensure cost cuts do not degrade output. Weekly time commitment: 6-8 hours during active optimization, 2-3 hours for maintenance.\n\n**Backend Engineer** owns caching, batch processing, and the application-layer infrastructure. They deploy and tune the AgentResponseCache, configure the WorkloadScheduler, and optimize inter-service communication. Weekly time commitment: 4-6 hours during deployment, 1-2 hours for maintenance.\n\n**Engineering Manager** owns the governance framework, executive reporting, and cross-team coordination. They run the weekly cost review, maintain the optimization backlog, and present the executive summary to leadership. Weekly time commitment: 3-4 hours.\n\n### Cost Governance Framework\n\nWithout governance, optimizations decay. New agents get deployed without cost budgets. Prompts creep back to verbose defaults. Model routing gets bypassed for \"just this one urgent task.\" A governance framework prevents regression.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom enum import Enum\n\n\nclass AlertSeverity(Enum):\n    INFO = \"info\"\n    WARNING = \"warning\"\n    CRITICAL = \"critical\"\n\n\n@dataclass\nclass CostBudget:\n    \"\"\"Cost budget for a single agent or team.\"\"\"\n    agent_id: str\n    monthly_budget_usd: float\n    daily_budget_usd: float = 0.0\n    alert_at_pct: float = 80.0       # Alert when spend reaches this % of budget\n    hard_limit_pct: float = 120.0    # Hard stop when spend reaches this %\n    owner: str = \"\"\n\n    def __post_init__(self):\n        if self.daily_budget_usd == 0:\n            self.daily_budget_usd = self.monthly_budget_usd \u002F 30\n\n\n@dataclass\nclass CostAlert:\n    \"\"\"A cost alert event.\"\"\"\n    agent_id: str\n    severity: AlertSeverity\n    message: str\n    current_spend_usd: float\n    budget_usd: float\n    spend_pct: float\n\n\nclass CostGovernor:\n    \"\"\"Enforces cost budgets and policies across the agent fleet.\n\n    Provides real-time budget monitoring, automatic alerts, and\n    hard spending limits that can throttle or stop agents that\n    exceed their allocated budget.\n    \"\"\"\n\n    def __init__(self):\n        self._budgets: Dict[str, CostBudget] = {}\n        self._spend: Dict[str, float] = {}       # Current period spend\n        self._alerts: List[CostAlert] = []\n        self._throttled: set = set()\n        self._policies: Dict[str, Any] = {\n            \"require_cost_estimate_for_new_agents\": True,\n            \"max_cost_per_single_request_usd\": 1.00,\n            \"require_model_routing\": True,\n            \"require_prompt_review_above_tokens\": 5000,\n            \"monthly_fleet_budget_usd\": 25000.0,\n        }\n\n    def set_budget(self, budget: CostBudget):\n        \"\"\"Set or update a cost budget for an agent.\"\"\"\n        self._budgets[budget.agent_id] = budget\n        if budget.agent_id not in self._spend:\n            self._spend[budget.agent_id] = 0.0\n\n    def record_spend(self, agent_id: str, amount_usd: float) -> Optional[CostAlert]:\n        \"\"\"Record spending and check against budget.\n\n        Returns a CostAlert if a threshold is crossed, or None.\n        Automatically throttles agents that exceed hard limits.\n        \"\"\"\n        self._spend[agent_id] = self._spend.get(agent_id, 0.0) + amount_usd\n\n        budget = self._budgets.get(agent_id)\n        if budget is None:\n            return None\n\n        spend_pct = self._spend[agent_id] \u002F budget.daily_budget_usd * 100\n\n        alert = None\n        if spend_pct >= budget.hard_limit_pct:\n            self._throttled.add(agent_id)\n            alert = CostAlert(\n                agent_id=agent_id,\n                severity=AlertSeverity.CRITICAL,\n                message=f\"Agent {agent_id} THROTTLED: spend at {spend_pct:.0f}% of daily budget\",\n                current_spend_usd=round(self._spend[agent_id], 4),\n                budget_usd=budget.daily_budget_usd,\n                spend_pct=round(spend_pct, 1),\n            )\n        elif spend_pct >= budget.alert_at_pct:\n            alert = CostAlert(\n                agent_id=agent_id,\n                severity=AlertSeverity.WARNING,\n                message=f\"Agent {agent_id}: spend at {spend_pct:.0f}% of daily budget\",\n                current_spend_usd=round(self._spend[agent_id], 4),\n                budget_usd=budget.daily_budget_usd,\n                spend_pct=round(spend_pct, 1),\n            )\n\n        if alert:\n            self._alerts.append(alert)\n        return alert\n\n    def is_allowed(self, agent_id: str, estimated_cost_usd: float) -> Dict[str, Any]:\n        \"\"\"Check if an agent request should be allowed.\n\n        Returns allow\u002Fdeny decision with reason. Used as a\n        pre-request gate to prevent budget overruns.\n        \"\"\"\n        if agent_id in self._throttled:\n            return {\n                \"allowed\": False,\n                \"reason\": \"agent_throttled\",\n                \"message\": f\"Agent {agent_id} is throttled due to budget overrun\",\n            }\n\n        if estimated_cost_usd > self._policies[\"max_cost_per_single_request_usd\"]:\n            return {\n                \"allowed\": False,\n                \"reason\": \"request_too_expensive\",\n                \"message\": (\n                    f\"Estimated cost ${estimated_cost_usd:.4f} exceeds \"\n                    f\"max ${self._policies['max_cost_per_single_request_usd']:.2f}\"\n                ),\n            }\n\n        budget = self._budgets.get(agent_id)\n        if budget:\n            projected = self._spend.get(agent_id, 0) + estimated_cost_usd\n            if projected > budget.daily_budget_usd * budget.hard_limit_pct \u002F 100:\n                return {\n                    \"allowed\": False,\n                    \"reason\": \"would_exceed_budget\",\n                    \"message\": (\n                        f\"Request would push spend to \"\n                        f\"${projected:.2f} against daily budget \"\n                        f\"${budget.daily_budget_usd:.2f}\"\n                    ),\n                }\n\n        return {\"allowed\": True, \"reason\": \"within_budget\"}\n\n    def fleet_status(self) -> Dict[str, Any]:\n        \"\"\"Generate a fleet-wide budget status report.\"\"\"\n        total_budget = sum(b.daily_budget_usd for b in self._budgets.values())\n        total_spend = sum(self._spend.values())\n\n        agent_status = {}\n        for agent_id, budget in self._budgets.items():\n            spend = self._spend.get(agent_id, 0)\n            pct = (spend \u002F budget.daily_budget_usd * 100) if budget.daily_budget_usd > 0 else 0\n            agent_status[agent_id] = {\n                \"budget_usd\": round(budget.daily_budget_usd, 2),\n                \"spend_usd\": round(spend, 4),\n                \"spend_pct\": round(pct, 1),\n                \"status\": (\n                    \"throttled\" if agent_id in self._throttled\n                    else \"critical\" if pct >= budget.hard_limit_pct\n                    else \"warning\" if pct >= budget.alert_at_pct\n                    else \"healthy\"\n                ),\n                \"owner\": budget.owner,\n            }\n\n        return {\n            \"fleet_daily_budget_usd\": round(total_budget, 2),\n            \"fleet_daily_spend_usd\": round(total_spend, 2),\n            \"fleet_spend_pct\": round(\n                total_spend \u002F total_budget * 100, 1\n            ) if total_budget > 0 else 0,\n            \"agents_throttled\": len(self._throttled),\n            \"alerts_fired\": len(self._alerts),\n            \"agents\": agent_status,\n        }\n\n    def reset_daily(self):\n        \"\"\"Reset daily spend counters. Call at midnight.\"\"\"\n        self._spend = {agent_id: 0.0 for agent_id in self._budgets}\n        self._throttled.clear()\n\n\n# Example: Set up governance for a 4-agent fleet\ngovernor = CostGovernor()\n\ngovernor.set_budget(CostBudget(\n    agent_id=\"researcher-01\",\n    monthly_budget_usd=4500,\n    owner=\"ML Team\",\n    alert_at_pct=80,\n    hard_limit_pct=120,\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"classifier-02\",\n    monthly_budget_usd=2000,\n    owner=\"Data Team\",\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"support-03\",\n    monthly_budget_usd=6000,\n    owner=\"CX Team\",\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"writer-04\",\n    monthly_budget_usd=2500,\n    owner=\"Content Team\",\n))\n\n# Simulate a day of spending\nrandom.seed(42)\nfor _ in range(500):\n    agent = random.choice([\"researcher-01\", \"classifier-02\", \"support-03\", \"writer-04\"])\n    cost = random.gauss(0.05, 0.03)\n    cost = max(0.001, cost)\n\n    # Check permission before processing\n    permission = governor.is_allowed(agent, cost)\n    if permission[\"allowed\"]:\n        alert = governor.record_spend(agent, cost)\n        if alert:\n            print(f\"ALERT [{alert.severity.value}]: {alert.message}\")\n    else:\n        pass  # Request denied -- queue for later or use cheaper model\n\nstatus = governor.fleet_status()\nprint(f\"\\nFleet budget: ${status['fleet_daily_budget_usd']}\u002Fday\")\nprint(f\"Fleet spend:  ${status['fleet_daily_spend_usd']:.2f}\u002Fday\")\nprint(f\"Throttled:    {status['agents_throttled']} agents\")\nfor agent, data in status[\"agents\"].items():\n    print(f\"  {agent:\u003C20s} ${data['spend_usd']:>7.2f} \u002F ${data['budget_usd']:>7.2f} \"\n          f\"({data['spend_pct']:>5.1f}%) [{data['status']}]\")\n```\n\n### Executive Reporting Template\n\nFinance and leadership do not care about tokens, spans, or cache hit rates. They care about three things: how much are we spending, is it within budget, and what is the return on investment. The executive report translates technical metrics into business language.\n\nThe report should be generated weekly and cover four sections: (1) total spend versus budget with trend line, (2) cost-per-successful-outcome by business function, (3) optimization program progress and realized savings, and (4) forecast for the next quarter. Keep it to one page. Use dollar amounts, not percentages, as the primary metric -- executives respond to \"we saved $4,200 this month\" more than \"we reduced token waste by 18%.\"\n\n```python\nclass ExecutiveReport:\n    \"\"\"Generates a one-page executive cost report.\n\n    Translates technical cost metrics into business-friendly\n    language suitable for C-suite and finance review.\n    \"\"\"\n\n    def __init__(\n        self,\n        monthly_budget_usd: float,\n        baseline_monthly_usd: float,\n    ):\n        self.budget = monthly_budget_usd\n        self.baseline = baseline_monthly_usd\n\n    def generate(\n        self,\n        actual_spend_usd: float,\n        cost_per_outcome: Dict[str, float],\n        optimization_savings_usd: float,\n        weeks_completed: int,\n        forecast_next_quarter_usd: float,\n    ) -> str:\n        \"\"\"Generate the executive report as formatted text.\"\"\"\n        variance = actual_spend_usd - self.budget\n        variance_pct = variance \u002F self.budget * 100 if self.budget > 0 else 0\n        savings_from_baseline = self.baseline - actual_spend_usd\n        savings_pct = savings_from_baseline \u002F self.baseline * 100 if self.baseline > 0 else 0\n\n        lines = []\n        lines.append(\"=\" * 65)\n        lines.append(\"     AI AGENT INFRASTRUCTURE - MONTHLY COST REPORT\")\n        lines.append(\"=\" * 65)\n\n        # Section 1: Spend vs Budget\n        lines.append(\"\\n1. SPEND vs BUDGET\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Monthly Budget:        ${self.budget:>12,.2f}\")\n        lines.append(f\"   Actual Spend:          ${actual_spend_usd:>12,.2f}\")\n        lines.append(f\"   Variance:              ${abs(variance):>12,.2f} \"\n                     f\"{'OVER' if variance > 0 else 'UNDER'}\")\n        lines.append(f\"   Pre-Optimization Base: ${self.baseline:>12,.2f}\")\n        lines.append(f\"   Realized Savings:      ${savings_from_baseline:>12,.2f} \"\n                     f\"({savings_pct:.0f}%)\")\n\n        # Section 2: Cost Per Outcome\n        lines.append(\"\\n2. COST PER SUCCESSFUL OUTCOME BY FUNCTION\")\n        lines.append(\"-\" * 40)\n        for function, cost in cost_per_outcome.items():\n            lines.append(f\"   {function:\u003C30s} ${cost:>8.4f}\")\n\n        # Section 3: Optimization Progress\n        lines.append(\"\\n3. OPTIMIZATION PROGRAM STATUS\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Program Week:          {weeks_completed} of 8\")\n        lines.append(f\"   Cumulative Savings:    ${optimization_savings_usd:>12,.2f}\u002Fmo\")\n        lines.append(f\"   Annualized Savings:    ${optimization_savings_usd * 12:>12,.2f}\")\n        lines.append(f\"   Progress:              \"\n                     f\"[{'#' * weeks_completed}{'.' * (8 - weeks_completed)}]\")\n\n        # Section 4: Forecast\n        lines.append(\"\\n4. NEXT QUARTER FORECAST\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Projected Q Spend:     ${forecast_next_quarter_usd:>12,.2f}\")\n        lines.append(f\"   Q Budget (3x monthly): ${self.budget * 3:>12,.2f}\")\n        q_variance = forecast_next_quarter_usd - self.budget * 3\n        lines.append(f\"   Projected Q Variance:  ${abs(q_variance):>12,.2f} \"\n                     f\"{'OVER' if q_variance > 0 else 'UNDER'}\")\n\n        lines.append(\"\\n\" + \"=\" * 65)\n        return \"\\n\".join(lines)\n\n\n# Generate the report\nreport_gen = ExecutiveReport(\n    monthly_budget_usd=15_000,\n    baseline_monthly_usd=22_000,\n)\n\nreport_text = report_gen.generate(\n    actual_spend_usd=9_200,\n    cost_per_outcome={\n        \"Research Reports\": 0.0832,\n        \"Document Classification\": 0.0041,\n        \"Customer Support\": 0.0156,\n        \"Content Generation\": 0.0287,\n    },\n    optimization_savings_usd=12_800,\n    weeks_completed=8,\n    forecast_next_quarter_usd=26_400,\n)\n\nprint(report_text)\n```\n\n### Putting It All Together\n\nThe strategies in this cookbook are not theoretical. They are battle-tested patterns deployed by teams running AI agents at scale. The numbers are real: 60% cost reduction is achievable by any team willing to invest eight weeks of focused effort. Some teams achieve more -- the Fortune 100 firm from the introduction reduced their $89,000\u002Fmonth bill to $31,000\u002Fmonth in six weeks using the exact strategies documented here.\n\nThe key insight is that agent cost optimization is not a one-time project. It is a discipline. Models change pricing. New models enter the market. Agent workloads shift. Prompts drift. The governance framework in this chapter -- budgets, alerts, reviews, executive reporting -- ensures that optimizations stick and that new waste is caught before it compounds.\n\nStart with Chapter 1. Instrument everything. Then follow the playbook. Week by week, your agent fleet becomes leaner, smarter, and more cost-effective. The 60% target is not a ceiling -- it is a floor.\n\n---\n","# AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n\n\nA Fortune 100 financial services firm deployed twelve LangChain agents to automate research workflows in January 2026. By March, their monthly AI infrastructure bill had grown from $14,000 to $89,000 -- a 536% increase that no one predicted, no one budgeted for, and no one could explain until a three-week forensic investigation traced the cost explosion to four root causes: unbounded context windows that grew with every conversation turn, a model routing configuration that sent simple classification tasks to GPT-4o instead of a model ten times cheaper, an observability pipeline that generated more telemetry data per agent request than the request itself cost to serve, and a retry loop in one agent that silently reprocessed failed tasks up to fifty times before giving up. Every one of these problems is fixable. Every one of them is preventable. This cookbook shows you how.\nThe numbers are stark. Observability vendors report that AI agent deployments increase telemetry costs by 40-200% over traditional application monitoring. Anthropic's own usage data shows that the median enterprise wastes 35-45% of its LLM inference spend on tokens that contribute nothing to output quality -- system prompt bloat, redundant few-shot examples, uncompressed tool descriptions, and response format overhead. A 2026 survey by the FinOps Foundation found that 80% of Fortune 500 companies are now deploying AI agents in production, with an average of twelve agents per enterprise, and that cost governance for these agents is rated the number one unsolved infrastructure problem by platform engineering teams.\nThis is not a theoretical guide. Every chapter contains working Python code that you can run against your own agent fleet today. The strategies are ordered by impact: Chapter 1 teaches you to measure where money actually goes (you cannot optimize what you cannot see). Chapter 2 covers LLM cost reduction through prompt caching, compression, and context management. Chapter 3 builds a model router that sends each task to the cheapest model that meets quality requirements. Chapter 4 tackles the observability cost explosion with adaptive sampling and cardinality management. Chapter 5 optimizes tokens at the prompt and response level. Chapter 6 introduces outcome-based metering as an alternative to input-based billing. Chapter 7 covers infrastructure right-sizing. Chapter 8 provides a week-by-week optimization playbook with ROI calculations. By the end, you will have a concrete, measurable plan to cut your agent bills by 60% or more.\n\n## What You'll Learn\n- Chapter 1: Where Agent Money Actually Goes\n- Chapter 2: LLM Cost Reduction Strategies\n- Chapter 3: Model Routing -- Right Model for the Job\n- Chapter 4: Observability Cost Control\n- Chapter 5: Token Optimization\n- Chapter 6: Outcome-Based Metering\n- Chapter 7: Infrastructure Right-Sizing\n- Chapter 8: Cost Optimization Playbook\n\n## Full Guide\n\n# AI Agent Cost Optimization Cookbook: Cut Your Agent Bills by 60% Without Sacrificing Quality\n\nA Fortune 100 financial services firm deployed twelve LangChain agents to automate research workflows in January 2026. By March, their monthly AI infrastructure bill had grown from $14,000 to $89,000 -- a 536% increase that no one predicted, no one budgeted for, and no one could explain until a three-week forensic investigation traced the cost explosion to four root causes: unbounded context windows that grew with every conversation turn, a model routing configuration that sent simple classification tasks to GPT-4o instead of a model ten times cheaper, an observability pipeline that generated more telemetry data per agent request than the request itself cost to serve, and a retry loop in one agent that silently reprocessed failed tasks up to fifty times before giving up. Every one of these problems is fixable. Every one of them is preventable. This cookbook shows you how.\n\nThe numbers are stark. Observability vendors report that AI agent deployments increase telemetry costs by 40-200% over traditional application monitoring. Anthropic's own usage data shows that the median enterprise wastes 35-45% of its LLM inference spend on tokens that contribute nothing to output quality -- system prompt bloat, redundant few-shot examples, uncompressed tool descriptions, and response format overhead. A 2026 survey by the FinOps Foundation found that 80% of Fortune 500 companies are now deploying AI agents in production, with an average of twelve agents per enterprise, and that cost governance for these agents is rated the number one unsolved infrastructure problem by platform engineering teams.\n\nThis is not a theoretical guide. Every chapter contains working Python code that you can run against your own agent fleet today. The strategies are ordered by impact: Chapter 1 teaches you to measure where money actually goes (you cannot optimize what you cannot see). Chapter 2 covers LLM cost reduction through prompt caching, compression, and context management. Chapter 3 builds a model router that sends each task to the cheapest model that meets quality requirements. Chapter 4 tackles the observability cost explosion with adaptive sampling and cardinality management. Chapter 5 optimizes tokens at the prompt and response level. Chapter 6 introduces outcome-based metering as an alternative to input-based billing. Chapter 7 covers infrastructure right-sizing. Chapter 8 provides a week-by-week optimization playbook with ROI calculations. By the end, you will have a concrete, measurable plan to cut your agent bills by 60% or more.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Where Agent Money Actually Goes](#chapter-1-where-agent-money-actually-goes)\n2. [LLM Cost Reduction Strategies](#chapter-2-llm-cost-reduction-strategies)\n3. [Model Routing -- Right Model for the Job](#chapter-3-model-routing----right-model-for-the-job)\n4. [Observability Cost Control](#chapter-4-observability-cost-control)\n5. [Token Optimization](#chapter-5-token-optimization)\n6. [Outcome-Based Metering](#chapter-6-outcome-based-metering)\n7. [Infrastructure Right-Sizing](#chapter-7-infrastructure-right-sizing)\n8. [Cost Optimization Playbook](#chapter-8-cost-optimization-playbook)\n\n---\n\n## Chapter 1: Where Agent Money Actually Goes\n\n### The Five Cost Components\n\nEvery AI agent incurs cost across five categories, and most teams only track one of them. Understanding all five is the prerequisite to optimization.\n\n**1. LLM Inference.** This is the cost most teams focus on because it is the most visible. Every call to GPT-4o, Claude, Llama, or any other language model has a per-token price for input and output. For a typical agent that processes 2,000 input tokens and generates 500 output tokens per request, using GPT-4o at $2.50\u002Fmillion input and $10.00\u002Fmillion output, the per-request inference cost is $0.01. At 10,000 requests per day, that is $100\u002Fday or $3,000\u002Fmonth. This is the floor -- the minimum you pay just for the LLM to think.\n\n**2. Tool Calls.** Agents do not just think; they act. Every tool call -- database query, API request, web search, code execution -- has a cost. Some are direct (the API charges per call), some are indirect (the compute to run the tool, the network egress, the storage for results). A research agent that calls a search API ($0.005\u002Fquery), a document retrieval service ($0.002\u002Fdoc), and a summarization endpoint ($0.008\u002Fsummary) per task adds $0.015 in tool costs on top of inference. At scale, tool costs often exceed inference costs.\n\n**3. Orchestration Overhead.** Multi-agent systems have coordination costs. The orchestrator agent spends tokens deciding which worker to call, parsing worker responses, managing conversation state, and handling errors. In a CrewAI or LangGraph workflow with five agents, the orchestrator may consume 30-40% of total inference tokens just for coordination -- tokens that produce no direct value for the end user.\n\n**4. Observability.** Every agent request generates traces, metrics, and logs. OpenTelemetry spans, custom metric submissions, structured log entries, and distributed trace propagation all consume storage and compute. The observability tax is often invisible because it is billed separately (by Datadog, Grafana Cloud, or your self-hosted stack), but it scales linearly with agent traffic. A single agent request that generates 15 spans, 8 metric data points, and 20 log lines can cost more in observability than the LLM inference itself.\n\n**5. Storage.** Conversation history, agent memory, tool call results, audit logs, and cached responses all require storage. For agents with long-running conversations or persistent memory, storage costs grow monotonically. A conversation that accumulates 50,000 tokens of history over 100 turns, stored in a vector database at $0.10\u002FGB\u002Fmonth, costs pennies per conversation -- but multiplied by thousands of concurrent conversations, it becomes material.\n\n### Instrumenting Cost: The CostTracker Class\n\nBefore optimizing anything, you need to measure everything. This class wraps every agent operation and records its cost.\n\n```python\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List, Any\nfrom contextlib import contextmanager\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass CostEvent:\n    \"\"\"A single cost event from an agent operation.\"\"\"\n    timestamp: str\n    agent_id: str\n    operation: str\n    category: str  # inference, tool_call, orchestration, observability, storage\n    input_tokens: int = 0\n    output_tokens: int = 0\n    cost_usd: float = 0.0\n    duration_ms: float = 0.0\n    metadata: Dict[str, Any] = field(default_factory=dict)\n\n\nclass CostTracker:\n    \"\"\"Tracks all cost events for an agent or fleet of agents.\n\n    Thread-safe. Supports concurrent agent operations.\n    \"\"\"\n\n    # Pricing per million tokens (input\u002Foutput) by model\n    MODEL_PRICING = {\n        \"gpt-4o\":           {\"input\": 2.50,  \"output\": 10.00},\n        \"gpt-4o-mini\":      {\"input\": 0.15,  \"output\": 0.60},\n        \"claude-sonnet-4\":  {\"input\": 3.00,  \"output\": 15.00},\n        \"claude-haiku-3.5\": {\"input\": 0.80,  \"output\": 4.00},\n        \"llama-3-70b\":      {\"input\": 0.70,  \"output\": 0.80},\n        \"llama-3-8b\":       {\"input\": 0.10,  \"output\": 0.10},\n        \"mistral-large\":    {\"input\": 2.00,  \"output\": 6.00},\n        \"mistral-small\":    {\"input\": 0.20,  \"output\": 0.60},\n    }\n\n    def __init__(self):\n        self._events: List[CostEvent] = []\n        self._lock = threading.Lock()\n\n    def record_inference(\n        self,\n        agent_id: str,\n        model: str,\n        input_tokens: int,\n        output_tokens: int,\n        duration_ms: float,\n        operation: str = \"inference\",\n    ) -> CostEvent:\n        \"\"\"Record an LLM inference cost event.\"\"\"\n        pricing = self.MODEL_PRICING.get(model, {\"input\": 0, \"output\": 0})\n        cost = (\n            input_tokens * pricing[\"input\"] \u002F 1_000_000\n            + output_tokens * pricing[\"output\"] \u002F 1_000_000\n        )\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=operation,\n            category=\"inference\",\n            input_tokens=input_tokens,\n            output_tokens=output_tokens,\n            cost_usd=round(cost, 6),\n            duration_ms=duration_ms,\n            metadata={\"model\": model},\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    def record_tool_call(\n        self,\n        agent_id: str,\n        tool_name: str,\n        cost_usd: float,\n        duration_ms: float,\n        metadata: Optional[Dict] = None,\n    ) -> CostEvent:\n        \"\"\"Record a tool call cost event.\"\"\"\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=tool_name,\n            category=\"tool_call\",\n            cost_usd=round(cost_usd, 6),\n            duration_ms=duration_ms,\n            metadata=metadata or {},\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    def record_observability(\n        self,\n        agent_id: str,\n        spans: int,\n        metrics: int,\n        log_lines: int,\n        cost_usd: float,\n    ) -> CostEvent:\n        \"\"\"Record observability cost for a request.\"\"\"\n        event = CostEvent(\n            timestamp=datetime.now(timezone.utc).isoformat(),\n            agent_id=agent_id,\n            operation=\"telemetry\",\n            category=\"observability\",\n            cost_usd=round(cost_usd, 6),\n            metadata={\n                \"spans\": spans,\n                \"metrics\": metrics,\n                \"log_lines\": log_lines,\n            },\n        )\n        with self._lock:\n            self._events.append(event)\n        return event\n\n    @contextmanager\n    def track_operation(\n        self,\n        agent_id: str,\n        operation: str,\n        category: str,\n    ):\n        \"\"\"Context manager that tracks duration and yields a cost recorder.\"\"\"\n        start = time.monotonic()\n        result = {\"cost_usd\": 0.0, \"metadata\": {}}\n        try:\n            yield result\n        finally:\n            duration_ms = (time.monotonic() - start) * 1000\n            event = CostEvent(\n                timestamp=datetime.now(timezone.utc).isoformat(),\n                agent_id=agent_id,\n                operation=operation,\n                category=category,\n                cost_usd=round(result[\"cost_usd\"], 6),\n                duration_ms=round(duration_ms, 2),\n                metadata=result.get(\"metadata\", {}),\n            )\n            with self._lock:\n                self._events.append(event)\n\n    def get_summary(\n        self,\n        agent_id: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Get a cost summary, optionally filtered by agent.\"\"\"\n        with self._lock:\n            events = [\n                e for e in self._events\n                if agent_id is None or e.agent_id == agent_id\n            ]\n\n        by_category = {}\n        total_cost = 0.0\n        total_tokens = 0\n\n        for e in events:\n            cat = e.category\n            if cat not in by_category:\n                by_category[cat] = {\n                    \"cost_usd\": 0.0,\n                    \"count\": 0,\n                    \"total_duration_ms\": 0.0,\n                }\n            by_category[cat][\"cost_usd\"] += e.cost_usd\n            by_category[cat][\"count\"] += 1\n            by_category[cat][\"total_duration_ms\"] += e.duration_ms\n            total_cost += e.cost_usd\n            total_tokens += e.input_tokens + e.output_tokens\n\n        return {\n            \"agent_id\": agent_id or \"all\",\n            \"total_cost_usd\": round(total_cost, 4),\n            \"total_tokens\": total_tokens,\n            \"total_events\": len(events),\n            \"by_category\": {\n                k: {\n                    \"cost_usd\": round(v[\"cost_usd\"], 4),\n                    \"count\": v[\"count\"],\n                    \"avg_duration_ms\": round(\n                        v[\"total_duration_ms\"] \u002F v[\"count\"], 2\n                    ) if v[\"count\"] > 0 else 0,\n                    \"pct_of_total\": round(\n                        v[\"cost_usd\"] \u002F total_cost * 100, 1\n                    ) if total_cost > 0 else 0,\n                }\n                for k, v in by_category.items()\n            },\n        }\n\n    def export_jsonl(self, filepath: str):\n        \"\"\"Export all events as JSONL for analysis.\"\"\"\n        with self._lock:\n            events = list(self._events)\n        with open(filepath, \"w\") as f:\n            for e in events:\n                f.write(json.dumps({\n                    \"timestamp\": e.timestamp,\n                    \"agent_id\": e.agent_id,\n                    \"operation\": e.operation,\n                    \"category\": e.category,\n                    \"input_tokens\": e.input_tokens,\n                    \"output_tokens\": e.output_tokens,\n                    \"cost_usd\": e.cost_usd,\n                    \"duration_ms\": e.duration_ms,\n                    \"metadata\": e.metadata,\n                }) + \"\\n\")\n```\n\n### Using the CostTracker\n\n```python\ntracker = CostTracker()\n\n# Track an LLM inference call\ntracker.record_inference(\n    agent_id=\"researcher-01\",\n    model=\"gpt-4o\",\n    input_tokens=1850,\n    output_tokens=420,\n    duration_ms=1230.5,\n    operation=\"analyze_document\",\n)\n\n# Track a tool call\ntracker.record_tool_call(\n    agent_id=\"researcher-01\",\n    tool_name=\"web_search\",\n    cost_usd=0.005,\n    duration_ms=340.2,\n    metadata={\"query\": \"climate data 2026\", \"results\": 10},\n)\n\n# Track observability overhead\ntracker.record_observability(\n    agent_id=\"researcher-01\",\n    spans=12,\n    metrics=6,\n    log_lines=18,\n    cost_usd=0.0003,\n)\n\n# Use the context manager for automatic duration tracking\nwith tracker.track_operation(\"researcher-01\", \"vector_search\", \"storage\") as op:\n    # ... perform the operation ...\n    op[\"cost_usd\"] = 0.0012\n    op[\"metadata\"] = {\"index\": \"documents\", \"results\": 25}\n\n# Print the summary\nsummary = tracker.get_summary(agent_id=\"researcher-01\")\nprint(f\"Total cost: ${summary['total_cost_usd']:.4f}\")\nfor cat, data in summary[\"by_category\"].items():\n    print(\n        f\"  {cat}: ${data['cost_usd']:.4f} \"\n        f\"({data['pct_of_total']}% of total, \"\n        f\"{data['count']} events, \"\n        f\"{data['avg_duration_ms']:.1f}ms avg)\"\n    )\n```\n\n### Real-World Cost Breakdown\n\nHere is what a typical cost breakdown looks like for a production agent fleet running twelve agents processing 50,000 requests per day, before any optimization:\n\n```\nCategory          Daily Cost    % of Total    Notes\n─────────────────────────────────────────────────────────────────\nLLM Inference     $312.00       41.2%         GPT-4o for all tasks\nTool Calls        $187.50       24.8%         Search, retrieval, APIs\nOrchestration     $98.00        12.9%         Coordinator agent tokens\nObservability     $118.00       15.6%         Datadog traces + metrics\nStorage           $41.50         5.5%         Vector DB + conversation logs\n─────────────────────────────────────────────────────────────────\nTotal             $757.00       100.0%        $22,710\u002Fmonth\n```\n\nAfter applying the optimizations in this cookbook:\n\n```\nCategory          Daily Cost    % of Total    Savings    How\n─────────────────────────────────────────────────────────────────\nLLM Inference     $118.00       39.3%         62.2%      Model routing + caching\nTool Calls        $112.50       37.5%         40.0%      Dedup + batching\nOrchestration     $29.40        9.8%          70.0%      Prompt compression\nObservability     $23.60        7.9%          80.0%      Adaptive sampling\nStorage           $16.60        5.5%          60.0%      TTL + compression\n─────────────────────────────────────────────────────────────────\nTotal             $300.10       100.0%        60.4%      $9,003\u002Fmonth\n```\n\nThe savings are $457\u002Fday, $13,707\u002Fmonth, $164,484\u002Fyear. That is the value of systematic cost optimization.\n\n---\n\n## Chapter 2: LLM Cost Reduction Strategies\n\n### Prompt Caching\n\nPrompt caching is the single highest-impact cost reduction technique for agents that use stable system prompts. Both Anthropic and OpenAI support server-side prompt caching that reduces the cost of repeated prompt prefixes by 90% (Anthropic) or 50% (OpenAI). If your agent sends the same 1,500-token system prompt with every request, and it makes 10,000 requests per day, caching that prefix saves thousands of dollars per month with zero code changes.\n\n**Anthropic Prompt Caching:**\n\nAnthropic's prompt caching automatically caches prompt prefixes longer than 1,024 tokens. Cached tokens are billed at 10% of the base input token price. The cache has a 5-minute TTL that resets on each hit, so agents making frequent requests keep the cache warm indefinitely.\n\n```python\nimport anthropic\nfrom cost_tracker import CostTracker\n\ntracker = CostTracker()\nclient = anthropic.Anthropic()\n\n# The system prompt is 1,800 tokens. With caching, only the first\n# request per 5-minute window pays full price. All subsequent\n# requests pay 10% for the cached prefix.\nSYSTEM_PROMPT = \"\"\"You are a financial research analyst agent. Your role is to:\n1. Analyze SEC filings, earnings transcripts, and market data\n2. Produce structured research reports with citations\n3. Flag material changes in financial metrics\n4. Compare performance against sector benchmarks\n... (remaining 1,600 tokens of detailed instructions) ...\"\"\"\n\ndef cached_inference(user_message: str, agent_id: str) -> str:\n    \"\"\"Make an inference call with automatic prompt caching.\"\"\"\n    start = __import__(\"time\").monotonic()\n\n    response = client.messages.create(\n        model=\"claude-sonnet-4-20250514\",\n        max_tokens=1024,\n        system=[{\n            \"type\": \"text\",\n            \"text\": SYSTEM_PROMPT,\n            \"cache_control\": {\"type\": \"ephemeral\"},\n        }],\n        messages=[{\"role\": \"user\", \"content\": user_message}],\n    )\n\n    duration_ms = (__import__(\"time\").monotonic() - start) * 1000\n\n    # Track costs with cache-aware pricing\n    usage = response.usage\n    cache_read_tokens = getattr(usage, \"cache_read_input_tokens\", 0)\n    cache_creation_tokens = getattr(usage, \"cache_creation_input_tokens\", 0)\n    uncached_input = usage.input_tokens - cache_read_tokens - cache_creation_tokens\n\n    # Anthropic Claude Sonnet: $3\u002FM input, $0.30\u002FM cached read, $3.75\u002FM cache write\n    cost = (\n        uncached_input * 3.00 \u002F 1_000_000\n        + cache_read_tokens * 0.30 \u002F 1_000_000\n        + cache_creation_tokens * 3.75 \u002F 1_000_000\n        + usage.output_tokens * 15.00 \u002F 1_000_000\n    )\n\n    tracker.record_inference(\n        agent_id=agent_id,\n        model=\"claude-sonnet-4\",\n        input_tokens=usage.input_tokens,\n        output_tokens=usage.output_tokens,\n        duration_ms=duration_ms,\n        operation=\"cached_inference\",\n    )\n\n    print(\n        f\"Tokens: {usage.input_tokens} in \"\n        f\"({cache_read_tokens} cached, {cache_creation_tokens} cache-write, \"\n        f\"{uncached_input} fresh), {usage.output_tokens} out. \"\n        f\"Cost: ${cost:.6f}\"\n    )\n\n    return response.content[0].text\n```\n\n**OpenAI Prompt Caching:**\n\nOpenAI automatically caches prompt prefixes of 1,024+ tokens. Cached tokens are billed at 50% of the input token price. No code changes required -- the caching happens server-side. You can verify cache hits by checking the `usage.prompt_tokens_details.cached_tokens` field.\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI()\n\ndef openai_cached_inference(\n    system_prompt: str,\n    user_message: str,\n) -> dict:\n    \"\"\"OpenAI inference with cache-aware cost tracking.\"\"\"\n    response = client.chat.completions.create(\n        model=\"gpt-4o\",\n        messages=[\n            {\"role\": \"system\", \"content\": system_prompt},\n            {\"role\": \"user\", \"content\": user_message},\n        ],\n    )\n\n    usage = response.usage\n    cached = getattr(usage, \"prompt_tokens_details\", None)\n    cached_tokens = cached.cached_tokens if cached else 0\n    uncached_tokens = usage.prompt_tokens - cached_tokens\n\n    # GPT-4o: $2.50\u002FM input, $1.25\u002FM cached, $10.00\u002FM output\n    cost = (\n        uncached_tokens * 2.50 \u002F 1_000_000\n        + cached_tokens * 1.25 \u002F 1_000_000\n        + usage.completion_tokens * 10.00 \u002F 1_000_000\n    )\n\n    return {\n        \"content\": response.choices[0].message.content,\n        \"cost_usd\": cost,\n        \"cached_tokens\": cached_tokens,\n        \"total_input_tokens\": usage.prompt_tokens,\n        \"output_tokens\": usage.completion_tokens,\n    }\n```\n\n### Prompt Compression\n\nMany agent system prompts are bloated with verbose instructions, redundant examples, and unnecessary formatting. Compressing prompts reduces input tokens without losing semantic content. The technique: rewrite prompts to be maximally information-dense, remove filler words, use abbreviations where unambiguous, and test that output quality is maintained.\n\n```python\nimport re\nfrom typing import Tuple\n\n\nclass PromptCompressor:\n    \"\"\"Compresses prompts to reduce token count while preserving semantics.\"\"\"\n\n    # Common verbose patterns and their compressed equivalents\n    COMPRESSION_RULES = [\n        # Remove filler phrases\n        (r\"\\bplease note that\\b\", \"\"),\n        (r\"\\bit is important to\\b\", \"\"),\n        (r\"\\bmake sure to\\b\", \"\"),\n        (r\"\\bkeep in mind that\\b\", \"\"),\n        (r\"\\byou should always\\b\", \"always\"),\n        (r\"\\bin order to\\b\", \"to\"),\n        (r\"\\bas well as\\b\", \"and\"),\n        (r\"\\bdue to the fact that\\b\", \"because\"),\n        (r\"\\bin the event that\\b\", \"if\"),\n        (r\"\\bfor the purpose of\\b\", \"to\"),\n        (r\"\\bwith respect to\\b\", \"regarding\"),\n        (r\"\\bat this point in time\\b\", \"now\"),\n        # Collapse whitespace\n        (r\"\\n{3,}\", \"\\n\\n\"),\n        (r\"  +\", \" \"),\n    ]\n\n    def compress(self, prompt: str) -> Tuple[str, dict]:\n        \"\"\"Compress a prompt and return the result with stats.\"\"\"\n        original_len = len(prompt.split())\n        compressed = prompt\n\n        for pattern, replacement in self.COMPRESSION_RULES:\n            compressed = re.sub(pattern, replacement, compressed, flags=re.IGNORECASE)\n\n        # Remove empty lines created by removals\n        compressed = re.sub(r\"\\n\\s*\\n\\s*\\n\", \"\\n\\n\", compressed)\n        compressed = compressed.strip()\n\n        compressed_len = len(compressed.split())\n        reduction = (1 - compressed_len \u002F original_len) * 100 if original_len > 0 else 0\n\n        return compressed, {\n            \"original_words\": original_len,\n            \"compressed_words\": compressed_len,\n            \"reduction_pct\": round(reduction, 1),\n        }\n\n\n# Usage\ncompressor = PromptCompressor()\nverbose_prompt = \"\"\"\nPlease note that you are a research analyst. It is important to always\nprovide accurate information. In order to do this, you should always\nverify facts against multiple sources. Make sure to cite your sources\nas well as provide confidence scores. Due to the fact that accuracy\nis critical, in the event that you are unsure, flag it explicitly.\nFor the purpose of clarity, with respect to formatting, at this point\nin time we require JSON output.\n\"\"\"\n\ncompressed, stats = compressor.compress(verbose_prompt)\nprint(f\"Before: {stats['original_words']} words\")\nprint(f\"After:  {stats['compressed_words']} words\")\nprint(f\"Reduction: {stats['reduction_pct']}%\")\nprint(f\"Compressed:\\n{compressed}\")\n```\n\n### Context Window Management\n\nThe most insidious cost driver in conversational agents is unbounded context growth. Every turn of conversation adds tokens to the context window. A 20-turn conversation that starts with a 2,000-token context can grow to 15,000+ tokens, with the agent paying for all accumulated tokens on every subsequent turn. This is quadratic cost growth -- the total cost of a conversation scales with the square of its length.\n\n```python\nfrom typing import List, Dict\n\n\nclass ContextWindowManager:\n    \"\"\"Manages conversation context to prevent unbounded cost growth.\n\n    Implements three strategies:\n    1. Sliding window: keep only the last N turns\n    2. Summarization: compress old turns into a summary\n    3. Relevance filtering: keep only turns relevant to the current task\n    \"\"\"\n\n    def __init__(\n        self,\n        max_tokens: int = 4000,\n        max_turns: int = 10,\n        summary_threshold: int = 6,\n    ):\n        self.max_tokens = max_tokens\n        self.max_turns = max_turns\n        self.summary_threshold = summary_threshold\n        self._turns: List[Dict[str, str]] = []\n        self._summary: str = \"\"\n        self._total_tokens_saved: int = 0\n\n    def add_turn(self, role: str, content: str, token_count: int):\n        \"\"\"Add a conversation turn.\"\"\"\n        self._turns.append({\n            \"role\": role,\n            \"content\": content,\n            \"tokens\": token_count,\n        })\n        self._maybe_compress()\n\n    def _maybe_compress(self):\n        \"\"\"Compress context if it exceeds limits.\"\"\"\n        total_tokens = sum(t[\"tokens\"] for t in self._turns)\n\n        if len(self._turns) > self.max_turns or total_tokens > self.max_tokens:\n            # Keep the last max_turns\u002F2 turns verbatim\n            keep = self.max_turns \u002F\u002F 2\n            old_turns = self._turns[:-keep]\n            kept_turns = self._turns[-keep:]\n\n            # Summarize old turns\n            old_tokens = sum(t[\"tokens\"] for t in old_turns)\n            old_text = \"\\n\".join(\n                f\"{t['role']}: {t['content'][:200]}\" for t in old_turns\n            )\n            # In production, call an LLM to summarize. Here we truncate.\n            self._summary = f\"[Previous context summary: {len(old_turns)} turns] {old_text[:500]}\"\n            self._total_tokens_saved += old_tokens\n\n            self._turns = kept_turns\n\n    def get_context(self) -> List[Dict[str, str]]:\n        \"\"\"Get the current context for the next LLM call.\"\"\"\n        messages = []\n        if self._summary:\n            messages.append({\n                \"role\": \"system\",\n                \"content\": f\"Context from earlier in the conversation:\\n{self._summary}\",\n            })\n        for turn in self._turns:\n            messages.append({\n                \"role\": turn[\"role\"],\n                \"content\": turn[\"content\"],\n            })\n        return messages\n\n    def get_stats(self) -> dict:\n        \"\"\"Get context management statistics.\"\"\"\n        current_tokens = sum(t[\"tokens\"] for t in self._turns)\n        return {\n            \"current_turns\": len(self._turns),\n            \"current_tokens\": current_tokens,\n            \"tokens_saved\": self._total_tokens_saved,\n            \"has_summary\": bool(self._summary),\n            \"cost_saved_usd\": round(\n                self._total_tokens_saved * 2.50 \u002F 1_000_000, 4\n            ),  # Assuming GPT-4o input pricing\n        }\n\n\n# Usage: 20-turn conversation with context management\nctx = ContextWindowManager(max_tokens=4000, max_turns=8)\n\nfor i in range(20):\n    ctx.add_turn(\"user\", f\"Question {i}: What about topic {i}?\", 50)\n    ctx.add_turn(\"assistant\", f\"Answer {i}: Here is info about topic {i}.\", 150)\n\nstats = ctx.get_stats()\nprint(f\"Current turns: {stats['current_turns']}\")\nprint(f\"Current tokens: {stats['current_tokens']}\")\nprint(f\"Tokens saved: {stats['tokens_saved']}\")\nprint(f\"Estimated cost saved: ${stats['cost_saved_usd']}\")\n```\n\n### Reducing Unnecessary Tool Calls\n\nAgents often make redundant tool calls -- querying for information they already have in context, or calling the same tool with the same parameters multiple times in a single reasoning chain. A tool call deduplication layer eliminates these.\n\n```python\nimport hashlib\nimport json\nimport time\nfrom typing import Any, Callable, Optional\n\n\nclass ToolCallDeduplicator:\n    \"\"\"Deduplicates tool calls within a configurable time window.\n\n    If the same tool is called with the same parameters within the\n    TTL window, the cached result is returned instead of making\n    a new call. This prevents agents from making redundant calls\n    during multi-step reasoning.\n    \"\"\"\n\n    def __init__(self, ttl_seconds: int = 300):\n        self.ttl = ttl_seconds\n        self._cache: dict[str, tuple[float, Any]] = {}\n        self._stats = {\"hits\": 0, \"misses\": 0, \"cost_saved\": 0.0}\n\n    def _cache_key(self, tool_name: str, params: dict) -> str:\n        param_str = json.dumps(params, sort_keys=True)\n        return hashlib.sha256(\n            f\"{tool_name}:{param_str}\".encode()\n        ).hexdigest()\n\n    def call(\n        self,\n        tool_name: str,\n        params: dict,\n        tool_fn: Callable,\n        estimated_cost: float = 0.005,\n    ) -> Any:\n        \"\"\"Call a tool with deduplication.\"\"\"\n        key = self._cache_key(tool_name, params)\n        now = time.monotonic()\n\n        # Check cache\n        if key in self._cache:\n            cached_time, cached_result = self._cache[key]\n            if now - cached_time \u003C self.ttl:\n                self._stats[\"hits\"] += 1\n                self._stats[\"cost_saved\"] += estimated_cost\n                return cached_result\n\n        # Cache miss -- make the actual call\n        result = tool_fn(tool_name, params)\n        self._cache[key] = (now, result)\n        self._stats[\"misses\"] += 1\n        return result\n\n    def get_stats(self) -> dict:\n        hit_rate = (\n            self._stats[\"hits\"]\n            \u002F (self._stats[\"hits\"] + self._stats[\"misses\"])\n            * 100\n            if (self._stats[\"hits\"] + self._stats[\"misses\"]) > 0\n            else 0\n        )\n        return {\n            **self._stats,\n            \"hit_rate_pct\": round(hit_rate, 1),\n            \"cache_size\": len(self._cache),\n        }\n\n\n# Usage\ndedup = ToolCallDeduplicator(ttl_seconds=300)\n\ndef mock_tool_call(tool_name: str, params: dict) -> dict:\n    \"\"\"Simulates an actual tool call.\"\"\"\n    return {\"result\": f\"data for {params}\"}\n\n# First call -- cache miss\nresult1 = dedup.call(\"web_search\", {\"query\": \"AI cost data\"}, mock_tool_call)\n\n# Second call with same params -- cache hit, no actual call made\nresult2 = dedup.call(\"web_search\", {\"query\": \"AI cost data\"}, mock_tool_call)\n\n# Different params -- cache miss\nresult3 = dedup.call(\"web_search\", {\"query\": \"different query\"}, mock_tool_call)\n\nprint(dedup.get_stats())\n# {\"hits\": 1, \"misses\": 2, \"cost_saved\": 0.005, \"hit_rate_pct\": 33.3, \"cache_size\": 2}\n```\n\n### Batch Inference for Non-Urgent Tasks\n\nNot every agent task needs real-time response. Background analysis, periodic reporting, bulk classification, and data enrichment can use batch inference APIs at 50% lower cost. Both Anthropic and OpenAI offer batch APIs with 24-hour turnaround at half the standard price.\n\n```python\nimport json\nimport time\nfrom typing import List, Dict\n\n\nclass BatchInferenceManager:\n    \"\"\"Manages batch inference jobs for non-urgent agent tasks.\n\n    Queues tasks and submits them as batch jobs, which run at 50%\n    of the standard API price with a 24-hour completion window.\n    \"\"\"\n\n    def __init__(self, client, batch_size: int = 100):\n        self.client = client\n        self.batch_size = batch_size\n        self._queue: List[Dict] = []\n        self._completed: Dict[str, Any] = {}\n\n    def enqueue(\n        self,\n        task_id: str,\n        model: str,\n        messages: List[Dict],\n        max_tokens: int = 1024,\n    ):\n        \"\"\"Add a task to the batch queue.\"\"\"\n        self._queue.append({\n            \"custom_id\": task_id,\n            \"method\": \"POST\",\n            \"url\": \"\u002Fv1\u002Fchat\u002Fcompletions\",\n            \"body\": {\n                \"model\": model,\n                \"messages\": messages,\n                \"max_tokens\": max_tokens,\n            },\n        })\n\n        # Auto-submit when batch is full\n        if len(self._queue) >= self.batch_size:\n            return self.submit()\n        return None\n\n    def submit(self) -> str:\n        \"\"\"Submit the current queue as a batch job.\"\"\"\n        if not self._queue:\n            return \"\"\n\n        # Write JSONL file for batch submission\n        batch_file = f\"\u002Ftmp\u002Fbatch_{int(time.time())}.jsonl\"\n        with open(batch_file, \"w\") as f:\n            for task in self._queue:\n                f.write(json.dumps(task) + \"\\n\")\n\n        # Upload and create batch\n        with open(batch_file, \"rb\") as f:\n            uploaded = self.client.files.create(file=f, purpose=\"batch\")\n\n        batch = self.client.batches.create(\n            input_file_id=uploaded.id,\n            endpoint=\"\u002Fv1\u002Fchat\u002Fcompletions\",\n            completion_window=\"24h\",\n        )\n\n        submitted_count = len(self._queue)\n        self._queue = []\n\n        print(\n            f\"Batch {batch.id} submitted: {submitted_count} tasks. \"\n            f\"Estimated savings: 50% vs real-time.\"\n        )\n        return batch.id\n\n    def check_status(self, batch_id: str) -> dict:\n        \"\"\"Check the status of a batch job.\"\"\"\n        batch = self.client.batches.retrieve(batch_id)\n        return {\n            \"id\": batch.id,\n            \"status\": batch.status,\n            \"completed\": batch.request_counts.completed,\n            \"failed\": batch.request_counts.failed,\n            \"total\": batch.request_counts.total,\n        }\n\n    def cost_comparison(self, task_count: int, avg_tokens: int) -> dict:\n        \"\"\"Compare batch vs real-time costs.\"\"\"\n        realtime_cost = task_count * avg_tokens * 2.50 \u002F 1_000_000\n        batch_cost = task_count * avg_tokens * 1.25 \u002F 1_000_000\n        return {\n            \"realtime_cost\": round(realtime_cost, 4),\n            \"batch_cost\": round(batch_cost, 4),\n            \"savings\": round(realtime_cost - batch_cost, 4),\n            \"savings_pct\": 50.0,\n        }\n```\n\n---\n\n## Chapter 3: Model Routing -- Right Model for the Job\n\n### The Case for Tiered Routing\n\nThe single most wasteful pattern in agent deployments is using the same model for every task. A GPT-4o call that classifies sentiment (\"positive\", \"negative\", \"neutral\") costs $0.005-0.01 in tokens. The same classification done by GPT-4o-mini costs $0.0003. The quality difference for this specific task is negligible -- both achieve 95%+ accuracy on sentiment classification. Multiply this across thousands of classification calls per day and the savings are enormous.\n\nTiered routing assigns each task to the cheapest model that meets quality requirements. Simple tasks (classification, extraction, formatting) go to small\u002Fcheap models. Complex tasks (reasoning, analysis, creative generation) go to expensive models. The router decides in real-time based on task characteristics.\n\n### The ModelRouter Implementation\n\n```python\nimport re\nimport time\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Callable, Any\nfrom enum import Enum\n\n\nclass TaskComplexity(Enum):\n    SIMPLE = \"simple\"        # Classification, extraction, formatting\n    MODERATE = \"moderate\"    # Summarization, Q&A, translation\n    COMPLEX = \"complex\"      # Reasoning, analysis, code generation\n    CRITICAL = \"critical\"    # High-stakes decisions, complex reasoning chains\n\n\n@dataclass\nclass ModelConfig:\n    \"\"\"Configuration for a model in the routing table.\"\"\"\n    name: str\n    provider: str  # openai, anthropic, local\n    cost_per_1k_input: float\n    cost_per_1k_output: float\n    quality_score: float  # 0.0 to 1.0, measured on your eval suite\n    max_tokens: int\n    latency_p50_ms: float\n    supports_tools: bool = True\n    supports_json_mode: bool = True\n\n\nclass ModelRouter:\n    \"\"\"Routes agent tasks to the optimal model based on complexity,\n    quality requirements, and cost constraints.\n\n    The router uses a combination of heuristic classification and\n    configurable routing rules to pick the cheapest model that meets\n    quality and latency requirements for each task.\n    \"\"\"\n\n    # Default model catalog -- override with your own benchmarks\n    DEFAULT_MODELS = {\n        \"gpt-4o\": ModelConfig(\n            name=\"gpt-4o\",\n            provider=\"openai\",\n            cost_per_1k_input=0.0025,\n            cost_per_1k_output=0.010,\n            quality_score=0.95,\n            max_tokens=128000,\n            latency_p50_ms=800,\n        ),\n        \"gpt-4o-mini\": ModelConfig(\n            name=\"gpt-4o-mini\",\n            provider=\"openai\",\n            cost_per_1k_input=0.00015,\n            cost_per_1k_output=0.0006,\n            quality_score=0.82,\n            max_tokens=128000,\n            latency_p50_ms=400,\n        ),\n        \"claude-sonnet-4\": ModelConfig(\n            name=\"claude-sonnet-4\",\n            provider=\"anthropic\",\n            cost_per_1k_input=0.003,\n            cost_per_1k_output=0.015,\n            quality_score=0.94,\n            max_tokens=200000,\n            latency_p50_ms=900,\n        ),\n        \"claude-haiku-3.5\": ModelConfig(\n            name=\"claude-haiku-3.5\",\n            provider=\"anthropic\",\n            cost_per_1k_input=0.0008,\n            cost_per_1k_output=0.004,\n            quality_score=0.85,\n            max_tokens=200000,\n            latency_p50_ms=350,\n        ),\n        \"llama-3-70b\": ModelConfig(\n            name=\"llama-3-70b\",\n            provider=\"local\",\n            cost_per_1k_input=0.0007,\n            cost_per_1k_output=0.0008,\n            quality_score=0.83,\n            max_tokens=8192,\n            latency_p50_ms=250,\n        ),\n        \"llama-3-8b\": ModelConfig(\n            name=\"llama-3-8b\",\n            provider=\"local\",\n            cost_per_1k_input=0.0001,\n            cost_per_1k_output=0.0001,\n            quality_score=0.72,\n            max_tokens=8192,\n            latency_p50_ms=100,\n        ),\n    }\n\n    # Heuristic complexity signals\n    COMPLEX_SIGNALS = [\n        r\"\\banalyze\\b\", r\"\\bcompare\\b\", r\"\\breason\\b\",\n        r\"\\bexplain why\\b\", r\"\\bwhat are the implications\\b\",\n        r\"\\bcritically evaluate\\b\", r\"\\btrade-?offs?\\b\",\n        r\"\\bstep by step\\b\", r\"\\bmulti-?step\\b\",\n    ]\n    SIMPLE_SIGNALS = [\n        r\"\\bclassify\\b\", r\"\\bextract\\b\", r\"\\bformat\\b\",\n        r\"\\bconvert\\b\", r\"\\btranslate\\b\", r\"\\blabel\\b\",\n        r\"\\byes or no\\b\", r\"\\btrue or false\\b\",\n        r\"\\bsentiment\\b\", r\"\\bcategorize\\b\",\n    ]\n\n    def __init__(\n        self,\n        models: Optional[Dict[str, ModelConfig]] = None,\n        quality_floor: float = 0.80,\n        latency_ceiling_ms: float = 5000,\n    ):\n        self.models = models or self.DEFAULT_MODELS\n        self.quality_floor = quality_floor\n        self.latency_ceiling_ms = latency_ceiling_ms\n        self._routing_log: List[dict] = []\n\n    def classify_complexity(self, prompt: str) -> TaskComplexity:\n        \"\"\"Heuristically classify task complexity from the prompt.\"\"\"\n        prompt_lower = prompt.lower()\n        prompt_tokens = len(prompt.split())\n\n        complex_score = sum(\n            1 for p in self.COMPLEX_SIGNALS\n            if re.search(p, prompt_lower)\n        )\n        simple_score = sum(\n            1 for p in self.SIMPLE_SIGNALS\n            if re.search(p, prompt_lower)\n        )\n\n        # Long prompts with many instructions tend to be complex\n        if prompt_tokens > 500:\n            complex_score += 2\n        elif prompt_tokens \u003C 50:\n            simple_score += 1\n\n        if complex_score >= 3:\n            return TaskComplexity.COMPLEX\n        elif complex_score >= 1 and simple_score == 0:\n            return TaskComplexity.MODERATE\n        elif simple_score >= 1:\n            return TaskComplexity.SIMPLE\n        else:\n            return TaskComplexity.MODERATE  # Default to moderate\n\n    def route(\n        self,\n        prompt: str,\n        min_quality: Optional[float] = None,\n        max_latency_ms: Optional[float] = None,\n        required_features: Optional[List[str]] = None,\n        force_complexity: Optional[TaskComplexity] = None,\n    ) -> ModelConfig:\n        \"\"\"Route a task to the optimal model.\n\n        Returns the cheapest model that meets all constraints.\n        \"\"\"\n        quality_floor = min_quality or self.quality_floor\n        latency_ceiling = max_latency_ms or self.latency_ceiling_ms\n        complexity = force_complexity or self.classify_complexity(prompt)\n\n        # Adjust quality floor based on complexity\n        adjusted_quality = {\n            TaskComplexity.SIMPLE: max(quality_floor - 0.10, 0.65),\n            TaskComplexity.MODERATE: quality_floor,\n            TaskComplexity.COMPLEX: min(quality_floor + 0.05, 0.99),\n            TaskComplexity.CRITICAL: min(quality_floor + 0.10, 0.99),\n        }[complexity]\n\n        # Filter eligible models\n        candidates = []\n        for name, config in self.models.items():\n            if config.quality_score \u003C adjusted_quality:\n                continue\n            if config.latency_p50_ms > latency_ceiling:\n                continue\n            if required_features:\n                if \"tools\" in required_features and not config.supports_tools:\n                    continue\n                if \"json_mode\" in required_features and not config.supports_json_mode:\n                    continue\n\n            # Estimate cost for this prompt\n            est_input_tokens = len(prompt.split()) * 1.3  # rough token estimate\n            est_output_tokens = est_input_tokens * 0.5\n            est_cost = (\n                est_input_tokens * config.cost_per_1k_input \u002F 1000\n                + est_output_tokens * config.cost_per_1k_output \u002F 1000\n            )\n            candidates.append((name, config, est_cost))\n\n        if not candidates:\n            # Fallback to the highest quality model\n            best = max(self.models.values(), key=lambda m: m.quality_score)\n            self._log_routing(prompt, complexity, best.name, \"fallback\")\n            return best\n\n        # Sort by cost (cheapest first), break ties by quality (highest first)\n        candidates.sort(key=lambda c: (c[2], -c[1].quality_score))\n        chosen_name, chosen_config, chosen_cost = candidates[0]\n\n        self._log_routing(prompt, complexity, chosen_name, \"optimal\")\n        return chosen_config\n\n    def _log_routing(\n        self,\n        prompt: str,\n        complexity: TaskComplexity,\n        model: str,\n        reason: str,\n    ):\n        self._routing_log.append({\n            \"timestamp\": time.time(),\n            \"complexity\": complexity.value,\n            \"model\": model,\n            \"reason\": reason,\n            \"prompt_preview\": prompt[:80],\n        })\n\n    def get_routing_stats(self) -> dict:\n        \"\"\"Get statistics on routing decisions.\"\"\"\n        if not self._routing_log:\n            return {\"total_routes\": 0}\n\n        model_counts = {}\n        complexity_counts = {}\n        for entry in self._routing_log:\n            model_counts[entry[\"model\"]] = model_counts.get(entry[\"model\"], 0) + 1\n            complexity_counts[entry[\"complexity\"]] = (\n                complexity_counts.get(entry[\"complexity\"], 0) + 1\n            )\n\n        total = len(self._routing_log)\n        return {\n            \"total_routes\": total,\n            \"by_model\": {\n                k: {\"count\": v, \"pct\": round(v \u002F total * 100, 1)}\n                for k, v in model_counts.items()\n            },\n            \"by_complexity\": {\n                k: {\"count\": v, \"pct\": round(v \u002F total * 100, 1)}\n                for k, v in complexity_counts.items()\n            },\n        }\n\n\n# Usage\nrouter = ModelRouter(quality_floor=0.80)\n\n# Simple task -- routes to cheap model\nsimple = router.route(\"Classify this text as positive, negative, or neutral: 'Great product!'\")\nprint(f\"Simple task -> {simple.name} (${simple.cost_per_1k_input}\u002F1K input)\")\n\n# Complex task -- routes to expensive model\ncomplex_task = router.route(\n    \"Analyze the trade-offs between microservice and monolithic architectures \"\n    \"for a high-frequency trading platform. Explain the implications for \"\n    \"latency, fault tolerance, and deployment complexity step by step.\"\n)\nprint(f\"Complex task -> {complex_task.name} (${complex_task.cost_per_1k_input}\u002F1K input)\")\n\n# Critical task with explicit quality floor\ncritical = router.route(\n    \"Review this legal contract for liability clauses\",\n    min_quality=0.93,\n    force_complexity=TaskComplexity.CRITICAL,\n)\nprint(f\"Critical task -> {critical.name}\")\n\n# Print routing stats\nprint(router.get_routing_stats())\n```\n\n### Fallback Chains\n\nModel APIs have outages. A production router needs fallback chains so that if the primary model is unavailable, the agent automatically tries the next-best option instead of failing.\n\n```python\nimport time\nfrom typing import List, Optional, Callable\n\n\nclass FallbackChain:\n    \"\"\"Executes inference with automatic fallback across model providers.\n\n    If the primary model fails (timeout, rate limit, server error),\n    the chain falls through to the next model. This provides both\n    resilience and cost optimization -- the fallback can be a cheaper\n    model that serves as a degraded-but-functional backup.\n    \"\"\"\n\n    def __init__(self, models: List[dict], timeout_ms: float = 5000):\n        \"\"\"\n        models: [{\"name\": \"gpt-4o\", \"client\": client, \"call_fn\": fn}, ...]\n        \"\"\"\n        self.models = models\n        self.timeout_ms = timeout_ms\n        self._fallback_stats = {\"attempts\": 0, \"fallbacks\": 0, \"failures\": 0}\n\n    def execute(self, messages: List[dict], max_tokens: int = 1024) -> dict:\n        \"\"\"Execute inference with fallback.\"\"\"\n        self._fallback_stats[\"attempts\"] += 1\n        errors = []\n\n        for i, model in enumerate(self.models):\n            try:\n                start = time.monotonic()\n                result = model[\"call_fn\"](\n                    model=model[\"name\"],\n                    messages=messages,\n                    max_tokens=max_tokens,\n                )\n                duration_ms = (time.monotonic() - start) * 1000\n\n                if i > 0:\n                    self._fallback_stats[\"fallbacks\"] += 1\n\n                return {\n                    \"content\": result,\n                    \"model_used\": model[\"name\"],\n                    \"fallback_index\": i,\n                    \"duration_ms\": round(duration_ms, 2),\n                    \"errors_before\": errors,\n                }\n            except Exception as e:\n                errors.append({\n                    \"model\": model[\"name\"],\n                    \"error\": str(e),\n                    \"type\": type(e).__name__,\n                })\n                continue\n\n        self._fallback_stats[\"failures\"] += 1\n        raise RuntimeError(\n            f\"All {len(self.models)} models failed. Errors: {errors}\"\n        )\n\n    def get_stats(self) -> dict:\n        total = self._fallback_stats[\"attempts\"]\n        return {\n            **self._fallback_stats,\n            \"fallback_rate_pct\": round(\n                self._fallback_stats[\"fallbacks\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n            \"failure_rate_pct\": round(\n                self._fallback_stats[\"failures\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n        }\n```\n\n### A\u002FB Testing Model Configurations\n\nBefore committing to a routing change, A\u002FB test it. Route a percentage of traffic to the new configuration and compare cost and quality metrics.\n\n```python\nimport random\nimport hashlib\nfrom typing import Dict\n\n\nclass ModelABTest:\n    \"\"\"A\u002FB tests model routing configurations.\n\n    Deterministically assigns requests to variants based on a\n    hash of the request ID, ensuring consistent assignment for\n    the same request across retries.\n    \"\"\"\n\n    def __init__(\n        self,\n        control_model: str,\n        treatment_model: str,\n        treatment_pct: float = 10.0,\n    ):\n        self.control = control_model\n        self.treatment = treatment_model\n        self.treatment_pct = treatment_pct\n        self._results: Dict[str, list] = {\"control\": [], \"treatment\": []}\n\n    def assign(self, request_id: str) -> str:\n        \"\"\"Deterministically assign a request to a variant.\"\"\"\n        hash_val = int(hashlib.md5(request_id.encode()).hexdigest(), 16)\n        bucket = hash_val % 1000\n        if bucket \u003C self.treatment_pct * 10:\n            return self.treatment\n        return self.control\n\n    def record_result(\n        self,\n        variant: str,\n        cost_usd: float,\n        quality_score: float,\n        latency_ms: float,\n    ):\n        \"\"\"Record the result of a request for analysis.\"\"\"\n        group = \"treatment\" if variant == self.treatment else \"control\"\n        self._results[group].append({\n            \"cost_usd\": cost_usd,\n            \"quality_score\": quality_score,\n            \"latency_ms\": latency_ms,\n        })\n\n    def analyze(self) -> dict:\n        \"\"\"Analyze A\u002FB test results.\"\"\"\n        analysis = {}\n        for group in [\"control\", \"treatment\"]:\n            results = self._results[group]\n            if not results:\n                analysis[group] = {\"count\": 0}\n                continue\n            analysis[group] = {\n                \"count\": len(results),\n                \"avg_cost\": round(\n                    sum(r[\"cost_usd\"] for r in results) \u002F len(results), 6\n                ),\n                \"avg_quality\": round(\n                    sum(r[\"quality_score\"] for r in results) \u002F len(results), 4\n                ),\n                \"avg_latency_ms\": round(\n                    sum(r[\"latency_ms\"] for r in results) \u002F len(results), 1\n                ),\n            }\n\n        # Compute lift\n        if analysis[\"control\"][\"count\"] > 0 and analysis[\"treatment\"][\"count\"] > 0:\n            cost_lift = (\n                (analysis[\"treatment\"][\"avg_cost\"] - analysis[\"control\"][\"avg_cost\"])\n                \u002F analysis[\"control\"][\"avg_cost\"] * 100\n            )\n            quality_lift = (\n                (analysis[\"treatment\"][\"avg_quality\"] - analysis[\"control\"][\"avg_quality\"])\n                \u002F analysis[\"control\"][\"avg_quality\"] * 100\n            )\n            analysis[\"lift\"] = {\n                \"cost_change_pct\": round(cost_lift, 1),\n                \"quality_change_pct\": round(quality_lift, 1),\n                \"recommendation\": (\n                    \"ADOPT treatment\"\n                    if cost_lift \u003C -10 and quality_lift > -2\n                    else \"KEEP control\"\n                    if quality_lift \u003C -5\n                    else \"CONTINUE testing\"\n                ),\n            }\n\n        return analysis\n\n\n# Usage\nab_test = ModelABTest(\n    control_model=\"gpt-4o\",\n    treatment_model=\"claude-haiku-3.5\",\n    treatment_pct=20.0,\n)\n\n# Simulate 1000 requests\nfor i in range(1000):\n    request_id = f\"req_{i}\"\n    model = ab_test.assign(request_id)\n\n    if model == \"gpt-4o\":\n        ab_test.record_result(\"gpt-4o\", cost_usd=0.008, quality_score=0.94, latency_ms=820)\n    else:\n        ab_test.record_result(\"claude-haiku-3.5\", cost_usd=0.001, quality_score=0.86, latency_ms=310)\n\nresults = ab_test.analyze()\nprint(f\"Control ({results['control']['count']} reqs): \"\n      f\"${results['control']['avg_cost']:.6f}\u002Freq, \"\n      f\"quality={results['control']['avg_quality']}\")\nprint(f\"Treatment ({results['treatment']['count']} reqs): \"\n      f\"${results['treatment']['avg_cost']:.6f}\u002Freq, \"\n      f\"quality={results['treatment']['avg_quality']}\")\nprint(f\"Recommendation: {results['lift']['recommendation']}\")\n```\n\n---\n\n## Chapter 4: Observability Cost Control\n\n### The Observability Bill Explosion\n\nWhen you deploy AI agents, your observability costs do not increase linearly -- they explode. A traditional web service generates one trace per HTTP request with 3-5 spans. An AI agent request generates 10-30 spans: the initial request, the LLM inference call, each tool call, each tool response parsing step, the orchestration decisions, and the final response assembly. Each span carries attributes for tokens, cost, model, latency, and agent-specific metadata. A single agent request that costs $0.01 in LLM inference can generate $0.005-0.02 in observability costs.\n\nThe math is brutal. A fleet of 12 agents handling 50,000 requests per day generates 500,000-1,500,000 spans per day. At Datadog's pricing of $1.70 per million spans, that is $0.85-2.55\u002Fday just for traces. Add custom metrics ($0.05 per custom metric per host), log management ($0.10 per GB ingested), and you are looking at $100-400\u002Fday in observability costs for a fleet that generates $300-500\u002Fday in direct AI costs. Observability becomes 20-80% of total operational cost.\n\nThe solution is not to stop observing. The solution is to observe intelligently: sample traces adaptively, manage metric cardinality, optimize log levels, and separate AI-specific telemetry from infrastructure telemetry.\n\n### Adaptive Sampling Middleware\n\nUniform sampling (e.g., \"sample 10% of all traces\") throws away valuable data. Errors, slow requests, and high-cost operations should always be sampled. Normal, fast, cheap operations can be sampled aggressively. Adaptive sampling adjusts the sampling rate based on the characteristics of each request.\n\n```python\nimport random\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Optional, Callable\n\n\n@dataclass\nclass SamplingConfig:\n    \"\"\"Configuration for adaptive sampling.\"\"\"\n    base_rate: float = 0.10       # Sample 10% of normal traffic\n    error_rate: float = 1.0       # Sample 100% of errors\n    slow_rate: float = 1.0        # Sample 100% of slow requests\n    expensive_rate: float = 0.50  # Sample 50% of expensive requests\n    slow_threshold_ms: float = 2000.0\n    expensive_threshold_usd: float = 0.05\n    min_rate: float = 0.01        # Never go below 1%\n    max_rate: float = 1.0         # Never exceed 100%\n\n\nclass AdaptiveSampler:\n    \"\"\"Adaptive trace sampler for AI agent observability.\n\n    Dynamically adjusts sampling rates based on request characteristics:\n    - Errors: always sampled\n    - Slow requests: always sampled\n    - Expensive operations: sampled at 50%\n    - Normal operations: sampled at configurable base rate\n    - Under high load: base rate decreases to control costs\n\n    The sampler also implements head-based sampling with consistent\n    hashing, so all spans for a given trace are either all sampled\n    or all dropped.\n    \"\"\"\n\n    def __init__(self, config: Optional[SamplingConfig] = None):\n        self.config = config or SamplingConfig()\n        self._stats = {\n            \"total\": 0,\n            \"sampled\": 0,\n            \"dropped\": 0,\n            \"by_reason\": {},\n        }\n        self._load_window: list = []  # (timestamp, count) for load tracking\n        self._current_rate = self.config.base_rate\n\n    def should_sample(\n        self,\n        trace_id: str,\n        is_error: bool = False,\n        duration_ms: Optional[float] = None,\n        cost_usd: Optional[float] = None,\n        metadata: Optional[Dict] = None,\n    ) -> bool:\n        \"\"\"Decide whether to sample a trace.\"\"\"\n        self._stats[\"total\"] += 1\n\n        # Determine the sampling rate for this request\n        rate, reason = self._compute_rate(is_error, duration_ms, cost_usd)\n\n        # Consistent hashing: same trace_id always gets same decision\n        hash_val = int(hashlib.md5(trace_id.encode()).hexdigest()[:8], 16)\n        threshold = int(rate * 0xFFFFFFFF)\n        sampled = hash_val \u003C= threshold\n\n        if sampled:\n            self._stats[\"sampled\"] += 1\n        else:\n            self._stats[\"dropped\"] += 1\n\n        self._stats[\"by_reason\"][reason] = (\n            self._stats[\"by_reason\"].get(reason, 0) + 1\n        )\n\n        return sampled\n\n    def _compute_rate(\n        self,\n        is_error: bool,\n        duration_ms: Optional[float],\n        cost_usd: Optional[float],\n    ) -> tuple:\n        \"\"\"Compute the sampling rate and reason for this request.\"\"\"\n        if is_error:\n            return self.config.error_rate, \"error\"\n\n        if duration_ms is not None and duration_ms > self.config.slow_threshold_ms:\n            return self.config.slow_rate, \"slow\"\n\n        if cost_usd is not None and cost_usd > self.config.expensive_threshold_usd:\n            return self.config.expensive_rate, \"expensive\"\n\n        # Adjust base rate based on load\n        self._update_load()\n        return self._current_rate, \"normal\"\n\n    def _update_load(self):\n        \"\"\"Reduce sampling rate under high load to control costs.\"\"\"\n        now = time.monotonic()\n        self._load_window.append(now)\n\n        # Keep only the last 60 seconds\n        cutoff = now - 60\n        self._load_window = [t for t in self._load_window if t > cutoff]\n\n        requests_per_minute = len(self._load_window)\n\n        # Scale down base rate as load increases\n        if requests_per_minute > 10000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.1)\n        elif requests_per_minute > 5000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.25)\n        elif requests_per_minute > 1000:\n            self._current_rate = max(self.config.min_rate, self.config.base_rate * 0.5)\n        else:\n            self._current_rate = self.config.base_rate\n\n    def get_stats(self) -> dict:\n        total = self._stats[\"total\"]\n        return {\n            \"total_decisions\": total,\n            \"sampled\": self._stats[\"sampled\"],\n            \"dropped\": self._stats[\"dropped\"],\n            \"effective_rate_pct\": round(\n                self._stats[\"sampled\"] \u002F total * 100, 1\n            ) if total > 0 else 0,\n            \"current_base_rate\": round(self._current_rate, 4),\n            \"by_reason\": self._stats[\"by_reason\"],\n        }\n\n    def estimate_cost_savings(\n        self,\n        cost_per_span: float = 0.0000017,  # $1.70 per million spans\n        avg_spans_per_trace: int = 15,\n    ) -> dict:\n        \"\"\"Estimate observability cost savings from sampling.\"\"\"\n        total = self._stats[\"total\"]\n        dropped = self._stats[\"dropped\"]\n\n        full_cost = total * avg_spans_per_trace * cost_per_span\n        actual_cost = (total - dropped) * avg_spans_per_trace * cost_per_span\n\n        return {\n            \"full_cost_usd\": round(full_cost, 4),\n            \"sampled_cost_usd\": round(actual_cost, 4),\n            \"savings_usd\": round(full_cost - actual_cost, 4),\n            \"savings_pct\": round(\n                (full_cost - actual_cost) \u002F full_cost * 100, 1\n            ) if full_cost > 0 else 0,\n        }\n\n\n# Usage\nsampler = AdaptiveSampler(SamplingConfig(\n    base_rate=0.10,\n    error_rate=1.0,\n    slow_rate=1.0,\n    expensive_rate=0.50,\n    slow_threshold_ms=2000,\n    expensive_threshold_usd=0.05,\n))\n\n# Simulate 10,000 requests with realistic distributions\nimport uuid\nfor i in range(10000):\n    trace_id = uuid.uuid4().hex\n    is_error = random.random() \u003C 0.02  # 2% error rate\n    duration = random.gauss(500, 300)  # Mean 500ms, some slow outliers\n    cost = random.gauss(0.01, 0.02)    # Mean $0.01, some expensive outliers\n\n    sampler.should_sample(\n        trace_id=trace_id,\n        is_error=is_error,\n        duration_ms=max(50, duration),\n        cost_usd=max(0.001, cost),\n    )\n\nstats = sampler.get_stats()\nprint(f\"Effective sampling rate: {stats['effective_rate_pct']}%\")\nprint(f\"Sampled: {stats['sampled']}, Dropped: {stats['dropped']}\")\nprint(f\"By reason: {stats['by_reason']}\")\n\nsavings = sampler.estimate_cost_savings()\nprint(f\"Observability cost savings: ${savings['savings_usd']:.4f} \"\n      f\"({savings['savings_pct']}%)\")\n```\n\n### Metrics Cardinality Management\n\nMetric cardinality -- the number of unique time series -- is the silent killer of observability budgets. Every unique combination of metric name and label values creates a new time series. If you have a metric `agent.request.duration` with labels `agent_id` (50 values), `model` (6 values), `status` (3 values), and `endpoint` (20 values), the cardinality is 50 * 6 * 3 * 20 = 18,000 time series. Add a `request_id` label by accident and cardinality becomes infinite.\n\n```python\nfrom typing import Set, Dict, List, Optional\nfrom collections import defaultdict\n\n\nclass CardinalityGuard:\n    \"\"\"Prevents metric cardinality explosion by enforcing limits\n    on label values and dropping high-cardinality dimensions.\n\n    Typical cost: Prometheus\u002FGrafana charges ~$8 per 1000 active\n    time series per month. Uncontrolled cardinality can create\n    millions of series, costing thousands of dollars per month\n    for metrics alone.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_cardinality_per_metric: int = 5000,\n        max_label_values: int = 100,\n        blocked_labels: Optional[Set[str]] = None,\n    ):\n        self.max_cardinality = max_cardinality_per_metric\n        self.max_label_values = max_label_values\n        self.blocked_labels = blocked_labels or {\n            \"request_id\", \"trace_id\", \"session_id\",\n            \"user_id\", \"conversation_id\", \"message_id\",\n        }\n        self._label_value_counts: Dict[str, Dict[str, int]] = defaultdict(dict)\n        self._series_counts: Dict[str, int] = defaultdict(int)\n        self._dropped: int = 0\n\n    def sanitize_labels(\n        self,\n        metric_name: str,\n        labels: Dict[str, str],\n    ) -> Optional[Dict[str, str]]:\n        \"\"\"Sanitize labels to prevent cardinality explosion.\n\n        Returns sanitized labels, or None if the metric should be dropped.\n        \"\"\"\n        # Remove blocked high-cardinality labels\n        sanitized = {\n            k: v for k, v in labels.items()\n            if k not in self.blocked_labels\n        }\n\n        # Check per-label cardinality\n        for key, value in list(sanitized.items()):\n            if key not in self._label_value_counts[metric_name]:\n                self._label_value_counts[metric_name][key] = {}\n            values = self._label_value_counts[metric_name][key]\n\n            if value not in values:\n                if len(values) >= self.max_label_values:\n                    # Replace with \"other\" to cap cardinality\n                    sanitized[key] = \"__other__\"\n                else:\n                    values[value] = 0\n            values.get(value, None)\n\n        # Check total series cardinality for this metric\n        series_key = f\"{metric_name}:{sorted(sanitized.items())}\"\n        self._series_counts[metric_name] += 1\n\n        if len(set(\n            str(sorted(labels.items()))\n            for labels in [sanitized]\n        )) > self.max_cardinality:\n            self._dropped += 1\n            return None\n\n        return sanitized\n\n    def get_stats(self) -> dict:\n        return {\n            \"tracked_metrics\": len(self._series_counts),\n            \"dropped_points\": self._dropped,\n            \"label_cardinality\": {\n                metric: {\n                    label: len(values)\n                    for label, values in labels.items()\n                }\n                for metric, labels in self._label_value_counts.items()\n            },\n        }\n\n\n# Usage\nguard = CardinalityGuard(\n    max_cardinality_per_metric=5000,\n    max_label_values=50,\n    blocked_labels={\"request_id\", \"trace_id\", \"session_id\"},\n)\n\n# This label set is safe\nsafe = guard.sanitize_labels(\"agent.duration\", {\n    \"agent_id\": \"researcher-01\",\n    \"model\": \"gpt-4o\",\n    \"status\": \"success\",\n})\nprint(f\"Safe labels: {safe}\")\n\n# This would cause cardinality explosion -- request_id is blocked\ndangerous = guard.sanitize_labels(\"agent.duration\", {\n    \"agent_id\": \"researcher-01\",\n    \"request_id\": \"req_abc123\",  # Blocked -- infinite cardinality\n    \"model\": \"gpt-4o\",\n})\nprint(f\"Sanitized labels: {dangerous}\")  # request_id removed\n```\n\n### Log Level Optimization\n\nAgent systems produce massive log volumes. A single LLM call can generate DEBUG-level logs for the full prompt, the full response, token counts, timing breakdowns, cache hits, and model metadata. At INFO level, you get the operation, model, token count, and duration. At WARN level, you get only slow requests and errors.\n\nThe optimization: use structured logging with dynamic level control per agent, and route AI-specific logs to a cheaper storage tier.\n\n```python\nimport logging\nimport json\nfrom typing import Dict, Optional\n\n\nclass CostAwareLogger:\n    \"\"\"Logger that optimizes log volume based on cost impact.\n\n    Routes logs to different backends based on category:\n    - AI inference logs: sampled, stored in cheap tier\n    - Error logs: always stored, stored in hot tier\n    - Debug logs: only in development, never in production\n\n    Estimated savings: 60-80% of log ingestion costs.\n    \"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        production: bool = True,\n        sample_rate: float = 0.10,\n    ):\n        self.agent_id = agent_id\n        self.production = production\n        self.sample_rate = sample_rate\n        self._log_counts: Dict[str, int] = {}\n\n        self.logger = logging.getLogger(f\"agent.{agent_id}\")\n        if production:\n            self.logger.setLevel(logging.WARNING)\n        else:\n            self.logger.setLevel(logging.DEBUG)\n\n    def inference(\n        self,\n        model: str,\n        input_tokens: int,\n        output_tokens: int,\n        duration_ms: float,\n        cost_usd: float,\n    ):\n        \"\"\"Log an inference event. Sampled in production.\"\"\"\n        self._count(\"inference\")\n\n        if self.production and __import__(\"random\").random() > self.sample_rate:\n            return  # Drop this log in production (sampled)\n\n        self.logger.info(json.dumps({\n            \"event\": \"inference\",\n            \"agent_id\": self.agent_id,\n            \"model\": model,\n            \"input_tokens\": input_tokens,\n            \"output_tokens\": output_tokens,\n            \"duration_ms\": round(duration_ms, 1),\n            \"cost_usd\": round(cost_usd, 6),\n        }))\n\n    def tool_call(self, tool: str, duration_ms: float, status: str):\n        \"\"\"Log a tool call. Always logged (low volume).\"\"\"\n        self._count(\"tool_call\")\n        self.logger.info(json.dumps({\n            \"event\": \"tool_call\",\n            \"agent_id\": self.agent_id,\n            \"tool\": tool,\n            \"duration_ms\": round(duration_ms, 1),\n            \"status\": status,\n        }))\n\n    def error(self, operation: str, error: str, context: Optional[Dict] = None):\n        \"\"\"Log an error. Always logged, never sampled.\"\"\"\n        self._count(\"error\")\n        self.logger.error(json.dumps({\n            \"event\": \"error\",\n            \"agent_id\": self.agent_id,\n            \"operation\": operation,\n            \"error\": error,\n            \"context\": context or {},\n        }))\n\n    def _count(self, event_type: str):\n        self._log_counts[event_type] = self._log_counts.get(event_type, 0) + 1\n\n    def get_log_volume_stats(self) -> dict:\n        total = sum(self._log_counts.values())\n        return {\n            \"total_events\": total,\n            \"by_type\": self._log_counts.copy(),\n            \"estimated_bytes\": total * 200,  # ~200 bytes per structured log\n            \"estimated_monthly_gb\": round(total * 200 * 30 \u002F 1e9, 3),\n        }\n```\n\n---\n\n## Chapter 5: Token Optimization\n\n### Measuring Token Waste\n\nBefore optimizing tokens, quantify the waste. Token waste is the difference between the tokens you send and the minimum tokens required to achieve the same output quality. Most agent systems waste 30-50% of input tokens on redundant system prompt content, verbose tool descriptions, unnecessary few-shot examples, and suboptimal response formatting instructions.\n\n```python\nimport re\nfrom typing import Dict, List, Tuple\n\n\nclass TokenWasteAnalyzer:\n    \"\"\"Analyzes an agent's prompts for token waste opportunities.\n\n    Identifies: redundant instructions, verbose phrasing, unnecessary\n    few-shot examples, bloated tool descriptions, and suboptimal\n    response format specifications.\n    \"\"\"\n\n    def __init__(self, tokens_per_word: float = 1.3):\n        self.tokens_per_word = tokens_per_word\n\n    def estimate_tokens(self, text: str) -> int:\n        return int(len(text.split()) * self.tokens_per_word)\n\n    def analyze_system_prompt(self, prompt: str) -> Dict:\n        \"\"\"Analyze a system prompt for waste.\"\"\"\n        total_tokens = self.estimate_tokens(prompt)\n        findings = []\n\n        # Check for redundant phrases\n        redundant = self._find_redundant_phrases(prompt)\n        if redundant:\n            findings.append({\n                \"type\": \"redundant_phrases\",\n                \"count\": len(redundant),\n                \"examples\": redundant[:5],\n                \"estimated_waste_tokens\": sum(\n                    self.estimate_tokens(phrase) for phrase in redundant\n                ),\n            })\n\n        # Check for verbose instructions\n        verbose = self._find_verbose_instructions(prompt)\n        if verbose:\n            findings.append({\n                \"type\": \"verbose_instructions\",\n                \"count\": len(verbose),\n                \"examples\": verbose[:3],\n                \"estimated_waste_tokens\": int(\n                    sum(self.estimate_tokens(v[0]) - self.estimate_tokens(v[1])\n                        for v in verbose)\n                ),\n            })\n\n        # Check for unnecessary few-shot examples\n        examples = self._count_examples(prompt)\n        if examples > 3:\n            waste = (examples - 2) * 150  # ~150 tokens per extra example\n            findings.append({\n                \"type\": \"excessive_examples\",\n                \"count\": examples,\n                \"recommended\": 2,\n                \"estimated_waste_tokens\": waste,\n            })\n\n        total_waste = sum(f.get(\"estimated_waste_tokens\", 0) for f in findings)\n        return {\n            \"total_tokens\": total_tokens,\n            \"estimated_waste_tokens\": total_waste,\n            \"waste_pct\": round(total_waste \u002F total_tokens * 100, 1) if total_tokens > 0 else 0,\n            \"findings\": findings,\n            \"potential_savings_per_1k_calls\": round(\n                total_waste * 2.50 \u002F 1_000_000 * 1000, 4\n            ),\n        }\n\n    def _find_redundant_phrases(self, text: str) -> List[str]:\n        \"\"\"Find phrases that appear multiple times.\"\"\"\n        # Split into sentences\n        sentences = re.split(r'[.!?]\\s+', text)\n        seen_concepts = {}\n        redundant = []\n        for s in sentences:\n            key = \" \".join(sorted(s.lower().split())[:5])\n            if key in seen_concepts and len(s.split()) > 5:\n                redundant.append(s.strip()[:100])\n            seen_concepts[key] = s\n        return redundant\n\n    def _find_verbose_instructions(self, text: str) -> List[Tuple[str, str]]:\n        \"\"\"Find verbose phrasings and suggest concise alternatives.\"\"\"\n        patterns = [\n            (r\"You must always make sure to (.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n            (r\"It is (?:very |extremely )?important (?:that you |to )(.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n            (r\"Please (?:make sure to |ensure that you )(.+?)(?:\\.|$)\",\n             lambda m: m.group(1).strip()),\n        ]\n        verbose = []\n        for pattern, fix in patterns:\n            for match in re.finditer(pattern, text, re.IGNORECASE):\n                verbose.append((match.group(0), fix(match)))\n        return verbose\n\n    def _count_examples(self, text: str) -> int:\n        \"\"\"Count few-shot examples in the prompt.\"\"\"\n        example_markers = [\n            r\"Example \\d+:\", r\"For example:\", r\"E\\.g\\.:\",\n            r\"Input:.*Output:\", r\"User:.*Assistant:\",\n            r\"```\\n.*?\\n```\",\n        ]\n        count = 0\n        for marker in example_markers:\n            count += len(re.findall(marker, text, re.IGNORECASE | re.DOTALL))\n        return count\n\n\n# Usage\nanalyzer = TokenWasteAnalyzer()\n\nbloated_prompt = \"\"\"\nYou are a helpful financial analysis assistant. You must always make sure to\nprovide accurate financial data. It is very important that you cite your sources.\nPlease make sure to format all numbers with two decimal places.\n\nYou must always make sure to check your calculations twice. It is extremely\nimportant to verify all financial figures. Please ensure that you provide\ncontext for every number you present.\n\nExample 1:\nUser: What is AAPL's P\u002FE ratio?\nAssistant: Apple's P\u002FE ratio is 28.5 as of April 2026.\n\nExample 2:\nUser: Compare AAPL and MSFT revenue.\nAssistant: Apple revenue: $394B. Microsoft revenue: $245B.\n\nExample 3:\nUser: What is the S&P 500 YTD return?\nAssistant: The S&P 500 YTD return is 8.2% as of April 2026.\n\nExample 4:\nUser: Calculate compound interest.\nAssistant: Using the formula A = P(1 + r\u002Fn)^(nt)...\n\nExample 5:\nUser: What is a good debt-to-equity ratio?\nAssistant: Generally, a D\u002FE ratio below 2.0 is considered healthy.\n\"\"\"\n\nanalysis = analyzer.analyze_system_prompt(bloated_prompt)\nprint(f\"Total tokens: {analysis['total_tokens']}\")\nprint(f\"Waste tokens: {analysis['estimated_waste_tokens']} ({analysis['waste_pct']}%)\")\nprint(f\"Savings per 1K calls: ${analysis['potential_savings_per_1k_calls']}\")\nfor finding in analysis[\"findings\"]:\n    print(f\"  {finding['type']}: {finding.get('estimated_waste_tokens', 0)} tokens\")\n```\n\n### System Prompt Optimization\n\nThe single largest token waste source is the system prompt. It is sent with every request, so even small reductions compound dramatically. Here is a systematic optimization process.\n\n```python\nclass SystemPromptOptimizer:\n    \"\"\"Optimizes system prompts through progressive compression.\n\n    Process:\n    1. Remove filler words and phrases\n    2. Consolidate duplicate instructions\n    3. Convert verbose rules to terse directives\n    4. Reduce few-shot examples to minimum effective set\n    5. Validate output quality is maintained\n    \"\"\"\n\n    def optimize(self, prompt: str) -> Tuple[str, dict]:\n        \"\"\"Optimize a system prompt. Returns (optimized, stats).\"\"\"\n        original_words = len(prompt.split())\n        result = prompt\n\n        # Step 1: Remove filler\n        result = self._remove_filler(result)\n\n        # Step 2: Consolidate duplicates\n        result = self._consolidate_duplicates(result)\n\n        # Step 3: Terse directives\n        result = self._to_terse_directives(result)\n\n        # Step 4: Clean up whitespace\n        result = re.sub(r'\\n{3,}', '\\n\\n', result)\n        result = re.sub(r'  +', ' ', result)\n        result = result.strip()\n\n        optimized_words = len(result.split())\n        reduction = (1 - optimized_words \u002F original_words) * 100\n\n        return result, {\n            \"original_words\": original_words,\n            \"optimized_words\": optimized_words,\n            \"reduction_pct\": round(reduction, 1),\n            \"estimated_token_savings\": int(\n                (original_words - optimized_words) * 1.3\n            ),\n        }\n\n    def _remove_filler(self, text: str) -> str:\n        fillers = [\n            r'\\bplease\\b', r'\\bkindly\\b', r'\\bmake sure to\\b',\n            r'\\bit is (?:very |extremely )?important (?:that |to )',\n            r'\\byou must always\\b', r'\\byou should always\\b',\n            r'\\bensure that you\\b', r'\\bremember to\\b',\n            r'\\bkeep in mind (?:that )?\\b', r'\\bnote that\\b',\n        ]\n        for filler in fillers:\n            text = re.sub(filler, '', text, flags=re.IGNORECASE)\n        return text\n\n    def _consolidate_duplicates(self, text: str) -> str:\n        sentences = re.split(r'(?\u003C=[.!?])\\s+', text)\n        seen = set()\n        unique = []\n        for s in sentences:\n            normalized = ' '.join(s.lower().split())\n            if normalized not in seen and len(normalized) > 10:\n                seen.add(normalized)\n                unique.append(s)\n        return ' '.join(unique)\n\n    def _to_terse_directives(self, text: str) -> str:\n        replacements = [\n            (r'When the user asks you to (.+?), you should (.+?)\\.', r'\\1: \\2.'),\n            (r'If (?:the user |a user |someone )(.+?), then (.+?)\\.', r'\\1 -> \\2.'),\n            (r'Always provide (.+?) in your responses', r'Include \\1'),\n            (r'You are a (.+?) assistant', r'Role: \\1'),\n        ]\n        for pattern, replacement in replacements:\n            text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)\n        return text\n\n\noptimizer = SystemPromptOptimizer()\noptimized, stats = optimizer.optimize(bloated_prompt)\nprint(f\"Before: {stats['original_words']} words\")\nprint(f\"After: {stats['optimized_words']} words\")\nprint(f\"Reduction: {stats['reduction_pct']}%\")\nprint(f\"Token savings: {stats['estimated_token_savings']}\")\n```\n\n### Response Format Optimization\n\nJSON output is often 30-50% more tokens than equivalent structured text. If your downstream consumer can parse structured text, switch from JSON to a compact text format.\n\n```python\nclass ResponseFormatOptimizer:\n    \"\"\"Optimizes response format instructions to minimize output tokens.\n\n    JSON: ~1.5x tokens vs structured text for the same information.\n    Markdown tables: ~1.2x tokens vs TSV.\n    Verbose JSON with descriptions: ~2.5x tokens vs compact JSON.\n    \"\"\"\n\n    FORMAT_COSTS = {\n        \"verbose_json\": 2.5,   # {\"name\": \"John\", \"age\": 30, \"city\": \"NYC\"}\n        \"compact_json\": 1.5,   # {\"n\":\"John\",\"a\":30,\"c\":\"NYC\"}\n        \"structured_text\": 1.0, # John|30|NYC\n        \"markdown_table\": 1.2,  # | John | 30 | NYC |\n        \"tsv\": 0.9,            # John\\t30\\tNYC\n    }\n\n    @staticmethod\n    def json_to_compact_instruction() -> str:\n        \"\"\"Generate a prompt instruction for compact JSON output.\"\"\"\n        return (\n            \"Output: JSON. No whitespace. Short keys. \"\n            \"Example: {\\\"n\\\":\\\"val\\\",\\\"s\\\":1} not {\\\"name\\\": \\\"val\\\", \\\"score\\\": 1}\"\n        )\n\n    @staticmethod\n    def estimate_format_savings(\n        records: int,\n        fields: int,\n        avg_value_length: int = 10,\n        from_format: str = \"verbose_json\",\n        to_format: str = \"compact_json\",\n    ) -> dict:\n        \"\"\"Estimate token savings from format change.\"\"\"\n        base_tokens = records * fields * (avg_value_length + 5)\n        from_tokens = base_tokens * ResponseFormatOptimizer.FORMAT_COSTS[from_format]\n        to_tokens = base_tokens * ResponseFormatOptimizer.FORMAT_COSTS[to_format]\n\n        savings = from_tokens - to_tokens\n        savings_pct = savings \u002F from_tokens * 100\n\n        return {\n            \"from_format\": from_format,\n            \"to_format\": to_format,\n            \"from_tokens\": int(from_tokens),\n            \"to_tokens\": int(to_tokens),\n            \"savings_tokens\": int(savings),\n            \"savings_pct\": round(savings_pct, 1),\n            \"savings_per_1k_calls_usd\": round(\n                savings * 10.00 \u002F 1_000_000 * 1000, 4  # Output token pricing\n            ),\n        }\n\n\n# Example: 50 records, 5 fields each\nsavings = ResponseFormatOptimizer.estimate_format_savings(\n    records=50, fields=5, from_format=\"verbose_json\", to_format=\"compact_json\"\n)\nprint(f\"Format change: {savings['from_format']} -> {savings['to_format']}\")\nprint(f\"Token savings: {savings['savings_tokens']} ({savings['savings_pct']}%)\")\nprint(f\"Savings per 1K calls: ${savings['savings_per_1k_calls_usd']}\")\n```\n\n### Tool Description Compression\n\nAgent tool descriptions are sent as part of the system prompt on every request. Twelve tools with verbose descriptions can add 3,000-5,000 tokens to every call. Compressing tool descriptions to the minimum needed for the model to use them correctly saves tokens on every single request.\n\n```python\nclass ToolDescriptionCompressor:\n    \"\"\"Compresses tool descriptions to minimize system prompt tokens.\n\n    A typical tool description with full parameter docs is 200-400 tokens.\n    Compressed to essential info only, it drops to 50-100 tokens.\n    With 12 tools, that is 1,800-3,600 tokens saved per request.\n    \"\"\"\n\n    def compress_tool(self, tool: dict) -> dict:\n        \"\"\"Compress a tool description.\"\"\"\n        compressed = {\n            \"name\": tool[\"name\"],\n            \"description\": self._shorten_description(\n                tool.get(\"description\", \"\")\n            ),\n            \"parameters\": self._compress_parameters(\n                tool.get(\"parameters\", {})\n            ),\n        }\n        return compressed\n\n    def _shorten_description(self, desc: str) -> str:\n        \"\"\"Shorten description to first sentence + key constraints.\"\"\"\n        sentences = desc.split(\". \")\n        if sentences:\n            short = sentences[0]\n            # Keep constraint sentences (containing \"must\", \"required\", \"max\")\n            for s in sentences[1:]:\n                if any(w in s.lower() for w in [\"must\", \"required\", \"max\", \"min\", \"limit\"]):\n                    short += \". \" + s\n            return short + \".\"\n        return desc\n\n    def _compress_parameters(self, params: dict) -> dict:\n        \"\"\"Remove verbose parameter descriptions, keep type and required.\"\"\"\n        if \"properties\" not in params:\n            return params\n        compressed = {\n            \"type\": params.get(\"type\", \"object\"),\n            \"properties\": {},\n            \"required\": params.get(\"required\", []),\n        }\n        for name, prop in params[\"properties\"].items():\n            compressed[\"properties\"][name] = {\n                \"type\": prop.get(\"type\", \"string\"),\n            }\n            if \"enum\" in prop:\n                compressed[\"properties\"][name][\"enum\"] = prop[\"enum\"]\n        return compressed\n\n    def compress_toolkit(self, tools: list) -> tuple:\n        \"\"\"Compress all tools and report savings.\"\"\"\n        import json\n        original_tokens = sum(\n            len(json.dumps(t).split()) * 1.3 for t in tools\n        )\n        compressed = [self.compress_tool(t) for t in tools]\n        compressed_tokens = sum(\n            len(json.dumps(t).split()) * 1.3 for t in compressed\n        )\n        savings = original_tokens - compressed_tokens\n\n        return compressed, {\n            \"original_tokens\": int(original_tokens),\n            \"compressed_tokens\": int(compressed_tokens),\n            \"savings_tokens\": int(savings),\n            \"savings_pct\": round(savings \u002F original_tokens * 100, 1),\n            \"savings_per_1k_calls_usd\": round(\n                savings * 2.50 \u002F 1_000_000 * 1000, 4\n            ),\n        }\n\n\n# Example: compress a verbose tool description\ncompressor = ToolDescriptionCompressor()\nverbose_tool = {\n    \"name\": \"search_documents\",\n    \"description\": (\n        \"Search the document database for relevant documents matching \"\n        \"the given query. This tool searches across all indexed documents \"\n        \"including PDFs, Word documents, and plain text files. The search \"\n        \"uses semantic similarity matching powered by embeddings. Results \"\n        \"are returned in order of relevance. You must provide a query \"\n        \"parameter. Maximum 50 results per query.\"\n    ),\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\n                \"type\": \"string\",\n                \"description\": \"The search query to match against documents. \"\n                               \"Should be a natural language description of what \"\n                               \"you are looking for. More specific queries produce \"\n                               \"better results.\",\n            },\n            \"max_results\": {\n                \"type\": \"integer\",\n                \"description\": \"The maximum number of results to return. \"\n                               \"Defaults to 10. Maximum allowed value is 50.\",\n            },\n            \"file_type\": {\n                \"type\": \"string\",\n                \"enum\": [\"pdf\", \"docx\", \"txt\", \"all\"],\n                \"description\": \"Filter results by file type. Use 'all' to \"\n                               \"search across all file types.\",\n            },\n        },\n        \"required\": [\"query\"],\n    },\n}\n\ncompressed = compressor.compress_tool(verbose_tool)\nprint(f\"Original description: {len(verbose_tool['description'].split())} words\")\nprint(f\"Compressed description: {len(compressed['description'].split())} words\")\n```\n\n---\n\n## Chapter 6: Outcome-Based Metering\n\n### The Problem with Input-Based Billing\n\nEvery cost optimization strategy in the previous chapters shares a blind spot: they measure cost in terms of inputs consumed -- tokens processed, API calls made, spans recorded, bytes stored. Input-based billing tells you what you spent, but it tells you nothing about what you got for that spending. A research agent that burns $4.20 in tokens and produces a report that saves the user three hours of manual work is wildly profitable. The same agent burning $0.80 and producing a hallucinated report that the user discards is infinitely expensive -- the cost-per-useful-outcome is undefined because the outcome was worthless.\n\nOutcome-based metering flips the equation. Instead of asking \"how much did we spend?\", it asks \"how much did we spend per successful outcome?\" This reframing changes every optimization decision. A model upgrade that increases token cost by 40% but doubles the success rate from 45% to 90% actually cuts cost-per-outcome by 30%. A prompt compression that saves 20% on tokens but drops success rate by 15% is a net loss. Without outcome metering, you would celebrate the token savings and never notice the quality degradation until customer complaints arrived weeks later.\n\nThe shift requires three capabilities: defining what constitutes a successful outcome, attributing outcomes across multi-step agent pipelines, and building the metering infrastructure to track cost-per-outcome in real time.\n\n### Defining Outcomes\n\nNot every agent invocation has a binary success\u002Ffailure. Outcomes exist on a spectrum, and your metering system must capture that nuance. Here is a taxonomy that works across most agent use cases.\n\n**1. Task Completion.** Did the agent finish the requested task? A code generation agent that produces compilable code has completed its task. One that errors out mid-generation has not. Completion rate is the baseline metric -- if your agents are not completing tasks, nothing else matters.\n\n**2. Quality Score.** Given that the task completed, how good was the output? Quality is domain-specific: for a summarization agent, it might be a ROUGE score against human summaries. For a classification agent, it is accuracy against labeled data. For a research agent, it might be the percentage of cited claims that are verifiable. Quality scores should be normalized to 0.0-1.0.\n\n**3. User Acceptance.** Did the end user accept the agent's output? This is the ultimate arbiter. An agent that produces technically correct output that the user rewrites from scratch has a zero acceptance rate. Track explicit signals (user clicked \"accept\", \"reject\", \"edit\") and implicit signals (user copied the output, user ignored it, user asked a follow-up that implies the first answer was wrong).\n\n**4. Business Value.** What was the downstream impact? A lead qualification agent that correctly identifies a $500K deal opportunity delivers more value than one that correctly classifies a $5K opportunity, even though both are \"correct.\" Business value metering connects agent cost to revenue impact.\n\n```python\nimport time\nimport hashlib\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List, Any\nfrom enum import Enum\nfrom datetime import datetime, timezone\n\n\nclass OutcomeStatus(Enum):\n    SUCCESS = \"success\"\n    PARTIAL = \"partial\"        # Task completed but with quality issues\n    FAILURE = \"failure\"        # Task did not complete\n    REJECTED = \"rejected\"      # User explicitly rejected the output\n    PENDING = \"pending\"        # Awaiting user feedback\n\n\n@dataclass\nclass OutcomeEvent:\n    \"\"\"Records the outcome of an agent task alongside its cost.\"\"\"\n    outcome_id: str\n    agent_id: str\n    task_type: str\n    status: OutcomeStatus\n    cost_usd: float\n    quality_score: float           # 0.0 to 1.0\n    user_accepted: Optional[bool] = None\n    business_value_usd: float = 0.0\n    input_tokens: int = 0\n    output_tokens: int = 0\n    latency_ms: float = 0.0\n    retries: int = 0\n    timestamp: str = field(\n        default_factory=lambda: datetime.now(timezone.utc).isoformat()\n    )\n    metadata: Dict[str, Any] = field(default_factory=dict)\n\n\nclass OutcomeMeter:\n    \"\"\"Tracks cost-per-outcome across agent operations.\n\n    Thread-safe. Computes real-time cost efficiency metrics\n    including cost-per-success, cost-per-quality-point, and\n    ROI based on business value attribution.\n    \"\"\"\n\n    def __init__(self):\n        self._outcomes: List[OutcomeEvent] = []\n\n    def record(self, outcome: OutcomeEvent):\n        \"\"\"Record an outcome event.\"\"\"\n        self._outcomes.append(outcome)\n\n    def cost_per_success(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate cost per successful outcome.\n\n        This is the core metric. Total cost divided by number of\n        successful outcomes gives you the true unit economics of\n        your agent fleet.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        successes = [e for e in events if e.status == OutcomeStatus.SUCCESS]\n        failures = [e for e in events if e.status == OutcomeStatus.FAILURE]\n        partials = [e for e in events if e.status == OutcomeStatus.PARTIAL]\n\n        success_count = len(successes)\n        cost_per_success = total_cost \u002F success_count if success_count > 0 else float(\"inf\")\n\n        # Cost wasted on failures\n        wasted_cost = sum(e.cost_usd for e in failures)\n\n        # Cost of retries (successful outcomes that required retries)\n        retry_overhead = sum(\n            e.cost_usd * (e.retries \u002F (e.retries + 1))\n            for e in successes if e.retries > 0\n        )\n\n        return {\n            \"total_outcomes\": len(events),\n            \"successes\": success_count,\n            \"failures\": len(failures),\n            \"partials\": len(partials),\n            \"success_rate_pct\": round(success_count \u002F len(events) * 100, 1),\n            \"total_cost_usd\": round(total_cost, 4),\n            \"cost_per_success_usd\": round(cost_per_success, 4),\n            \"wasted_cost_usd\": round(wasted_cost, 4),\n            \"wasted_pct\": round(wasted_cost \u002F total_cost * 100, 1) if total_cost > 0 else 0,\n            \"retry_overhead_usd\": round(retry_overhead, 4),\n        }\n\n    def quality_adjusted_cost(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate quality-adjusted cost per outcome.\n\n        Weights each outcome by its quality score. A $0.05 outcome\n        with quality 0.9 costs $0.056 per quality point. A $0.03\n        outcome with quality 0.5 costs $0.060 per quality point.\n        The cheaper outcome is actually more expensive when adjusted\n        for quality.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        total_quality = sum(e.quality_score for e in events)\n        avg_quality = total_quality \u002F len(events)\n        quality_adjusted = total_cost \u002F total_quality if total_quality > 0 else float(\"inf\")\n\n        # Segment by quality tier\n        high_quality = [e for e in events if e.quality_score >= 0.8]\n        mid_quality = [e for e in events if 0.5 \u003C= e.quality_score \u003C 0.8]\n        low_quality = [e for e in events if e.quality_score \u003C 0.5]\n\n        return {\n            \"total_outcomes\": len(events),\n            \"avg_quality_score\": round(avg_quality, 3),\n            \"total_cost_usd\": round(total_cost, 4),\n            \"cost_per_quality_point_usd\": round(quality_adjusted, 4),\n            \"high_quality_count\": len(high_quality),\n            \"high_quality_avg_cost\": round(\n                sum(e.cost_usd for e in high_quality) \u002F len(high_quality), 4\n            ) if high_quality else 0,\n            \"mid_quality_count\": len(mid_quality),\n            \"mid_quality_avg_cost\": round(\n                sum(e.cost_usd for e in mid_quality) \u002F len(mid_quality), 4\n            ) if mid_quality else 0,\n            \"low_quality_count\": len(low_quality),\n            \"low_quality_avg_cost\": round(\n                sum(e.cost_usd for e in low_quality) \u002F len(low_quality), 4\n            ) if low_quality else 0,\n        }\n\n    def roi_analysis(\n        self,\n        agent_id: Optional[str] = None,\n        task_type: Optional[str] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate ROI based on business value attribution.\n\n        Compares the total cost of agent operations against the\n        business value generated by successful outcomes.\n        \"\"\"\n        events = self._filter(agent_id, task_type)\n        if not events:\n            return {\"error\": \"no outcomes recorded\"}\n\n        total_cost = sum(e.cost_usd for e in events)\n        total_value = sum(e.business_value_usd for e in events if e.status == OutcomeStatus.SUCCESS)\n        roi = ((total_value - total_cost) \u002F total_cost * 100) if total_cost > 0 else 0\n\n        return {\n            \"total_cost_usd\": round(total_cost, 2),\n            \"total_business_value_usd\": round(total_value, 2),\n            \"net_value_usd\": round(total_value - total_cost, 2),\n            \"roi_pct\": round(roi, 1),\n            \"cost_to_value_ratio\": round(\n                total_cost \u002F total_value, 4\n            ) if total_value > 0 else float(\"inf\"),\n        }\n\n    def _filter(\n        self,\n        agent_id: Optional[str],\n        task_type: Optional[str],\n    ) -> List[OutcomeEvent]:\n        events = self._outcomes\n        if agent_id:\n            events = [e for e in events if e.agent_id == agent_id]\n        if task_type:\n            events = [e for e in events if e.task_type == task_type]\n        return events\n\n\n# Usage: track outcomes for a research agent fleet\nmeter = OutcomeMeter()\n\n# Simulate 500 research tasks across two agents\nimport random\nrandom.seed(42)\n\nfor i in range(500):\n    agent = random.choice([\"researcher-01\", \"researcher-02\"])\n    quality = random.gauss(0.78, 0.15)\n    quality = max(0.0, min(1.0, quality))\n    failed = quality \u003C 0.3\n    retries = random.randint(0, 3) if not failed else 0\n    base_cost = random.gauss(0.04, 0.015)\n    cost = base_cost * (1 + retries * 0.8)\n\n    meter.record(OutcomeEvent(\n        outcome_id=f\"task_{i:04d}\",\n        agent_id=agent,\n        task_type=\"research_report\",\n        status=OutcomeStatus.FAILURE if failed else OutcomeStatus.SUCCESS,\n        cost_usd=max(0.005, cost),\n        quality_score=quality,\n        business_value_usd=0 if failed else random.uniform(2.0, 15.0),\n        retries=retries,\n    ))\n\ncps = meter.cost_per_success()\nprint(f\"Success rate: {cps['success_rate_pct']}%\")\nprint(f\"Cost per success: ${cps['cost_per_success_usd']}\")\nprint(f\"Wasted on failures: ${cps['wasted_cost_usd']} ({cps['wasted_pct']}%)\")\n\nqac = meter.quality_adjusted_cost()\nprint(f\"Cost per quality point: ${qac['cost_per_quality_point_usd']}\")\n\nroi = meter.roi_analysis()\nprint(f\"ROI: {roi['roi_pct']}%\")\nprint(f\"Cost-to-value ratio: {roi['cost_to_value_ratio']}\")\n```\n\n### Outcome Attribution in Multi-Agent Pipelines\n\nIn a single-agent system, attribution is trivial: the agent either succeeded or it did not. Multi-agent pipelines break this simplicity. A research pipeline with an intake agent, a search agent, a synthesis agent, and a review agent involves four cost centers. When the pipeline produces a high-quality report, which agent gets credit? When it produces garbage, which agent is at fault?\n\nThe answer is proportional attribution with failure isolation. Each agent in the pipeline gets a share of the outcome value proportional to its cost contribution, but failure attribution is localized to the specific agent that caused the failure.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass PipelineStep:\n    \"\"\"A single step in a multi-agent pipeline.\"\"\"\n    agent_id: str\n    step_name: str\n    cost_usd: float\n    quality_score: float        # Quality of this step's output\n    duration_ms: float\n    input_tokens: int = 0\n    output_tokens: int = 0\n    passed_quality_gate: bool = True\n    failure_reason: Optional[str] = None\n\n\n@dataclass\nclass PipelineOutcome:\n    \"\"\"Complete outcome of a multi-agent pipeline execution.\"\"\"\n    pipeline_id: str\n    steps: List[PipelineStep]\n    final_status: OutcomeStatus\n    final_quality: float\n    business_value_usd: float = 0.0\n\n\nclass PipelineAttributor:\n    \"\"\"Attributes costs and outcomes across multi-agent pipelines.\n\n    Uses proportional cost attribution for successes and\n    root-cause isolation for failures. Each step has a quality\n    gate -- if a step's output quality falls below threshold,\n    downstream costs are attributed to the failing step.\n    \"\"\"\n\n    def __init__(self, quality_gate_threshold: float = 0.5):\n        self.quality_gate = quality_gate_threshold\n        self._pipelines: List[PipelineOutcome] = []\n\n    def record_pipeline(self, outcome: PipelineOutcome):\n        self._pipelines.append(outcome)\n\n    def attribute(self, pipeline: PipelineOutcome) -> Dict[str, Any]:\n        \"\"\"Attribute outcome value and waste across pipeline steps.\"\"\"\n        total_cost = sum(s.cost_usd for s in pipeline.steps)\n        attribution = {}\n\n        if pipeline.final_status == OutcomeStatus.SUCCESS:\n            # Proportional attribution: each step gets value\n            # proportional to its cost share, weighted by quality\n            quality_weighted_costs = {\n                s.step_name: s.cost_usd * s.quality_score\n                for s in pipeline.steps\n            }\n            total_weighted = sum(quality_weighted_costs.values())\n\n            for step in pipeline.steps:\n                weight = (\n                    quality_weighted_costs[step.step_name] \u002F total_weighted\n                    if total_weighted > 0 else 1.0 \u002F len(pipeline.steps)\n                )\n                attribution[step.step_name] = {\n                    \"agent_id\": step.agent_id,\n                    \"cost_usd\": round(step.cost_usd, 4),\n                    \"cost_share_pct\": round(step.cost_usd \u002F total_cost * 100, 1),\n                    \"value_share_pct\": round(weight * 100, 1),\n                    \"attributed_value_usd\": round(\n                        pipeline.business_value_usd * weight, 2\n                    ),\n                    \"quality_score\": round(step.quality_score, 3),\n                    \"status\": \"contributing\",\n                }\n        else:\n            # Failure attribution: find the root cause step\n            root_cause = None\n            for step in pipeline.steps:\n                if not step.passed_quality_gate or step.failure_reason:\n                    root_cause = step.step_name\n                    break\n\n            wasted_downstream = 0.0\n            past_failure = False\n            for step in pipeline.steps:\n                if step.step_name == root_cause:\n                    past_failure = True\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"root_cause\",\n                        \"failure_reason\": step.failure_reason or \"below quality gate\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n                elif past_failure:\n                    wasted_downstream += step.cost_usd\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"wasted_downstream\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n                else:\n                    attribution[step.step_name] = {\n                        \"agent_id\": step.agent_id,\n                        \"cost_usd\": round(step.cost_usd, 4),\n                        \"status\": \"completed_before_failure\",\n                        \"quality_score\": round(step.quality_score, 3),\n                    }\n\n            attribution[\"_failure_summary\"] = {\n                \"root_cause_step\": root_cause,\n                \"wasted_downstream_usd\": round(wasted_downstream, 4),\n                \"wasted_pct\": round(\n                    wasted_downstream \u002F total_cost * 100, 1\n                ) if total_cost > 0 else 0,\n            }\n\n        return {\n            \"pipeline_id\": pipeline.pipeline_id,\n            \"total_cost_usd\": round(total_cost, 4),\n            \"final_status\": pipeline.final_status.value,\n            \"attribution\": attribution,\n        }\n\n    def fleet_summary(self) -> Dict[str, Any]:\n        \"\"\"Summarize attribution across all recorded pipelines.\"\"\"\n        agent_stats: Dict[str, Dict[str, float]] = {}\n\n        for pipeline in self._pipelines:\n            attr = self.attribute(pipeline)\n            for step_name, data in attr[\"attribution\"].items():\n                if step_name.startswith(\"_\"):\n                    continue\n                aid = data[\"agent_id\"]\n                if aid not in agent_stats:\n                    agent_stats[aid] = {\n                        \"total_cost\": 0.0,\n                        \"attributed_value\": 0.0,\n                        \"root_cause_failures\": 0,\n                        \"wasted_downstream_cost\": 0.0,\n                    }\n                agent_stats[aid][\"total_cost\"] += data[\"cost_usd\"]\n                agent_stats[aid][\"attributed_value\"] += data.get(\n                    \"attributed_value_usd\", 0.0\n                )\n                if data.get(\"status\") == \"root_cause\":\n                    agent_stats[aid][\"root_cause_failures\"] += 1\n                if data.get(\"status\") == \"wasted_downstream\":\n                    agent_stats[aid][\"wasted_downstream_cost\"] += data[\"cost_usd\"]\n\n        return {\n            agent_id: {\n                \"total_cost_usd\": round(stats[\"total_cost\"], 2),\n                \"attributed_value_usd\": round(stats[\"attributed_value\"], 2),\n                \"root_cause_failures\": stats[\"root_cause_failures\"],\n                \"wasted_downstream_usd\": round(stats[\"wasted_downstream_cost\"], 2),\n                \"efficiency_ratio\": round(\n                    stats[\"attributed_value\"] \u002F stats[\"total_cost\"], 2\n                ) if stats[\"total_cost\"] > 0 else 0,\n            }\n            for agent_id, stats in agent_stats.items()\n        }\n\n\n# Example: a 4-step research pipeline\nattributor = PipelineAttributor(quality_gate_threshold=0.5)\n\n# Successful pipeline\nattributor.record_pipeline(PipelineOutcome(\n    pipeline_id=\"pipe_001\",\n    steps=[\n        PipelineStep(\"intake-agent\", \"intake\", 0.008, 0.95, 320),\n        PipelineStep(\"search-agent\", \"search\", 0.025, 0.88, 1200),\n        PipelineStep(\"synthesis-agent\", \"synthesis\", 0.045, 0.82, 2100),\n        PipelineStep(\"review-agent\", \"review\", 0.015, 0.91, 800),\n    ],\n    final_status=OutcomeStatus.SUCCESS,\n    final_quality=0.88,\n    business_value_usd=12.50,\n))\n\n# Failed pipeline -- search agent returned low-quality results\nattributor.record_pipeline(PipelineOutcome(\n    pipeline_id=\"pipe_002\",\n    steps=[\n        PipelineStep(\"intake-agent\", \"intake\", 0.008, 0.93, 310),\n        PipelineStep(\"search-agent\", \"search\", 0.022, 0.30, 900,\n                     passed_quality_gate=False,\n                     failure_reason=\"insufficient relevant sources\"),\n        PipelineStep(\"synthesis-agent\", \"synthesis\", 0.040, 0.25, 1800),\n        PipelineStep(\"review-agent\", \"review\", 0.012, 0.20, 600),\n    ],\n    final_status=OutcomeStatus.FAILURE,\n    final_quality=0.20,\n))\n\n# Analyze the failed pipeline\nresult = attributor.attribute(attributor._pipelines[1])\nprint(f\"Pipeline {result['pipeline_id']}: {result['final_status']}\")\nprint(f\"Total cost: ${result['total_cost_usd']}\")\nsummary = result[\"attribution\"][\"_failure_summary\"]\nprint(f\"Root cause: {summary['root_cause_step']}\")\nprint(f\"Wasted downstream: ${summary['wasted_downstream_usd']} ({summary['wasted_pct']}%)\")\n```\n\n### Pricing Strategies Tied to Value Delivered\n\nOutcome-based metering enables outcome-based pricing -- charging customers based on results rather than consumption. This aligns incentives: you only earn when your agents deliver value. Four pricing models work in practice.\n\n| Pricing Model | How It Works | Best For | Example |\n|---|---|---|---|\n| Per-successful-outcome | Flat fee per completed task | High-volume, uniform tasks | $0.15 per classified document |\n| Quality-tiered | Price varies by output quality | Tasks with measurable quality | $0.05 (draft) \u002F $0.20 (polished) |\n| Value-share | Percentage of business value generated | High-value, variable outcomes | 2% of deal value identified |\n| Guaranteed SLA | Fixed price with quality guarantee, refund on failure | Enterprise contracts | $0.25\u002Ftask, 95% quality SLA |\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any, Optional\nfrom enum import Enum\n\n\nclass PricingModel(Enum):\n    PER_SUCCESS = \"per_success\"\n    QUALITY_TIERED = \"quality_tiered\"\n    VALUE_SHARE = \"value_share\"\n    GUARANTEED_SLA = \"guaranteed_sla\"\n\n\n@dataclass\nclass PricingConfig:\n    model: PricingModel\n    # Per-success pricing\n    price_per_success: float = 0.0\n    # Quality-tiered pricing\n    quality_tiers: Dict[str, float] = None  # {\"high\": 0.20, \"medium\": 0.10, \"low\": 0.05}\n    quality_thresholds: Dict[str, float] = None  # {\"high\": 0.85, \"medium\": 0.60}\n    # Value-share pricing\n    value_share_pct: float = 0.0\n    minimum_fee: float = 0.0\n    # Guaranteed SLA\n    sla_price: float = 0.0\n    sla_quality_threshold: float = 0.0\n    sla_refund_pct: float = 100.0\n\n    def __post_init__(self):\n        if self.quality_tiers is None:\n            self.quality_tiers = {\"high\": 0.20, \"medium\": 0.10, \"low\": 0.05}\n        if self.quality_thresholds is None:\n            self.quality_thresholds = {\"high\": 0.85, \"medium\": 0.60}\n\n\nclass OutcomePricer:\n    \"\"\"Calculates charges based on outcome-based pricing models.\n\n    Replaces input-based billing (per-token, per-call) with\n    value-aligned pricing that charges based on results delivered.\n    \"\"\"\n\n    def __init__(self, config: PricingConfig):\n        self.config = config\n\n    def calculate_charge(\n        self,\n        status: OutcomeStatus,\n        quality_score: float,\n        business_value_usd: float = 0.0,\n        actual_cost_usd: float = 0.0,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate the charge for an outcome.\"\"\"\n        if self.config.model == PricingModel.PER_SUCCESS:\n            return self._per_success(status, actual_cost_usd)\n        elif self.config.model == PricingModel.QUALITY_TIERED:\n            return self._quality_tiered(status, quality_score, actual_cost_usd)\n        elif self.config.model == PricingModel.VALUE_SHARE:\n            return self._value_share(status, business_value_usd, actual_cost_usd)\n        elif self.config.model == PricingModel.GUARANTEED_SLA:\n            return self._guaranteed_sla(status, quality_score, actual_cost_usd)\n        return {\"error\": \"unknown pricing model\"}\n\n    def _per_success(self, status: OutcomeStatus, cost: float) -> Dict[str, Any]:\n        charge = self.config.price_per_success if status == OutcomeStatus.SUCCESS else 0.0\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"margin_pct\": round((charge - cost) \u002F charge * 100, 1) if charge > 0 else -100.0,\n            \"pricing_model\": \"per_success\",\n        }\n\n    def _quality_tiered(\n        self, status: OutcomeStatus, quality: float, cost: float,\n    ) -> Dict[str, Any]:\n        if status == OutcomeStatus.FAILURE:\n            tier, charge = \"failed\", 0.0\n        elif quality >= self.config.quality_thresholds[\"high\"]:\n            tier = \"high\"\n            charge = self.config.quality_tiers[\"high\"]\n        elif quality >= self.config.quality_thresholds[\"medium\"]:\n            tier = \"medium\"\n            charge = self.config.quality_tiers[\"medium\"]\n        else:\n            tier = \"low\"\n            charge = self.config.quality_tiers[\"low\"]\n\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"quality_tier\": tier,\n            \"quality_score\": round(quality, 3),\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"quality_tiered\",\n        }\n\n    def _value_share(\n        self, status: OutcomeStatus, value: float, cost: float,\n    ) -> Dict[str, Any]:\n        if status == OutcomeStatus.FAILURE:\n            charge = 0.0\n        else:\n            charge = max(\n                value * self.config.value_share_pct \u002F 100,\n                self.config.minimum_fee,\n            )\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"business_value_usd\": round(value, 2),\n            \"value_share_pct\": self.config.value_share_pct,\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"value_share\",\n        }\n\n    def _guaranteed_sla(\n        self, status: OutcomeStatus, quality: float, cost: float,\n    ) -> Dict[str, Any]:\n        charge = self.config.sla_price\n        refund = 0.0\n        if status == OutcomeStatus.FAILURE or quality \u003C self.config.sla_quality_threshold:\n            refund = charge * self.config.sla_refund_pct \u002F 100\n            charge -= refund\n\n        return {\n            \"charge_usd\": round(charge, 4),\n            \"refund_usd\": round(refund, 4),\n            \"met_sla\": status == OutcomeStatus.SUCCESS and quality >= self.config.sla_quality_threshold,\n            \"cost_usd\": round(cost, 4),\n            \"margin_usd\": round(charge - cost, 4),\n            \"pricing_model\": \"guaranteed_sla\",\n        }\n\n\n# Compare pricing models on same workload\nconfigs = {\n    \"per_success\": PricingConfig(\n        model=PricingModel.PER_SUCCESS,\n        price_per_success=0.15,\n    ),\n    \"quality_tiered\": PricingConfig(\n        model=PricingModel.QUALITY_TIERED,\n        quality_tiers={\"high\": 0.20, \"medium\": 0.10, \"low\": 0.03},\n        quality_thresholds={\"high\": 0.85, \"medium\": 0.60},\n    ),\n    \"value_share\": PricingConfig(\n        model=PricingModel.VALUE_SHARE,\n        value_share_pct=2.0,\n        minimum_fee=0.05,\n    ),\n    \"guaranteed_sla\": PricingConfig(\n        model=PricingModel.GUARANTEED_SLA,\n        sla_price=0.25,\n        sla_quality_threshold=0.80,\n        sla_refund_pct=100.0,\n    ),\n}\n\n# Simulate: 1000 tasks, 85% success, avg quality 0.78, avg value $8\nrandom.seed(99)\nfor name, config in configs.items():\n    pricer = OutcomePricer(config)\n    total_charge = 0.0\n    total_cost = 0.0\n    for _ in range(1000):\n        succeeded = random.random() \u003C 0.85\n        quality = random.gauss(0.78, 0.12)\n        quality = max(0.0, min(1.0, quality))\n        cost = random.gauss(0.04, 0.01)\n        value = random.uniform(3.0, 15.0) if succeeded else 0.0\n\n        result = pricer.calculate_charge(\n            status=OutcomeStatus.SUCCESS if succeeded else OutcomeStatus.FAILURE,\n            quality_score=quality,\n            business_value_usd=value,\n            actual_cost_usd=cost,\n        )\n        total_charge += result[\"charge_usd\"]\n        total_cost += result[\"cost_usd\"]\n\n    print(f\"{name:20s}: revenue=${total_charge:7.2f}  \"\n          f\"cost=${total_cost:6.2f}  \"\n          f\"margin=${total_charge - total_cost:7.2f}  \"\n          f\"margin%={((total_charge - total_cost) \u002F total_charge * 100) if total_charge > 0 else 0:5.1f}%\")\n```\n\nThe output reveals the tradeoffs clearly. Per-success pricing is predictable but ignores quality variation. Quality-tiered pricing rewards investment in output quality. Value-share pricing has the highest upside but the widest variance. Guaranteed-SLA pricing commands premium prices but exposes you to refund risk if quality drops. Most production deployments use quality-tiered pricing for high-volume tasks and value-share pricing for high-value, low-volume workflows.\n\n---\n\n## Chapter 7: Infrastructure Right-Sizing\n\n### The Infrastructure Cost Iceberg\n\nLLM inference costs dominate the conversation, but infrastructure costs are the iceberg beneath the surface. A production agent fleet requires compute for inference serving, batch processing queues, cache layers, persistent storage for agent memory, network bandwidth for inter-service communication, and orchestration overhead for container management. For teams running self-hosted models or hybrid architectures (some calls to API providers, some to local models), infrastructure can account for 40-60% of total agent cost. Even teams using only API providers pay infrastructure costs for the application layer, caching, observability, and storage.\n\nThe core principle of right-sizing is matching resource allocation to actual workload characteristics. Agent workloads are bursty, heterogeneous, and latency-sensitive in unpredictable ways. A customer-facing chat agent needs sub-second responses during business hours and near-zero traffic at 3 AM. A batch analysis pipeline needs maximum throughput for four hours and nothing for the other twenty. A background research agent needs moderate throughput with tolerance for multi-second latency. One infrastructure configuration cannot serve all three efficiently.\n\n### GPU vs CPU Sizing for Inference\n\nSelf-hosted model inference is the largest infrastructure cost decision. The wrong GPU choice wastes thousands of dollars per month. The right choice depends on three factors: model size, throughput requirement, and latency target.\n\n| Model Size | Recommended GPU | On-Demand $\u002Fhr | Throughput (tokens\u002Fs) | Cost per 1M Tokens |\n|---|---|---|---|---|\n| 7-8B params | NVIDIA T4 (16GB) | $0.526 | 80-120 | $1.22-1.83 |\n| 7-8B params | NVIDIA L4 (24GB) | $0.810 | 140-180 | $1.25-1.61 |\n| 13B params | NVIDIA A10G (24GB) | $1.212 | 60-90 | $3.74-5.61 |\n| 34B params | NVIDIA A100 40GB | $3.673 | 40-65 | $15.69-25.51 |\n| 70B params | NVIDIA A100 80GB | $4.234 | 20-35 | $33.60-58.81 |\n| 70B params | 2x NVIDIA A100 80GB | $8.468 | 45-70 | $33.60-52.27 |\n| 8B (quantized INT4) | NVIDIA T4 (16GB) | $0.526 | 150-220 | $0.66-0.97 |\n\nThe table reveals a critical insight: quantized small models on cheap GPUs often beat large models on expensive GPUs in cost-per-token by 10-30x. A quantized Llama 3 8B on a T4 at $0.97 per million tokens undercuts GPT-4o's API price of $2.50 per million input tokens -- and you control the hardware.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass GPUConfig:\n    \"\"\"Configuration for a GPU instance used for model inference.\"\"\"\n    name: str\n    gpu_type: str\n    vram_gb: int\n    hourly_cost: float\n    throughput_tokens_per_sec: float  # Sustained output throughput\n    max_batch_size: int\n    power_watts: int\n\n\n@dataclass\nclass InferenceWorkload:\n    \"\"\"Describes an inference workload's requirements.\"\"\"\n    model_size_b: float              # Model size in billions of params\n    avg_input_tokens: int\n    avg_output_tokens: int\n    requests_per_hour: int\n    latency_target_ms: float         # p95 target\n    hours_per_day: float = 24.0\n    quantized: bool = False\n\n\nclass InfrastructureSizer:\n    \"\"\"Calculates optimal GPU configuration for inference workloads.\n\n    Compares self-hosted inference costs against API provider costs\n    and recommends the most cost-effective deployment strategy.\n    \"\"\"\n\n    GPU_CATALOG = {\n        \"t4\": GPUConfig(\"t4\", \"NVIDIA T4\", 16, 0.526, 100, 32, 70),\n        \"l4\": GPUConfig(\"l4\", \"NVIDIA L4\", 24, 0.810, 160, 64, 72),\n        \"a10g\": GPUConfig(\"a10g\", \"NVIDIA A10G\", 24, 1.212, 75, 48, 150),\n        \"a100-40\": GPUConfig(\"a100-40\", \"NVIDIA A100 40GB\", 40, 3.673, 52, 64, 250),\n        \"a100-80\": GPUConfig(\"a100-80\", \"NVIDIA A100 80GB\", 80, 4.234, 28, 128, 300),\n    }\n\n    API_PRICING = {\n        \"gpt-4o\":           {\"input\": 2.50, \"output\": 10.00},\n        \"gpt-4o-mini\":      {\"input\": 0.15, \"output\": 0.60},\n        \"claude-sonnet-4\":  {\"input\": 3.00, \"output\": 15.00},\n        \"claude-haiku-3.5\": {\"input\": 0.80, \"output\": 4.00},\n    }\n\n    # Approximate VRAM requirement: ~2 bytes per param (FP16), ~0.5 bytes (INT4)\n    BYTES_PER_PARAM_FP16 = 2.0\n    BYTES_PER_PARAM_INT4 = 0.5\n\n    def size_gpu(self, workload: InferenceWorkload) -> Dict[str, Any]:\n        \"\"\"Find the cheapest GPU config that meets workload requirements.\"\"\"\n        bytes_per_param = (\n            self.BYTES_PER_PARAM_INT4 if workload.quantized\n            else self.BYTES_PER_PARAM_FP16\n        )\n        required_vram_gb = workload.model_size_b * bytes_per_param\n\n        # Filter GPUs that have enough VRAM (with 20% headroom for KV cache)\n        viable_gpus = [\n            gpu for gpu in self.GPU_CATALOG.values()\n            if gpu.vram_gb >= required_vram_gb * 1.2\n        ]\n\n        if not viable_gpus:\n            return {\"error\": f\"No single GPU has enough VRAM for {required_vram_gb:.1f}GB model\"}\n\n        # Check throughput requirements\n        tokens_per_hour = workload.requests_per_hour * (\n            workload.avg_input_tokens + workload.avg_output_tokens\n        )\n        tokens_per_sec_needed = tokens_per_hour \u002F 3600\n\n        results = []\n        for gpu in viable_gpus:\n            # Throughput scales with quantization\n            effective_throughput = (\n                gpu.throughput_tokens_per_sec * 1.8 if workload.quantized\n                else gpu.throughput_tokens_per_sec\n            )\n\n            gpus_needed = max(1, int(\n                tokens_per_sec_needed \u002F effective_throughput + 0.99\n            ))\n\n            # Cost calculation\n            hourly_cost = gpu.hourly_cost * gpus_needed\n            daily_cost = hourly_cost * workload.hours_per_day\n            monthly_cost = daily_cost * 30\n            cost_per_1m_tokens = (\n                hourly_cost \u002F (effective_throughput * gpus_needed * 3600) * 1_000_000\n            )\n\n            # Latency estimate (simplified: output tokens \u002F throughput * 1000)\n            latency_est_ms = (\n                workload.avg_output_tokens \u002F effective_throughput * 1000\n            )\n\n            results.append({\n                \"gpu_type\": gpu.name,\n                \"gpu_name\": gpu.gpu_type,\n                \"gpus_needed\": gpus_needed,\n                \"monthly_cost_usd\": round(monthly_cost, 2),\n                \"cost_per_1m_tokens_usd\": round(cost_per_1m_tokens, 4),\n                \"estimated_latency_ms\": round(latency_est_ms, 1),\n                \"meets_latency_target\": latency_est_ms \u003C= workload.latency_target_ms,\n                \"utilization_pct\": round(\n                    tokens_per_sec_needed \u002F (effective_throughput * gpus_needed) * 100, 1\n                ),\n            })\n\n        results.sort(key=lambda r: r[\"monthly_cost_usd\"])\n        return {\n            \"workload\": {\n                \"model_size_b\": workload.model_size_b,\n                \"requests_per_hour\": workload.requests_per_hour,\n                \"tokens_per_sec_needed\": round(tokens_per_sec_needed, 1),\n                \"quantized\": workload.quantized,\n            },\n            \"options\": results,\n            \"recommended\": next(\n                (r for r in results if r[\"meets_latency_target\"]),\n                results[0] if results else None,\n            ),\n        }\n\n    def compare_self_hosted_vs_api(\n        self,\n        workload: InferenceWorkload,\n        api_model: str = \"gpt-4o-mini\",\n    ) -> Dict[str, Any]:\n        \"\"\"Compare self-hosted inference cost against API provider.\"\"\"\n        gpu_result = self.size_gpu(workload)\n        if \"error\" in gpu_result:\n            return gpu_result\n\n        recommended = gpu_result[\"recommended\"]\n        self_hosted_monthly = recommended[\"monthly_cost_usd\"]\n\n        # API cost\n        pricing = self.API_PRICING.get(api_model, {\"input\": 2.50, \"output\": 10.00})\n        requests_per_month = workload.requests_per_hour * workload.hours_per_day * 30\n        api_monthly = requests_per_month * (\n            workload.avg_input_tokens * pricing[\"input\"] \u002F 1_000_000\n            + workload.avg_output_tokens * pricing[\"output\"] \u002F 1_000_000\n        )\n\n        savings = api_monthly - self_hosted_monthly\n        savings_pct = (savings \u002F api_monthly * 100) if api_monthly > 0 else 0\n\n        return {\n            \"self_hosted\": {\n                \"gpu\": recommended[\"gpu_name\"],\n                \"gpus_needed\": recommended[\"gpus_needed\"],\n                \"monthly_cost_usd\": round(self_hosted_monthly, 2),\n                \"cost_per_1m_tokens\": recommended[\"cost_per_1m_tokens_usd\"],\n            },\n            \"api\": {\n                \"model\": api_model,\n                \"monthly_cost_usd\": round(api_monthly, 2),\n                \"cost_per_1m_tokens\": round(\n                    (pricing[\"input\"] + pricing[\"output\"]) \u002F 2, 2\n                ),\n            },\n            \"savings_usd\": round(savings, 2),\n            \"savings_pct\": round(savings_pct, 1),\n            \"recommendation\": (\n                \"SELF-HOST\" if savings > 200 and savings_pct > 20\n                else \"USE API\" if savings \u003C -100\n                else \"EVALUATE FURTHER\"\n            ),\n            \"breakeven_requests_per_hour\": round(\n                self_hosted_monthly \u002F 30 \u002F workload.hours_per_day \u002F (\n                    workload.avg_input_tokens * pricing[\"input\"] \u002F 1_000_000\n                    + workload.avg_output_tokens * pricing[\"output\"] \u002F 1_000_000\n                ), 0\n            ) if api_monthly > 0 else 0,\n        }\n\n\n# Example: Size infrastructure for a classification agent fleet\nsizer = InfrastructureSizer()\n\n# Workload: 8B quantized model, 5000 req\u002Fhr, 500ms latency target\nclassification_workload = InferenceWorkload(\n    model_size_b=8.0,\n    avg_input_tokens=500,\n    avg_output_tokens=50,\n    requests_per_hour=5000,\n    latency_target_ms=500,\n    hours_per_day=16,  # Business hours only\n    quantized=True,\n)\n\nresult = sizer.size_gpu(classification_workload)\nrec = result[\"recommended\"]\nprint(f\"Recommended: {rec['gpus_needed']}x {rec['gpu_name']}\")\nprint(f\"Monthly cost: ${rec['monthly_cost_usd']}\")\nprint(f\"Cost per 1M tokens: ${rec['cost_per_1m_tokens_usd']}\")\nprint(f\"Estimated latency: {rec['estimated_latency_ms']}ms\")\n\n# Compare against API\ncomparison = sizer.compare_self_hosted_vs_api(classification_workload, \"gpt-4o-mini\")\nprint(f\"\\nSelf-hosted: ${comparison['self_hosted']['monthly_cost_usd']}\u002Fmo\")\nprint(f\"API ({comparison['api']['model']}): ${comparison['api']['monthly_cost_usd']}\u002Fmo\")\nprint(f\"Savings: ${comparison['savings_usd']}\u002Fmo ({comparison['savings_pct']}%)\")\nprint(f\"Recommendation: {comparison['recommendation']}\")\n```\n\n### Batch Processing vs Real-Time\n\nNot every agent task requires real-time response. Batch processing is 50% cheaper on both OpenAI and Anthropic APIs, and self-hosted batch processing achieves higher GPU utilization (90%+ vs 30-50% for real-time serving). The key is identifying which tasks can tolerate latency.\n\n| Task Type | Latency Tolerance | Processing Mode | Cost Multiplier |\n|---|---|---|---|\n| Customer chat responses | \u003C 2 seconds | Real-time | 1.0x |\n| Email draft generation | \u003C 30 seconds | Near-real-time | 0.8x |\n| Document classification | \u003C 5 minutes | Micro-batch | 0.6x |\n| Nightly report generation | \u003C 4 hours | Batch | 0.5x |\n| Training data labeling | \u003C 24 hours | Batch (off-peak) | 0.35x |\n| Embedding generation | \u003C 12 hours | Batch (spot instances) | 0.25x |\n\n```python\nimport time\nimport heapq\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Any, Optional, Callable\nfrom enum import Enum\nfrom datetime import datetime, timezone\n\n\nclass ProcessingMode(Enum):\n    REALTIME = \"realtime\"\n    NEAR_REALTIME = \"near_realtime\"\n    MICRO_BATCH = \"micro_batch\"\n    BATCH = \"batch\"\n\n\n@dataclass\nclass AgentTask:\n    \"\"\"A task to be processed by an agent.\"\"\"\n    task_id: str\n    task_type: str\n    payload: Dict[str, Any]\n    priority: int = 0                     # Lower is higher priority\n    max_latency_ms: float = 2000.0\n    created_at: float = field(default_factory=time.time)\n    estimated_tokens: int = 1000\n\n\nclass WorkloadScheduler:\n    \"\"\"Schedules agent tasks across processing modes for cost optimization.\n\n    Routes tasks to the cheapest processing mode that meets their\n    latency requirements. Accumulates batch-eligible tasks and\n    flushes them at configurable intervals.\n    \"\"\"\n\n    MODE_COST_MULTIPLIERS = {\n        ProcessingMode.REALTIME: 1.0,\n        ProcessingMode.NEAR_REALTIME: 0.8,\n        ProcessingMode.MICRO_BATCH: 0.6,\n        ProcessingMode.BATCH: 0.5,\n    }\n\n    # Latency thresholds for mode assignment (milliseconds)\n    MODE_THRESHOLDS = {\n        ProcessingMode.REALTIME: 2_000,\n        ProcessingMode.NEAR_REALTIME: 30_000,\n        ProcessingMode.MICRO_BATCH: 300_000,\n        ProcessingMode.BATCH: 14_400_000,   # 4 hours\n    }\n\n    def __init__(\n        self,\n        micro_batch_size: int = 20,\n        micro_batch_interval_sec: float = 60.0,\n        batch_flush_interval_sec: float = 3600.0,\n    ):\n        self.micro_batch_size = micro_batch_size\n        self.micro_batch_interval = micro_batch_interval_sec\n        self.batch_flush_interval = batch_flush_interval_sec\n\n        self._realtime_queue: List[AgentTask] = []\n        self._micro_batch_queue: List[AgentTask] = []\n        self._batch_queue: List[AgentTask] = []\n        self._stats = {mode.value: {\"count\": 0, \"tokens\": 0} for mode in ProcessingMode}\n\n    def classify_and_enqueue(self, task: AgentTask) -> ProcessingMode:\n        \"\"\"Classify a task's processing mode and add it to the right queue.\"\"\"\n        mode = self._classify(task)\n        self._stats[mode.value][\"count\"] += 1\n        self._stats[mode.value][\"tokens\"] += task.estimated_tokens\n\n        if mode == ProcessingMode.REALTIME or mode == ProcessingMode.NEAR_REALTIME:\n            self._realtime_queue.append(task)\n        elif mode == ProcessingMode.MICRO_BATCH:\n            self._micro_batch_queue.append(task)\n        else:\n            self._batch_queue.append(task)\n\n        return mode\n\n    def _classify(self, task: AgentTask) -> ProcessingMode:\n        \"\"\"Assign the cheapest processing mode that meets latency requirements.\"\"\"\n        for mode in [ProcessingMode.BATCH, ProcessingMode.MICRO_BATCH,\n                     ProcessingMode.NEAR_REALTIME, ProcessingMode.REALTIME]:\n            if task.max_latency_ms >= self.MODE_THRESHOLDS[mode]:\n                return mode\n        return ProcessingMode.REALTIME\n\n    def get_micro_batch(self) -> Optional[List[AgentTask]]:\n        \"\"\"Get a micro-batch if enough tasks are queued.\"\"\"\n        if len(self._micro_batch_queue) >= self.micro_batch_size:\n            batch = self._micro_batch_queue[:self.micro_batch_size]\n            self._micro_batch_queue = self._micro_batch_queue[self.micro_batch_size:]\n            return batch\n        return None\n\n    def flush_batch_queue(self) -> List[AgentTask]:\n        \"\"\"Flush all accumulated batch tasks for processing.\"\"\"\n        tasks = list(self._batch_queue)\n        self._batch_queue = []\n        return tasks\n\n    def cost_savings_report(self, base_cost_per_1m_tokens: float = 2.50) -> Dict[str, Any]:\n        \"\"\"Calculate savings from workload scheduling.\"\"\"\n        total_tokens = sum(s[\"tokens\"] for s in self._stats.values())\n        realtime_cost = total_tokens * base_cost_per_1m_tokens \u002F 1_000_000\n\n        actual_cost = 0.0\n        mode_breakdown = {}\n        for mode in ProcessingMode:\n            stats = self._stats[mode.value]\n            multiplier = self.MODE_COST_MULTIPLIERS[mode]\n            mode_cost = stats[\"tokens\"] * base_cost_per_1m_tokens * multiplier \u002F 1_000_000\n            actual_cost += mode_cost\n            mode_breakdown[mode.value] = {\n                \"task_count\": stats[\"count\"],\n                \"tokens\": stats[\"tokens\"],\n                \"cost_usd\": round(mode_cost, 4),\n                \"cost_multiplier\": multiplier,\n            }\n\n        return {\n            \"total_tokens\": total_tokens,\n            \"all_realtime_cost_usd\": round(realtime_cost, 4),\n            \"actual_cost_usd\": round(actual_cost, 4),\n            \"savings_usd\": round(realtime_cost - actual_cost, 4),\n            \"savings_pct\": round(\n                (realtime_cost - actual_cost) \u002F realtime_cost * 100, 1\n            ) if realtime_cost > 0 else 0,\n            \"by_mode\": mode_breakdown,\n        }\n\n\n# Example: Schedule 1000 mixed tasks\nscheduler = WorkloadScheduler(micro_batch_size=20)\nimport random\nrandom.seed(42)\n\ntask_profiles = [\n    (\"chat_response\", 1500, 500),       # Must be fast\n    (\"email_draft\", 20000, 2000),        # Can wait 20 seconds\n    (\"document_classify\", 300000, 800),  # Can wait 5 minutes\n    (\"nightly_report\", 14400000, 5000),  # Can wait 4 hours\n    (\"embedding_gen\", 43200000, 300),    # Can wait 12 hours\n]\n\nfor i in range(1000):\n    task_type, max_latency, tokens = random.choice(task_profiles)\n    task = AgentTask(\n        task_id=f\"task_{i:04d}\",\n        task_type=task_type,\n        payload={\"content\": f\"task content {i}\"},\n        max_latency_ms=max_latency,\n        estimated_tokens=tokens,\n    )\n    scheduler.classify_and_enqueue(task)\n\nreport = scheduler.cost_savings_report(base_cost_per_1m_tokens=2.50)\nprint(f\"All real-time cost: ${report['all_realtime_cost_usd']}\")\nprint(f\"Scheduled cost:     ${report['actual_cost_usd']}\")\nprint(f\"Savings:            ${report['savings_usd']} ({report['savings_pct']}%)\")\nfor mode, data in report[\"by_mode\"].items():\n    print(f\"  {mode:20s}: {data['task_count']:4d} tasks, ${data['cost_usd']:.4f}\")\n```\n\n### Autoscaling Patterns for Agent Workloads\n\nAgent traffic is bursty. A customer support fleet might handle 200 requests per minute during business hours and 5 requests per minute overnight. Paying for peak capacity 24\u002F7 wastes 70-80% of off-peak compute. Autoscaling solves this -- but standard autoscaling policies designed for web servers perform poorly for agent workloads because agent requests are long-running (5-30 seconds vs 50-200ms for web requests) and resource-intensive.\n\n```python\nimport time\nimport math\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass ScalingConfig:\n    \"\"\"Autoscaling configuration for an agent inference fleet.\"\"\"\n    min_replicas: int = 1\n    max_replicas: int = 20\n    target_utilization_pct: float = 70.0\n    scale_up_threshold_pct: float = 80.0\n    scale_down_threshold_pct: float = 40.0\n    scale_up_cooldown_sec: float = 60.0\n    scale_down_cooldown_sec: float = 300.0\n    requests_per_replica: float = 10.0     # Max concurrent requests per replica\n    cost_per_replica_hour: float = 1.212   # A10G on-demand\n\n\nclass AgentAutoscaler:\n    \"\"\"Autoscaler optimized for AI agent workloads.\n\n    Key differences from standard web autoscalers:\n    1. Predictive scaling: uses time-of-day patterns to pre-scale\n    2. Request-duration-aware: accounts for long-running agent requests\n    3. Cost-aware: factors in cost when deciding scale-down speed\n    4. Warm pool: keeps a minimum warm pool to handle burst arrivals\n    \"\"\"\n\n    def __init__(self, config: ScalingConfig):\n        self.config = config\n        self.current_replicas = config.min_replicas\n        self._last_scale_up = 0.0\n        self._last_scale_down = 0.0\n        self._history: List[Dict[str, Any]] = []\n        self._hourly_patterns: Dict[int, float] = {}  # hour -> avg requests\n\n    def record_traffic(self, hour: int, requests_per_minute: float):\n        \"\"\"Record traffic pattern for predictive scaling.\"\"\"\n        if hour not in self._hourly_patterns:\n            self._hourly_patterns[hour] = requests_per_minute\n        else:\n            # Exponential moving average\n            self._hourly_patterns[hour] = (\n                0.7 * self._hourly_patterns[hour] + 0.3 * requests_per_minute\n            )\n\n    def evaluate(\n        self,\n        current_requests_per_minute: float,\n        avg_request_duration_sec: float,\n        current_hour: int,\n    ) -> Dict[str, Any]:\n        \"\"\"Evaluate whether to scale up, down, or hold.\n\n        Returns scaling decision with cost impact analysis.\n        \"\"\"\n        now = time.time()\n\n        # Calculate current utilization\n        concurrent_requests = current_requests_per_minute \u002F 60 * avg_request_duration_sec\n        capacity = self.current_replicas * self.config.requests_per_replica\n        utilization = (concurrent_requests \u002F capacity * 100) if capacity > 0 else 100\n\n        # Predictive component: look ahead 1 hour\n        next_hour = (current_hour + 1) % 24\n        predicted_rpm = self._hourly_patterns.get(next_hour, current_requests_per_minute)\n        predicted_concurrent = predicted_rpm \u002F 60 * avg_request_duration_sec\n\n        # Desired replicas based on current load\n        desired_current = math.ceil(\n            concurrent_requests \u002F (self.config.requests_per_replica\n                                   * self.config.target_utilization_pct \u002F 100)\n        )\n        # Desired replicas based on predicted load\n        desired_predicted = math.ceil(\n            predicted_concurrent \u002F (self.config.requests_per_replica\n                                    * self.config.target_utilization_pct \u002F 100)\n        )\n        # Take the higher of current and predicted (pre-scale for upcoming load)\n        desired = max(desired_current, desired_predicted)\n        desired = max(self.config.min_replicas, min(self.config.max_replicas, desired))\n\n        action = \"hold\"\n        new_replicas = self.current_replicas\n\n        if desired > self.current_replicas:\n            if now - self._last_scale_up >= self.config.scale_up_cooldown_sec:\n                new_replicas = desired\n                action = \"scale_up\"\n                self._last_scale_up = now\n        elif desired \u003C self.current_replicas:\n            if now - self._last_scale_down >= self.config.scale_down_cooldown_sec:\n                # Scale down gradually (max 25% at a time to avoid thrashing)\n                max_reduction = max(1, self.current_replicas \u002F\u002F 4)\n                new_replicas = max(desired, self.current_replicas - max_reduction)\n                action = \"scale_down\"\n                self._last_scale_down = now\n\n        cost_before = self.current_replicas * self.config.cost_per_replica_hour\n        cost_after = new_replicas * self.config.cost_per_replica_hour\n        old_replicas = self.current_replicas\n        self.current_replicas = new_replicas\n\n        decision = {\n            \"action\": action,\n            \"replicas_before\": old_replicas,\n            \"replicas_after\": new_replicas,\n            \"utilization_pct\": round(utilization, 1),\n            \"concurrent_requests\": round(concurrent_requests, 1),\n            \"predicted_next_hour_rpm\": round(predicted_rpm, 1),\n            \"hourly_cost_before\": round(cost_before, 2),\n            \"hourly_cost_after\": round(cost_after, 2),\n            \"hourly_savings\": round(cost_before - cost_after, 2),\n        }\n        self._history.append(decision)\n        return decision\n\n    def daily_cost_report(self) -> Dict[str, Any]:\n        \"\"\"Summarize daily scaling behavior and costs.\"\"\"\n        if not self._history:\n            return {\"error\": \"no scaling history\"}\n\n        total_replica_hours = sum(\n            d[\"replicas_after\"] for d in self._history\n        )  # Approximation: 1 evaluation per hour\n        max_cost = (\n            self.config.max_replicas * self.config.cost_per_replica_hour * len(self._history)\n        )\n        actual_cost = total_replica_hours * self.config.cost_per_replica_hour\n        always_on_cost = (\n            self._history[0][\"replicas_after\"] * self.config.cost_per_replica_hour\n            * len(self._history)\n        ) if self._history else 0\n\n        peak_replicas = max(d[\"replicas_after\"] for d in self._history)\n        min_replicas = min(d[\"replicas_after\"] for d in self._history)\n\n        return {\n            \"evaluations\": len(self._history),\n            \"peak_replicas\": peak_replicas,\n            \"min_replicas\": min_replicas,\n            \"avg_replicas\": round(total_replica_hours \u002F len(self._history), 1),\n            \"actual_cost_usd\": round(actual_cost, 2),\n            \"max_capacity_cost_usd\": round(max_cost, 2),\n            \"savings_vs_max_usd\": round(max_cost - actual_cost, 2),\n            \"savings_vs_max_pct\": round(\n                (max_cost - actual_cost) \u002F max_cost * 100, 1\n            ) if max_cost > 0 else 0,\n            \"scale_up_events\": sum(1 for d in self._history if d[\"action\"] == \"scale_up\"),\n            \"scale_down_events\": sum(1 for d in self._history if d[\"action\"] == \"scale_down\"),\n        }\n\n\n# Simulate a 24-hour traffic pattern\nautoscaler = AgentAutoscaler(ScalingConfig(\n    min_replicas=2,\n    max_replicas=20,\n    target_utilization_pct=70,\n    cost_per_replica_hour=1.212,\n    requests_per_replica=10,\n    scale_up_cooldown_sec=0,    # Disable cooldown for simulation\n    scale_down_cooldown_sec=0,\n))\n\n# Typical business-hours traffic pattern (requests per minute)\nhourly_traffic = {\n    0: 3, 1: 2, 2: 2, 3: 2, 4: 3, 5: 5,\n    6: 15, 7: 40, 8: 80, 9: 120, 10: 150, 11: 140,\n    12: 100, 13: 130, 14: 145, 15: 135, 16: 110, 17: 70,\n    18: 30, 19: 15, 20: 10, 21: 8, 22: 5, 23: 4,\n}\n\n# Train the predictor\nfor hour, rpm in hourly_traffic.items():\n    autoscaler.record_traffic(hour, rpm)\n\n# Simulate\nfor hour in range(24):\n    rpm = hourly_traffic[hour]\n    decision = autoscaler.evaluate(\n        current_requests_per_minute=rpm,\n        avg_request_duration_sec=8.0,\n        current_hour=hour,\n    )\n    print(\n        f\"Hour {hour:2d}: {rpm:3.0f} rpm, \"\n        f\"{decision['action']:10s} -> {decision['replicas_after']:2d} replicas, \"\n        f\"${decision['hourly_cost_after']:.2f}\u002Fhr, \"\n        f\"util={decision['utilization_pct']:.0f}%\"\n    )\n\nreport = autoscaler.daily_cost_report()\nprint(f\"\\nDaily cost: ${report['actual_cost_usd']}\")\nprint(f\"Max capacity cost: ${report['max_capacity_cost_usd']}\")\nprint(f\"Savings: ${report['savings_vs_max_usd']} ({report['savings_vs_max_pct']}%)\")\n```\n\n### Cache Layer Optimization\n\nCaching is the highest-ROI infrastructure investment for agent fleets. A semantic cache that stores responses for similar (not identical) queries can achieve 20-40% hit rates on typical agent workloads, eliminating those inference calls entirely. The cost of the cache infrastructure is a fraction of the inference cost it displaces.\n\n```python\nimport hashlib\nimport json\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any, Tuple\n\n\n@dataclass\nclass CacheEntry:\n    \"\"\"A cached agent response.\"\"\"\n    key: str\n    response: str\n    embedding: List[float]        # For semantic similarity matching\n    cost_avoided_usd: float       # What this call would have cost\n    created_at: float\n    ttl_seconds: float\n    hit_count: int = 0\n    last_hit_at: float = 0.0\n\n\nclass AgentResponseCache:\n    \"\"\"Multi-tier cache for agent responses.\n\n    Tier 1: Exact match (hash-based, O(1) lookup).\n    Tier 2: Semantic similarity (embedding-based, approximate).\n\n    Exact match handles repeated identical queries (common in\n    automated pipelines). Semantic match handles paraphrased\n    queries from different users asking the same thing.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_entries: int = 10_000,\n        semantic_threshold: float = 0.92,\n        default_ttl_sec: float = 3600.0,\n    ):\n        self.max_entries = max_entries\n        self.semantic_threshold = semantic_threshold\n        self.default_ttl = default_ttl_sec\n        self._exact_cache: Dict[str, CacheEntry] = {}\n        self._semantic_entries: List[CacheEntry] = []\n        self._stats = {\n            \"exact_hits\": 0,\n            \"semantic_hits\": 0,\n            \"misses\": 0,\n            \"total_cost_avoided_usd\": 0.0,\n            \"evictions\": 0,\n        }\n\n    def _hash_key(self, query: str, context: str = \"\") -> str:\n        \"\"\"Create an exact-match cache key.\"\"\"\n        content = f\"{query}|{context}\"\n        return hashlib.sha256(content.encode()).hexdigest()\n\n    def _cosine_similarity(self, a: List[float], b: List[float]) -> float:\n        \"\"\"Compute cosine similarity between two embedding vectors.\"\"\"\n        dot = sum(x * y for x, y in zip(a, b))\n        norm_a = sum(x * x for x in a) ** 0.5\n        norm_b = sum(x * x for x in b) ** 0.5\n        if norm_a == 0 or norm_b == 0:\n            return 0.0\n        return dot \u002F (norm_a * norm_b)\n\n    def get(\n        self,\n        query: str,\n        context: str = \"\",\n        query_embedding: Optional[List[float]] = None,\n    ) -> Optional[Tuple[str, str]]:\n        \"\"\"Look up a cached response.\n\n        Returns (response, cache_tier) or None.\n        \"\"\"\n        now = time.time()\n\n        # Tier 1: Exact match\n        key = self._hash_key(query, context)\n        if key in self._exact_cache:\n            entry = self._exact_cache[key]\n            if now - entry.created_at \u003C entry.ttl_seconds:\n                entry.hit_count += 1\n                entry.last_hit_at = now\n                self._stats[\"exact_hits\"] += 1\n                self._stats[\"total_cost_avoided_usd\"] += entry.cost_avoided_usd\n                return entry.response, \"exact\"\n            else:\n                del self._exact_cache[key]\n\n        # Tier 2: Semantic match\n        if query_embedding:\n            best_match = None\n            best_score = 0.0\n            for entry in self._semantic_entries:\n                if now - entry.created_at >= entry.ttl_seconds:\n                    continue\n                score = self._cosine_similarity(query_embedding, entry.embedding)\n                if score > best_score and score >= self.semantic_threshold:\n                    best_score = score\n                    best_match = entry\n\n            if best_match:\n                best_match.hit_count += 1\n                best_match.last_hit_at = now\n                self._stats[\"semantic_hits\"] += 1\n                self._stats[\"total_cost_avoided_usd\"] += best_match.cost_avoided_usd\n                return best_match.response, \"semantic\"\n\n        self._stats[\"misses\"] += 1\n        return None\n\n    def put(\n        self,\n        query: str,\n        response: str,\n        cost_usd: float,\n        context: str = \"\",\n        embedding: Optional[List[float]] = None,\n        ttl_seconds: Optional[float] = None,\n    ):\n        \"\"\"Store a response in the cache.\"\"\"\n        now = time.time()\n        ttl = ttl_seconds or self.default_ttl\n        key = self._hash_key(query, context)\n\n        entry = CacheEntry(\n            key=key,\n            response=response,\n            embedding=embedding or [],\n            cost_avoided_usd=cost_usd,\n            created_at=now,\n            ttl_seconds=ttl,\n        )\n\n        # Store in exact cache\n        self._exact_cache[key] = entry\n\n        # Store in semantic cache if embedding provided\n        if embedding:\n            self._semantic_entries.append(entry)\n\n        # Evict if over capacity (LRU by last_hit_at)\n        self._evict_if_needed()\n\n    def _evict_if_needed(self):\n        \"\"\"Evict least-recently-used entries if over capacity.\"\"\"\n        while len(self._exact_cache) > self.max_entries:\n            oldest_key = min(\n                self._exact_cache,\n                key=lambda k: self._exact_cache[k].last_hit_at,\n            )\n            del self._exact_cache[oldest_key]\n            self._stats[\"evictions\"] += 1\n\n        while len(self._semantic_entries) > self.max_entries:\n            self._semantic_entries.sort(key=lambda e: e.last_hit_at)\n            self._semantic_entries.pop(0)\n            self._stats[\"evictions\"] += 1\n\n    def cost_report(self) -> Dict[str, Any]:\n        \"\"\"Report cache performance and cost savings.\"\"\"\n        total_lookups = (\n            self._stats[\"exact_hits\"]\n            + self._stats[\"semantic_hits\"]\n            + self._stats[\"misses\"]\n        )\n        hit_rate = (\n            (self._stats[\"exact_hits\"] + self._stats[\"semantic_hits\"])\n            \u002F total_lookups * 100\n        ) if total_lookups > 0 else 0\n\n        # Estimate cache infrastructure cost\n        # Redis\u002FElastiCache: ~$0.017\u002FGB\u002Fhour, assume 1GB for 10K entries\n        cache_infra_monthly = 0.017 * 24 * 30  # ~$12.24\u002Fmo for 1GB\n\n        return {\n            \"total_lookups\": total_lookups,\n            \"exact_hits\": self._stats[\"exact_hits\"],\n            \"semantic_hits\": self._stats[\"semantic_hits\"],\n            \"misses\": self._stats[\"misses\"],\n            \"hit_rate_pct\": round(hit_rate, 1),\n            \"total_cost_avoided_usd\": round(self._stats[\"total_cost_avoided_usd\"], 2),\n            \"cache_infra_monthly_usd\": round(cache_infra_monthly, 2),\n            \"net_savings_usd\": round(\n                self._stats[\"total_cost_avoided_usd\"] - cache_infra_monthly \u002F 30, 2\n            ),\n            \"cached_entries\": len(self._exact_cache),\n            \"evictions\": self._stats[\"evictions\"],\n        }\n\n\n# Simulate cache usage\ncache = AgentResponseCache(\n    max_entries=5000,\n    semantic_threshold=0.92,\n    default_ttl_sec=3600,\n)\n\n# Simulate 10,000 queries with 30% repetition rate\nrandom.seed(42)\nunique_queries = [f\"What is the status of order {i}?\" for i in range(700)]\nunique_queries += [f\"Explain the return policy for item {i}\" for i in range(300)]\n\nfor i in range(10000):\n    query = random.choice(unique_queries)\n    # Simple fake embedding: hash-based deterministic vector\n    embedding = [\n        float(int(hashlib.md5(f\"{query}_{d}\".encode()).hexdigest()[:4], 16)) \u002F 65535\n        for d in range(64)\n    ]\n\n    result = cache.get(query, query_embedding=embedding)\n    if result is None:\n        # Cache miss: \"call\" the LLM and cache the response\n        cache.put(\n            query=query,\n            response=f\"Response for: {query}\",\n            cost_usd=0.008,\n            embedding=embedding,\n        )\n\nreport = cache.cost_report()\nprint(f\"Hit rate: {report['hit_rate_pct']}%\")\nprint(f\"Cost avoided: ${report['total_cost_avoided_usd']}\")\nprint(f\"Cache infra cost: ${report['cache_infra_monthly_usd']}\u002Fmo\")\n```\n\n### Storage Tiering for Agent Memory\n\nAgent memory -- conversation history, tool call results, learned preferences, and vector embeddings -- grows monotonically and never self-prunes. A single long-running agent conversation can accumulate 200,000+ tokens of history. Multiply by thousands of concurrent conversations, and storage costs become material. The solution is tiered storage that moves data between cost tiers based on access patterns.\n\n| Storage Tier | Cost ($\u002FGB\u002Fmonth) | Access Latency | Use Case |\n|---|---|---|---|\n| In-memory (Redis) | $12.24 | \u003C 1ms | Active conversation context, hot cache |\n| SSD (EBS gp3) | $0.08 | 1-5ms | Recent conversation history (\u003C 24hr) |\n| Object storage (S3) | $0.023 | 50-100ms | Archived conversations, audit logs |\n| Cold archive (S3 Glacier) | $0.004 | 3-5 hours | Compliance retention, training data |\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass StorageTier:\n    name: str\n    cost_per_gb_month: float\n    access_latency_ms: float\n    max_access_latency_ms: float\n\n\n@dataclass\nclass MemoryObject:\n    \"\"\"A piece of agent memory (conversation, embedding, etc.).\"\"\"\n    object_id: str\n    agent_id: str\n    size_bytes: int\n    created_at: float\n    last_accessed_at: float\n    access_count: int = 0\n    current_tier: str = \"hot\"\n\n\nclass StorageTierManager:\n    \"\"\"Manages automatic tiering of agent memory across storage tiers.\n\n    Implements time-based and access-based policies to move data\n    from expensive, fast tiers to cheap, slow tiers as it ages.\n    \"\"\"\n\n    TIERS = {\n        \"hot\": StorageTier(\"hot\", 12.24, 0.5, 1.0),\n        \"warm\": StorageTier(\"warm\", 0.08, 3.0, 5.0),\n        \"cold\": StorageTier(\"cold\", 0.023, 75.0, 100.0),\n        \"archive\": StorageTier(\"archive\", 0.004, 18_000_000.0, 18_000_000.0),\n    }\n\n    # Tier transition rules (seconds since last access)\n    TIER_RULES = {\n        \"hot\": {\"max_idle_sec\": 3600, \"demote_to\": \"warm\"},          # 1 hour\n        \"warm\": {\"max_idle_sec\": 86400, \"demote_to\": \"cold\"},        # 24 hours\n        \"cold\": {\"max_idle_sec\": 2592000, \"demote_to\": \"archive\"},   # 30 days\n    }\n\n    def __init__(self):\n        self._objects: Dict[str, MemoryObject] = {}\n        self._tier_sizes: Dict[str, int] = {tier: 0 for tier in self.TIERS}\n        self._transitions: List[Dict[str, Any]] = []\n\n    def store(self, obj: MemoryObject):\n        \"\"\"Store a new memory object in the hot tier.\"\"\"\n        self._objects[obj.object_id] = obj\n        self._tier_sizes[obj.current_tier] += obj.size_bytes\n\n    def access(self, object_id: str) -> Optional[MemoryObject]:\n        \"\"\"Access a memory object. Promotes to hot tier if needed.\"\"\"\n        obj = self._objects.get(object_id)\n        if obj is None:\n            return None\n\n        obj.last_accessed_at = time.time()\n        obj.access_count += 1\n\n        # Promote to hot if accessed from a lower tier\n        if obj.current_tier != \"hot\":\n            self._transition(obj, \"hot\")\n\n        return obj\n\n    def run_tiering(self):\n        \"\"\"Evaluate all objects and demote idle ones to lower tiers.\"\"\"\n        now = time.time()\n        for obj in list(self._objects.values()):\n            rule = self.TIER_RULES.get(obj.current_tier)\n            if rule is None:\n                continue  # Archive tier has no demotion\n\n            idle_seconds = now - obj.last_accessed_at\n            if idle_seconds > rule[\"max_idle_sec\"]:\n                self._transition(obj, rule[\"demote_to\"])\n\n    def _transition(self, obj: MemoryObject, new_tier: str):\n        \"\"\"Move an object between tiers.\"\"\"\n        old_tier = obj.current_tier\n        self._tier_sizes[old_tier] -= obj.size_bytes\n        self._tier_sizes[new_tier] += obj.size_bytes\n        obj.current_tier = new_tier\n\n        self._transitions.append({\n            \"object_id\": obj.object_id,\n            \"from_tier\": old_tier,\n            \"to_tier\": new_tier,\n            \"size_bytes\": obj.size_bytes,\n        })\n\n    def cost_report(self) -> Dict[str, Any]:\n        \"\"\"Calculate monthly storage costs by tier.\"\"\"\n        tier_costs = {}\n        total_cost = 0.0\n        total_bytes = 0\n\n        for tier_name, tier in self.TIERS.items():\n            size_gb = self._tier_sizes[tier_name] \u002F (1024 ** 3)\n            cost = size_gb * tier.cost_per_gb_month\n            tier_costs[tier_name] = {\n                \"size_gb\": round(size_gb, 4),\n                \"monthly_cost_usd\": round(cost, 4),\n                \"object_count\": sum(\n                    1 for o in self._objects.values() if o.current_tier == tier_name\n                ),\n            }\n            total_cost += cost\n            total_bytes += self._tier_sizes[tier_name]\n\n        # Calculate what it would cost if everything were in hot tier\n        all_hot_cost = (total_bytes \u002F (1024 ** 3)) * self.TIERS[\"hot\"].cost_per_gb_month\n\n        return {\n            \"total_size_gb\": round(total_bytes \u002F (1024 ** 3), 4),\n            \"total_monthly_cost_usd\": round(total_cost, 4),\n            \"all_hot_cost_usd\": round(all_hot_cost, 4),\n            \"savings_usd\": round(all_hot_cost - total_cost, 4),\n            \"savings_pct\": round(\n                (all_hot_cost - total_cost) \u002F all_hot_cost * 100, 1\n            ) if all_hot_cost > 0 else 0,\n            \"tiers\": tier_costs,\n            \"total_transitions\": len(self._transitions),\n        }\n\n\n# Simulate 30 days of agent memory accumulation and tiering\nmanager = StorageTierManager()\n\nnow = time.time()\nrandom.seed(42)\n\n# Create 5000 conversation memory objects over 30 days\nfor i in range(5000):\n    days_ago = random.uniform(0, 30)\n    created = now - (days_ago * 86400)\n    # More recent objects are more likely to be accessed recently\n    last_access_offset = random.expovariate(1.0 \u002F (days_ago * 86400 + 3600))\n    last_accessed = min(now, created + last_access_offset)\n\n    obj = MemoryObject(\n        object_id=f\"conv_{i:05d}\",\n        agent_id=f\"agent_{i % 12:02d}\",\n        size_bytes=random.randint(50_000, 500_000),  # 50KB-500KB per conversation\n        created_at=created,\n        last_accessed_at=last_accessed,\n        access_count=random.randint(1, 50),\n        current_tier=\"hot\",\n    )\n    manager.store(obj)\n\n# Run tiering\nmanager.run_tiering()\n\nreport = manager.cost_report()\nprint(f\"Total storage: {report['total_size_gb']:.2f} GB\")\nprint(f\"Tiered cost: ${report['total_monthly_cost_usd']:.2f}\u002Fmo\")\nprint(f\"All-hot cost: ${report['all_hot_cost_usd']:.2f}\u002Fmo\")\nprint(f\"Savings: ${report['savings_usd']:.2f}\u002Fmo ({report['savings_pct']}%)\")\nfor tier, data in report[\"tiers\"].items():\n    print(f\"  {tier:8s}: {data['object_count']:5d} objects, \"\n          f\"{data['size_gb']:.3f} GB, ${data['monthly_cost_usd']:.4f}\u002Fmo\")\n```\n\n### Network Cost Reduction\n\nNetwork egress is the silent cost killer in distributed agent architectures. Every API call to an LLM provider sends tokens out and receives tokens back. Every inter-service call between agents in a pipeline crosses a network boundary. At AWS's standard egress rate of $0.09\u002FGB, a fleet sending 50GB\u002Fmonth of prompt data to external APIs pays $4.50 in egress alone -- modest. But add inter-service traffic between agents, observability data shipped to external collectors, and embedding vectors transferred between services, and network costs can reach $200-500\u002Fmonth for a medium fleet.\n\nThree strategies reduce network costs significantly. First, co-locate communicating services. Agents that frequently call each other should run in the same availability zone ($0.00\u002FGB intra-AZ vs $0.01\u002FGB inter-AZ). Second, compress payloads. gzip compression reduces JSON payloads by 70-85%, and agent payloads (mostly text) compress extremely well. Third, use regional endpoints. If your agents serve global users but call a single LLM API region, deploy regional proxy caches that batch and deduplicate requests before forwarding to the provider.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any\n\n\n@dataclass\nclass NetworkCostModel:\n    \"\"\"Models network costs for an agent fleet.\"\"\"\n    egress_per_gb: float = 0.09           # AWS standard\n    inter_az_per_gb: float = 0.01\n    intra_az_per_gb: float = 0.00\n    compression_ratio: float = 0.20       # Compressed size as fraction of original\n\n    def monthly_cost(\n        self,\n        api_calls_per_day: int,\n        avg_payload_kb: float,\n        inter_service_calls_per_day: int,\n        inter_service_payload_kb: float,\n        observability_gb_per_day: float,\n        cross_az_pct: float = 0.30,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate monthly network costs with and without optimization.\"\"\"\n        days = 30\n\n        # API egress (uncompressed)\n        api_gb = api_calls_per_day * avg_payload_kb \u002F (1024 * 1024) * days\n        api_cost = api_gb * self.egress_per_gb\n\n        # Inter-service traffic\n        inter_gb = (\n            inter_service_calls_per_day * inter_service_payload_kb\n            \u002F (1024 * 1024) * days\n        )\n        inter_cost = (\n            inter_gb * cross_az_pct * self.inter_az_per_gb\n            + inter_gb * (1 - cross_az_pct) * self.intra_az_per_gb\n        )\n\n        # Observability egress\n        obs_gb = observability_gb_per_day * days\n        obs_cost = obs_gb * self.egress_per_gb\n\n        total_unoptimized = api_cost + inter_cost + obs_cost\n\n        # Optimized: compression + co-location\n        api_cost_opt = api_gb * self.compression_ratio * self.egress_per_gb\n        inter_cost_opt = inter_gb * 0.05 * self.inter_az_per_gb  # 95% co-located\n        obs_cost_opt = obs_gb * self.compression_ratio * self.egress_per_gb\n\n        total_optimized = api_cost_opt + inter_cost_opt + obs_cost_opt\n\n        return {\n            \"unoptimized\": {\n                \"api_egress_usd\": round(api_cost, 2),\n                \"inter_service_usd\": round(inter_cost, 2),\n                \"observability_usd\": round(obs_cost, 2),\n                \"total_usd\": round(total_unoptimized, 2),\n            },\n            \"optimized\": {\n                \"api_egress_usd\": round(api_cost_opt, 2),\n                \"inter_service_usd\": round(inter_cost_opt, 2),\n                \"observability_usd\": round(obs_cost_opt, 2),\n                \"total_usd\": round(total_optimized, 2),\n            },\n            \"savings_usd\": round(total_unoptimized - total_optimized, 2),\n            \"savings_pct\": round(\n                (total_unoptimized - total_optimized) \u002F total_unoptimized * 100, 1\n            ) if total_unoptimized > 0 else 0,\n        }\n\n\n# Example: medium-sized agent fleet\nnetwork = NetworkCostModel()\nresult = network.monthly_cost(\n    api_calls_per_day=50_000,\n    avg_payload_kb=12.0,\n    inter_service_calls_per_day=200_000,\n    inter_service_payload_kb=4.0,\n    observability_gb_per_day=2.5,\n    cross_az_pct=0.30,\n)\nprint(f\"Unoptimized: ${result['unoptimized']['total_usd']}\u002Fmo\")\nprint(f\"Optimized:   ${result['optimized']['total_usd']}\u002Fmo\")\nprint(f\"Savings:     ${result['savings_usd']}\u002Fmo ({result['savings_pct']}%)\")\n```\n\n---\n\n## Chapter 8: Cost Optimization Playbook\n\n### The Eight-Week Plan\n\nThe strategies in Chapters 1-7 are individually powerful but collectively overwhelming. This chapter turns them into a sequenced execution plan. The order is deliberate: early weeks focus on measurement and quick wins that fund later investments. Later weeks tackle structural changes that deliver compounding returns. Each week has a defined owner, deliverable, and expected savings.\n\n**Baseline assumptions.** This playbook is calibrated for a team running 8-15 agents in production with a monthly AI infrastructure bill of $8,000-25,000. If your bill is smaller, the absolute savings shrink but the percentages hold. If your bill is larger, the savings are proportionally bigger and the ROI on engineering time is even higher.\n\n| Week | Focus Area | Owner | Expected Savings | Cumulative Savings |\n|---|---|---|---|---|\n| 1 | Instrumentation and cost visibility | Platform engineer | 0% (measurement) | 0% |\n| 2 | Prompt compression and system prompt optimization | ML engineer | 8-12% | 8-12% |\n| 3 | Model routing (tiered model assignment) | ML engineer | 15-25% | 23-37% |\n| 4 | Observability cost control | Platform engineer | 5-10% | 28-47% |\n| 5 | Caching layer deployment | Backend engineer | 8-15% | 36-62% |\n| 6 | Batch processing for async workloads | Backend engineer | 5-10% | 41-72% |\n| 7 | Infrastructure right-sizing and autoscaling | DevOps engineer | 5-12% | 46-84% |\n| 8 | Outcome-based metering and governance framework | Engineering manager | 3-5% (+ ongoing gains) | 49-89% |\n\n### Week 1: Instrumentation and Cost Visibility\n\nYou cannot optimize what you cannot see. Week 1 deploys the `CostTracker` from Chapter 1 across every agent in production. Every LLM call, tool invocation, and storage operation gets a cost tag. By end of week, you have a dashboard showing cost-per-agent, cost-per-operation, and cost-per-category breakdown.\n\n**Deliverables:**\n- CostTracker integrated into all agent entry points\n- Daily cost report emailed to engineering and finance\n- Top-5 cost drivers identified with specific dollar amounts\n\n**Common findings from Week 1 instrumentation:**\n- One agent consuming 40-60% of total budget (the \"cost hog\")\n- System prompt bloat adding $500-2,000\u002Fmonth in unnecessary tokens\n- Retry storms on a single flaky tool doubling that agent's cost\n- Observability costs 15-30% of inference costs\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass WeeklyTarget:\n    \"\"\"A single week's optimization target.\"\"\"\n    week: int\n    focus: str\n    owner: str\n    tasks: List[str]\n    expected_savings_pct_low: float\n    expected_savings_pct_high: float\n    dependencies: List[int] = field(default_factory=list)\n    completed: bool = False\n    actual_savings_pct: float = 0.0\n\n\nclass OptimizationPlaybook:\n    \"\"\"Manages an 8-week cost optimization program.\n\n    Tracks progress, calculates cumulative savings, and generates\n    executive reports showing ROI on engineering investment.\n    \"\"\"\n\n    def __init__(self, monthly_baseline_usd: float):\n        self.baseline = monthly_baseline_usd\n        self.weeks: List[WeeklyTarget] = self._build_plan()\n        self._weekly_spend: Dict[int, float] = {}\n\n    def _build_plan(self) -> List[WeeklyTarget]:\n        return [\n            WeeklyTarget(\n                week=1,\n                focus=\"Instrumentation and cost visibility\",\n                owner=\"Platform engineer\",\n                tasks=[\n                    \"Deploy CostTracker to all agents\",\n                    \"Set up daily cost report pipeline\",\n                    \"Identify top-5 cost drivers\",\n                    \"Baseline cost-per-agent metrics\",\n                ],\n                expected_savings_pct_low=0,\n                expected_savings_pct_high=0,\n            ),\n            WeeklyTarget(\n                week=2,\n                focus=\"Prompt compression and optimization\",\n                owner=\"ML engineer\",\n                tasks=[\n                    \"Audit all system prompts with TokenWasteAnalyzer\",\n                    \"Compress top-3 highest-cost prompts\",\n                    \"Remove redundant few-shot examples\",\n                    \"Optimize tool descriptions\",\n                    \"A\u002FB test compressed vs original prompts\",\n                ],\n                expected_savings_pct_low=8,\n                expected_savings_pct_high=12,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=3,\n                focus=\"Model routing\",\n                owner=\"ML engineer\",\n                tasks=[\n                    \"Classify all agent tasks by complexity tier\",\n                    \"Deploy ModelRouter with conservative routing rules\",\n                    \"Route SIMPLE tasks to cheap models (GPT-4o-mini\u002FHaiku)\",\n                    \"Monitor quality metrics for routed tasks\",\n                    \"Expand routing to MODERATE tasks if quality holds\",\n                ],\n                expected_savings_pct_low=15,\n                expected_savings_pct_high=25,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=4,\n                focus=\"Observability cost control\",\n                owner=\"Platform engineer\",\n                tasks=[\n                    \"Deploy AdaptiveSampler for trace sampling\",\n                    \"Implement metric cardinality limits\",\n                    \"Switch to structured logging with level optimization\",\n                    \"Separate AI telemetry from infra telemetry\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=10,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=5,\n                focus=\"Caching layer deployment\",\n                owner=\"Backend engineer\",\n                tasks=[\n                    \"Deploy AgentResponseCache with exact matching\",\n                    \"Add semantic similarity matching\",\n                    \"Tune cache TTL based on content type\",\n                    \"Monitor hit rates and quality of cached responses\",\n                ],\n                expected_savings_pct_low=8,\n                expected_savings_pct_high=15,\n                dependencies=[1, 2],\n            ),\n            WeeklyTarget(\n                week=6,\n                focus=\"Batch processing for async workloads\",\n                owner=\"Backend engineer\",\n                tasks=[\n                    \"Identify tasks tolerant of >5 minute latency\",\n                    \"Deploy WorkloadScheduler with micro-batch queues\",\n                    \"Migrate nightly\u002Fweekly report generation to batch API\",\n                    \"Set up batch job monitoring\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=10,\n                dependencies=[1],\n            ),\n            WeeklyTarget(\n                week=7,\n                focus=\"Infrastructure right-sizing and autoscaling\",\n                owner=\"DevOps engineer\",\n                tasks=[\n                    \"Analyze GPU utilization and right-size instances\",\n                    \"Deploy AgentAutoscaler with predictive scaling\",\n                    \"Implement storage tiering for agent memory\",\n                    \"Optimize network costs (co-location, compression)\",\n                ],\n                expected_savings_pct_low=5,\n                expected_savings_pct_high=12,\n                dependencies=[1, 6],\n            ),\n            WeeklyTarget(\n                week=8,\n                focus=\"Outcome metering and governance\",\n                owner=\"Engineering manager\",\n                tasks=[\n                    \"Deploy OutcomeMeter for cost-per-success tracking\",\n                    \"Define quality gates for each agent\",\n                    \"Set up cost governance alerts and budgets\",\n                    \"Establish monthly cost review cadence\",\n                    \"Create executive cost report template\",\n                ],\n                expected_savings_pct_low=3,\n                expected_savings_pct_high=5,\n                dependencies=[1, 2, 3],\n            ),\n        ]\n\n    def record_week(self, week: int, actual_spend_usd: float, savings_pct: float):\n        \"\"\"Record actual results for a completed week.\"\"\"\n        self._weekly_spend[week] = actual_spend_usd\n        target = self.weeks[week - 1]\n        target.completed = True\n        target.actual_savings_pct = savings_pct\n\n    def progress_report(self) -> Dict[str, Any]:\n        \"\"\"Generate a progress report across all weeks.\"\"\"\n        completed = [w for w in self.weeks if w.completed]\n        cumulative_savings_pct = sum(w.actual_savings_pct for w in completed)\n        monthly_savings_usd = self.baseline * cumulative_savings_pct \u002F 100\n        projected_annual_savings = monthly_savings_usd * 12\n\n        return {\n            \"baseline_monthly_usd\": self.baseline,\n            \"weeks_completed\": len(completed),\n            \"weeks_remaining\": len(self.weeks) - len(completed),\n            \"cumulative_savings_pct\": round(cumulative_savings_pct, 1),\n            \"monthly_savings_usd\": round(monthly_savings_usd, 2),\n            \"projected_annual_savings_usd\": round(projected_annual_savings, 2),\n            \"current_monthly_spend_usd\": round(\n                self.baseline - monthly_savings_usd, 2\n            ),\n            \"week_details\": [\n                {\n                    \"week\": w.week,\n                    \"focus\": w.focus,\n                    \"status\": \"completed\" if w.completed else \"pending\",\n                    \"actual_savings_pct\": w.actual_savings_pct if w.completed else None,\n                    \"expected_range\": f\"{w.expected_savings_pct_low}-{w.expected_savings_pct_high}%\",\n                }\n                for w in self.weeks\n            ],\n        }\n\n    def roi_calculation(\n        self,\n        engineer_hours_per_week: float = 30.0,\n        engineer_hourly_rate: float = 95.0,\n    ) -> Dict[str, Any]:\n        \"\"\"Calculate ROI of the optimization program.\n\n        Compares engineering investment against realized savings.\n        Assumes savings compound monthly (each month benefits from\n        all previous optimizations).\n        \"\"\"\n        completed = [w for w in self.weeks if w.completed]\n        total_eng_hours = len(completed) * engineer_hours_per_week\n        total_eng_cost = total_eng_hours * engineer_hourly_rate\n\n        # Monthly savings grow as each week's optimization is deployed\n        total_savings_12mo = 0.0\n        cumulative_pct = 0.0\n        for w in self.weeks:\n            if w.completed:\n                cumulative_pct += w.actual_savings_pct\n            monthly_saving = self.baseline * cumulative_pct \u002F 100\n            # This week's savings apply for (12 - week_number) months\n            remaining_months = max(0, 12 - w.week + 1)\n            total_savings_12mo += monthly_saving * (remaining_months \u002F 12)\n\n        annual_savings = total_savings_12mo * 12 \u002F max(1, len(self.weeks))\n        roi = ((annual_savings - total_eng_cost) \u002F total_eng_cost * 100) if total_eng_cost > 0 else 0\n\n        return {\n            \"engineering_investment\": {\n                \"total_hours\": total_eng_hours,\n                \"hourly_rate_usd\": engineer_hourly_rate,\n                \"total_cost_usd\": round(total_eng_cost, 2),\n            },\n            \"savings\": {\n                \"monthly_recurring_usd\": round(\n                    self.baseline * cumulative_pct \u002F 100, 2\n                ),\n                \"projected_annual_usd\": round(annual_savings, 2),\n            },\n            \"roi_pct\": round(roi, 1),\n            \"payback_period_weeks\": round(\n                total_eng_cost \u002F (self.baseline * cumulative_pct \u002F 100 \u002F 4.33), 1\n            ) if cumulative_pct > 0 else float(\"inf\"),\n        }\n\n\n# Example: Run the playbook for a $15,000\u002Fmonth fleet\nplaybook = OptimizationPlaybook(monthly_baseline_usd=15_000)\n\n# Simulate completing all 8 weeks with realistic savings\nactual_results = [\n    (1, 15000, 0),     # Week 1: measurement only\n    (2, 13650, 9),     # Week 2: prompt compression saved 9%\n    (3, 10920, 18),    # Week 3: model routing saved 18%\n    (4, 9828, 7),      # Week 4: observability saved 7%\n    (5, 8356, 10),     # Week 5: caching saved 10%\n    (6, 7521, 6),      # Week 6: batch processing saved 6%\n    (7, 6394, 8),      # Week 7: infrastructure saved 8%\n    (8, 6074, 2),      # Week 8: governance saved 2%\n]\n\nfor week, spend, savings in actual_results:\n    playbook.record_week(week, spend, savings)\n\nreport = playbook.progress_report()\nprint(f\"Baseline: ${report['baseline_monthly_usd']:,.0f}\u002Fmo\")\nprint(f\"Current:  ${report['current_monthly_spend_usd']:,.0f}\u002Fmo\")\nprint(f\"Savings:  {report['cumulative_savings_pct']}% \"\n      f\"(${report['monthly_savings_usd']:,.0f}\u002Fmo)\")\nprint(f\"Annual:   ${report['projected_annual_savings_usd']:,.0f}\")\n\nroi = playbook.roi_calculation(engineer_hours_per_week=30, engineer_hourly_rate=95)\nprint(f\"\\nEngineering investment: ${roi['engineering_investment']['total_cost_usd']:,.0f}\")\nprint(f\"Annual savings: ${roi['savings']['projected_annual_usd']:,.0f}\")\nprint(f\"ROI: {roi['roi_pct']}%\")\nprint(f\"Payback period: {roi['payback_period_weeks']} weeks\")\n```\n\n### Quick Wins vs Long-Term Investments\n\nNot all optimizations have the same effort-to-impact ratio. The following matrix categorizes every strategy from this cookbook by implementation effort and expected savings magnitude. Start with the upper-left quadrant (low effort, high impact) and work toward the lower-right.\n\n| Strategy | Effort (days) | Monthly Savings | Payback Period | Category |\n|---|---|---|---|---|\n| Prompt compression | 1-2 | 8-12% | Immediate | Quick win |\n| Tool description compression | 0.5-1 | 2-4% | Immediate | Quick win |\n| Batch API for async tasks | 1-2 | 5-10% | Immediate | Quick win |\n| Response format optimization | 0.5-1 | 2-5% | Immediate | Quick win |\n| Model routing (simple tasks) | 3-5 | 15-25% | 1-2 weeks | High-impact investment |\n| Semantic caching | 5-8 | 8-15% | 2-3 weeks | High-impact investment |\n| Adaptive trace sampling | 2-3 | 5-10% | 1 week | High-impact investment |\n| Autoscaling (predictive) | 5-10 | 5-12% | 3-4 weeks | Long-term investment |\n| Self-hosted inference | 10-20 | 20-50% | 4-8 weeks | Long-term investment |\n| Storage tiering | 3-5 | 2-5% | 2-3 weeks | Long-term investment |\n| Outcome-based metering | 5-8 | 3-5% ongoing | 3-4 weeks | Strategic investment |\n| Full cost governance framework | 8-15 | 5-10% ongoing | 6-8 weeks | Strategic investment |\n\n```python\nfrom dataclasses import dataclass\nfrom typing import List, Dict, Any\n\n\n@dataclass\nclass OptimizationStrategy:\n    \"\"\"A single cost optimization strategy with effort and impact.\"\"\"\n    name: str\n    effort_days_low: float\n    effort_days_high: float\n    savings_pct_low: float\n    savings_pct_high: float\n    category: str  # quick_win, high_impact, long_term, strategic\n    chapter: int\n    recurring: bool = False  # True if savings compound over time\n\n\nclass OptimizationPrioritizer:\n    \"\"\"Prioritizes optimization strategies by ROI.\n\n    Ranks strategies by savings-per-engineering-day, helping teams\n    decide what to tackle first given limited engineering bandwidth.\n    \"\"\"\n\n    STRATEGIES = [\n        OptimizationStrategy(\"Prompt compression\", 1, 2, 8, 12, \"quick_win\", 5),\n        OptimizationStrategy(\"Tool description compression\", 0.5, 1, 2, 4, \"quick_win\", 5),\n        OptimizationStrategy(\"Batch API for async tasks\", 1, 2, 5, 10, \"quick_win\", 7),\n        OptimizationStrategy(\"Response format optimization\", 0.5, 1, 2, 5, \"quick_win\", 5),\n        OptimizationStrategy(\"Model routing\", 3, 5, 15, 25, \"high_impact\", 3),\n        OptimizationStrategy(\"Semantic caching\", 5, 8, 8, 15, \"high_impact\", 7),\n        OptimizationStrategy(\"Adaptive trace sampling\", 2, 3, 5, 10, \"high_impact\", 4),\n        OptimizationStrategy(\"Predictive autoscaling\", 5, 10, 5, 12, \"long_term\", 7),\n        OptimizationStrategy(\"Self-hosted inference\", 10, 20, 20, 50, \"long_term\", 7),\n        OptimizationStrategy(\"Storage tiering\", 3, 5, 2, 5, \"long_term\", 7),\n        OptimizationStrategy(\"Outcome-based metering\", 5, 8, 3, 5, \"strategic\", 6, True),\n        OptimizationStrategy(\"Cost governance framework\", 8, 15, 5, 10, \"strategic\", 8, True),\n    ]\n\n    def __init__(self, monthly_spend_usd: float, engineer_daily_rate: float = 760.0):\n        self.monthly_spend = monthly_spend_usd\n        self.daily_rate = engineer_daily_rate  # $95\u002Fhr * 8hr\n\n    def prioritize(self) -> List[Dict[str, Any]]:\n        \"\"\"Rank strategies by ROI (savings per engineering dollar).\"\"\"\n        ranked = []\n        for s in self.STRATEGIES:\n            avg_effort = (s.effort_days_low + s.effort_days_high) \u002F 2\n            avg_savings_pct = (s.savings_pct_low + s.savings_pct_high) \u002F 2\n            monthly_savings = self.monthly_spend * avg_savings_pct \u002F 100\n            annual_savings = monthly_savings * 12\n            eng_cost = avg_effort * self.daily_rate\n\n            roi = ((annual_savings - eng_cost) \u002F eng_cost * 100) if eng_cost > 0 else 0\n            savings_per_eng_day = monthly_savings \u002F avg_effort if avg_effort > 0 else 0\n\n            ranked.append({\n                \"strategy\": s.name,\n                \"category\": s.category,\n                \"chapter\": s.chapter,\n                \"effort_days\": f\"{s.effort_days_low}-{s.effort_days_high}\",\n                \"savings_pct\": f\"{s.savings_pct_low}-{s.savings_pct_high}%\",\n                \"monthly_savings_usd\": round(monthly_savings, 2),\n                \"annual_savings_usd\": round(annual_savings, 2),\n                \"engineering_cost_usd\": round(eng_cost, 2),\n                \"roi_pct\": round(roi, 1),\n                \"savings_per_eng_day_usd\": round(savings_per_eng_day, 2),\n            })\n\n        ranked.sort(key=lambda r: r[\"savings_per_eng_day_usd\"], reverse=True)\n        return ranked\n\n    def print_priority_report(self):\n        \"\"\"Print a formatted priority report.\"\"\"\n        ranked = self.prioritize()\n        print(f\"{'Strategy':\u003C35} {'Effort':>8} {'Savings\u002Fmo':>12} \"\n              f\"{'Eng Cost':>10} {'ROI':>8} {'$\u002Feng-day':>10}\")\n        print(\"-\" * 85)\n        for r in ranked:\n            print(f\"{r['strategy']:\u003C35} {r['effort_days']:>8} \"\n                  f\"${r['monthly_savings_usd']:>10,.0f} \"\n                  f\"${r['engineering_cost_usd']:>8,.0f} \"\n                  f\"{r['roi_pct']:>7.0f}% \"\n                  f\"${r['savings_per_eng_day_usd']:>8,.0f}\")\n\n\n# Example: Prioritize for a $15,000\u002Fmonth fleet\nprioritizer = OptimizationPrioritizer(monthly_spend_usd=15_000)\nprioritizer.print_priority_report()\n```\n\n### Monitoring Dashboard Design\n\nSustained optimization requires continuous monitoring. A single dashboard with four panels gives your team real-time visibility into cost health.\n\n**Panel 1: Cost Burn Rate.** A time-series chart showing hourly cost across all agents, stacked by category (inference, tools, observability, storage, orchestration). The burn rate line should have an overlay showing the budget line -- if the burn rate consistently exceeds budget, an alert fires.\n\n**Panel 2: Cost Per Outcome.** A time-series showing cost-per-successful-outcome for each agent. This is the single most important metric. If cost-per-outcome rises while total cost stays flat, your agents are getting less efficient. If cost-per-outcome drops while total cost rises, you are scaling efficiently.\n\n**Panel 3: Model Router Performance.** A breakdown showing which model handles what percentage of requests, cost per model tier, and quality scores per tier. A stacked bar chart with SIMPLE\u002FMODERATE\u002FCOMPLEX\u002FCRITICAL tiers lets you see if routing is working.\n\n**Panel 4: Waste Tracker.** A gauge showing three waste metrics: token waste percentage (from TokenWasteAnalyzer), failure waste (cost of failed outcomes), and retry waste (cost of retries that eventually succeeded). Each gauge should have a target zone (green), warning zone (yellow), and critical zone (red).\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass DashboardMetric:\n    \"\"\"A single metric for the cost monitoring dashboard.\"\"\"\n    name: str\n    value: float\n    unit: str\n    threshold_warning: float\n    threshold_critical: float\n    trend: str = \"stable\"  # improving, degrading, stable\n\n\nclass CostDashboard:\n    \"\"\"Generates cost monitoring dashboard data.\n\n    Produces structured data suitable for rendering in Grafana,\n    Datadog, or any dashboard tool that accepts JSON metrics.\n    \"\"\"\n\n    def __init__(self, monthly_budget_usd: float):\n        self.budget = monthly_budget_usd\n        self._hourly_costs: List[Dict[str, float]] = []\n        self._outcome_costs: List[Dict[str, float]] = []\n\n    def record_hourly_snapshot(\n        self,\n        inference_usd: float,\n        tools_usd: float,\n        observability_usd: float,\n        storage_usd: float,\n        orchestration_usd: float,\n    ):\n        \"\"\"Record an hourly cost snapshot.\"\"\"\n        self._hourly_costs.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"inference\": inference_usd,\n            \"tools\": tools_usd,\n            \"observability\": observability_usd,\n            \"storage\": storage_usd,\n            \"orchestration\": orchestration_usd,\n            \"total\": (\n                inference_usd + tools_usd + observability_usd\n                + storage_usd + orchestration_usd\n            ),\n        })\n\n    def record_outcome_snapshot(\n        self,\n        agent_id: str,\n        cost_per_success: float,\n        success_rate: float,\n        quality_score: float,\n    ):\n        self._outcome_costs.append({\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"agent_id\": agent_id,\n            \"cost_per_success\": cost_per_success,\n            \"success_rate\": success_rate,\n            \"quality_score\": quality_score,\n        })\n\n    def generate_panels(self) -> Dict[str, Any]:\n        \"\"\"Generate dashboard panel data.\"\"\"\n        panels = {}\n\n        # Panel 1: Burn rate\n        if self._hourly_costs:\n            recent = self._hourly_costs[-24:]  # Last 24 hours\n            daily_total = sum(h[\"total\"] for h in recent)\n            hourly_budget = self.budget \u002F 30 \u002F 24\n            daily_budget = self.budget \u002F 30\n\n            panels[\"burn_rate\"] = {\n                \"daily_spend_usd\": round(daily_total, 2),\n                \"daily_budget_usd\": round(daily_budget, 2),\n                \"burn_rate_pct\": round(daily_total \u002F daily_budget * 100, 1) if daily_budget > 0 else 0,\n                \"projected_monthly_usd\": round(daily_total * 30, 2),\n                \"over_budget\": daily_total > daily_budget * 1.1,\n                \"breakdown\": {\n                    cat: round(sum(h[cat] for h in recent), 2)\n                    for cat in [\"inference\", \"tools\", \"observability\", \"storage\", \"orchestration\"]\n                },\n            }\n\n        # Panel 2: Cost per outcome\n        if self._outcome_costs:\n            by_agent: Dict[str, list] = {}\n            for o in self._outcome_costs:\n                by_agent.setdefault(o[\"agent_id\"], []).append(o)\n\n            panels[\"cost_per_outcome\"] = {\n                agent: {\n                    \"avg_cost_per_success\": round(\n                        sum(o[\"cost_per_success\"] for o in entries) \u002F len(entries), 4\n                    ),\n                    \"avg_success_rate\": round(\n                        sum(o[\"success_rate\"] for o in entries) \u002F len(entries), 3\n                    ),\n                    \"avg_quality\": round(\n                        sum(o[\"quality_score\"] for o in entries) \u002F len(entries), 3\n                    ),\n                    \"data_points\": len(entries),\n                }\n                for agent, entries in by_agent.items()\n            }\n\n        # Panel 4: Waste metrics\n        panels[\"waste_tracker\"] = self._compute_waste_metrics()\n\n        return panels\n\n    def _compute_waste_metrics(self) -> Dict[str, DashboardMetric]:\n        \"\"\"Compute waste metrics for the waste tracker panel.\"\"\"\n        metrics = {}\n\n        if self._hourly_costs:\n            recent = self._hourly_costs[-24:]\n            total = sum(h[\"total\"] for h in recent)\n            obs = sum(h[\"observability\"] for h in recent)\n            obs_pct = (obs \u002F total * 100) if total > 0 else 0\n\n            metrics[\"observability_overhead\"] = {\n                \"value\": round(obs_pct, 1),\n                \"unit\": \"%\",\n                \"status\": (\n                    \"critical\" if obs_pct > 25\n                    else \"warning\" if obs_pct > 15\n                    else \"healthy\"\n                ),\n            }\n\n        if self._outcome_costs:\n            failed = [o for o in self._outcome_costs if o[\"success_rate\"] \u003C 0.5]\n            failure_rate = len(failed) \u002F len(self._outcome_costs) * 100\n\n            metrics[\"failure_waste\"] = {\n                \"value\": round(failure_rate, 1),\n                \"unit\": \"%\",\n                \"status\": (\n                    \"critical\" if failure_rate > 20\n                    else \"warning\" if failure_rate > 10\n                    else \"healthy\"\n                ),\n            }\n\n        return metrics\n\n    def executive_summary(self) -> str:\n        \"\"\"Generate an executive-level cost summary as formatted text.\"\"\"\n        panels = self.generate_panels()\n        lines = []\n        lines.append(\"=\" * 60)\n        lines.append(\"AI AGENT COST OPTIMIZATION - EXECUTIVE SUMMARY\")\n        lines.append(\"=\" * 60)\n\n        if \"burn_rate\" in panels:\n            br = panels[\"burn_rate\"]\n            lines.append(f\"\\nMonthly Budget:     ${self.budget:>12,.2f}\")\n            lines.append(f\"Projected Spend:    ${br['projected_monthly_usd']:>12,.2f}\")\n            variance = br[\"projected_monthly_usd\"] - self.budget\n            status = \"OVER BUDGET\" if variance > 0 else \"UNDER BUDGET\"\n            lines.append(f\"Variance:           ${abs(variance):>12,.2f} ({status})\")\n            lines.append(f\"\\nDaily Breakdown:\")\n            for cat, val in br[\"breakdown\"].items():\n                pct = val \u002F br[\"daily_spend_usd\"] * 100 if br[\"daily_spend_usd\"] > 0 else 0\n                lines.append(f\"  {cat:\u003C20s} ${val:>8,.2f}  ({pct:>5.1f}%)\")\n\n        if \"cost_per_outcome\" in panels:\n            lines.append(f\"\\nAgent Efficiency:\")\n            for agent, data in panels[\"cost_per_outcome\"].items():\n                lines.append(\n                    f\"  {agent:\u003C20s} ${data['avg_cost_per_success']:.4f}\u002Fsuccess  \"\n                    f\"rate={data['avg_success_rate']:.1%}  \"\n                    f\"quality={data['avg_quality']:.2f}\"\n                )\n\n        lines.append(\"\\n\" + \"=\" * 60)\n        return \"\\n\".join(lines)\n\n\n# Example: Generate dashboard data\ndashboard = CostDashboard(monthly_budget_usd=15_000)\n\n# Simulate 24 hours of data\nimport random\nrandom.seed(42)\nfor hour in range(24):\n    # Cost varies by time of day (higher during business hours)\n    multiplier = 2.5 if 8 \u003C= hour \u003C= 17 else 0.5\n    dashboard.record_hourly_snapshot(\n        inference_usd=random.gauss(12.0, 3.0) * multiplier,\n        tools_usd=random.gauss(3.0, 1.0) * multiplier,\n        observability_usd=random.gauss(2.5, 0.8) * multiplier,\n        storage_usd=random.gauss(0.8, 0.2),\n        orchestration_usd=random.gauss(1.5, 0.5) * multiplier,\n    )\n\n# Simulate outcome data for 3 agents\nfor agent in [\"researcher-01\", \"classifier-02\", \"support-03\"]:\n    for _ in range(50):\n        dashboard.record_outcome_snapshot(\n            agent_id=agent,\n            cost_per_success=random.gauss(0.05, 0.02),\n            success_rate=random.gauss(0.85, 0.08),\n            quality_score=random.gauss(0.82, 0.10),\n        )\n\nprint(dashboard.executive_summary())\n```\n\n### Team Roles and Responsibilities\n\nCost optimization is not a one-person job. It requires sustained attention from four roles, each owning a specific piece of the cost stack.\n\n**Platform Engineer** owns instrumentation, observability cost control, and the cost tracking infrastructure. They deploy and maintain the CostTracker, AdaptiveSampler, and cost dashboards. They are the first responder when cost alerts fire. Weekly time commitment: 4-6 hours after initial setup.\n\n**ML Engineer** owns prompt optimization, model routing, and quality measurement. They run the TokenWasteAnalyzer against production prompts, configure the ModelRouter, and monitor quality metrics to ensure cost cuts do not degrade output. Weekly time commitment: 6-8 hours during active optimization, 2-3 hours for maintenance.\n\n**Backend Engineer** owns caching, batch processing, and the application-layer infrastructure. They deploy and tune the AgentResponseCache, configure the WorkloadScheduler, and optimize inter-service communication. Weekly time commitment: 4-6 hours during deployment, 1-2 hours for maintenance.\n\n**Engineering Manager** owns the governance framework, executive reporting, and cross-team coordination. They run the weekly cost review, maintain the optimization backlog, and present the executive summary to leadership. Weekly time commitment: 3-4 hours.\n\n### Cost Governance Framework\n\nWithout governance, optimizations decay. New agents get deployed without cost budgets. Prompts creep back to verbose defaults. Model routing gets bypassed for \"just this one urgent task.\" A governance framework prevents regression.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Any, Optional\nfrom enum import Enum\n\n\nclass AlertSeverity(Enum):\n    INFO = \"info\"\n    WARNING = \"warning\"\n    CRITICAL = \"critical\"\n\n\n@dataclass\nclass CostBudget:\n    \"\"\"Cost budget for a single agent or team.\"\"\"\n    agent_id: str\n    monthly_budget_usd: float\n    daily_budget_usd: float = 0.0\n    alert_at_pct: float = 80.0       # Alert when spend reaches this % of budget\n    hard_limit_pct: float = 120.0    # Hard stop when spend reaches this %\n    owner: str = \"\"\n\n    def __post_init__(self):\n        if self.daily_budget_usd == 0:\n            self.daily_budget_usd = self.monthly_budget_usd \u002F 30\n\n\n@dataclass\nclass CostAlert:\n    \"\"\"A cost alert event.\"\"\"\n    agent_id: str\n    severity: AlertSeverity\n    message: str\n    current_spend_usd: float\n    budget_usd: float\n    spend_pct: float\n\n\nclass CostGovernor:\n    \"\"\"Enforces cost budgets and policies across the agent fleet.\n\n    Provides real-time budget monitoring, automatic alerts, and\n    hard spending limits that can throttle or stop agents that\n    exceed their allocated budget.\n    \"\"\"\n\n    def __init__(self):\n        self._budgets: Dict[str, CostBudget] = {}\n        self._spend: Dict[str, float] = {}       # Current period spend\n        self._alerts: List[CostAlert] = []\n        self._throttled: set = set()\n        self._policies: Dict[str, Any] = {\n            \"require_cost_estimate_for_new_agents\": True,\n            \"max_cost_per_single_request_usd\": 1.00,\n            \"require_model_routing\": True,\n            \"require_prompt_review_above_tokens\": 5000,\n            \"monthly_fleet_budget_usd\": 25000.0,\n        }\n\n    def set_budget(self, budget: CostBudget):\n        \"\"\"Set or update a cost budget for an agent.\"\"\"\n        self._budgets[budget.agent_id] = budget\n        if budget.agent_id not in self._spend:\n            self._spend[budget.agent_id] = 0.0\n\n    def record_spend(self, agent_id: str, amount_usd: float) -> Optional[CostAlert]:\n        \"\"\"Record spending and check against budget.\n\n        Returns a CostAlert if a threshold is crossed, or None.\n        Automatically throttles agents that exceed hard limits.\n        \"\"\"\n        self._spend[agent_id] = self._spend.get(agent_id, 0.0) + amount_usd\n\n        budget = self._budgets.get(agent_id)\n        if budget is None:\n            return None\n\n        spend_pct = self._spend[agent_id] \u002F budget.daily_budget_usd * 100\n\n        alert = None\n        if spend_pct >= budget.hard_limit_pct:\n            self._throttled.add(agent_id)\n            alert = CostAlert(\n                agent_id=agent_id,\n                severity=AlertSeverity.CRITICAL,\n                message=f\"Agent {agent_id} THROTTLED: spend at {spend_pct:.0f}% of daily budget\",\n                current_spend_usd=round(self._spend[agent_id], 4),\n                budget_usd=budget.daily_budget_usd,\n                spend_pct=round(spend_pct, 1),\n            )\n        elif spend_pct >= budget.alert_at_pct:\n            alert = CostAlert(\n                agent_id=agent_id,\n                severity=AlertSeverity.WARNING,\n                message=f\"Agent {agent_id}: spend at {spend_pct:.0f}% of daily budget\",\n                current_spend_usd=round(self._spend[agent_id], 4),\n                budget_usd=budget.daily_budget_usd,\n                spend_pct=round(spend_pct, 1),\n            )\n\n        if alert:\n            self._alerts.append(alert)\n        return alert\n\n    def is_allowed(self, agent_id: str, estimated_cost_usd: float) -> Dict[str, Any]:\n        \"\"\"Check if an agent request should be allowed.\n\n        Returns allow\u002Fdeny decision with reason. Used as a\n        pre-request gate to prevent budget overruns.\n        \"\"\"\n        if agent_id in self._throttled:\n            return {\n                \"allowed\": False,\n                \"reason\": \"agent_throttled\",\n                \"message\": f\"Agent {agent_id} is throttled due to budget overrun\",\n            }\n\n        if estimated_cost_usd > self._policies[\"max_cost_per_single_request_usd\"]:\n            return {\n                \"allowed\": False,\n                \"reason\": \"request_too_expensive\",\n                \"message\": (\n                    f\"Estimated cost ${estimated_cost_usd:.4f} exceeds \"\n                    f\"max ${self._policies['max_cost_per_single_request_usd']:.2f}\"\n                ),\n            }\n\n        budget = self._budgets.get(agent_id)\n        if budget:\n            projected = self._spend.get(agent_id, 0) + estimated_cost_usd\n            if projected > budget.daily_budget_usd * budget.hard_limit_pct \u002F 100:\n                return {\n                    \"allowed\": False,\n                    \"reason\": \"would_exceed_budget\",\n                    \"message\": (\n                        f\"Request would push spend to \"\n                        f\"${projected:.2f} against daily budget \"\n                        f\"${budget.daily_budget_usd:.2f}\"\n                    ),\n                }\n\n        return {\"allowed\": True, \"reason\": \"within_budget\"}\n\n    def fleet_status(self) -> Dict[str, Any]:\n        \"\"\"Generate a fleet-wide budget status report.\"\"\"\n        total_budget = sum(b.daily_budget_usd for b in self._budgets.values())\n        total_spend = sum(self._spend.values())\n\n        agent_status = {}\n        for agent_id, budget in self._budgets.items():\n            spend = self._spend.get(agent_id, 0)\n            pct = (spend \u002F budget.daily_budget_usd * 100) if budget.daily_budget_usd > 0 else 0\n            agent_status[agent_id] = {\n                \"budget_usd\": round(budget.daily_budget_usd, 2),\n                \"spend_usd\": round(spend, 4),\n                \"spend_pct\": round(pct, 1),\n                \"status\": (\n                    \"throttled\" if agent_id in self._throttled\n                    else \"critical\" if pct >= budget.hard_limit_pct\n                    else \"warning\" if pct >= budget.alert_at_pct\n                    else \"healthy\"\n                ),\n                \"owner\": budget.owner,\n            }\n\n        return {\n            \"fleet_daily_budget_usd\": round(total_budget, 2),\n            \"fleet_daily_spend_usd\": round(total_spend, 2),\n            \"fleet_spend_pct\": round(\n                total_spend \u002F total_budget * 100, 1\n            ) if total_budget > 0 else 0,\n            \"agents_throttled\": len(self._throttled),\n            \"alerts_fired\": len(self._alerts),\n            \"agents\": agent_status,\n        }\n\n    def reset_daily(self):\n        \"\"\"Reset daily spend counters. Call at midnight.\"\"\"\n        self._spend = {agent_id: 0.0 for agent_id in self._budgets}\n        self._throttled.clear()\n\n\n# Example: Set up governance for a 4-agent fleet\ngovernor = CostGovernor()\n\ngovernor.set_budget(CostBudget(\n    agent_id=\"researcher-01\",\n    monthly_budget_usd=4500,\n    owner=\"ML Team\",\n    alert_at_pct=80,\n    hard_limit_pct=120,\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"classifier-02\",\n    monthly_budget_usd=2000,\n    owner=\"Data Team\",\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"support-03\",\n    monthly_budget_usd=6000,\n    owner=\"CX Team\",\n))\ngovernor.set_budget(CostBudget(\n    agent_id=\"writer-04\",\n    monthly_budget_usd=2500,\n    owner=\"Content Team\",\n))\n\n# Simulate a day of spending\nrandom.seed(42)\nfor _ in range(500):\n    agent = random.choice([\"researcher-01\", \"classifier-02\", \"support-03\", \"writer-04\"])\n    cost = random.gauss(0.05, 0.03)\n    cost = max(0.001, cost)\n\n    # Check permission before processing\n    permission = governor.is_allowed(agent, cost)\n    if permission[\"allowed\"]:\n        alert = governor.record_spend(agent, cost)\n        if alert:\n            print(f\"ALERT [{alert.severity.value}]: {alert.message}\")\n    else:\n        pass  # Request denied -- queue for later or use cheaper model\n\nstatus = governor.fleet_status()\nprint(f\"\\nFleet budget: ${status['fleet_daily_budget_usd']}\u002Fday\")\nprint(f\"Fleet spend:  ${status['fleet_daily_spend_usd']:.2f}\u002Fday\")\nprint(f\"Throttled:    {status['agents_throttled']} agents\")\nfor agent, data in status[\"agents\"].items():\n    print(f\"  {agent:\u003C20s} ${data['spend_usd']:>7.2f} \u002F ${data['budget_usd']:>7.2f} \"\n          f\"({data['spend_pct']:>5.1f}%) [{data['status']}]\")\n```\n\n### Executive Reporting Template\n\nFinance and leadership do not care about tokens, spans, or cache hit rates. They care about three things: how much are we spending, is it within budget, and what is the return on investment. The executive report translates technical metrics into business language.\n\nThe report should be generated weekly and cover four sections: (1) total spend versus budget with trend line, (2) cost-per-successful-outcome by business function, (3) optimization program progress and realized savings, and (4) forecast for the next quarter. Keep it to one page. Use dollar amounts, not percentages, as the primary metric -- executives respond to \"we saved $4,200 this month\" more than \"we reduced token waste by 18%.\"\n\n```python\nclass ExecutiveReport:\n    \"\"\"Generates a one-page executive cost report.\n\n    Translates technical cost metrics into business-friendly\n    language suitable for C-suite and finance review.\n    \"\"\"\n\n    def __init__(\n        self,\n        monthly_budget_usd: float,\n        baseline_monthly_usd: float,\n    ):\n        self.budget = monthly_budget_usd\n        self.baseline = baseline_monthly_usd\n\n    def generate(\n        self,\n        actual_spend_usd: float,\n        cost_per_outcome: Dict[str, float],\n        optimization_savings_usd: float,\n        weeks_completed: int,\n        forecast_next_quarter_usd: float,\n    ) -> str:\n        \"\"\"Generate the executive report as formatted text.\"\"\"\n        variance = actual_spend_usd - self.budget\n        variance_pct = variance \u002F self.budget * 100 if self.budget > 0 else 0\n        savings_from_baseline = self.baseline - actual_spend_usd\n        savings_pct = savings_from_baseline \u002F self.baseline * 100 if self.baseline > 0 else 0\n\n        lines = []\n        lines.append(\"=\" * 65)\n        lines.append(\"     AI AGENT INFRASTRUCTURE - MONTHLY COST REPORT\")\n        lines.append(\"=\" * 65)\n\n        # Section 1: Spend vs Budget\n        lines.append(\"\\n1. SPEND vs BUDGET\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Monthly Budget:        ${self.budget:>12,.2f}\")\n        lines.append(f\"   Actual Spend:          ${actual_spend_usd:>12,.2f}\")\n        lines.append(f\"   Variance:              ${abs(variance):>12,.2f} \"\n                     f\"{'OVER' if variance > 0 else 'UNDER'}\")\n        lines.append(f\"   Pre-Optimization Base: ${self.baseline:>12,.2f}\")\n        lines.append(f\"   Realized Savings:      ${savings_from_baseline:>12,.2f} \"\n                     f\"({savings_pct:.0f}%)\")\n\n        # Section 2: Cost Per Outcome\n        lines.append(\"\\n2. COST PER SUCCESSFUL OUTCOME BY FUNCTION\")\n        lines.append(\"-\" * 40)\n        for function, cost in cost_per_outcome.items():\n            lines.append(f\"   {function:\u003C30s} ${cost:>8.4f}\")\n\n        # Section 3: Optimization Progress\n        lines.append(\"\\n3. OPTIMIZATION PROGRAM STATUS\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Program Week:          {weeks_completed} of 8\")\n        lines.append(f\"   Cumulative Savings:    ${optimization_savings_usd:>12,.2f}\u002Fmo\")\n        lines.append(f\"   Annualized Savings:    ${optimization_savings_usd * 12:>12,.2f}\")\n        lines.append(f\"   Progress:              \"\n                     f\"[{'#' * weeks_completed}{'.' * (8 - weeks_completed)}]\")\n\n        # Section 4: Forecast\n        lines.append(\"\\n4. NEXT QUARTER FORECAST\")\n        lines.append(\"-\" * 40)\n        lines.append(f\"   Projected Q Spend:     ${forecast_next_quarter_usd:>12,.2f}\")\n        lines.append(f\"   Q Budget (3x monthly): ${self.budget * 3:>12,.2f}\")\n        q_variance = forecast_next_quarter_usd - self.budget * 3\n        lines.append(f\"   Projected Q Variance:  ${abs(q_variance):>12,.2f} \"\n                     f\"{'OVER' if q_variance > 0 else 'UNDER'}\")\n\n        lines.append(\"\\n\" + \"=\" * 65)\n        return \"\\n\".join(lines)\n\n\n# Generate the report\nreport_gen = ExecutiveReport(\n    monthly_budget_usd=15_000,\n    baseline_monthly_usd=22_000,\n)\n\nreport_text = report_gen.generate(\n    actual_spend_usd=9_200,\n    cost_per_outcome={\n        \"Research Reports\": 0.0832,\n        \"Document Classification\": 0.0041,\n        \"Customer Support\": 0.0156,\n        \"Content Generation\": 0.0287,\n    },\n    optimization_savings_usd=12_800,\n    weeks_completed=8,\n    forecast_next_quarter_usd=26_400,\n)\n\nprint(report_text)\n```\n\n### Putting It All Together\n\nThe strategies in this cookbook are not theoretical. They are battle-tested patterns deployed by teams running AI agents at scale. The numbers are real: 60% cost reduction is achievable by any team willing to invest eight weeks of focused effort. Some teams achieve more -- the Fortune 100 firm from the introduction reduced their $89,000\u002Fmonth bill to $31,000\u002Fmonth in six weeks using the exact strategies documented here.\n\nThe key insight is that agent cost optimization is not a one-time project. It is a discipline. Models change pricing. New models enter the market. Agent workloads shift. Prompts drift. The governance framework in this chapter -- budgets, alerts, reviews, executive reporting -- ensures that optimizations stick and that new waste is caught before it compounds.\n\nStart with Chapter 1. Instrument everything. Then follow the playbook. Week by week, your agent fleet becomes leaner, smarter, and more cost-effective. The 60% target is not a ceiling -- it is a floor.\n\n---\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33,34],"cost-optimization","finops","observability","metering","model-routing","agent-operations","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42],"WALLET_ADDRESS",29,[42],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-cost-optimization",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-cost-optimization",{"tool":62,"command":63},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-cost-optimization",{"tool":65,"command":66},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-cost-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-cost-optimization\u002FSKILL.md",true,[],[71,78,85,92,99,106],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]