Lab 4 — ค่าใช้จ่ายของงาน และ prompt caching
Lab walkthrough · EP08 Tools, State and Error Handling
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP08 Tools, State and Error Handling
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
จากคลิปทฤษฎี (§18.8): ค่าใช้จ่ายของงานหนึ่งงาน (สมการ 18.16) และ prompt caching — provider เก็บงานที่คำนวณไว้แล้วของ ส่วนต้นที่ซ้ำกันเป๊ะ กฎจึงเป็น ส่วนที่คงที่ไว้หน้า ส่วนที่เปลี่ยนไว้ท้าย
สิ่งที่จะได้เรียน
- คิดค่าใช้จ่ายของแต่ละ call จาก
usage— แยก token ที่ cache ได้ (ราคาถูกกว่า) - system prompt ยาว (กฎ + รายชื่อ paper 120 เรื่อง) ถามแปดคำถาม: เวลาปัจจุบันไว้ ท้าย vs ไว้ บรรทัดแรก — อ่าน
cached_tokens - ค่าใช้จ่ายของงานตามสมการ 18.16: ค่า model ทุก call + ค่า tool ทุกครั้ง
- งบ token ต่องาน: เตือนเมื่อใกล้ หยุดเมื่อเกิน
รายชื่อ paper และค่า tool เป็น ข้อมูลจำลองเพื่อการสอน ส่วนจำนวน token, cached_tokens และคำตอบมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.8 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | ใช้ key เดียวกับ Lab 1 (lab นี้ใช้ราว 1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv |
วิธีใส่ key อยู่ใน Lab 1 — ที่นั่นอธิบายด้วยว่าทำไม EP นี้ล็อก provider ไว้ที่ Makora: เพราะ lab นี้
%pip install -q "openai>=1.50" python-dotenvimport os, random, uuid
from datetime import datetime
from openai import OpenAI
def load_key():
try: # Google Colab Secrets
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
pass
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key())
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False}, "provider": {"order": ["makora"], "allow_fallbacks": False}}1. ค่าใช้จ่ายของหนึ่ง call
ราคาของ Makora ต่อล้าน token (ดูได้ที่หน้า model บน OpenRouter → Providers):
| ดอลลาร์ / 1M token | |
|---|---|
| input | 0.09 |
| input ที่ cache ได้ (cache read) | 0.049 |
| output | 0.28 |
usage.prompt_tokens_details.cached_tokens = จำนวน token ขาเข้าที่ provider อ่านจาก cache
# ✏️ TODO 1 (▶ วิดีโอ 0:59): คิดราคา: token ใหม่ × ราคา input + token ที่ cache × ราคา cache + token ขาออก × ราคา output
PRICE = {"in": 0.09, "cached": 0.049, "out": 0.28} # USD per 1M tokens (Makora)
def call_cost(usage):
details = usage.prompt_tokens_details
cached = (details.cached_tokens or 0) if details else 0
fresh = usage.prompt_tokens - cached
return ___, cachedPRICE = {"in": 0.09, "cached": 0.049, "out": 0.28} # USD per 1M tokens (Makora)
def call_cost(usage):
details = usage.prompt_tokens_details
cached = (details.cached_tokens or 0) if details else 0
fresh = usage.prompt_tokens - cached
return (fresh * PRICE["in"] + cached * PRICE["cached"] + usage.completion_tokens * PRICE["out"]) / 1e6, cached2. Prompt caching: ส่วนคงที่ไว้หน้า vs เวลาไว้บรรทัดแรก
system prompt = กฎ + รายชื่อ paper จำลอง 120 เรื่อง (ราว 4,600 token) ซึ่ง เหมือนเดิมทุก call — แบบเดียวกับ system prompt + นิยาม tool ในคลิปทฤษฎี SNAPSHOT คือเลขสุ่มของรายชื่อชุดนี้ ทำให้รัน notebook ใหม่แล้วไม่ไปเจอ cache ที่เหลือจากการรันครั้งก่อน
random.seed(7)
SNAPSHOT = uuid.uuid4().hex[:6]
TOPICS = ["forecasting", "anomaly detection", "imputation", "classification", "foundation models"]
CATALOG = "\n".join(
f"- P{i}: {random.choice(['Transformer', 'MLP', 'CNN', 'State-space'])} model for time-series {random.choice(TOPICS)} "
f"({2018 + i % 7}). Benchmarks: ETTh1, Weather, Traffic. Main idea: "
f"{random.choice(['patching', 'sparse attention', 'decomposition', 'frequency mixing', 'pre-training on many datasets'])}."
for i in range(1, 121))
RULES = ("You are the Cogito Learn research assistant.\n"
"Rules: cite paper ids like [P12]; answer in under 60 words; say 'not in the catalog' if unsure.\n\n"
f"Paper catalog (snapshot {SNAPSHOT}):\n" + CATALOG)
QUESTIONS = ["Which papers use patching?", "Name one anomaly detection paper.", "Which papers are from 2024?",
"Any state-space models?", "Which paper is about imputation?", "Name a CNN paper.",
"Which papers do frequency mixing?", "Name an MLP paper about forecasting."]def ask(system, user):
reply = client.chat.completions.create(model=MODEL, max_tokens=80, extra_body=EXTRA,
messages=[{"role": "system", "content": system}, {"role": "user", "content": user}])
return reply.usage
def run(name, build):
total, hits = 0.0, 0
for q in QUESTIONS:
system, user = build(q)
usage = ask(system, user)
cost, cached = call_cost(usage)
total += cost; hits += cached > 0
print(f" {usage.prompt_tokens:,} in · cached {cached:,} · ${cost:.6f}")
print(f"{name}: {hits}/{len(QUESTIONS)} calls hit the cache · ${total:.5f}\n")
return total# ✏️ TODO 2 (▶ วิดีโอ 2:14): วางกฎ (คงที่) ไว้หน้า และเวลาปัจจุบัน (เปลี่ยนตลอด) ไว้ท้ายข้อความผู้ใช้
def static_first(q):
return ___, f"{q}\n(Current time: {datetime.now():%H:%M:%S})"
cost_static = run("static first", static_first)def static_first(q):
return RULES, f"{q}\n(Current time: {datetime.now():%H:%M:%S})"
cost_static = run("static first", static_first) 4,611 in · cached 0 · $0.000437
4,612 in · cached 4,480 · $0.000238
4,616 in · cached 0 · $0.000438
4,612 in · cached 0 · $0.000437
4,612 in · cached 4,480 · $0.000254
4,611 in · cached 4,480 · $0.000239
4,612 in · cached 4,480 · $0.000254
4,613 in · cached 4,480 · $0.000251
static first: 5/8 calls hit the cache · $0.00255
def time_first(q):
return f"Current time: {datetime.now():%H:%M:%S}\n" + RULES, q
cost_time = run("time first", time_first) 4,609 in · cached 0 · $0.000437
4,610 in · cached 0 · $0.000424
4,614 in · cached 0 · $0.000438
4,610 in · cached 0 · $0.000437
4,610 in · cached 0 · $0.000437
4,609 in · cached 0 · $0.000428
4,610 in · cached 0 · $0.000437
4,611 in · cached 0 · $0.000435
time first: 0/8 calls hit the cache · $0.00347
print(f"static first ${cost_static:.5f} vs time first ${cost_time:.5f} → saved {1 - cost_static / cost_time:.0%}")static first $0.00255 vs time first $0.00347 → saved 27%
3. ค่าใช้จ่ายของทั้งงาน (สมการ 18.16)
\[\text{Cost}_{task} = \sum_{i=1}^{T} \left(p_{in} \cdot n_{in,i} + p_{out} \cdot n_{out,i}\right) + \sum_{j=1}^{K} c_j\]
ค่า model ทุก call (T ครั้ง) + ค่า tool ทุกครั้ง (K ครั้ง) · สมมติว่าก่อนตอบแต่ละคำถาม agent เรียก search API ที่คิด 0.001 ดอลลาร์ต่อครั้ง (ราคาจำลอง)
# ✏️ TODO 3 (▶ วิดีโอ 3:40): ค่าใช้จ่ายของ tool = จำนวนครั้งที่เรียก × ราคาต่อครั้ง
TOOL_PRICE = 0.001 # USD per search call (simulated)
llm_cost = cost_static # the eight model calls, static first
tool_cost = ___
print(f"LLM ${llm_cost:.5f} + tools ${tool_cost:.5f} = ${llm_cost + tool_cost:.5f} per task")TOOL_PRICE = 0.001 # USD per search call (simulated)
llm_cost = cost_static # the eight model calls, static first
tool_cost = len(QUESTIONS) * TOOL_PRICE
print(f"LLM ${llm_cost:.5f} + tools ${tool_cost:.5f} = ${llm_cost + tool_cost:.5f} per task")LLM $0.00255 + tools $0.00800 = $0.01055 per task
4. งบ token ต่องาน
ตำรา §18.8.2: กำหนดงบ token ต่องาน (และต่อผู้ใช้) เตือนเมื่อใกล้ · หยุดเมื่อเกิน
# ✏️ TODO 4 (▶ วิดีโอ 4:18): บวก token ของ call นี้ แล้วหยุดด้วย error เมื่อเกิน limit
class TokenBudget:
def __init__(self, limit, warn_at=0.8):
self.limit, self.warn_at, self.used = limit, warn_at, 0
def charge(self, usage):
self.used += ___
if ___:
raise RuntimeError(f"token budget exceeded: {self.used:,} > {self.limit:,}")
if self.used > self.warn_at * self.limit:
print(f" ⚠️ {self.used:,} of {self.limit:,} tokens used")class TokenBudget:
def __init__(self, limit, warn_at=0.8):
self.limit, self.warn_at, self.used = limit, warn_at, 0
def charge(self, usage):
self.used += usage.prompt_tokens + usage.completion_tokens
if self.used > self.limit:
raise RuntimeError(f"token budget exceeded: {self.used:,} > {self.limit:,}")
if self.used > self.warn_at * self.limit:
print(f" ⚠️ {self.used:,} of {self.limit:,} tokens used")budget = TokenBudget(limit=20_000)
try:
for q in QUESTIONS:
budget.charge(ask(*static_first(q)))
print(f"✓ {q} ({budget.used:,} tokens so far)")
except RuntimeError as e:
print("🛑", e)✓ Which papers use patching? (4,691 tokens so far)
✓ Name one anomaly detection paper. (9,333 tokens so far)
✓ Which papers are from 2024? (14,028 tokens so far)
⚠️ 18,720 of 20,000 tokens used
✓ Any state-space models? (18,720 tokens so far)
🛑 token budget exceeded: 23,412 > 20,000
สรุป
| สิ่งที่ทำ | ที่เราเห็นใน lab |
|---|---|
| ค่าใช้จ่ายต่อ call | แยก token ที่ cache ได้ ซึ่ง Makora คิดถูกกว่าราว 46% (ตำราบอก 50–90% — ขึ้นกับ provider) |
| ส่วนคงที่ไว้หน้า | call แรกไม่ได้ cache · หลังจากนั้นหลาย call ได้ (ไม่ทุกครั้ง: provider มีหลายเครื่อง) · call ที่ได้ cache ถูกลงเกือบครึ่ง |
| เวลาไว้บรรทัดแรก | ไม่ได้ cache สักครั้ง แม้อีกสี่พันกว่า token จะเหมือนเดิม |
| สมการ 18.16 | ค่า tool แพงกว่าค่า model ราวสามเท่า — ต้องนับทั้งสองส่วน |
| งบ token | เตือนที่ 80% · หยุดเมื่อเกิน · cache ลดเงิน ไม่ลด token |
แบบฝึกหัด
- Model routing: ให้คำถามสั้นๆ ใช้
google/gemma-3-12b-it(providerdeepinfra/bf16, Lab 3) แทน แล้วเทียบค่าใช้จ่ายและคุณภาพคำตอบ - ใส่เวลาปัจจุบันไว้ กลาง system prompt (หลังกฎ ก่อนรายชื่อ paper) — cache ได้กี่ token และทำไม
ถัดไป — Lab 5: ทำ checkpoint ของ Lab 2 อีกครั้งด้วย LangGraph — พังกลางทาง ทำต่อ และย้อนดูทุก checkpoint