0Pricing
AI Prompt Engineering · 강의

비용과 지연 시간의 절충

사고 토큰 예산, 추론 비용, 하이브리드 라우팅 전략을 살펴봅니다.

비용과 지연 시간의 절충은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

비용·품질·지연 시간의 삼각형

LLM 시스템 설계에는 근본적인 삼각형이 있습니다. 바로 비용, 품질, 지연 시간입니다. 어느 시점에서든 이 세 가지 중 최대 두 가지에 대해서만 최적화할 수 있습니다.

  • 낮은 비용 + 높은 품질 = 느림(추론 모델, 느린 생성)
  • 낮은 비용 + 짧은 지연 시간 = 낮은 품질(소형·고속 모델)
  • 높은 품질 + 짧은 지연 시간 = 높은 비용(스트리밍을 사용하는 추론 모델)

모든 시스템 구조 결정은 이 삼각형 안에서 상충 관계를 이룹니다.

추론 모델의 가격 책정

사고 토큰에는 표준 입력 토큰과 출력 토큰 비용에 더해 추가 비용이 발생합니다. 추론 모델 호출 비용에는 입력 토큰 + 사고 토큰 + 출력 토큰이 포함됩니다.

빠르고 작은 모델과 비교하면 토큰당 o3는 GPT-4o-mini보다 대략 20배 비싸고, 확장 사고 기능을 사용하는 Claude Opus는 출력 토큰당 Claude Haiku보다 대략 10~15배 비쌉니다.

# Rough cost estimates (2025 pricing, may change)
# Source: provider pricing pages

PRICING = {
    # (input $/1M tokens, output $/1M tokens)
    'gpt-4o-mini':       (0.15,   0.60),
    'gpt-4o':            (2.50,  10.00),
    'o3-mini':           (1.10,   4.40),
    'o3':                (10.0,  40.00),
    'claude-haiku-4-5':  (0.25,   1.25),
    'claude-sonnet-4-5': (3.00,  15.00),
    'claude-opus-4-5':   (15.0,  75.00),
}

def estimate_cost(model, input_tokens, output_tokens, thinking_tokens=0):
    inp_price, out_price = PRICING[model]
    # Thinking tokens billed as output tokens
    total_out = output_tokens + thinking_tokens
    cost = (input_tokens / 1e6 * inp_price) + (total_out / 1e6 * out_price)
    return cost

# A single hard question with 8000 thinking tokens:
cost = estimate_cost('claude-opus-4-5', 500, 300, thinking_tokens=8000)
print(f'Cost per call: ${cost:.4f}')

사고 토큰 오버헤드

사고 토큰은 출력 토큰보다 훨씬 많은 경우가 많습니다. 간결한 200단어 답변도 5,000~15,000개의 사고 토큰을 바탕으로 생성될 수 있습니다. 이러한 사고 토큰에도 출력 토큰과 동일한 비용이 부과됩니다.

따라서 추론 모델의 비용 배수는 답변 길이보다 사고 토큰에 의해 주로 결정됩니다.

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

def analyze_token_breakdown(question, budget_tokens):
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=budget_tokens + 2000,
        thinking={'type': 'enabled', 'budget_tokens': budget_tokens},
        messages=[{'role': 'user', 'content': question}]
    )

    # Usage breakdown
    usage = response.usage
    print(f'Input tokens:  {usage.input_tokens:,}')
    print(f'Output tokens: {usage.output_tokens:,}')

    # Thinking tokens are in cache_creation_input_tokens on some APIs
    # or can be estimated from thinking block content length
    thinking_blocks = [b for b in response.content if b.type == 'thinking']
    est_thinking = sum(len(b.thinking.split()) * 1.3 for b in thinking_blocks)
    print(f'Est. thinking tokens: {int(est_thinking):,}')
    answer = next(b.text for b in response.content if b.type == 'text')
    print(f'Answer words: {len(answer.split())}')

analyze_token_breakdown(
    'Explain the trade-offs between REST and GraphQL APIs.',
    budget_tokens=5000
)

지연 시간: 예상되는 범위

모델 구성별로 관찰된 지연 시간의 범위는 다음과 같습니다. 부하와 문제 난이도에 따라 크게 달라질 수 있습니다.

  • Claude Haiku: 0.5~2초
  • Claude Sonnet: 2~8초
  • Claude Opus (사고 기능 없음): 5~15초
  • Claude Opus (사고 5K): 15~40초
  • Claude Opus (사고 16K): 40~90초
  • o3 (높은 작업량): 30~120초
import time
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

def benchmark_latency(prompt, model, budget_tokens=None):
    kwargs = {
        'model': model,
        'max_tokens': 2000,
        'messages': [{'role': 'user', 'content': prompt}]
    }
    if budget_tokens:
        kwargs['thinking'] = {'type': 'enabled', 'budget_tokens': budget_tokens}
        kwargs['max_tokens'] = budget_tokens + 2000

    start = time.time()
    response = client.messages.create(**kwargs)
    elapsed = time.time() - start
    answer = response.content[-1].text
    print(f'{model} (budget={budget_tokens}): {elapsed:.1f}s')
    return elapsed, answer

benchmark_latency('Name 3 planets', 'claude-haiku-4-5')
benchmark_latency('Solve x^2 - 5x + 6 = 0', 'claude-opus-4-5', 3000)
benchmark_latency('Design a fault-tolerant payment system', 'claude-opus-4-5', 10000)

스트리밍을 사용한 첫 토큰까지의 시간

추론 모델의 전체 지연 시간은 길지만, 스트리밍을 사용하면 첫 토큰까지의 시간(TTFT)은 훨씬 짧아질 수 있습니다. 모델은 사고를 마친 직후 답변 스트리밍을 시작합니다. 스트리밍을 사용해 사용자에게 빠르게 무언가를 보여 주십시오.

import anthropic
import time

client = anthropic.Anthropic(api_key='sk-ant-...')

def stream_with_timing(prompt):
    start = time.time()
    first_token_time = None
    full_text = ''

    with client.messages.stream(
        model='claude-opus-4-5',
        max_tokens=10000,
        thinking={'type': 'enabled', 'budget_tokens': 5000},
        messages=[{'role': 'user', 'content': prompt}]
    ) as stream:
        in_answer = False
        for text_chunk in stream.text_stream:
            if not in_answer:
                in_answer = True
                first_token_time = time.time() - start
                print(f'Time to first answer token: {first_token_time:.1f}s')
            full_text += text_chunk
            print(text_chunk, end='', flush=True)

    total_time = time.time() - start
    print(f'\nTotal time: {total_time:.1f}s')

stream_with_timing('List 5 key benefits of microservices.')

하이브리드 아키텍처 패턴

실용적인 운영 환경 패턴은 먼저 빠른 표준 모델을 사용하는 것입니다. 결과가 만족스러우면 품질 지표로 확인한 뒤 즉시 반환합니다. 만족스럽지 않으면 추론 모델로 넘깁니다. 이렇게 하면 평균 지연 시간과 비용은 낮추면서 어려운 사례에서는 높은 정확도를 얻을 수 있습니다.

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

def hybrid_query(question, quality_threshold=0.7):
    # Step 1: Try fast model first
    r_fast = client.messages.create(
        model='claude-haiku-4-5',
        max_tokens=300,
        messages=[{'role': 'user', 'content': question}]
    )
    fast_answer = r_fast.content[0].text

    # Step 2: Quick confidence check
    confidence_check = client.messages.create(
        model='claude-haiku-4-5',
        max_tokens=20,
        messages=[{
            'role': 'user',
            'content': (
                f'Q: {question}\nA: {fast_answer}\n'
                f'Rate answer quality 0.0-1.0. Number only:'
            )
        }]
    )
    try:
        quality = float(confidence_check.content[0].text.strip())
    except ValueError:
        quality = 0.5

    if quality >= quality_threshold:
        return fast_answer, 'fast'

    # Step 3: Escalate to reasoning model
    r_slow = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=8000,
        thinking={'type': 'enabled', 'budget_tokens': 6000},
        messages=[{'role': 'user', 'content': question}]
    )
    return next(b.text for b in r_slow.content if b.type == 'text'), 'reasoning'

대규모 운영 비용: 계산해 보기

테스트에서는 감당할 만해 보이는 추론 모델도 대규모로 운영하면 상당한 비용이 됩니다. 아키텍처를 선택하기 전에 항상 비용을 예측하십시오.

def project_monthly_cost(daily_queries, model_config):
    """
    Project monthly API costs for different configurations.
    model_config: dict with 'cost_per_query' key
    """
    monthly_queries = daily_queries * 30
    monthly_cost = monthly_queries * model_config['cost_per_query']

    print(f'Daily queries: {daily_queries:,}')
    print(f'Monthly queries: {monthly_queries:,}')
    print(f'Cost per query: ${model_config["cost_per_query"]:.4f}')
    print(f'Monthly cost: ${monthly_cost:,.2f}')
    return monthly_cost

# Compare configurations at 10,000 queries/day
configs = [
    {'name': 'All Haiku', 'cost_per_query': 0.0005},
    {'name': 'All Sonnet', 'cost_per_query': 0.015},
    {'name': 'All Opus+Thinking', 'cost_per_query': 0.85},
    {'name': 'Hybrid (90% Haiku, 10% Opus)', 'cost_per_query': 0.9*0.0005 + 0.1*0.85},
]

for config in configs:
    print(f'\n--- {config["name"]} ---')
    project_monthly_cost(10_000, config)

비용 절감을 위한 프롬프트 캐싱

길고 반복되는 시스템 프롬프트나 컨텍스트를 사용하는 추론 모델 호출에는 프롬프트 캐싱을 사용하십시오. 캐시된 토큰은 캐시되지 않은 토큰보다 비용이 90% 저렴합니다. 동일한 대규모 컨텍스트(문서, 코드)를 반복해서 전송할 때 특히 효과적입니다.

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

LONG_CONTEXT = 'A' * 50000  # Simulated large document

# With prompt caching: mark large context as cacheable
response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=10000,
    thinking={'type': 'enabled', 'budget_tokens': 6000},
    system=[
        {
            'type': 'text',
            'text': f'You are analyzing this document: {LONG_CONTEXT}',
            'cache_control': {'type': 'ephemeral'}  # Cache this prefix
        }
    ],
    messages=[{
        'role': 'user',
        'content': 'What are the main themes in this document?'
    }]
)

usage = response.usage
print(f'Cache read tokens: {getattr(usage, "cache_read_input_tokens", 0):,}')
print(f'Cache creation tokens: {getattr(usage, "cache_creation_input_tokens", 0):,}')
# Second call with same system content costs ~90% less on cached tokens

비용 효율을 위한 일괄 처리

OpenAI와 Anthropic은 모두 시간에 민감하지 않은 요청에 대해 비용을 50% 할인하는 일괄 처리 인터페이스를 제공합니다. 결과를 몇 시간 기다릴 수 있는 대량의 질의가 있다면 일괄 처리가 가장 비용 효율적인 선택입니다.

import anthropic
import json

client = anthropic.Anthropic(api_key='sk-ant-...')

# Batch API: 50% cheaper, 24-hour turnaround
requests = [
    {
        'custom_id': f'query_{i}',
        'params': {
            'model': 'claude-opus-4-5',
            'max_tokens': 1024,
            'messages': [{'role': 'user', 'content': f'Analyze dataset row {i}'}]
        }
    }
    for i in range(100)  # 100 queries in one batch
]

# Submit batch
batch = client.messages.batches.create(requests=requests)
print(f'Batch ID: {batch.id}')
print(f'Status: {batch.processing_status}')
print(f'Requests: {batch.request_counts}')
# Poll batch.id for results when processing_status == 'ended'

토큰 예산 최적화

문제 유형에 맞게 budget_tokens의 크기를 조정하십시오. 단순한 문제에 16K 예산을 사용하면 토큰이 낭비되고 지연 시간이 늘어납니다. 문제 난이도 등급을 기준으로 예산 조회표를 만드십시오.

BUDGET_LOOKUP = {
    'simple_math':        1000,   # Arithmetic, basic algebra
    'medium_code':        3000,   # Function implementation, debugging
    'complex_reasoning':  8000,   # System design, complex analysis
    'research_grade':    16000,   # Proofs, research-level problems
}

def budget_for_query(query):
    q_lower = query.lower()
    if any(kw in q_lower for kw in ['calculate', 'what is', 'how many', 'convert']):
        return BUDGET_LOOKUP['simple_math']
    elif any(kw in q_lower for kw in ['code', 'function', 'bug', 'implement']):
        return BUDGET_LOOKUP['medium_code']
    elif any(kw in q_lower for kw in ['design', 'architecture', 'analyze', 'strategy']):
        return BUDGET_LOOKUP['complex_reasoning']
    else:
        return BUDGET_LOOKUP['medium_code']  # Safe default

print(budget_for_query('What is 15% of 340?'))       # 1000
print(budget_for_query('Implement a trie in Python')) # 3000
print(budget_for_query('Design a CDC pipeline'))      # 8000

LLM 애플리케이션의 SLA 설정

표준 모델과 추론 모델 중 하나를 선택하기 전에 애플리케이션의 서비스 수준 계약(SLA) 요구 사항을 정의하십시오.

  • P50 지연 시간: 일반적인 사용자 경험
  • P99 지연 시간: 최악의 사용자 경험
  • 토큰 예산: 사용자 질의당 최대 비용
  • 품질 기준선: 테스트 세트에서 허용되는 최소 정확도

추론 모델은 대화형 애플리케이션에서 P99 지연 시간 SLA를 쉽게 위반합니다. 아키텍처 결정을 확정하기 전에 제약 조건을 파악하십시오.

지식 확인: 추론 모델 비용

표준 모델과 비교할 때 추론 모델의 높은 비용을 유발하는 주된 요인은 무엇입니까?

복습: 비용과 지연 시간의 상충 관계

추론 모델은 비쌉니다. 사고 토큰은 출력 토큰으로 청구되며, 눈에 보이는 답변보다 10~50배 많을 수 있습니다. 어려운 문제의 지연 시간은 15~120초에 이릅니다. 다음 방법으로 완화할 수 있습니다. 하이브리드 패턴을 사용해 먼저 빠른 모델을 호출하고 확신이 낮을 때만 상위 모델로 넘기며, 반복되는 대규모 컨텍스트에는 프롬프트 캐싱을 사용하고 캐시된 토큰에 90% 할인을 적용하며, 오프라인 작업에는 일괄 처리 인터페이스를 사용해 50% 할인을 받고, 문제 난이도에 맞게 budget_tokens의 크기를 조정하십시오. 대규모로 운영하면 질의당 작은 비용도 누적되어 큰 월별 청구액이 됩니다. 아키텍처를 확정하기 전에 항상 비용을 예측하십시오.

자주 묻는 질문

“비용과 지연 시간의 절충” 강의는 무료인가요?

네 — “비용과 지연 시간의 절충” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“비용과 지연 시간의 절충”에서 뭘 배우나요?

사고 토큰 예산, 추론 비용, 하이브리드 라우팅 전략을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“비용과 지연 시간의 절충” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 추론 모델은 어떻게 다른가요?
  2. 확장된 사고를 위한 효과적인 프롬프트
  3. 추론 모델과 일반 모델은 언제 사용할까요?
  4. 비용과 지연 시간의 절충
← AI Prompt Engineering(으)로 돌아가기