[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HBZPD4Q5GZKWEB1AS76G2":3,"skill-same:01M77HBZPD4Q5GZKWEB1AS76G2":69},{"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":43,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HBZPD4Q5GZKWEB1AS76G2","greenhelix-agent-finops-playbook",null,"The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems. Complete guide to cost governance for multi-agent systems: per-agent wallets, budget caps, spend alerts via webhooks, cost attribution, volume discounts, fleet dashboards, and API key isolation. Includes detailed Python code examples with full API integration.","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-finops-playbook\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-finops-playbook\nversion: \"1.3.1\"\ndescription: \"The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems. Complete guide to cost governance for multi-agent systems: per-agent wallets, budget caps, spend alerts via webhooks, cost attribution, volume discounts, fleet dashboards, and API key isolation. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [finops, billing, budgets, webhooks, cost-management, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems\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> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nWhen a CrewAI orchestrator spawns five researcher agents, each calling GPT-4o at $0.005 per request, and one agent enters a retry loop that fires 12,000 requests in an hour, who gets the bill? When a LangGraph workflow fans out to eight parallel tool-calling agents across three cloud providers, how does the platform team attribute $2,400 in daily compute back to the workflow that caused it? When a production AutoGen group chat quietly doubles its tool-call volume over three weeks because a prompt change removed a termination condition, who notices before the monthly invoice arrives? These are not hypothetical problems. A March 2026 postmortem from an AI infrastructure startup revealed that a single misconfigured agent loop consumed $47,000 in API credits over a weekend -- with no alert, no budget cap, and no way to attribute the cost to a specific agent. The FinOps Foundation's \"FinOps for AI\" initiative, launched in January 2026, identified cost governance for autonomous agents as one of the top three unsolved problems in AI infrastructure economics. This guide solves it. Using the GreenHelix A2A Commerce Gateway's 23 billing and webhook tools, you will build a complete FinOps control plane: per-agent wallets with hard budget caps, real-time spend alerts, cost attribution by agent and workflow, volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary. Every pattern is production-ready, backed by working Python code, and deployable today.\nBefore diving into the full guide, here is the minimum viable FinOps setup: one agent, one wallet, one budget cap, one alert. This takes under two minutes.\n```python\n\n## What You'll Learn\n- Quick Start\n- Chapter 1: The Multi-Agent Cost Problem\n- Chapter 2: Per-Agent Wallet Provisioning\n- Chapter 3: Budget Caps and Hard Stops\n- Chapter 4: Real-Time Spend Alerts with Webhooks\n- Chapter 5: Cost Attribution and Category Spend\n- Chapter 6: Volume Discounts and Cost Optimization\n- Chapter 7: Fleet Dashboards and Leaderboards\n- Chapter 8: API Key Isolation and Security\n- Chapter 9: Putting It All Together: The FinOps Control Plane\n\n## Full Guide\n\n# The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems\n\nWhen a CrewAI orchestrator spawns five researcher agents, each calling GPT-4o at $0.005 per request, and one agent enters a retry loop that fires 12,000 requests in an hour, who gets the bill? When a LangGraph workflow fans out to eight parallel tool-calling agents across three cloud providers, how does the platform team attribute $2,400 in daily compute back to the workflow that caused it? When a production AutoGen group chat quietly doubles its tool-call volume over three weeks because a prompt change removed a termination condition, who notices before the monthly invoice arrives? These are not hypothetical problems. A March 2026 postmortem from an AI infrastructure startup revealed that a single misconfigured agent loop consumed $47,000 in API credits over a weekend -- with no alert, no budget cap, and no way to attribute the cost to a specific agent. The FinOps Foundation's \"FinOps for AI\" initiative, launched in January 2026, identified cost governance for autonomous agents as one of the top three unsolved problems in AI infrastructure economics. This guide solves it. Using the GreenHelix A2A Commerce Gateway's 23 billing and webhook tools, you will build a complete FinOps control plane: per-agent wallets with hard budget caps, real-time spend alerts, cost attribution by agent and workflow, volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary. Every pattern is production-ready, backed by working Python code, and deployable today.\n\n---\n\n## Quick Start\n\nBefore diving into the full guide, here is the minimum viable FinOps setup: one agent, one wallet, one budget cap, one alert. This takes under two minutes.\n\n```python\nfrom greenhelix_trading import AgentFinOps\nimport os\n\n# Initialize the FinOps client for a single agent\nfinops = AgentFinOps(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"research-agent-01\",\n    base_url=\"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n)\n\n# 1. Create an isolated wallet\nfinops.create_wallet()\n\n# 2. Fund it\nfinops.deposit(amount=100.00)\n\n# 3. Set a hard daily budget cap\nfinops.set_budget_cap(daily_limit=25.00, monthly_limit=500.00)\n\n# 4. Register an alert at 75% spend\nfinops.register_webhook(\n    url=\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fbudget\",\n    events=[\"budget.threshold\"],\n    config={\"threshold_pct\": 75},\n)\n\n# 5. Check balance before any operation\nbalance = finops.get_balance()\nprint(f\"Agent research-agent-01 ready. Balance: ${balance['balance']}\")\n```\n\nThat is five API calls. Your agent now has an isolated wallet, a $25\u002Fday hard stop, and an alert that fires when 75% of the daily budget is consumed. The rest of this guide builds on this foundation.\n\n---\n\n## Table of Contents\n\n1. [The Multi-Agent Cost Problem](#chapter-1-the-multi-agent-cost-problem)\n2. [Per-Agent Wallet Provisioning](#chapter-2-per-agent-wallet-provisioning)\n3. [Budget Caps and Hard Stops](#chapter-3-budget-caps-and-hard-stops)\n4. [Real-Time Spend Alerts with Webhooks](#chapter-4-real-time-spend-alerts-with-webhooks)\n5. [Cost Attribution and Category Spend](#chapter-5-cost-attribution-and-category-spend)\n6. [Volume Discounts and Cost Optimization](#chapter-6-volume-discounts-and-cost-optimization)\n7. [Fleet Dashboards and Leaderboards](#chapter-7-fleet-dashboards-and-leaderboards)\n8. [API Key Isolation and Security](#chapter-8-api-key-isolation-and-security)\n9. [Putting It All Together: The FinOps Control Plane](#chapter-9-putting-it-all-together-the-finops-control-plane)\n10. [What to Do Next](#chapter-10-what-to-do-next)\n\n---\n\n## Chapter 1: The Multi-Agent Cost Problem\n\n### Why Autonomous Agents Create Unbounded Cost\n\nHuman engineers have an implicit cost governor: they get tired, they context-switch, they go home at 6 PM. Agents do not. A LangChain agent with access to a tool catalog will call tools as long as its reasoning loop tells it to. A CrewAI crew that delegates subtasks to specialist agents will spawn as many subtasks as the orchestrator deems necessary. An AutoGen group chat will continue conversing until a termination condition is met -- and if that condition has a bug, the conversation runs forever. Each tool call, each LLM inference, each API request costs money. Without explicit cost governance, the spend trajectory of a multi-agent system is bounded only by the rate limit of the underlying API provider.\n\n### Three Failure Modes\n\nEvery multi-agent cost incident traces back to one of three root causes.\n\n**Failure Mode 1: Runaway Loops.** An agent enters a retry or reasoning loop that never terminates. The most common trigger is a tool that returns an error, causing the agent to retry indefinitely. A single agent in a retry loop against GPT-4o can consume $50-200\u002Fhour depending on context window size. Without a per-agent budget cap, there is no circuit breaker.\n\n**Failure Mode 2: Tool-Call Amplification.** An orchestrator agent delegates a task to N worker agents, each of which calls M tools, each of which triggers K downstream API calls. The total cost is O(N * M * K), and small changes to any multiplier produce large cost swings. A prompt change that causes each worker to call one additional tool per task can double fleet-wide spend overnight.\n\n**Failure Mode 3: No Attribution.** All agents share a single API key and a single billing account. When the monthly bill spikes, there is no way to determine which agent, which workflow, or which tool category caused the increase. Without attribution, there is no accountability, and without accountability, there is no optimization.\n\n### The Wallet-Per-Agent Architecture\n\nThe GreenHelix approach solves all three failure modes with a single architectural pattern: every agent gets its own wallet with its own budget cap. This is the same principle as giving each microservice its own database -- isolation prevents blast radius propagation.\n\n```\n+-------------------+     +-------------------+     +-------------------+\n| Agent: researcher |     | Agent: summarizer |     | Agent: classifier |\n| Wallet: $100      |     | Wallet: $50       |     | Wallet: $75       |\n| Cap: $25\u002Fday      |     | Cap: $15\u002Fday      |     | Cap: $20\u002Fday      |\n| Key: ak_res_xxxxx |     | Key: ak_sum_xxxxx |     | Key: ak_cls_xxxxx |\n+--------+----------+     +--------+----------+     +--------+----------+\n         |                         |                         |\n         +------------+------------+------------+------------+\n                      |                         |\n              +-------v-------------------------v-------+\n              |     GreenHelix A2A Commerce Gateway      |\n              |     Budget enforcement layer             |\n              |     Cost attribution engine              |\n              |     Webhook alert system                 |\n              +------------------------------------------+\n```\n\nWhen the researcher agent hits its $25\u002Fday cap, it gets a `402 Payment Required` response. The summarizer and classifier agents are unaffected. The blast radius of a runaway researcher is exactly $25 -- not the entire fleet budget.\n\n### The AgentFinOps Class\n\nThis class wraps every GreenHelix billing and webhook tool used in this guide. Define it once; reference it in every subsequent chapter.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional\n\n\nclass AgentFinOps:\n    \"\"\"FinOps client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 23 billing and webhook tools into a clean interface\n    for budget enforcement, cost allocation, and spend analytics.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} has exceeded its budget cap. \"\n                f\"Response: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Wallet Management -------------------------------------------\n\n    def create_wallet(self) -> dict:\n        return self._execute(\"create_wallet\", {})\n\n    def get_balance(self) -> dict:\n        return self._execute(\"get_balance\", {})\n\n    def deposit(self, amount: float) -> dict:\n        return self._execute(\"deposit\", {\"amount\": str(amount)})\n\n    # -- Budget Enforcement ------------------------------------------\n\n    def set_budget_cap(\n        self,\n        daily_limit: float,\n        monthly_limit: Optional[float] = None,\n    ) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": str(daily_limit),\n        }\n        if monthly_limit is not None:\n            payload[\"monthly_limit\"] = str(monthly_limit)\n        return self._execute(\"set_budget_cap\", payload)\n\n    def get_budget_status(self) -> dict:\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    # -- Cost Analytics ----------------------------------------------\n\n    def get_usage_analytics(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        return self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"start_date\": start_date,\n            \"end_date\": end_date,\n        })\n\n    def get_billing_summary(self, period: str = \"monthly\") -> dict:\n        return self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def get_spending_by_category(\n        self,\n        start_date: Optional[str] = None,\n        end_date: Optional[str] = None,\n    ) -> dict:\n        payload = {\"agent_id\": self.agent_id}\n        if start_date:\n            payload[\"start_date\"] = start_date\n        if end_date:\n            payload[\"end_date\"] = end_date\n        return self._execute(\"get_spending_by_category\", payload)\n\n    # -- Cost Optimization -------------------------------------------\n\n    def get_volume_discount(self) -> dict:\n        return self._execute(\"get_volume_discount\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def estimate_cost(self, tool_name: str, parameters: dict) -> dict:\n        return self._execute(\"estimate_cost\", {\n            \"tool\": tool_name,\n            \"parameters\": parameters,\n        })\n\n    def convert_currency(\n        self,\n        amount: float,\n        from_currency: str,\n        to_currency: str,\n    ) -> dict:\n        return self._execute(\"convert_currency\", {\n            \"amount\": str(amount),\n            \"from_currency\": from_currency,\n            \"to_currency\": to_currency,\n        })\n\n    # -- Fleet Analytics ---------------------------------------------\n\n    def get_agent_leaderboard(self, metric: str = \"cost_efficiency\") -> dict:\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def get_platform_stats(self) -> dict:\n        return self._execute(\"get_platform_stats\", {})\n\n    # -- API Key Management ------------------------------------------\n\n    def create_api_key(self, label: str, permissions: list = None) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"label\": label,\n        }\n        if permissions:\n            payload[\"permissions\"] = permissions\n        return self._execute(\"create_api_key\", payload)\n\n    def rotate_api_key(self, key_id: str) -> dict:\n        return self._execute(\"rotate_api_key\", {\n            \"agent_id\": self.agent_id,\n            \"key_id\": key_id,\n        })\n\n    # -- Webhooks ----------------------------------------------------\n\n    def register_webhook(\n        self,\n        url: str,\n        events: list,\n        config: Optional[dict] = None,\n    ) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"url\": url,\n            \"events\": events,\n        }\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"register_webhook\", payload)\n\n    def list_webhooks(self) -> dict:\n        return self._execute(\"list_webhooks\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def update_webhook(\n        self,\n        webhook_id: str,\n        url: Optional[str] = None,\n        events: Optional[list] = None,\n        config: Optional[dict] = None,\n    ) -> dict:\n        payload = {\"webhook_id\": webhook_id}\n        if url:\n            payload[\"url\"] = url\n        if events:\n            payload[\"events\"] = events\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"update_webhook\", payload)\n\n    def delete_webhook(self, webhook_id: str) -> dict:\n        return self._execute(\"delete_webhook\", {\n            \"webhook_id\": webhook_id,\n        })\n\n    def get_webhook_logs(\n        self,\n        webhook_id: str,\n        limit: int = 50,\n    ) -> dict:\n        return self._execute(\"get_webhook_logs\", {\n            \"webhook_id\": webhook_id,\n            \"limit\": limit,\n        })\n\n\nclass BudgetExhaustedError(Exception):\n    \"\"\"Raised when an agent exceeds its budget cap (HTTP 402).\"\"\"\n    pass\n```\n\n---\n\n## Chapter 2: Per-Agent Wallet Provisioning\n\n### Why One Wallet Per Agent\n\nShared wallets are the multi-agent equivalent of running all your microservices as root. When five agents share a wallet, a runaway agent drains funds that other agents need. There is no spend attribution, no blast radius containment, and no way to set different budget policies for agents with different risk profiles.\n\nThe rule is simple: every agent that can incur cost gets its own wallet. The orchestrator agent gets a wallet. Each worker agent gets a wallet. If the orchestrator funds worker wallets as part of task delegation, the funding amount becomes an explicit cost parameter of the task -- visible, auditable, and capped.\n\n### Creating Wallets for a Fleet\n\n```python\nimport os\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\n\n# Define your agent fleet\nfleet = [\n    {\"agent_id\": \"orchestrator-01\", \"initial_deposit\": 500.00},\n    {\"agent_id\": \"researcher-01\",   \"initial_deposit\": 100.00},\n    {\"agent_id\": \"researcher-02\",   \"initial_deposit\": 100.00},\n    {\"agent_id\": \"summarizer-01\",   \"initial_deposit\": 75.00},\n    {\"agent_id\": \"classifier-01\",   \"initial_deposit\": 50.00},\n]\n\nfor agent_cfg in fleet:\n    finops = AgentFinOps(\n        api_key=API_KEY,\n        agent_id=agent_cfg[\"agent_id\"],\n    )\n\n    # Create wallet\n    wallet = finops.create_wallet()\n    print(f\"Wallet created for {agent_cfg['agent_id']}: {wallet['wallet_id']}\")\n\n    # Fund it\n    deposit = finops.deposit(amount=agent_cfg[\"initial_deposit\"])\n    print(f\"  Deposited ${agent_cfg['initial_deposit']:.2f}\")\n\n    # Verify balance\n    balance = finops.get_balance()\n    print(f\"  Balance: ${balance['balance']}\")\n```\n\n### Pre-Flight Cost Estimation\n\nBefore an agent executes an expensive tool call, estimate the cost and compare it against the remaining budget. This prevents the agent from starting work it cannot afford to finish.\n\n```python\ndef preflight_check(finops: AgentFinOps, tool_name: str, params: dict) -> bool:\n    \"\"\"Check if the agent can afford a tool call before executing it.\"\"\"\n    # Estimate the cost of the upcoming operation\n    estimate = finops.estimate_cost(tool_name=tool_name, parameters=params)\n    estimated_cost = float(estimate.get(\"estimated_cost\", 0))\n\n    # Check remaining budget\n    budget = finops.get_budget_status()\n    remaining_daily = (\n        float(budget.get(\"daily_limit\", 0))\n        - float(budget.get(\"spent_today\", 0))\n    )\n\n    # Check wallet balance\n    balance = finops.get_balance()\n    wallet_balance = float(balance.get(\"balance\", 0))\n\n    # Both budget and balance must be sufficient\n    can_afford = (\n        estimated_cost \u003C= remaining_daily\n        and estimated_cost \u003C= wallet_balance\n    )\n\n    if not can_afford:\n        print(\n            f\"Pre-flight FAIL: {tool_name} costs ~${estimated_cost:.4f}, \"\n            f\"daily remaining=${remaining_daily:.2f}, \"\n            f\"wallet=${wallet_balance:.2f}\"\n        )\n    return can_afford\n\n\n# Usage in an agent loop\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\ntasks = [\n    (\"search_services\", {\"query\": \"document summarization\"}),\n    (\"create_escrow\", {\"amount\": \"25.00\", \"payee\": \"summarizer-01\"}),\n    (\"submit_metrics\", {\"metrics\": {\"accuracy\": 0.95}}),\n]\n\nfor tool_name, params in tasks:\n    if preflight_check(finops, tool_name, params):\n        result = finops._execute(tool_name, params)\n        print(f\"  Executed {tool_name}: OK\")\n    else:\n        print(f\"  Skipped {tool_name}: insufficient budget\")\n        break  # Stop the workflow, do not accumulate partial state\n```\n\n### Funding Workflows: Orchestrator-to-Worker Deposits\n\nIn many architectures, the orchestrator agent funds worker agents as part of task assignment. This creates an explicit cost boundary around each task.\n\n```python\ndef fund_worker_for_task(\n    orchestrator: AgentFinOps,\n    worker_agent_id: str,\n    task_budget: float,\n    api_key: str,\n) -> AgentFinOps:\n    \"\"\"Fund a worker agent's wallet for a specific task.\"\"\"\n    worker = AgentFinOps(\n        api_key=api_key,\n        agent_id=worker_agent_id,\n    )\n\n    # Estimate worker's current balance\n    balance = worker.get_balance()\n    current = float(balance.get(\"balance\", 0))\n\n    # Top up only what is needed\n    if current \u003C task_budget:\n        shortfall = task_budget - current\n        worker.deposit(amount=shortfall)\n        print(\n            f\"Funded {worker_agent_id}: +${shortfall:.2f} \"\n            f\"(new balance: ${task_budget:.2f})\"\n        )\n\n    # Set a tight budget cap for this task\n    worker.set_budget_cap(daily_limit=task_budget)\n    return worker\n\n\n# Orchestrator delegates a research task with a $15 budget\norchestrator = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\nworker = fund_worker_for_task(\n    orchestrator=orchestrator,\n    worker_agent_id=\"researcher-01\",\n    task_budget=15.00,\n    api_key=API_KEY,\n)\n```\n\n---\n\n## Chapter 3: Budget Caps and Hard Stops\n\n### Per-Agent Budget Caps\n\nBudget caps are the most important cost governance primitive. When an agent exceeds its cap, the gateway returns `402 Payment Required` on the next tool call. The agent's code catches this as a `BudgetExhaustedError` and can implement any fail-fast behavior: log the event, notify the orchestrator, gracefully terminate, or queue the remaining work for the next budget cycle.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Set daily and monthly caps\nfinops.set_budget_cap(daily_limit=25.00, monthly_limit=500.00)\n\n# Verify the cap is active\nstatus = finops.get_budget_status()\nprint(f\"Daily limit:   ${status['daily_limit']}\")\nprint(f\"Monthly limit: ${status['monthly_limit']}\")\nprint(f\"Spent today:   ${status['spent_today']}\")\nprint(f\"Spent this month: ${status['spent_this_month']}\")\n```\n\n**curl -- set budget cap:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"set_budget_cap\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"daily_limit\": \"25.00\",\n      \"monthly_limit\": \"500.00\"\n    }\n  }'\n```\n\n### Per-Workflow Budget Caps\n\nSometimes you need a budget cap on a workflow, not just an individual agent. The pattern: create a dedicated agent ID per workflow run, give it a wallet with exactly the workflow budget, and route all tool calls through it.\n\n```python\nimport uuid\nfrom datetime import datetime, timezone\n\n\ndef create_workflow_budget(\n    api_key: str,\n    workflow_name: str,\n    budget: float,\n) -> AgentFinOps:\n    \"\"\"Create a budget-capped agent for a single workflow run.\"\"\"\n    run_id = uuid.uuid4().hex[:8]\n    workflow_agent_id = f\"wf-{workflow_name}-{run_id}\"\n\n    finops = AgentFinOps(\n        api_key=api_key,\n        agent_id=workflow_agent_id,\n    )\n\n    finops.create_wallet()\n    finops.deposit(amount=budget)\n    finops.set_budget_cap(daily_limit=budget)  # Entire budget as one-shot\n\n    print(\n        f\"Workflow {workflow_name} ({run_id}): \"\n        f\"${budget:.2f} budget allocated\"\n    )\n    return finops\n\n\n# Create a $50 budget for a research workflow\nwf_finops = create_workflow_budget(\n    api_key=API_KEY,\n    workflow_name=\"quarterly-report\",\n    budget=50.00,\n)\n```\n\n### Handling 402 Payment Required\n\nWhen the budget cap is hit, the gateway returns HTTP 402. Your agent code must handle this gracefully -- not with a retry, but with a controlled shutdown.\n\n```python\ndef safe_execute(finops: AgentFinOps, tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a tool with budget-aware error handling.\"\"\"\n    try:\n        return finops._execute(tool, input_data)\n    except BudgetExhaustedError:\n        # Log the budget exhaustion event\n        print(\n            f\"BUDGET EXHAUSTED: Agent {finops.agent_id} hit cap \"\n            f\"while calling {tool}. Stopping execution.\"\n        )\n        # Return a sentinel that the calling code can check\n        return {\"error\": \"budget_exhausted\", \"tool\": tool}\n    except requests.exceptions.HTTPError as e:\n        if e.response.status_code == 429:\n            # Rate limited -- back off and retry\n            time.sleep(2)\n            return finops._execute(tool, input_data)\n        raise\n\n\n# Agent loop with budget-aware execution\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\nfor i in range(100):  # Agent might try 100 tool calls\n    result = safe_execute(finops, \"search_services\", {\"query\": f\"topic-{i}\"})\n    if result.get(\"error\") == \"budget_exhausted\":\n        print(f\"Stopped at iteration {i}. Budget exhausted.\")\n        break\n    # Process result normally\n```\n\n### Setting Budget Caps Across a Fleet\n\n```python\n# Define tiered budget policies\nBUDGET_TIERS = {\n    \"orchestrator\": {\"daily\": 100.00, \"monthly\": 2000.00},\n    \"researcher\":   {\"daily\": 25.00,  \"monthly\": 500.00},\n    \"summarizer\":   {\"daily\": 15.00,  \"monthly\": 300.00},\n    \"classifier\":   {\"daily\": 10.00,  \"monthly\": 200.00},\n}\n\ndef apply_fleet_budget_policy(api_key: str, agents: list[dict]):\n    \"\"\"Apply budget caps to all agents based on their role tier.\"\"\"\n    for agent in agents:\n        role = agent[\"role\"]\n        tier = BUDGET_TIERS.get(role)\n        if not tier:\n            print(f\"WARNING: No budget tier for role '{role}'. Skipping.\")\n            continue\n\n        finops = AgentFinOps(api_key=api_key, agent_id=agent[\"agent_id\"])\n        finops.set_budget_cap(\n            daily_limit=tier[\"daily\"],\n            monthly_limit=tier[\"monthly\"],\n        )\n        print(\n            f\"  {agent['agent_id']} ({role}): \"\n            f\"${tier['daily']}\u002Fday, ${tier['monthly']}\u002Fmonth\"\n        )\n\n\nagents = [\n    {\"agent_id\": \"orchestrator-01\", \"role\": \"orchestrator\"},\n    {\"agent_id\": \"researcher-01\",   \"role\": \"researcher\"},\n    {\"agent_id\": \"researcher-02\",   \"role\": \"researcher\"},\n    {\"agent_id\": \"summarizer-01\",   \"role\": \"summarizer\"},\n    {\"agent_id\": \"classifier-01\",   \"role\": \"classifier\"},\n]\n\napply_fleet_budget_policy(API_KEY, agents)\n```\n\n---\n\n## Chapter 4: Real-Time Spend Alerts with Webhooks\n\n### Why Polling Is Not Enough\n\nChecking `get_budget_status` inside your agent loop works for pre-flight checks, but it misses spend that happens between checks. If your agent makes ten tool calls in rapid succession and the budget cap is hit on call seven, calls eight through ten fail with 402. Webhooks push alerts to your system the moment a threshold is crossed, enabling real-time escalation -- warn the team at 75%, pause the agent at 90%, kill it at 100%.\n\n### Registering Budget Threshold Alerts\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Register three escalation tiers\nalert_tiers = [\n    {\"threshold_pct\": 75, \"label\": \"warning\"},\n    {\"threshold_pct\": 90, \"label\": \"critical\"},\n    {\"threshold_pct\": 100, \"label\": \"exhausted\"},\n]\n\nwebhook_ids = []\nfor tier in alert_tiers:\n    webhook = finops.register_webhook(\n        url=f\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002F{tier['label']}\",\n        events=[\"budget.threshold\"],\n        config={\"threshold_pct\": tier[\"threshold_pct\"]},\n    )\n    webhook_ids.append(webhook[\"webhook_id\"])\n    print(\n        f\"Alert registered: {tier['label']} at {tier['threshold_pct']}% \"\n        f\"(webhook_id: {webhook['webhook_id']})\"\n    )\n```\n\n**curl -- register a webhook:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"url\": \"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fwarning\",\n      \"events\": [\"budget.threshold\"],\n      \"config\": {\"threshold_pct\": 75}\n    }\n  }'\n```\n\n### Building the Alert Receiver\n\nYour alert receiver is a simple HTTP endpoint that receives webhook payloads and dispatches escalation actions.\n\n```python\nfrom flask import Flask, request, jsonify\nimport logging\n\napp = Flask(__name__)\nlogger = logging.getLogger(\"finops_alerts\")\n\n\n@app.route(\"\u002Falerts\u002Fwarning\", methods=[\"POST\"])\ndef handle_warning():\n    \"\"\"75% budget consumed -- log and notify Slack.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n    spent_pct = payload.get(\"spent_pct\")\n    remaining = payload.get(\"remaining_budget\")\n\n    logger.warning(\n        f\"BUDGET WARNING: {agent_id} at {spent_pct}% \"\n        f\"(${remaining} remaining)\"\n    )\n    # Send Slack\u002FPagerDuty notification\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"Agent {agent_id} has consumed {spent_pct}% of its daily budget. \"\n                f\"${remaining} remaining.\",\n    )\n    return jsonify({\"status\": \"acknowledged\"})\n\n\n@app.route(\"\u002Falerts\u002Fcritical\", methods=[\"POST\"])\ndef handle_critical():\n    \"\"\"90% budget consumed -- pause the agent.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n\n    logger.critical(\n        f\"BUDGET CRITICAL: {agent_id} at {payload.get('spent_pct')}%. \"\n        f\"Pausing agent.\"\n    )\n    # Signal the agent to pause (via shared state, message queue, etc.)\n    pause_agent(agent_id)\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"CRITICAL: Agent {agent_id} paused at 90% budget.\",\n    )\n    return jsonify({\"status\": \"agent_paused\"})\n\n\n@app.route(\"\u002Falerts\u002Fexhausted\", methods=[\"POST\"])\ndef handle_exhausted():\n    \"\"\"100% budget consumed -- kill the agent process.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n\n    logger.error(\n        f\"BUDGET EXHAUSTED: {agent_id}. Terminating.\"\n    )\n    kill_agent(agent_id)\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"EXHAUSTED: Agent {agent_id} terminated. Budget fully consumed.\",\n    )\n    return jsonify({\"status\": \"agent_terminated\"})\n\n\ndef notify_slack(channel: str, message: str):\n    \"\"\"Send a Slack notification. Replace with your Slack webhook.\"\"\"\n    import requests as req\n    req.post(os.environ.get(\"SLACK_WEBHOOK_URL\", \"\"), json={\n        \"channel\": channel,\n        \"text\": message,\n    })\n\n\ndef pause_agent(agent_id: str):\n    \"\"\"Signal an agent to pause. Implementation depends on your runtime.\"\"\"\n    # Example: write a pause flag to Redis\n    # redis_client.set(f\"agent:{agent_id}:paused\", \"1\", ex=3600)\n    pass\n\n\ndef kill_agent(agent_id: str):\n    \"\"\"Terminate an agent process. Implementation depends on your runtime.\"\"\"\n    # Example: send SIGTERM to the agent's PID\n    # os.kill(agent_pids[agent_id], signal.SIGTERM)\n    pass\n```\n\n### Auditing Webhook Configuration\n\nBefore relying on webhooks in production, verify they are correctly configured.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# List all registered webhooks\nwebhooks = finops.list_webhooks()\nfor wh in webhooks.get(\"webhooks\", []):\n    print(\n        f\"  ID: {wh['webhook_id']} | URL: {wh['url']} | \"\n        f\"Events: {wh['events']} | Config: {wh.get('config', {})}\"\n    )\n```\n\n**curl -- list webhooks:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"list_webhooks\",\n    \"input\": {\"agent_id\": \"researcher-01\"}\n  }'\n```\n\n### Adjusting Thresholds Dynamically\n\nAs your fleet evolves, you may need to tighten or relax alert thresholds. Use `update_webhook` to adjust without deleting and re-creating.\n\n```python\n# Tighten the warning threshold from 75% to 60%\nfinops.update_webhook(\n    webhook_id=webhook_ids[0],\n    config={\"threshold_pct\": 60},\n)\nprint(\"Warning threshold tightened to 60%\")\n```\n\n### Debugging Missed Alerts\n\nWhen an alert should have fired but did not, check the webhook logs.\n\n```python\n# Inspect delivery history for a specific webhook\nlogs = finops.get_webhook_logs(webhook_id=webhook_ids[0], limit=20)\nfor entry in logs.get(\"logs\", []):\n    print(\n        f\"  {entry['timestamp']} | Status: {entry['delivery_status']} | \"\n        f\"HTTP {entry.get('response_code', 'N\u002FA')}\"\n    )\n```\n\n**curl -- get webhook logs:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_webhook_logs\",\n    \"input\": {\"webhook_id\": \"wh_abc123\", \"limit\": 20}\n  }'\n```\n\n### Cleaning Up Stale Webhooks\n\nWhen decommissioning an agent, remove its webhooks to prevent orphaned alert traffic.\n\n```python\ndef cleanup_agent_webhooks(finops: AgentFinOps):\n    \"\"\"Remove all webhooks for an agent being decommissioned.\"\"\"\n    webhooks = finops.list_webhooks()\n    for wh in webhooks.get(\"webhooks\", []):\n        finops.delete_webhook(wh[\"webhook_id\"])\n        print(f\"  Deleted webhook {wh['webhook_id']}\")\n```\n\n---\n\n## Chapter 5: Cost Attribution and Category Spend\n\n### Why Attribution Matters\n\nBudget caps prevent overspend. Attribution answers a different question: where is the money going? Without category-level spend data, you cannot optimize. You cannot answer \"which tool category consumes 60% of our budget?\" or \"which agent has the worst cost-per-task ratio?\" or \"did last week's prompt change increase or decrease total spend?\"\n\n### Tagging Spend by Agent, Workflow, and Tool\n\nGreenHelix tracks spend at the agent level natively. Every tool call executed by an agent is attributed to that agent's wallet. To get workflow-level attribution, use the dedicated workflow agent pattern from Chapter 3. To get tool-level attribution, use `get_spending_by_category`.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Get spend breakdown by tool category\ncategory_spend = finops.get_spending_by_category(\n    start_date=\"2026-04-01\",\n    end_date=\"2026-04-06\",\n)\n\nprint(\"Spend by category (April 1-6):\")\nfor category in category_spend.get(\"categories\", []):\n    print(\n        f\"  {category['category']:.\u003C30} \"\n        f\"${category['total_cost']:>8.2f}  \"\n        f\"({category['call_count']} calls)\"\n    )\n```\n\n**curl -- get spending by category:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_spending_by_category\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"start_date\": \"2026-04-01\",\n      \"end_date\": \"2026-04-06\"\n    }\n  }'\n```\n\n### Building Chargeback Reports\n\nIn organizations where different teams own different agents, chargebacks attribute platform costs to the team that caused them. This is standard FinOps practice for cloud infrastructure, adapted for multi-agent systems.\n\n```python\ndef generate_chargeback_report(\n    api_key: str,\n    team_agents: dict[str, list[str]],\n    period: str = \"monthly\",\n) -> dict:\n    \"\"\"Generate a chargeback report by team.\n\n    team_agents: {\"data-team\": [\"researcher-01\", \"researcher-02\"],\n                  \"ml-team\": [\"classifier-01\", \"summarizer-01\"]}\n    \"\"\"\n    report = {}\n    for team, agent_ids in team_agents.items():\n        team_total = 0.0\n        agent_details = []\n        for agent_id in agent_ids:\n            finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n            summary = finops.get_billing_summary(period=period)\n            agent_cost = float(summary.get(\"total_cost\", 0))\n            team_total += agent_cost\n            agent_details.append({\n                \"agent_id\": agent_id,\n                \"cost\": agent_cost,\n                \"tool_calls\": summary.get(\"total_calls\", 0),\n            })\n        report[team] = {\n            \"total_cost\": round(team_total, 2),\n            \"agents\": agent_details,\n        }\n    return report\n\n\n# Generate monthly chargeback\nchargeback = generate_chargeback_report(\n    api_key=API_KEY,\n    team_agents={\n        \"data-team\": [\"researcher-01\", \"researcher-02\"],\n        \"ml-team\": [\"classifier-01\", \"summarizer-01\"],\n        \"ops-team\": [\"orchestrator-01\"],\n    },\n)\n\nfor team, data in chargeback.items():\n    print(f\"\\n{team}: ${data['total_cost']:.2f}\")\n    for agent in data[\"agents\"]:\n        print(\n            f\"  {agent['agent_id']}: ${agent['cost']:.2f} \"\n            f\"({agent['tool_calls']} calls)\"\n        )\n```\n\n### Per-Agent P&L Statements\n\nFor agents that both spend and earn (e.g., a service agent that charges for its work), compute a per-agent profit and loss.\n\n```python\ndef agent_pnl(api_key: str, agent_id: str, period: str = \"monthly\") -> dict:\n    \"\"\"Compute profit and loss for an agent.\"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n\n    # Cost side: what the agent spent\n    summary = finops.get_billing_summary(period=period)\n    total_cost = float(summary.get(\"total_cost\", 0))\n\n    # Revenue side: what the agent earned (from usage analytics)\n    analytics = finops.get_usage_analytics(\n        start_date=summary.get(\"period_start\", \"2026-04-01\"),\n        end_date=summary.get(\"period_end\", \"2026-04-30\"),\n    )\n    total_revenue = float(analytics.get(\"revenue_earned\", 0))\n\n    return {\n        \"agent_id\": agent_id,\n        \"revenue\": round(total_revenue, 2),\n        \"cost\": round(total_cost, 2),\n        \"profit\": round(total_revenue - total_cost, 2),\n        \"margin_pct\": (\n            round((total_revenue - total_cost) \u002F total_revenue * 100, 1)\n            if total_revenue > 0 else 0.0\n        ),\n    }\n\n\n# Compute P&L for a service agent\npnl = agent_pnl(API_KEY, \"summarizer-01\")\nprint(\n    f\"Agent {pnl['agent_id']}: \"\n    f\"Revenue=${pnl['revenue']}, Cost=${pnl['cost']}, \"\n    f\"Profit=${pnl['profit']} ({pnl['margin_pct']}% margin)\"\n)\n```\n\n### Historical Spend Analysis\n\nUse `get_usage_analytics` for time-series spend data to identify trends, anomalies, and the impact of configuration changes.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Pull weekly analytics for the last 4 weeks\nweeks = [\n    (\"2026-03-09\", \"2026-03-15\"),\n    (\"2026-03-16\", \"2026-03-22\"),\n    (\"2026-03-23\", \"2026-03-29\"),\n    (\"2026-03-30\", \"2026-04-05\"),\n]\n\nprint(\"Weekly spend trend for researcher-01:\")\nfor start, end in weeks:\n    analytics = finops.get_usage_analytics(start_date=start, end_date=end)\n    cost = float(analytics.get(\"total_cost\", 0))\n    calls = analytics.get(\"total_calls\", 0)\n    print(f\"  {start} to {end}: ${cost:.2f} ({calls} calls)\")\n```\n\n---\n\n## Chapter 6: Volume Discounts and Cost Optimization\n\n### Checking Volume Discount Eligibility\n\nHigh-volume agents may qualify for automatic discounts based on cumulative usage. Check your current tier and what it takes to reach the next one.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\ndiscount = finops.get_volume_discount()\nprint(f\"Current tier:      {discount.get('current_tier')}\")\nprint(f\"Discount rate:     {discount.get('discount_pct')}%\")\nprint(f\"Monthly volume:    ${discount.get('monthly_volume')}\")\nprint(f\"Next tier at:      ${discount.get('next_tier_threshold')}\")\nprint(f\"Next tier discount: {discount.get('next_tier_discount_pct')}%\")\n```\n\n**curl -- check volume discount:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_volume_discount\",\n    \"input\": {\"agent_id\": \"orchestrator-01\"}\n  }'\n```\n\n### Pre-Execution Cost Estimation\n\nBefore choosing which tool to use for a task, estimate the cost of each option. This enables cost-aware routing: the orchestrator picks the cheapest tool that meets quality requirements.\n\n```python\ndef cheapest_tool(\n    finops: AgentFinOps,\n    candidates: list[dict],\n) -> dict:\n    \"\"\"Pick the cheapest tool from a list of candidates.\n\n    Each candidate: {\"tool\": \"tool_name\", \"params\": {...}, \"quality\": float}\n    Quality must be >= min_quality to be considered.\n    \"\"\"\n    min_quality = 0.8\n    estimated = []\n\n    for candidate in candidates:\n        if candidate[\"quality\"] \u003C min_quality:\n            continue\n        estimate = finops.estimate_cost(\n            tool_name=candidate[\"tool\"],\n            parameters=candidate[\"params\"],\n        )\n        candidate[\"estimated_cost\"] = float(\n            estimate.get(\"estimated_cost\", float(\"inf\"))\n        )\n        estimated.append(candidate)\n\n    if not estimated:\n        raise ValueError(\"No candidate meets minimum quality threshold\")\n\n    # Sort by cost, pick cheapest\n    estimated.sort(key=lambda c: c[\"estimated_cost\"])\n    winner = estimated[0]\n    print(\n        f\"Selected {winner['tool']} at ${winner['estimated_cost']:.4f} \"\n        f\"(quality={winner['quality']})\"\n    )\n    return winner\n\n\n# Orchestrator choosing between three summarization tools\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\nbest = cheapest_tool(finops, [\n    {\"tool\": \"summarize_gpt4o\", \"params\": {\"tokens\": 2000}, \"quality\": 0.95},\n    {\"tool\": \"summarize_claude\", \"params\": {\"tokens\": 2000}, \"quality\": 0.93},\n    {\"tool\": \"summarize_llama\", \"params\": {\"tokens\": 2000}, \"quality\": 0.82},\n])\n```\n\n### Multi-Currency Cost Normalization\n\nWhen your fleet operates across regions or platforms with different billing currencies, normalize everything to a single currency for consistent reporting.\n\n```python\ndef normalize_fleet_costs(\n    api_key: str,\n    agent_costs: list[dict],\n    target_currency: str = \"USD\",\n) -> list[dict]:\n    \"\"\"Convert all agent costs to a single currency.\n\n    agent_costs: [{\"agent_id\": \"x\", \"cost\": 100, \"currency\": \"EUR\"}, ...]\n    \"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=\"system\")\n    normalized = []\n\n    for entry in agent_costs:\n        if entry[\"currency\"] == target_currency:\n            entry[\"normalized_cost\"] = entry[\"cost\"]\n        else:\n            conversion = finops.convert_currency(\n                amount=entry[\"cost\"],\n                from_currency=entry[\"currency\"],\n                to_currency=target_currency,\n            )\n            entry[\"normalized_cost\"] = float(\n                conversion.get(\"converted_amount\", entry[\"cost\"])\n            )\n        normalized.append(entry)\n\n    return normalized\n\n\n# Normalize costs from a multi-region fleet\ncosts = normalize_fleet_costs(API_KEY, [\n    {\"agent_id\": \"eu-researcher\", \"cost\": 85.50, \"currency\": \"EUR\"},\n    {\"agent_id\": \"us-researcher\", \"cost\": 92.00, \"currency\": \"USD\"},\n    {\"agent_id\": \"jp-researcher\", \"cost\": 12000, \"currency\": \"JPY\"},\n])\n\nfor c in costs:\n    print(\n        f\"  {c['agent_id']}: {c['cost']} {c['currency']} \"\n        f\"= ${c['normalized_cost']:.2f} USD\"\n    )\n```\n\n### Cost-Aware Model Routing\n\nCombine cost estimation with quality requirements to route agent tasks to the most cost-effective model at runtime.\n\n```python\ndef cost_aware_route(\n    finops: AgentFinOps,\n    task_type: str,\n    quality_floor: float = 0.85,\n) -> str:\n    \"\"\"Route a task to the cheapest model that meets quality requirements.\"\"\"\n    MODEL_CATALOG = {\n        \"gpt-4o\":      {\"quality\": 0.95, \"tool\": \"inference_gpt4o\"},\n        \"claude-3.5\":  {\"quality\": 0.93, \"tool\": \"inference_claude\"},\n        \"llama-3-70b\": {\"quality\": 0.85, \"tool\": \"inference_llama\"},\n        \"mistral-8x7b\":{\"quality\": 0.80, \"tool\": \"inference_mistral\"},\n    }\n\n    candidates = []\n    for model, spec in MODEL_CATALOG.items():\n        if spec[\"quality\"] \u003C quality_floor:\n            continue\n        est = finops.estimate_cost(\n            tool_name=spec[\"tool\"],\n            parameters={\"task_type\": task_type},\n        )\n        candidates.append({\n            \"model\": model,\n            \"cost\": float(est.get(\"estimated_cost\", float(\"inf\"))),\n            \"quality\": spec[\"quality\"],\n        })\n\n    candidates.sort(key=lambda c: c[\"cost\"])\n    if candidates:\n        pick = candidates[0]\n        print(\n            f\"Routing {task_type} to {pick['model']}: \"\n            f\"${pick['cost']:.4f}\u002Fcall, quality={pick['quality']}\"\n        )\n        return pick[\"model\"]\n    raise ValueError(f\"No model meets quality floor {quality_floor}\")\n```\n\n---\n\n## Chapter 7: Fleet Dashboards and Leaderboards\n\n### Cost-Efficiency Leaderboard\n\nThe agent leaderboard ranks all agents in your fleet by cost efficiency -- the ratio of useful output to money spent. This is the FinOps equivalent of cloud cost-per-transaction dashboards, applied to agents.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\n# Pull the cost-efficiency leaderboard\nleaderboard = finops.get_agent_leaderboard(metric=\"cost_efficiency\")\n\nprint(\"Agent Cost-Efficiency Leaderboard\")\nprint(\"-\" * 65)\nprint(f\"{'Rank':\u003C6}{'Agent ID':\u003C25}{'Efficiency':\u003C15}{'Total Spend':\u003C15}\")\nprint(\"-\" * 65)\nfor i, entry in enumerate(leaderboard.get(\"agents\", []), 1):\n    print(\n        f\"{i:\u003C6}{entry['agent_id']:\u003C25}\"\n        f\"{entry.get('efficiency_score', 'N\u002FA'):\u003C15}\"\n        f\"${float(entry.get('total_spend', 0)):\u003C14.2f}\"\n    )\n```\n\n**curl -- get leaderboard:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_agent_leaderboard\",\n    \"input\": {\"metric\": \"cost_efficiency\"}\n  }'\n```\n\n### Platform-Wide Statistics\n\nGet a bird's-eye view of your entire agent platform: total spend, active agents, average cost per call, and utilization rates.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\nstats = finops.get_platform_stats()\nprint(\"Platform-Wide FinOps Summary\")\nprint(\"=\" * 45)\nprint(f\"Active agents:       {stats.get('active_agents')}\")\nprint(f\"Total spend (MTD):   ${stats.get('total_spend_mtd')}\")\nprint(f\"Avg cost\u002Fcall:       ${stats.get('avg_cost_per_call')}\")\nprint(f\"Total tool calls:    {stats.get('total_calls_mtd')}\")\nprint(f\"Budget utilization:  {stats.get('budget_utilization_pct')}%\")\nprint(f\"Agents over budget:  {stats.get('agents_over_budget', 0)}\")\n```\n\n**curl -- get platform stats:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_platform_stats\",\n    \"input\": {}\n  }'\n```\n\n### Trend Analysis: Week-over-Week Spend Comparison\n\n```python\ndef weekly_trend_report(\n    api_key: str,\n    agent_ids: list[str],\n    weeks: list[tuple[str, str]],\n):\n    \"\"\"Print week-over-week spend trends for a fleet of agents.\"\"\"\n    print(f\"\\n{'Agent':\u003C22}\", end=\"\")\n    for start, end in weeks:\n        print(f\"{start:\u003C16}\", end=\"\")\n    print(\"  WoW Change\")\n    print(\"-\" * (22 + 16 * len(weeks) + 12))\n\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        costs = []\n        print(f\"{agent_id:\u003C22}\", end=\"\")\n        for start, end in weeks:\n            analytics = finops.get_usage_analytics(\n                start_date=start,\n                end_date=end,\n            )\n            cost = float(analytics.get(\"total_cost\", 0))\n            costs.append(cost)\n            print(f\"${cost:\u003C15.2f}\", end=\"\")\n\n        # Compute week-over-week change for last two weeks\n        if len(costs) >= 2 and costs[-2] > 0:\n            change_pct = (costs[-1] - costs[-2]) \u002F costs[-2] * 100\n            direction = \"+\" if change_pct > 0 else \"\"\n            print(f\"  {direction}{change_pct:.1f}%\")\n        else:\n            print(\"  N\u002FA\")\n\n\nweekly_trend_report(\n    api_key=API_KEY,\n    agent_ids=[\n        \"orchestrator-01\", \"researcher-01\", \"researcher-02\",\n        \"summarizer-01\", \"classifier-01\",\n    ],\n    weeks=[\n        (\"2026-03-16\", \"2026-03-22\"),\n        (\"2026-03-23\", \"2026-03-29\"),\n        (\"2026-03-30\", \"2026-04-05\"),\n    ],\n)\n```\n\n### Building a Daily FinOps Dashboard\n\nCombine all the analytics tools into a single dashboard function that your team runs every morning.\n\n```python\ndef daily_finops_dashboard(api_key: str, agent_ids: list[str]):\n    \"\"\"Print a comprehensive daily FinOps dashboard.\"\"\"\n    print(\"=\" * 70)\n    print(\"  DAILY FINOPS DASHBOARD  |  \" + datetime.now(timezone.utc).strftime(\"%Y-%m-%d %H:%M UTC\"))\n    print(\"=\" * 70)\n\n    # Platform overview\n    system = AgentFinOps(api_key=api_key, agent_id=agent_ids[0])\n    stats = system.get_platform_stats()\n    print(f\"\\nPlatform: {stats.get('active_agents')} agents | \"\n          f\"${stats.get('total_spend_mtd')} MTD | \"\n          f\"{stats.get('budget_utilization_pct')}% budget used\")\n\n    # Per-agent status\n    print(f\"\\n{'Agent':\u003C22}{'Balance':>10}{'Spent Today':>13}\"\n          f\"{'Daily Cap':>11}{'% Used':>9}\")\n    print(\"-\" * 65)\n\n    alerts = []\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        balance = finops.get_balance()\n        budget = finops.get_budget_status()\n\n        bal = float(balance.get(\"balance\", 0))\n        spent = float(budget.get(\"spent_today\", 0))\n        cap = float(budget.get(\"daily_limit\", 0))\n        pct = (spent \u002F cap * 100) if cap > 0 else 0\n\n        flag = \" !!!\" if pct > 80 else \"\"\n        print(\n            f\"{agent_id:\u003C22}${bal:>9.2f}${spent:>12.2f}\"\n            f\"${cap:>10.2f}{pct:>8.1f}%{flag}\"\n        )\n\n        if pct > 80:\n            alerts.append(f\"  {agent_id}: {pct:.1f}% of daily budget used\")\n\n    if alerts:\n        print(f\"\\nALERTS ({len(alerts)}):\")\n        for alert in alerts:\n            print(alert)\n\n    # Top spenders by category (fleet-wide, using first agent for API access)\n    print(\"\\nTop spending categories (fleet-wide, last 24h):\")\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        cats = finops.get_spending_by_category(\n            start_date=datetime.now(timezone.utc).strftime(\"%Y-%m-%d\"),\n        )\n        for cat in cats.get(\"categories\", [])[:3]:\n            print(\n                f\"  {agent_id} > {cat['category']}: \"\n                f\"${cat['total_cost']:.2f} ({cat['call_count']} calls)\"\n            )\n\n    print(\"\\n\" + \"=\" * 70)\n```\n\n---\n\n## Chapter 8: API Key Isolation and Security\n\n### Why Per-Agent API Keys Matter for Cost Control\n\nAPI keys are not just a security boundary -- they are a cost boundary. When five agents share one API key, revoking the key to stop a runaway agent kills all five. Per-agent keys let you revoke one agent's access without disrupting the rest of the fleet. This makes key revocation a viable cost control mechanism, not a fleet-wide outage.\n\n### Creating Per-Agent Keys\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Create a dedicated key with restricted permissions\nkey_result = finops.create_api_key(\n    label=\"researcher-01-production\",\n    permissions=[\"search_services\", \"get_balance\", \"get_budget_status\"],\n)\n\nnew_api_key = key_result.get(\"api_key\")\nkey_id = key_result.get(\"key_id\")\nprint(f\"API key created: {key_id}\")\nprint(f\"Key value: {new_api_key[:8]}...{new_api_key[-4:]}\")\nprint(f\"Permissions: {key_result.get('permissions')}\")\n```\n\n**curl -- create API key:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_api_key\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"label\": \"researcher-01-production\",\n      \"permissions\": [\"search_services\", \"get_balance\", \"get_budget_status\"]\n    }\n  }'\n```\n\n### Automated Key Rotation\n\nRotate keys on a schedule. The pattern: create a new key, update the agent's configuration to use it, verify it works, then delete the old key. Never delete the old key before the new one is in use.\n\n```python\ndef rotate_agent_key(\n    admin_finops: AgentFinOps,\n    agent_id: str,\n    old_key_id: str,\n) -> dict:\n    \"\"\"Rotate an agent's API key with zero downtime.\"\"\"\n    finops = AgentFinOps(\n        api_key=admin_finops.session.headers[\"Authorization\"].split(\" \")[1],\n        agent_id=agent_id,\n    )\n\n    # Step 1: Create new key\n    new_key = finops.create_api_key(\n        label=f\"{agent_id}-rotated-{int(time.time())}\",\n    )\n    print(f\"New key created: {new_key['key_id']}\")\n\n    # Step 2: Rotate -- this invalidates the old key after a grace period\n    rotate_result = finops.rotate_api_key(key_id=old_key_id)\n    print(f\"Old key {old_key_id} scheduled for invalidation\")\n\n    return {\n        \"new_key_id\": new_key[\"key_id\"],\n        \"new_api_key\": new_key[\"api_key\"],\n        \"old_key_id\": old_key_id,\n        \"rotation_status\": rotate_result.get(\"status\"),\n    }\n\n\n# Rotate the researcher's key\nresult = rotate_agent_key(\n    admin_finops=AgentFinOps(api_key=API_KEY, agent_id=\"admin\"),\n    agent_id=\"researcher-01\",\n    old_key_id=\"key_abc123\",\n)\nprint(f\"Rotation complete. New key: {result['new_key_id']}\")\n```\n\n**curl -- rotate API key:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"rotate_api_key\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"key_id\": \"key_abc123\"\n    }\n  }'\n```\n\n### Credential Revocation as Cost Control\n\nWhen you detect a runaway agent through a webhook alert or dashboard anomaly, the fastest way to stop the bleed is to revoke its API key. This is faster than killing the process (which requires infrastructure access) and more targeted than disabling the entire fleet.\n\n```python\ndef emergency_cost_stop(api_key: str, agent_id: str, key_id: str):\n    \"\"\"Emergency procedure: revoke an agent's API key to stop spend.\"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n\n    # Rotate the key -- the old key becomes invalid\n    finops.rotate_api_key(key_id=key_id)\n    print(f\"EMERGENCY: API key {key_id} revoked for {agent_id}\")\n\n    # Check final spend\n    budget = finops.get_budget_status()\n    print(f\"Final spend today: ${budget.get('spent_today')}\")\n\n    # Log the incident\n    return {\n        \"agent_id\": agent_id,\n        \"action\": \"key_revoked\",\n        \"final_spend\": budget.get(\"spent_today\"),\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n    }\n```\n\n### Fleet Key Rotation Schedule\n\nAutomate key rotation across the entire fleet as a weekly cron job.\n\n```python\ndef fleet_key_rotation(api_key: str, agents: list[dict]):\n    \"\"\"Rotate API keys for all agents in the fleet.\n\n    Run as a weekly cron job.\n    agents: [{\"agent_id\": \"...\", \"key_id\": \"...\"}, ...]\n    \"\"\"\n    admin = AgentFinOps(api_key=api_key, agent_id=\"admin\")\n    results = []\n\n    for agent in agents:\n        try:\n            result = rotate_agent_key(\n                admin_finops=admin,\n                agent_id=agent[\"agent_id\"],\n                old_key_id=agent[\"key_id\"],\n            )\n            results.append({\n                \"agent_id\": agent[\"agent_id\"],\n                \"status\": \"rotated\",\n                \"new_key_id\": result[\"new_key_id\"],\n            })\n        except Exception as e:\n            results.append({\n                \"agent_id\": agent[\"agent_id\"],\n                \"status\": \"failed\",\n                \"error\": str(e),\n            })\n\n    # Summary\n    rotated = sum(1 for r in results if r[\"status\"] == \"rotated\")\n    failed = sum(1 for r in results if r[\"status\"] == \"failed\")\n    print(f\"Key rotation complete: {rotated} rotated, {failed} failed\")\n    return results\n```\n\n---\n\n## Chapter 9: Putting It All Together: The FinOps Control Plane\n\n### End-to-End Scenario: Five-Agent Research Fleet\n\nThis section ties together every concept from the previous chapters into a single, production-ready control plane. The scenario: you are running a research fleet with five agents -- one orchestrator, two researchers, one summarizer, and one classifier. The fleet processes incoming research requests, delegates work, and must operate within a $200\u002Fday fleet budget.\n\n```python\nimport os\nfrom datetime import datetime, timezone\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nALERT_BASE_URL = \"https:\u002F\u002Fyour-app.example.com\u002Falerts\"\n\n# ── Step 1: Provision the fleet ─────────────────────────────────\n\nFLEET = [\n    {\"agent_id\": \"orch-01\",   \"role\": \"orchestrator\", \"deposit\": 200.00,\n     \"daily_cap\": 80.00,  \"monthly_cap\": 1600.00},\n    {\"agent_id\": \"res-01\",    \"role\": \"researcher\",   \"deposit\": 75.00,\n     \"daily_cap\": 30.00,  \"monthly_cap\": 600.00},\n    {\"agent_id\": \"res-02\",    \"role\": \"researcher\",   \"deposit\": 75.00,\n     \"daily_cap\": 30.00,  \"monthly_cap\": 600.00},\n    {\"agent_id\": \"sum-01\",    \"role\": \"summarizer\",   \"deposit\": 50.00,\n     \"daily_cap\": 20.00,  \"monthly_cap\": 400.00},\n    {\"agent_id\": \"cls-01\",    \"role\": \"classifier\",   \"deposit\": 40.00,\n     \"daily_cap\": 15.00,  \"monthly_cap\": 300.00},\n]\n\nfleet_clients = {}\n\nfor agent_cfg in FLEET:\n    finops = AgentFinOps(api_key=API_KEY, agent_id=agent_cfg[\"agent_id\"])\n\n    # Create wallet and fund\n    finops.create_wallet()\n    finops.deposit(amount=agent_cfg[\"deposit\"])\n\n    # Set budget caps\n    finops.set_budget_cap(\n        daily_limit=agent_cfg[\"daily_cap\"],\n        monthly_limit=agent_cfg[\"monthly_cap\"],\n    )\n\n    # Create dedicated API key\n    key = finops.create_api_key(\n        label=f\"{agent_cfg['agent_id']}-prod-key\",\n    )\n\n    # Register budget alerts at 75%, 90%, and 100%\n    for pct in [75, 90, 100]:\n        finops.register_webhook(\n            url=f\"{ALERT_BASE_URL}\u002F{agent_cfg['agent_id']}\u002F{pct}\",\n            events=[\"budget.threshold\"],\n            config={\"threshold_pct\": pct},\n        )\n\n    fleet_clients[agent_cfg[\"agent_id\"]] = finops\n    print(\n        f\"Provisioned {agent_cfg['agent_id']} \"\n        f\"(${agent_cfg['deposit']:.2f} balance, \"\n        f\"${agent_cfg['daily_cap']:.2f}\u002Fday cap)\"\n    )\n\n\n# ── Step 2: Pre-flight check before task delegation ─────────────\n\ndef delegate_task(\n    orchestrator: AgentFinOps,\n    worker_id: str,\n    tool: str,\n    params: dict,\n) -> dict:\n    \"\"\"Orchestrator delegates a task to a worker with full FinOps checks.\"\"\"\n    worker = fleet_clients[worker_id]\n\n    # Estimate cost\n    estimate = worker.estimate_cost(tool_name=tool, parameters=params)\n    cost = float(estimate.get(\"estimated_cost\", 0))\n\n    # Check worker's remaining budget\n    budget = worker.get_budget_status()\n    remaining = (\n        float(budget.get(\"daily_limit\", 0))\n        - float(budget.get(\"spent_today\", 0))\n    )\n\n    if cost > remaining:\n        print(\n            f\"SKIP: {worker_id} cannot afford {tool} \"\n            f\"(${cost:.4f} > ${remaining:.2f} remaining)\"\n        )\n        return {\"status\": \"skipped\", \"reason\": \"insufficient_budget\"}\n\n    # Execute\n    try:\n        result = worker._execute(tool, params)\n        return {\"status\": \"success\", \"result\": result}\n    except BudgetExhaustedError:\n        return {\"status\": \"budget_exhausted\"}\n\n\n# ── Step 3: Run a workflow ──────────────────────────────────────\n\norch = fleet_clients[\"orch-01\"]\n\n# The orchestrator delegates research tasks to the two researchers\ntasks = [\n    (\"res-01\", \"search_services\", {\"query\": \"climate data analysis\"}),\n    (\"res-02\", \"search_services\", {\"query\": \"economic forecasting models\"}),\n]\n\nresults = []\nfor worker_id, tool, params in tasks:\n    result = delegate_task(orch, worker_id, tool, params)\n    results.append(result)\n    print(f\"  {worker_id} > {tool}: {result['status']}\")\n\n# Summarizer processes the combined results\ndelegate_task(\n    orch, \"sum-01\",\n    \"search_services\",\n    {\"query\": \"summarize findings\"},\n)\n\n# Classifier categorizes the output\ndelegate_task(\n    orch, \"cls-01\",\n    \"search_services\",\n    {\"query\": \"classify report type\"},\n)\n\n\n# ── Step 4: Generate end-of-day report ──────────────────────────\n\ndef end_of_day_report(api_key: str, fleet: list[dict]):\n    \"\"\"Generate a fleet-wide end-of-day FinOps report.\"\"\"\n    print(\"\\n\" + \"=\" * 70)\n    print(\"  END-OF-DAY FINOPS REPORT  |  \" +\n          datetime.now(timezone.utc).strftime(\"%Y-%m-%d\"))\n    print(\"=\" * 70)\n\n    total_fleet_spend = 0.0\n\n    print(f\"\\n{'Agent':\u003C14}{'Spent Today':>13}{'Daily Cap':>11}\"\n          f\"{'Utilization':>13}{'Balance':>10}\")\n    print(\"-\" * 61)\n\n    for agent_cfg in fleet:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_cfg[\"agent_id\"])\n        budget = finops.get_budget_status()\n        balance = finops.get_balance()\n\n        spent = float(budget.get(\"spent_today\", 0))\n        cap = float(budget.get(\"daily_limit\", 0))\n        bal = float(balance.get(\"balance\", 0))\n        util = (spent \u002F cap * 100) if cap > 0 else 0\n        total_fleet_spend += spent\n\n        print(\n            f\"{agent_cfg['agent_id']:\u003C14}${spent:>12.2f}${cap:>10.2f}\"\n            f\"{util:>12.1f}%${bal:>9.2f}\"\n        )\n\n    print(\"-\" * 61)\n    print(f\"{'Fleet Total':\u003C14}${total_fleet_spend:>12.2f}\")\n\n    # Leaderboard\n    system = AgentFinOps(api_key=api_key, agent_id=fleet[0][\"agent_id\"])\n    lb = system.get_agent_leaderboard(metric=\"cost_efficiency\")\n    print(\"\\nEfficiency Leaderboard (top 3):\")\n    for i, entry in enumerate(lb.get(\"agents\", [])[:3], 1):\n        print(\n            f\"  #{i} {entry['agent_id']}: \"\n            f\"efficiency={entry.get('efficiency_score', 'N\u002FA')}\"\n        )\n\n    print(\"\\n\" + \"=\" * 70)\n\n\nend_of_day_report(API_KEY, FLEET)\n```\n\n### The Complete FinOps Control Plane Class\n\nFor production use, wrap the orchestration logic into a reusable control plane class.\n\n```python\nclass FinOpsControlPlane:\n    \"\"\"Centralized FinOps control plane for multi-agent fleets.\"\"\"\n\n    def __init__(self, api_key: str, alert_base_url: str):\n        self.api_key = api_key\n        self.alert_base_url = alert_base_url\n        self.agents: dict[str, AgentFinOps] = {}\n\n    def provision_agent(\n        self,\n        agent_id: str,\n        deposit: float,\n        daily_cap: float,\n        monthly_cap: float,\n        alert_thresholds: list[int] = None,\n    ) -> AgentFinOps:\n        \"\"\"Provision an agent with wallet, budget, key, and alerts.\"\"\"\n        if alert_thresholds is None:\n            alert_thresholds = [75, 90, 100]\n\n        finops = AgentFinOps(\n            api_key=self.api_key,\n            agent_id=agent_id,\n        )\n\n        finops.create_wallet()\n        finops.deposit(amount=deposit)\n        finops.set_budget_cap(\n            daily_limit=daily_cap,\n            monthly_limit=monthly_cap,\n        )\n        finops.create_api_key(label=f\"{agent_id}-managed\")\n\n        for pct in alert_thresholds:\n            finops.register_webhook(\n                url=f\"{self.alert_base_url}\u002F{agent_id}\u002F{pct}\",\n                events=[\"budget.threshold\"],\n                config={\"threshold_pct\": pct},\n            )\n\n        self.agents[agent_id] = finops\n        return finops\n\n    def fleet_budget_status(self) -> dict:\n        \"\"\"Get budget status for all managed agents.\"\"\"\n        statuses = {}\n        for agent_id, finops in self.agents.items():\n            budget = finops.get_budget_status()\n            balance = finops.get_balance()\n            statuses[agent_id] = {\n                \"spent_today\": budget.get(\"spent_today\"),\n                \"daily_limit\": budget.get(\"daily_limit\"),\n                \"balance\": balance.get(\"balance\"),\n            }\n        return statuses\n\n    def emergency_stop(self, agent_id: str, key_id: str):\n        \"\"\"Emergency: revoke an agent's API key to halt spending.\"\"\"\n        finops = self.agents.get(agent_id)\n        if finops:\n            finops.rotate_api_key(key_id=key_id)\n            print(f\"EMERGENCY STOP: {agent_id} key revoked\")\n\n    def fleet_chargeback(\n        self,\n        team_map: dict[str, list[str]],\n    ) -> dict:\n        \"\"\"Generate chargeback by team.\"\"\"\n        report = {}\n        for team, ids in team_map.items():\n            total = 0.0\n            for agent_id in ids:\n                if agent_id in self.agents:\n                    summary = self.agents[agent_id].get_billing_summary()\n                    total += float(summary.get(\"total_cost\", 0))\n            report[team] = round(total, 2)\n        return report\n\n    def rotate_all_keys(self, key_map: dict[str, str]):\n        \"\"\"Rotate API keys for all agents. key_map: {agent_id: key_id}.\"\"\"\n        for agent_id, key_id in key_map.items():\n            if agent_id in self.agents:\n                self.agents[agent_id].rotate_api_key(key_id=key_id)\n                print(f\"Rotated key for {agent_id}\")\n\n\n# ── Usage ────────────────────────────────────────────────────────\n\ncp = FinOpsControlPlane(\n    api_key=API_KEY,\n    alert_base_url=\"https:\u002F\u002Fyour-app.example.com\u002Falerts\",\n)\n\n# Provision the fleet\ncp.provision_agent(\"orch-01\",  deposit=200, daily_cap=80,  monthly_cap=1600)\ncp.provision_agent(\"res-01\",   deposit=75,  daily_cap=30,  monthly_cap=600)\ncp.provision_agent(\"res-02\",   deposit=75,  daily_cap=30,  monthly_cap=600)\ncp.provision_agent(\"sum-01\",   deposit=50,  daily_cap=20,  monthly_cap=400)\ncp.provision_agent(\"cls-01\",   deposit=40,  daily_cap=15,  monthly_cap=300)\n\n# Daily status check\nstatus = cp.fleet_budget_status()\nfor agent_id, s in status.items():\n    print(f\"  {agent_id}: spent=${s['spent_today']}, balance=${s['balance']}\")\n\n# Monthly chargeback\nchargeback = cp.fleet_chargeback({\n    \"research-team\": [\"res-01\", \"res-02\"],\n    \"processing-team\": [\"sum-01\", \"cls-01\"],\n    \"platform-team\": [\"orch-01\"],\n})\nfor team, cost in chargeback.items():\n    print(f\"  {team}: ${cost:.2f}\")\n```\n\n### Production Checklist\n\nBefore deploying your FinOps control plane to production, verify every item on this list.\n\n**Wallet Isolation**\n\n- [ ] Every agent has its own wallet. No shared wallets.\n- [ ] Orchestrator agents that fund workers have a documented funding budget per task type.\n- [ ] Initial deposit amounts are based on expected 7-day spend plus 30% buffer.\n\n**Budget Caps**\n\n- [ ] Every agent has a `set_budget_cap` with both daily and monthly limits.\n- [ ] Daily limits are set to the maximum reasonable daily spend for that agent's role, not the wallet balance.\n- [ ] Your code handles `402 Payment Required` as a `BudgetExhaustedError` with a graceful shutdown path, not a retry.\n- [ ] Workflow-level budget caps use dedicated per-workflow agent IDs.\n\n**Spend Alerts**\n\n- [ ] Every agent has webhook alerts at 75%, 90%, and 100% of daily budget.\n- [ ] The alert receiver endpoint is monitored for uptime (if it is down, you get no alerts).\n- [ ] Critical alerts (90%+) trigger PagerDuty or equivalent on-call notification.\n- [ ] The 100% alert triggers an automatic agent pause or key revocation.\n- [ ] `get_webhook_logs` is checked weekly to verify alert delivery.\n\n**Cost Attribution**\n\n- [ ] `get_spending_by_category` is pulled daily for each agent.\n- [ ] Monthly chargeback reports are generated and sent to team leads.\n- [ ] Historical spend data from `get_usage_analytics` is stored in your data warehouse for trend analysis.\n\n**Cost Optimization**\n\n- [ ] `estimate_cost` is called before expensive tool executions.\n- [ ] `get_volume_discount` is checked monthly; agents are consolidated if it improves tier eligibility.\n- [ ] Multi-currency costs are normalized to a single reporting currency.\n\n**API Key Security**\n\n- [ ] Every agent has its own API key with scoped permissions.\n- [ ] Key rotation runs weekly as an automated job.\n- [ ] The emergency key revocation procedure is documented and tested quarterly.\n- [ ] API keys are stored in a secrets manager, never in code or environment files.\n\n**Fleet Monitoring**\n\n- [ ] The daily FinOps dashboard runs automatically each morning.\n- [ ] The cost-efficiency leaderboard is reviewed weekly to identify underperforming agents.\n- [ ] `get_platform_stats` is tracked over time to detect fleet-wide cost anomalies.\n- [ ] Week-over-week spend comparison is reviewed for every agent with >$10\u002Fday average spend.\n\n**Incident Response**\n\n- [ ] A runbook exists for \"runaway agent spend\" incidents: detect via webhook, diagnose via `get_spending_by_category`, stop via key revocation, postmortem via `get_usage_analytics`.\n- [ ] The emergency stop procedure (revoke API key) is executable by any on-call engineer.\n- [ ] Post-incident, the budget cap for the affected agent is reviewed and tightened if necessary.\n\n---\n\n## Chapter 10: What to Do Next\n\n### Advanced Pattern: Dynamic Budget Reallocation\n\nIn a fleet with a fixed total budget, idle agents waste allocated capacity while busy agents hit their caps. Dynamic reallocation moves budget from idle agents to active ones in real time.\n\n```python\ndef rebalance_fleet_budgets(\n    control_plane: FinOpsControlPlane,\n    fleet_daily_budget: float,\n):\n    \"\"\"Dynamically reallocate daily budgets based on current utilization.\"\"\"\n    statuses = control_plane.fleet_budget_status()\n\n    # Calculate utilization for each agent\n    utilizations = {}\n    for agent_id, s in statuses.items():\n        cap = float(s.get(\"daily_limit\", 1))\n        spent = float(s.get(\"spent_today\", 0))\n        utilizations[agent_id] = spent \u002F cap if cap > 0 else 0\n\n    # Agents under 30% utilization donate budget to agents over 80%\n    donors = {k: v for k, v in utilizations.items() if v \u003C 0.30}\n    receivers = {k: v for k, v in utilizations.items() if v > 0.80}\n\n    if not donors or not receivers:\n        print(\"No rebalancing needed.\")\n        return\n\n    # Calculate redistributable budget\n    redistributable = 0.0\n    for agent_id in donors:\n        cap = float(statuses[agent_id][\"daily_limit\"])\n        spent = float(statuses[agent_id][\"spent_today\"])\n        donatable = (cap - spent) * 0.5  # Donate half of unused budget\n        redistributable += donatable\n\n    # Distribute evenly to receivers\n    per_receiver = redistributable \u002F len(receivers)\n    for agent_id in receivers:\n        finops = control_plane.agents[agent_id]\n        current_cap = float(statuses[agent_id][\"daily_limit\"])\n        new_cap = current_cap + per_receiver\n        finops.set_budget_cap(daily_limit=new_cap)\n        print(\n            f\"  {agent_id}: cap raised from ${current_cap:.2f} \"\n            f\"to ${new_cap:.2f} (+${per_receiver:.2f})\"\n        )\n\n    # Reduce donor caps\n    per_donor_reduction = redistributable \u002F len(donors)\n    for agent_id in donors:\n        finops = control_plane.agents[agent_id]\n        current_cap = float(statuses[agent_id][\"daily_limit\"])\n        new_cap = max(current_cap - per_donor_reduction, 5.00)  # Minimum $5\n        finops.set_budget_cap(daily_limit=new_cap)\n        print(\n            f\"  {agent_id}: cap lowered from ${current_cap:.2f} \"\n            f\"to ${new_cap:.2f}\"\n        )\n```\n\n### Advanced Pattern: Cost-Aware Workflow Routing\n\nInstead of always routing to the same set of agents, pick the workflow path that minimizes cost while meeting quality constraints.\n\n```python\ndef cost_aware_workflow_route(\n    control_plane: FinOpsControlPlane,\n    task: dict,\n) -> list[str]:\n    \"\"\"Pick the cheapest agent path for a workflow task.\"\"\"\n    capable_agents = task[\"capable_agents\"]  # List of agent IDs\n    quality_floor = task.get(\"quality_floor\", 0.8)\n\n    # Score each candidate by remaining budget and efficiency\n    candidates = []\n    for agent_id in capable_agents:\n        if agent_id not in control_plane.agents:\n            continue\n        finops = control_plane.agents[agent_id]\n\n        budget = finops.get_budget_status()\n        remaining = (\n            float(budget.get(\"daily_limit\", 0))\n            - float(budget.get(\"spent_today\", 0))\n        )\n\n        estimate = finops.estimate_cost(\n            tool_name=task[\"tool\"],\n            parameters=task[\"params\"],\n        )\n        cost = float(estimate.get(\"estimated_cost\", float(\"inf\")))\n\n        if cost \u003C= remaining:\n            candidates.append({\n                \"agent_id\": agent_id,\n                \"cost\": cost,\n                \"remaining_budget\": remaining,\n            })\n\n    # Sort by cost, then by remaining budget (prefer agents with more headroom)\n    candidates.sort(key=lambda c: (c[\"cost\"], -c[\"remaining_budget\"]))\n\n    if candidates:\n        chosen = candidates[0][\"agent_id\"]\n        print(\n            f\"Routing to {chosen} \"\n            f\"(cost=${candidates[0]['cost']:.4f}, \"\n            f\"${candidates[0]['remaining_budget']:.2f} remaining)\"\n        )\n        return [chosen]\n\n    raise RuntimeError(\"No agent can afford this task within budget\")\n```\n\n### Building a SaaS Billing Layer\n\nIf you are building a platform where customers deploy their own agent fleets, you can build a multi-tenant billing layer on top of GreenHelix. The pattern: each customer gets a top-level orchestrator agent that funds and manages their fleet. Your platform charges the customer based on their fleet's total spend via `get_billing_summary`, applying your own markup.\n\n```python\ndef customer_invoice(\n    api_key: str,\n    customer_id: str,\n    customer_agents: list[str],\n    markup_pct: float = 20.0,\n) -> dict:\n    \"\"\"Generate an invoice for a customer based on their fleet spend.\"\"\"\n    total_platform_cost = 0.0\n    line_items = []\n\n    for agent_id in customer_agents:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        summary = finops.get_billing_summary(period=\"monthly\")\n        cost = float(summary.get(\"total_cost\", 0))\n        total_platform_cost += cost\n        line_items.append({\n            \"agent_id\": agent_id,\n            \"platform_cost\": round(cost, 2),\n            \"calls\": summary.get(\"total_calls\", 0),\n        })\n\n    markup = total_platform_cost * (markup_pct \u002F 100)\n    total_invoice = total_platform_cost + markup\n\n    return {\n        \"customer_id\": customer_id,\n        \"period\": \"April 2026\",\n        \"line_items\": line_items,\n        \"platform_cost\": round(total_platform_cost, 2),\n        \"markup_pct\": markup_pct,\n        \"markup_amount\": round(markup, 2),\n        \"total_invoice\": round(total_invoice, 2),\n    }\n```\n\n### Where This Guide Fits in the GreenHelix Ecosystem\n\nThis guide covers budget enforcement, cost allocation, and spend analytics -- the FinOps layer. For the other layers of agent commerce infrastructure, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** -- the foundational guide covering wallet setup, escrow patterns (standard, performance, split), marketplace discovery, subscriptions, dispute resolution, and framework integration with CrewAI, LangChain, and AutoGen.\n- **The Agent Strategy Marketplace Playbook** -- how to sell verified trading strategies with performance escrow, including metric submission pipelines, claim chains, and pricing tiers.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains, covering the trust score algorithm and leaderboard mechanics.\n- **Tamper-Proof Audit Trails for Trading Bots** -- EU AI Act, MiFID II, and SEC compliance using GreenHelix's event bus and Merkle audit chains.\n\nFor the full API reference and tool catalog (all 128 tools, including the 23 billing and webhook tools covered in this guide), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\nFor updates on the FinOps Foundation's \"FinOps for AI\" initiative and how GreenHelix aligns with their emerging standards for AI cost governance, follow the FinOps Foundation at [finops.org](https:\u002F\u002Fwww.finops.org\u002F).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n","# The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems\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> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nWhen a CrewAI orchestrator spawns five researcher agents, each calling GPT-4o at $0.005 per request, and one agent enters a retry loop that fires 12,000 requests in an hour, who gets the bill? When a LangGraph workflow fans out to eight parallel tool-calling agents across three cloud providers, how does the platform team attribute $2,400 in daily compute back to the workflow that caused it? When a production AutoGen group chat quietly doubles its tool-call volume over three weeks because a prompt change removed a termination condition, who notices before the monthly invoice arrives? These are not hypothetical problems. A March 2026 postmortem from an AI infrastructure startup revealed that a single misconfigured agent loop consumed $47,000 in API credits over a weekend -- with no alert, no budget cap, and no way to attribute the cost to a specific agent. The FinOps Foundation's \"FinOps for AI\" initiative, launched in January 2026, identified cost governance for autonomous agents as one of the top three unsolved problems in AI infrastructure economics. This guide solves it. Using the GreenHelix A2A Commerce Gateway's 23 billing and webhook tools, you will build a complete FinOps control plane: per-agent wallets with hard budget caps, real-time spend alerts, cost attribution by agent and workflow, volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary. Every pattern is production-ready, backed by working Python code, and deployable today.\nBefore diving into the full guide, here is the minimum viable FinOps setup: one agent, one wallet, one budget cap, one alert. This takes under two minutes.\n```python\n\n## What You'll Learn\n- Quick Start\n- Chapter 1: The Multi-Agent Cost Problem\n- Chapter 2: Per-Agent Wallet Provisioning\n- Chapter 3: Budget Caps and Hard Stops\n- Chapter 4: Real-Time Spend Alerts with Webhooks\n- Chapter 5: Cost Attribution and Category Spend\n- Chapter 6: Volume Discounts and Cost Optimization\n- Chapter 7: Fleet Dashboards and Leaderboards\n- Chapter 8: API Key Isolation and Security\n- Chapter 9: Putting It All Together: The FinOps Control Plane\n\n## Full Guide\n\n# The AI Agent FinOps Playbook: Budget Enforcement, Cost Allocation & Spend Analytics for Multi-Agent Systems\n\nWhen a CrewAI orchestrator spawns five researcher agents, each calling GPT-4o at $0.005 per request, and one agent enters a retry loop that fires 12,000 requests in an hour, who gets the bill? When a LangGraph workflow fans out to eight parallel tool-calling agents across three cloud providers, how does the platform team attribute $2,400 in daily compute back to the workflow that caused it? When a production AutoGen group chat quietly doubles its tool-call volume over three weeks because a prompt change removed a termination condition, who notices before the monthly invoice arrives? These are not hypothetical problems. A March 2026 postmortem from an AI infrastructure startup revealed that a single misconfigured agent loop consumed $47,000 in API credits over a weekend -- with no alert, no budget cap, and no way to attribute the cost to a specific agent. The FinOps Foundation's \"FinOps for AI\" initiative, launched in January 2026, identified cost governance for autonomous agents as one of the top three unsolved problems in AI infrastructure economics. This guide solves it. Using the GreenHelix A2A Commerce Gateway's 23 billing and webhook tools, you will build a complete FinOps control plane: per-agent wallets with hard budget caps, real-time spend alerts, cost attribution by agent and workflow, volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary. Every pattern is production-ready, backed by working Python code, and deployable today.\n\n---\n\n## Quick Start\n\nBefore diving into the full guide, here is the minimum viable FinOps setup: one agent, one wallet, one budget cap, one alert. This takes under two minutes.\n\n```python\nfrom greenhelix_trading import AgentFinOps\nimport os\n\n# Initialize the FinOps client for a single agent\nfinops = AgentFinOps(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"research-agent-01\",\n    base_url=\"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n)\n\n# 1. Create an isolated wallet\nfinops.create_wallet()\n\n# 2. Fund it\nfinops.deposit(amount=100.00)\n\n# 3. Set a hard daily budget cap\nfinops.set_budget_cap(daily_limit=25.00, monthly_limit=500.00)\n\n# 4. Register an alert at 75% spend\nfinops.register_webhook(\n    url=\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fbudget\",\n    events=[\"budget.threshold\"],\n    config={\"threshold_pct\": 75},\n)\n\n# 5. Check balance before any operation\nbalance = finops.get_balance()\nprint(f\"Agent research-agent-01 ready. Balance: ${balance['balance']}\")\n```\n\nThat is five API calls. Your agent now has an isolated wallet, a $25\u002Fday hard stop, and an alert that fires when 75% of the daily budget is consumed. The rest of this guide builds on this foundation.\n\n---\n\n## Table of Contents\n\n1. [The Multi-Agent Cost Problem](#chapter-1-the-multi-agent-cost-problem)\n2. [Per-Agent Wallet Provisioning](#chapter-2-per-agent-wallet-provisioning)\n3. [Budget Caps and Hard Stops](#chapter-3-budget-caps-and-hard-stops)\n4. [Real-Time Spend Alerts with Webhooks](#chapter-4-real-time-spend-alerts-with-webhooks)\n5. [Cost Attribution and Category Spend](#chapter-5-cost-attribution-and-category-spend)\n6. [Volume Discounts and Cost Optimization](#chapter-6-volume-discounts-and-cost-optimization)\n7. [Fleet Dashboards and Leaderboards](#chapter-7-fleet-dashboards-and-leaderboards)\n8. [API Key Isolation and Security](#chapter-8-api-key-isolation-and-security)\n9. [Putting It All Together: The FinOps Control Plane](#chapter-9-putting-it-all-together-the-finops-control-plane)\n10. [What to Do Next](#chapter-10-what-to-do-next)\n\n---\n\n## Chapter 1: The Multi-Agent Cost Problem\n\n### Why Autonomous Agents Create Unbounded Cost\n\nHuman engineers have an implicit cost governor: they get tired, they context-switch, they go home at 6 PM. Agents do not. A LangChain agent with access to a tool catalog will call tools as long as its reasoning loop tells it to. A CrewAI crew that delegates subtasks to specialist agents will spawn as many subtasks as the orchestrator deems necessary. An AutoGen group chat will continue conversing until a termination condition is met -- and if that condition has a bug, the conversation runs forever. Each tool call, each LLM inference, each API request costs money. Without explicit cost governance, the spend trajectory of a multi-agent system is bounded only by the rate limit of the underlying API provider.\n\n### Three Failure Modes\n\nEvery multi-agent cost incident traces back to one of three root causes.\n\n**Failure Mode 1: Runaway Loops.** An agent enters a retry or reasoning loop that never terminates. The most common trigger is a tool that returns an error, causing the agent to retry indefinitely. A single agent in a retry loop against GPT-4o can consume $50-200\u002Fhour depending on context window size. Without a per-agent budget cap, there is no circuit breaker.\n\n**Failure Mode 2: Tool-Call Amplification.** An orchestrator agent delegates a task to N worker agents, each of which calls M tools, each of which triggers K downstream API calls. The total cost is O(N * M * K), and small changes to any multiplier produce large cost swings. A prompt change that causes each worker to call one additional tool per task can double fleet-wide spend overnight.\n\n**Failure Mode 3: No Attribution.** All agents share a single API key and a single billing account. When the monthly bill spikes, there is no way to determine which agent, which workflow, or which tool category caused the increase. Without attribution, there is no accountability, and without accountability, there is no optimization.\n\n### The Wallet-Per-Agent Architecture\n\nThe GreenHelix approach solves all three failure modes with a single architectural pattern: every agent gets its own wallet with its own budget cap. This is the same principle as giving each microservice its own database -- isolation prevents blast radius propagation.\n\n```\n+-------------------+     +-------------------+     +-------------------+\n| Agent: researcher |     | Agent: summarizer |     | Agent: classifier |\n| Wallet: $100      |     | Wallet: $50       |     | Wallet: $75       |\n| Cap: $25\u002Fday      |     | Cap: $15\u002Fday      |     | Cap: $20\u002Fday      |\n| Key: ak_res_xxxxx |     | Key: ak_sum_xxxxx |     | Key: ak_cls_xxxxx |\n+--------+----------+     +--------+----------+     +--------+----------+\n         |                         |                         |\n         +------------+------------+------------+------------+\n                      |                         |\n              +-------v-------------------------v-------+\n              |     GreenHelix A2A Commerce Gateway      |\n              |     Budget enforcement layer             |\n              |     Cost attribution engine              |\n              |     Webhook alert system                 |\n              +------------------------------------------+\n```\n\nWhen the researcher agent hits its $25\u002Fday cap, it gets a `402 Payment Required` response. The summarizer and classifier agents are unaffected. The blast radius of a runaway researcher is exactly $25 -- not the entire fleet budget.\n\n### The AgentFinOps Class\n\nThis class wraps every GreenHelix billing and webhook tool used in this guide. Define it once; reference it in every subsequent chapter.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional\n\n\nclass AgentFinOps:\n    \"\"\"FinOps client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 23 billing and webhook tools into a clean interface\n    for budget enforcement, cost allocation, and spend analytics.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} has exceeded its budget cap. \"\n                f\"Response: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Wallet Management -------------------------------------------\n\n    def create_wallet(self) -> dict:\n        return self._execute(\"create_wallet\", {})\n\n    def get_balance(self) -> dict:\n        return self._execute(\"get_balance\", {})\n\n    def deposit(self, amount: float) -> dict:\n        return self._execute(\"deposit\", {\"amount\": str(amount)})\n\n    # -- Budget Enforcement ------------------------------------------\n\n    def set_budget_cap(\n        self,\n        daily_limit: float,\n        monthly_limit: Optional[float] = None,\n    ) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": str(daily_limit),\n        }\n        if monthly_limit is not None:\n            payload[\"monthly_limit\"] = str(monthly_limit)\n        return self._execute(\"set_budget_cap\", payload)\n\n    def get_budget_status(self) -> dict:\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    # -- Cost Analytics ----------------------------------------------\n\n    def get_usage_analytics(\n        self,\n        start_date: str,\n        end_date: str,\n    ) -> dict:\n        return self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"start_date\": start_date,\n            \"end_date\": end_date,\n        })\n\n    def get_billing_summary(self, period: str = \"monthly\") -> dict:\n        return self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def get_spending_by_category(\n        self,\n        start_date: Optional[str] = None,\n        end_date: Optional[str] = None,\n    ) -> dict:\n        payload = {\"agent_id\": self.agent_id}\n        if start_date:\n            payload[\"start_date\"] = start_date\n        if end_date:\n            payload[\"end_date\"] = end_date\n        return self._execute(\"get_spending_by_category\", payload)\n\n    # -- Cost Optimization -------------------------------------------\n\n    def get_volume_discount(self) -> dict:\n        return self._execute(\"get_volume_discount\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def estimate_cost(self, tool_name: str, parameters: dict) -> dict:\n        return self._execute(\"estimate_cost\", {\n            \"tool\": tool_name,\n            \"parameters\": parameters,\n        })\n\n    def convert_currency(\n        self,\n        amount: float,\n        from_currency: str,\n        to_currency: str,\n    ) -> dict:\n        return self._execute(\"convert_currency\", {\n            \"amount\": str(amount),\n            \"from_currency\": from_currency,\n            \"to_currency\": to_currency,\n        })\n\n    # -- Fleet Analytics ---------------------------------------------\n\n    def get_agent_leaderboard(self, metric: str = \"cost_efficiency\") -> dict:\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def get_platform_stats(self) -> dict:\n        return self._execute(\"get_platform_stats\", {})\n\n    # -- API Key Management ------------------------------------------\n\n    def create_api_key(self, label: str, permissions: list = None) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"label\": label,\n        }\n        if permissions:\n            payload[\"permissions\"] = permissions\n        return self._execute(\"create_api_key\", payload)\n\n    def rotate_api_key(self, key_id: str) -> dict:\n        return self._execute(\"rotate_api_key\", {\n            \"agent_id\": self.agent_id,\n            \"key_id\": key_id,\n        })\n\n    # -- Webhooks ----------------------------------------------------\n\n    def register_webhook(\n        self,\n        url: str,\n        events: list,\n        config: Optional[dict] = None,\n    ) -> dict:\n        payload = {\n            \"agent_id\": self.agent_id,\n            \"url\": url,\n            \"events\": events,\n        }\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"register_webhook\", payload)\n\n    def list_webhooks(self) -> dict:\n        return self._execute(\"list_webhooks\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def update_webhook(\n        self,\n        webhook_id: str,\n        url: Optional[str] = None,\n        events: Optional[list] = None,\n        config: Optional[dict] = None,\n    ) -> dict:\n        payload = {\"webhook_id\": webhook_id}\n        if url:\n            payload[\"url\"] = url\n        if events:\n            payload[\"events\"] = events\n        if config:\n            payload[\"config\"] = config\n        return self._execute(\"update_webhook\", payload)\n\n    def delete_webhook(self, webhook_id: str) -> dict:\n        return self._execute(\"delete_webhook\", {\n            \"webhook_id\": webhook_id,\n        })\n\n    def get_webhook_logs(\n        self,\n        webhook_id: str,\n        limit: int = 50,\n    ) -> dict:\n        return self._execute(\"get_webhook_logs\", {\n            \"webhook_id\": webhook_id,\n            \"limit\": limit,\n        })\n\n\nclass BudgetExhaustedError(Exception):\n    \"\"\"Raised when an agent exceeds its budget cap (HTTP 402).\"\"\"\n    pass\n```\n\n---\n\n## Chapter 2: Per-Agent Wallet Provisioning\n\n### Why One Wallet Per Agent\n\nShared wallets are the multi-agent equivalent of running all your microservices as root. When five agents share a wallet, a runaway agent drains funds that other agents need. There is no spend attribution, no blast radius containment, and no way to set different budget policies for agents with different risk profiles.\n\nThe rule is simple: every agent that can incur cost gets its own wallet. The orchestrator agent gets a wallet. Each worker agent gets a wallet. If the orchestrator funds worker wallets as part of task delegation, the funding amount becomes an explicit cost parameter of the task -- visible, auditable, and capped.\n\n### Creating Wallets for a Fleet\n\n```python\nimport os\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\n\n# Define your agent fleet\nfleet = [\n    {\"agent_id\": \"orchestrator-01\", \"initial_deposit\": 500.00},\n    {\"agent_id\": \"researcher-01\",   \"initial_deposit\": 100.00},\n    {\"agent_id\": \"researcher-02\",   \"initial_deposit\": 100.00},\n    {\"agent_id\": \"summarizer-01\",   \"initial_deposit\": 75.00},\n    {\"agent_id\": \"classifier-01\",   \"initial_deposit\": 50.00},\n]\n\nfor agent_cfg in fleet:\n    finops = AgentFinOps(\n        api_key=API_KEY,\n        agent_id=agent_cfg[\"agent_id\"],\n    )\n\n    # Create wallet\n    wallet = finops.create_wallet()\n    print(f\"Wallet created for {agent_cfg['agent_id']}: {wallet['wallet_id']}\")\n\n    # Fund it\n    deposit = finops.deposit(amount=agent_cfg[\"initial_deposit\"])\n    print(f\"  Deposited ${agent_cfg['initial_deposit']:.2f}\")\n\n    # Verify balance\n    balance = finops.get_balance()\n    print(f\"  Balance: ${balance['balance']}\")\n```\n\n### Pre-Flight Cost Estimation\n\nBefore an agent executes an expensive tool call, estimate the cost and compare it against the remaining budget. This prevents the agent from starting work it cannot afford to finish.\n\n```python\ndef preflight_check(finops: AgentFinOps, tool_name: str, params: dict) -> bool:\n    \"\"\"Check if the agent can afford a tool call before executing it.\"\"\"\n    # Estimate the cost of the upcoming operation\n    estimate = finops.estimate_cost(tool_name=tool_name, parameters=params)\n    estimated_cost = float(estimate.get(\"estimated_cost\", 0))\n\n    # Check remaining budget\n    budget = finops.get_budget_status()\n    remaining_daily = (\n        float(budget.get(\"daily_limit\", 0))\n        - float(budget.get(\"spent_today\", 0))\n    )\n\n    # Check wallet balance\n    balance = finops.get_balance()\n    wallet_balance = float(balance.get(\"balance\", 0))\n\n    # Both budget and balance must be sufficient\n    can_afford = (\n        estimated_cost \u003C= remaining_daily\n        and estimated_cost \u003C= wallet_balance\n    )\n\n    if not can_afford:\n        print(\n            f\"Pre-flight FAIL: {tool_name} costs ~${estimated_cost:.4f}, \"\n            f\"daily remaining=${remaining_daily:.2f}, \"\n            f\"wallet=${wallet_balance:.2f}\"\n        )\n    return can_afford\n\n\n# Usage in an agent loop\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\ntasks = [\n    (\"search_services\", {\"query\": \"document summarization\"}),\n    (\"create_escrow\", {\"amount\": \"25.00\", \"payee\": \"summarizer-01\"}),\n    (\"submit_metrics\", {\"metrics\": {\"accuracy\": 0.95}}),\n]\n\nfor tool_name, params in tasks:\n    if preflight_check(finops, tool_name, params):\n        result = finops._execute(tool_name, params)\n        print(f\"  Executed {tool_name}: OK\")\n    else:\n        print(f\"  Skipped {tool_name}: insufficient budget\")\n        break  # Stop the workflow, do not accumulate partial state\n```\n\n### Funding Workflows: Orchestrator-to-Worker Deposits\n\nIn many architectures, the orchestrator agent funds worker agents as part of task assignment. This creates an explicit cost boundary around each task.\n\n```python\ndef fund_worker_for_task(\n    orchestrator: AgentFinOps,\n    worker_agent_id: str,\n    task_budget: float,\n    api_key: str,\n) -> AgentFinOps:\n    \"\"\"Fund a worker agent's wallet for a specific task.\"\"\"\n    worker = AgentFinOps(\n        api_key=api_key,\n        agent_id=worker_agent_id,\n    )\n\n    # Estimate worker's current balance\n    balance = worker.get_balance()\n    current = float(balance.get(\"balance\", 0))\n\n    # Top up only what is needed\n    if current \u003C task_budget:\n        shortfall = task_budget - current\n        worker.deposit(amount=shortfall)\n        print(\n            f\"Funded {worker_agent_id}: +${shortfall:.2f} \"\n            f\"(new balance: ${task_budget:.2f})\"\n        )\n\n    # Set a tight budget cap for this task\n    worker.set_budget_cap(daily_limit=task_budget)\n    return worker\n\n\n# Orchestrator delegates a research task with a $15 budget\norchestrator = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\nworker = fund_worker_for_task(\n    orchestrator=orchestrator,\n    worker_agent_id=\"researcher-01\",\n    task_budget=15.00,\n    api_key=API_KEY,\n)\n```\n\n---\n\n## Chapter 3: Budget Caps and Hard Stops\n\n### Per-Agent Budget Caps\n\nBudget caps are the most important cost governance primitive. When an agent exceeds its cap, the gateway returns `402 Payment Required` on the next tool call. The agent's code catches this as a `BudgetExhaustedError` and can implement any fail-fast behavior: log the event, notify the orchestrator, gracefully terminate, or queue the remaining work for the next budget cycle.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Set daily and monthly caps\nfinops.set_budget_cap(daily_limit=25.00, monthly_limit=500.00)\n\n# Verify the cap is active\nstatus = finops.get_budget_status()\nprint(f\"Daily limit:   ${status['daily_limit']}\")\nprint(f\"Monthly limit: ${status['monthly_limit']}\")\nprint(f\"Spent today:   ${status['spent_today']}\")\nprint(f\"Spent this month: ${status['spent_this_month']}\")\n```\n\n**curl -- set budget cap:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"set_budget_cap\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"daily_limit\": \"25.00\",\n      \"monthly_limit\": \"500.00\"\n    }\n  }'\n```\n\n### Per-Workflow Budget Caps\n\nSometimes you need a budget cap on a workflow, not just an individual agent. The pattern: create a dedicated agent ID per workflow run, give it a wallet with exactly the workflow budget, and route all tool calls through it.\n\n```python\nimport uuid\nfrom datetime import datetime, timezone\n\n\ndef create_workflow_budget(\n    api_key: str,\n    workflow_name: str,\n    budget: float,\n) -> AgentFinOps:\n    \"\"\"Create a budget-capped agent for a single workflow run.\"\"\"\n    run_id = uuid.uuid4().hex[:8]\n    workflow_agent_id = f\"wf-{workflow_name}-{run_id}\"\n\n    finops = AgentFinOps(\n        api_key=api_key,\n        agent_id=workflow_agent_id,\n    )\n\n    finops.create_wallet()\n    finops.deposit(amount=budget)\n    finops.set_budget_cap(daily_limit=budget)  # Entire budget as one-shot\n\n    print(\n        f\"Workflow {workflow_name} ({run_id}): \"\n        f\"${budget:.2f} budget allocated\"\n    )\n    return finops\n\n\n# Create a $50 budget for a research workflow\nwf_finops = create_workflow_budget(\n    api_key=API_KEY,\n    workflow_name=\"quarterly-report\",\n    budget=50.00,\n)\n```\n\n### Handling 402 Payment Required\n\nWhen the budget cap is hit, the gateway returns HTTP 402. Your agent code must handle this gracefully -- not with a retry, but with a controlled shutdown.\n\n```python\ndef safe_execute(finops: AgentFinOps, tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a tool with budget-aware error handling.\"\"\"\n    try:\n        return finops._execute(tool, input_data)\n    except BudgetExhaustedError:\n        # Log the budget exhaustion event\n        print(\n            f\"BUDGET EXHAUSTED: Agent {finops.agent_id} hit cap \"\n            f\"while calling {tool}. Stopping execution.\"\n        )\n        # Return a sentinel that the calling code can check\n        return {\"error\": \"budget_exhausted\", \"tool\": tool}\n    except requests.exceptions.HTTPError as e:\n        if e.response.status_code == 429:\n            # Rate limited -- back off and retry\n            time.sleep(2)\n            return finops._execute(tool, input_data)\n        raise\n\n\n# Agent loop with budget-aware execution\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\nfor i in range(100):  # Agent might try 100 tool calls\n    result = safe_execute(finops, \"search_services\", {\"query\": f\"topic-{i}\"})\n    if result.get(\"error\") == \"budget_exhausted\":\n        print(f\"Stopped at iteration {i}. Budget exhausted.\")\n        break\n    # Process result normally\n```\n\n### Setting Budget Caps Across a Fleet\n\n```python\n# Define tiered budget policies\nBUDGET_TIERS = {\n    \"orchestrator\": {\"daily\": 100.00, \"monthly\": 2000.00},\n    \"researcher\":   {\"daily\": 25.00,  \"monthly\": 500.00},\n    \"summarizer\":   {\"daily\": 15.00,  \"monthly\": 300.00},\n    \"classifier\":   {\"daily\": 10.00,  \"monthly\": 200.00},\n}\n\ndef apply_fleet_budget_policy(api_key: str, agents: list[dict]):\n    \"\"\"Apply budget caps to all agents based on their role tier.\"\"\"\n    for agent in agents:\n        role = agent[\"role\"]\n        tier = BUDGET_TIERS.get(role)\n        if not tier:\n            print(f\"WARNING: No budget tier for role '{role}'. Skipping.\")\n            continue\n\n        finops = AgentFinOps(api_key=api_key, agent_id=agent[\"agent_id\"])\n        finops.set_budget_cap(\n            daily_limit=tier[\"daily\"],\n            monthly_limit=tier[\"monthly\"],\n        )\n        print(\n            f\"  {agent['agent_id']} ({role}): \"\n            f\"${tier['daily']}\u002Fday, ${tier['monthly']}\u002Fmonth\"\n        )\n\n\nagents = [\n    {\"agent_id\": \"orchestrator-01\", \"role\": \"orchestrator\"},\n    {\"agent_id\": \"researcher-01\",   \"role\": \"researcher\"},\n    {\"agent_id\": \"researcher-02\",   \"role\": \"researcher\"},\n    {\"agent_id\": \"summarizer-01\",   \"role\": \"summarizer\"},\n    {\"agent_id\": \"classifier-01\",   \"role\": \"classifier\"},\n]\n\napply_fleet_budget_policy(API_KEY, agents)\n```\n\n---\n\n## Chapter 4: Real-Time Spend Alerts with Webhooks\n\n### Why Polling Is Not Enough\n\nChecking `get_budget_status` inside your agent loop works for pre-flight checks, but it misses spend that happens between checks. If your agent makes ten tool calls in rapid succession and the budget cap is hit on call seven, calls eight through ten fail with 402. Webhooks push alerts to your system the moment a threshold is crossed, enabling real-time escalation -- warn the team at 75%, pause the agent at 90%, kill it at 100%.\n\n### Registering Budget Threshold Alerts\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Register three escalation tiers\nalert_tiers = [\n    {\"threshold_pct\": 75, \"label\": \"warning\"},\n    {\"threshold_pct\": 90, \"label\": \"critical\"},\n    {\"threshold_pct\": 100, \"label\": \"exhausted\"},\n]\n\nwebhook_ids = []\nfor tier in alert_tiers:\n    webhook = finops.register_webhook(\n        url=f\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002F{tier['label']}\",\n        events=[\"budget.threshold\"],\n        config={\"threshold_pct\": tier[\"threshold_pct\"]},\n    )\n    webhook_ids.append(webhook[\"webhook_id\"])\n    print(\n        f\"Alert registered: {tier['label']} at {tier['threshold_pct']}% \"\n        f\"(webhook_id: {webhook['webhook_id']})\"\n    )\n```\n\n**curl -- register a webhook:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_webhook\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"url\": \"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fwarning\",\n      \"events\": [\"budget.threshold\"],\n      \"config\": {\"threshold_pct\": 75}\n    }\n  }'\n```\n\n### Building the Alert Receiver\n\nYour alert receiver is a simple HTTP endpoint that receives webhook payloads and dispatches escalation actions.\n\n```python\nfrom flask import Flask, request, jsonify\nimport logging\n\napp = Flask(__name__)\nlogger = logging.getLogger(\"finops_alerts\")\n\n\n@app.route(\"\u002Falerts\u002Fwarning\", methods=[\"POST\"])\ndef handle_warning():\n    \"\"\"75% budget consumed -- log and notify Slack.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n    spent_pct = payload.get(\"spent_pct\")\n    remaining = payload.get(\"remaining_budget\")\n\n    logger.warning(\n        f\"BUDGET WARNING: {agent_id} at {spent_pct}% \"\n        f\"(${remaining} remaining)\"\n    )\n    # Send Slack\u002FPagerDuty notification\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"Agent {agent_id} has consumed {spent_pct}% of its daily budget. \"\n                f\"${remaining} remaining.\",\n    )\n    return jsonify({\"status\": \"acknowledged\"})\n\n\n@app.route(\"\u002Falerts\u002Fcritical\", methods=[\"POST\"])\ndef handle_critical():\n    \"\"\"90% budget consumed -- pause the agent.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n\n    logger.critical(\n        f\"BUDGET CRITICAL: {agent_id} at {payload.get('spent_pct')}%. \"\n        f\"Pausing agent.\"\n    )\n    # Signal the agent to pause (via shared state, message queue, etc.)\n    pause_agent(agent_id)\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"CRITICAL: Agent {agent_id} paused at 90% budget.\",\n    )\n    return jsonify({\"status\": \"agent_paused\"})\n\n\n@app.route(\"\u002Falerts\u002Fexhausted\", methods=[\"POST\"])\ndef handle_exhausted():\n    \"\"\"100% budget consumed -- kill the agent process.\"\"\"\n    payload = request.json\n    agent_id = payload.get(\"agent_id\")\n\n    logger.error(\n        f\"BUDGET EXHAUSTED: {agent_id}. Terminating.\"\n    )\n    kill_agent(agent_id)\n    notify_slack(\n        channel=\"#agent-finops\",\n        message=f\"EXHAUSTED: Agent {agent_id} terminated. Budget fully consumed.\",\n    )\n    return jsonify({\"status\": \"agent_terminated\"})\n\n\ndef notify_slack(channel: str, message: str):\n    \"\"\"Send a Slack notification. Replace with your Slack webhook.\"\"\"\n    import requests as req\n    req.post(os.environ.get(\"SLACK_WEBHOOK_URL\", \"\"), json={\n        \"channel\": channel,\n        \"text\": message,\n    })\n\n\ndef pause_agent(agent_id: str):\n    \"\"\"Signal an agent to pause. Implementation depends on your runtime.\"\"\"\n    # Example: write a pause flag to Redis\n    # redis_client.set(f\"agent:{agent_id}:paused\", \"1\", ex=3600)\n    pass\n\n\ndef kill_agent(agent_id: str):\n    \"\"\"Terminate an agent process. Implementation depends on your runtime.\"\"\"\n    # Example: send SIGTERM to the agent's PID\n    # os.kill(agent_pids[agent_id], signal.SIGTERM)\n    pass\n```\n\n### Auditing Webhook Configuration\n\nBefore relying on webhooks in production, verify they are correctly configured.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# List all registered webhooks\nwebhooks = finops.list_webhooks()\nfor wh in webhooks.get(\"webhooks\", []):\n    print(\n        f\"  ID: {wh['webhook_id']} | URL: {wh['url']} | \"\n        f\"Events: {wh['events']} | Config: {wh.get('config', {})}\"\n    )\n```\n\n**curl -- list webhooks:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"list_webhooks\",\n    \"input\": {\"agent_id\": \"researcher-01\"}\n  }'\n```\n\n### Adjusting Thresholds Dynamically\n\nAs your fleet evolves, you may need to tighten or relax alert thresholds. Use `update_webhook` to adjust without deleting and re-creating.\n\n```python\n# Tighten the warning threshold from 75% to 60%\nfinops.update_webhook(\n    webhook_id=webhook_ids[0],\n    config={\"threshold_pct\": 60},\n)\nprint(\"Warning threshold tightened to 60%\")\n```\n\n### Debugging Missed Alerts\n\nWhen an alert should have fired but did not, check the webhook logs.\n\n```python\n# Inspect delivery history for a specific webhook\nlogs = finops.get_webhook_logs(webhook_id=webhook_ids[0], limit=20)\nfor entry in logs.get(\"logs\", []):\n    print(\n        f\"  {entry['timestamp']} | Status: {entry['delivery_status']} | \"\n        f\"HTTP {entry.get('response_code', 'N\u002FA')}\"\n    )\n```\n\n**curl -- get webhook logs:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_webhook_logs\",\n    \"input\": {\"webhook_id\": \"wh_abc123\", \"limit\": 20}\n  }'\n```\n\n### Cleaning Up Stale Webhooks\n\nWhen decommissioning an agent, remove its webhooks to prevent orphaned alert traffic.\n\n```python\ndef cleanup_agent_webhooks(finops: AgentFinOps):\n    \"\"\"Remove all webhooks for an agent being decommissioned.\"\"\"\n    webhooks = finops.list_webhooks()\n    for wh in webhooks.get(\"webhooks\", []):\n        finops.delete_webhook(wh[\"webhook_id\"])\n        print(f\"  Deleted webhook {wh['webhook_id']}\")\n```\n\n---\n\n## Chapter 5: Cost Attribution and Category Spend\n\n### Why Attribution Matters\n\nBudget caps prevent overspend. Attribution answers a different question: where is the money going? Without category-level spend data, you cannot optimize. You cannot answer \"which tool category consumes 60% of our budget?\" or \"which agent has the worst cost-per-task ratio?\" or \"did last week's prompt change increase or decrease total spend?\"\n\n### Tagging Spend by Agent, Workflow, and Tool\n\nGreenHelix tracks spend at the agent level natively. Every tool call executed by an agent is attributed to that agent's wallet. To get workflow-level attribution, use the dedicated workflow agent pattern from Chapter 3. To get tool-level attribution, use `get_spending_by_category`.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Get spend breakdown by tool category\ncategory_spend = finops.get_spending_by_category(\n    start_date=\"2026-04-01\",\n    end_date=\"2026-04-06\",\n)\n\nprint(\"Spend by category (April 1-6):\")\nfor category in category_spend.get(\"categories\", []):\n    print(\n        f\"  {category['category']:.\u003C30} \"\n        f\"${category['total_cost']:>8.2f}  \"\n        f\"({category['call_count']} calls)\"\n    )\n```\n\n**curl -- get spending by category:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_spending_by_category\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"start_date\": \"2026-04-01\",\n      \"end_date\": \"2026-04-06\"\n    }\n  }'\n```\n\n### Building Chargeback Reports\n\nIn organizations where different teams own different agents, chargebacks attribute platform costs to the team that caused them. This is standard FinOps practice for cloud infrastructure, adapted for multi-agent systems.\n\n```python\ndef generate_chargeback_report(\n    api_key: str,\n    team_agents: dict[str, list[str]],\n    period: str = \"monthly\",\n) -> dict:\n    \"\"\"Generate a chargeback report by team.\n\n    team_agents: {\"data-team\": [\"researcher-01\", \"researcher-02\"],\n                  \"ml-team\": [\"classifier-01\", \"summarizer-01\"]}\n    \"\"\"\n    report = {}\n    for team, agent_ids in team_agents.items():\n        team_total = 0.0\n        agent_details = []\n        for agent_id in agent_ids:\n            finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n            summary = finops.get_billing_summary(period=period)\n            agent_cost = float(summary.get(\"total_cost\", 0))\n            team_total += agent_cost\n            agent_details.append({\n                \"agent_id\": agent_id,\n                \"cost\": agent_cost,\n                \"tool_calls\": summary.get(\"total_calls\", 0),\n            })\n        report[team] = {\n            \"total_cost\": round(team_total, 2),\n            \"agents\": agent_details,\n        }\n    return report\n\n\n# Generate monthly chargeback\nchargeback = generate_chargeback_report(\n    api_key=API_KEY,\n    team_agents={\n        \"data-team\": [\"researcher-01\", \"researcher-02\"],\n        \"ml-team\": [\"classifier-01\", \"summarizer-01\"],\n        \"ops-team\": [\"orchestrator-01\"],\n    },\n)\n\nfor team, data in chargeback.items():\n    print(f\"\\n{team}: ${data['total_cost']:.2f}\")\n    for agent in data[\"agents\"]:\n        print(\n            f\"  {agent['agent_id']}: ${agent['cost']:.2f} \"\n            f\"({agent['tool_calls']} calls)\"\n        )\n```\n\n### Per-Agent P&L Statements\n\nFor agents that both spend and earn (e.g., a service agent that charges for its work), compute a per-agent profit and loss.\n\n```python\ndef agent_pnl(api_key: str, agent_id: str, period: str = \"monthly\") -> dict:\n    \"\"\"Compute profit and loss for an agent.\"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n\n    # Cost side: what the agent spent\n    summary = finops.get_billing_summary(period=period)\n    total_cost = float(summary.get(\"total_cost\", 0))\n\n    # Revenue side: what the agent earned (from usage analytics)\n    analytics = finops.get_usage_analytics(\n        start_date=summary.get(\"period_start\", \"2026-04-01\"),\n        end_date=summary.get(\"period_end\", \"2026-04-30\"),\n    )\n    total_revenue = float(analytics.get(\"revenue_earned\", 0))\n\n    return {\n        \"agent_id\": agent_id,\n        \"revenue\": round(total_revenue, 2),\n        \"cost\": round(total_cost, 2),\n        \"profit\": round(total_revenue - total_cost, 2),\n        \"margin_pct\": (\n            round((total_revenue - total_cost) \u002F total_revenue * 100, 1)\n            if total_revenue > 0 else 0.0\n        ),\n    }\n\n\n# Compute P&L for a service agent\npnl = agent_pnl(API_KEY, \"summarizer-01\")\nprint(\n    f\"Agent {pnl['agent_id']}: \"\n    f\"Revenue=${pnl['revenue']}, Cost=${pnl['cost']}, \"\n    f\"Profit=${pnl['profit']} ({pnl['margin_pct']}% margin)\"\n)\n```\n\n### Historical Spend Analysis\n\nUse `get_usage_analytics` for time-series spend data to identify trends, anomalies, and the impact of configuration changes.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Pull weekly analytics for the last 4 weeks\nweeks = [\n    (\"2026-03-09\", \"2026-03-15\"),\n    (\"2026-03-16\", \"2026-03-22\"),\n    (\"2026-03-23\", \"2026-03-29\"),\n    (\"2026-03-30\", \"2026-04-05\"),\n]\n\nprint(\"Weekly spend trend for researcher-01:\")\nfor start, end in weeks:\n    analytics = finops.get_usage_analytics(start_date=start, end_date=end)\n    cost = float(analytics.get(\"total_cost\", 0))\n    calls = analytics.get(\"total_calls\", 0)\n    print(f\"  {start} to {end}: ${cost:.2f} ({calls} calls)\")\n```\n\n---\n\n## Chapter 6: Volume Discounts and Cost Optimization\n\n### Checking Volume Discount Eligibility\n\nHigh-volume agents may qualify for automatic discounts based on cumulative usage. Check your current tier and what it takes to reach the next one.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\ndiscount = finops.get_volume_discount()\nprint(f\"Current tier:      {discount.get('current_tier')}\")\nprint(f\"Discount rate:     {discount.get('discount_pct')}%\")\nprint(f\"Monthly volume:    ${discount.get('monthly_volume')}\")\nprint(f\"Next tier at:      ${discount.get('next_tier_threshold')}\")\nprint(f\"Next tier discount: {discount.get('next_tier_discount_pct')}%\")\n```\n\n**curl -- check volume discount:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_volume_discount\",\n    \"input\": {\"agent_id\": \"orchestrator-01\"}\n  }'\n```\n\n### Pre-Execution Cost Estimation\n\nBefore choosing which tool to use for a task, estimate the cost of each option. This enables cost-aware routing: the orchestrator picks the cheapest tool that meets quality requirements.\n\n```python\ndef cheapest_tool(\n    finops: AgentFinOps,\n    candidates: list[dict],\n) -> dict:\n    \"\"\"Pick the cheapest tool from a list of candidates.\n\n    Each candidate: {\"tool\": \"tool_name\", \"params\": {...}, \"quality\": float}\n    Quality must be >= min_quality to be considered.\n    \"\"\"\n    min_quality = 0.8\n    estimated = []\n\n    for candidate in candidates:\n        if candidate[\"quality\"] \u003C min_quality:\n            continue\n        estimate = finops.estimate_cost(\n            tool_name=candidate[\"tool\"],\n            parameters=candidate[\"params\"],\n        )\n        candidate[\"estimated_cost\"] = float(\n            estimate.get(\"estimated_cost\", float(\"inf\"))\n        )\n        estimated.append(candidate)\n\n    if not estimated:\n        raise ValueError(\"No candidate meets minimum quality threshold\")\n\n    # Sort by cost, pick cheapest\n    estimated.sort(key=lambda c: c[\"estimated_cost\"])\n    winner = estimated[0]\n    print(\n        f\"Selected {winner['tool']} at ${winner['estimated_cost']:.4f} \"\n        f\"(quality={winner['quality']})\"\n    )\n    return winner\n\n\n# Orchestrator choosing between three summarization tools\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\nbest = cheapest_tool(finops, [\n    {\"tool\": \"summarize_gpt4o\", \"params\": {\"tokens\": 2000}, \"quality\": 0.95},\n    {\"tool\": \"summarize_claude\", \"params\": {\"tokens\": 2000}, \"quality\": 0.93},\n    {\"tool\": \"summarize_llama\", \"params\": {\"tokens\": 2000}, \"quality\": 0.82},\n])\n```\n\n### Multi-Currency Cost Normalization\n\nWhen your fleet operates across regions or platforms with different billing currencies, normalize everything to a single currency for consistent reporting.\n\n```python\ndef normalize_fleet_costs(\n    api_key: str,\n    agent_costs: list[dict],\n    target_currency: str = \"USD\",\n) -> list[dict]:\n    \"\"\"Convert all agent costs to a single currency.\n\n    agent_costs: [{\"agent_id\": \"x\", \"cost\": 100, \"currency\": \"EUR\"}, ...]\n    \"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=\"system\")\n    normalized = []\n\n    for entry in agent_costs:\n        if entry[\"currency\"] == target_currency:\n            entry[\"normalized_cost\"] = entry[\"cost\"]\n        else:\n            conversion = finops.convert_currency(\n                amount=entry[\"cost\"],\n                from_currency=entry[\"currency\"],\n                to_currency=target_currency,\n            )\n            entry[\"normalized_cost\"] = float(\n                conversion.get(\"converted_amount\", entry[\"cost\"])\n            )\n        normalized.append(entry)\n\n    return normalized\n\n\n# Normalize costs from a multi-region fleet\ncosts = normalize_fleet_costs(API_KEY, [\n    {\"agent_id\": \"eu-researcher\", \"cost\": 85.50, \"currency\": \"EUR\"},\n    {\"agent_id\": \"us-researcher\", \"cost\": 92.00, \"currency\": \"USD\"},\n    {\"agent_id\": \"jp-researcher\", \"cost\": 12000, \"currency\": \"JPY\"},\n])\n\nfor c in costs:\n    print(\n        f\"  {c['agent_id']}: {c['cost']} {c['currency']} \"\n        f\"= ${c['normalized_cost']:.2f} USD\"\n    )\n```\n\n### Cost-Aware Model Routing\n\nCombine cost estimation with quality requirements to route agent tasks to the most cost-effective model at runtime.\n\n```python\ndef cost_aware_route(\n    finops: AgentFinOps,\n    task_type: str,\n    quality_floor: float = 0.85,\n) -> str:\n    \"\"\"Route a task to the cheapest model that meets quality requirements.\"\"\"\n    MODEL_CATALOG = {\n        \"gpt-4o\":      {\"quality\": 0.95, \"tool\": \"inference_gpt4o\"},\n        \"claude-3.5\":  {\"quality\": 0.93, \"tool\": \"inference_claude\"},\n        \"llama-3-70b\": {\"quality\": 0.85, \"tool\": \"inference_llama\"},\n        \"mistral-8x7b\":{\"quality\": 0.80, \"tool\": \"inference_mistral\"},\n    }\n\n    candidates = []\n    for model, spec in MODEL_CATALOG.items():\n        if spec[\"quality\"] \u003C quality_floor:\n            continue\n        est = finops.estimate_cost(\n            tool_name=spec[\"tool\"],\n            parameters={\"task_type\": task_type},\n        )\n        candidates.append({\n            \"model\": model,\n            \"cost\": float(est.get(\"estimated_cost\", float(\"inf\"))),\n            \"quality\": spec[\"quality\"],\n        })\n\n    candidates.sort(key=lambda c: c[\"cost\"])\n    if candidates:\n        pick = candidates[0]\n        print(\n            f\"Routing {task_type} to {pick['model']}: \"\n            f\"${pick['cost']:.4f}\u002Fcall, quality={pick['quality']}\"\n        )\n        return pick[\"model\"]\n    raise ValueError(f\"No model meets quality floor {quality_floor}\")\n```\n\n---\n\n## Chapter 7: Fleet Dashboards and Leaderboards\n\n### Cost-Efficiency Leaderboard\n\nThe agent leaderboard ranks all agents in your fleet by cost efficiency -- the ratio of useful output to money spent. This is the FinOps equivalent of cloud cost-per-transaction dashboards, applied to agents.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\n# Pull the cost-efficiency leaderboard\nleaderboard = finops.get_agent_leaderboard(metric=\"cost_efficiency\")\n\nprint(\"Agent Cost-Efficiency Leaderboard\")\nprint(\"-\" * 65)\nprint(f\"{'Rank':\u003C6}{'Agent ID':\u003C25}{'Efficiency':\u003C15}{'Total Spend':\u003C15}\")\nprint(\"-\" * 65)\nfor i, entry in enumerate(leaderboard.get(\"agents\", []), 1):\n    print(\n        f\"{i:\u003C6}{entry['agent_id']:\u003C25}\"\n        f\"{entry.get('efficiency_score', 'N\u002FA'):\u003C15}\"\n        f\"${float(entry.get('total_spend', 0)):\u003C14.2f}\"\n    )\n```\n\n**curl -- get leaderboard:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_agent_leaderboard\",\n    \"input\": {\"metric\": \"cost_efficiency\"}\n  }'\n```\n\n### Platform-Wide Statistics\n\nGet a bird's-eye view of your entire agent platform: total spend, active agents, average cost per call, and utilization rates.\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"orchestrator-01\")\n\nstats = finops.get_platform_stats()\nprint(\"Platform-Wide FinOps Summary\")\nprint(\"=\" * 45)\nprint(f\"Active agents:       {stats.get('active_agents')}\")\nprint(f\"Total spend (MTD):   ${stats.get('total_spend_mtd')}\")\nprint(f\"Avg cost\u002Fcall:       ${stats.get('avg_cost_per_call')}\")\nprint(f\"Total tool calls:    {stats.get('total_calls_mtd')}\")\nprint(f\"Budget utilization:  {stats.get('budget_utilization_pct')}%\")\nprint(f\"Agents over budget:  {stats.get('agents_over_budget', 0)}\")\n```\n\n**curl -- get platform stats:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_platform_stats\",\n    \"input\": {}\n  }'\n```\n\n### Trend Analysis: Week-over-Week Spend Comparison\n\n```python\ndef weekly_trend_report(\n    api_key: str,\n    agent_ids: list[str],\n    weeks: list[tuple[str, str]],\n):\n    \"\"\"Print week-over-week spend trends for a fleet of agents.\"\"\"\n    print(f\"\\n{'Agent':\u003C22}\", end=\"\")\n    for start, end in weeks:\n        print(f\"{start:\u003C16}\", end=\"\")\n    print(\"  WoW Change\")\n    print(\"-\" * (22 + 16 * len(weeks) + 12))\n\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        costs = []\n        print(f\"{agent_id:\u003C22}\", end=\"\")\n        for start, end in weeks:\n            analytics = finops.get_usage_analytics(\n                start_date=start,\n                end_date=end,\n            )\n            cost = float(analytics.get(\"total_cost\", 0))\n            costs.append(cost)\n            print(f\"${cost:\u003C15.2f}\", end=\"\")\n\n        # Compute week-over-week change for last two weeks\n        if len(costs) >= 2 and costs[-2] > 0:\n            change_pct = (costs[-1] - costs[-2]) \u002F costs[-2] * 100\n            direction = \"+\" if change_pct > 0 else \"\"\n            print(f\"  {direction}{change_pct:.1f}%\")\n        else:\n            print(\"  N\u002FA\")\n\n\nweekly_trend_report(\n    api_key=API_KEY,\n    agent_ids=[\n        \"orchestrator-01\", \"researcher-01\", \"researcher-02\",\n        \"summarizer-01\", \"classifier-01\",\n    ],\n    weeks=[\n        (\"2026-03-16\", \"2026-03-22\"),\n        (\"2026-03-23\", \"2026-03-29\"),\n        (\"2026-03-30\", \"2026-04-05\"),\n    ],\n)\n```\n\n### Building a Daily FinOps Dashboard\n\nCombine all the analytics tools into a single dashboard function that your team runs every morning.\n\n```python\ndef daily_finops_dashboard(api_key: str, agent_ids: list[str]):\n    \"\"\"Print a comprehensive daily FinOps dashboard.\"\"\"\n    print(\"=\" * 70)\n    print(\"  DAILY FINOPS DASHBOARD  |  \" + datetime.now(timezone.utc).strftime(\"%Y-%m-%d %H:%M UTC\"))\n    print(\"=\" * 70)\n\n    # Platform overview\n    system = AgentFinOps(api_key=api_key, agent_id=agent_ids[0])\n    stats = system.get_platform_stats()\n    print(f\"\\nPlatform: {stats.get('active_agents')} agents | \"\n          f\"${stats.get('total_spend_mtd')} MTD | \"\n          f\"{stats.get('budget_utilization_pct')}% budget used\")\n\n    # Per-agent status\n    print(f\"\\n{'Agent':\u003C22}{'Balance':>10}{'Spent Today':>13}\"\n          f\"{'Daily Cap':>11}{'% Used':>9}\")\n    print(\"-\" * 65)\n\n    alerts = []\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        balance = finops.get_balance()\n        budget = finops.get_budget_status()\n\n        bal = float(balance.get(\"balance\", 0))\n        spent = float(budget.get(\"spent_today\", 0))\n        cap = float(budget.get(\"daily_limit\", 0))\n        pct = (spent \u002F cap * 100) if cap > 0 else 0\n\n        flag = \" !!!\" if pct > 80 else \"\"\n        print(\n            f\"{agent_id:\u003C22}${bal:>9.2f}${spent:>12.2f}\"\n            f\"${cap:>10.2f}{pct:>8.1f}%{flag}\"\n        )\n\n        if pct > 80:\n            alerts.append(f\"  {agent_id}: {pct:.1f}% of daily budget used\")\n\n    if alerts:\n        print(f\"\\nALERTS ({len(alerts)}):\")\n        for alert in alerts:\n            print(alert)\n\n    # Top spenders by category (fleet-wide, using first agent for API access)\n    print(\"\\nTop spending categories (fleet-wide, last 24h):\")\n    for agent_id in agent_ids:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        cats = finops.get_spending_by_category(\n            start_date=datetime.now(timezone.utc).strftime(\"%Y-%m-%d\"),\n        )\n        for cat in cats.get(\"categories\", [])[:3]:\n            print(\n                f\"  {agent_id} > {cat['category']}: \"\n                f\"${cat['total_cost']:.2f} ({cat['call_count']} calls)\"\n            )\n\n    print(\"\\n\" + \"=\" * 70)\n```\n\n---\n\n## Chapter 8: API Key Isolation and Security\n\n### Why Per-Agent API Keys Matter for Cost Control\n\nAPI keys are not just a security boundary -- they are a cost boundary. When five agents share one API key, revoking the key to stop a runaway agent kills all five. Per-agent keys let you revoke one agent's access without disrupting the rest of the fleet. This makes key revocation a viable cost control mechanism, not a fleet-wide outage.\n\n### Creating Per-Agent Keys\n\n```python\nfinops = AgentFinOps(api_key=API_KEY, agent_id=\"researcher-01\")\n\n# Create a dedicated key with restricted permissions\nkey_result = finops.create_api_key(\n    label=\"researcher-01-production\",\n    permissions=[\"search_services\", \"get_balance\", \"get_budget_status\"],\n)\n\nnew_api_key = key_result.get(\"api_key\")\nkey_id = key_result.get(\"key_id\")\nprint(f\"API key created: {key_id}\")\nprint(f\"Key value: {new_api_key[:8]}...{new_api_key[-4:]}\")\nprint(f\"Permissions: {key_result.get('permissions')}\")\n```\n\n**curl -- create API key:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_api_key\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"label\": \"researcher-01-production\",\n      \"permissions\": [\"search_services\", \"get_balance\", \"get_budget_status\"]\n    }\n  }'\n```\n\n### Automated Key Rotation\n\nRotate keys on a schedule. The pattern: create a new key, update the agent's configuration to use it, verify it works, then delete the old key. Never delete the old key before the new one is in use.\n\n```python\ndef rotate_agent_key(\n    admin_finops: AgentFinOps,\n    agent_id: str,\n    old_key_id: str,\n) -> dict:\n    \"\"\"Rotate an agent's API key with zero downtime.\"\"\"\n    finops = AgentFinOps(\n        api_key=admin_finops.session.headers[\"Authorization\"].split(\" \")[1],\n        agent_id=agent_id,\n    )\n\n    # Step 1: Create new key\n    new_key = finops.create_api_key(\n        label=f\"{agent_id}-rotated-{int(time.time())}\",\n    )\n    print(f\"New key created: {new_key['key_id']}\")\n\n    # Step 2: Rotate -- this invalidates the old key after a grace period\n    rotate_result = finops.rotate_api_key(key_id=old_key_id)\n    print(f\"Old key {old_key_id} scheduled for invalidation\")\n\n    return {\n        \"new_key_id\": new_key[\"key_id\"],\n        \"new_api_key\": new_key[\"api_key\"],\n        \"old_key_id\": old_key_id,\n        \"rotation_status\": rotate_result.get(\"status\"),\n    }\n\n\n# Rotate the researcher's key\nresult = rotate_agent_key(\n    admin_finops=AgentFinOps(api_key=API_KEY, agent_id=\"admin\"),\n    agent_id=\"researcher-01\",\n    old_key_id=\"key_abc123\",\n)\nprint(f\"Rotation complete. New key: {result['new_key_id']}\")\n```\n\n**curl -- rotate API key:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"rotate_api_key\",\n    \"input\": {\n      \"agent_id\": \"researcher-01\",\n      \"key_id\": \"key_abc123\"\n    }\n  }'\n```\n\n### Credential Revocation as Cost Control\n\nWhen you detect a runaway agent through a webhook alert or dashboard anomaly, the fastest way to stop the bleed is to revoke its API key. This is faster than killing the process (which requires infrastructure access) and more targeted than disabling the entire fleet.\n\n```python\ndef emergency_cost_stop(api_key: str, agent_id: str, key_id: str):\n    \"\"\"Emergency procedure: revoke an agent's API key to stop spend.\"\"\"\n    finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n\n    # Rotate the key -- the old key becomes invalid\n    finops.rotate_api_key(key_id=key_id)\n    print(f\"EMERGENCY: API key {key_id} revoked for {agent_id}\")\n\n    # Check final spend\n    budget = finops.get_budget_status()\n    print(f\"Final spend today: ${budget.get('spent_today')}\")\n\n    # Log the incident\n    return {\n        \"agent_id\": agent_id,\n        \"action\": \"key_revoked\",\n        \"final_spend\": budget.get(\"spent_today\"),\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n    }\n```\n\n### Fleet Key Rotation Schedule\n\nAutomate key rotation across the entire fleet as a weekly cron job.\n\n```python\ndef fleet_key_rotation(api_key: str, agents: list[dict]):\n    \"\"\"Rotate API keys for all agents in the fleet.\n\n    Run as a weekly cron job.\n    agents: [{\"agent_id\": \"...\", \"key_id\": \"...\"}, ...]\n    \"\"\"\n    admin = AgentFinOps(api_key=api_key, agent_id=\"admin\")\n    results = []\n\n    for agent in agents:\n        try:\n            result = rotate_agent_key(\n                admin_finops=admin,\n                agent_id=agent[\"agent_id\"],\n                old_key_id=agent[\"key_id\"],\n            )\n            results.append({\n                \"agent_id\": agent[\"agent_id\"],\n                \"status\": \"rotated\",\n                \"new_key_id\": result[\"new_key_id\"],\n            })\n        except Exception as e:\n            results.append({\n                \"agent_id\": agent[\"agent_id\"],\n                \"status\": \"failed\",\n                \"error\": str(e),\n            })\n\n    # Summary\n    rotated = sum(1 for r in results if r[\"status\"] == \"rotated\")\n    failed = sum(1 for r in results if r[\"status\"] == \"failed\")\n    print(f\"Key rotation complete: {rotated} rotated, {failed} failed\")\n    return results\n```\n\n---\n\n## Chapter 9: Putting It All Together: The FinOps Control Plane\n\n### End-to-End Scenario: Five-Agent Research Fleet\n\nThis section ties together every concept from the previous chapters into a single, production-ready control plane. The scenario: you are running a research fleet with five agents -- one orchestrator, two researchers, one summarizer, and one classifier. The fleet processes incoming research requests, delegates work, and must operate within a $200\u002Fday fleet budget.\n\n```python\nimport os\nfrom datetime import datetime, timezone\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nALERT_BASE_URL = \"https:\u002F\u002Fyour-app.example.com\u002Falerts\"\n\n# ── Step 1: Provision the fleet ─────────────────────────────────\n\nFLEET = [\n    {\"agent_id\": \"orch-01\",   \"role\": \"orchestrator\", \"deposit\": 200.00,\n     \"daily_cap\": 80.00,  \"monthly_cap\": 1600.00},\n    {\"agent_id\": \"res-01\",    \"role\": \"researcher\",   \"deposit\": 75.00,\n     \"daily_cap\": 30.00,  \"monthly_cap\": 600.00},\n    {\"agent_id\": \"res-02\",    \"role\": \"researcher\",   \"deposit\": 75.00,\n     \"daily_cap\": 30.00,  \"monthly_cap\": 600.00},\n    {\"agent_id\": \"sum-01\",    \"role\": \"summarizer\",   \"deposit\": 50.00,\n     \"daily_cap\": 20.00,  \"monthly_cap\": 400.00},\n    {\"agent_id\": \"cls-01\",    \"role\": \"classifier\",   \"deposit\": 40.00,\n     \"daily_cap\": 15.00,  \"monthly_cap\": 300.00},\n]\n\nfleet_clients = {}\n\nfor agent_cfg in FLEET:\n    finops = AgentFinOps(api_key=API_KEY, agent_id=agent_cfg[\"agent_id\"])\n\n    # Create wallet and fund\n    finops.create_wallet()\n    finops.deposit(amount=agent_cfg[\"deposit\"])\n\n    # Set budget caps\n    finops.set_budget_cap(\n        daily_limit=agent_cfg[\"daily_cap\"],\n        monthly_limit=agent_cfg[\"monthly_cap\"],\n    )\n\n    # Create dedicated API key\n    key = finops.create_api_key(\n        label=f\"{agent_cfg['agent_id']}-prod-key\",\n    )\n\n    # Register budget alerts at 75%, 90%, and 100%\n    for pct in [75, 90, 100]:\n        finops.register_webhook(\n            url=f\"{ALERT_BASE_URL}\u002F{agent_cfg['agent_id']}\u002F{pct}\",\n            events=[\"budget.threshold\"],\n            config={\"threshold_pct\": pct},\n        )\n\n    fleet_clients[agent_cfg[\"agent_id\"]] = finops\n    print(\n        f\"Provisioned {agent_cfg['agent_id']} \"\n        f\"(${agent_cfg['deposit']:.2f} balance, \"\n        f\"${agent_cfg['daily_cap']:.2f}\u002Fday cap)\"\n    )\n\n\n# ── Step 2: Pre-flight check before task delegation ─────────────\n\ndef delegate_task(\n    orchestrator: AgentFinOps,\n    worker_id: str,\n    tool: str,\n    params: dict,\n) -> dict:\n    \"\"\"Orchestrator delegates a task to a worker with full FinOps checks.\"\"\"\n    worker = fleet_clients[worker_id]\n\n    # Estimate cost\n    estimate = worker.estimate_cost(tool_name=tool, parameters=params)\n    cost = float(estimate.get(\"estimated_cost\", 0))\n\n    # Check worker's remaining budget\n    budget = worker.get_budget_status()\n    remaining = (\n        float(budget.get(\"daily_limit\", 0))\n        - float(budget.get(\"spent_today\", 0))\n    )\n\n    if cost > remaining:\n        print(\n            f\"SKIP: {worker_id} cannot afford {tool} \"\n            f\"(${cost:.4f} > ${remaining:.2f} remaining)\"\n        )\n        return {\"status\": \"skipped\", \"reason\": \"insufficient_budget\"}\n\n    # Execute\n    try:\n        result = worker._execute(tool, params)\n        return {\"status\": \"success\", \"result\": result}\n    except BudgetExhaustedError:\n        return {\"status\": \"budget_exhausted\"}\n\n\n# ── Step 3: Run a workflow ──────────────────────────────────────\n\norch = fleet_clients[\"orch-01\"]\n\n# The orchestrator delegates research tasks to the two researchers\ntasks = [\n    (\"res-01\", \"search_services\", {\"query\": \"climate data analysis\"}),\n    (\"res-02\", \"search_services\", {\"query\": \"economic forecasting models\"}),\n]\n\nresults = []\nfor worker_id, tool, params in tasks:\n    result = delegate_task(orch, worker_id, tool, params)\n    results.append(result)\n    print(f\"  {worker_id} > {tool}: {result['status']}\")\n\n# Summarizer processes the combined results\ndelegate_task(\n    orch, \"sum-01\",\n    \"search_services\",\n    {\"query\": \"summarize findings\"},\n)\n\n# Classifier categorizes the output\ndelegate_task(\n    orch, \"cls-01\",\n    \"search_services\",\n    {\"query\": \"classify report type\"},\n)\n\n\n# ── Step 4: Generate end-of-day report ──────────────────────────\n\ndef end_of_day_report(api_key: str, fleet: list[dict]):\n    \"\"\"Generate a fleet-wide end-of-day FinOps report.\"\"\"\n    print(\"\\n\" + \"=\" * 70)\n    print(\"  END-OF-DAY FINOPS REPORT  |  \" +\n          datetime.now(timezone.utc).strftime(\"%Y-%m-%d\"))\n    print(\"=\" * 70)\n\n    total_fleet_spend = 0.0\n\n    print(f\"\\n{'Agent':\u003C14}{'Spent Today':>13}{'Daily Cap':>11}\"\n          f\"{'Utilization':>13}{'Balance':>10}\")\n    print(\"-\" * 61)\n\n    for agent_cfg in fleet:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_cfg[\"agent_id\"])\n        budget = finops.get_budget_status()\n        balance = finops.get_balance()\n\n        spent = float(budget.get(\"spent_today\", 0))\n        cap = float(budget.get(\"daily_limit\", 0))\n        bal = float(balance.get(\"balance\", 0))\n        util = (spent \u002F cap * 100) if cap > 0 else 0\n        total_fleet_spend += spent\n\n        print(\n            f\"{agent_cfg['agent_id']:\u003C14}${spent:>12.2f}${cap:>10.2f}\"\n            f\"{util:>12.1f}%${bal:>9.2f}\"\n        )\n\n    print(\"-\" * 61)\n    print(f\"{'Fleet Total':\u003C14}${total_fleet_spend:>12.2f}\")\n\n    # Leaderboard\n    system = AgentFinOps(api_key=api_key, agent_id=fleet[0][\"agent_id\"])\n    lb = system.get_agent_leaderboard(metric=\"cost_efficiency\")\n    print(\"\\nEfficiency Leaderboard (top 3):\")\n    for i, entry in enumerate(lb.get(\"agents\", [])[:3], 1):\n        print(\n            f\"  #{i} {entry['agent_id']}: \"\n            f\"efficiency={entry.get('efficiency_score', 'N\u002FA')}\"\n        )\n\n    print(\"\\n\" + \"=\" * 70)\n\n\nend_of_day_report(API_KEY, FLEET)\n```\n\n### The Complete FinOps Control Plane Class\n\nFor production use, wrap the orchestration logic into a reusable control plane class.\n\n```python\nclass FinOpsControlPlane:\n    \"\"\"Centralized FinOps control plane for multi-agent fleets.\"\"\"\n\n    def __init__(self, api_key: str, alert_base_url: str):\n        self.api_key = api_key\n        self.alert_base_url = alert_base_url\n        self.agents: dict[str, AgentFinOps] = {}\n\n    def provision_agent(\n        self,\n        agent_id: str,\n        deposit: float,\n        daily_cap: float,\n        monthly_cap: float,\n        alert_thresholds: list[int] = None,\n    ) -> AgentFinOps:\n        \"\"\"Provision an agent with wallet, budget, key, and alerts.\"\"\"\n        if alert_thresholds is None:\n            alert_thresholds = [75, 90, 100]\n\n        finops = AgentFinOps(\n            api_key=self.api_key,\n            agent_id=agent_id,\n        )\n\n        finops.create_wallet()\n        finops.deposit(amount=deposit)\n        finops.set_budget_cap(\n            daily_limit=daily_cap,\n            monthly_limit=monthly_cap,\n        )\n        finops.create_api_key(label=f\"{agent_id}-managed\")\n\n        for pct in alert_thresholds:\n            finops.register_webhook(\n                url=f\"{self.alert_base_url}\u002F{agent_id}\u002F{pct}\",\n                events=[\"budget.threshold\"],\n                config={\"threshold_pct\": pct},\n            )\n\n        self.agents[agent_id] = finops\n        return finops\n\n    def fleet_budget_status(self) -> dict:\n        \"\"\"Get budget status for all managed agents.\"\"\"\n        statuses = {}\n        for agent_id, finops in self.agents.items():\n            budget = finops.get_budget_status()\n            balance = finops.get_balance()\n            statuses[agent_id] = {\n                \"spent_today\": budget.get(\"spent_today\"),\n                \"daily_limit\": budget.get(\"daily_limit\"),\n                \"balance\": balance.get(\"balance\"),\n            }\n        return statuses\n\n    def emergency_stop(self, agent_id: str, key_id: str):\n        \"\"\"Emergency: revoke an agent's API key to halt spending.\"\"\"\n        finops = self.agents.get(agent_id)\n        if finops:\n            finops.rotate_api_key(key_id=key_id)\n            print(f\"EMERGENCY STOP: {agent_id} key revoked\")\n\n    def fleet_chargeback(\n        self,\n        team_map: dict[str, list[str]],\n    ) -> dict:\n        \"\"\"Generate chargeback by team.\"\"\"\n        report = {}\n        for team, ids in team_map.items():\n            total = 0.0\n            for agent_id in ids:\n                if agent_id in self.agents:\n                    summary = self.agents[agent_id].get_billing_summary()\n                    total += float(summary.get(\"total_cost\", 0))\n            report[team] = round(total, 2)\n        return report\n\n    def rotate_all_keys(self, key_map: dict[str, str]):\n        \"\"\"Rotate API keys for all agents. key_map: {agent_id: key_id}.\"\"\"\n        for agent_id, key_id in key_map.items():\n            if agent_id in self.agents:\n                self.agents[agent_id].rotate_api_key(key_id=key_id)\n                print(f\"Rotated key for {agent_id}\")\n\n\n# ── Usage ────────────────────────────────────────────────────────\n\ncp = FinOpsControlPlane(\n    api_key=API_KEY,\n    alert_base_url=\"https:\u002F\u002Fyour-app.example.com\u002Falerts\",\n)\n\n# Provision the fleet\ncp.provision_agent(\"orch-01\",  deposit=200, daily_cap=80,  monthly_cap=1600)\ncp.provision_agent(\"res-01\",   deposit=75,  daily_cap=30,  monthly_cap=600)\ncp.provision_agent(\"res-02\",   deposit=75,  daily_cap=30,  monthly_cap=600)\ncp.provision_agent(\"sum-01\",   deposit=50,  daily_cap=20,  monthly_cap=400)\ncp.provision_agent(\"cls-01\",   deposit=40,  daily_cap=15,  monthly_cap=300)\n\n# Daily status check\nstatus = cp.fleet_budget_status()\nfor agent_id, s in status.items():\n    print(f\"  {agent_id}: spent=${s['spent_today']}, balance=${s['balance']}\")\n\n# Monthly chargeback\nchargeback = cp.fleet_chargeback({\n    \"research-team\": [\"res-01\", \"res-02\"],\n    \"processing-team\": [\"sum-01\", \"cls-01\"],\n    \"platform-team\": [\"orch-01\"],\n})\nfor team, cost in chargeback.items():\n    print(f\"  {team}: ${cost:.2f}\")\n```\n\n### Production Checklist\n\nBefore deploying your FinOps control plane to production, verify every item on this list.\n\n**Wallet Isolation**\n\n- [ ] Every agent has its own wallet. No shared wallets.\n- [ ] Orchestrator agents that fund workers have a documented funding budget per task type.\n- [ ] Initial deposit amounts are based on expected 7-day spend plus 30% buffer.\n\n**Budget Caps**\n\n- [ ] Every agent has a `set_budget_cap` with both daily and monthly limits.\n- [ ] Daily limits are set to the maximum reasonable daily spend for that agent's role, not the wallet balance.\n- [ ] Your code handles `402 Payment Required` as a `BudgetExhaustedError` with a graceful shutdown path, not a retry.\n- [ ] Workflow-level budget caps use dedicated per-workflow agent IDs.\n\n**Spend Alerts**\n\n- [ ] Every agent has webhook alerts at 75%, 90%, and 100% of daily budget.\n- [ ] The alert receiver endpoint is monitored for uptime (if it is down, you get no alerts).\n- [ ] Critical alerts (90%+) trigger PagerDuty or equivalent on-call notification.\n- [ ] The 100% alert triggers an automatic agent pause or key revocation.\n- [ ] `get_webhook_logs` is checked weekly to verify alert delivery.\n\n**Cost Attribution**\n\n- [ ] `get_spending_by_category` is pulled daily for each agent.\n- [ ] Monthly chargeback reports are generated and sent to team leads.\n- [ ] Historical spend data from `get_usage_analytics` is stored in your data warehouse for trend analysis.\n\n**Cost Optimization**\n\n- [ ] `estimate_cost` is called before expensive tool executions.\n- [ ] `get_volume_discount` is checked monthly; agents are consolidated if it improves tier eligibility.\n- [ ] Multi-currency costs are normalized to a single reporting currency.\n\n**API Key Security**\n\n- [ ] Every agent has its own API key with scoped permissions.\n- [ ] Key rotation runs weekly as an automated job.\n- [ ] The emergency key revocation procedure is documented and tested quarterly.\n- [ ] API keys are stored in a secrets manager, never in code or environment files.\n\n**Fleet Monitoring**\n\n- [ ] The daily FinOps dashboard runs automatically each morning.\n- [ ] The cost-efficiency leaderboard is reviewed weekly to identify underperforming agents.\n- [ ] `get_platform_stats` is tracked over time to detect fleet-wide cost anomalies.\n- [ ] Week-over-week spend comparison is reviewed for every agent with >$10\u002Fday average spend.\n\n**Incident Response**\n\n- [ ] A runbook exists for \"runaway agent spend\" incidents: detect via webhook, diagnose via `get_spending_by_category`, stop via key revocation, postmortem via `get_usage_analytics`.\n- [ ] The emergency stop procedure (revoke API key) is executable by any on-call engineer.\n- [ ] Post-incident, the budget cap for the affected agent is reviewed and tightened if necessary.\n\n---\n\n## Chapter 10: What to Do Next\n\n### Advanced Pattern: Dynamic Budget Reallocation\n\nIn a fleet with a fixed total budget, idle agents waste allocated capacity while busy agents hit their caps. Dynamic reallocation moves budget from idle agents to active ones in real time.\n\n```python\ndef rebalance_fleet_budgets(\n    control_plane: FinOpsControlPlane,\n    fleet_daily_budget: float,\n):\n    \"\"\"Dynamically reallocate daily budgets based on current utilization.\"\"\"\n    statuses = control_plane.fleet_budget_status()\n\n    # Calculate utilization for each agent\n    utilizations = {}\n    for agent_id, s in statuses.items():\n        cap = float(s.get(\"daily_limit\", 1))\n        spent = float(s.get(\"spent_today\", 0))\n        utilizations[agent_id] = spent \u002F cap if cap > 0 else 0\n\n    # Agents under 30% utilization donate budget to agents over 80%\n    donors = {k: v for k, v in utilizations.items() if v \u003C 0.30}\n    receivers = {k: v for k, v in utilizations.items() if v > 0.80}\n\n    if not donors or not receivers:\n        print(\"No rebalancing needed.\")\n        return\n\n    # Calculate redistributable budget\n    redistributable = 0.0\n    for agent_id in donors:\n        cap = float(statuses[agent_id][\"daily_limit\"])\n        spent = float(statuses[agent_id][\"spent_today\"])\n        donatable = (cap - spent) * 0.5  # Donate half of unused budget\n        redistributable += donatable\n\n    # Distribute evenly to receivers\n    per_receiver = redistributable \u002F len(receivers)\n    for agent_id in receivers:\n        finops = control_plane.agents[agent_id]\n        current_cap = float(statuses[agent_id][\"daily_limit\"])\n        new_cap = current_cap + per_receiver\n        finops.set_budget_cap(daily_limit=new_cap)\n        print(\n            f\"  {agent_id}: cap raised from ${current_cap:.2f} \"\n            f\"to ${new_cap:.2f} (+${per_receiver:.2f})\"\n        )\n\n    # Reduce donor caps\n    per_donor_reduction = redistributable \u002F len(donors)\n    for agent_id in donors:\n        finops = control_plane.agents[agent_id]\n        current_cap = float(statuses[agent_id][\"daily_limit\"])\n        new_cap = max(current_cap - per_donor_reduction, 5.00)  # Minimum $5\n        finops.set_budget_cap(daily_limit=new_cap)\n        print(\n            f\"  {agent_id}: cap lowered from ${current_cap:.2f} \"\n            f\"to ${new_cap:.2f}\"\n        )\n```\n\n### Advanced Pattern: Cost-Aware Workflow Routing\n\nInstead of always routing to the same set of agents, pick the workflow path that minimizes cost while meeting quality constraints.\n\n```python\ndef cost_aware_workflow_route(\n    control_plane: FinOpsControlPlane,\n    task: dict,\n) -> list[str]:\n    \"\"\"Pick the cheapest agent path for a workflow task.\"\"\"\n    capable_agents = task[\"capable_agents\"]  # List of agent IDs\n    quality_floor = task.get(\"quality_floor\", 0.8)\n\n    # Score each candidate by remaining budget and efficiency\n    candidates = []\n    for agent_id in capable_agents:\n        if agent_id not in control_plane.agents:\n            continue\n        finops = control_plane.agents[agent_id]\n\n        budget = finops.get_budget_status()\n        remaining = (\n            float(budget.get(\"daily_limit\", 0))\n            - float(budget.get(\"spent_today\", 0))\n        )\n\n        estimate = finops.estimate_cost(\n            tool_name=task[\"tool\"],\n            parameters=task[\"params\"],\n        )\n        cost = float(estimate.get(\"estimated_cost\", float(\"inf\")))\n\n        if cost \u003C= remaining:\n            candidates.append({\n                \"agent_id\": agent_id,\n                \"cost\": cost,\n                \"remaining_budget\": remaining,\n            })\n\n    # Sort by cost, then by remaining budget (prefer agents with more headroom)\n    candidates.sort(key=lambda c: (c[\"cost\"], -c[\"remaining_budget\"]))\n\n    if candidates:\n        chosen = candidates[0][\"agent_id\"]\n        print(\n            f\"Routing to {chosen} \"\n            f\"(cost=${candidates[0]['cost']:.4f}, \"\n            f\"${candidates[0]['remaining_budget']:.2f} remaining)\"\n        )\n        return [chosen]\n\n    raise RuntimeError(\"No agent can afford this task within budget\")\n```\n\n### Building a SaaS Billing Layer\n\nIf you are building a platform where customers deploy their own agent fleets, you can build a multi-tenant billing layer on top of GreenHelix. The pattern: each customer gets a top-level orchestrator agent that funds and manages their fleet. Your platform charges the customer based on their fleet's total spend via `get_billing_summary`, applying your own markup.\n\n```python\ndef customer_invoice(\n    api_key: str,\n    customer_id: str,\n    customer_agents: list[str],\n    markup_pct: float = 20.0,\n) -> dict:\n    \"\"\"Generate an invoice for a customer based on their fleet spend.\"\"\"\n    total_platform_cost = 0.0\n    line_items = []\n\n    for agent_id in customer_agents:\n        finops = AgentFinOps(api_key=api_key, agent_id=agent_id)\n        summary = finops.get_billing_summary(period=\"monthly\")\n        cost = float(summary.get(\"total_cost\", 0))\n        total_platform_cost += cost\n        line_items.append({\n            \"agent_id\": agent_id,\n            \"platform_cost\": round(cost, 2),\n            \"calls\": summary.get(\"total_calls\", 0),\n        })\n\n    markup = total_platform_cost * (markup_pct \u002F 100)\n    total_invoice = total_platform_cost + markup\n\n    return {\n        \"customer_id\": customer_id,\n        \"period\": \"April 2026\",\n        \"line_items\": line_items,\n        \"platform_cost\": round(total_platform_cost, 2),\n        \"markup_pct\": markup_pct,\n        \"markup_amount\": round(markup, 2),\n        \"total_invoice\": round(total_invoice, 2),\n    }\n```\n\n### Where This Guide Fits in the GreenHelix Ecosystem\n\nThis guide covers budget enforcement, cost allocation, and spend analytics -- the FinOps layer. For the other layers of agent commerce infrastructure, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** -- the foundational guide covering wallet setup, escrow patterns (standard, performance, split), marketplace discovery, subscriptions, dispute resolution, and framework integration with CrewAI, LangChain, and AutoGen.\n- **The Agent Strategy Marketplace Playbook** -- how to sell verified trading strategies with performance escrow, including metric submission pipelines, claim chains, and pricing tiers.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains, covering the trust score algorithm and leaderboard mechanics.\n- **Tamper-Proof Audit Trails for Trading Bots** -- EU AI Act, MiFID II, and SEC compliance using GreenHelix's event bus and Merkle audit chains.\n\nFor the full API reference and tool catalog (all 128 tools, including the 23 billing and webhook tools covered in this guide), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\nFor updates on the FinOps Foundation's \"FinOps for AI\" initiative and how GreenHelix aligns with their emerging standards for AI cost governance, follow the FinOps Foundation at [finops.org](https:\u002F\u002Fwww.finops.org\u002F).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33],"finops","billing","budgets","webhooks","cost-management","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41,42],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY",0,[41,42],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-finops-playbook","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":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-finops-playbook",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-finops-playbook",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-finops-playbook","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-finops-playbook\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"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":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"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":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"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":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"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":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"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":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"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",[],[]]