본문으로 건너뛰기
Skillpedia
에이전트48k · #5082

llm-cost-optimization

하는 일

이 도구는 인공지능(AI) 사용 비용을 낮추는 데 도움을 줍니다. 각 작업에 맞는 모델을 고르고, 자주 쓰는 답변을 저장해 다시 묻지 않으며(캐싱), 여러 요청을 묶어 한 번에 처리하도록 제안합니다.

사용하는 경우

  • ✓AI 지출이 빠르게 늘어날 때.
  • ✓팀이나 제품별로 AI 비용을 추적해야 할 때.
  • ✓같은 질문을 AI에 반복하지 않으려 할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/llm-cost-optimization/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/llm-cost-optimization/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“간단한 질문에는 더 저렴한 AI 모델을 쓰려면 어떻게 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

도구는 AI를 사용하는 방식을 분석해 최적화를 제안합니다. 쉬운 작업에는 더 작고 저렴한 모델을 쓰고, 답변을 저장해 다시 생성하지 않으며, 작업을 묶어 일괄 처리하도록 제안합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

LLM Cost Optimization

Cut LLM costs by 50–90% with the right combination of caching, model selection, prompt optimization, and self-hosting.

When to Use This Skill

Use this skill when:

  • LLM API spend is growing faster than revenue
  • You need to attribute AI costs to teams, products, or customers
  • Implementing caching to avoid redundant LLM calls
  • Deciding when to switch from API providers to self-hosted models
  • Optimizing prompt length without sacrificing quality

Cost Levers by Impact

Strategy Typical Savings Effort
Semantic caching 20–50% Low
Model right-sizing 30–70% Low
Prompt compression 10–30% Medium
Provider caching (prompt cache) 10–25% Low
Batching offline workloads 50% (Batch API) Medium
Self-hosting 7–8B models 80–95% at scale High
Quantization 30–50% VRAM cost Medium

Track Costs First

# Use LiteLLM's cost tracking (automatic per-model pricing)
import litellm

response = litellm.completion(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello"}],
)
cost = litellm.completion_cost(response)
print(f"Cost: ${cost:.6f}")

# Add custom cost callbacks
def log_cost(kwargs, completion_response, start_time, end_time):
    cost = kwargs.get("response_cost", 0)
    model = kwargs.get("model")
    user = kwargs.get("user")
    # Send to your analytics DB
    db.record_cost(user=user, model=model, cost=cost)

litellm.success_callback = [log_cost]

Model Right-Sizing

# Route by task complexity — don't use GPT-4o for everything
def get_model_for_task(task_type: str) -> str:
    routing = {
        "classification":     "gpt-4o-mini",      # ~30× cheaper than gpt-4o
        "summarization":      "gpt-4o-mini",
        "extraction":         "gpt-4o-mini",
        "simple_qa":          "gpt-4o-mini",
        "complex_reasoning":  "gpt-4o",
        "code_generation":    "claude-sonnet-4-6",
        "creative_writing":   "claude-opus-4-6",
    }
    return routing.get(task_type, "gpt-4o-mini")

# Cost comparison (per 1M tokens, 2025 approx.)
# gpt-4o-mini:          input $0.15 / output $0.60
# gpt-4o:               input $2.50 / output $10.00
# claude-sonnet-4-6:    input $3.00 / output $15.00
# llama-3.1-8b (self):  ~$0.05–0.10 all-in (GPU amortized)

Prompt Caching (Provider-Side)

# Anthropic — cache long system prompts (saves 90% on cached tokens)
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are a helpful assistant.",
        },
        {
            "type": "text",
            "text": open("large-context.txt").read(),  # large doc
            "cache_control": {"type": "ephemeral"},     # cache this!
        }
    ],
    messages=[{"role": "user", "content": "Summarize the key points."}],
)
# First call: full price. Subsequent calls: 90% discount on cached part.
print(f"Cache read tokens: {response.usage.cache_read_input_tokens}")

# OpenAI — prompt caching is automatic for repeated prefixes >1024 tokens
# No code change needed; check usage.prompt_tokens_details.cached_tokens

Batching with OpenAI Batch API (50% Discount)

import json
from openai import OpenAI

client = OpenAI()

# Prepare batch requests
requests = [
    {
        "custom_id": f"task-{i}",
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": {
            "model": "gpt-4o-mini",
            "messages": [{"role": "user", "content": f"Classify: {text}"}],
            "max_tokens": 50,
        }
    }
    for i, text in enumerate(texts)
]

# Write JSONL file
with open("batch.jsonl", "w") as f:
    for req in requests:
        f.write(json.dumps(req) + "\n")

# Upload and create batch
batch_file = client.files.create(file=open("batch.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
    input_file_id=batch_file.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)
print(f"Batch ID: {batch.id}")  # poll status with client.batches.retrieve(batch.id)

Semantic Caching

import hashlib
import json
import redis
import numpy as np
from sentence_transformers import SentenceTransformer

r = redis.Redis(host="localhost", port=6379)
embed_model = SentenceTransformer("BAAI/bge-small-en-v1.5")

SIMILARITY_THRESHOLD = 0.92

…
자주 묻는 질문

‘캐싱’이란 무엇인가요?

빠른 메모리와 같습니다. AI가 이전에 답한 질문이라면 저장된 답변을 사용해 다시 생각할 필요가 없으므로 시간과 비용을 아낍니다.

‘모델 크기 조정(model right-sizing)’이란 무엇인가요?

작업에 맞는 AI 모델을 고른다는 뜻입니다. 간단한 작업에 아주 강력한 모델을 쓰는 것은 빵을 사러 트럭을 몰고 가는 것과 같아 비용이 더 듭니다. 도구는 알맞은 ‘크기’를 고르도록 돕습니다.

‘배칭(batching)’이란 무엇인가요?

여러 작업이나 요청을 하나의 묶음으로 모아 함께 처리하는 것입니다. 편지를 하나씩 보내는 대신 한꺼번에 보내는 것처럼 더 효율적입니다.

상세 정보

작성자의 원본 설명

Reduce LLM API and infrastructure costs through model selection, prompt caching, batching, caching, quantization, and self-hosting strategies.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5082
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬