Communitygithub.com

Kostenbewusste LLM-Pipeline

Optimierungsmuster für LLM-API-Kosten – Modell-Routing nach Aufgabenkomplexität, Budgetverfolgung, Wiederholungslogik und Prompt-Caching. Verwenden Sie dies, wenn die LLM-Ausgaben sinken müssen oder wenn Aufgaben über Modellstufen und Budgets geroutet werden sollen.

Was ist Kostenbewusste LLM-Pipeline?

Diese Skill (Kostenbewusste LLM-Pipeline) bietet eine Zusammenstellung von Entwurfsmustern zur Kontrolle der LLM-API-Kosten bei gleichzeitiger Beibehaltung der Qualität. Sie kombiniert Modell-Routing nach Aufgabenkomplexität, unveränderliche Kostenverfolgung mit frozen Dataclasses, enge Wiederholungslogik (nur bei vorübergehenden Fehlern) und Prompt-Caching. Die Pipeline ist als komponierbare Funktion konzipiert, die alle vier Techniken in einem Schritt zusammenführt und sich ideal für Anwendungen eignet, die Claude, GPT oder ähnliche APIs aufrufen, insbesondere bei Batch-Verarbeitung und Produktionssystemen mit Budgetgrenzen. Die Skill unterstützt Plattformen wie Claude Code und ähnliche KI-Agenten und enthält eine Preisreferenztabelle (Stand 2026) und Best Practices, um typische Anti-Patterns wie übermäßige Wiederholungen oder die Verwendung teurer Modelle für alle Anfragen zu vermeiden.

Funktioniert mit✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/cost-aware-llm-pipeline

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Kostenbewusste LLM-Pipeline?

Muster zur Kontrolle der LLM-API-Kosten bei gleichzeitiger Beibehaltung der Qualität. Kombiniert Modell-Routing, Budgetverfolgung, Wiederholungslogik und Prompt-Caching zu einer komponierbaren Pipeline.

Wann zu aktivieren

  • Erstellen von Anwendungen, die LLM-APIs (Claude, GPT, usw.) aufrufen
  • Verarbeiten von Batches mit Elementen unterschiedlicher Komplexität
  • Notwendigkeit, innerhalb eines Budgets für API-Ausgaben zu bleiben
  • Optimierung der Kosten, ohne bei komplexen Aufgaben die Qualität zu beeinträchtigen

Kernkonzepte

1. Modell-Routing nach Aufgabenkomplexität

Automatisch günstigere Modelle für einfache Aufgaben auswählen, teure Modelle für komplexe reservieren.

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

_SONNET_TEXT_THRESHOLD = 10_000  # Zeichen
_SONNET_ITEM_THRESHOLD = 30     # Elemente

def select_model(
    text_length: int,
    item_count: int,
    force_model: str | None = None,
) -> str:
    """Modell basierend auf Aufgabenkomplexität auswählen."""
    if force_model is not None:
        return force_model
    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:
        return MODEL_SONNET  # Komplexe Aufgabe
    return MODEL_HAIKU  # Einfache Aufgabe (3-4x günstiger)

2. Unveränderliche Kostenverfolgung

Kumulative Ausgaben mit frozen Dataclasses verfolgen. Jeder API-Aufruf gibt einen neuen Tracker zurück – mutiert niemals den Zustand.

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":
        """Gibt neuen Tracker mit hinzugefügtem Datensatz zurück (mutiert self nie)."""
        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. Enge Wiederholungslogik

Nur bei vorübergehenden Fehlern wiederholen. Bei Authentifizierungs- oder fehlerhaften Anfragefehlern schnell scheitern.

from anthropic import (
    APIConnectionError,
    InternalServerError,
    RateLimitError,
)

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

def call_with_retry(func, *, max_retries: int = _MAX_RETRIES):
    """Nur bei vorübergehenden Fehlern wiederholen, bei anderen sofort scheitern."""
    for attempt in range(max_retries):
        try:
            return func()
        except _RETRYABLE_ERRORS:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponentielles Backoff
    # AuthenticationError, BadRequestError usw. → sofort auslösen

4. Prompt-Caching

Lange System-Prompts cachen, um sie nicht bei jeder Anfrage erneut senden zu müssen.

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"},  # Dies cachen
            },
            {
                "type": "text",
                "text": user_input,  # Variabler Teil
            },
        ],
    }
]

Komposition

Alle vier Techniken in einer einzigen Pipeline-Funktion kombinieren:

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

    # 2. Budget prüfen
    if tracker.over_budget:
        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)

    # 3. Mit Wiederholung + Caching aufrufen
    response = call_with_retry(lambda: client.messages.create(
        model=model,
        messages=build_cached_messages(system_prompt, text),
    ))

    # 4. Kosten verfolgen (unveränderlich)
    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)
    tracker = tracker.add(record)

    return parse_result(response), tracker

Preisreferenz (2026)

ModellEingabe ($/1M Tokens)Ausgabe ($/1M Tokens)Relative Kosten
Haiku 3.5 (Legacy)$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 (Legacy)$15.00$75.0015x

Best Practices

  • Mit dem günstigsten Modell beginnen und nur zu teuren Modellen routen, wenn Komplexitätsschwellen erreicht sind
  • Explizite Budgetlimits setzen, bevor Batches verarbeitet werden – früh scheitern, statt zu viel auszugeben
  • Modellauswahlentscheidungen protokollieren, um Schwellenwerte basierend auf echten Daten anpassen zu können
  • Prompt-Caching für System-Prompts über 1024 Tokens verwenden – spart sowohl Kosten als auch Latenz
  • Nie bei Authentifizierungs- oder Validierungsfehlern wiederholen – nur bei vorübergehenden Fehlern (Netzwerk, Ratenlimit, Serverfehler)

Anti-Patterns, die vermieden werden sollten

  • Das teuerste Modell für alle Anfragen verwenden, unabhängig von der Komplexität
  • Bei allen Fehlern wiederholen (verschwendet Budget für dauerhafte Fehler)
  • Kostenverfolgungszustand mutieren (erschwert Debugging und Auditing)
  • Modellnamen hart im gesamten Codebase codieren (Konstanten oder Konfiguration verwenden)
  • Prompt-Caching für wiederholte System-Prompts ignorieren

Wann zu verwenden

  • Jede Anwendung, die Claude, OpenAI oder ähnliche LLM-APIs aufruft
  • Batch-Verarbeitungspipelines, bei denen die Kosten schnell steigen
  • Multi-Modell-Architekturen, die intelligentes Routing benötigen
  • Produktionssysteme, die Budgetgrenzen benötigen

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

Verwandte Skills