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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
J
Java Code Geeks
腾讯CDC
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
罗磊的独立博客
Last Week in AI
Last Week in AI
B
Blog
IT之家
IT之家
S
SegmentFault 最新的问题
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - 聂微东
U
Unit 42
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
MyScale Blog
MyScale Blog

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
วิธีลดค่าใช้จ่ายโทเค็นเอเจนต์จาก 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 เพื่อให้การประหยัดวัดผลได้จริง