[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D8483AP1VHREFH6QRX2C8R":3,"skill-same:01M6D8483AP1VHREFH6QRX2C8R":65},{"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":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":6,"ownerHtmlUrl":47,"ownerBlogUrl":48,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M6D8483AP1VHREFH6QRX2C8R","cost-aware-llm-pipeline",null,"Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.","oabdelmaksoud\u002FSuperClaw","oabdelmaksoud","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F50699149?v=4","01M6D5CVVN778ZCDP1WHS816SP","Omar Abdelmaksoud","01M6D5CW1RHNSKCJR85GJACBFT",2,"MIT","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fcost-aware-llm-pipeline\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],"cost aware llm pipeline","pipeline","cost","prompt","logic","caching","patterns","task","complexity","tracking","cost optimization","model","api","Budget","prompt caching","Optimization","routing","2026-11-10 10:12:30",false,"---\nname: cost-aware-llm-pipeline\ndescription: Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.\norigin: ECC\n---\n\n# Cost-Aware LLM Pipeline\n\nPatterns for controlling LLM API costs while maintaining quality. Combines model routing, budget tracking, retry logic, and prompt caching into a composable pipeline.\n\n## When to Activate\n\n- Building applications that call LLM APIs (Claude, GPT, etc.)\n- Processing batches of items with varying complexity\n- Need to stay within a budget for API spend\n- Optimizing cost without sacrificing quality on complex tasks\n\n## Core Concepts\n\n### 1. Model Routing by Task Complexity\n\nAutomatically select cheaper models for simple tasks, reserving expensive models for complex ones.\n\n```python\nMODEL_SONNET = \"claude-sonnet-4-6\"\nMODEL_HAIKU = \"claude-haiku-4-5-20251001\"\n\n_SONNET_TEXT_THRESHOLD = 10_000  # chars\n_SONNET_ITEM_THRESHOLD = 30     # items\n\ndef select_model(\n    text_length: int,\n    item_count: int,\n    force_model: str | None = None,\n) -> str:\n    \"\"\"Select model based on task complexity.\"\"\"\n    if force_model is not None:\n        return force_model\n    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:\n        return MODEL_SONNET  # Complex task\n    return MODEL_HAIKU  # Simple task (3-4x cheaper)\n```\n\n### 2. Immutable Cost Tracking\n\nTrack cumulative spend with frozen dataclasses. Each API call returns a new tracker — never mutates state.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass CostRecord:\n    model: str\n    input_tokens: int\n    output_tokens: int\n    cost_usd: float\n\n@dataclass(frozen=True, slots=True)\nclass CostTracker:\n    budget_limit: float = 1.00\n    records: tuple[CostRecord, ...] = ()\n\n    def add(self, record: CostRecord) -> \"CostTracker\":\n        \"\"\"Return new tracker with added record (never mutates self).\"\"\"\n        return CostTracker(\n            budget_limit=self.budget_limit,\n            records=(*self.records, record),\n        )\n\n    @property\n    def total_cost(self) -> float:\n        return sum(r.cost_usd for r in self.records)\n\n    @property\n    def over_budget(self) -> bool:\n        return self.total_cost > self.budget_limit\n```\n\n### 3. Narrow Retry Logic\n\nRetry only on transient errors. Fail fast on authentication or bad request errors.\n\n```python\nfrom anthropic import (\n    APIConnectionError,\n    InternalServerError,\n    RateLimitError,\n)\n\n_RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError)\n_MAX_RETRIES = 3\n\ndef call_with_retry(func, *, max_retries: int = _MAX_RETRIES):\n    \"\"\"Retry only on transient errors, fail fast on others.\"\"\"\n    for attempt in range(max_retries):\n        try:\n            return func()\n        except _RETRYABLE_ERRORS:\n            if attempt == max_retries - 1:\n                raise\n            time.sleep(2 ** attempt)  # Exponential backoff\n    # AuthenticationError, BadRequestError etc. → raise immediately\n```\n\n### 4. Prompt Caching\n\nCache long system prompts to avoid resending them on every request.\n\n```python\nmessages = [\n    {\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": system_prompt,\n                \"cache_control\": {\"type\": \"ephemeral\"},  # Cache this\n            },\n            {\n                \"type\": \"text\",\n                \"text\": user_input,  # Variable part\n            },\n        ],\n    }\n]\n```\n\n## Composition\n\nCombine all four techniques in a single pipeline function:\n\n```python\ndef process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:\n    # 1. Route model\n    model = select_model(len(text), estimated_items, config.force_model)\n\n    # 2. Check budget\n    if tracker.over_budget:\n        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)\n\n    # 3. Call with retry + caching\n    response = call_with_retry(lambda: client.messages.create(\n        model=model,\n        messages=build_cached_messages(system_prompt, text),\n    ))\n\n    # 4. Track cost (immutable)\n    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)\n    tracker = tracker.add(record)\n\n    return parse_result(response), tracker\n```\n\n## Pricing Reference (2025-2026)\n\n| Model | Input ($\u002F1M tokens) | Output ($\u002F1M tokens) | Relative Cost |\n|-------|---------------------|----------------------|---------------|\n| Haiku 4.5 | $0.80 | $4.00 | 1x |\n| Sonnet 4.6 | $3.00 | $15.00 | ~4x |\n| Opus 4.5 | $15.00 | $75.00 | ~19x |\n\n## Best Practices\n\n- **Start with the cheapest model** and only route to expensive models when complexity thresholds are met\n- **Set explicit budget limits** before processing batches — fail early rather than overspend\n- **Log model selection decisions** so you can tune thresholds based on real data\n- **Use prompt caching** for system prompts over 1024 tokens — saves both cost and latency\n- **Never retry on authentication or validation errors** — only transient failures (network, rate limit, server error)\n\n## Anti-Patterns to Avoid\n\n- Using the most expensive model for all requests regardless of complexity\n- Retrying on all errors (wastes budget on permanent failures)\n- Mutating cost tracking state (makes debugging and auditing difficult)\n- Hardcoding model names throughout the codebase (use constants or config)\n- Ignoring prompt caching for repetitive system prompts\n\n## When to Use\n\n- Any application calling Claude, OpenAI, or similar LLM APIs\n- Batch processing pipelines where cost adds up quickly\n- Multi-model architectures that need intelligent routing\n- Production systems that need budget guardrails\n","# Cost-Aware LLM Pipeline\n\nPatterns for controlling LLM API costs while maintaining quality. Combines model routing, budget tracking, retry logic, and prompt caching into a composable pipeline.\n\n## When to Activate\n\n- Building applications that call LLM APIs (Claude, GPT, etc.)\n- Processing batches of items with varying complexity\n- Need to stay within a budget for API spend\n- Optimizing cost without sacrificing quality on complex tasks\n\n## Core Concepts\n\n### 1. Model Routing by Task Complexity\n\nAutomatically select cheaper models for simple tasks, reserving expensive models for complex ones.\n\n```python\nMODEL_SONNET = \"claude-sonnet-4-6\"\nMODEL_HAIKU = \"claude-haiku-4-5-20251001\"\n\n_SONNET_TEXT_THRESHOLD = 10_000  # chars\n_SONNET_ITEM_THRESHOLD = 30     # items\n\ndef select_model(\n    text_length: int,\n    item_count: int,\n    force_model: str | None = None,\n) -> str:\n    \"\"\"Select model based on task complexity.\"\"\"\n    if force_model is not None:\n        return force_model\n    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:\n        return MODEL_SONNET  # Complex task\n    return MODEL_HAIKU  # Simple task (3-4x cheaper)\n```\n\n### 2. Immutable Cost Tracking\n\nTrack cumulative spend with frozen dataclasses. Each API call returns a new tracker — never mutates state.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, slots=True)\nclass CostRecord:\n    model: str\n    input_tokens: int\n    output_tokens: int\n    cost_usd: float\n\n@dataclass(frozen=True, slots=True)\nclass CostTracker:\n    budget_limit: float = 1.00\n    records: tuple[CostRecord, ...] = ()\n\n    def add(self, record: CostRecord) -> \"CostTracker\":\n        \"\"\"Return new tracker with added record (never mutates self).\"\"\"\n        return CostTracker(\n            budget_limit=self.budget_limit,\n            records=(*self.records, record),\n        )\n\n    @property\n    def total_cost(self) -> float:\n        return sum(r.cost_usd for r in self.records)\n\n    @property\n    def over_budget(self) -> bool:\n        return self.total_cost > self.budget_limit\n```\n\n### 3. Narrow Retry Logic\n\nRetry only on transient errors. Fail fast on authentication or bad request errors.\n\n```python\nfrom anthropic import (\n    APIConnectionError,\n    InternalServerError,\n    RateLimitError,\n)\n\n_RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError)\n_MAX_RETRIES = 3\n\ndef call_with_retry(func, *, max_retries: int = _MAX_RETRIES):\n    \"\"\"Retry only on transient errors, fail fast on others.\"\"\"\n    for attempt in range(max_retries):\n        try:\n            return func()\n        except _RETRYABLE_ERRORS:\n            if attempt == max_retries - 1:\n                raise\n            time.sleep(2 ** attempt)  # Exponential backoff\n    # AuthenticationError, BadRequestError etc. → raise immediately\n```\n\n### 4. Prompt Caching\n\nCache long system prompts to avoid resending them on every request.\n\n```python\nmessages = [\n    {\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": system_prompt,\n                \"cache_control\": {\"type\": \"ephemeral\"},  # Cache this\n            },\n            {\n                \"type\": \"text\",\n                \"text\": user_input,  # Variable part\n            },\n        ],\n    }\n]\n```\n\n## Composition\n\nCombine all four techniques in a single pipeline function:\n\n```python\ndef process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:\n    # 1. Route model\n    model = select_model(len(text), estimated_items, config.force_model)\n\n    # 2. Check budget\n    if tracker.over_budget:\n        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)\n\n    # 3. Call with retry + caching\n    response = call_with_retry(lambda: client.messages.create(\n        model=model,\n        messages=build_cached_messages(system_prompt, text),\n    ))\n\n    # 4. Track cost (immutable)\n    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)\n    tracker = tracker.add(record)\n\n    return parse_result(response), tracker\n```\n\n## Pricing Reference (2025-2026)\n\n| Model | Input ($\u002F1M tokens) | Output ($\u002F1M tokens) | Relative Cost |\n|-------|---------------------|----------------------|---------------|\n| Haiku 4.5 | $0.80 | $4.00 | 1x |\n| Sonnet 4.6 | $3.00 | $15.00 | ~4x |\n| Opus 4.5 | $15.00 | $75.00 | ~19x |\n\n## Best Practices\n\n- **Start with the cheapest model** and only route to expensive models when complexity thresholds are met\n- **Set explicit budget limits** before processing batches — fail early rather than overspend\n- **Log model selection decisions** so you can tune thresholds based on real data\n- **Use prompt caching** for system prompts over 1024 tokens — saves both cost and latency\n- **Never retry on authentication or validation errors** — only transient failures (network, rate limit, server error)\n\n## Anti-Patterns to Avoid\n\n- Using the most expensive model for all requests regardless of complexity\n- Retrying on all errors (wastes budget on permanent failures)\n- Mutating cost tracking state (makes debugging and auditing difficult)\n- Hardcoding model names throughout the codebase (use constants or config)\n- Ignoring prompt caching for repetitive system prompts\n\n## When to Use\n\n- Any application calling Claude, OpenAI, or similar LLM APIs\n- Batch processing pipelines where cost adds up quickly\n- Multi-model architectures that need intelligent routing\n- Production systems that need budget guardrails\n",{"name":5,"origin":41,"description":7},"ECC","main","7b610356e36623652299fa2acb477ff821b1d920","upstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fcost-aware-llm-pipeline",0,"https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud","https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fo-abdelmaksoud\u002F","Full-Stack Engineer | AI Systems Architect | Building autonomous multi-agent systems","2026-03-08 21:12:53",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add oabdelmaksoud\u002FSuperClaw --skill cost-aware-llm-pipeline",{"tool":57,"command":58},"bunx","bunx skills add oabdelmaksoud\u002FSuperClaw --skill cost-aware-llm-pipeline",{"tool":60,"command":61},"pnpm","pnpm dlx skills add oabdelmaksoud\u002FSuperClaw --skill cost-aware-llm-pipeline","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fcost-aware-llm-pipeline\u002FSKILL.md",true,[],[66,87,101,132,156,175],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":77,"publishedAt":36},"01M6D88QCPTBZVCRED0NZ1Y8K8","visa-doc-translate","Translate visa application documents (images) to English and create a bilingual PDF with original and translation","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fvisa-doc-translate\u002FSKILL.md",[72],{"categoryNo":73,"categoryName":74,"taxonomyType":75,"taxonomyTypeDesc":76},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",[78,79,80,81,82,83,84,85,86],"translate","doc","visa doc translate","translation","application","create","images","PDF","documents",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":36},"01M6D88NBM95T3TFM50CYYAP65","verification-loop","A comprehensive verification system for Claude Code sessions.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[94,95,96,97,98,99,100],"verification","loop","verification loop","sessions","code","claude code sessions","system",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":118,"publishedAt":36},"01M6D88JFZ2P996GVRHJNSZSTM","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[107,110,113],{"categoryNo":108,"categoryName":109,"taxonomyType":75,"taxonomyTypeDesc":76},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":111,"categoryName":112,"taxonomyType":75,"taxonomyTypeDesc":76},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":114,"categoryName":115,"taxonomyType":116,"taxonomyTypeDesc":117},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[119,120,121,122,123,124,98,125,126,127,128,129,130,131],"tdd","workflow","tdd workflow","e2e tests","e2e","integration","development","use","test","refactoring","coverage","tests","writing",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":36},"01M6D88FTHRRSVJMXF2G7MQAK3","swiftui-patterns","SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS\u002FmacOS UI best practices.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswiftui-patterns\u002FSKILL.md",[],[25,139,140,141,142,143,144,145,146,147,34,148,149,150,151,152,153,154,155],"swiftui","swiftui patterns","architecture","macos","performance","state management","best practices","state","ui","ios","architecture patterns","Composition","performance optimization","view","management","swiftui architecture","navigation",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":163,"publishedAt":36},"01M6D88D527QTQT9DKHTRFN6EA","swift-protocol-di-testing","Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswift-protocol-di-testing\u002FSKILL.md",[162],{"categoryNo":108,"categoryName":109,"taxonomyType":75,"taxonomyTypeDesc":76},[164,165,166,167,98,168,169,170,171,100,172,173,174],"swift protocol di testing","protocol","swift","testing","protocols","file","network","injection","dependency","swift testing","dependency injection",{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":181,"publishedAt":36},"01M6D88AJW8H2QNWSW5ZY82R43","swift-concurrency-6-2","Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent for explicit background offloading, isolated conformances for main actor types.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FSuperClaw\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswift-concurrency-6-2\u002FSKILL.md",[],[182,183,166,184,185,42],"concurrency","swift concurrency","swift concurrency 6 2","default"]