惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Spread Privacy
Spread Privacy
T
Threatpost
C
Cisco Blogs
P
Palo Alto Networks Blog
AI
AI
Cyberwarzone
Cyberwarzone
NISL@THU
NISL@THU
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Latest news
Latest news
AWS News Blog
AWS News Blog
D
Docker
S
SegmentFault 最新的问题
博客园 - 聂微东
WordPress大学
WordPress大学
Vercel News
Vercel News
S
Securelist
爱范儿
爱范儿
J
Java Code Geeks
Know Your Adversary
Know Your Adversary
S
Schneier on Security
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
D
DataBreaches.Net
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
K
Kaspersky official blog
美团技术团队
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
量子位
博客园_首页
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
Google Online Security Blog
Google Online Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
腾讯CDC
T
Threat Research - Cisco Blogs
雷峰网
雷峰网
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
วิธีลดค่าใช้จ่ายโทเค็นเอเจนต์จาก CLI (คู่มือปี 2026)
Thanawat Won · 2026-05-20 · via DEV Community

เอเจนต์เขียนโค้ด CLI อย่าง Claude Code หรือ Codex ช่วยให้ทำงานเร็วขึ้น แต่ค่าโทเค็นจะพุ่งทันทีถ้าปล่อยให้มันอ่าน repo ทั้งก้อน รัน test ซ้ำหลายรอบ และส่งประวัติสนทนาทั้งหมดกลับเข้าโมเดลทุกเทิร์น ข่าวดีคือคุณลดค่าใช้จ่ายได้จากบรรทัดคำสั่ง: จำกัดบริบท, ทำ output ให้สั้น, ใช้ prompt caching, route งานง่ายไปโมเดลราคาถูก และวัดต้นทุนต่อการรันจริง

ลองใช้ Apidog วันนี้

สรุปสั้นๆ (TL;DR)

ถ้าต้องการลดค่าใช้จ่ายโทเค็นของ CLI coding agents ให้เริ่มจากสิ่งเหล่านี้:

  1. จำกัด scope ก่อนให้เอเจนต์ทำงาน
  2. ทำ CLAUDE.md หรือ memory file ให้สั้น
  3. ใช้ /compact หรือ /clear เมื่อเปลี่ยนงาน
  4. เปิด prompt caching สำหรับ prefix ที่เสถียร
  5. ใช้โมเดลราคาถูกกับงานย่อยที่ความเสี่ยงต่ำ
  6. ลด output จาก test runner, install command, logs และ diff
  7. วัด token usage และต้นทุนต่อ run

เป้าหมายคือส่งเฉพาะบริบทที่จำเป็นให้โมเดล ไม่ใช่ส่งทั้ง repo และประวัติทั้งหมดทุกครั้ง

ทำไม CLI agents ถึงกินโทเค็นเยอะ

ปัญหาหลักไม่ได้อยู่ที่โมเดลอย่างเดียว แต่อยู่ที่พฤติกรรม default ของเอเจนต์:

  • อ่านไฟล์ทั้งไฟล์ ทั้งที่ต้องใช้แค่ฟังก์ชันเดียว
  • ส่ง system prompt, tool definitions และ repo context ซ้ำทุกเทิร์น
  • เล่นซ้ำ conversation history ทั้งหมด
  • dump log จาก test runner หรือ command line กลับเข้า context
  • ใช้โมเดลแพงกับงานง่าย เช่น commit message หรือ changelog

ตัวอย่าง: งาน refactor ที่ต้องใช้โค้ดจริงประมาณ 2,000 tokens อาจกลายเป็น request ขนาด 180,000 tokens ได้ ถ้าเอเจนต์อ่านหลายไฟล์ รัน test verbose และแบก history ยาวๆ ไปด้วย

ค่าใช้จ่ายที่ซ่อนอีกจุดคือการ debug API เอเจนต์ที่เรียก API ภายในซึ่งไม่เสถียรจะ retry, อ่าน error, อ่าน docs ซ้ำ และวนหลายรอบ ทุก loop มีค่าโทเค็นเต็ม

💡 หากเอเจนต์ของคุณต้องทำงานกับ API ให้ design, mock และ test API เหล่านั้นใน Apidog ก่อน แล้วค่อยให้เอเจนต์เขียนโค้ดกับ contract ที่คาดเดาได้ วิธีนี้ช่วยลดการลองผิดลองถูกกับ endpoint จริงที่อาจสร้าง error และกินโทเค็นโดยไม่จำเป็น

โทเค็นหายไปไหนในการรันจริง

หนึ่ง turn ของเอเจนต์มีทั้ง input tokens และ output tokens คุณจ่ายทั้งสองฝั่ง โดย output tokens มักแพงกว่า input tokens หลายเท่า

สิ่งที่อยู่ใน input payload มักประกอบด้วย:

  • System prompt และ tool definitions

    เช่น instruction ของ agent และ JSON schema ของ tools มักถูกส่งซ้ำทุก turn

  • Memory/project files

    เช่น CLAUDE.md, coding conventions, repo rules

  • Conversation history

    user message, model response, tool call และ tool output เก่าทั้งหมด

  • ไฟล์ที่เอเจนต์อ่าน

    การอ่านไฟล์ 1,200 บรรทัดครั้งเดียวอาจมีขนาด 12,000–18,000 tokens

  • Tool output

    log จาก npm install, test failure, stack trace, git diff, lockfile diff

จุดสำคัญคือ conversation history ถูกส่งซ้ำทุก turn ดังนั้น session 30 turns ไม่ได้แพงแค่ 30 เท่าของ 1 turn แต่แพงขึ้นตาม prefix ที่โตขึ้นเรื่อยๆ

ถ้าต้องการเข้าใจเรื่อง session/window เพิ่มเติม อ่านได้ที่ วิธีการรีเซ็ตหน้าต่างโทเค็นของ Claude Code

1. จำกัด scope ก่อนให้เอเจนต์เริ่มงาน

โทเค็นที่ถูกที่สุดคือโทเค็นที่ไม่ต้องส่ง อย่าเริ่มจาก prompt กว้างๆ เช่น:

claude "refactor the billing logic"

Enter fullscreen mode Exit fullscreen mode

ให้ระบุไฟล์และขอบเขตให้ชัด:

claude "refactor the retry logic so it uses exponential backoff,
only in src/payments/retry.ts and src/payments/retry.test.ts"

Enter fullscreen mode Exit fullscreen mode

ถ้าต้องให้เอเจนต์สำรวจ codebase ให้จำกัด directory:

claude "find the payment retry implementation under src/payments only,
then propose the minimal change"

Enter fullscreen mode Exit fullscreen mode

แนวทางใช้งาน:

  • หนึ่ง prompt ควรมีหนึ่งงานหลัก
  • ระบุไฟล์หรือ directory
  • บอกสิ่งที่ห้ามแตะ เช่น migration, generated files, lockfiles
  • หลีกเลี่ยงคำสั่งประเภท “scan the whole repo”

2. ทำ memory file ให้สั้น

ไฟล์อย่าง CLAUDE.md ถูกโหลดเข้า context บ่อยมาก ถ้ามันกลายเป็น wiki ยาว 4,000 tokens ทีมจะจ่ายซ้ำทุก turn

ตรวจขนาดแบบคร่าวๆ:

wc -c CLAUDE.md | awk '{print "≈", int($1/4), "tokens per turn"}'

Enter fullscreen mode Exit fullscreen mode

ควรเก็บเฉพาะ:

# CLAUDE.md

## Commands
- Run tests: npm test --silent -- --reporter=dot
- Typecheck: npm run typecheck
- Lint: npm run lint

## Rules
- Do not edit generated files.
- Do not modify package-lock.json unless dependency changes are requested.
- Keep changes minimal and scoped to the requested files.

## References
- API contracts: docs/api/
- Architecture notes: docs/architecture.md

Enter fullscreen mode Exit fullscreen mode

ไม่ควรใส่:

  • onboarding docs ทั้งชุด
  • changelog ยาวๆ
  • architecture document ทั้งไฟล์
  • ตัวอย่างโค้ดจำนวนมากที่ไม่ได้ใช้ทุกงาน

ถ้าเอกสารบางส่วนใช้เดือนละครั้ง ให้เก็บไว้เป็นไฟล์แยก แล้วให้เอเจนต์อ่านเมื่อจำเป็น

3. ใช้ /compact หรือ /clear เมื่อเปลี่ยนงาน

session ยาวคือแหล่งกินโทเค็นหลัก เพราะทุก turn ใหม่ต้องแบก history เก่าทั้งหมด

ใน Claude Code:

/compact

Enter fullscreen mode Exit fullscreen mode

ใช้เมื่อ session ยาว แต่ยังอยากเก็บสรุปของงานเดิมไว้

/clear

Enter fullscreen mode Exit fullscreen mode

ใช้เมื่อเริ่มงานใหม่ที่ไม่เกี่ยวข้อง

กฎง่ายๆ:

  • หนึ่ง logical task ต่อหนึ่ง session
  • หลัง refactor เสร็จแล้ว อย่าใช้ session เดิมไปเขียน docs ต่อ
  • ก่อนเริ่มงานใหม่ ให้ /clear
  • ถ้างานยังต่อเนื่องแต่ history ยาว ให้ /compact

ดู workflow เพิ่มเติมได้ที่ เวิร์กโฟลว์ของ Claude Code

4. ใช้ ignore files เพื่อตัดไฟล์ที่ไม่ควรเห็น

ให้เอเจนต์หลีกเลี่ยงไฟล์ที่สร้างขึ้นหรือไม่ควรแก้ เช่น:

node_modules/
dist/
build/
coverage/
.next/
.nuxt/
*.log
package-lock.json
pnpm-lock.yaml
yarn.lock

Enter fullscreen mode Exit fullscreen mode

ถ้าเอเจนต์ไม่เห็น dist/, coverage/ หรือ lockfile diff มันก็ไม่เสียโทเค็นกับสิ่งเหล่านั้น

เพิ่มกฎใน memory file ด้วย:

Do not read or edit generated files, build output, coverage output, or dependency directories.

Enter fullscreen mode Exit fullscreen mode

5. เปิด prompt caching สำหรับ prefix ที่เสถียร

Prompt caching ช่วยลดค่าใช้จ่ายของ prefix ที่ส่งซ้ำ เช่น system prompt, tools และ repo conventions

แนวคิดคือ:

  • วางข้อมูลที่เสถียรไว้ด้านหน้า
  • วาง input ที่เปลี่ยนบ่อยไว้ด้านหลัง
  • cache เฉพาะ prefix ที่ไม่เปลี่ยน

ตัวอย่างถ้าเรียก API เอง:

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    system=[
        {
            "type": "text",
            "text": SYSTEM_PROMPT + REPO_CONVENTIONS,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[
        {
            "role": "user",
            "content": user_task,
        }
    ],
)

u = response.usage
print("cache write:", u.cache_creation_input_tokens)
print("cache read :", u.cache_read_input_tokens)
print("fresh input:", u.input_tokens)

Enter fullscreen mode Exit fullscreen mode

ข้อควรระวัง:

  • prefix ต้อง byte-stable
  • อย่าใส่ timestamp หรือข้อมูล runtime ไว้ก่อน cache boundary
  • ถ้าเปลี่ยน character เดียวก่อนจุด cache อาจทำให้ cache miss
  • จัดกลุ่มงานที่เกี่ยวข้องให้รันใกล้กัน เพื่อใช้ cache ที่ยัง warm อยู่

Prompt caching เหมาะมากกับ agent ที่ใช้ system prompt และ repo rules เดิมซ้ำหลายสิบครั้งต่อวัน

ถ้าใช้ Codex หรือ OpenAI models ที่มี cached input discount หลักการคล้ายกัน แม้รายละเอียด implementation ต่างกัน อ่านเสริมได้ที่ การรัน GPT-5.5 ฟรีผ่าน Codex

6. Route งานง่ายไปโมเดลราคาถูก

ไม่ใช่ทุกงานต้องใช้โมเดลหลัก งานเหล่านี้มักใช้โมเดลเล็กได้:

  • commit message
  • changelog
  • summarize diff
  • generate boilerplate test
  • explain lint error
  • rename variable แบบตรงไปตรงมา

ตัวอย่าง:

# งานง่าย ใช้โมเดลถูก
claude --model haiku "write a conventional commit message for the staged diff"

# งานยาก ใช้โมเดลแรง
claude --model sonnet "redesign the caching layer for the payments service"

Enter fullscreen mode Exit fullscreen mode

แนวทางที่ดีคือ default เป็นโมเดลราคาถูก แล้วค่อยยกระดับเมื่อจำเป็น แทนที่จะใช้โมเดลแพงกับทุกอย่าง

ถ้า framework รองรับ sub-agent ให้ใช้โมเดลเล็กกับงานค้นหา/สรุป แล้วส่งผลลัพธ์สั้นๆ กลับให้ parent agent ที่ใช้โมเดลแพง

อ่านรูปแบบ autonomous loop เพิ่มเติมได้ที่ คำสั่ง goal ใน Codex และ Claude Code

การ route ไม่ได้ช่วยแค่ค่าเงิน แต่ยังช่วยยืด quota ในแผนที่มี usage limit ด้วย แม้จะมี การเพิ่มขีดจำกัดรายสัปดาห์ของ Claude Code การใช้โมเดลแพงกับงานเล็กก็ยังเป็นการเผา quota โดยไม่จำเป็น

7. ทำ command output ให้สั้น

Tool output เป็นตัวกินงบแบบเงียบๆ เพราะทุกบรรทัดที่ command print ออกมาอาจถูกส่งกลับเข้า context

เปลี่ยนจาก command ที่ verbose:

npm test

Enter fullscreen mode Exit fullscreen mode

เป็นแบบสั้น:

npm test --silent -- --reporter=dot

Enter fullscreen mode Exit fullscreen mode

ติดตั้ง dependency แบบลด noise:

npm install --silent --no-audit --no-fund

Enter fullscreen mode Exit fullscreen mode

จำกัด test output:

pytest -q 2>&1 | tail -n 30

Enter fullscreen mode Exit fullscreen mode

ดู diff แบบสรุปก่อน:

git diff --stat

Enter fullscreen mode Exit fullscreen mode

กรองเฉพาะ error:

npm test 2>&1 | grep -E "(FAIL|✗|Error)" | head -n 20

Enter fullscreen mode Exit fullscreen mode

ถ้าเอเจนต์ต้อง debug test failure มันมักต้องการแค่:

  • test ไหน fail
  • error message
  • stack trace ส่วนบน
  • expected vs actual

ไม่ต้องการ log ทั้งหมด 5,000 บรรทัด

8. ให้เอเจนต์อ่านเฉพาะส่วนที่เกี่ยวข้อง

แทนที่จะให้เอเจนต์อ่านไฟล์ 1,500 บรรทัด ให้สั่งให้ค้นหา symbol ก่อน:

claude "find the function that handles payment retry,
read only that function and nearby tests, then suggest the minimal patch"

Enter fullscreen mode Exit fullscreen mode

หรือใช้ shell ช่วยตัดบริบท:

grep -n "function retryPayment" -n src/payments/retry.ts
sed -n '120,220p' src/payments/retry.ts

Enter fullscreen mode Exit fullscreen mode

ถ้าใช้ ripgrep:

rg "retryPayment|exponentialBackoff|RetryPolicy" src/payments

Enter fullscreen mode Exit fullscreen mode

เป้าหมายคือให้โมเดลเห็น context ขนาด 500–1,000 tokens แทนที่จะเป็นทั้งไฟล์ขนาด 18,000 tokens

9. จำกัด retrieval/RAG

ถ้า agent ใช้ code search หรือ RAG บนเอกสาร ให้จำกัดจำนวน chunk และขนาด chunk

ตัวอย่าง configuration ที่ควรตั้ง:

{
  "retrieval": {
    "max_chunks": 10,
    "chunk_size_tokens": 200,
    "include_full_file": false
  }
}

Enter fullscreen mode Exit fullscreen mode

หลักการ:

  • chunk สั้นแต่ตรงคำถามดีกว่า chunk ยาวจำนวนมาก
  • อย่าดึง full file ถ้าไม่จำเป็น
  • ให้ ranking เลือกเฉพาะ context ที่เกี่ยวข้องจริง
  • log จำนวน retrieved tokens เพื่อวัดผล

คุณจ่ายสำหรับทุก token ที่ดึงมา แม้โมเดลจะไม่ได้ใช้มันตอบก็ตาม

10. วัดต้นทุนต่อการรัน

อย่าดูแค่ bill รายเดือน ให้เก็บต้นทุนต่อ task เช่น:

  • daily refactor run
  • PR review run
  • test-fix run
  • API integration run

ถ้าเรียก API เอง ให้เก็บ usage:

u = response.usage

INPUT_RATE  = 3.00 / 1_000_000
OUTPUT_RATE = 15.00 / 1_000_000
CACHE_READ  = 0.30 / 1_000_000
CACHE_WRITE = 3.75 / 1_000_000

cost = (
    u.input_tokens * INPUT_RATE +
    u.output_tokens * OUTPUT_RATE +
    u.cache_read_input_tokens * CACHE_READ +
    u.cache_creation_input_tokens * CACHE_WRITE
)

print(
    f"run cost ≈ ${cost:.4f} "
    f"(in={u.input_tokens} out={u.output_tokens} "
    f"cache_read={u.cache_read_input_tokens})"
)

Enter fullscreen mode Exit fullscreen mode

ถ้าใช้ CLI ให้ใช้วิธีเหล่านี้:

# ตรวจ cost ของ session
claude /cost

Enter fullscreen mode Exit fullscreen mode

หรือแยก API key ตาม project/agent เพื่อดู usage จาก provider console

หรือห่อ command ด้วย script ที่ log ข้อมูลลง CSV:

#!/usr/bin/env bash

TASK="$1"
START=$(date -Iseconds)

claude "$TASK"

END=$(date -Iseconds)
echo "$START,$END,$TASK" >> agent-runs.csv

Enter fullscreen mode Exit fullscreen mode

จากนั้นเทียบต้นทุนก่อน/หลังปรับ:

  • ก่อนใช้ prompt caching
  • หลังลด CLAUDE.md
  • หลังเปลี่ยน test reporter
  • หลัง route งานง่ายไปโมเดลถูก

ถ้าตัวเลขไม่ลด แปลว่ากลยุทธ์นั้นอาจไม่ใช่จุดรั่วหลักของคุณ

ตารางเปรียบเทียบกลยุทธ์

กลยุทธ์ การประหยัดโทเค็นโดยทั่วไป ความพยายาม
จำกัดขอบเขตการทำงาน เช่น ระบุชื่อไฟล์ 30–60% ของ input ต่อ run ต่ำ
ทำ memory file ให้สั้นและเสถียร 5–15% ต่อ turn ต่ำ
ใช้ /compact หรือ /clear ระหว่างงาน 40–80% สำหรับ session ยาว ต่ำ
Prompt caching สำหรับ prefix ที่เสถียร ประมาณ 90% สำหรับส่วนที่ cache ปานกลาง
Route งานง่ายไปโมเดลราคาถูก 50–80% สำหรับงานย่อยนั้น ปานกลาง
ลด/กรอง tool output 20–50% สำหรับ run ที่ใช้ tools เยอะ ต่ำ
อ่านเฉพาะส่วนของไฟล์ 70–95% สำหรับไฟล์ใหญ่ ต่ำ
จำกัด retrieval/RAG 30–60% สำหรับ agent ที่ใช้ retrieval มาก ปานกลาง
วัดต้นทุนต่อ run ไม่ลดโดยตรง แต่ทำให้ optimize ได้จริง ต่ำ

ตัวเลขเป็นช่วงโดยประมาณ ผลจริงขึ้นอยู่กับ workflow และความสิ้นเปลืองตั้งต้นของแต่ละทีม

Checklist สำหรับนำไปใช้ทันที

เริ่มจากรายการที่ทำครั้งเดียวแล้วได้ผลทุก run:

[ ] ลด CLAUDE.md ให้เหลือเฉพาะ command, rule และ pointer
[ ] เพิ่ม ignore สำหรับ generated files, build output, coverage, dependencies
[ ] เปลี่ยน test command ให้ silent/summary
[ ] ใช้ git diff --stat ก่อน full diff
[ ] สั่ง agent ให้อ่านเฉพาะ function หรือไฟล์ที่ระบุ
[ ] ใช้ /compact เมื่อ session ยาว
[ ] ใช้ /clear เมื่อเปลี่ยนงาน
[ ] ตั้งโมเดลราคาถูกเป็น default สำหรับงานง่าย
[ ] เปิด prompt caching ถ้าเรียก model API เอง
[ ] log token usage หรือต้นทุนต่อ task

Enter fullscreen mode Exit fullscreen mode

บทสรุป

ค่าโทเค็นของ CLI coding agents ลดได้โดยไม่ต้องเปลี่ยนคุณภาพของงาน จุดที่ควรจัดการคือบริบทที่ส่งซ้ำ, output ที่ไม่จำเป็น และการใช้โมเดลแพงกับงานที่ไม่ต้องใช้ reasoning สูง

เริ่มจากสิ่งที่ง่ายที่สุด: scope งานให้แคบ, ทำ command output ให้เงียบ, ลด memory file และ clear session ระหว่างงาน จากนั้นค่อยเพิ่ม prompt caching, model routing และ cost tracking เพื่อให้การประหยัดวัดผลได้จริง