본문 바로가기
AI2024년 4월 20일7분 읽기

LLM 토큰 최적화 — 비용 50% 절감하는 프롬프트 기법

YS
김영삼
조회 532

토큰이란 무엇인가

LLM에서 토큰은 텍스트를 처리하는 기본 단위입니다. 영어 1 토큰은 약 4글자, 한국어는 한 글자가 2-3 토큰을 소비합니다. GPT-4의 경우 입력 토큰당 $0.03/1K, 출력 토큰당 $0.06/1K이므로 토큰 최적화는 곧 비용 절감입니다.

토큰 사용량 측정하기

import tiktoken

def count_tokens(text, model="gpt-4"):
    encoding = tiktoken.encoding_for_model(model)
    tokens = encoding.encode(text)
    return len(tokens)

# 사용 예시
prompt = "PostgreSQL에서 인덱스를 최적화하는 방법을 설명해주세요."
print(f"토큰 수: {count_tokens(prompt)}")  # 약 25-30 토큰

# 한국어는 토큰 효율이 낮음
en = "Explain PostgreSQL index optimization."
ko = "PostgreSQL 인덱스 최적화를 설명해주세요."
print(f"영어: {count_tokens(en)} tokens")   # ~7
print(f"한국어: {count_tokens(ko)} tokens")  # ~20

프롬프트 최적화 기법

1. 시스템 메시지 압축

시스템 메시지는 매 요청마다 포함되므로, 간결하게 작성하는 것이 누적 비용에 큰 영향을 줍니다.

# BAD: 장황한 시스템 메시지 (약 200 토큰)
system_bad = """
당신은 매우 친절하고 전문적인 시니어 소프트웨어 엔지니어입니다.
사용자의 질문에 대해 항상 정확하고 상세한 답변을 제공해야 합니다.
코드 예제를 포함하고, 장단점을 분석하며, 실제 프로덕션에서의
경험을 바탕으로 조언해 주세요. 답변은 한국어로 합니다.
"""

# GOOD: 핵심만 담은 시스템 메시지 (약 40 토큰)
system_good = "Senior SW engineer. Answer in Korean with code examples."

2. Few-shot을 One-shot으로 줄이기

Few-shot 예제가 3-5개 필요한 경우, 가장 대표적인 1개로 줄이고 나머지는 지시문으로 대체할 수 있습니다.

3. 출력 형식 제한

# 출력 토큰 제한으로 비용 절감
response = openai.chat.completions.create(
    model="gpt-4",
    messages=messages,
    max_tokens=500,           # 출력 토큰 상한
    temperature=0,            # 결정론적 출력
    response_format={"type": "json_object"}  # JSON 강제
)

시스템 수준 최적화

프롬프트 캐싱

동일한 시스템 메시지와 프롬프트 접두사에 대해 캐싱을 적용하면, 반복 요청에서 입력 토큰을 크게 절감할 수 있습니다.

import hashlib
import redis

r = redis.Redis()

def cached_completion(messages, **kwargs):
    cache_key = hashlib.sha256(
        str(messages).encode()
    ).hexdigest()

    cached = r.get(cache_key)
    if cached:
        return cached.decode()

    response = openai.chat.completions.create(
        model="gpt-4",
        messages=messages,
        **kwargs
    )
    result = response.choices[0].message.content
    r.setex(cache_key, 3600, result)  # 1시간 캐시
    return result

모델 선택 전략

작업 유형권장 모델비용 (1K tokens)
분류, 추출GPT-3.5-turbo$0.0005 / $0.0015
요약, 번역GPT-3.5-turbo$0.0005 / $0.0015
코드 생성GPT-4$0.03 / $0.06
복잡한 추론GPT-4$0.03 / $0.06

비용 모니터링 대시보드

from collections import defaultdict

class TokenTracker:
    def __init__(self):
        self.usage = defaultdict(lambda: {"input": 0, "output": 0, "cost": 0})

    def track(self, model, usage):
        rates = {
            "gpt-4": (0.03, 0.06),
            "gpt-3.5-turbo": (0.0005, 0.0015)
        }
        inp_rate, out_rate = rates.get(model, (0.03, 0.06))
        cost = (usage.prompt_tokens * inp_rate +
                usage.completion_tokens * out_rate) / 1000

        self.usage[model]["input"] += usage.prompt_tokens
        self.usage[model]["output"] += usage.completion_tokens
        self.usage[model]["cost"] += cost

    def report(self):
        for model, data in self.usage.items():
            print(f"{model}: {data['input']+data['output']} tokens, ${data['cost']:.4f}")

핵심 정리

  • 시스템 메시지를 50토큰 이내로 압축하면 수천 건 요청에서 비용 차이가 큽니다.
  • 단순 작업은 GPT-3.5-turbo로 라우팅하고, 복잡한 추론만 GPT-4를 사용하세요.
  • 프롬프트 캐싱을 적용하면 동일/유사 요청에서 API 호출 자체를 줄일 수 있습니다.
  • max_tokens과 response_format을 활용하여 출력 토큰을 제한하세요.
  • 토큰 사용량을 지속적으로 모니터링하고 비정상 사용 패턴을 감지하세요.

댓글 0

아직 댓글이 없습니다.
Ctrl+Enter로 등록