Communitygithub.com

pipeline-llm-consciente-de-costos

Patrones de optimización de costos para el uso de API de LLM: enrutamiento de modelos según la complejidad de la tarea, seguimiento de presupuesto, lógica de reintentos y almacenamiento en caché de indicaciones. Úselo cuando necesite reducir el gasto de LLM o cuando necesite enrutar tareas entre niveles de modelo y presupuestos.

¿Qué es pipeline-llm-consciente-de-costos?

Este skill proporciona un conjunto de patrones comprobados para controlar los costos de las API de LLM sin sacrificar la calidad. Combina cuatro técnicas clave: enrutamiento de modelos basado en la complejidad de la tarea (seleccionando automáticamente modelos más baratos para tareas simples), seguimiento de costos inmutable con dataclasses congeladas, lógica de reintentos específica para errores transitorios (como errores de conexión, límite de tasa o del servidor) y almacenamiento en caché de indicaciones del sistema para ahorrar tokens. El skill incluye una función de pipeline compuesta que integra todas estas técnicas, y además proporciona una tabla de referencia de precios (2026) para modelos populares de Anthropic. Es útil para desarrolladores que construyen aplicaciones que llaman a LLMs (Claude, GPT, etc.), procesan lotes de elementos con complejidad variable o necesitan mantenerse dentro de un presupuesto de API. El código está diseñado para ser componible e inmutable, lo que facilita la depuración y la auditoría.

Compatible con✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/cost-aware-llm-pipeline

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Pipeline LLM Consciente de Costos

Patrones para controlar los costos de las API de LLM mientras se mantiene la calidad. Combina enrutamiento de modelos, seguimiento de presupuesto, lógica de reintentos y almacenamiento en caché de indicaciones en un pipeline componible.

Cuándo Activarlo

  • Al construir aplicaciones que llaman a API de LLM (Claude, GPT, etc.)
  • Al procesar lotes de elementos con complejidad variable
  • Cuando se necesita mantenerse dentro de un presupuesto de gasto de API
  • Al optimizar costos sin sacrificar calidad en tareas complejas

Conceptos Clave

1. Enrutamiento de Modelos por Complejidad de la Tarea

Selecciona automáticamente modelos más baratos para tareas simples, reservando modelos costosos para las complejas.

MODEL_SONNET = "claude-sonnet-5"
MODEL_HAIKU = "claude-haiku-4-5-20251001"

_SONNET_TEXT_THRESHOLD = 10_000  # caracteres
_SONNET_ITEM_THRESHOLD = 30     # elementos

def select_model(
    text_length: int,
    item_count: int,
    force_model: str | None = None,
) -> str:
    """Selecciona modelo basado en la complejidad de la tarea."""
    if force_model is not None:
        return force_model
    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:
        return MODEL_SONNET  # Tarea compleja
    return MODEL_HAIKU  # Tarea simple (3-4x más barato)

2. Seguimiento de Costos Inmutable

Rastrea el gasto acumulado con dataclasses congeladas. Cada llamada a la API devuelve un nuevo tracker (nunca muta el estado).

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":
        """Devuelve un nuevo tracker con el registro añadido (nunca muta 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

3. Lógica de Reintentos Específica

Reintentar solo en errores transitorios. Fallar rápidamente en errores de autenticación o de solicitud incorrecta.

from anthropic import (
    APIConnectionError,
    InternalServerError,
    RateLimitError,
)

_RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError)
_MAX_RETRIES = 3

def call_with_retry(func, *, max_retries: int = _MAX_RETRIES):
    """Reintenta solo en errores transitorios, falla rápido en otros."""
    for attempt in range(max_retries):
        try:
            return func()
        except _RETRYABLE_ERRORS:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Retroceso exponencial
    # AuthenticationError, BadRequestError etc. → lanzar inmediatamente

4. Almacenamiento en Caché de Indicaciones

Almacenar en caché indicaciones del sistema largas para evitar reenviarlas en cada solicitud.

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"},  # Almacenar en caché esto
            },
            {
                "type": "text",
                "text": user_input,  # Parte variable
            },
        ],
    }
]

Composición

Combina las cuatro técnicas en una única función de pipeline:

def process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:
    # 1. Enrutar modelo
    model = select_model(len(text), estimated_items, config.force_model)

    # 2. Verificar presupuesto
    if tracker.over_budget:
        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)

    # 3. Llamar con reintentos + almacenamiento en caché
    response = call_with_retry(lambda: client.messages.create(
        model=model,
        messages=build_cached_messages(system_prompt, text),
    ))

    # 4. Rastrear costo (inmutable)
    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)
    tracker = tracker.add(record)

    return parse_result(response), tracker

Referencia de Precios (2026)

ModeloEntrada ($/1M tokens)Salida ($/1M tokens)Costo Relativo
Haiku 3.5 (heredado)$0.80$4.000.8x
Haiku 4.5$1.00$5.001x
Sonnet 5$2.00$10.002x
Sonnet 4.6$3.00$15.003x
Opus 4.8$5.00$25.005x
Fable 5 / Mythos 5$10.00$50.0010x
Opus 4.0 / 4.1 (heredado)$15.00$75.0015x

Mejores Prácticas

  • Comience con el modelo más barato y solo enrute a modelos costosos cuando se cumplan los umbrales de complejidad
  • Establezca límites de presupuesto explícitos antes de procesar lotes: falle temprano en lugar de gastar de más
  • Registre las decisiones de selección de modelos para poder ajustar los umbrales basándose en datos reales
  • Use el almacenamiento en caché de indicaciones para indicaciones del sistema de más de 1024 tokens: ahorra tanto costo como latencia
  • Nunca reintente errores de autenticación o validación — solo fallos transitorios (red, límite de tasa, error del servidor)

Antipatrones a Evitar

  • Usar el modelo más caro para todas las solicitudes independientemente de la complejidad
  • Reintentar todos los errores (desperdicia presupuesto en fallos permanentes)
  • Mutar el estado de seguimiento de costos (dificulta la depuración y auditoría)
  • Codificar nombres de modelo en todo el código base (use constantes o configuración)
  • Ignorar el almacenamiento en caché de indicaciones para indicaciones del sistema repetitivas

Cuándo Usarlo

  • Cualquier aplicación que llame a Claude, OpenAI o API de LLM similares
  • Pipelines de procesamiento por lotes donde los costos se acumulan rápidamente
  • Arquitecturas multimodelo que necesitan enrutamiento inteligente
  • Sistemas de producción que necesitan barreras de seguridad de presupuesto

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills relacionados