본문 바로가기
C.W.K.
Stream
Lesson 02 of 04 · published

비용 최적화 라우팅

~12 min · cost, routing, model-selection

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

가장 큰 비용 조절 장치

Pro는 출력 토큰당 Flash-Lite보다 약 22.5배 비싸. 트래픽 대부분에는 Pro가 필요하지 않아. 일상 작업은 Flash-Lite, 기본 작업은 Flash, 정말 필요할 때만 Pro로 보내는 지능형 라우터는 보통 운영 청구서를 70–90% 줄여.

라우팅 판단 기준

  • 추론이 필요한가? 여러 단계의 논리, 코드, 수학은 Pro로 보내.
  • 컨텍스트가 큰가? 200K토큰을 넘으면 Pro로 보내. Pro가 긴 컨텍스트를 가장 잘 다루고 Flash와 Flash-Lite는 품질이 떨어질 수 있어.
  • 도구를 쓰는가? 여러 도구를 복잡하게 호출하는 에이전트형 반복은 Pro, 단순한 도구 하나의 호출은 Flash가 맞아.
  • 지연 시간이 빡빡한가? 500ms 미만이 필요하면 가장 작고 TTFT가 빠른 Flash-Lite를 골라.
  • 물량이 많은가? 대량의 단순 작업은 Flash-Lite로 보내.

실제 수치

전략상대 비용알맞은 경우
항상 Pro1.0x최고 품질이 필요하고 비용 상한이 없을 때
지능형 라우팅약 0.3x대부분의 운영 앱
Flash-Lite만약 0.04x대량의 단순 작업
캐싱 사용캐시된 호출당 약 0.1xPDF 질의응답처럼 컨텍스트를 반복할 때
Batch API(오프라인)0.5x비동기 파이프라인

Code

지능형 라우터 — 최소 버전·python
class SmartRouter:
    """Pick the cheapest capable Gemini model for a request."""

    def route(
        self,
        needs_tools: bool = False,
        needs_reasoning: bool = False,
        max_context: int = 0,
        latency_budget_ms: int = 10_000,
    ) -> str:
        # Tight latency budget — go straight to Flash-Lite
        if latency_budget_ms < 500:
            return 'gemini-2.5-flash-lite'

        # Reasoning or huge context — Pro is the only safe choice
        if needs_reasoning or max_context > 200_000:
            return 'gemini-2.5-pro'

        # Tools without reasoning — Flash handles fine
        if needs_tools or max_context > 50_000:
            return 'gemini-2.5-flash'

        # Simple high-volume — cheapest model
        return 'gemini-2.5-flash-lite'

router = SmartRouter()
model = router.route(
    needs_tools=True,
    needs_reasoning=False,
    max_context=80_000,
)
print(model)  # 'gemini-2.5-flash'
살펴본 뒤 선택하기 — 프롬프트 자체 분류·python
async def route_by_classification(prompt: str) -> str:
    """Use Flash-Lite to decide which model the real prompt deserves."""
    classifier = await client.aio.models.generate_content(
        model='gemini-2.5-flash-lite',
        contents=(
            'Classify the following user request into exactly one bucket: '
            'CHAT (simple Q&A), CODE (writing or debugging code), '
            'REASON (multi-step logic), or AGENT (multi-tool workflow). '
            f'Output only the bucket name.\n\nRequest: {prompt}'
        ),
        config={'max_output_tokens': 10, 'temperature': 0.0},
    )
    bucket = classifier.text.strip().upper()
    return {
        'CHAT':   'gemini-2.5-flash-lite',
        'CODE':   'gemini-2.5-flash',
        'REASON': 'gemini-2.5-pro',
        'AGENT':  'gemini-2.5-pro',
    }.get(bucket, 'gemini-2.5-flash')

External links

Exercise

첫 코드 블록의 지능형 라우터를 만들어 앞 레슨의 GeminiAdapter에 연결해. 생성할 때 모델을 고정하지 말고 호출마다 선택하게 해. 채팅, 추론, 긴 컨텍스트를 섞은 프롬프트 100개를 실행해 어느 모델이 선택됐는지 기록하고, 항상 Pro와 항상 Flash-Lite를 쓰는 기준선에 비해 비용이 얼마나 드는지 계산해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.