一键导入
cost-aware-llm-pipeline
Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Create stunning 3D websites with pixel art and mosaic UI/UX design using Three.js. Use this skill when the user asks to build a 3D website or landing page, add Three.js 3D effects or scenes, create pixel art / mosaic / voxel-style web design, combine 3D rendering with retro or pixel aesthetics, animate 3D elements on a webpage, create immersive scrollytelling / Z-axis scrolljacking experiences, or build 2.5D HD-2D worlds mixing Low-Poly 3D environments with pixel art sprite billboards. Triggers include any mention of 3D site, Three.js, pixel design, mosaique 3D, effet 3D pixel, voxel web, CRT effect, scanline effect, scrollytelling, scrolljacking, défilement axe Z, 2.5D, HD-2D, sprite billboard, Low-Poly world, or caméra sur rail.
Meta-skill for continuous AI self-improvement through structured feedback analysis. Creates domain-specific learning skills that accumulate actionable principles over time. Use this skill when: (1) The user wants the AI to learn and improve on a specific domain (e.g., VSL creation, sales coaching, content curation, code review). (2) The user provides examples of good vs bad outputs and wants the AI to extract reusable principles. (3) The user says things like "learn from this", "improve based on feedback", "remember this for next time", "analyze what works", "create a learning profile", "get better at X". (4) The user wants to create structured knowledge from repeated feedback loops. This skill does NOT replace domain expertise — it provides the methodology for extracting and storing transferable principles from user feedback.
Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.
C++ coding standards based on the C++ Core Guidelines (isocpp.github.io). Use when writing, reviewing, or refactoring C++ code to enforce modern, safe, and idiomatic practices.
Comprehensive task planning using the `everything-claude-code` ecosystem. Use this skill when the user has provided detailed specifications or after a specification phase is complete. It spontaneously proposes a detailed execution plan (`task.md`) by consulting the `capabilities_library.md` to select the most appropriate Agents, Skills, and Rules for each step of the task.
Guide for creating and managing cron jobs and scheduled tasks in OpenClaw. Use this skill when the user wants to schedule periodic tasks, set up reminders, batch automated checks, configure the OpenClaw Gateway scheduler, or decide between using a cron job versus a heartbeat. Triggers include "create a cron job", "schedule a task", "remind me in", "run every", "automate this check", "cron vs heartbeat".
| name | cost-aware-llm-pipeline |
| description | Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching. |
Patterns for controlling LLM API costs while maintaining quality. Combines model routing, budget tracking, retry logic, and prompt caching into a composable pipeline.
Automatically select cheaper models for simple tasks, reserving expensive models for complex ones.
MODEL_SONNET = "claude-sonnet-4-5-20250929"
MODEL_HAIKU = "claude-haiku-4-5-20251001"
_SONNET_TEXT_THRESHOLD = 10_000 # chars
_SONNET_ITEM_THRESHOLD = 30 # items
def select_model(
text_length: int,
item_count: int,
force_model: str | None = None,
) -> str:
"""Select model based on task complexity."""
if force_model is not None:
return force_model
if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:
return MODEL_SONNET # Complex task
return MODEL_HAIKU # Simple task (3-4x cheaper)
Track cumulative spend with frozen dataclasses. Each API call returns a new tracker — never mutates state.
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class CostRecord:
model: str
input_tokens: int
output_tokens: int
cost_usd: float
@dataclass(frozen=True, slots=True)
class CostTracker:
budget_limit: float = 1.00
records: tuple[CostRecord, ...] = ()
def add(self, record: CostRecord) -> "CostTracker":
"""Return new tracker with added record (never mutates self)."""
return CostTracker(
budget_limit=self.budget_limit,
records=(*self.records, record),
)
@property
def total_cost(self) -> float:
return sum(r.cost_usd for r in self.records)
@property
def over_budget(self) -> bool:
return self.total_cost > self.budget_limit
Retry only on transient errors. Fail fast on authentication or bad request errors.
from anthropic import (
APIConnectionError,
InternalServerError,
RateLimitError,
)
_RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError)
_MAX_RETRIES = 3
def call_with_retry(func, *, max_retries: int = _MAX_RETRIES):
"""Retry only on transient errors, fail fast on others."""
for attempt in range(max_retries):
try:
return func()
except _RETRYABLE_ERRORS:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # Exponential backoff
# AuthenticationError, BadRequestError etc. → raise immediately
Cache long system prompts to avoid resending them on every request.
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"}, # Cache this
},
{
"type": "text",
"text": user_input, # Variable part
},
],
}
]
Combine all four techniques in a single pipeline function:
def process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:
# 1. Route model
model = select_model(len(text), estimated_items, config.force_model)
# 2. Check budget
if tracker.over_budget:
raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)
# 3. Call with retry + caching
response = call_with_retry(lambda: client.messages.create(
model=model,
messages=build_cached_messages(system_prompt, text),
))
# 4. Track cost (immutable)
record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)
tracker = tracker.add(record)
return parse_result(response), tracker
| Model | Input ($/1M tokens) | Output ($/1M tokens) | Relative Cost |
|---|---|---|---|
| Haiku 4.5 | $0.80 | $4.00 | 1x |
| Sonnet 4.5 | $3.00 | $15.00 | ~4x |
| Opus 4.5 | $15.00 | $75.00 | ~19x |