Communitygithub.com

비용 인식 LLM 파이프라인

LLM API 사용 비용을 제어하면서도 품질을 유지하는 패턴입니다. 작업 복잡도에 따른 모델 라우팅, 예산 추적, 재시도 로직, 프롬프트 캐싱을 조합한 파이프라인입니다. LLM 비용을 낮춰야 하거나 작업을 여러 모델 및 예산에 걸쳐 라우팅할 때 사용하세요.

비용 인식 LLM 파이프라인란 무엇인가요?

이 스킬은 LLM API 비용을 최적화하는 파이프라인 패턴을 제공합니다. 작업 복잡도에 따라 값비싼 모델(예: Claude Sonnet)과 저렴한 모델(예: Claude Haiku)을 자동으로 선택하는 모델 라우팅, 불변 데이터클래스를 사용해 누적 비용을 추적하고 예산 초과 시 빠르게 실패하는 비용 추적기, 일시적인 네트워크 오류나 속도 제한 등에만 재시도하고 인증 오류 등 영구적 오류는 즉시 실패하는 재시도 로직, 반복되는 시스템 프롬프트를 캐싱하여 비용과 지연 시간을 줄이는 프롬프트 캐싱을 결합합니다. 이 모든 기술을 하나의 파이프라인 함수로 조합할 수 있어 Claude, GPT 등 LLM API를 사용하는 모든 애플리케이션에 적용 가능합니다. 특히 예산 제약이 있는 배치 처리 시스템이나 다중 모델 아키텍처에서 유용하며, 코드 예제와 함께 실제 구현 방법을 상세히 제공합니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

비용 인식 LLM 파이프라인은(는) 무엇을 하나요?

LLM API 비용을 제어하면서도 품질을 유지하는 패턴입니다. 모델 라우팅, 예산 추적, 재시도 로직, 프롬프트 캐싱을 조합 가능한 파이프라인으로 결합합니다.

활성화 시점

  • LLM API(Claude, GPT 등)를 호출하는 애플리케이션 구축 시
  • 다양한 복잡도의 항목을 배치 처리할 때
  • API 사용 비용을 예산 내로 유지해야 할 때
  • 복잡한 작업의 품질 저하 없이 비용 최적화가 필요할 때

핵심 개념

1. 작업 복잡도에 따른 모델 라우팅

간단한 작업에는 자동으로 저렴한 모델을 선택하고, 복잡한 작업에는 고비용 모델을 예약합니다.

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

_SONNET_TEXT_THRESHOLD = 10_000  # 문자 수
_SONNET_ITEM_THRESHOLD = 30     # 항목 수

def select_model(
    text_length: int,
    item_count: int,
    force_model: str | None = None,
) -> str:
    """작업 복잡도에 따라 모델을 선택합니다."""
    if force_model is not None:
        return force_model
    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:
        return MODEL_SONNET  # 복잡한 작업
    return MODEL_HAIKU  # 간단한 작업 (3~4배 저렴)

2. 불변 비용 추적

불변 데이터클래스로 누적 비용을 추적합니다. 각 API 호출은 새 추적기를 반환하며, 상태를 변경하지 않습니다.

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 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. 좁은 범위의 재시도 로직

일시적인 오류에 대해서만 재시도합니다. 인증 오류나 잘못된 요청 오류는 즉시 실패합니다.

from anthropic import (
    APIConnectionError,
    InternalServerError,
    RateLimitError,
)

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

def call_with_retry(func, *, max_retries: int = _MAX_RETRIES):
    """일시적인 오류에 대해서만 재시도하고, 다른 오류는 즉시 실패합니다."""
    for attempt in range(max_retries):
        try:
            return func()
        except _RETRYABLE_ERRORS:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # 지수 백오프
    # AuthenticationError, BadRequestError 등은 즉시 발생

4. 프롬프트 캐싱

긴 시스템 프롬프트를 캐싱하여 매 요청마다 다시 보내지 않도록 합니다.

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"},  # 캐싱
            },
            {
                "type": "text",
                "text": user_input,  # 가변 부분
            },
        ],
    }
]

조합

네 가지 기술을 모두 하나의 파이프라인 함수로 결합합니다.

def process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:
    # 1. 모델 라우팅
    model = select_model(len(text), estimated_items, config.force_model)

    # 2. 예산 확인
    if tracker.over_budget:
        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)

    # 3. 재시도 + 캐싱으로 호출
    response = call_with_retry(lambda: client.messages.create(
        model=model,
        messages=build_cached_messages(system_prompt, text),
    ))

    # 4. 비용 추적 (불변)
    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)
    tracker = tracker.add(record)

    return parse_result(response), tracker

가격 참고 (2026년)

모델입력 ($/100만 토큰)출력 ($/100만 토큰)상대 비용
Haiku 3.5 (레거시)$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 (레거시)$15.00$75.0015x

모범 사례

  • 가장 저렴한 모델로 시작하고 복잡도 임계값을 초과할 때만 고비용 모델로 라우팅하세요
  • 배치 처리 전에 명시적인 예산 한도를 설정하세요 — 초과 지출보다는 조기 실패가 낫습니다
  • 모델 선택 결정을 로깅하여 실제 데이터를 기반으로 임계값을 조정할 수 있도록 하세요
  • 1024 토큰 이상의 시스템 프롬프트에 프롬프트 캐싱을 사용하세요 — 비용과 지연 시간을 모두 절약합니다
  • 인증 또는 검증 오류에서는 절대 재시도하지 마세요 — 일시적인 오류(네트워크, 속도 제한, 서버 오류)에만 재시도하세요

피해야 할 안티패턴

  • 복잡도와 관계없이 모든 요청에 가장 비싼 모델 사용
  • 모든 오류에서 재시도 (영구적 실패에 예산 낭비)
  • 비용 추적 상태 변경 (디버깅 및 감사가 어려워짐)
  • 코드베이스 전체에 모델 이름 하드코딩 (상수 또는 설정 사용)
  • 반복되는 시스템 프롬프트에 프롬프트 캐싱 무시

사용 시기

  • Claude, OpenAI 또는 유사 LLM API를 호출하는 모든 애플리케이션
  • 비용이 빠르게 증가하는 배치 처리 파이프라인
  • 지능적 라우팅이 필요한 다중 모델 아키텍처
  • 예산 보호 장치가 필요한 프로덕션 시스템

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.

관련 스킬