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

컨텍스트 캐싱과 File API

~14 min · caching, file-api, cost

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

컨텍스트 캐싱 — 90% 할인

같은 긴 컨텍스트에 여러 질문을 던질 거라면 PDF, 코드베이스, 녹취록을 한 번 캐시하고 이후 질문마다 약 10%의 토큰 비용만 내. Flash의 실제 단가는 일반 입력 $0.30/M에서 캐시된 입력 $0.03/M으로 내려가.

캐시할 수 있는 최소 크기

  • Flash: 최소 1,024토큰.
  • Pro: 최소 4,096토큰.

최소 크기보다 작으면 캐싱은 아무 효과가 없고 일반 입력 단가를 그대로 내.

TTL을 정할 수 있어

기본값은 1시간이야. ttl='300s'처럼 기간 문자열로 설정해. 캐시는 토큰과 시간에 따라 과금되므로 큰 컨텍스트를 오래 유지하는 것 자체가 비용이야. 실제로 다시 쓸 시간대에 TTL을 맞춰.

호출이 끝난 뒤에도 쓸 파일에는 File API

앞 멀티모달 레슨에서 본 File API와 같아. 파일은 48시간 동안 유지되고, 그동안 여러 캐시나 생성 호출에 다시 붙일 수 있어.

Code

PDF를 캐시해 여러 질문에 쓰기·python
from google import genai
from google.genai import types

client = genai.Client()

# 1. Upload the doc
doc = client.files.upload(
    file='whitepaper.pdf',
    config=dict(mime_type='application/pdf'),
)

# 2. Create a cache
cache = client.caches.create(
    model='gemini-2.5-flash',
    config=types.CreateCachedContentConfig(
        system_instruction='You are a precise document analyst.',
        contents=[doc],
        ttl='300s',  # 5 minutes; raise for longer reuse windows
    ),
)

# 3. Ask many questions, each cheap
for question in ['Summarize.', 'List the methods.', "What's the headline result?"]:
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents=question,
        config=types.GenerateContentConfig(
            cached_content=cache.name,
        ),
    )
    print(question, '->', response.text[:120], '...')

# 4. Cleanup
client.caches.delete(name=cache.name)
File API — 직접 업로드하고 기다리기·python
import time

uploaded = client.files.upload(
    file='video.mp4',
    config=types.UploadFileConfig(display_name='intro_video'),
)

# Wait for processing if needed
while uploaded.state.name == 'PROCESSING':
    time.sleep(2.5)
    uploaded = client.files.get(name=uploaded.name)

# File is now usable for 48h
# Reuse across multiple calls — the upload is the expensive step
for question in ['Summarize the video.', "What's the title slide say?"]:
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents=[uploaded, question],
    )
    print(response.text[:200])

client.files.delete(name=uploaded.name)
캐시하지 말아야 할 때·python
# Tiny context — cache overhead > benefit
context = 'Hello, world.'  # 4 tokens
# Don't cache. Just include in contents.

# One-shot question — never reused
context = open('huge_doc.txt').read()
questions = ['Summarize']  # only one
# Cache costs the same as one normal call. No win.

# Reuse > 4 — caching wins on Flash. Reuse > 6 — wins on Pro.
# Math: cache create cost ≈ 1.0× normal input.
# Per-question cached cost ≈ 0.1× normal input.
# Break-even at ~ 1 / (1 - 0.1) ≈ 1.1 reuses (after the first).

External links

Exercise

교과서 한 장, 긴 README, 연구 논문 PDF처럼 5K토큰이 넘는 문서를 골라 두 실험을 해. (a) 캐싱 없이 질문 5개를 보내 호출마다 시간과 비용을 재고, (b) 문서를 캐시한 뒤 같은 질문 5개를 보내 다시 측정해. 합계를 비교해 캐싱이 손익분기점 위에서 실제로 더 싼지 확인하고, 측정한 손익분기점을 적어.

Progress

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

댓글 0

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

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