# agent-tokenomics — Full Documentation Corpus (English & Korean) Source: https://dotnetpower.github.io/agent-tokenomics/ Repository: https://github.com/dotnetpower/agent-tokenomics Structured Index: https://dotnetpower.github.io/agent-tokenomics/llms.txt Generated for generative-engine ingestion (one file, one fetch). Each section below is one published documentation page separated by `---` rulers. --- ## 0. Concepts: Tokenomics & Token Economics for LLM Agents (agent-tokenomics/00-concepts.md) Canonical URL: > Core concepts of LLM tokenomics and token economics: stateless re-sending, request anatomy, agent loop fan-out, pricing, prompt caching, and context rot. Read this once before the [troubleshooting stages](../01-diagnose/). Every later page assumes these **LLM tokenomics (token economics)** fundamentals. ## 1. A model call is stateless The model remembers nothing between calls. An agent "remembers" only because **every request re-sends** the instructions, tool definitions, and the conversation so far. Token cost is therefore driven less by what you type than by what the framework **carries along** on each call. ## 2. Anatomy of one request | Part | Direction | Changes between requests? | Typical waste | |------|-----------|---------------------------|---------------| | System prompt (framework + yours) | input | No — stable | Long, repeated rules | | Instruction files / standing facts | input | Rarely | Facts the code already shows; duplicates | | **Tool definitions** (schemas) | input | Rarely | Tools never called | | Conversation history (user, assistant) | input | Grows every turn | Old topics, resolved detours | | **Tool results** (file reads, command output) | input | Grows every step | Whole files, verbose logs | | Attachments / retrieved context | input | Per task | Irrelevant or duplicated context | | Current user prompt | input | Yes | Usually the smallest part | | Model text, tool calls | output | Yes | Verbosity, restating the question | | Reasoning ("thinking") | output (typically billed as output) | Yes | Effort higher than the task needs | The top rows form the **prefix**: the part that stays the same from call to call. That matters for caching (section 5). ## 3. The agent loop multiplies everything ```text step 1: model call ─► tool call ─► result appended step 2: model call (re-sends prefix + history + result 1) ─► tool call ─► result appended step 3: model call (re-sends prefix + history + result 1..2) ─► … ``` Each step is a billed model call, and each call re-sends all earlier content. Over a task of *n* steps: ```text input tokens ≈ n × prefix + Σ(history and tool results accumulated before each step) ``` The first term grows linearly with steps; the second grows faster than linearly because every step adds to what all later steps re-send. This is why **fewer steps**, **smaller results**, and **smaller prefixes** all pay off, and why a loop that gets stuck is expensive. **Pipelines multiply too.** Not every agent is a free-form loop. Many production agents run a fixed chain of model calls per user request (for example: safety check → query rewrite → router → classifier → answer → follow-up question → final reply). The user sees one question; the provider bills **one call per step**, and each step carries its own system prompt and reference documents. Call this **fan-out** (LLM calls per user request). Anything large and attached to several steps (or to a step that is called twice) is paid `tokens × calls`.
Step 1 (Call #1)
Prefix (System + Tools)
User
9,200 tok
Step 2 (Call #2)
Prefix (re-sent)
History
Tool Result 1
13,800 tok
Step 3 (Call #3)
Prefix (re-sent)
History + Result 1
Tool Result 2
19,500 tok
Figure 1. Across an agent loop, the static prefix (n × prefix) is re-sent on every step while prior history and tool outputs (Σ) accumulate. References: ReAct (ICLR 2022) and microsoft/TokenEconomizer.
**Long-context degradation in custom agents.** As history and tool results accumulate, models can use information buried in the middle less reliably than information at the beginning or end ([Lost in the Middle](https://arxiv.org/abs/2307.03172)); [RULER](https://arxiv.org/abs/2404.06654) also tests how effective context capacity varies by task. Unbounded history can therefore hurt task accuracy as well as increase token cost; verify the effect on your own agent. ## 4. What you are billed for | Dimension | What it is | Why it matters | |-----------|------------|----------------| | Uncached input tokens | Input processed from scratch | Full input price | | **Cached input tokens** | Input served from the provider's prompt cache | Billed at a reduced rate on most providers | | Output tokens (incl. reasoning) | Everything the model generates | Usually priced higher per token than input | Rates differ by provider and model, and change; read the current price list of the model you use instead of relying on a ratio from an article. Total cost for a request is `uncached_in × p_in + cached_in × p_cached + out × p_out`, summed over all requests. **Cost is not the only goal.** Decide which you are optimizing, because the metrics differ: | Goal | Typical situation | Metrics | |------|-------------------|---------| | Money | Pay-as-you-go or credits | Tokens by type per task, cost per successful task | | Capacity | Reserved / provisioned throughput, rate limits | Tokens per minute per request, utilization, concurrent users served | | Latency | Interactive use | Input tokens per call, time to first token, p95 end-to-end time | Fewer input tokens generally help all three. Caching helps money and capacity only if your provider counts cached tokens favorably for your deployment type (see the checklist in section 5). ### How tokens are counted across languages (tiktoken) Models do not count characters or words. They split UTF-8 bytes into subword pieces using a **Byte Pair Encoding (BPE)** tokenizer such as OpenAI's [`tiktoken`](https://github.com/openai/tiktoken) (`o200k_base` for GPT-4o, GPT-4.1, GPT-5, and o-series; `cl100k_base` for GPT-4 and GPT-3.5). Because BPE vocabularies are trained predominantly on English and source code, the same meaning costs different token counts across languages (`examples/count_tokens.py`, `tiktoken` 0.14.0): | Language | Sample sentence | Chars | UTF-8 bytes | `o200k_base` tokens | `cl100k_base` tokens | |----------|-----------------|------:|------------:|--------------------:|---------------------:| | English | I met a huge dog | 16 | 16 | **5** (1.0×) | **5** (1.0×) | | Spanish | Conocí a un perro enorme | 24 | 25 | **7** (1.4×) | **8** (1.6×) | | Korean | 나는 커다란 개를 만났다 | 13 | 35 | **8** (1.6×) | **13** (2.6×) | | Japanese | 大きな犬に出会った | 9 | 27 | **8** (1.6×) | **11** (2.2×) | | Chinese | 我遇見了一隻大狗 | 8 | 24 | **8** (1.6×) | **12** (2.4×) |
English (5 tokens) I ·met ·a ·huge ·dog
Korean o200k_base (8 tokens) 나는 ·커 다 란 ·개 를 ·만 났다
Korean cl100k_base (13 tokens) 나 는 ·커[1/2] 커[2/2] 다 란[1/2] 란[2/2] ·개 를 ·만 났[1/2] 났[2/2] 다
Figure 2. Actual tiktoken BPE token segmentation for the same sentence (· denotes a leading space). In cl100k_base, less common syllables (커, 란, 났) split into two UTF-8 byte fragments each (13 tokens total), whereas o200k_base merges common Korean words and syllables into 8 tokens. Sources: openai/tiktoken, OpenAI Tokenizer, and examples/count_tokens.py.
Three practical implications for agent builders: 1. **Shorter character count does not mean fewer tokens.** Korean, Japanese, and Chinese use fewer characters than English, but each syllable or character takes 2–3 UTF-8 bytes and often splits into multiple tokens. 2. **Match the tokenizer encoding to your model.** Newer vocabularies (`o200k_base`) cut the non-English multiplier significantly compared with `cl100k_base` (for Korean, `2.6× → 1.6×`). When profiling locally with `tokprof`, select the matching encoding (`tokprof --tokenizer o200k_base`). 3. **Keep repeated prefix content in English or BPE-friendly notation.** System prompts, standing rules, and tool descriptions are sent on every call (`tokens × calls`), so language overhead in the prefix multiplies across the entire session. See [Language and tokenization](../../copilot-tokenomics/07-language-and-tokenization/) for BPE-aligned prompt techniques. ## 5. Prompt caching Providers can reuse the **longest matching prefix** of a request seen recently. A cache hit needs the start of the request to be *identical*, so one early change (a reordered instruction, an edited tool list, a rewritten history) invalidates the cache from that point on. Behavior is provider-, model-, and deployment-specific: switching models does not reuse the old cache. Design rule: **stable content first, volatile content last, append-only history**. For agents you build or operate, [`tokprof`](../01-diagnose/#profile-without-changing-code-tokprof) tracks `cached_tokens` share and system-prompt hash stability across calls. Official provider guides: [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching), [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching), [Anthropic Claude](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), [Google Gemini](https://ai.google.dev/gemini-api/docs/caching).
Stable Prefix
✓ CACHE HIT: System + Tools + History (≥ 1,024 tok identical)
New Turn
Discounted
Early Change
Match
✗ CACHE MISS: Dynamic timestamp or reordered tools invalidates rest
Full Price
Figure 3. Prompt caching reuses the matching leading prefix (≥ 1,024 tokens); any early mutation (such as a dynamic timestamp or reordered tool definitions) invalidates the cache from that point onward. References: Azure OpenAI Prompt Caching, OpenAI Prompt Caching, and SGLang RadixAttention (NeurIPS 2023).
### Provider caching: what to verify Caching rules differ by provider, model family, and deployment type, and they change. Before you design around caching, get written answers to these. The right-hand column records what the official docs said on 2026-11-03 for [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching) and [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching); re-verify for your model. | Question | Why it matters | What the docs said (2026-11-03) | |----------|----------------|---------------------------------| | Minimum cacheable prefix? | Short prompts (guardrails, small classifiers, summarizers) may never cache | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching): the request needs ≥ 1,024 tokens and the first 1,024 must be identical (increments of 128 tokens thereafter). [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): 1,024 minimum for GPT-5.6 and later; varies for earlier models. ([Anthropic](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): 1,024–4,096 tokens depending on Claude model) | | Which models and retention policies? | A model without support, or without extended retention, changes the plan | [Azure OpenAI supported models](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching#supported-models): in-memory retention for GPT-4o or newer; extended retention only for a listed set of models, so check the list for your exact model, including "mini" variants | | Where do hits show up? | You cannot tune what you cannot see | [Azure chat completions](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching): `usage.prompt_tokens_details.cached_tokens` (0 means a miss); on GPT-5.6 and later Standard deployments also `cache_write_tokens` | | Does a cache key help? | Routing related requests together raises hit rate | [Azure / OpenAI (`prompt_cache_key`)](https://developers.openai.com/api/docs/guides/prompt-caching): on GPT-5.6 and later, reuse one `prompt_cache_key` per shared prefix; above about 15 requests per minute for one prefix and key, some requests may miss, so partition across keys with a stable mapping | | How long is it kept? | Determines whether a quiet period wastes the cache | [Azure OpenAI retention](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching): in-memory is typically cleared after 5–10 minutes idle, always within an hour. Extended: up to 24 hours (key/value tensors offloaded to GPU-local storage). On GPT-5.6 and later the policy field is deprecated in favor of a 30-minute minimum lifetime | | How is it billed and counted? | Determines whether caching saves money, capacity, or both | [Azure OpenAI pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/): discounted cache reads on Standard; up to a 100% input discount on Provisioned deployments; on GPT-5.6 and later, cache writes can incur charges. [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): pricing varies by model. Ask how cached tokens count toward your capacity utilization | | What is stored, and where? | Security and data-residency review | [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): the cache stores key-value tensors, not raw text. [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching): not shared between subscriptions; extended retention stays within the regional or data-zone boundary of the deployment type | | Can it be disabled or cleared? | Needed for some compliance cases | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching): on GPT-5.6 and later Standard deployments, `explicit` mode with no breakpoints disables caching; earlier models and managed provisioned deployments cannot disable it | Short prompts that cannot be cached are a design signal, not a problem to pad away: merge the step into a neighbor, move it to a deterministic check, or accept that it is small. Do not add filler tokens to reach a threshold. ## 6. Tools have two costs 1. **Definition cost** — every enabled tool's schema is in the prefix of every request, used or not. 2. **Result cost** — what a tool returns is appended to the history and re-sent on all later steps. Pruning unused tools attacks the first; truncating, paginating, or summarizing results attacks the second. ## 7. Cost without quality is meaningless A cheaper run that fails is not a saving. Track **cost per successful task**. Also note that per-step errors compound across a long loop (see the table in [Prove](../03-prove/#multi-step-reliability)), so shortening a loop can improve success and cost together. ## 8. From concepts to causes | Concept | Waste it creates | Where you diagnose it | |---------|------------------|-----------------------| | Stateless re-send, big prefix | Fixed overhead; re-learned facts | [Diagnose](../01-diagnose/), [Isolate](../02-isolate/) | | Tool definition cost | Unused tools | [Isolate](../02-isolate/) | | Tool result cost | Bloated output | [Improve](../04-improve/) | | Loop multiplication | Failure loops, retries | [Prove](../03-prove/) | | History accumulation | History growth, long-context degradation | [Improve: compaction](../04-improve/#compaction-without-losing-the-cache) | | Cache prefix rule | Prefix churn, cache misses | [Diagnose](../01-diagnose/) | | Output pricing, reasoning | Verbosity, over-sized effort | [Improve](../04-improve/) | ## Worked example In the synthetic log [`sample-requests.jsonl`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-requests.jsonl), the first request of session `s1` is 9,200 input tokens. Its four tool definitions add up to 220 + 180 + 900 + 1,100 = **2,400 tokens (about 26% of that request)**, and two of those tools are never called. From request 2 on, 9,000 of 9,600 input tokens are served from cache — *because the prefix stayed identical*. Remove a tool or reorder instructions mid-session and that hit rate would fall. That single log already shows three concepts: prefix overhead, tool-definition cost, and caching. ## Next Start measuring in [1. Diagnose](../01-diagnose/). ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629) — ICLR 2022, 13,383 citations. Interleaves reasoning and tool actions: the agent loop whose cost this guide analyzes. - [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) — SOSP 2023, 9,724 citations. PagedAttention manages KV-cache memory to raise serving throughput; basis of vLLM. - [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) — TACL 2023, 5,818 citations. Accuracy drops when the relevant information sits in the middle of a long input. - [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) — NeurIPS 2023, 1,783 citations. RadixAttention reuses KV cache across calls that share a prefix; foundation for prefix caching. - [RULER: What's the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) — preprint 2024, 1,580 citations. Benchmark showing the effective context length is often shorter than the advertised window. ## Sources - [Lost in the Middle (arXiv:2307.03172)](https://arxiv.org/abs/2307.03172) - [openai/tiktoken — fast BPE tokenizer for OpenAI models](https://github.com/openai/tiktoken) and [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py) - [Prompt caching in Azure OpenAI (Microsoft Learn)](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching) and [Azure OpenAI Service pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/) - [Prompt caching — OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching), [Anthropic Claude](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), [Google Gemini](https://ai.google.dev/gemini-api/docs/caching) - [TokenEconomizer](https://github.com/microsoft/TokenEconomizer): describes the same carried-along costs (instructions, loaded tools, conversation so far) --- ## 1. Diagnose the current state (agent-tokenomics/01-diagnose.md) Canonical URL: > LLM agent tokenomics Stage 1 (Diagnose): measure per-request input, cached, output, and reasoning tokens, fixed prompt overhead, and turn growth curves. **Goal:** a baseline you trust. Do not optimize yet. ## Symptoms - The bill or token count is higher than expected, or grows faster than usage. - Sessions slow down as they get longer. - Similar tasks have very different costs. ## Collect the request log You need one record per model call (fields: see the [index](../)). Four ways to get it: 1. **Provider usage fields** — log the `usage` object each API response returns (input, cached, output, reasoning tokens). 2. **Tracing SDK / OpenTelemetry** — instrument the agent so each model call and tool call becomes a span. 3. **Gateway / proxy** — route model traffic through a gateway that logs every request. 4. **Profiler without code changes** — [`tokprof`](#profile-without-changing-code-tokprof) runs your existing agent under a local gateway and breaks every call's input tokens down by system prompt, history, user prompt, and tool content. These platforms can do 2 and 3 for agents you build or operate. Pick one; do not stack several on the same traffic. | Platform | Style | Good for | Links | |----------|-------|----------|-------| | **Arize Phoenix** | Tracing (OpenTelemetry / OpenInference); self-hostable (check its license) | Step-by-step traces of model, retrieval, and tool calls; evals and prompt experiments in one place | [docs](https://arize.com/docs/phoenix), [repo](https://github.com/Arize-ai/phoenix) | | **Langfuse** | Tracing SDKs and integrations; open source, self-hostable or cloud | Per-generation usage and cost by type (input, output, cached…), cost dashboards, alerts, Metrics API | [token & cost tracking](https://langfuse.com/docs/observability/features/token-and-cost-tracking), [repo](https://github.com/langfuse/langfuse) | | **LangSmith** | Tracing (LangChain's hosted platform) | Token and cost breakdown per trace (input incl. cache reads, output incl. reasoning), project stats and dashboards | [cost tracking](https://docs.langchain.com/langsmith/cost-tracking) | | **Helicone** | Gateway / proxy (OpenAI-compatible) | Logging every request with minimal code change; fallbacks across providers | [quickstart](https://docs.helicone.ai/getting-started/quick-start), [repo](https://github.com/Helicone/helicone) | | **Portkey** | Gateway (unified API) plus observability | One interface to many models with monitoring, controls, and guardrails | [docs](https://portkey.ai/docs/introduction/what-is-portkey), [repo](https://github.com/Portkey-AI/gateway) | How to choose: - **Tracing** shows the *structure* of a run (which step, which tool, how nested) — best for isolating loops and bloated tool output. It needs instrumentation in your code or framework. - **Gateways** are quickest to add (change a base URL) and see every call, but they see only the model traffic, not what happened between calls, and they sit in the path of your prompts. - Check each product's current license, hosting options, pricing, data-retention, and whether it records the **cached-token and reasoning-token** fields you need. Features change; verify before committing. - Prompts and tool results often contain private code or data: configure **redaction / sampling** and review the data-handling terms before sending production traffic. - Tools that ship model price tables compute cost for you, but their prices can lag. Treat dollar figures as estimates and keep **token counts** as the primary metric. To use [`token_report.py`](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples) with any of them, export or query the platform's data and map it to the JSONL fields (`session`, `turn`, `input_tokens`, `cached_input_tokens`, `output_tokens`, `tool_defs`, `tool_calls`). **Two JSONL schemas:** `.tokprof/*.jsonl` contains `tokprof`'s rich `v: 1` records with per-segment token estimates, salted hashes, and secret-redacted prompt/response text (unless `--no-content` is used). By contrast, `examples/sample-requests.jsonl` uses the compact summary schema read by `examples/token_report.py`. Convert a recording before passing it to that script: ```bash tokprof export run.jsonl --out legacy.jsonl ``` Redaction is not a guarantee that a log is safe to share; review it first. Using GitHub Copilot in VS Code instead? These do not instrument it; use [Agent Debug Logs and the Cache Explorer](../../copilot-tokenomics/02-measure-usage/). ## Profile without changing code: tokprof [`tokprof`](../tokprof/) ([PyPI](https://pypi.org/project/tokprof/), standalone native Rust single binary, no dependency on your agent's project) answers "which part of each request costs the tokens?" for agents you start through it or attach to: ```bash pip install tokprof # or: uv tool install tokprof / uvx tokprof / pipx install tokprof tokprof # show detailed usage guide & examples (--lang en | --lang ko) tokprof start # start background profiling (Linux: auto-captures running processes & Docker) tokprof stop # stop session, print visual report, and write .tokprof/latest.html tokprof -- python my_agent.py # one-step command: run, print visual report, and write .tokprof/latest.html tokprof report --format pretty --html --csv # summarize the latest run and write HTML + CSV reports tokprof report --format csv # output per-session, per-turn, and per-call CSV to stdout tokprof report --watch # live-updating terminal view while an agent runs tokprof compare before.jsonl after.jsonl # bootstrap interval, for stages 3 and 5 ``` See the full [tokprof: Install & Usage guide](../tokprof/) for all capture modes, CLI options, and private/on-prem endpoint configuration. - **How it captures.** `tokprof start` launches a background session that on Linux automatically attaches the eBPF tap to running host processes and Docker containers (use `tokprof start --comm ` to scope by process, working directory, or container name) and stops with `tokprof stop` (printing the visual report and saving `.tokprof/latest.html`). `tokprof run` starts a gateway on `127.0.0.1` and points `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `AZURE_OPENAI_ENDPOINT`, and pattern-matched base-URL variables (`VLLM_BASE_URL`, `OLLAMA_HOST`, …) at it **for that command only**, plus in-process hooks (Python `httpx`, `requests`, `urllib3`, `aiohttp`, and `urllib.request` through `sitecustomize`; Node `fetch`, `http.request`, and `https.request` through `--require`). - **Which requests count as LLM calls.** Not a fixed list of URLs. `tokprof` scores the request body shape (a `messages` list, Gemini `contents`, a Responses-style `input`, a `prompt`), the path, the host (private DNS, RFC 1918, `.svc.cluster.local`, `privatelink`, `vllm`/`ollama` names, conventional ports) and, for ambiguous bodies, the response (usage counters, `choices`, Ollama/llama.cpp/TGI counters). That covers private DNS endpoints, on-prem vLLM, Ollama, TGI, llama.cpp, LiteLLM-style gateways, Azure private endpoints, and Gemini. `tokprof explain --body request.json` shows why a request was or was not recorded; `--llm-host`, `--llm-path` and `--exclude-host` override the decision. A private CA is trusted through `SSL_CERT_FILE` or `--upstream-ca`. - **What it shows.** Per-session, per-turn, and per-call breakdowns of input tokens by system prompt (split by section), conversation history, current user prompt (including structured JSON user payloads with `utterance`, `context`/`history`, and `capabilities`), tool definitions, tool calls, tool results, and response schemas, plus full prompt & response text inspection; fixed overhead; per-step token map; calls per request; unused tools; repeated static blocks; failure loops (repeated identical tool calls or HTTP errors); prompt cache-busting (dynamic values changing the system prompt hash); and rapid conversation history growth. Outputs terminal (`pretty`, `text`, `--full-prompts`), CSV (`--format csv` / `--csv`), Markdown, JSON, and a self-contained interactive HTML dashboard (`--html`). Running `tokprof` with no arguments prints detailed usage and examples (`--lang en` or `--lang ko`). - **What it stores.** Counts, salted hashes, lengths, section/tool names, and secret-redacted prompt/response texts (pass `--no-content` to omit text). Never headers or API keys. - **Accuracy.** Providers report only totals, so segment counts are local estimates and the rest is shown as *unattributed*. Install `tiktoken` for OpenAI-family models. Check the residual before trusting a breakdown. - **Already-running processes (Linux).** `tokprof ebpf --pid ` attaches eBPF probes to the process's TLS library (OpenSSL and Go `crypto/tls`) and raw syscall tracepoints, recording its LLM calls without restarting or changing it, including plain `http://` and `h2c` calls to an on-prem server. It needs root or `CAP_BPF`; it follows HTTP/1.1 and HTTP/2 (for connections opened after it attached). See the [profiler README](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler#linux-ebpf-tap-running-processes-no-restart-no-code-change). - **Limits today.** Outside the eBPF tap, only processes started under `tokprof` are captured. Clients that neither honor the base-URL variables nor use `httpx`, `requests`, `urllib3`, `aiohttp`, `urllib.request`, Node `fetch`, or Node `http`/`https` are not captured under `tokprof run`. On Windows and macOS, `tokprof mitm --local ` uses mitmproxy's local capture instead (needs administrator rights and trusting the mitmproxy CA). ## Checks Run the example script on your log: ```bash python examples/token_report.py requests.jsonl ``` Record these for the baseline: | Metric | How to get it | Why it matters | |--------|---------------|----------------| | Input / cached / output tokens per request | Provider usage fields | Input usually dominates; cached input is cheaper | | **Cache hit %** | cached ÷ input | Low hit % with a stable prefix suggests prefix churn | | **Fixed overhead** | Input tokens of the *first* request in a session | System prompt + instructions + tool definitions, paid every request | | **LLM calls per user request (fan-out)** | Count model calls that share a request or trace id | One question may trigger many calls; each carries its own prompt | | **Per-step token map** | Per step: model, calls, fixed tokens per call, dynamic tokens | Shows which step and which component dominates (see below) | | **Coverage** | Sum of logged tokens vs the provider's billed or monitored tokens for the same period | A gap means un-instrumented calls (sub-services, embeddings, background jobs) | | **Tool-definition tokens** | Sum of tool schemas sent | Paid on every request, used or not | | **Context growth curve** | Input tokens by request index | Steep growth = history or tool output accumulating | | **Tool output tokens by tool** | Tokens each tool result adds | Finds bloated results (big file reads, verbose logs) | | **History vs tool-output share** | Split the growth in each request into *conversation text* and *tool results* | Decides whether summarizing history can help at all; tool results are often the larger part | | **Retries / errors per turn** | Tool-call error signatures | Repeated errors = wasted loops | | Cost per successful task | Cost ÷ passed tasks | The number you ultimately want to lower | ## Per-step token map For agents that run several model calls per user request, build one table per request type. Below is a filled example from the synthetic pipeline [`examples/sample-pipeline.json`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-pipeline.json) (once you collect runtime logs, fill in the `Dynamic tokens / call` column with average retrieved passages, history, and tool results): | Step | Model | Calls | Fixed tokens / call | Dynamic tokens / call | Fixed total | Share | Note | |------|-------|------:|--------------------:|----------------------:|------------:|------:|------| | `guardrail` | `small` | 1 | 800 | *(from logs)* | 800 | 1.0% | `< 1,024 tok`: likely not cacheable | | `rewrite` | `small` | 1 | 2,500 | *(from logs)* | 2,500 | 3.2% | | | `router` | `large` | 1 | 12,000 | *(from logs)* | 12,000 | 15.2% | Large-model routing overhead | | `classify` | `small` | 1 | 2,000 | *(from logs)* | 2,000 | 2.5% | | | **`answer`** | **`large`** | **2** | **28,000** | *(from logs)* | **56,000** | **71.1%** | `reference_doc` (20k) + `rules_and_tools` (8k) × 2 calls | | `follow_up` | `small` | 1 | 3,500 | *(from logs)* | 3,500 | 4.4% | | | `final_reply` | `large` | 1 | 2,000 | *(from logs)* | 2,000 | 2.5% | | | **Total (per request)** | — | **8** | — | — | **78,800** | **100.0%** | Lower bound (excluding dynamic tokens) | Rank **components** (system prompt, tool schemas, output schema, reference documents) by `tokens × calls` (`answer/reference_doc`: `20,000 × 2 = 40,000 tok, 50.8%` → `answer/rules_and_tools`: `8,000 × 2 = 16,000 tok, 20.3%` → `router/fixed`: `12,000 × 1 = 12,000 tok, 15.2%`). The top one or two usually explain most of the waste. ### No production access? Estimate statically If you cannot read production usage yet, count the fixed prompt parts from the code with a tokenizer. [`examples/prompt_budget.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/prompt_budget.py) takes a small JSON description of the steps (a prompt file or a token count, plus calls per request) and prints the map: ```bash python3 examples/prompt_budget.py examples/sample-pipeline.json ``` Treat the result as a **lower bound**: it excludes everything that arrives per request (user data, retrieved passages, conversation history, tool results), so real usage is higher. Use it to rank candidates; confirm with real measurements as soon as you can, and say plainly in any report that the figures are estimates. Also flag steps whose fixed prompt is below your provider's minimum cacheable length. ## Interpretation | Observation | Likely direction (verify in stage 2) | |-------------|--------------------------------------| | High overhead on request #1 | Large instructions or tool catalog | | Steep growth between requests | Large tool outputs or unpruned history (check the history vs tool-output split before choosing a fix) | | Low cache hit % | Prefix changes between requests | | Same error signature ≥ 3 in a turn | Failure loop | | High output tokens | Verbose answers or excessive reasoning effort | | One reference document is a large share of a step, or the step is called more than once | Static prompt bloat × call count | | Many LLM calls per user request, several of them small classifiers or checks | Redundant pipeline steps (fan-out) | | Logged tokens are well below billed tokens | Un-instrumented calls: add them to the log before trusting any conclusion | | A per-session list (messages, reports, tool results) only ever grows | Unbounded state: find the truncation logic; if none, add it | ## Sharing measurements safely Diagnosis often involves a vendor, a platform team, or a customer. Share what is needed and no more: - **Safe by default:** aggregated token counts, prompt sizes, call counts, hit rates, error signatures. - **Ask first:** prompt text, tool results, retrieved passages, user or customer data, internal names. - Redact identifiers and sample or aggregate before export; remember that log and trace platforms store whatever you send them. - Agree up front who decides what: the platform or vendor team proposes structure and settings; the domain owner decides which facts must survive a summary; the security owner approves retention or data-handling changes.
Input mix
100%
Illustrative mix: system prompt 61.4%, tool definitions 23.0%, tool results 6.3%, history and user input 9.3%. In the sample log, tool definitions account for 16,800 / 73,000 input tokens across seven requests, or 23.0%. The other segments are hypothetical: the log does not record that breakdown. See tokprof for estimated segments and token_report.py for the aggregate.
## Worked example On the sample log, `s1` shows 9,200 tokens of overhead on its first request, of which two tool definitions (`notebook_edit`, `browser_open`) are never called. Turn 1 in `s1` has three identical `pytest: command not found` errors. For a pipeline, run the static estimate on the synthetic [`sample-pipeline.json`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-pipeline.json) (invented numbers for illustration): 8 LLM calls per request and about 78,800 fixed tokens. One reference document attached to the answer step (called twice) accounts for about half of all fixed tokens, and the guardrail step is under 1,024 tokens, so it likely cannot be cached. That single table already says where to look first. ## Next Pick the **largest** suspicious signal and go to [2. Isolate](../02-isolate/). --- ## 2. Isolate the problem (agent-tokenomics/02-isolate.md) Canonical URL: > LLM agent tokenomics Stage 2 (Isolate): attribute token cost to unused tools, failure loops, bloated tool outputs, or history growth one variable at a time. **Goal:** turn "it's expensive" into one specific, testable cause. ## Cause categories | Category | Signal in the diagnosis | Isolating experiment | |----------|------------------------|----------------------| | **Re-learning repo facts** | Same discovery calls and the same corrected command at the start of many sessions | Count identical early tool calls across sessions | | **Unused tools** | Tool definitions never called, yet sent every request | Compute `definition tokens × requests` per unused tool | | **Failure loops** | Same error signature repeated in a turn | Count repeats per turn; read the transcript | | **Bloated tool output** | A few tools dominate tool-output tokens | Rank tools by output tokens; inspect the largest results | | **History growth** | Steep input growth with little new information, and conversation text (not tool results) is the larger share | Replay a session with history truncated or summarized; check that cache hit % does not collapse | | **Prefix churn (cache misses)** | Low cache hit % | Diff consecutive requests; find the first divergence | | **Over-large model / effort** | Easy steps use the biggest model | Re-run those steps with a smaller model | | **Retries and rework** | Many tool calls per accepted change | Inspect turns that ended in revert/redo | | **Context rot** | Quality drops in long sessions before the window is full; instructions given early are ignored | Re-run the task with a fresh session carrying a short summary; compare success | | **Tool-count × step-count multiplier** | Large tool catalog *and* many steps per task | Compute `schema tokens × steps`; re-run with a minimal tool set | | **Large static documents × call count** | One reference document (rules, cheat sheet, policy) is a big share of a step's fixed tokens, and the step is called more than once | Rank components by `tokens × calls`; re-run with the document attached only when relevant and compare | | **Redundant pipeline steps (fan-out)** | Many LLM calls per user request; some are small checks or classifiers | Trace one request end to end; for each step ask what changes if it is skipped, merged, or done with a rule | | **Unbounded per-session state** | Input grows turn after turn from internal messages, reports, or tool results that are never trimmed | Search the code for truncation or windowing; replay a long session with the state capped | | **Short, uncacheable prompts** | Several steps have fixed prompts below the provider's minimum cacheable length | Compare each step's fixed tokens with the minimum; check `cached_tokens` is 0 for them | | **Over-broad prompt / instructions** | Agent explores widely, or instructions repeat what the code already says | Replace with a scoped prompt and a trimmed instruction file; compare steps and success | ## Method 1. Rank categories by **estimated tokens at stake** (from the baseline), not by how plausible they feel. 2. For the top one, design an experiment that changes **only that variable** (e.g., remove the unused tools, nothing else). 3. Write the hypothesis in one sentence with a number: *"Unused tool definitions cost ~14,000 tokens across 7 requests (19% of input)."*
Unused tools
2,000 tok/call
run_tests ×3
28,800 input tok
read_file output
4,200 output tok
The sample s1 shows definitions per call, total input across the three error calls, and one read_file result; the log does not establish whether it was filtered. Bar lengths are not comparable because units and scopes differ; not all 28,800 tokens are avoidable. The causes can overlap, so do not sum them.
### Check prompt cache-busting Inspect a recording from `.tokprof/*.jsonl` for **prefix hash churn**. Putting `datetime.now()`, request UUIDs, or nondeterministically ordered dictionary entries into the system prompt can change `sysfp` on each call and prevent cache reuse. Nondeterministic tool ordering can also break the request prefix, but `sysfp` fingerprints **system text only**, so inspect the tool segments separately. ```bash jq -r '[.conv, .sysfp, .usage.cached] | @tsv' run.jsonl ``` Compare calls within the same conversation and recording; `sysfp` is salted and may be absent. A changing hash is a clue, not proof of cache misses: cached counts can be unavailable, and provider minimum lengths, routing, and expiry also matter. Confirm the first prefix divergence and compare cache usage before changing one variable. ## Interpretation - Rule out **tool output** before blaming history: if tool results dominate the growth, truncating or paginating them is cheaper and safer than summarizing the conversation. - If two causes overlap (e.g., a failure loop also inflates history), attribute tokens to the **root** (the loop) and handle that first. - If no category explains more than ~10% of tokens, the baseline may be fine; check whether the *task* genuinely needs that much context before optimizing further. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) — NeurIPS 2024, 2,357 citations. Shows that interface design, including concise and bounded observations, changes agent success. - [Reducing Cost of LLM Agents with Trajectory Reduction](https://arxiv.org/abs/2509.23586) — PACMSE 2025, 68 citations. Reduces agent cost by trimming waste out of the trajectory. - [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) — preprint 2024, 566 citations. A fixed localize-repair-validate pipeline competes with open-ended agent loops on SWE-bench Lite at low cost. - [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) — preprint 2025, 66 citations. Simple observation masking is as efficient as LLM summarization for agent context management. - [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) — preprint 2025, 40 citations. Systematic study of the efficiency-effectiveness trade-off in agent system design. ## Next Reproduce and quantify it in [3. Prove](../03-prove/). --- ## 3. Prove the problem (agent-tokenomics/03-prove.md) Canonical URL: > LLM agent tokenomics Stage 3 (Prove): reproduce token waste on a frozen task set and quantify cost and confidence intervals across repeat runs. **Goal:** a hypothesis is not accepted until a repeatable measurement supports it. ## Checks 1. **Freeze the setup:** model, version, temperature/effort, prompts, tool set, task list, and environment. 2. **Baseline runs:** run every task **at least 3 times** (outputs are nondeterministic). Record per task: total tokens by type, cost, success (pass/fail), duration. 3. **Targeted counter-run:** apply only the isolation change from stage 2 (e.g., disable the unused tools) and run again with the same task set and repetitions. 4. **Compare:** the waste attributed to the cause should appear as a drop in the specific metric (e.g., input tokens on request #1), not just in the total. ## Evidence standard | Question | Evidence required | |----------|-------------------| | Is the cause real? | The metric moves when only that variable changes. | | How big is it? | Mean and spread across repetitions, per task and overall. | | Is it general? | It appears in more than one task / session / repository. | | Is it safe to remove? | Success rate in the counter-run is not lower beyond noise. | If the spread between repetitions is larger than the effect, run more repetitions or choose a bigger target. ### Cost measurements versus pass-rate guardrails For a deterministic fixed-prefix reduction, such as a **synthetic** 2,000-token drop, 3–5 repeats per task can establish the size of the token-count change if the observed spread is small; variable effects require checking the spread and repeating as needed. This is not enough to establish success-rate parity. For a 3–5 percentage-point change in Pass@1, use a substantially larger fixed task set and calculate a paired confidence interval or power analysis before deciding. A 20–50+ task subset can be an exploratory starting point, **not** a sufficient sample-size guarantee: small differences can require hundreds or more tasks depending on paired outcomes, desired power, and the equivalence margin. Report the uncertainty and leave the guardrail inconclusive when it is too wide ([Adding Error Bars to Evals](https://arxiv.org/abs/2411.00640)). ## When the fix is lossy (summaries, compaction) Compressing history cannot *guarantee* the same result; it can only be **shown** equivalent on your tasks. Define "equivalent" before running the experiment: 1. **Success parity** — use the same tasks and enough observations that a paired confidence interval fits within the predeclared equivalence margin; otherwise the result is inconclusive. 2. **Preserved facts** — list what must survive: decisions, constraints, file paths, error signatures, open TODOs. After compaction, ask questions whose answers are in that list and count correct recalls. 3. **No new rework** — re-asked questions and repeated explorations per task do not increase. 4. **Net cost** — saved input tokens, minus the cost of the summarization call and of any lost prompt-cache reuse (see [Improve](../04-improve/#compaction-without-losing-the-cache)), is positive. Keep the original transcript so a failed recall can be traced to what the summary dropped. ## Component-level evals (routers, classifiers, guardrails) In a pipeline, a small decision step (which route, which category, allowed or blocked) can silently change the final answer. When the fix shrinks such a step's prompt or tool descriptions, prove it with a **component-level eval set** in addition to end-to-end success: 1. Build a labeled set of real-shaped cases (hundreds is typical; sample from production with redaction). 2. Measure **decision accuracy** and a confusion table, before and after the change, on the same cases. 3. Set the minimum acceptable accuracy per class **before** running (the rare, high-cost classes matter more than the average). 4. Do not shrink tool descriptions or output schemas without this check: they interact with answer accuracy. 5. For static-document fixes, also report the `tokens × calls` before and after, not only the total. ## Multi-step reliability Per-step errors compound: if each step succeeds with probability *p*, an *n*-step run succeeds with *pⁿ* (when steps are independent). That is simple arithmetic, not a measurement of your agent, but it shows why long loops are fragile: | Steps | p = 0.95 | p = 0.99 | |------:|---------:|---------:| | 5 | 0.774 | 0.951 | | 10 | 0.599 | 0.904 | | 20 | 0.358 | 0.818 | | 50 | 0.077 | 0.605 | Consequences for your proof: report **cost per *successful* task**, not total tokens; and expect that fixes which *shorten* the loop (clear done-criteria, pre-stated repo facts, fewer retries) can raise success as well as cut cost.
5 steps
77%
10 steps
60%
20 steps
36%
Rounded pn values assume independent steps with p = 0.95; these are not measurements of an actual agent.
## Template ```text Hypothesis: Variable: Tasks / reps: Baseline: tokens= cost=<> success= Counter-run: tokens= cost=<> success= Conclusion: confirmed | rejected | inconclusive (why) ``` ## Worked example For the sample, the hypothesis "three identical `pytest: command not found` errors in one turn cause two avoidable extra requests (and their re-sent context)" is proven by running the same task with the right command (`python -m pytest`) stated up front, and confirming the requests per turn drop while success stays equal. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [Evaluating Very Long-Term Conversational Memory of LLM Agents](https://arxiv.org/abs/2402.17753) — ACL 2024, 1,082 citations. Benchmark of very long-term conversational memory. - [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) — ICLR 2024, 869 citations. Benchmark of long-term memory in chat assistants; useful for designing recall checks. - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — TMLR 2024, 289 citations. Argues agent evaluations must control for cost, not just accuracy. - [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — preprint 2024, 1,669 citations. Benchmark that introduces pass^k to measure agent reliability across repeated runs. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — preprint 2024, 194 citations. Statistical guidance for reporting uncertainty in LLM evaluations. - [Non-Determinism of"Deterministic"LLM Settings](https://arxiv.org/abs/2408.04667) — preprint 2024, 159 citations. Shows outputs vary across runs even in settings meant to be deterministic. ## Next Only a **confirmed** hypothesis moves on to [4. Improve](../04-improve/). --- ## 4. Improve (agent-tokenomics/04-improve.md) Canonical URL: > LLM agent tokenomics Stage 4 (Improve): apply one targeted fix per experiment — micro-skills, tool pruning, loop guards, output truncation, or prompt caching. **Goal:** the smallest change that removes the proven waste. One fix per experiment. ## Fix catalog | Proven cause | Fix | Notes | |--------------|-----|-------| | Re-learning repo facts | Put short, confirmed repo facts at the start of the session (instructions file or injected "micro-skills"): correct test command, required env var, where generated files live | Keep facts few and verified; drop a fact when later sessions contradict it | | Unused tools | **Prune** tool definitions; load tools on demand; give sub-agents narrow tool sets | Keep a one-step way to re-enable a pruned tool | | Failure loops | Detect repeated identical errors in a turn; inject **one** redirect ("try a different approach"); if still stuck, tell the user how to stop | Never silently kill a turn; cap redirects per turn | | Bloated tool output | Truncate or paginate results; search before reading whole files; return summaries; run bulk loops in a script and return only the result | Make truncation visible so the agent can ask for more | | History growth | Compact/summarize older turns; start fresh sessions per task; isolate exploration in sub-agents | Summaries are lossy — see [Compaction without losing the cache](#compaction-without-losing-the-cache) | | Prefix churn | Put stable content first (system prompt, instructions, tool definitions), volatile content last; do not edit the prefix mid-session | Check with a cache-diff view | | Over-large model / effort | Route easy steps to a smaller model; lower reasoning effort by default | Gate with the stage-3 quality check | | Retries and rework | Better success criteria in the prompt; validate cheaply before expensive steps | Often also improves quality | | Context rot | Put critical rules at the start *and* restate key constraints near the end; compact or restart before the window is nearly full | Models attend less reliably to the middle of long contexts ([Lost in the Middle](https://arxiv.org/abs/2307.03172)) | | Tool-count × step-count multiplier | Per-workspace tool sets; audit servers by usage; cap steps (`maxTurns`-style limit) and define a done-criterion | See [MCP audit](../../copilot-tokenomics/09-mcp-audit/) | | Over-broad prompt / instructions | Keep only "landmine" facts; declarative rules; one task per prompt; a plan file for complex work | Context files often add cost without raising success ([arXiv:2602.11988](https://arxiv.org/abs/2602.11988)) | | Long, stable knowledge in every prompt | Package as an on-demand **skill** instead of always-on text | Keep one source of truth | | Verbose model output | Standing output limits ("code only", fixed formats); structured output | Output tokens usually cost more than input | | Large static documents × call count | Attach a reference document only when the question needs it (rule or retrieval); split into sections and include the relevant ones; load on demand through a tool or skill; attach it once rather than on every call of a multi-call step | Gate the condition with the component-level eval from stage 3; measure `tokens × calls` | | Redundant pipeline steps (fan-out) | Skip a step with a deterministic check; merge neighboring classification steps into one call; use a smaller model for guardrails and routing; drop steps whose output is rarely used | Each removed step must pass the stage-3 eval; keep the old path behind a flag until proven | | Unbounded per-session state | Cap or window internal messages; keep only what later steps need (a short result, not the full report); summarize by the compaction rules below | Search for the missing truncation first: it is often a one-line fix | | Short, uncacheable prompts | Merge the step into a neighbor, replace it with a rule, or accept it (it is small); never pad to reach the minimum | Check the provider's current minimum and `cached_tokens` | | Bulk / polling tool loops | Run the loop in a script and return only the summary | Benchmark scripted vs interactive |
TokenEconomizer framework for controlling costs across agent sessions
Reference framework for experience-driven cost control. Source: microsoft/TokenEconomizer (Apache 2.0); see also arXiv:2610.22732.
## Observation masking for old tool output For [bloated tool output or history growth](../02-isolate/), replace large tool results older than the last `K` steps with a deterministic placeholder rather than making an extra LLM summarization call. In this **synthetic** example, preserve the tool call/result pairing and recent working window: ```text current_step = 5; K = 3 # keep results from steps 3–5 unchanged turn 1 read_file result → [omitted 4,200-token read_file output from turn 1; path=src/checkout.py lines=1..180] ``` Masking requires no summarization model call, but the placeholder still consumes input tokens. It is lossy and can invalidate part of the prompt cache; retain the original securely for on-demand rereading, redact paths if needed, and measure cost, cache reuse, and task success against the baseline. This approach is informed by [The Complexity Trap](https://arxiv.org/abs/2508.21433); its results are reported by the authors and are not independently reproduced here. ## Compaction without losing the cache Compaction and prompt caching pull in opposite directions: rewriting the *beginning* of the history changes the request prefix, so the provider can no longer reuse its cache and you pay full input price again.
Stable prefix
Stable prefixSummaryRecent turns
CACHE HIT
Full rewrite
Rewritten prefix
CACHE MISS
Conceptual comparison: placing a summary and recent turns after a stable prefix can preserve prefix cache reuse; rewriting the prefix invalidates the old match. Actual hits depend on provider minimum length, retention, and other cache conditions.
- **Keep the prefix stable.** System prompt, instructions, and tool definitions first and unchanged; keep the history append-only between compactions. - **Compact rarely, in one batch,** when a threshold is reached (for example, a fraction of the context window) or at a task boundary — not every turn. - **Break-even check.** Compact only if `saved tokens × remaining turns × (1 − cached-input discount)` exceeds `summarization call cost + cache rebuild cost`. Short remaining sessions rarely pay back. - **Structure the summary** by what the agent needs, not by chronology: ```text Goal: Decisions: Constraints: Done / artifacts: Open items: Failures to avoid: ``` A few lines of natural language can carry nuance the fields cannot; use the structure as the core and add prose only for what does not fit. - **Summarize in the background, off the critical path:** trigger when the context passes a token threshold, run asynchronously after the answer, and use the result from the next turn on. - **Mix summary and raw tail:** send the summary plus the last few raw turns, and cap the summary length. The summarizer's own prompt is usually short (often below the cacheable minimum), so its cost is mostly uncached input; make sure the savings on later calls outweigh it (break-even above). - **Domain owners decide what must survive** (for example, the facts a human advisor would never want lost); engineers implement and test it. Review the list when the domain changes. - **Offload instead of summarizing** when you can: save long raw output to a file and keep a one-line summary plus the path, so the agent can re-read it on demand (near-lossless). - **Guard the summary:** do not summarize a summary repeatedly (errors compound); keep the original; redact secrets and personal data before they enter a summary. - Validate with the [lossy-fix criteria](../03-prove/#when-the-fix-is-lossy-summaries-compaction). ### Worked example: multi-turn counselor dialogue compaction In customer-support and counseling agents, older dialogue turns repeat greetings, apologies, raw `` JSON wrappers, duplicate session UUIDs, and closing boilerplate. Compacting completed episodes into a BPE-aligned chain (`intent -> tool(args) => outcome | ...`) cuts multi-turn history tokens while retaining **100%** of customer IDs, order IDs, dates, prices, tracking numbers, and escalation outcomes. English examples live in [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py) and Korean examples live in [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py) (unified runner: [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) `--lang {en,ko,all}`, verified 2026-11-04): **English multi-turn chat & support dialogues (`examples/formula_prompt_en.py`):** | English dialogue & Hugging Face dataset (`row`) | Raw chat (`o200k` / `cl100k`) | Compacted BPE chain (`o200k` / `cl100k`) | `o200k_base` delta | `cl100k_base` delta | Slots kept | |-------------------------------------------------|------------------------------:|-----------------------------------------:|-------------------:|--------------------:|-----------:| | Login OTP fallback call (13 turns, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[0]`) | 336 / 350 | 57 / 58 | **-83.0%** | **-83.4%** | 7/7 | | Recalled monitor return & refund (13 turns, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[1]`) | 339 / 347 | 53 / 53 | **-84.4%** | **-84.7%** | 8/8 | | Warranty replacement & Cancel glitch (19 turns, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[2]`) | 526 / 535 | 81 / 81 | **-84.6%** | **-84.9%** | 9/9 | | OTP lockout & password reset (17 turns, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[3]`) | 460 / 471 | 49 / 49 | **-89.3%** | **-89.6%** | 6/6 | | Medical intake palpitations chat (10 turns, [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) `sessions[0..9]`) | 321 / 322 | 74 / 73 | **-76.9%** | **-77.3%** | 9/9 | | Production line robot support chat (4 turns, [`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) `train[1,2]`) | 112 / 114 | 35 / 36 | **-68.8%** | **-68.4%** | 6/6 | | **Total (6 English multi-turn chat dialogues)** | **2,094 / 2,139** | **349 / 350** | **-83.3%** | **-83.6%** | **45/45 (100%)** | **Korean multi-turn chat & counseling dialogues (`examples/formula_prompt_ko.py`):** | Korean dialogue & Hugging Face dataset (`row`) | Raw chat (`o200k` / `cl100k`) | Compacted BPE chain (`o200k` / `cl100k`) | `o200k_base` delta | `cl100k_base` delta | Slots kept | |------------------------------------------------|------------------------------:|-----------------------------------------:|-------------------:|--------------------:|-----------:| | Address + shipping + spam report (14 turns, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[0]`) | 304 / 460 | 84 / 129 | **-72.4%** | **-72.0%** | 9/9 | | Cart + laptop defect + receipt (15 turns, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[2]`) | 386 / 565 | 127 / 190 | **-67.1%** | **-66.4%** | 9/9 | | Shipping + Gold tier + refund/cancel (16 turns, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[5]`) | 436 / 638 | 158 / 225 | **-63.8%** | **-64.7%** | 11/11 | | Return/exchange + refusal + orders (13 turns, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[6]`) | 368 / 545 | 124 / 194 | **-66.3%** | **-64.4%** | 11/11 | | Parcel lookup & locker redirect chat (6 turns, [`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[2]`) | 195 / 226 | 55 / 61 | **-71.8%** | **-73.0%** | 5/5 | | Medical intake palpitations chat (10 turns, [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) `sessions[0..9]`) | 402 / 613 | 102 / 144 | **-74.6%** | **-76.5%** | 10/10 | | Multi-session persona & family chat (18 turns, [`nayohan/141_korean_multi_session_dialogue`](https://huggingface.co/datasets/nayohan/141_korean_multi_session_dialogue) `train[0]`) | 359 / 567 | 77 / 103 | **-78.6%** | **-81.8%** | 11/11 | | **Total (7 Korean multi-turn chat dialogues)** | **2,450 / 3,614** | **727 / 1,046** | **-70.3%** | **-71.1%** | **66/66 (100%)** | Across **580 live chat, customer-support, and counseling sessions** (250 English rows across 5 datasets + 330 Korean rows across 7 datasets) fetched from public Hugging Face datasets (`python3 examples/formula_prompt.py --hf-live --hf-rows 50`), generalized BPE grammar and discourse compression reduces total tokens by **56.3% on `o200k_base`** (**54.9% on `cl100k_base`**) while preserving **1,731 / 1,731 (100.0%)** strict slots (statute numbers, court case IDs, emails, UUIDs, kebab-case IDs, order/user IDs, dates, amounts, and placeholders): | Language & Hugging Face dataset (`--hf-live --hf-rows 50`) | Rows | `o200k_base` (Raw → BPE) | `cl100k_base` (Raw → BPE) | Strict slots kept | |------------------------------------------------------------|-----:|-------------------------:|--------------------------:|------------------:| | EN: [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) | 50 | 23,979 → 11,538 (**-51.9%**) | 24,629 → 11,912 (**-51.6%**) | 124/124 | | EN: [`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) | 50 | 11,431 → 3,390 (**-70.3%**) | 11,639 → 3,406 (**-70.7%**) | 281/281 | | EN: [`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) | 50 | 3,146 → 1,548 (**-50.8%**) | 3,226 → 1,590 (**-50.7%**) | 0/0 (100%) | | EN: [`Kaludi/Customer-Support-Responses`](https://huggingface.co/datasets/Kaludi/Customer-Support-Responses) | 50 | 1,837 → 893 (**-51.4%**) | 1,883 → 919 (**-51.2%**) | 1/1 | | EN: [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions`, EN) | 50 | 1,462 → 608 (**-58.4%**) | 1,467 → 610 (**-58.4%**) | 11/11 | | **English subtotal (5 datasets)** | **250** | **41,855 → 17,977 (-57.0%)** | **42,844 → 18,437 (-57.0%)** | **417/417 (100%)** | | KO: [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) | 50 | 19,243 → 7,774 (**-59.6%**) | 29,172 → 12,468 (**-57.3%**) | 220/220 | | KO: [`jjun123/delivery-app-function-calling-datasets-korean`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) | 30 | 42,129 → 18,182 (**-56.8%**) | 52,592 → 24,433 (**-53.5%**) | 325/325 | | KO: [`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) | 50 | 27,325 → 12,357 (**-54.8%**) | 42,753 → 18,872 (**-55.9%**) | 465/465 | | KO: [`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) | 50 | 5,788 → 2,498 (**-56.8%**) | 9,588 → 4,041 (**-57.9%**) | 38/38 | | KO: [`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) | 50 | 7,437 → 3,119 (**-58.1%**) | 9,405 → 4,478 (**-52.4%**) | 176/176 | | KO: [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions`, KO) | 50 | 1,854 → 882 (**-52.4%**) | 2,791 → 1,304 (**-53.3%**) | 13/13 | | KO: [`nayohan/141_korean_multi_session_dialogue`](https://huggingface.co/datasets/nayohan/141_korean_multi_session_dialogue) | 50 | 18,307 → 8,914 (**-51.3%**) | 28,868 → 14,252 (**-50.6%**) | 77/77 | | **Korean subtotal (7 datasets)** | **330** | **122,083 → 53,726 (-56.0%)** | **175,169 → 79,848 (-54.4%)** | **1,314/1,314 (100%)** | | **Combined total (12 dataset benchmarks, 580 chat & counseling cases)** | **580** | **163,938 → 71,703 (-56.3%)** | **218,013 → 98,285 (-54.9%)** | **1,731/1,731 (100%)** | ## Rules - **One fix at a time.** Combined changes make results unattributable. - Define the **revert condition** in advance (e.g., success drops by more than your noise threshold). - Prefer fixes that are **reversible and visible** (settings/config) over silent behavior changes. - Black-box first: if you cannot modify the agent itself, act through its configuration, instructions, and tool settings. ## Evidence by cause Published work behind each fix, ordered by venue tier then citations within a row (full list: [Papers](../../papers/)). Treat each as a hypothesis for *your* agent: prove it with [stage 3](../03-prove/). | Cause | Papers | |-------|--------| | Re-learned repo facts | [Agentic Context Engineering](https://arxiv.org/abs/2510.04618) (ICLR 2025); [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) (ICML 2024); [TokenEconomizer](https://arxiv.org/abs/2610.22732) (preprint 2026) | | Unused tools / tool schema size | [MCP-Zero](https://arxiv.org/abs/2506.01056) (preprint 2025); [RAG-MCP](https://arxiv.org/abs/2505.03275) (preprint 2025); [Less is More (function calling)](https://arxiv.org/abs/2411.15399) (preprint 2024) | | Failure loops, agent design | [SWE-agent](https://arxiv.org/abs/2405.15793) (NeurIPS 2024); [Agentless](https://arxiv.org/abs/2407.01489) (preprint 2024); [Efficient Agents](https://arxiv.org/abs/2508.02694) (preprint 2025) | | Bloated tool output / trajectory | [SWE-agent](https://arxiv.org/abs/2405.15793) (NeurIPS 2024); [Trajectory Reduction](https://arxiv.org/abs/2509.23586) (PACMSE 2025); [The Complexity Trap (observation masking)](https://arxiv.org/abs/2508.21433) (preprint 2025) | | History growth / memory | [Mem0](https://arxiv.org/abs/2504.19413) (ECAI 2025); [Recursively Summarizing](https://arxiv.org/abs/2308.15022) (Neurocomputing 2023); [MemGPT](https://arxiv.org/abs/2310.08560) (preprint 2023); [The Complexity Trap (observation masking)](https://arxiv.org/abs/2508.21433) (preprint 2025) | | Context rot | [Lost in the Middle](https://arxiv.org/abs/2307.03172) (TACL 2023); [LLMs Get Lost in Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) (ICLR 2025); [Same Task, More Tokens](https://arxiv.org/abs/2402.14848) (ACL 2024) | | Prefix churn / cache misses | [SGLang](https://arxiv.org/abs/2312.07104) (NeurIPS 2023); [Prompt Cache](https://arxiv.org/abs/2311.04934) (MLSys 2023); [Don't Break the Cache](https://arxiv.org/abs/2601.06007) (preprint 2026) | | Prompt and context compression | [LongLLMLingua](https://arxiv.org/abs/2310.06839) (ACL 2023); [LLMLingua-2](https://arxiv.org/abs/2403.12968) (ACL 2024); [LLMLingua](https://arxiv.org/abs/2310.05736) (EMNLP 2023) | | Over-large model | [FrugalGPT](https://arxiv.org/abs/2305.05176) (TMLR 2023); [Hybrid LLM](https://arxiv.org/abs/2404.14618) (ICLR 2024); [RouteLLM](https://arxiv.org/abs/2406.18665) (preprint 2024) | | Reasoning length / effort | [Token-Budget-Aware Reasoning](https://arxiv.org/abs/2412.18547) (ACL 2024); [L1 (length-controlled reasoning)](https://arxiv.org/abs/2503.04697) (preprint 2025); [Chain of Draft](https://arxiv.org/abs/2502.18600) (preprint 2025) | | Redundant pipeline steps / unneeded model size | [FrugalGPT](https://arxiv.org/abs/2305.05176) (TMLR 2023); [AutoMix](https://arxiv.org/abs/2310.12963) (NeurIPS 2023); [Agentless](https://arxiv.org/abs/2407.01489) (preprint 2024) | | Bulk calls | [Batch Prompting](https://arxiv.org/abs/2301.08721) (EMNLP 2023) | ## Next Re-measure in [5. Result](../05-result/). --- ## 5. Result (agent-tokenomics/05-result.md) Canonical URL: > LLM agent tokenomics Stage 5 (Result): re-measure token cost, task pass rate (quality guardrail), and latency against baseline to decide keep or revert. **Goal:** an honest before/after comparison and a recorded decision. ## Checks Run the *same* task set, repetitions, and environment as the baseline, now with the fix. | Metric | Baseline | With fix | Change | Acceptable? | |--------|----------|----------|--------|-------------| | Mean cost per task | | | | | | Input / cached / output tokens | | | | | | **Success rate (guardrail)** | | | | must not drop beyond noise | | Median latency | | | | | | Cost of the fix itself (extra model calls, maintenance) | | | | include it (e.g., the summarization call) | | Cache hit % | | | | a compaction that wipes the cache can erase its own savings | | Capacity and latency (when those are the goal) | | | | tokens per minute per request, utilization, p95 latency, time to first token | | Decision accuracy of changed components (routers, classifiers) | | | | from the stage-3 component eval; per class, not only average | | Recall of must-keep facts (lossy fixes only) | | | | from the stage-3 recall check | Count **every** cost the fix introduces (e.g., a judge model, a summarizer), as TokenEconomizer does in its reports.
Baseline
39,200 input tok
Illustrative fix
~15,200 input tok
In the sample, s1 turn 1 has 39,200 input tokens over four calls. The after value assumes two calls of 7,200 and 8,000 input tokens after tool pruning and a loop guard; it is not a measured result. A held pass rate is also an assumption: repeat the same tasks to verify quality and cost. Test the two changes separately.
## Decision - **Keep** if cost fell and success held. Record the change, the numbers, and the date. - **Revert** if success dropped or the saving is within noise. - **Iterate:** go back to stage 2 with the next-largest cause. Savings usually come from several small fixes, not one. ## Report template ```text Change: Cause proven: Cost / task: -> () Success: -> Side costs: Decision: keep | revert Next cause: ``` ## Keep it healthy Re-run the diagnosis periodically: new tools, longer instructions, or model changes can silently bring the waste back. ### Continuous drift guard After keeping a fix, run a fixed representative task set in CI or a weekly job when tools or instructions change. Record the baseline and assert that `first_call_input` (first-call input tokens, a fixed-overhead proxy) and `unused_tool_defs` (definitions unused across the selected task set) stay within agreed thresholds. Compare the same model, tools, and tasks; investigate intentional changes rather than silently updating the baseline. An unused tool on a small set is only a candidate for review, not proof it is unnecessary. Track task success alongside cost so the check does not reward a quality regression. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — TMLR 2024, 289 citations. Argues agent evaluations must control for cost, not just accuracy. - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — ICLR 2025, 56 citations. Defines the expected cost to obtain a correct answer and compares models on it. - [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — preprint 2024, 1,669 citations. Benchmark that introduces pass^k to measure agent reliability across repeated runs. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — preprint 2024, 194 citations. Statistical guidance for reporting uncertainty in LLM evaluations. --- ## 6. Golden dataset and rubric evaluation (agent-tokenomics/06-golden-dataset-and-rubric.md) Canonical URL: > Design an Excel/CSV Golden Dataset for single-turn and multi-turn LLM agents, combine keyword and intent matching, and score quality with a rubric. **Goal:** build a **repeatable quality guardrail** that verifies your agent preserves both answer accuracy and multi-turn memory after you cut tokens. --- ## 1. How to define a "correct answer": Keyword match vs. Intent match Using a single grading method across all agent tasks breaks down in practice. Combine **four complementary checks** in a **hybrid grading pipeline**: | Check type | When to use it | How it works (example) | Evaluation token cost | |------------|----------------|------------------------|-----------------------| | **1. Required keywords & slots (`must_include_all`)** | Missing an exact identifier, number, boundary operator, or file path makes the answer wrong | `checkout.py;>= 100` (all items must appear) | **0 tokens** (string / regex) | | **2. Synonym groups (`must_include_any`)** | Phrasing can vary, but at least one term from each concept group must appear | `weekday\|business day\|Monday;exclude weekends` | **0 tokens** (string / regex) | | **3. Forbidden phrases & tool checks (`must_not_include` / `expected_tools`)** | Blocking hallucinated promises, policy violations, unsafe commands, or skipped tool calls | Forbidden: `full refund approved`, Required tool: `update_shipping_address` | **0 tokens** (log / string) | | **4. Intent & semantic rubric (`expected_intent` + Rubric)** | Judging whether differently worded prose reaches the right conclusion and respects constraints | `"Politely decline full refund past the 7-day window and offer inspection instead"` | **Low** (LLM-as-a-Judge) |
Stage 1 (0 tok)
Deterministic check: must_include_all · must_include_any · must_not_include · expected_tools
Fast filter
Stage 2 (Judge)
5-Axis Rubric (Intent · Facts/Slots · Multi-Turn · Tools/Policy · Conciseness, 10 pts)
Verbosity Guard
Semantic check
Figure 1. Two-stage hybrid evaluation pipeline: zero-cost deterministic keyword and tool checks run first, followed by a 5-axis, 10-point intent rubric with a verbosity-bias guard.
--- ## 2. How to evaluate multi-turn conversations When testing token optimizations (such as `/compact`, observation masking, or tool pruning) across multi-turn dialogues (`Turn 1 → Turn 2 → Turn 3`), live free-form rollouts often diverge on Turn 1 — making it impossible to compare Turn 2 on identical inputs. Use two complementary modes: ### Mode A: Pinned-History Slicing (recommended default for before/after comparisons) - **How it works:** Freeze `Turn 1 .. Turn k-1` (including prior tool outputs or summaries) in `prior_turns_context`, and compare the baseline and candidate only on **Turn `k`**. - **Testing multi-turn memory retention (Planted Facts):** - **Turn 1 (Setup):** Plant a critical constraint or identifier (`"I need to change the address for order ORD-901, and I cannot receive packages on weekends"`). - **Turn 2 (Memory Check):** Ask the follow-up without repeating the constraint (`"Change it to 123 Teheran-ro, Gangnam-gu, and tell me when it will arrive"`). - Verify that after context compaction or prompt compression, the agent still remembers both `ORD-901` and the **no-weekend delivery** constraint on Turn 2. ### Mode B: End-to-End Trajectory Simulation (`pass^k`) - When evaluating loop reduction or autonomous multi-step completion, run a scripted user scenario across up to `N` turns and measure end-to-end task completion consistency (`pass^k`, [tau-bench, arXiv:2406.12045](https://arxiv.org/abs/2406.12045)) alongside total session tokens. --- ## 3. Organizing the Golden Dataset in Excel (`.xlsx` / `.csv`) To let engineers, PMs, and domain experts edit and review test cases together in Microsoft Excel without wrestling with nested JSON, use **one row per evaluated turn** in an `.xlsx` workbook and group multi-turn dialogues by `session_id` and `turn_index` (`1..5`): - **Download the actual Excel workbook (2 sheets: `Golden_Dataset` 16 rows + `Rubric_Criteria` guide)**: - [📥 Download `sample-golden-dataset.xlsx` (Excel Workbook)](https://github.com/dotnetpower/agent-tokenomics/raw/main/examples/sample-golden-dataset.xlsx) · [Open local demo `.xlsx`](/demo/sample-golden-dataset.xlsx) - [📥 Download `sample-golden-dataset.csv` (UTF-8 BOM CSV)](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-golden-dataset.csv) · [Generator & grader `golden_dataset_tool.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/golden_dataset_tool.py) | Column name | Format | Purpose & example | |-------------|--------|-------------------| | `case_id` | `HF-ECOM5-T2` | Unique row ID (`session_id` + turn number) | | `session_id` | `HF-ECOM5` | Groups turns belonging to the same conversation | | `turn_index` | `1` .. `5` | Turn order within the session | | `hf_dataset` / `hf_row` | `iamjoon/...` / `train[5]` | Source Hugging Face dataset name and split/row index | | `slice` | `multi_turn_tool` | Workload slice (`multi_turn_tool`, `multi_turn_memory`, `policy_guardrail`, `legal_statute_qa`) | | `match_mode` | `hybrid` | `keyword_only`, `intent_only`, or `hybrid` | | `prior_turns_context` | `[T1 User] ... [T1 Tool] ...` | Pinned conversation/tool history before this turn (empty for Turn 1) | | `user_input` | Text | Current user prompt for this turn | | `must_include_all` | `;`-separated | Mandatory keywords, numbers, or IDs (`5월 10일;무선 이어폰;4567891230`) | | `must_include_any` | `;` groups, `\|` synonyms | Synonym groups where at least one per group must match (`희망 날짜\|희망하는 날짜;모의 서비스\|가상`) | | `must_not_include` | `;`-separated | Forbidden strings that trigger immediate failure (`제가 바로 결제 취소해 드렸습니다`) | | `expected_tools` | `;`-separated | Tools that must be called on this turn (`view_order_history;view_order_details`) | | `expected_intent` | 1-sentence statement | **Intent grading reference:** the core meaning and conclusion required to pass | | `baseline_response` / `baseline_tokens` | Text / integer | Pre-optimization response text and token count | | `candidate_response` / `candidate_tokens` | Text / integer | Post-optimization response text and token count | ### 16 Golden Dataset rows drawn from 6 public Hugging Face datasets (`sample-golden-dataset.xlsx` Sheet 1) | Case (Turn) | Hugging Face dataset (`hf_row`) | Mode / Tools | `must_include_all` (slots) | `must_include_any` (synonyms) | `expected_intent` (intent rubric target) | |---|---|---|---|---|---| | **`HF-ECOM5-T1`** (1/5) | [`iamjoon/ecommerce-...`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) (`train[5]`) | `hybrid`
`view_order_history` | `5월 10일`
`무선 이어폰`
`4567891230` | `한진택배`
`배송 중\|배송중` | Call `view_order_history(U002)` and report May 10 wireless earbuds shipping via Hanjin (`4567891230`) | | **`HF-ECOM5-T2`** (2/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`view_user_profile` | `Gold`
`10%` | `할인 쿠폰\|쿠폰` | Retain `U002` from Turn 1, call `view_user_profile(U002)`, and report `Gold` tier + `10%` coupon | | **`HF-ECOM5-T3`** (3/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`search_policy_info` | `7일`
`왕복 배송비` | `수령 후\|수령일`
`고객센터\|신청` | Call `search_policy_info(환불)` and state the 7-day post-receipt refund window and round-trip shipping fee | | **`HF-ECOM5-T4`** (4/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`search_policy_info` | `반품` | `출고되기 전\|출고 전`
`출고 이후\|출고 후`
`주문취소 버튼\|주문내역` | Distinguish pre-shipment cancellation (order history button) from post-shipment return | | **`HF-ECOM5-T5`** (5/5) | `iamjoon/ecommerce-...` (`train[5]`) | `intent_only`
*(no tool)* | `담당자` | `직접 처리할 수 없\|직접 처리 불가`
`전달` | State that the AI agent cannot cancel payment directly and escalate to a human representative | | **`HF-ECOM2-T1`** (1/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
`show_cart` | `블루투스 이어폰`
`무선 마우스` | `1개;2개` | Call `show_cart(U001)` and report 1 Bluetooth earbud + 2 wireless mice | | **`HF-ECOM2-T2`** (2/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
`view_order_history`
`view_order_details` | `고성능 노트북`
`1,150,000원` | `1대;구매` | Retain `U001`, chain `view_order_history` → `view_order_details(O102)`, and confirm laptop purchase (`1,150,000원`) | | **`HF-ECOM2-T3`** (3/4) | `iamjoon/ecommerce-...` (`train[2]`) | `intent_only`
*(no tool)* | `담당자` | `기술적인 지원\|기술 지원`
`전달` | Identify repeated power-off as requiring technical support and escalate to the specialist team | | **`HF-ECOM2-T4`** (4/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
*(no tool)* | `카드 영수증`
`담당자` | `직접 처리할 수 없\|직접 처리 불가`
`전달` | State that card receipt issuance cannot be handled directly by the bot and forward to staff | | **`HF-DELIV-T1`** (1/1) | [`jjun123/delivery-app-...`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) (`train[0]`) | `hybrid`
`create_delivery_order` | `14,900원;7,000원`
`21,900원;이서준`
`e2a4b1c9-...` | `관악구 관악로 1`
`준비 중\|준비중`
`담당자` | Summarize items, total (`21,900원`), recipient (`이서준`), order UUID, preparation status, and escalate ETA check | | **`HF-DFM14-T1`** (1/1) | [`schneiderkamplab/dfm14-...`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) (`train[2]`) | `keyword_only`
`lookup_parcel`
`redirect_parcel` | `parcel-610`
`locker-16`
`redirect-610` | `변경 처리가 완료\|변경 완료` | Chain `lookup_parcel(10610, tracking-610)` → `redirect_parcel(locker-16, parcel-610)` and return `redirect-610` | | **`HF-CLINIC-T1`** (1/1) | `schneiderkamplab/dfm14-...` (`train[11]`) | `hybrid`
*(no tool)* | `병원 이름`
`서비스 종류` | `희망 날짜\|희망하는 날짜`
`모의 서비스\|가상`
`예약 가능 시간대` | Clarify that the service is a mock slot lookup (no real booking or medical advice) | | **`HF-KLAC-T1`** (1/1) | [`jihye-moon/klac_legal_aid...`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) (`train[1]`) | `hybrid`
*(no tool)* | `제34조;제4조`
`1년;4주;15시간` | `근로기준법`
`근로자퇴직급여 보장법`
`퇴직연금` | Cite Labor Standards Act Art. 34 & Retirement Benefit Act Art. 4 plus `< 1 year` and `< 15h/week` exclusions | | **`HF-KLAC-T2`** (1/1) | `jihye-moon/klac_legal_aid...` (`train[0]`) | `hybrid`
*(no tool)* | `최저임금법`
`제6조;무효;90%` | `3월\|3개월`
`수습` | Cite Minimum Wage Act Art. 6 (sub-minimum agreements void) and `90%` probation rule (`≤ 3 months`) | | **`HF-LABOR-T1`** (1/1) | [`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) (`train[34]`) | `hybrid`
*(no tool)* | `30일;30일분`
`통상임금;3개월` | `천재·사변\|부득이한 사유`
`예외` | State 30-day dismissal notice or `≥ 30 days` ordinary wage rule and `< 3 months` / force-majeure exceptions | | **`HF-OSCE-T1`** (2/2) | [`nwirandx/Korean-OSCE-...`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions[0..9]`) | `hybrid`
*(no tool)* | `김서현`
`1984년 5월 23일`
`20일;15분;20분;30분` | `과거력 없음\|과거력은 없`
`어지럽고\|어지러움`
`숨이 차\|호흡곤란` | Summarize 9 turns of clinical intake (patient info, 20-day onset, 15–20m → >30m progression, no past history, dizziness/dyspnea) | --- ## 4. Reviewing & designing a 10-point Rubric (5 axes × 0–2 points = 10 points max) Unanchored 1–10 scales drift between judge runs. Instead, decompose the 10-point score into **5 orthogonal axes × 0 / 1 / 2 points = 10 points max**. Separating **current-turn fact/slot accuracy (Axis 2)** from **multi-turn context retention (Axis 3)** and **tool/policy compliance (Axis 4)** pinpoints exactly which optimization caused a regression: | Rubric axis (5 Axes × 2 pts = 10 pts) | 0 pts (Fail — critical defect) | 1 pt (Partial) | 2 pts (Pass — full credit) | What it guards against | |---|---|---|---|---| | **1. Intent & core resolution**
(`intent_and_resolution`) | Misreads user intent or reaches a conclusion contrary to `expected_intent` | Captures intent but omits part of the required resolution or next step | Fully satisfies `expected_intent` regardless of phrasing | Semantic correctness when wording differs (`intent_only` / `hybrid`) | | **2. Fact, slot & numerical accuracy**
(`fact_and_slot_accuracy`) | Drops/distorts required IDs, numbers, dates, or statutes, or hallucinates facts | Core facts hold, but secondary numbers or conditions are vague | States all required keywords, numbers, IDs, and statutes accurately | Slot/number loss during BPE or prompt compression (`keyword` / `hybrid`) | | **3. Multi-turn context & state retention**
(`multiturn_context_retention`) | Forgets constraints or IDs from `prior_turns_context`, contradicting or re-asking | Partially recalls prior turns or links context loosely | Consistently retains user IDs, planted constraints, and state across turns | Memory loss after `/compact` or observation masking | | **4. Tool selection & policy guardrails**
(`tool_and_policy_compliance`) | Skips required tools and fabricates results, or violates `must_not_include` / policy | Obeys safety boundaries but makes redundant tool calls or minor format errors | Calls the right tools (or escalates out-of-scope actions) and obeys all policies | Over-pruned tool schemas or weakened guardrail prompts | | **5. Concise completeness (Verbosity guard)**
(`concise_completeness`) | Omits essential details so the user must ask again, or produces broken text | Complete but padded with repetitive greetings, apologies, or filler | **Complete, actionable, and concise — awards full marks to shorter answers** | **Prevents LLM judges from favoring bloated replies** | > **Recommended pass threshold:** A turn passes (`PASS`) only when all deterministic checks succeed **and** the 5-axis rubric total is **≥ 8 / 10** with no `0`-point axis. --- ## 5. Runnable Python `.xlsx` / `.csv` generator & evaluator (`examples/golden_dataset_tool.py`) [`examples/golden_dataset_tool.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/golden_dataset_tool.py) uses only the Python standard library to generate a native two-sheet Microsoft Excel workbook ([`examples/sample-golden-dataset.xlsx`](https://github.com/dotnetpower/agent-tokenomics/raw/main/examples/sample-golden-dataset.xlsx): `Golden_Dataset` + `Rubric_Criteria` 10-point guide) and a `utf-8-sig` CSV ([`examples/sample-golden-dataset.csv`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-golden-dataset.csv)), evaluate all 16 Hugging Face single-turn and multi-turn rows directly from `.xlsx` or `.csv`, and print the 10-point LLM-as-a-Judge prompt: ```bash # 1. Generate the two-sheet Excel workbook (.xlsx) and UTF-8 BOM CSV (.csv) python3 examples/golden_dataset_tool.py --write-sample # 2. Evaluate Baseline vs. Candidate directly from the .xlsx workbook python3 examples/golden_dataset_tool.py --eval examples/sample-golden-dataset.xlsx # 3. Print the 10-point LLM-as-a-Judge rubric prompt for a 5-turn Hugging Face case (HF-ECOM5-T5) python3 examples/golden_dataset_tool.py --print-judge-prompt HF-ECOM5-T5 ``` ### Sample evaluation output (`examples/sample-golden-dataset.xlsx`, 16 rows) ```text case_id turn hf_dataset base_ok cand_ok base_tok cand_tok delta rubric -------------------------------------------------------------------------------------------------------- HF-ECOM5-T1 1 iamjoon/ecommerce-function-calli PASS PASS 4,200 2,350 -44.0% 10/10 HF-ECOM5-T2 2 iamjoon/ecommerce-function-calli PASS PASS 5,800 3,100 -46.6% 10/10 HF-ECOM5-T3 3 iamjoon/ecommerce-function-calli PASS PASS 7,400 3,850 -48.0% 10/10 HF-ECOM5-T4 4 iamjoon/ecommerce-function-calli PASS PASS 9,100 4,500 -50.5% 10/10 HF-ECOM5-T5 5 iamjoon/ecommerce-function-calli PASS PASS 10,800 4,950 -54.2% 10/10 HF-ECOM2-T1 1 iamjoon/ecommerce-function-calli PASS PASS 4,100 2,200 -46.3% 10/10 HF-ECOM2-T2 2 iamjoon/ecommerce-function-calli PASS PASS 6,900 3,600 -47.8% 10/10 HF-ECOM2-T3 3 iamjoon/ecommerce-function-calli PASS PASS 8,300 4,100 -50.6% 10/10 HF-ECOM2-T4 4 iamjoon/ecommerce-function-calli PASS PASS 9,600 4,450 -53.6% 10/10 HF-DELIV-T1 1 jjun123/delivery-app-function-ca PASS PASS 12,400 6,800 -45.2% 10/10 HF-DFM14-T1 1 schneiderkamplab/dfm14-ko-synthe PASS PASS 5,400 2,900 -46.3% 10/10 HF-CLINIC-T1 1 schneiderkamplab/dfm14-ko-synthe PASS PASS 4,900 2,700 -44.9% 10/10 HF-KLAC-T1 1 jihye-moon/klac_legal_aid_counse PASS PASS 6,400 3,300 -48.4% 10/10 HF-KLAC-T2 1 jihye-moon/klac_legal_aid_counse PASS PASS 5,900 3,100 -47.5% 10/10 HF-LABOR-T1 1 seventy4/labor-counsel-qa PASS PASS 5,200 2,850 -45.2% 10/10 HF-OSCE-T1 2 nwirandx/Korean-OSCE-history-tak PASS PASS 9,400 4,600 -51.1% 10/10 -------------------------------------------------------------------------------------------------------- Pass rate : Baseline 16/16 (100.0%) -> Candidate 16/16 (100.0%) Mean rubric score : Baseline 9.62/10 -> Candidate 10.00/10 Total tokens : Baseline 115,800 -> Candidate 59,350 (-48.7%) Cost-of-Pass (tok) : Baseline 7,238 tok/pass -> Candidate 3,709 tok/pass Decision : KEEP (Quality held & tokens reduced) ``` --- ## Further reading (papers) - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — preprint 2025. Evaluates models by expected cost per successful task (`Cost-of-Pass`) rather than per-call price alone. - [$\tau$-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — preprint 2024. Evaluates multi-turn tool calls and policy compliance across repeat trials (`pass^k`). - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — preprint 2024. Establishes joint cost-and-accuracy reporting and anti-contamination practices for agent benchmarks. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — preprint 2024. Computes paired confidence intervals and sample-size requirements for evaluations. - [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) — ICLR 2025. Benchmarks multi-turn fact retention and knowledge updates across long sessions. --- ## Case study: TokenEconomizer (agent-tokenomics/case-tokeneconomizer.md) Canonical URL: > What microsoft/TokenEconomizer does and how it maps to the troubleshooting stages. [TokenEconomizer](https://github.com/microsoft/TokenEconomizer) is an experience-driven, black-box cost-control plugin for coding agents (Claude Code, Codex, GitHub Copilot CLI, Pi; experimental opencode and Cursor Agent). It learns from an agent's earlier sessions **in the same repository** and does not change the agent's model or code. This page summarizes its published design in our own words. ## Three mechanisms | Mechanism | What it does | Defaults reported | |-----------|--------------|-------------------| | **Micro-skills** | Learns repo facts (command spellings, env vars, build order, file locations) from repeated failures and from a model that reviews recent sessions; states a fact at session start once confirmed, drops it if contradicted | Review every *k* = 3 sessions; confirm after 3 sessions | | **Tool pruning** | Leaves out tool definitions unused over *p* prompts across ≥ *m* sessions, or over *s* sessions, via the agent's own settings; one command restores them | *p* = 10, *m* = 2, *s* = 5 | | **Failure-loop intervention (loop guard)** | A judge model checks a stuck turn; if ≥ *c* sure, injects one redirect; if still stuck, tells the user how to stop — never stops a turn itself | *c* = 0.7, *r* = 1 redirect per turn |
Repo facts
Micro-skills
Tool selection
Pruning
Failure handling
Loop guard
Three black-box mechanisms of TokenEconomizer. The authors report 18.4–30.9% lower mean cost across five SWE-Bench agent–model pairs. This is not independently reproduced here; see the paper and quality results below.
TokenEconomizer demonstration of its cost-control workflow Overview of the TokenEconomizer cost-control framework
Official project visuals. Source: microsoft/TokenEconomizer (Apache 2.0); Experience-Driven Black-Box Cost Control for Coding Agents (arXiv:2610.22732).
## Reported results On 277 SWE-Bench tasks across six repositories and five agent–model combinations, the authors report **18.4–30.9% lower mean cost**, cheaper in all 30 repository × combination cells, with Pass@1 higher in 4 of 5 combinations. Costs include every model call TokenEconomizer itself makes. See the [paper](https://arxiv.org/abs/2610.22732) and [project page](https://tokeneconomizer.github.io) for details. ## Mapping to this guide | TokenEconomizer | Waste category ([stage 2](../02-isolate/)) | Fix ([stage 4](../04-improve/)) | |-----------------|--------------------------------------------|---------------------------------| | Micro-skills | Re-learning repo facts | Short confirmed facts at session start | | Tool pruning | Unused tools | Prune tool definitions | | Loop guard | Failure loops | One redirect, then surface to the user | Design lessons worth copying: act through the agent's **own settings**; require **confirmation** before stating a learned fact; **cap** interventions; **include the optimizer's own cost** in the accounting; **fail open** (if the optimizer fails, the session continues as if it were not installed). ## Recommended adoption order for your own agent 1. **Failure-loop guard:** detect repeated errors within the current turn, redirect once, and surface persistent failure. This does not require cross-session training state and can limit costly tail runs. 2. **Unused-tool pruning:** start with a manually reviewed, task-scoped tool set; it also needs no cross-session training state and can cut repeated schema overhead. Keep an escape hatch for rare tools. TokenEconomizer's *automatic* pruning uses usage across sessions, as shown above. 3. **Repo micro-skills:** once session logs accumulate, confirm recurring facts before injecting short, reversible guidance at session start. This is a practical starting order, not a guarantee that these are the largest savings for every agent. Measure each change separately against cost and task success; prioritize the largest observed waste instead when your baseline points elsewhere. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) — NeurIPS 2024, 2,357 citations. Shows that interface design, including concise and bounded observations, changes agent success. - [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) — ICML 2024, 451 citations. Agents induce reusable workflows from past trajectories and reuse them, similar in spirit to micro-skills. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — preprint 2025, 41 citations. Retrieves only the relevant MCP tool descriptions instead of loading every tool (prompt bloat). - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) — preprint 2026, 36 citations. Repository context files did not generally improve task success and raised inference cost by over 20% on average. - [TokenEconomizer: Experience-Driven Black-Box Cost Control for Coding Agents](https://arxiv.org/abs/2610.22732) — preprint 2026, 0 citations. Micro-skills, tool pruning, and a loop guard cut coding-agent cost using experience from earlier sessions. --- ## Agent Tokenomics (Token Economics) (agent-tokenomics/index.md) Canonical URL: > LLM agent tokenomics and token economics troubleshooting guide: Diagnose, Isolate, Prove, Improve, and verify quality with tokprof and golden datasets. Track B covers **Agent Tokenomics (LLM token economics)** for engineers who **build or operate** LLM agents. Treat high token cost like a production incident: do not guess, follow a procedure. New here? Start with [0. Concepts](00-concepts/) — how an agent spends tokens — then follow the procedure: ```text Diagnose → Isolate → Prove → Improve → Result └────────── repeat with the next biggest cause ──────────┘ ``` | Stage | Question | Output | |-------|----------|--------| | [0. Concepts](00-concepts/) | How does an agent spend tokens? | A shared mental model | | [1. Diagnose](01-diagnose/) | Where do tokens go today? | A measured baseline | | [2. Isolate](02-isolate/) | Which cause is responsible? | One ranked hypothesis | | [3. Prove](03-prove/) | Is that cause real and how big? | A reproduced, quantified waste | | [4. Improve](04-improve/) | What targeted fix removes it? | One change, one experiment | | [5. Result](05-result/) | Did cost fall without hurting quality? | Keep / revert decision | | [6. Golden dataset and rubric evaluation](06-golden-dataset-and-rubric/) | How do you grade single-turn and multi-turn quality (keywords + intent)? | Excel (CSV) dataset & hybrid rubric | Plus [tokprof: Install & Usage](tokprof/), a [case study of TokenEconomizer](case-tokeneconomizer/), the [ranked paper list](../papers/) behind the fixes, and a runnable [measurement script](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples).
An agent repeatedly uses tools and their results to advance a task
The agent loop: instructions, tools, conversation history, and tool results shape successive calls. Stages 0–5 diagnose and optimize their cost. Sources: VS Code Docs — Agents Overview and microsoft/TokenEconomizer.
## What you need - A **request log**: one record per model call with input / cached / output tokens, tool definitions sent, tool calls and errors, and which user prompt (turn) and session it belongs to. Most agent frameworks can emit this; otherwise wrap your model client. - A **task set** you can re-run (5–20 representative tasks) with an automatic success check. - Discipline: change one variable at a time. ## Rule zero A token reduction is only a win if **task success does not drop**. Always report cost *and* a quality metric. --- ## tokprof: Install & Usage (agent-tokenomics/tokprof.md) Canonical URL: > Install tokprof from PyPI and profile LLM agent token usage per session, turn, and call without changing agent code. [`tokprof`](https://pypi.org/project/tokprof/) is a standalone native Rust single-binary profiler that decomposes the **input tokens of every LLM call** into system prompt, conversation history, current user prompt, and tool-related content (definitions, calls, results, response schemas) — without modifying agent code and without adding dependencies to your agent's project. ## 1. Install `tokprof` is published on [PyPI](https://pypi.org/project/tokprof/) with prebuilt native wheels for Linux (`x86_64`, `aarch64`), macOS (`arm64`, `x86_64`), and Windows (`x64`). You do **not** need a Rust or Go toolchain installed. ```bash # Install globally as an isolated CLI tool (recommended) uv tool install tokprof # or pipx install tokprof # Or install with pip in any Python environment pip install tokprof # Or run immediately without installing uvx tokprof --help ``` ### Prebuilt platform packages | Platform | Wheel / Package | Included binaries | |----------|-----------------|-------------------| | Linux `x86_64` & `aarch64` | `manylinux2014` wheel | `tokprof` + static `tokprof-ebpf` helper | | macOS Apple Silicon (`arm64`) & Intel (`x86_64`) | `macosx` wheel | `tokprof` | | Windows `x64` (`amd64`) | `win_amd64` wheel | `tokprof.exe` | | Source distribution (`sdist`) / Cargo | `tokprof-*.tar.gz` | Builds from Rust source (`cargo install --path ./profiler`) | Verify your installation and check which capture modes your machine supports: ```bash tokprof --version tokprof doctor # checks tokenizers, Linux eBPF kernel BTF/uprobes, mitmproxy, and Node tokprof selftest # runs a local mock LLM through the full capture & decomposition pipeline ``` For full CLI help and examples in English or Korean: ```bash tokprof --help # English (default) tokprof --lang ko # Korean (한국어 상세 도움말 및 예시) ``` --- ## 2. Quick start workflows ### Workflow A — Profile already-running services & Docker containers (`start` / `status` / `stop`) On Linux, `tokprof start` starts a background session and automatically attaches the eBPF probe to running host processes and Docker containers (when root or passwordless `sudo` is available): ```bash # 1. Start background profiling (or filter with: tokprof start --comm my_agent) tokprof start # 2. Trigger the agent workflow, API endpoint, or test you want to measure pytest tests/test_agent.py # 3. Check captured call count while the session is active tokprof status # 4. Stop the session, print the terminal breakdown, and write .tokprof/latest.html tokprof stop ``` > **Tip (non-Linux or without root/eBPF):** When eBPF is unavailable, `tokprof start` prints `eval "$(tokprof env)"`. Run that in the terminal where you launch your agent so child processes route through the local gateway. ### Workflow B — Profile a single command in one step (`tokprof -- `) On Linux, macOS, and Windows, pass any command after `--` to run it through the local gateway and in-process hooks, print the visual report on exit, and generate `.tokprof/latest.html`: ```bash tokprof -- python my_agent.py tokprof -- pytest tests/ tokprof -- node agent.js ``` ### Workflow C — Interactive subshell (`tokprof shell`) Open a subshell where every command you run is profiled into one session: ```bash tokprof shell # run multiple agent commands inside the subshell, then exit: exit ``` --- ## 3. Capture modes | Mode | Command | OS | Requires restart? | How it works | |------|---------|----|-------------------|--------------| | **Gateway + In-process hooks** | `tokprof -- `
`tokprof run -- `
`tokprof shell` | Linux, macOS, Windows | Yes (starts child process) | Routes `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `AZURE_OPENAI_ENDPOINT`, and pattern-matched `*_BASE_URL` / `*_ENDPOINT` variables through `127.0.0.1`, plus Python (`httpx`, `requests`, `urllib3`, `aiohttp`, `urllib.request`) and Node (`fetch`, `http`, `https`) hooks for clients that hard-code URLs. | | **Linux eBPF tap** | `tokprof start`
`tokprof ebpf --comm `
`tokprof ebpf --pid ` | Linux (x86_64, ARM64) | **No** (attaches live) | Attaches uprobes to OpenSSL and Go `crypto/tls` plus syscall tracepoints for plain `http://` / `h2c` across host processes and Docker containers. Requires root or `CAP_BPF`. | | **mitmproxy capture** | `tokprof mitm --local ` | Windows, macOS, Linux | **No** (in `--local` mode) | Uses `mitmdump` with `tokprof`'s addon script. Run `tokprof mitm --trust-help` for per-process CA trust instructions. | | **Azure Application Insights / Log Analytics** | `tokprof pull --workspace `
`tokprof pull --app-insights `
`tokprof import ` | Any OS & **Azure Cloud Shell** | **No** (reads telemetry) | Queries `AppDependencies` + `AppTraces` (OpenTelemetry GenAI, OpenInference, APIM, or `[TOKPROF_CHUNK]` logs), reassembles prompts/tools, and runs full 7-segment attribution or usage-only fallback. | --- ## 4. Reports, HTML dashboard, CSV, and before/after comparison Every completed session writes a timestamped JSONL recording and updates `.tokprof/latest.html` (and `.tokprof/latest.csv` when requested). ```bash # Pretty terminal breakdown of the most recent run in .tokprof/ tokprof report # Print full, untruncated prompt and response texts in the terminal tokprof report --full-prompts # Generate the self-contained HTML dashboard (.tokprof/latest.html) and open it tokprof report --html --open # Export per-session, per-turn, and per-call breakdown + prompt texts to CSV tokprof report --format csv --out run.csv tokprof report --csv # Live-refreshing terminal dashboard while an agent is running tokprof report --watch # Add cost estimates using your own per-1M-token price table tokprof report --prices prices.json # Compare two runs with a 95% bootstrap confidence interval (Stages 3 & 5) tokprof compare before.jsonl after.jsonl ``` ### What the HTML and CLI reports show 1. **Input token breakdown (total):** System prompt (split by markdown headings and XML tags), tool definitions, tool results, tool calls, conversation history (user and assistant turns), current user prompt (including structured JSON payloads with `utterance`, `context`/`history`, and `capabilities`), response schema, and unattributed template overhead. 2. **Per-Session & Per-Turn lineage:** How fixed prefix tokens, history accumulation, cache hits, and fan-out (`calls/turn`) evolve across turns. 3. **Call & Turn Prompt Dossier:** Inspect the exact secret-redacted system prompt, history messages, user prompt, tool schemas, and assistant output for each turn and individual call. 4. **Automated diagnostic findings:** Flags unused tool definitions, repeated identical tool calls or HTTP failure loops, prompt cache-busting (dynamic values in the system prompt), and steep history growth, linking each finding to the matching Track B stage. --- ## 5. Private / on-prem endpoints and privacy ### Private DNS, vLLM, Ollama, TGI, LiteLLM, and custom CAs `tokprof` scores request body shapes, URL paths, host/port hints, and response usage fields rather than matching a hardcoded domain list. ```bash # Check why a specific URL and request body is (or is not) classified as an LLM call tokprof explain http://vllm.internal:8000/v1/chat/completions --body request.json # Force or exclude specific hosts/paths and trust an internal CA certificate tokprof start --llm-host 'gpu*.corp' --llm-path '/internal/ask$' --upstream-ca corp-ca.pem tokprof run --exclude-host telemetry.corp -- python my_agent.py ``` ### Privacy & redaction - **Never recorded:** HTTP headers (`Authorization`, `x-api-key`) or API keys. - **File permissions:** All `.tokprof/` files are written with mode `0600`. - **Omit prompt text:** Pass `--no-content` (`tokprof start --no-content` or `tokprof run --no-content -- ...`) to record only token counts, byte lengths, and salted SHA-256 hashes without storing prompt or response text. --- ## 6. Profiling agents already deployed on Azure (Cloud Shell & Application Insights) When an agent is already running on Azure, host-level eBPF (`CAP_BPF`) is only available on Linux VMs and privileged AKS nodes. For managed PaaS and serverless services, `tokprof` provides `tokprof pull`, `tokprof import`, and a lossless chunked log bridge. ### Feasibility matrix by Azure hosting target | Azure hosting target | `tokprof ebpf` | `tokprof run` / hooks | `tokprof pull` / `import` (App Insights) | Recommended method | |----------------------|----------------|-----------------------|------------------------------------------|--------------------| | **Azure VM / VMSS (Linux)** | **Yes** | **Yes** | **Yes** | SSH/Bastion + `sudo tokprof start` (zero restart) | | **AKS (Kubernetes)** | **Conditional** (needs `CAP_BPF` + `/sys/kernel/btf`) | **Yes** | **Yes** | Privileged debug container/DaemonSet, sidecar gateway, or `tokprof pull` | | **Azure App Service / Container Apps (ACA)** | **No** (sandboxed kernel) | **Yes** (startup command or `PYTHONPATH` / `NODE_OPTIONS`) | **Yes** | `tokprof pull` from Application Insights, or `TOKPROF_STDOUT_LOG=1` hook | | **Azure Functions** | **No** | **Hooks only** (`PYTHONPATH` / `NODE_OPTIONS`) | **Yes** | `tokprof pull` from Application Insights or `TOKPROF_STDOUT_LOG=1` | | **Azure AI Foundry Hosted Agent** | **No** (managed runtime) | **No** | **Yes** | `tokprof pull` against the Foundry project's Application Insights / Log Analytics workspace | ### Running `tokprof` in Azure Cloud Shell Because `tokprof` ships as a static `manylinux2014_x86_64` binary wheel on PyPI, it installs in Azure Cloud Shell in seconds without a Rust or Go toolchain and persists across sessions in `$HOME`: ```bash # Install in Azure Cloud Shell pip install --user tokprof export PATH="$HOME/.local/bin:$PATH" # Pull the last 6 hours of LLM calls from Log Analytics or Application Insights # (uses your active Cloud Shell `az` login automatically) tokprof pull --workspace --since 6h tokprof pull --app-insights --since 2h --conv # Print the underlying KQL query to run in Azure Portal Logs tokprof pull --print-kql --since 24h # Import an exported JSON, NDJSON, or container log file offline tokprof import appinsights_export.json --report ``` When `tokprof` detects Azure Cloud Shell (`CLOUD_SHELL=true` or `ACC_CLOUD`), its HTML report server automatically binds to Cloud Shell Web Preview ports (`8080`, `8000–8090`, or `8888`) instead of `18765`, and prints instructions to open **[Web Preview] → [Configure] → Port 8080** or run `download .tokprof/latest.html`. ### Application Insights collection tiers & lossless bridge | Telemetry mode | Segment breakdown (`system`, `tool_def`, `history_*`, `user_prompt`) | How to enable | |----------------|----------------------------------------------------------------------|---------------| | **Tier 1 — Full OTel GenAI Content Recording** | **Yes (7 segments + `sysfp`)** | Set `AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=true` or `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true` on the agent so `AppTraces` records `gen_ai.*.message` and `gen_ai.choice` events. | | **Tier 2 — Usage-Only Fallback (default OTel)** | **No (totals, cost, latency, and turn curve only)** | Works with default `gen_ai.usage.*` attributes; `tokprof` marks calls as `usage_only` and adds a diagnostic banner explaining how to enable content recording. | | **Tier 3 — Lossless Chunked Bridge (>32 KB prompts)** | **Yes (100% lossless, bypasses 32 KB App Insights limit)** | Set `TOKPROF_STDOUT_LOG=1` with `tokprof`'s Python/Node hooks (`PYTHONPATH` / `NODE_OPTIONS`). Hooks emit gzip+base64 `[TOKPROF_CHUNK]` lines (20 KB each) to container logs, which `tokprof pull` / `import` reassembles automatically. | ### Production operational safeguards: RBAC, LAW ingestion lag, and Cloud Shell 30m timeout | Operational issue | Built-in `tokprof` safeguard | CLI flag / usage | |-------------------|------------------------------|------------------| | **No workspace RBAC (resource-only permission)** | Resource-centric query via `/v1/subscriptions/.../query` when the user only has `Monitoring Reader` on the Application Insights resource | `tokprof pull --resource-id /subscriptions//.../components/` | | **Table-level RBAC blocking `AppTraces`** | Automatically detects `InsufficientAccessError` / `403` on `AppTraces` and falls back to an `AppDependencies`-only query (`usage_only` mode) | Automatic on `tokprof pull` | | **Subscription / tenant mismatch or missing RBAC** | Classifies `401` / `403` / `404` (`InvalidAuthenticationTokenTenant`, `InsufficientAccessError`) and prints exact `az account set` / `az role assignment create` commands | Automatic on `tokprof pull` | | **Log Analytics ingestion latency (2–15m) & split arrival** | Tracks `IngestionTime - TimeGenerated` lag, polls until late `AppTraces` events arrive, and upgrades `usage_only` spans to full 7-segment `tier1_full` in-place | `tokprof pull --workspace --wait-ingest 5m --poll-interval 15s` | | **Azure Cloud Shell 20–30m session timeout** | Persists `.tokprof/pull-checkpoint.json` and recordings under `~/clouddrive/.tokprof` (Azure Files mount), caps waits at 25m, and resumes cleanly after disconnect | `tokprof pull --resume` | | **HTTP 429 rate limiting & Sovereign Clouds** | Exponential backoff honoring `Retry-After` / `x-ms-retry-after-ms`, plus Sovereign Cloud endpoints (`api.loganalytics.us`, `api.loganalytics.azure.cn`) | `tokprof pull --cloud {public,usgov,china}` | | **Multi-replica duplicate spans & Azure secrets** | Deduplicates spans by `(OperationId, SpanId)` across replicas/retries and redacts Azure `AccountKey=`, `SharedAccessKey=`, and SAS `sig=` tokens | Automatic | #### Step-by-step production examples (RBAC, LAW latency, Cloud Shell timeout, Portal CSV) ```bash # 1) Resource-centric RBAC: when you have Monitoring Reader on the App Insights resource # but NO permission on the shared Log Analytics Workspace tokprof pull \ --resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-agent/providers/Microsoft.Insights/components/my-agent-ai \ --since 6h # 2) Log Analytics ingestion latency (2–15m): poll until delayed AppTraces message events arrive # and automatically upgrade usage-only spans to full 7-segment breakdowns in-place tokprof pull --workspace --since 30m --wait-ingest 5m --poll-interval 15s # 3) Azure Cloud Shell 30m session timeout recovery: resume from ~/clouddrive/.tokprof/pull-checkpoint.json # using an incremental KQL timestamp watermark tokprof pull --resume # 4) Offline import from an Azure Portal CSV export (when CLI token access is blocked by Conditional Access) tokprof import portal_query_export.csv --out .tokprof/portal.jsonl --report # 5) Sovereign Cloud (Azure US Government or Azure China) tokprof pull --workspace --cloud usgov --since 24h ``` ### Handling oversized logs, controlling prompt inclusion, and verifying output #### What happens when logs or prompts are very large? `tokprof` applies four layered safeguards so oversized prompts or multi-hundred-thousand-row workspaces never break token attribution: | Layer | Limit / Threshold | Behavior when exceeded | Impact on token counts & hashes | |-------|-------------------|------------------------|---------------------------------| | **1. Gateway & Hook Capture** | Gateway: **64 MB** (`MAX_BODY`)
Python/Node hooks: **32 MB** (`_CAP`) | Captures full request and streaming SSE response bodies up to 32–64 MB without dropping frames. | **100% exact** | | **2. Per-Segment Stored Preview Cap** | **32,768 chars** per segment (`MAX_SEGMENT_TEXT_CHARS`) | Token count (`tokens`), character length (`chars`), and salted SHA-256 fingerprint (`hash`) are computed on the **entire original text first** before capping the stored preview string (`text`) at 32,768 chars with `... [truncated, N chars total]`. | **100% exact** (tokenization happens before preview truncation) | | **3. App Insights 32 KB Property Limit** | **32 KB (32,768 B)** per `Properties` / `Message` column | • Single-pass `parse_or_repair_json` repairs JSON cut off mid-string/object and marks `... [truncated by App Insights]`.
• Setting `TOKPROF_STDOUT_LOG=1` enables the gzip+base64 `[TOKPROF_CHUNK]` bridge (20 KB per line), recovering **100 KB+ prompts with 0% loss**. | Unrepaired tail is attributed to `residual`; **100% exact** with chunk bridge | | **4. Log Analytics Query Result Limit** | **500,000 rows** or **64 MB** (`ResponsePayloadTooLarge`) | • Requests `Accept-Encoding: gzip, deflate, br` (reducing transfer size by ~97.7%).
• On `ResponsePayloadTooLarge`, automatically retries with `\| take 20000` and falls back to `AppDependencies`-only.
• Supports explicit `--limit ` and `--usage-only`. | Safe fallback prevents query failure | #### Three modes for including or excluding prompts You can choose whether prompt/response texts are fetched and stored at collection time (`pull` / `start` / `run`), import time (`import`), or report time (`report`): | Mode | CLI flag / Env var | Prompt text stored on disk? | 7-segment breakdown & `sysfp` hash? | Measured artifact size (200 calls / 1,400 segments) | |------|--------------------|-----------------------------|-------------------------------------|-----------------------------------------------------| | **1. Full Prompts (`full-prompts`)** | *(default)*
Terminal untruncated view: `--full-prompts` | **Yes** (secrets auto-redacted) | **Yes (7 segments + `sysfp`)** | JSONL: `1.50 MB`
HTML: `1.90 MB`
CSV: `1.17 MB` | | **2. Segment Counts Only (`no-content`)** | `--no-content` or `TOKPROF_NO_CONTENT=1` | **No (`0 chars`)** | **Yes (100% identical tokens & `sysfp` hashes)** | JSONL: `384 KB` (**-74.4%**)
HTML: `245 KB` (**-87.1%**)
CSV: `25.6 KB` (**-97.8%**) | | **3. Totals Only (`usage-only`)** | `tokprof pull --usage-only`
`tokprof import --usage-only` | **No (`0 chars`, `AppTraces` not queried)** | **No** (total input/output, cost, latency, and turn curve only) | JSONL: `138 KB` (**-90.8%**)
HTML: `186 KB` (**-90.2%**)
CSV: `27.8 KB` (**-97.6%**) | ```bash # Mode 1: Keep redacted prompt & response texts (default) and inspect full text in terminal tokprof pull --workspace --since 6h tokprof report --full-prompts # Mode 2: Compute full 7-segment token breakdown & cache hashes, but omit all prompt/response text tokprof pull --workspace --since 6h --no-content tokprof import appinsights_export.json --no-content --out .tokprof/no-content.jsonl # Strip prompt texts from an ALREADY recorded full JSONL file when generating shareable HTML/CSV/JSONL tokprof report .tokprof/full.jsonl --no-content --html shareable.html --csv shareable.csv tokprof import .tokprof/full.jsonl --no-content --out .tokprof/stripped.jsonl # Mode 3: Skip AppTraces completely on huge workspaces (query only AppDependencies token totals + row cap) tokprof pull --workspace --since 7d --usage-only --limit 50000 ``` #### How to verify whether prompts were included, omitted, or truncated 1. **Automatic `content verification` summary on `stderr`:** Every `tokprof pull` and `tokprof import` run inspects the resulting records and prints an exact verification line: ```text # Default (full-prompts): tokprof: content verification — mode=full-prompts, segments_with_text=1400/1400, stored_prompt_chars=1000580, stored_response_chars=74890, 32k_preview_capped=0, appinsights_32kb_repaired=0 # With --no-content (proves 0 prompt/response chars are stored while all 1,400 segments are preserved): tokprof: content verification — mode=no-content, segments_with_text=0/1400, stored_prompt_chars=0, stored_response_chars=0, 32k_preview_capped=0, appinsights_32kb_repaired=0 # With --usage-only: tokprof: content verification — mode=usage-only, segments_with_text=0/0, stored_prompt_chars=0, stored_response_chars=0, 32k_preview_capped=0, appinsights_32kb_repaired=0 ``` 2. **Direct JSONL audit with `jq`:** Run this one-liner against any `.tokprof/*.jsonl` file to verify that no prompt text (`text` / `response_text`) exists or to count 32 KB truncations: ```bash jq -s '{ calls: length, total_segments: ([.[].segments | length] | add), segments_with_text: ([.[].segments[] | select(.text != null)] | length), responses_with_text: ([.[] | select(.response_text != null)] | length), appinsights_32kb_repaired: ([.[] | select(.detect.truncated_repaired == true)] | length), preview_32k_capped: ([.[].segments[] | select(.text != null and (.text | contains("[truncated,")))] | length) }' .tokprof/no-content.jsonl ``` --- ## 7. CLI command reference | Command | Description | |---------|-------------| | `tokprof start [--comm NAME] [--no-content]` | Start a background profiling session (auto-attaches eBPF on Linux). | | `tokprof status` | Show the active background session and recorded LLM call count. | | `tokprof stop` | Stop the active session, print the terminal report, and write `.tokprof/latest.html`. | | `tokprof -- [args...]` | Profile a single command and write the terminal + HTML report. | | `tokprof profile [--comm NAME \| -- ]` | Foreground profiling of running processes or a child command. | | `tokprof report [FILE] [--format FMT] [--html] [--csv]` | Render a recorded JSONL run (`pretty`, `text`, `html`, `csv`, `md`, `json`). | | `tokprof compare ` | Compare two runs with a 95% bootstrap confidence interval. | | `tokprof run -- [args...]` | Run a command through the local gateway and in-process hooks. | | `tokprof shell` | Open an interactive shell where child processes are profiled. | | `tokprof ebpf (--pid PID \| --comm NAME \| --all)` | Attach Linux eBPF probes to already-running processes. | | `tokprof mitm [--local PROC \| --trust-help]` | Capture traffic via `mitmproxy` on Windows, macOS, or Linux. | | `tokprof pull (--workspace ID \| --app-insights ID \| --resource-id ARM_ID) [flags]` | Pull and decompose LLM calls from Azure Application Insights / Log Analytics (`--since`, `--wait-ingest`, `--resume`, `--no-content`, `--usage-only`, `--limit`, `--cloud`). | | `tokprof import [--no-content] [--usage-only] [--report]` | Convert exported App Insights JSON/CSV, OTel GenAI, APIM, or `[TOKPROF_CHUNK]` logs into JSONL. | | `tokprof explain [--body FILE]` | Explain how a URL and request body are scored for LLM detection. | | `tokprof export --out ` | Convert a recording to the compact `examples/token_report.py` schema. | | `tokprof doctor` | Check local tokenizers, kernel eBPF support, and helper binaries. | | `tokprof selftest` | Run an end-to-end self-test against a local mock LLM server. | ## Sources - PyPI package: [`tokprof` on PyPI](https://pypi.org/project/tokprof/) (verified 2026-11-06) - Source code & architecture: [`profiler/` in `dotnetpower/agent-tokenomics`](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler) --- ## How Copilot usage is charged (copilot-tokenomics/01-how-usage-is-charged.md) Canonical URL: > Copilot tokenomics & token economics billing guide: understand GitHub AI Credits (input, cached, output token rates) vs. legacy Premium Request multipliers. ## Problem You cannot reduce what you do not understand. Two billing models exist today, and they reward different habits. ## What changed - **Usage-based billing (current).** GitHub announced that from **June 1, 2026**, Copilot usage consumes **GitHub AI Credits**. Credits are consumed at different rates depending on the **model** and the **number of tokens processed**. Each plan includes a monthly allowance. - **Legacy premium-request billing.** Some Pro / Pro+ subscribers on an existing annual plan stayed on request-based billing. There, each prompt in chat counts as one premium request multiplied by the model's rate, and autonomous tool calls inside an agent run do not count separately. | | Usage-based (AI credits) | Legacy (premium requests) | |---|---|---| | Unit | Tokens × model rate | Prompts × model multiplier | | Long chat history | Costs more (re-sent as input) | Not billed per token | | Large tool catalog / instructions | Costs more (sent every request) | Not billed per token | | Strongest lever | Smaller context, right model | Fewer prompts, lower-multiplier model | Check which plan you are on in your GitHub Copilot billing settings before choosing tactics.
VS Code Copilot status dashboard displaying usage
Use the Copilot status dashboard to review usage. Source: VS Code Docs — Optimize AI credit usage in VS Code.
## Why tokens matter for every request Each request sends **input tokens** (system prompt, instructions, tool definitions, the whole conversation so far, attachments, tool results) and receives **output tokens** (including any reasoning). Input grows with every turn, so a long session pays for old context again and again. Providers can reuse an unchanged request prefix (**prompt caching**), which lowers cost and latency when the beginning of the request stays stable. ### Cached input and billing When a prefix cache hits, `cached_input_tokens` are charged at the model's discounted cache-read rate under AI Credits, rather than the uncached input rate. Under legacy premium-request billing, the prompt still consumes `1 × model multiplier` premium requests regardless of a cache hit; caching can still reduce latency and rate-limit pressure. Check the model picker hover for the applicable rates and Agent Debug Logs for the request's cache usage; verify billing details in your plan's usage report. ## Trade-offs Everything in this track trades *context* against *cost*. Removing context the model needs leads to retries and rework, which can cost more than it saves. ## Sources - [GitHub Copilot is moving to usage-based billing (GitHub Blog, 2026-04-27)](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/) - [Usage-based billing for individuals (GitHub Docs)](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals) - [Requests in GitHub Copilot — legacy (GitHub Docs)](https://docs.github.com/en/copilot/concepts/billing/copilot-requests) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) --- ## Measure your usage (copilot-tokenomics/02-measure-usage.md) Canonical URL: > Measure GitHub Copilot tokenomics and AI credit spend in VS Code using Agent Debug Logs, Cache Explorer, context window controls, and cctx usage telemetry. ## Problem "Copilot feels expensive" is not actionable. You need to know *which* session, request, or component costs the most. ## Actions 1. **Per request** — hover over a chat response to see the credits used by that turn. 2. **Per session** — hover over (or select) the **context window control** in the chat input. The popover shows total session cost in credits and cumulative context-window token usage. 3. **Per month** — open the **Copilot status dashboard** from the VS Code status bar to see the percentage of your monthly allowance used, with a link to usage details on GitHub. 4. **What is inside a session** — open **Agent Debug Logs** (the `...` menu in the Chat view → *Show Agent Debug Logs*). The **Summary** view shows aggregate token usage, tool calls, and duration; the **Logs** view shows individual requests, errors, and tool calls. 5. **Prompt caching** — use the **Cache Explorer** (Agent Debug Logs → Summary → *Cache Explorer*) when the Summary reports low cache reuse together with unexpected duration or input tokens. It diffs consecutive requests and shows the *first divergence* in the prompt signature (system instructions, tool definitions, messages). 6. **Personalized tips** — run `/chronicle:cost-tips` in a chat session for recommendations based on your recent activity. This requires a recent VS Code / Copilot Chat build with the Chronicle cost-tips participant enabled. If it is unavailable, use Agent Debug Logs → **Summary** and **Cache Explorer** directly. 7. **Model cost** — the model picker's hover shows cost per token type and a Low / Medium / High tier. 8. **Live retrieval & multi-session savings (`cctx`)** — if you install the [Code Context (`cctx`) VS Code extension](../cctx/) from the Marketplace (`dotnetpower.code-context-native`), hover over the `CCTX N` status bar badge or run `cctx usage --hours 24` in the terminal to see per-model token spend, prompt-cache hit rates, lookup latency, and estimated AIC/USD savings across recent sessions.
VS Code Agent Logs Summary view showing aggregate token usage and tool call counts VS Code Cache Explorer side-by-side comparison showing cached prefix tokens and the first divergence point
VS Code Agent Debug Logs Summary view (left) and Cache Explorer side-by-side prompt prefix comparison (right). Sources: VS Code Docs — Agent Debug View and Cache Explorer.
## How to verify Pick one representative task and run it twice with the same model. Record per-request credits, session total, and cache hit %. This is your baseline for every later change. For a before/after comparison, copy the request or session summary values into your baseline record, or select the session in Agent Debug Logs and use **Export** to save its OpenTelemetry JSON. Compare the two runs with the same task and model; review exports for sensitive content before sharing. ## Trade-offs and cautions - The Cache Explorer diff explains a reported cache metric; it does **not** prove how a provider processed or billed the request. Cache information may be absent for some models. - Do not remove necessary instructions or tools just to raise cache reuse. Quality comes first. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) — NeurIPS 2023, 1,783 citations. RadixAttention reuses KV cache across calls that share a prefix; foundation for prefix caching. - [Prompt Cache: Modular Attention Reuse for Low-Latency Inference](https://arxiv.org/abs/2311.04934) — MLSys 2023, 417 citations. Reuses precomputed attention states of recurring prompt modules to cut latency. - [Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks](https://arxiv.org/abs/2601.06007) — preprint 2026, 25 citations. Evaluates prompt caching on long-horizon agentic tasks. ## Sources - [Optimize AI credit usage in VS Code — Monitor and Inspect sections](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) - [Debug chat interactions](https://code.visualstudio.com/docs/agents/agent-troubleshooting/chat-debug-view) --- ## Keep context lean (copilot-tokenomics/03-context-hygiene.md) Canonical URL: > Reduce GitHub Copilot token usage with context hygiene: new chats per task, /fork, /compact, focused #file attachments, workspace exclusions, and cctx. ## Problem A conversation accumulates messages, tool outputs, and file contents. Every new request re-sends that history as input, so an unrelated old topic keeps costing tokens without improving answers. ### Context window and context rot The **context window** is the maximum the model can consider in one request (input and output share it). It is a hard limit *and* a soft one: models use information in the middle of long contexts less reliably than at the start or end ([Lost in the Middle](https://arxiv.org/abs/2307.03172)), so quality can degrade well before the window is full. Cost and quality both argue for **as little context as the task needs, but enough**.
VS Code Chat context window control showing token usage by category VS Code Chat context picker for adding relevant context
Monitor context usage (left) and add relevant context (right). Sources: VS Code Docs — Add context to chat and Optimize AI credit usage.
## Actions | Situation | Action | |-----------|--------| | Switching to an unrelated task | Start a **new chat session** (`Ctrl+N` / `⌘N`). | | Want to try an alternative or ask a side question | **Fork** the conversation (`/fork`, or hover a message → *Fork Conversation*) instead of re-explaining. | | Long session you still need | Run `/compact` (optionally `/compact focus on the API design decisions`) to summarize older turns. | | You know the relevant code | **#-mention** the file, folder, or symbol rather than letting the agent search broadly. | | You need codebase search | `#codebase` runs a search; it does **not** add the whole codebase to context. | | Repeated `grep` + `view` loops slow down tasks and bloat history | Install [Code Context (`cctx`)](../cctx/) from the VS Code Marketplace so Copilot uses single-call, block-clamped `#cctxNativeContext` lookups (`<8 KiB` inline budget; 15.20× faster warm retrieval and 24.7% faster task completion, as reported). | | Noisy search results (logs, build output, generated files) | Exclude them: `.gitignore` (index + agent search), `files.exclude` (hide entirely), `search.exclude` (hide from agent search only). | | Web reference | Use `#fetch` with a URL only when needed; fetched pages enter the context. | | Independent research | Delegate to a **subagent** so the exploration stays out of the main conversation. | Search-match snippets count toward the context window even when the agent never opens the file, so excluding noisy paths helps directly. ### Subagent delegation break-even rule A subagent keeps intermediate exploration out of the parent chat's context window, but its first turn has its own system-prompt and tool-schema prefix. As a practical heuristic, handle short lookups (up to 5 tool calls) directly; delegate broad or multi-file exploration when its intermediate results would otherwise bloat later parent turns. Measure both cost and task success: isolation is not free. ## How to verify Repeat the baseline task from [Measure your usage](../02-measure-usage/) after the change and compare session credits and the context-window token count. Confirm the answer quality is unchanged. ## Trade-offs - `/compact` is lossy: details you still need may be summarized away. Add focus instructions, and say what must survive (decisions, constraints, file paths, open items). - Compacting changes the start of the history, so the provider's prompt cache for that prefix is rebuilt. Compact once at a natural pause rather than repeatedly; for a short remaining task, finishing it is often cheaper. - If a long session is dominated by big tool results (file reads, command output), trimming those (or starting a new chat with a short hand-off note) usually helps more than summarizing the conversation. - Starting a new chat loses history; put durable facts into [custom instructions](../04-instructions-and-tools/) so you do not re-explain them. - Attach the **smallest set of authoritative context** that lets the task succeed — not everything available. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) — TACL 2023, 5,818 citations. Accuracy drops when the relevant information sits in the middle of a long input. - [Large Language Models Can Be Easily Distracted by Irrelevant Context](https://arxiv.org/abs/2302.00093) — ICML 2023, 1,358 citations. Irrelevant context in the prompt can substantially reduce model accuracy. - [LLMs Get Lost In Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) — ICLR 2025, 562 citations. Models perform worse in multi-turn, underspecified conversations than in single-turn ones. - [Same Task, More Tokens: the Impact of Input Length on the Reasoning Performance of Large Language Models](https://arxiv.org/abs/2402.14848) — ACL 2024, 270 citations. Isolates input length as a factor and shows reasoning degrades as inputs grow. - [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) — preprint 2025, 66 citations. Simple observation masking is as efficient as LLM summarization for agent context management. ## Sources - [Add context to chat](https://code.visualstudio.com/docs/chat/copilot-chat-context) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) --- ## Instructions and tools (copilot-tokenomics/04-instructions-and-tools.md) Canonical URL: > Cut recurring input token overhead in VS Code GitHub Copilot by trimming always-on custom instructions (copilot-instructions.md, AGENTS.md) and tool schemas. ## Problem Custom instructions and tool definitions included in a request add recurring input. Unused or bloated items are a fixed tax; some tool schemas can be loaded on demand (see [MCP audit](../09-mcp-audit/)).
Unscoped instructions + 40 tools
Fixed 82%
Task 18%
100%
applyTo scoped + pruned tools
Fixed 22%
Task 18%
40%
Synthetic illustration, not a measured result: against the original input, fixed overhead falls from 82% to 22%, and the task remains at 18%; the new total is 40% of the original. Scoping and pruning reduce fixed overhead while the task stays the same; actual savings vary. Colors distinguish configurations, not cache hits or misses.
VS Code chat customizations editor showing agent instruction settings
Manage agent customizations in VS Code. Source: VS Code Docs — Agent Customization Overview.
## Actions **Custom instructions** (`.github/copilot-instructions.md`, `*.instructions.md`, `AGENTS.md`) - Keep only *stable, high-value* facts: build/test commands that differ from defaults, required env vars, where generated files live, conventions the agent cannot infer. - Scope with `applyTo` in `*.instructions.md` so language- or folder-specific rules load only where they apply. Think in three tiers: **always-on** (few rules that apply every time), **conditional** (`applyTo` path rules), and **on-demand** (skills or notes for occasional workflows such as PR review). - Delete anything the agent can discover cheaply from the code. Do not paste long style guides. - Facts stated once in instructions save the agent from rediscovering them in every session. - Avoid duplicating rules across `copilot-instructions.md`, `AGENTS.md`, `CLAUDE.md`, and `*.instructions.md`. Applicable files can be injected together, duplicating fixed prefix tokens; keep one canonical source per scope and check what actually loaded. - Write the rules tersely (declarative rules, no filler); the file is re-sent on every request. - For tool-routing and fallback instructions, consider a **BPE-aligned formula layout** (`need => tool`, `condition -> action`, `>` priority chains; see [Prompt and output style](../06-prompt-and-output-style/#4-bpe-aligned-formula-notation)). As a VS Code reference case, converting the auto-loaded `.instructions.md` in [dotnetpower/code-context](https://github.com/dotnetpower/code-context) from 106-line prose (9,127 bytes, 2,048 `o200k_base` tokens) to a 26-line BPE-aligned formula specification (2,688 bytes, 718 tokens) cut per-turn instruction tokens by **64.9%** while retaining **100% (31/31)** rule-recognition accuracy across 12 edge-case scenarios. **Do not auto-generate and forget.** An ETH Zurich study of repository context files (arXiv 2602.11988) found that context files do not generally improve task success while increasing inference cost by over 20% on average; repository overviews were not helpful, while instructions for **non-standard practices** were followed. Treat the file like a bug tracker: add a line when the agent hits a real "landmine", delete lines the agent can learn from the code, and re-evaluate when the code changes. | Keep (landmines) | Delete (self-discoverable) | |------------------|----------------------------| | "Use `uv`, not `pip`" | "This is a Python project" | | "Run tests with `--no-cache`" | "Tests live in `tests/`" | | "Do not refactor `auth/` — audit pending" | "We use PostgreSQL" | | "Deploy requires VPN" | "Code quality matters" (empty advice) | **Tool catalog** - Use **Configure Tools** in the chat input to enable only the tools or MCP servers the current task needs. - In custom agents, set the `tools` property to a narrow, task-specific list. - Prefer one focused CLI (invoked through the terminal tool) over loading dozens of single-purpose MCP tools — if your organization can maintain and secure it. - Choose tools **before** starting a session: enabling an MCP server mid-session changes the tool definitions and can break prompt-cache reuse (visible as the first divergence in the Cache Explorer). **Batch deterministic loops** - For bulk or polling workflows, run a reviewed script via the terminal and give the model only the summary, rather than many tool calls whose outputs all land in context. ## How to verify In Agent Debug Logs, compare input tokens of the first request before and after trimming. Then run the baseline task and compare session credits. Re-check quality: did the agent start rediscovering things? ## Trade-offs - Over-pruned instructions cause repeated discovery; over-pruned tools cause failed or manual workarounds. - Benchmark scripted versus interactive versions — savings depend on the tools and results. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [Batch Prompting: Efficient Inference with Large Language Model APIs](https://arxiv.org/abs/2301.08721) — EMNLP 2023, 154 citations. Packs several samples into one prompt so instruction tokens are shared. - [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) — preprint 2025, 55 citations. Lets the agent request tools on demand instead of injecting all tool schemas. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — preprint 2025, 41 citations. Retrieves only the relevant MCP tool descriptions instead of loading every tool (prompt bloat). - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) — preprint 2026, 36 citations. Repository context files did not generally improve task success and raised inference cost by over 20% on average. ## Sources - [Optimize AI credit usage — Keep the tool catalog focused, Batch repetitive operations, Ground the agent](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents? (arXiv:2602.11988)](https://arxiv.org/abs/2602.11988) - [MCP audit](../09-mcp-audit/) for the deeper tool-catalog procedure --- ## Models, planning, delegation (copilot-tokenomics/05-models-and-planning.md) Canonical URL: > Optimize LLM token economics in VS Code Copilot: choose models by cost per completed task, plan before coding, and isolate exploration in subagents. ## Problem The cheapest model per token is not always the cheapest per *result*, and jumping straight to code with the wrong approach wastes whole sessions.
VS Code language model selection dropdown VS Code thinking effort submenu
Choose a model (left) and its thinking effort (right). Source: VS Code Docs — Language Models.
## Actions 1. **Choose models on evidence.** Define the expected result and how you will judge it; run each candidate more than once (output is nondeterministic); compare completion, quality, reliability, duration, and credits; pick the cheapest model that consistently meets the bar. Re-evaluate as models change. 2. **Low-maintenance default:** use **auto model selection**. For repeatable workflows, pin a model in a **custom agent**. 3. **Leave thinking effort at defaults.** Higher effort produces more thinking tokens (cost and latency). Raise it only for genuinely complex work such as architectural planning or multi-step debugging. 4. **Plan, then implement.** Use the Plan agent with a capable model, review the plan, split it into well-scoped tasks, and delegate those to **custom agents as subagents** with cheaper models, focused instructions, and minimal tools. The primary agent reviews results. ### Failure-retry paradox A simple approximation is `total cost = rate × calls × accumulated context` (where accumulated context is the average tokens per call). For a synthetic comparison, a model with one-third the token rate that makes four failed test-loop calls and then succeeds uses at least `1/3 × 5` of the frontier model's one-call cost if their average context is equal; growing tool outputs can increase it further. Real bills also distinguish input, cached input, and output rates. Compare models at the same task success and include retries, tool outputs, and any final successful run. ## How to verify For a recurring task type, compare (a) one strong model end-to-end against (b) plan with a strong model + workers on a cheaper one. Record credits, retries, and whether the result passes your acceptance check. ## Trade-offs - Delegation itself uses tokens. Keep small tasks in the main session if isolation and a cheaper model do not offset the orchestration overhead. - A cheaper model that needs retries or creates rework can cost more overall. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance](https://arxiv.org/abs/2305.05176) — TMLR 2023, 1,247 citations. Selects and cascades LLMs to approach a strong model's quality at lower cost. - [Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing](https://arxiv.org/abs/2404.14618) — ICLR 2024, 519 citations. A router predicts query difficulty and sends easy queries to a smaller model. - [AutoMix: Automatically Mixing Language Models](https://arxiv.org/abs/2310.12963) — NeurIPS 2023, 169 citations. Has a small model verify its own answer and escalates to a larger model only when needed. - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — ICLR 2025, 56 citations. Defines the expected cost to obtain a correct answer and compares models on it. - [RouteLLM: Learning to Route LLMs with Preference Data](https://arxiv.org/abs/2406.18665) — preprint 2024, 922 citations. Learns from preference data to route queries between a strong and a cheaper model. ## Sources - [Optimize AI credit usage — Choose models, Plan and delegate, Thinking effort](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [AI model comparison (GitHub Docs)](https://docs.github.com/en/copilot/reference/ai-models/model-comparison) --- ## Prompt and output style (copilot-tokenomics/06-prompt-and-output-style.md) Canonical URL: > Shorter prompts, structured requests, and capped output - the levers on both sides of the request. ## Problem You pay for the tokens you send **and** the tokens the model writes. Filler in a prompt is small; filler in every *answer* repeats on every request. Output tokens are also priced higher than input tokens on most models, so response length is often the best lever per minute of effort. (Check your model's rates in the GitHub Docs model pricing; the ratio differs by model.)
VS Code prompt file creation interface
Create a reusable prompt file. Source: VS Code Docs — Prompt Files.
## Actions ### 1. Cap the output (highest return) Add a standing rule to `copilot-instructions.md` and/or end a prompt with a format limit: | Instruction | Effect | |-------------|--------| | `Code only, no explanation.` | No prose around the change. Ask "why" explicitly when you need it. | | `Answer in one sentence.` | Limits verbosity. | | `3 bullet points max.` | Hard cap on items. | | `Yes or no, then one line why.` | Shortest useful answer. | | `Reply as JSON.` / `Table format.` | Structured output, no narrative. | A concise *prompt* does not make the *answer* concise. Set both. **Structured-output trade-off.** A `response_format` or strict JSON schema can simplify parsing, but forcing reasoning into a rigid format can reduce accuracy on multi-step tasks. [Let Me Speak Freely?](https://arxiv.org/abs/2408.02442) reports this effect for the models and tasks it evaluated, not every model or schema. If accuracy falls, allow brief reasoning before formatting or extract structured fields in a final step, then verify both schema validity and task success. Availability of these controls depends on the client and provider. ### 2. Trim the prompt - Drop politeness, hedging, and filler (`please`, `I think maybe`, `basically`). Keep technical terms, code, and concrete details exactly. - Prefer **structured** input (bullets, `key: value`) over prose paragraphs. - Prefer **declarative** rules over procedures: `All exported functions: JSDoc required.` instead of a step-by-step "first read the file, then find…". - Often the shortest accurate form is code-like: a type signature, pseudo-code, or "like `getUserById` but for emails. Return 404 if missing." - Use common abbreviations (`DB`, `auth`, `config`, `env`, `repo`) only if the model already knows them. Define project-specific abbreviations in your instructions first. - **One task per prompt.** A prompt that mixes refactor + tests + docs + security tends to do each part partially; split it, review each step, and redo only the step that failed. ### 3. Terse-style instructions Community "caveman" style skills compress both input and output with a short rule such as *drop articles and filler, fragments OK, code unchanged*. See [caveman](https://github.com/JuliusBrussee/caveman) and the [measured evaluation](https://github.com/danielle34/cavewoman). Compression levels trade clarity for tokens: heavier compression can make complex instructions ambiguous, so keep it light for customer-facing or onboarding text. ### 4. BPE-aligned formula notation When expressing routing rules, preconditions, or multi-step workflows, a **BPE-aligned ASCII formula** is shorter and less ambiguous than prose — but **Unicode math symbols (`∀`, `∈`, `∪`, `≻`, `∘`) are a trap**. In `o200k_base` and `cl100k_base`, multi-byte math symbols split into 2–3 tokens and prevent adjacent English words from merging with a leading space. Spaced ASCII operators (` ->`, ` =>`, ` >`, ` <=`, ` >=`, ` &`, ` |`) each encode as **1 token** including their leading space. Reproduced with [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py) (or `python3 examples/formula_prompt.py --lang en`, `tiktoken` 0.14.0, verified 2026-11-04): | Style | Text | Bytes | `o200k_base` | vs. Prose | `cl100k_base` | |-------|------|------:|-------------:|----------:|--------------:| | Prose (with backticks) | ``When you need to find a symbol or literal and read its surrounding lines, use `code_context` in one call instead of searching first and reading later.`` | 150 | 31 | 0.0% | 31 | | Unicode math (unspaced) | `∀x∈Sym∪Lit: need(x+ctx) ⇒ code_context(x) ≻ (grep(x) ∘ read(x))` | 75 | 30 | -3.2% | 31 | | ASCII formula (unspaced) | `δ(symbol\|literal+surrounding_lines)=>code_context(root,pattern,radius<=20)` | 75 | 20 | -35.5% | 20 | | **BPE-aligned formula (spaced)** | `symbol + context => code_context (1 call > grep + read)` | **55** | **14** | **-54.8%** | **14** | Rules for BPE-aligned formulas: - Use **spaced ASCII operators** (` ->`, ` =>`, ` >=`, ` <=`, ` !=`, ` &`, ` |`), not Unicode math (`∀`, `∈`, `≻`, `∘`). - Avoid wrapping every identifier in inline backticks (`` `name` `` adds 2 extra tokens per identifier). - Keep spaces around `+`, `|`, and `=>` so BPE tokenizers merge `" word"` into a single token instead of splitting after punctuation. Applied to 7 English customer-support SOP and live-chat responses from public Hugging Face datasets (`examples/formula_prompt_en.py`), BPE-aligned formulas reduce tokens by **75.9% on `o200k_base`** while preserving **43/43 (100%)** required slots and template placeholders (for Korean counseling and chat examples in `examples/formula_prompt_ko.py`, see [Language and tokenization](../07-language-and-tokenization/#hugging-face-customer-support-and-counseling-benchmark)): | English SOP / chat case & Hugging Face dataset (`row`) | Prose (`o200k` / `cl100k`) | BPE formula (`o200k` / `cl100k`) | `o200k_base` delta | `cl100k_base` delta | Slots kept | |--------------------------------------------------------|---------------------------:|---------------------------------:|-------------------:|--------------------:|-----------:| | Order cancel SOP ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[2]`) | 223 / 226 | 55 / 55 | **-75.3%** | **-75.7%** | 9/9 | | Order change SOP ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[1001]`) | 225 / 230 | 54 / 54 | **-76.0%** | **-76.5%** | 9/9 | | Cancellation fee check SOP ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[3001]`) | 98 / 100 | 26 / 27 | **-73.5%** | **-73.0%** | 5/5 | | Refund timeframe & lookup ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[6000]`) | 221 / 225 | 34 / 34 | **-84.6%** | **-84.9%** | 5/5 | | Recall return & refund SOP ([`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[1]`) | 131 / 131 | 42 / 42 | **-67.9%** | **-67.9%** | 6/6 | | Robotic arm recalibration chat ([`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) `train[0]`) | 60 / 61 | 18 / 18 | **-70.0%** | **-70.5%** | 5/5 | | Delayed order live-chat reply ([`Kaludi/Customer-Support-Responses`](https://huggingface.co/datasets/Kaludi/Customer-Support-Responses) `train[0]`) | 28 / 29 | 9 / 9 | **-67.9%** | **-69.0%** | 4/4 | | **Total (7 English SOP & live-chat cases)** | **986 / 1,002** | **238 / 239** | **-75.9%** | **-76.1%** | **43/43 (100%)** | ## How to verify Measure, do not assume. With the [token counter](../07-language-and-tokenization/) on the `o200k_base` encoding, one example prompt falls from 38 tokens to 11: ```text Hey, could you please help me refactor this function? I think it might have some issues with how it handles the authentication, and I'd really like it to be more efficient. Thanks! -> 38 tokens Refactor function. Fix auth handling. Make efficient. -> 11 tokens ``` Then compare **session credits** for a real task before and after, and check the output still meets your acceptance criteria. ## Trade-offs - Learning or debugging needs explanations: ask for them on demand (`Explain why this beats X`). - Over-compressed prompts lose constraints. Keep exact technical terms and concrete details. - The talk deck this page draws from reports large output savings for these instructions (tens of percent, higher for yes/no style). We could not reproduce those figures independently; treat them as directional and measure on your tasks. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression](https://arxiv.org/abs/2310.06839) — ACL 2023, 658 citations. Question-aware compression for long contexts, aiming to cut cost while keeping or improving accuracy. - [LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression](https://arxiv.org/abs/2403.12968) — ACL 2024, 487 citations. Distills a faster, task-agnostic prompt compressor that generalizes across tasks. - [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736) — EMNLP 2023, 418 citations. Uses a small language model to drop low-information tokens from a prompt, with a controllable budget. - [Compressing Context to Enhance Inference Efficiency of Large Language Models](https://arxiv.org/abs/2310.06201) — EMNLP 2023, 272 citations. Prunes redundant lexical units by self-information to shorten inputs before inference. - [Let Me Speak Freely? A Study On The Impact Of Format Restrictions On Large Language Model Performance.](https://arxiv.org/abs/2408.02442) — EMNLP 2024, 142 citations. Strict output-format restrictions can lower reasoning performance. - [Chain of Draft: Thinking Faster by Writing Less](https://arxiv.org/abs/2502.18600) — preprint 2025, 324 citations. Prompts the model to write minimal draft steps instead of verbose chain-of-thought. ## Sources - Token Efficiency and Context Engineering — developer talk deck (June 2026), prompt-compression and output-control sections (figures as reported, not independently verified) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py), [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) — reproducible English BPE formula measurement and prompt converter - [caveman](https://github.com/JuliusBrussee/caveman), [cavewoman](https://github.com/danielle34/cavewoman) --- ## Language and tokenization (copilot-tokenomics/07-language-and-tokenization.md) Canonical URL: > Why the same sentence costs different token counts in different languages, and what to do about it. ## Problem "Is it cheaper to write my prompts in my native language, or to translate them?" Token counts depend on the tokenizer, and tokenizers are trained mostly on English text. The same meaning usually needs **more tokens in non-English languages**, so the answer is rarely "native is cheaper". ## Measure it yourself [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py) counts one sentence ("I met a huge dog") in several languages with [tiktoken](https://github.com/openai/tiktoken). Results from our run (tiktoken 0.14.0, 2026-11-03): | Language | Characters | o200k_base tokens | × English | cl100k_base tokens | × English | |----------|-----------:|------------------:|----------:|-------------------:|----------:| | English | 16 | 5 | 1.0 | 5 | 1.0 | | Spanish | 24 | 7 | 1.4 | 8 | 1.6 | | Korean | 13 | 8 | 1.6 | 13 | 2.6 | | Chinese | 8 | 8 | 1.6 | 12 | 2.4 | | Japanese | 9 | 8 | 1.6 | 11 | 2.2 | | Russian | 26 | 7 | 1.4 | 14 | 2.8 | | Hebrew | 13 | 7 | 1.4 | 16 | 3.2 | Two lessons: 1. **Fewer characters does not mean fewer tokens.** Chinese, Japanese, and Korean use few characters, but each character can cost one or more tokens. 2. **The gap depends on the tokenizer.** Newer vocabularies (`o200k_base`) narrow it a lot compared with older ones (`cl100k_base`). Copilot can route to several providers, so run the script with an encoding close to your model, or use that provider's token-counting API for exact numbers. ## Actions - Write **instructions files and standing rules in English**. They are sent on every request, so a persistent multiplier there matters most. - **Do not translate a prompt just to save tokens** unless you measured it: translation can cost more than it saves and may change meaning. - **For non-English workflows (e.g. Korean), keep native domain nouns and replace grammatical endings with BPE formula operators.** In agglutinative languages such as Korean, polite verb endings, auxiliary verbs, and particles (`~을 완료할수 있도록`, `~에 대한 계획을 세워서`, `~한 다음`) account for a large share of tokens. Keeping the core Korean domain nouns and action stems intact while replacing connectors with spaced ASCII formula operators (` ->`, ` =>`, ` >=`, ` <=`, ` &`) and a `[ko]` reply-language tag cuts input tokens by **22–39% on `o200k_base`** (**31–49% on `cl100k_base`**) without losing domain precision or Korean replies. - Keep **code, identifiers, comments, and commit messages in English** regardless of the language you chat in. - Non-Latin text can sometimes be transliterated to Latin script for fewer tokens, but this hurts readability; measure before adopting it. - Ask the model to *reply* in the language you read best only when needed; replies are output tokens, which are priced higher. ### Hybrid Korean + BPE formula benchmark Measured with [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py) (or `python3 examples/formula_prompt.py --lang ko`, `tiktoken` 0.14.0, verified 2026-11-04): | Workflow pattern | Korean prose (`o200k` / `cl100k`) | Hybrid Korean + BPE formula (`[ko] :: ...`) | `o200k_base` delta | `cl100k_base` delta | |------------------|----------------------------------:|---------------------------------------------|-------------------:|--------------------:| | Issue completion pipeline | 44 / 72 | `[ko] :: #1945 남은작업 계획수립 -> 모두조치 -> push & merge -> 이슈닫기` | **27 (-38.6%)** | **37 (-48.6%)** | | Bulk gap discovery & loop | 46 / 74 | `[ko] :: 보강점 >=100 발굴 -> 모두조치 -> loop 10x -> 수치표 보고 -> commit & push & merge` | **31 (-32.6%)** | **38 (-48.6%)** | | Bounded hardening loop | 54 / 91 | `[ko] :: 모두적용 -> loop(비평 >=10 하드닝, until 심각도 <= Low) -> 개선점 >=100 발굴 -> 모두보강 -> push & merge -> 보고` | **42 (-22.2%)** | **57 (-37.4%)** | | Optimization audit & list | 31 / 51 | `[ko] :: 절감액 기반 최적화 >=30 발굴 -> 계획수립 -> 목록 보고` | **22 (-29.0%)** | **35 (-31.4%)** | | **Total (4 prompts)** | **175 / 288** | — | **122 (-30.3%)** | **167 (-42.0%)** | Why keep core Korean nouns instead of replacing everything with English shorthand? In an evaluation across 8 real Korean Copilot requests (47 constraint checkpoints), naive English keyword replacement (for example turning `"보강점 100개 이상 찾아서"` into `gaps >=100`) caused the model to misread imperative commands ("find at least 100 gaps") as conditional guards ("if gaps are at least 100"), dropping constraint accuracy to **81.5% (44/54)**. Keeping the Korean action noun (`보강점 >=100 발굴`) with BPE operators achieved **100.0% (47/47)** constraint accuracy and **100% Korean replies**. **Keep spaces before Korean nouns and strip decorative quotes/brackets.** In `o200k_base`, **643 multi-syllable Korean words** (including `" 고객"`, `" 담당"`, `" 주문"`, `" 완료"`, `" 직접"`, `" 처리"`, `" 확인"`, `" 전달"`, `" 안내"`, `" 기준"`) encode as **1 token only when preceded by a space**, and split into 2 tokens when glued into unspaced compounds (`직접처리` = 3 tokens vs `직접 처리` = 2 tokens; `주문완료` = 3 tokens vs `주문 완료` = 2 tokens) or wrapped in quotes/corner brackets (`'무선 이어폰'`, `‘무선 이어폰’`, `「근로기준법」`). ### Hugging Face customer-support and counseling benchmark The same Korean core-noun + BPE formula rule applies to Korean customer-support, delivery, legal, and labor counseling utterances where polite openings, apologies, and repetitive policy clauses dominate token count. Reproduced with [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py) and verified by [`examples/test_formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/test_formula_prompt.py) (`tiktoken` 0.14.0, verified 2026-11-04; for English SOP examples in `examples/formula_prompt_en.py`, see [Prompt and output style](../06-prompt-and-output-style/#4-bpe-aligned-formula-notation)): | Korean case & Hugging Face dataset (`row`) | Prose (`o200k` / `cl100k`) | BPE formula (`o200k` / `cl100k`) | `o200k_base` delta | `cl100k_base` delta | Slots kept | |--------------------------------------------|---------------------------:|---------------------------------:|-------------------:|--------------------:|-----------:| | E-commerce shipping & refund ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[5]`) | 103 / 158 | 64 / 94 | **-37.9%** | **-40.5%** | 11/11 | | Defect & receipt escalation ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[2]`) | 90 / 147 | 45 / 73 | **-50.0%** | **-50.3%** | 8/8 | | Return & exchange policy ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[6]`) | 101 / 173 | 59 / 99 | **-41.6%** | **-42.8%** | 9/9 | | Delivery checkout & ETA ([`jjun123/delivery-app-function-calling-datasets-korean`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) `train[0]`) | 173 / 229 | 127 / 162 | **-26.6%** | **-29.3%** | 11/11 | | Severance pay statute ([`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) `train[1]`) | 173 / 256 | 73 / 109 | **-57.8%** | **-57.4%** | 7/7 | | Minimum wage & 90% probation ([`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) `train[0]`) | 124 / 189 | 65 / 101 | **-47.6%** | **-46.6%** | 7/7 | | Average wage & floor rule ([`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) `train[2,3]`) | 104 / 177 | 65 / 113 | **-37.5%** | **-36.2%** | 6/6 | | Dismissal 30-day notice rule ([`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) `train[34]`) | 90 / 142 | 51 / 74 | **-43.3%** | **-47.9%** | 7/7 | | Parcel locker redirect chat ([`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[2]`) | 51 / 68 | 30 / 36 | **-41.2%** | **-47.1%** | 4/4 | | Mock clinic slot chat policy ([`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[11]`) | 91 / 164 | 42 / 68 | **-53.8%** | **-58.5%** | 7/7 | | **Total (10 Korean chat & counseling cases)** | **1,100 / 1,703** | **621 / 929** | **-43.5%** | **-45.4%** | **77/77 (100%)** | In the evaluated benchmarks, the hybrid approach preserved 47/47 constraint checkpoints across 8 Korean Copilot requests. A separate live benchmark of 330 Korean cases from 7 Hugging Face datasets retained 1,314/1,314 extracted strict slots, with no token expansion on the two tested tokenizers (see [the live benchmark](../../agent-tokenomics/04-improve/#compaction-without-losing-the-cache)). These are results on the tested sets, not guarantees of semantic accuracy or performance on arbitrary inputs. Verify slot preservation, task accuracy, and token counts on your own domain prompts. To reduce omissions, `examples/formula_prompt_ko.py` and `examples/formula_prompt_en.py` extract recognized patterns for statute references (`제N조`, `제N항`, `제N호`), supreme-court case ID (`98다46198`), email, phone number, kebab-case entity ID (`parcel-610`, `locker-16`), order/user/product ID, quantity, price, date, and template placeholder (`{{...}}`) before compression, restore any omitted token automatically (`ensure_slot_preservation`), and fall back to the original string whenever a compressed candidate does not strictly reduce `o200k_base` tokens. For multi-turn chat and counselor conversation history compaction and the 580-row live benchmark (`--compress-dialogue` and `--hf-live --hf-rows 50`), see [Track B — 4. Improve](../../agent-tokenomics/04-improve/#compaction-without-losing-the-cache). ## Trade-offs Clarity and correctness beat a small token saving. If you think more precisely in Korean (or any language), write that way for complex requirements and keep the *standing* files (instructions, tool descriptions) in English. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909) — ACL 2015, 9,243 citations. Introduced the subword (BPE) units that underlie most LLM tokenizers. - [Language Model Tokenizers Introduce Unfairness Between Languages](https://arxiv.org/abs/2305.15425) — NeurIPS 2023, 319 citations. The same text tokenizes to very different lengths across languages. - [Do All Languages Cost the Same? Tokenization in the Era of Commercial Language Models](https://arxiv.org/abs/2305.13707) — EMNLP 2023, 278 citations. Shows that tokenization differences make commercial API usage cost different amounts per language. ## Sources - [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py) — reproducible measurement - [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py), [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) — reproducible Korean + BPE formula measurement and converter - [tiktoken](https://github.com/openai/tiktoken) - Token Efficiency and Context Engineering — developer talk deck (June 2026): reports the same direction (non-English text costs more tokens) with a different tokenizer; our table is our own measurement. --- ## Agent modes and budget guards (copilot-tokenomics/08-agent-modes-and-budget.md) Canonical URL: > Ask vs Plan vs Agent, agent loop limits, reasoning effort, and cloud-agent setup. ## Problem An agent run is a **loop**: each step is a model call, and each call re-sends the instructions, tool definitions, and conversation so far. A vague prompt can trigger a long exploration that ends in a misunderstanding and a restart.
Agent Debug View flow chart showing model requests and tool calls VS Code custom agent creation interface
Inspect an agent run (left) and create a custom agent (right). Sources: Agent Debug View and Custom Agents.
## Actions ### Pick the cheapest mode that fits | Mode | Typical shape | Use for | |------|---------------|---------| | Ask | One model call | Questions, explanations, lookups | | Plan | One planning pass | Scoping a change before any code is written | | Agent | Many calls (tool loop) | Multi-file refactors, building a feature from scratch | Default to Ask for questions; use Plan to clarify scope; use Agent when the task genuinely needs tools. The expensive pattern is running Agent on an ambiguous prompt. ### Bound the loop - **`chat.agent.maxRequests`** — the maximum number of requests the agent can make in a run (default 25 in the VS Code settings reference we checked on 2026-11-03). Lower it if runaway loops worry you; raise it deliberately for known long tasks. - Give a **clear completion criterion** ("done = tests pass and lint is clean") so the agent stops exploring. - For complex work, have the agent write a **plan file** first and then execute it. - Name the tool to use when you know it ("use only the GitHub create-PR tool") to reduce tool searching. - Give **concrete context**: files, error text, constraints (see [Keep context lean](../03-context-hygiene/)). For Autopilot or a background agent, add an explicit loop guard to the task prompt: ```text Run focused tests first. If the same command or test fails twice with the same error, stop and report the blocker instead of retrying in a loop. ``` This is an instruction, not a hard enforcement mechanism; check the logs and use request or budget limits as additional safeguards. ### Models and reasoning - Use **auto model selection** as a default; pin a stronger model for planning and a cheaper one for bounded implementation (see [Models, planning, delegation](../05-models-and-planning/)). - Auto is a convenient default, **not a cost optimizer**: confirm in the docs how it picks models before relying on it to control spend. - Leave **thinking effort** at the default; raise it only for hard problems. Higher effort writes more thinking tokens (cost and latency). - A model switch starts a fresh prompt cache: caching is provider-, model-, and deployment-specific, so switching models mid-session does not reuse the earlier cache. ### Copilot cloud agent (issue → PR) A cloud-agent task can consume a large amount of tokens. Reduce the start-up cost: - Write a precise issue: acceptance criteria (tests or behavior), reproduction steps, links to relevant files, explicit scope — not just "fix this". - Pre-install dependencies and pre-run the build in the repository's **Copilot setup steps** workflow, `.github/workflows/copilot-setup-steps.yml`, so the agent does not rediscover the environment each time. ### Where limits apply Usage-based billing adds account-level budget controls on GitHub (for example per-user or cost-center spending limits) in addition to the in-editor loop limit. Check your plan's current options in the [GitHub Docs](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals). Note that automation which calls Copilot (CI review, generated tests, scans) consumes credits on every run. ## How to verify Run one multi-step task in Ask, Plan, and Agent where each is appropriate and compare session credits and number of tool calls in **Agent Debug Logs**. Confirm that the loop ends on your completion criterion rather than at the request limit. ## Trade-offs A low `maxRequests` can cut off legitimate long tasks mid-way (wasting the tokens already spent). Prefer a clear done-criterion and a plan file over tight limits. ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [Training Language Models to Reason Efficiently](https://arxiv.org/abs/2502.04463) — NeurIPS 2025, 285 citations. Trains reasoning models to trade accuracy against reasoning length. - [Token-Budget-Aware LLM Reasoning](https://arxiv.org/abs/2412.18547) — ACL 2024, 259 citations. Estimates a token budget per problem to shorten chain-of-thought reasoning. - [Do NOT Think That Much for 2+3=? On the Overthinking of o1-Like LLMs](https://arxiv.org/abs/2412.21187) — preprint 2024, 605 citations. Shows o1-like models spend excessive tokens on simple questions and proposes ways to cut them. - [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) — preprint 2024, 566 citations. A fixed localize-repair-validate pipeline competes with open-ended agent loops on SWE-bench Lite at low cost. - [L1: Controlling How Long A Reasoning Model Thinks With Reinforcement Learning](https://arxiv.org/abs/2503.04697) — preprint 2025, 416 citations. Trains reasoning models to obey a user-specified length budget. - [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) — preprint 2025, 40 citations. Systematic study of the efficiency-effectiveness trade-off in agent system design. ## Sources - [VS Code Copilot settings reference](https://code.visualstudio.com/docs/copilot/reference/copilot-settings) (`chat.agent.maxRequests`) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Customize the cloud agent environment (copilot-setup-steps.yml)](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/customize-the-agent-environment) - Token Efficiency and Context Engineering — developer talk deck (June 2026): mode comparison and cloud-agent tips (qualitative points only; the deck's token figures are not reproduced here) --- ## MCP audit (copilot-tokenomics/09-mcp-audit.md) Canonical URL: > Every enabled tool is a per-request tax. Audit servers by usage and scope them per workspace. ## Problem MCP **tool definitions (schemas)** included in a request add input whether used or not. Some clients defer schemas through virtual tool grouping, as described below. When all schemas are sent on each step of an agent loop, the cost multiplies: ```text tokens per task ≈ (tool schema tokens × steps) + accumulated conversation + tool responses ``` An idle server whose full schemas are loaded still costs tokens on each step; deferred schemas can change this baseline.
5 MCP servers
Tools 65%
Other 35%
100%
1 relevant server
Tools 15%
Other 35%
50%
Synthetic illustration, not a measured result: against the original prefix, tool definitions fall from 65% to 15%, while the other prefix stays at 35%; the new total is 50% of the original. Keeping one relevant server reduces the definitions sent on each turn; actual savings vary. Green indicates the pruned configuration, not a cache hit.
## Actions ### Run a monthly audit 1. List every MCP server and its tool count (the tools picker, **Configure Tools**, shows them). 2. For each server, note how often you used it last month (Agent Debug Logs show tool calls). 3. Decide per server: | Usage | Decision | |-------|----------| | Used most days | Keep | | Used occasionally | Keep **disabled by default**, enable per task | | Rarely/never, or duplicated by another tool | Remove | | Large server where you need two tools | Use a narrower server or a small CLI the agent calls from the terminal | 4. Re-measure the first-request input size and the baseline task ([Measure your usage](../02-measure-usage/)). ### On-demand tool loading and virtual grouping Recent VS Code Copilot builds can group a large tool catalog into virtual tools and defer full schemas until a group is activated (a tool-search step such as `tool_search`, where supported). Once activated, the group's schemas can remain in later requests for the session; behavior depends on the build and model. If grouping is disabled or unsupported, full schemas may be sent from the start. Check Agent Debug Logs and Cache Explorer rather than assuming a cache saving. The experimental `github.copilot.chat.virtualTools.threshold` controls when grouping is used ([VS Code settings reference](https://code.visualstudio.com/docs/copilot/reference/copilot-settings)). Disabling unused MCP servers per workspace remains the most reliable baseline for reducing the available catalog. ### Scope per workspace, not globally Put MCP configuration in the repository (`.vscode/mcp.json`) so each project loads only what it needs: a backend repo does not need design-tool servers; a frontend repo does not need database-schema tools. Reviewing a per-repo file is also easier than a global list. ### Replace long knowledge with Skills Repeated or large reference material (a house style, a runbook, API notes) can be packaged as an **agent skill** that loads on demand instead of sitting in always-on instructions. Benefits: less repeated input, one place to update, consistent results. ### Keep tool output small Tool results are often the largest part of the context (file reads, grep, shell output). Prefer targeted searches over reading whole files, and exclude noisy paths ([Keep context lean](../03-context-hygiene/)). ## How to verify Record the first-request input tokens in Agent Debug Logs before and after pruning, then run the same task and compare credits and success. Keep the change only if quality held. ## Trade-offs A pruned tool the task needed leads to workarounds and extra steps. Keep a fast way to re-enable tools, and prune by evidence (usage), not by guesswork. ## Illustrative numbers The talk deck this page draws on describes a team that reduced 187 tools to 52 and reports about a 72% drop in agent-task token use. We could not verify that case independently; use it as an example of the *method*, and measure your own result. TokenEconomizer automates the same idea by pruning tools that go unused across sessions (see the [case study](../../agent-tokenomics/case-tokeneconomizer/)). ## Further reading (papers) Ordered by venue tier, then citations. Findings are hypotheses to verify on your own workload; see the full list in [Papers](../../papers/). - [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) — preprint 2025, 55 citations. Lets the agent request tools on demand instead of injecting all tool schemas. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — preprint 2025, 41 citations. Retrieves only the relevant MCP tool descriptions instead of loading every tool (prompt bloat). - [Less is More: Optimizing Function Calling for LLM Execution on Edge Devices](https://arxiv.org/abs/2411.15399) — preprint 2024, 33 citations. Presents a smaller selected tool set at function-calling time to cut cost on edge devices. ## Sources - [Optimize AI credit usage — Keep the tool catalog focused](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Use tools with agents (VS Code)](https://code.visualstudio.com/docs/agents/run/tools) - Token Efficiency and Context Engineering — developer talk deck (June 2026), MCP sections (figures as reported) --- ## Checklist (copilot-tokenomics/10-checklist.md) Canonical URL: > One-page Copilot tokenomics checklist: high-impact habits before, during, and after VS Code GitHub Copilot sessions to cut token and AI credit spend. Impact tiers are qualitative starting priorities, not measured savings; impact varies by billing plan and workload. Confirm cost and quality against your baseline. ## Before you start a session - [ ] [High] New task → new chat. Side question → `/fork`. - [ ] [High] Only the tools/MCP servers this task needs are enabled. - [ ] [High] Model chosen deliberately (auto by default); thinking effort left at default. - [ ] [Medium] Noisy paths excluded (`.gitignore`, `files.exclude`, `search.exclude`). - [ ] [High] Prompt names the files/errors/constraints and the success criteria. - [ ] [Medium] Prompt ends with an output limit (`Code only.` / `3 bullets max.`); one task per prompt. - [ ] [Medium] Standing instructions and rules are written in English, terse, and de-duplicated. ## During - [ ] [Medium] Use #-mentions for known files; `#codebase` only when you need search. - [ ] [High] Complex change? Plan first, then implement; delegate bounded pieces to cheaper subagents. - [ ] [High] Ambiguous task? Use Ask/Plan before Agent; give a clear "done" criterion. - [ ] [High] Session getting long and still needed? `/compact` with a focus hint. - [ ] [Medium] Bulk/polling work → run a script, hand the model the summary. ## Weekly review - [ ] [Low] Open the Copilot status dashboard: monthly allowance used? - [ ] [Medium] Find your three most expensive sessions (context-window popover). What made them large? - [ ] [Low] Run `/chronicle:cost-tips` if available; otherwise inspect Agent Debug Logs Summary and Cache Explorer. - [ ] [High] Prune instructions and tools you never needed ([MCP audit](../09-mcp-audit/)). ## When in doubt Measure ([page 2](../02-measure-usage/)), change one thing, measure again, keep it only if quality held. --- ## cctx: VS Code Copilot Token Saver & Accelerator (copilot-tokenomics/cctx.md) Canonical URL: > Install Code Context (cctx) from the VS Code Marketplace to cut Copilot lookup tokens, speed up coding tasks, and inspect live AIC/USD cost savings. [Code Context (`cctx`)](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) is a **VS Code Native Language Model Tools extension** (`dotnetpower.code-context-native`) backed by a shared local Rust trigram index. Installed directly from the VS Code Marketplace, it both **reduces Copilot token/AI Credit consumption** and **accelerates development speed** by replacing multi-step `grep` + full-file `view` loops with single-call, block-clamped context lookups — while surfacing live per-model token, cache-hit, and AIC/USD savings right inside VS Code. ## Problem When GitHub Copilot Agent Mode explores a repository using built-in search and file-read tools, two compounding costs slow you down and drain AI Credits: 1. **Multi-turn exploration latency (slower development):** Finding a symbol, reading its definition, and checking nearby callers typically takes several `grep` → `view` → `grep` round trips. Each extra LLM turn adds network and prefill latency. 2. **History bloat (higher token cost):** Unclamped file reads (`100–200+` lines or whole documents) enter the conversation history and are **re-sent on every subsequent turn** of the session. Verbose prose agent instructions add another fixed per-turn tax. --- ## Action: Install in VS Code (Marketplace) `cctx` works as a native VS Code extension (`VS Code 1.140+`) on **Linux, native Windows (`cctx.exe`), WSL, and SSH** — no MCP JSON configuration or proposed API flags are required for VS Code Copilot. ### 1. Install the VS Code extension from Marketplace Install **[Code Context by dotnetpower](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native)** from the VS Code Extensions view, or run: ```bash code --install-extension dotnetpower.code-context-native ``` ### 2. Install the local Rust backend (`cctx`) The VS Code extension talks to a fast local Rust daemon (`cctx`) on your machine: ```bash # Linux / WSL / macOS / SSH: git clone https://github.com/dotnetpower/code-context.git cd code-context && bash scripts/install.sh && ~/.local/bin/cctx ping # Native Windows (PowerShell, no WSL required): cargo build --locked --release copy target\release\cctx.exe $HOME\.local\bin\cctx.exe ``` ### 3. Open your project and run Getting Started Run **Code Context: Getting Started** from the VS Code Command Palette (`Ctrl+Shift+P` / `⌘Shift+P`). On native Windows, `cctx.exe daemon` starts automatically in the background. The extension automatically attaches a compact, BPE-aligned instruction file (`applyTo: "**"`) so Copilot prefers the native tools without manual prompting: | VS Code Native Tool | What Copilot uses it for | Why it is faster & cheaper | |---|---|---| | `#cctxNativeContext` | **Symbol / pattern + nearby code in 1 call** | Replaces separate `grep` + `view` turns; clamps snippets to function/block boundaries within `<8 KiB`. | | `#cctxNativeGrep` | **Trigram-indexed literal / regex search** | Prioritizes symbol definitions (`max_matches_per_file`) instead of dumping noisy match lists. | | `#cctxNativeFiles` | **Instant filename & path glob discovery** | Sub-millisecond in-memory path matching (`0.307 ms` warm median). | | `#cctxNativeRead` | **Hash-verified line-range & anchor reads** | Reads exact line ranges or `#toc` / `#slide-N-M` / `#heading` anchors in `.md`, `.docx`, `.pptx`, and `.pdf` files. | --- ## Why it both saves cost and accelerates development In the published [8-session, 40-round, 8,960-pair benchmark suite](https://github.com/dotnetpower/code-context/blob/main/docs/BENCHMARKS.md) on `aks-store-demo` and Copilot A/B coding trials (as reported by `dotnetpower/code-context`), `cctx` improves both **developer velocity** and **token efficiency** without reducing answer accuracy: ### 1. Development speed acceleration - **15.20× faster warm code retrieval** across the mixed retrieval suite (`4.450 ms → 0.293 ms` per operation; 95% CI `14.53–15.84×`; `29.115 ms` cold sync median): - Literal search: **20.35× faster** (`5.885 ms → 0.289 ms`) - Search + context: **18.70× faster** (`5.935 ms → 0.317 ms`) - Filename discovery: **16.03× faster** (`4.923 ms → 0.307 ms`) - **61.9% fewer tool calls** per coding task (`7.00 → 2.67` calls) and **26.7% fewer LLM round-trip turns** (`5.00 → 3.67` turns), eliminating back-and-forth search loops. - **24.7% faster end-to-end task completion wall time** (`20.31 s → 15.30 s` at 100% answer accuracy). - **Nonblocking cold cache:** If a workspace index is still warming up, `cctx` returns `CACHE_MISS` immediately and loads in the background so Copilot never stalls waiting for indexing. ### 2. Token and AI Credit savings | Benchmark dimension | Baseline (`rg` + `view`) | With `cctx` in VS Code | Reported impact | |---|---:|---:|---| | **Rust 6-symbol lookup payload** | 15,028 tok (100L) / 25,133 tok (200L) | **4,031 tok** (6 calls vs 20) | **-73.2% to -84.0% tokens** (**10.3×** faster) | | **Python 6-symbol lookup payload** | 13,997 tok (100L) / 24,609 tok (200L) | **2,141 tok** (6 calls vs 15) | **-84.7% to -91.3% tokens** (**13.16×** faster) | | **Rich documents (`.pptx` / `.docx` / `.md`)** | Full-document read | Virtual `#toc` + `#slide-N-M` anchors | **-86.3% to -98.9% tokens** | | **Auto-loaded agent instructions** | 2,048 tok prose | **756 tok** BPE-aligned formula spec | **-63.1% instruction overhead** | | **Copilot A/B net session cost** | 6,360 payload tok / 4.76B nanoAIU | **3,177 payload tok / 3.55B nanoAIU** | **-50.0% payload tok · -25.4% AIU cost** | --- ## How to verify: Live usage & cost savings in VS Code You do not need to guess whether `cctx` is being used or how much it saves. The extension provides two built-in usage views. ### 1. VS Code Status Bar badge & hover popover (instant, in-editor) Look at the bottom status bar in VS Code. `cctx` displays live native call counts, active model, estimated tokens saved, and USD/AIC savings: ```text $(database) CCTX N S:382 C:4 P:0 E:0 · Claude Sonnet 4.6 · ~142.8K tok (+$0.48) ``` Hovering over the status bar item opens a rich Markdown popover showing per-model spend, cache hit rate, and native tool breakdown (synthetic example): | 💰 Cost Saved (@$0.001) | 💎 API Value (@$0.01) | 🔥 Tokens Saved | 🎯 Warm Hit Rate | ⚡ Avg Latency | | :---: | :---: | :---: | :---: | :---: | | **+$0.48** (`~480.0 AIC`) | **+$4.80** | **~142.8K tok** | **99.0%** (`382/386`) | **0.31 ms** | | Operation | Calls (OK/Miss) | Delivered | Saved Tok | Avg ms | | :--- | ---: | ---: | ---: | ---: | | `cctxNativeContext` | 142 (140/2) | ~68.4K | ~94.2K | 0.32 ms | | `cctxNativeRead` | 128 (127/1) | ~52.1K | ~31.5K | 0.26 ms | | `cctxNativeGrep` | 74 (73/1) | ~16.8K | ~12.4K | 0.29 ms | | `cctxNativeFiles` | 42 (42/0) | ~5.5K | ~4.7K | 0.30 ms | ### 2. Multi-session terminal dashboard (`cctx usage --hours 24`) To inspect aggregate LLM spend, prompt-cache hit rate, eligible source adoption, and per-model/per-session savings across all your recent VS Code Copilot sessions, run `cctx usage --hours 24` (or `--hours 168` for 7 days) in the VS Code terminal (synthetic example): ```text $ cctx usage --hours 24 ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗ ║ ⚡ CODE CONTEXT (cctx) — MODEL, TOKEN & COST SAVINGS DASHBOARD (Window: 24.0h) ║ ╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣ ║ 💰 COST SAVED (@$0.001/AIC) : +$24.80 USD (-23.5% of baseline bill · ~24800.0 AIC saved) ║ ║ 💎 API LIST VALUE (@$0.01) : +$248.00 USD (Frontier API list price: $2/$0.10/$10 per 1M) ║ ║ 🔥 TOKENS SAVED : ~740.20M tok (Payload ~7.42M + 35x Cache ~259.7M + ~2040 Turns ~450.1M + BPE ~22.98M) ║ ║ 🧬 BPE FORMULA COMPRESSION : ██████████ 100.0% (4/4 surfaces: ext·mcp·subagent·global · ~2100 tok/turn · +$12.30) ║ ║ 🎯 WARM CACHE HIT RATE : ██████████ 97.2% (4680 warm hits / 4815 CCTX lookups) ║ ║ 🚀 ELIGIBLE SOURCE ADOPTION : ███████░░░ 74.8% (4815/6437 · excl. 920 /tmp & 680 pre-edit) ║ ╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝ 1. LLM MODEL USAGE, CACHE HIT & COST SAVINGS ┌──────────────────────────┬────────────┬─────────────────┬───────────────┬───────────────┬───────────┬────────────────────────┬──────────────────────────────────────────┐ │ Model (Effort) │ Sess/Turns │ Input (Cache%) │ Out+Rsn Tok │ CCTX (Warm%) │ Src Adopt │ LLM Spend (@$0.001) │ COST SAVED (@$0.001 / API @$0.01) │ ├──────────────────────────┼────────────┼─────────────────┼───────────────┼───────────────┼───────────┼────────────────────────┼──────────────────────────────────────────┤ │ Claude Sonnet 4.6 (high) │ 18/4120 │ 1.84B (96.2%) │ 4.12M+1.90M │ 3410 (97.5%) │ 76.4% │ $58.40 (58400.0 AIC) │ +$18.20 / API +$182.00 (~18200.0 AIC) │ │ GPT-5.4 (medium) │ 24/1980 │ 640.00M (97.4%) │ 2.10M+1.15M │ 1405 (96.5%) │ 71.2% │ $22.10 (22100.0 AIC) │ +$6.60 / API +$66.00 (~6600.0 AIC) │ │ TOTAL (All Models) │ 42/6100 │ 2.48B (96.5%) │ 6.22M+3.05M │ 4815 (97.2%) │ 74.8% │ $80.50 (80500.0 AIC) │ +$24.80 / API +$248.00 (~24800.0 AIC) │ └──────────────────────────┴────────────┴─────────────────┴───────────────┴───────────────┴───────────┴────────────────────────┴──────────────────────────────────────────┘ ``` Combine this with VS Code's built-in [Agent Debug Logs](../02-measure-usage/) to compare a representative task before and after enabling `cctx`. --- ## Trade-offs and cautions - **Tiny known-range file reads:** Because `cctx` communicates with a local daemon over IPC, reading a tiny known slice of a single file can be slightly slower in raw sub-millisecond latency (`0.251 ms` vs `0.083 ms` direct host read), though `#cctxNativeRead` adds SHA-256 verification and `<8 KiB` inline budget clamping. - **Cold-start fallback:** A `CACHE_MISS` on the first lookup in a new workspace is normal — it is **not** an empty search result. Copilot falls back to standard host tools for that turn while the daemon finishes indexing in the background (`~29 ms` median on medium repos). - **Security and exclusion boundaries:** Hidden configuration directories (`.github`, `.vscode`), `.gitignore` paths, `/tmp`, and secret files are intentionally excluded from the trigram cache and handled by VS Code's policy-aware host tools. ## Sources - [Code Context by dotnetpower — VS Code Marketplace (`dotnetpower.code-context-native`)](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) - [dotnetpower/code-context GitHub repository](https://github.com/dotnetpower/code-context) - [Code Context Benchmarks & Token Efficiency Report](https://github.com/dotnetpower/code-context/blob/main/docs/BENCHMARKS.md) - [VS Code Setup & Troubleshooting Guide](https://github.com/dotnetpower/code-context/blob/main/vscode-extension/docs/SETUP.md) --- ## Copilot Tokenomics (Token Economics) (copilot-tokenomics/index.md) Canonical URL: > Practical tokenomics and token economics for GitHub Copilot in VS Code: save tokens and AI credits, trim MCP overhead, and speed up coding with cctx. Track A covers **Copilot Tokenomics (token economics)** for developers who **use** GitHub Copilot in VS Code. Every page follows the same shape: *Problem → Action → How to verify → Trade-offs*. Check your Copilot billing settings first; the best levers depend on your plan. | Billing model | What is charged | Start with | |---|---|---| | AI Credits (usage-based) | Input, cached input, and output tokens × their model rates | [Measure usage](02-measure-usage/), [context](03-context-hygiene/), and [tools](04-instructions-and-tools/) | | Legacy Premium Requests | Each prompt/turn × the model multiplier | [Billing](01-how-usage-is-charged/), [models](05-models-and-planning/), and [budget guards](08-agent-modes-and-budget/) |
VS Code diagram showing how agent context is assembled
Agent context is assembled from multiple sources. Source: VS Code Docs — Context in Agents.
| Page | Question it answers | |------|---------------------| | [How Copilot usage is charged](01-how-usage-is-charged/) | What am I actually spending? | | [Measure your usage](02-measure-usage/) | Which chats and requests are expensive? | | [Keep context lean](03-context-hygiene/) | How do I stop paying for irrelevant history? | | [Instructions and tools](04-instructions-and-tools/) | What is sent on every request, and can it shrink? | | [Models, planning, delegation](05-models-and-planning/) | When is a cheaper model or a plan-first flow worth it? | | [Prompt and output style](06-prompt-and-output-style/) | How do I shorten prompts and cap answers? | | [Language and tokenization](07-language-and-tokenization/) | Is writing in my language more expensive? | | [Agent modes and budget guards](08-agent-modes-and-budget/) | Ask vs Plan vs Agent; how do I bound the loop? | | [MCP audit](09-mcp-audit/) | Which tool servers should stay enabled? | | [Checklist](10-checklist/) | A one-page routine. | | [cctx: VS Code Token Saver & Accelerator](cctx/) | How do I cut lookup tokens, speed up coding tasks, and see live AIC/USD savings in VS Code? | | [Resources](../resources/) | Tools and repos worth knowing. | | [Papers](../papers/) | Research behind these tactics, ranked by authority. | :::note Copilot billing, UI, and settings change quickly. Each page states the date it was verified and links the official source. If something differs in your VS Code, trust the official docs. ::: --- ## Tokenomics & Token Economics Glossary (glossary.md) Canonical URL: > Definitions of tokenomics, token economics, prompt caching, context window, tool pruning, and LLM agent cost terms (English ↔ Korean). | English | 한국어 | Meaning | |---------|--------|---------| | tokenomics / token economics | 토큰 이코노믹스 / 토큰 경제학 | The discipline of measuring, pricing, budgeting, and optimizing token usage, caching, and context across LLM requests and AI agent loops without degrading output quality. | | token | 토큰 | Unit of text a model reads or writes; the basis of usage billing. | | input / output tokens | 입력 / 출력 토큰 | Tokens sent to the model / generated by it. | | context window | 컨텍스트 윈도우 | Maximum tokens a model can consider in one request. | | prefix | 접두부 | The beginning of a request; an unchanged prefix may be reused by provider caches. | | prompt caching | 프롬프트 캐싱 | Provider reuse of an unchanged request prefix, lowering cost and latency. | | cache hit rate | 캐시 적중률 | Share of input tokens served from the cache. | | AI credits | AI 크레딧 | GitHub Copilot's usage-based billing unit. | | premium request | 프리미엄 요청 | Legacy Copilot billing unit: prompt × model multiplier. | | compaction | 컨텍스트 압축 | Summarizing older conversation to free context space. | | observation masking | 관찰 마스킹 | Replacing older tool results with compact placeholders while retaining recent observations. | | tokenizer encoding (`o200k_base` / `cl100k_base`) | 토크나이저 인코딩 | The tokenization vocabulary and rules used to map text to tokens; counts depend on the encoding. | | tool definition | 도구 정의 | The schema of a tool sent to the model on every request. | | tool pruning | 도구 가지치기 | Leaving unused tool definitions out of requests. | | micro-skill | 마이크로 스킬 | A short, confirmed repository fact stated at session start. | | failure loop | 실패 루프 | A turn repeatedly hitting the same failure. | | loop guard | 루프 가드 | Mechanism that detects a failure loop and redirects the agent once. | | turn | 턴 | The agent's work on one user prompt. | | baseline | 기준선 | The measured starting point to compare against. | | subagent | 서브에이전트 | A separate agent run that keeps exploration out of the main conversation. | | context rot | 컨텍스트 열화 | Quality loss in long contexts even before the window is full (e.g., middle content is used less reliably). | | landmine (instruction) | 지뢰 규칙 | A rule the agent cannot infer from code and would break if unknown; the kind worth putting in instructions. | | tool schema tax | 도구 스키마 세금 | Tokens spent re-sending tool definitions on every request. | | agent skill | 에이전트 스킬 | On-demand packaged knowledge or tooling that replaces always-on instructions. | | reasoning effort | 추론 강도 | Setting that controls how many thinking tokens a model spends per request. | | fan-out (LLM calls per request) | 팬아웃 (요청당 LLM 호출 수) | Number of model calls triggered by one user request in a pipeline or agent. | | token map | 토큰 지도 | Per-step table of fixed and dynamic tokens, calls, and share of the total. | | cacheable prefix | 캐시 가능 접두부 | The stable start of a request that meets the provider's minimum length and can be served from the prompt cache. | | provisioned throughput | 프로비저닝 처리량 | Reserved model capacity billed for capacity rather than per token; optimizing it means capacity and latency, not only cost. | --- ## Tokenomics & Token Economics for LLMs & AI Agents (index.mdx) Canonical URL: > Tokenomics and token economics guide for LLMs & AI agents: cut token costs in VS Code Copilot, speed up coding with cctx, and profile calls with tokprof. (Interactive landing page — see structured index in llms.txt and Track A / Track B sections below.) --- ## Papers (papers.md) Canonical URL: > 75 papers on saving tokens, ranked by venue tier and citations. 75 papers relevant to saving tokens, compiled on **2026-11-03** and ranked by a transparent authority proxy. Each entry links to its arXiv page; takeaways are our own one-line summaries. ## How the ranking works 1. **Tier 1** — peer-reviewed at a flagship ML / NLP / systems venue (ICLR, NeurIPS, ICML, ACL, EMNLP, NAACL, TACL, TMLR, SOSP, MLSys). 2. **Tier 2** — other peer-reviewed venues (journals and other conferences). 3. **Tier 3** — preprints (no venue listed). 4. Within a tier, **more citations first**. :::caution[Read the ranking as a reading order, not a verdict] - Year is the year Semantic Scholar lists for the paper (often its first preprint year, which can precede the venue year). - Venue and citation count come from the [Semantic Scholar](https://www.semanticscholar.org/) Graph API on 2026-11-03. Venues can lag the final publication, and citations keep changing. Re-run `examples/fetch_paper_meta.py` then `examples/build_papers.py` to refresh. - Citations favor older and foundational work; recent preprints rank low simply because they are new. - Peer review and citations do not guarantee a result holds for your agent or model. Treat every finding as a hypothesis and verify it with the [troubleshooting procedure](../agent-tokenomics/). - We summarize the claim, not the numbers. Read the paper for the setup before relying on a figure. ::: ## Where each topic is applied | Topic | Papers | Used in | |-------|-------:|---------| | Foundations | 3 | [Concepts](../agent-tokenomics/00-concepts/) | | Tokenization and language | 3 | [Language and tokenization](../copilot-tokenomics/07-language-and-tokenization/) | | Long context and context rot | 9 | [Concepts](../agent-tokenomics/00-concepts/), [Keep context lean](../copilot-tokenomics/03-context-hygiene/), [Improve](../agent-tokenomics/04-improve/) | | Prompt / KV caching | 10 | [Concepts](../agent-tokenomics/00-concepts/), [Measure your usage](../copilot-tokenomics/02-measure-usage/), [Improve](../agent-tokenomics/04-improve/) | | Prompt compression | 10 | [Prompt and output style](../copilot-tokenomics/06-prompt-and-output-style/), [Improve](../agent-tokenomics/04-improve/) | | Output format | 1 | [Prompt and output style](../copilot-tokenomics/06-prompt-and-output-style/) | | Batching | 1 | [Instructions and tools](../copilot-tokenomics/04-instructions-and-tools/), [Improve](../agent-tokenomics/04-improve/) | | Model routing and cascades | 5 | [Models, planning, delegation](../copilot-tokenomics/05-models-and-planning/), [Improve](../agent-tokenomics/04-improve/) | | Efficient reasoning / output length | 6 | [Agent modes and budget guards](../copilot-tokenomics/08-agent-modes-and-budget/), [Improve](../agent-tokenomics/04-improve/) | | Agent cost and context management | 9 | [Isolate](../agent-tokenomics/02-isolate/), [Improve](../agent-tokenomics/04-improve/), [TokenEconomizer case study](../agent-tokenomics/case-tokeneconomizer/) | | Tool selection and schema size | 3 | [MCP audit](../copilot-tokenomics/09-mcp-audit/), [Improve](../agent-tokenomics/04-improve/) | | Instruction / context files | 1 | [Instructions and tools](../copilot-tokenomics/04-instructions-and-tools/) | | Memory and summarization | 4 | [Prove](../agent-tokenomics/03-prove/), [Improve: compaction](../agent-tokenomics/04-improve/#compaction-without-losing-the-cache) | | Evaluation and statistics | 5 | [Prove](../agent-tokenomics/03-prove/), [Result](../agent-tokenomics/05-result/) | | Surveys | 5 | [Resources](../resources/) | ## Ranked list | # | Paper | Venue · Year | Cited | Topic | Takeaway | |--:|-------|--------------|------:|-------|----------| | 1 | [Chain of Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/abs/2201.11903) | NeurIPS · 2022 | 23,523 | Foundations | Step-by-step prompting improves reasoning, and also increases output tokens. | | 2 | [ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629) | ICLR · 2022 | 13,383 | Foundations | Interleaves reasoning and tool actions: the agent loop whose cost this guide analyzes. | | 3 | [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) | SOSP · 2023 | 9,724 | Prompt / KV caching | PagedAttention manages KV-cache memory to raise serving throughput; basis of vLLM. | | 4 | [Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909) | ACL · 2015 | 9,243 | Tokenization and language | Introduced the subword (BPE) units that underlie most LLM tokenizers. | | 5 | [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) | TACL · 2023 | 5,818 | Long context and context rot | Accuracy drops when the relevant information sits in the middle of a long input. | | 6 | [SWE-bench: Can Language Models Resolve Real-World GitHub Issues?](https://arxiv.org/abs/2310.06770) | ICLR · 2023 | 4,683 | Foundations | Benchmark of real GitHub issues used to evaluate coding agents, including by TokenEconomizer. | | 7 | [Efficient Streaming Language Models with Attention Sinks](https://arxiv.org/abs/2309.17453) | ICLR · 2023 | 2,768 | Long context and context rot | Keeps attention-sink tokens plus a recent window so inference can stream without full history. | | 8 | [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) | NeurIPS · 2024 | 2,357 | Agent cost and context management | Shows that interface design, including concise and bounded observations, changes agent success. | | 9 | [LongBench: A Bilingual, Multitask Benchmark for Long Context Understanding](https://arxiv.org/abs/2308.14508) | ACL · 2023 | 1,888 | Long context and context rot | Bilingual, multi-task benchmark for long-context understanding. | | 10 | [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) | NeurIPS · 2023 | 1,783 | Prompt / KV caching | RadixAttention reuses KV cache across calls that share a prefix; foundation for prefix caching. | | 11 | [Large Language Models Can Be Easily Distracted by Irrelevant Context](https://arxiv.org/abs/2302.00093) | ICML · 2023 | 1,358 | Long context and context rot | Irrelevant context in the prompt can substantially reduce model accuracy. | | 12 | [FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance](https://arxiv.org/abs/2305.05176) | TMLR · 2023 | 1,247 | Model routing and cascades | Selects and cascades LLMs to approach a strong model's quality at lower cost. | | 13 | [SnapKV: LLM Knows What You are Looking for Before Generation](https://arxiv.org/abs/2404.14469) | NeurIPS · 2024 | 1,132 | Prompt / KV caching | Selects the important KV positions per attention head to shrink the cache. | | 14 | [H2O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models](https://arxiv.org/abs/2306.14048) | NeurIPS · 2023 | 1,091 | Prompt / KV caching | Evicts KV-cache entries, keeping 'heavy hitter' tokens to shrink memory. | | 15 | [Evaluating Very Long-Term Conversational Memory of LLM Agents](https://arxiv.org/abs/2402.17753) | ACL · 2024 | 1,082 | Memory and summarization | Benchmark of very long-term conversational memory. | | 16 | [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) | ICLR · 2024 | 869 | Memory and summarization | Benchmark of long-term memory in chat assistants; useful for designing recall checks. | | 17 | [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache](https://arxiv.org/abs/2402.02750) | ICML · 2024 | 825 | Prompt / KV caching | Quantizes the KV cache to 2 bits without tuning. | | 18 | [LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression](https://arxiv.org/abs/2310.06839) | ACL · 2023 | 658 | Prompt compression | Question-aware compression for long contexts, aiming to cut cost while keeping or improving accuracy. | | 19 | [Scissorhands: Exploiting the Persistence of Importance Hypothesis for LLM KV Cache Compression at Test Time](https://arxiv.org/abs/2305.17118) | NeurIPS · 2023 | 598 | Prompt / KV caching | Exploits the persistence of token importance to compress the KV cache. | | 20 | [LLMs Get Lost In Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) | ICLR · 2025 | 562 | Long context and context rot | Models perform worse in multi-turn, underspecified conversations than in single-turn ones. | | 21 | [Learning to Compress Prompts with Gist Tokens](https://arxiv.org/abs/2304.08467) | NeurIPS · 2023 | 534 | Prompt compression | Trains a model to compress a prompt into a few reusable 'gist' tokens. | | 22 | [Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing](https://arxiv.org/abs/2404.14618) | ICLR · 2024 | 519 | Model routing and cascades | A router predicts query difficulty and sends easy queries to a smaller model. | | 23 | [Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models](https://arxiv.org/abs/2510.04618) | ICLR · 2025 | 505 | Agent cost and context management | Treats the context as an evolving playbook updated incrementally to avoid context collapse from rewriting. | | 24 | [Stop Overthinking: A Survey on Efficient Reasoning for Large Language Models](https://arxiv.org/abs/2503.16419) | TMLR · 2025 | 499 | Surveys | Survey of methods for efficient reasoning in large reasoning models. | | 25 | [LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression](https://arxiv.org/abs/2403.12968) | ACL · 2024 | 487 | Prompt compression | Distills a faster, task-agnostic prompt compressor that generalizes across tasks. | | 26 | [Adapting Language Models to Compress Contexts](https://arxiv.org/abs/2305.14788) | EMNLP · 2023 | 465 | Prompt compression | Fine-tunes a model to compress long contexts into short summary vectors reused as soft prompts. | | 27 | [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) | ICML · 2024 | 451 | Agent cost and context management | Agents induce reusable workflows from past trajectories and reuse them, similar in spirit to micro-skills. | | 28 | [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736) | EMNLP · 2023 | 418 | Prompt compression | Uses a small language model to drop low-information tokens from a prompt, with a controllable budget. | | 29 | [Prompt Cache: Modular Attention Reuse for Low-Latency Inference](https://arxiv.org/abs/2311.04934) | MLSys · 2023 | 417 | Prompt / KV caching | Reuses precomputed attention states of recurring prompt modules to cut latency. | | 30 | [RECOMP: Improving Retrieval-Augmented LMs with Compression and Selective Augmentation](https://arxiv.org/abs/2310.04408) | ICLR · 2023 | 340 | Prompt compression | Compresses retrieved documents into short summaries before they enter a retrieval-augmented prompt. | | 31 | [Language Model Tokenizers Introduce Unfairness Between Languages](https://arxiv.org/abs/2305.15425) | NeurIPS · 2023 | 319 | Tokenization and language | The same text tokenizes to very different lengths across languages. | | 32 | [AI Agents That Matter](https://arxiv.org/abs/2407.01502) | TMLR · 2024 | 289 | Evaluation and statistics | Argues agent evaluations must control for cost, not just accuracy. | | 33 | [Training Language Models to Reason Efficiently](https://arxiv.org/abs/2502.04463) | NeurIPS · 2025 | 285 | Efficient reasoning / output length | Trains reasoning models to trade accuracy against reasoning length. | | 34 | [Do All Languages Cost the Same? Tokenization in the Era of Commercial Language Models](https://arxiv.org/abs/2305.13707) | EMNLP · 2023 | 278 | Tokenization and language | Shows that tokenization differences make commercial API usage cost different amounts per language. | | 35 | [Compressing Context to Enhance Inference Efficiency of Large Language Models](https://arxiv.org/abs/2310.06201) | EMNLP · 2023 | 272 | Prompt compression | Prunes redundant lexical units by self-information to shorten inputs before inference. | | 36 | [Same Task, More Tokens: the Impact of Input Length on the Reasoning Performance of Large Language Models](https://arxiv.org/abs/2402.14848) | ACL · 2024 | 270 | Long context and context rot | Isolates input length as a factor and shows reasoning degrades as inputs grow. | | 37 | [Token-Budget-Aware LLM Reasoning](https://arxiv.org/abs/2412.18547) | ACL · 2024 | 259 | Efficient reasoning / output length | Estimates a token budget per problem to shorten chain-of-thought reasoning. | | 38 | [In-context Autoencoder for Context Compression in a Large Language Model](https://arxiv.org/abs/2307.06945) | ICLR · 2023 | 242 | Prompt compression | Encodes a long context into a few memory slots that a frozen decoder can read. | | 39 | [xRAG: Extreme Context Compression for Retrieval-augmented Generation with One Token](https://arxiv.org/abs/2405.13792) | NeurIPS · 2024 | 174 | Prompt compression | Represents each retrieved document as a single embedding token to shrink RAG context. | | 40 | [AutoMix: Automatically Mixing Language Models](https://arxiv.org/abs/2310.12963) | NeurIPS · 2023 | 169 | Model routing and cascades | Has a small model verify its own answer and escalates to a larger model only when needed. | | 41 | [Retrieval meets Long Context Large Language Models](https://arxiv.org/abs/2310.03025) | ICLR · 2023 | 159 | Long context and context rot | Compares retrieval augmentation with long context windows; retrieval can rival a longer window with less computation. | | 42 | [Batch Prompting: Efficient Inference with Large Language Model APIs](https://arxiv.org/abs/2301.08721) | EMNLP · 2023 | 154 | Batching | Packs several samples into one prompt so instruction tokens are shared. | | 43 | [Found in the Middle: Calibrating Positional Attention Bias Improves Long Context Utilization](https://arxiv.org/abs/2406.16008) | ACL · 2024 | 151 | Long context and context rot | Calibrates positional attention bias to reduce the lost-in-the-middle effect. | | 44 | [Let Me Speak Freely? A Study On The Impact Of Format Restrictions On Large Language Model Performance.](https://arxiv.org/abs/2408.02442) | EMNLP · 2024 | 142 | Output format | Strict output-format restrictions can lower reasoning performance. | | 45 | [Prompt Compression for Large Language Models: A Survey](https://arxiv.org/abs/2410.12388) | NAACL · 2024 | 96 | Surveys | Survey of hard (token-level) and soft prompt-compression methods. | | 46 | [500xCompressor: Generalized Prompt Compression for Large Language Models](https://arxiv.org/abs/2408.03094) | ACL · 2024 | 57 | Prompt compression | Targets extreme prompt compression into very few special tokens. | | 47 | [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) | ICLR · 2025 | 56 | Evaluation and statistics | Defines the expected cost to obtain a correct answer and compares models on it. | | 48 | [Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory](https://arxiv.org/abs/2504.19413) | ECAI · 2025 | 868 | Memory and summarization | Memory layer that extracts and retrieves salient facts instead of replaying the full history. | | 49 | [CacheBlend: Fast Large Language Model Serving for RAG with Cached Knowledge Fusion](https://arxiv.org/abs/2405.16444) | ACM TOCS · 2024 | 342 | Prompt / KV caching | Reuses KV caches of retrieved chunks in RAG even when they are not a shared prefix. | | 50 | [Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving](https://arxiv.org/abs/2407.00079) | ACM ToS · 2024 | 313 | Prompt / KV caching | Production serving architecture for Kimi built around a scheduler that reuses cached KV prefixes. | | 51 | [Recursively Summarizing Enables Long-Term Dialogue Memory in Large Language Models](https://arxiv.org/abs/2308.15022) | Neurocomputing · 2023 | 114 | Memory and summarization | Recursive summaries serve as memory for long dialogue. | | 52 | [Reducing Cost of LLM Agents with Trajectory Reduction](https://arxiv.org/abs/2509.23586) | PACMSE · 2025 | 68 | Agent cost and context management | Reduces agent cost by trimming waste out of the trajectory. | | 53 | [MemGPT: Towards LLMs as Operating Systems](https://arxiv.org/abs/2310.08560) | preprint · 2023 | 1,764 | Agent cost and context management | Manages memory tiers so an agent can work beyond its context window. | | 54 | [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) | preprint · 2024 | 1,669 | Evaluation and statistics | Benchmark that introduces pass^k to measure agent reliability across repeated runs. | | 55 | [RULER: What's the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) | preprint · 2024 | 1,580 | Long context and context rot | Benchmark showing the effective context length is often shorter than the advertised window. | | 56 | [RouteLLM: Learning to Route LLMs with Preference Data](https://arxiv.org/abs/2406.18665) | preprint · 2024 | 922 | Model routing and cascades | Learns from preference data to route queries between a strong and a cheaper model. | | 57 | [Do NOT Think That Much for 2+3=? On the Overthinking of o1-Like LLMs](https://arxiv.org/abs/2412.21187) | preprint · 2024 | 605 | Efficient reasoning / output length | Shows o1-like models spend excessive tokens on simple questions and proposes ways to cut them. | | 58 | [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) | preprint · 2024 | 566 | Agent cost and context management | A fixed localize-repair-validate pipeline competes with open-ended agent loops on SWE-bench Lite at low cost. | | 59 | [L1: Controlling How Long A Reasoning Model Thinks With Reinforcement Learning](https://arxiv.org/abs/2503.04697) | preprint · 2025 | 416 | Efficient reasoning / output length | Trains reasoning models to obey a user-specified length budget. | | 60 | [Chain of Draft: Thinking Faster by Writing Less](https://arxiv.org/abs/2502.18600) | preprint · 2025 | 324 | Efficient reasoning / output length | Prompts the model to write minimal draft steps instead of verbose chain-of-thought. | | 61 | [RouterBench: A Benchmark for Multi-LLM Routing System](https://arxiv.org/abs/2403.12031) | preprint · 2024 | 300 | Model routing and cascades | Benchmark and evaluation framework for multi-LLM routing systems. | | 62 | [Efficient Large Language Models: A Survey](https://arxiv.org/abs/2312.03863) | preprint · 2023 | 276 | Surveys | Broad survey of efficiency techniques across data, model, and system levels. | | 63 | [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) | preprint · 2024 | 194 | Evaluation and statistics | Statistical guidance for reporting uncertainty in LLM evaluations. | | 64 | [A Survey of Context Engineering for Large Language Models](https://arxiv.org/abs/2507.13334) | preprint · 2025 | 171 | Surveys | Survey organizing techniques for selecting, compressing, and managing LLM context. | | 65 | [Non-Determinism of"Deterministic"LLM Settings](https://arxiv.org/abs/2408.04667) | preprint · 2024 | 159 | Evaluation and statistics | Shows outputs vary across runs even in settings meant to be deterministic. | | 66 | [Efficient Prompting Methods for Large Language Models: A Survey](https://arxiv.org/abs/2404.01077) | preprint · 2024 | 71 | Surveys | Survey of prompt compression and prompt-optimization methods for efficiency. | | 67 | [Concise Reasoning via Reinforcement Learning](https://arxiv.org/abs/2504.05185) | preprint · 2025 | 69 | Efficient reasoning / output length | Uses reinforcement learning to encourage concise reasoning. | | 68 | [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) | preprint · 2025 | 66 | Agent cost and context management | Simple observation masking is as efficient as LLM summarization for agent context management. | | 69 | [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) | preprint · 2025 | 55 | Tool selection and schema size | Lets the agent request tools on demand instead of injecting all tool schemas. | | 70 | [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) | preprint · 2025 | 41 | Tool selection and schema size | Retrieves only the relevant MCP tool descriptions instead of loading every tool (prompt bloat). | | 71 | [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) | preprint · 2025 | 40 | Agent cost and context management | Systematic study of the efficiency-effectiveness trade-off in agent system design. | | 72 | [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) | preprint · 2026 | 36 | Instruction / context files | Repository context files did not generally improve task success and raised inference cost by over 20% on average. | | 73 | [Less is More: Optimizing Function Calling for LLM Execution on Edge Devices](https://arxiv.org/abs/2411.15399) | preprint · 2024 | 33 | Tool selection and schema size | Presents a smaller selected tool set at function-calling time to cut cost on edge devices. | | 74 | [Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks](https://arxiv.org/abs/2601.06007) | preprint · 2026 | 25 | Prompt / KV caching | Evaluates prompt caching on long-horizon agentic tasks. | | 75 | [TokenEconomizer: Experience-Driven Black-Box Cost Control for Coding Agents](https://arxiv.org/abs/2610.22732) | preprint · 2026 | 0 | Agent cost and context management | Micro-skills, tool pruning, and a loop guard cut coding-agent cost using experience from earlier sessions. | ## Suggest a paper Add an entry to `examples/papers.json` (arXiv id, one topic, a one-line note in your own words), run the two scripts, and open a PR. The metadata fetch fails on an unknown id, which guards against typos. --- ## Resources (resources.md) Canonical URL: > Repositories, papers, and docs for saving tokens. Curated and checked for existence on 2026-11-03. A curated list. Every link was checked on **2026-11-03**. Inclusion is **not an endorsement**: each project's savings figures are its authors' own claims, and we have not reproduced them. Benchmark on your own tasks and track a quality metric next to cost (see [Agent Tokenomics](../agent-tokenomics/)). :::caution Proxies, gateways, and compressors sit between your agent and the model, so they **see your prompts and code**. Read the license and data-handling notes, and review before using them with private repositories. ::: ## Start here | Resource | Why | |----------|-----| | [microsoft/TokenEconomizer](https://github.com/microsoft/TokenEconomizer) | Experience-driven cost control for coding agents: micro-skills, tool pruning, loop guard. Paper: [arXiv:2610.22732](https://arxiv.org/abs/2610.22732), [project page](https://tokeneconomizer.github.io). | | [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) | Official practical guide. | | [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) | Official: find the first prefix divergence between requests. | | [Azure OpenAI prompt caching](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/prompt-caching) | Minimum length, `cached_tokens`, `prompt_cache_key`, retention, billing and data-residency rules for Azure OpenAI. | | [OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) | Cacheable prefix rules, settings that invalidate the cache, diagnostics. | | [Usage-based billing for individuals](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals) | How AI credits are charged. | | [github/awesome-copilot](https://github.com/github/awesome-copilot) | Community instructions, agents, and skills for Copilot. | | [pleasedodisturb/awesome-llm-token-optimization](https://github.com/pleasedodisturb/awesome-llm-token-optimization) | Another curated list of strategies, tools, and papers. | ## Reduce tool output and command noise | Project | What it does | |---------|--------------| | [rtk-ai/rtk](https://github.com/rtk-ai/rtk) | CLI proxy that condenses output of common dev commands before the model sees it. | | [headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) | Compresses tool outputs, logs, files, and RAG chunks before they reach the LLM. | | [gglucass/headroom-desktop](https://github.com/gglucass/headroom-desktop) | Desktop app wrapper around the same idea for coding agents. | | [Dave-London/Pare](https://github.com/Dave-London/Pare) | Structured, token-efficient MCP servers for git, test runners, npm, Docker. | | [claw-compactor](https://github.com/open-compress/claw-compactor) | Multi-stage, reversible compression pipeline with code-aware analysis. | | [optscale-kompressor](https://github.com/hystax/optscale-kompressor) | Deterministic prompt compression for coding agents in one Rust binary. | | [fkiene/llmtrim](https://github.com/fkiene/llmtrim) | Local proxy that trims prompts, history, and tool output in API requests. | | [Paritok-official/paritok-4b-v1](https://github.com/Paritok-official/paritok-4b-v1) | Non-destructive compression gateway for coding agents. | ## Compress prompts and data | Project | What it does | |---------|--------------| | [microsoft/LLMLingua](https://github.com/microsoft/LLMLingua) | Prompt compression research (LLMLingua, LLMLingua-2). Paper: [arXiv:2310.05736](https://arxiv.org/abs/2310.05736). | | [jia-gao/leanctx](https://github.com/jia-gao/leanctx) | Drop-in prompt compression SDK for production apps (LLMLingua-2 based). | | [3DAgentWorld/Toolkit-for-Prompt-Compression](https://github.com/3DAgentWorld/Toolkit-for-Prompt-Compression) | Toolkit collecting prompt-compression methods. | | [ZongqianLi/Prompt-Compression-Survey](https://github.com/ZongqianLi/Prompt-Compression-Survey) | Survey of prompt-compression methods (NAACL 2025). | | [sriinnu/clipforge-PAKT](https://github.com/sriinnu/clipforge-PAKT) | Lossless-first compression for JSON, YAML, CSV, Markdown. | | [ISON-format/ison](https://github.com/ISON-format/ison) | Token-efficient JSON alternative for LLM data. | ## Terse style and measured evaluation | Project | What it does | |---------|--------------| | [JuliusBrussee/caveman](https://github.com/JuliusBrussee/caveman) | Skill/proxy that makes agents answer tersely. | | [danielle34/cavewoman](https://github.com/danielle34/cavewoman) | Evaluation framework measuring what input vs output compression actually saves. | | [YangJunMan/claude-code-token-savings-benchmark](https://github.com/YangJunMan/claude-code-token-savings-benchmark) | Reproducible benchmark comparing several token-saving tools. | ## Retrieve less code and keep memory small | Project | What it does | |---------|--------------| | [dotnetpower/code-context](https://github.com/dotnetpower/code-context) ([Marketplace](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) · [Track A guide](../copilot-tokenomics/cctx/)) | VS Code native Language Model Tools + shared local Rust trigram index (`cctx`) with `<8 KiB` inline-budgeted reads, BPE-formula instructions, 15.20× faster warm retrieval, and live status-bar/`cctx usage` AIC/USD savings telemetry. | | [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify) | Turns a folder (code, docs, PDFs, images) into a queryable knowledge graph. | | [jgravelle/jcodemunch-mcp](https://github.com/jgravelle/jcodemunch-mcp) | Symbol-level retrieval: fetch the function you need, not the whole file. | | [redhat-et/ripwire](https://github.com/redhat-et/ripwire) | CLI + MCP server to find relevant code without reading the repo. | | [yamadashy/repomix](https://github.com/yamadashy/repomix) | Packs a repository into one AI-friendly file (use selectively; big packs cost tokens). | | [radimsem/remindb](https://github.com/radimsem/remindb) | Portable agent memory in a SQLite file. | | [cytostack/openwolf](https://github.com/cytostack/openwolf) | Project memory across agents, with token accounting from transcripts. | | [fajarhide/contexere](https://github.com/fajarhide/contexere) | One place for skills, keys, and memory across agents. | ## Audit tokens, tools, and cost | Project | What it does | |---------|--------------| | [tokprof](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler) (this repository) | Breaks each call's input tokens down by system prompt, history, user prompt, and tool content without code changes; early development. | | [alexgreensh/token-optimizer](https://github.com/alexgreensh/token-optimizer) | Finds "ghost tokens" and context-quality decay in agent sessions. | | [activeing123/mcptoon](https://github.com/activeing123/mcptoon) | MCP gateway CLI aimed at tool discovery and context compression. | | [ccusage/ccusage](https://github.com/ccusage/ccusage) | Usage and cost reports from local Claude Code logs. | | [Maciek-roboblog/Claude-Code-Usage-Monitor](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor) | Real-time usage monitor with predictions. | | [junhoyeo/tokscale](https://github.com/junhoyeo/tokscale) | Token usage across several AI coding agents from the terminal. | ## Observability and gateways (for agents you operate) | Project | What it does | |---------|--------------| | [langfuse/langfuse](https://github.com/langfuse/langfuse) | Open-source tracing, evals, and cost tracking for LLM apps. | | [Arize-ai/phoenix](https://github.com/Arize-ai/phoenix) | AI observability and evaluation on OpenTelemetry ([docs](https://arize.com/docs/phoenix)). | | [Helicone/helicone](https://github.com/Helicone/helicone) | LLM observability platform and OpenAI-compatible gateway ([docs](https://docs.helicone.ai/getting-started/quick-start)). | | [LangSmith](https://docs.langchain.com/langsmith/cost-tracking) | LangChain's hosted tracing and evaluation platform with token and cost breakdowns (SDKs: [Python](https://github.com/langchain-ai/langsmith-python), [JS](https://github.com/langchain-ai/langsmith-javascript)). | | [Portkey-AI/gateway](https://github.com/Portkey-AI/gateway) | AI gateway with guardrails; Portkey's platform adds monitoring ([docs](https://portkey.ai/docs/introduction/what-is-portkey)). | | [openlit/openlit](https://github.com/openlit/openlit) | OpenTelemetry-based tracing and evaluation for agents. | | [AgentOps-AI/agentops](https://github.com/AgentOps-AI/agentops) | Agent monitoring and LLM cost tracking SDK. | | [BerriAI/litellm](https://github.com/BerriAI/litellm) | Gateway with cost tracking and routing across 100+ providers. | | [maximhq/bifrost](https://github.com/maximhq/bifrost) | LLM / MCP / agent gateway with failover. | These map to [stage 1 (Diagnose)](../agent-tokenomics/01-diagnose/#collect-the-request-log), which compares Phoenix, Langfuse, LangSmith, Helicone, and Portkey. They give you the per-request log that the [example script](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples) consumes. ## Context engineering and spec-driven workflows | Project | What it does | |---------|--------------| | [github/spec-kit](https://github.com/github/spec-kit) | Toolkit for spec-driven development: plan first, then implement. | | [Fission-AI/OpenSpec](https://github.com/Fission-AI/OpenSpec) | Spec-driven development for AI coding assistants. | | [shanraisshan/claude-code-best-practice](https://github.com/shanraisshan/claude-code-best-practice) | Practices for agentic engineering with Claude Code. | | [microsoft/vscode-copilot-chat](https://github.com/microsoft/vscode-copilot-chat) | Source of the VS Code Copilot Chat extension. | ## Papers The full ranked list (by venue tier, then citations) is on the [Papers](../papers/) page. Highlights: | Paper | Takeaway | |-------|----------| | [Evaluating AGENTS.md (arXiv:2602.11988)](https://arxiv.org/abs/2602.11988) | Context files did not generally improve task success and raised cost by over 20% on average; useful for non-standard practices. | | [Lost in the Middle (arXiv:2307.03172)](https://arxiv.org/abs/2307.03172) | Models use information in the middle of long contexts less reliably than at the start or end. | | [TokenEconomizer (arXiv:2610.22732)](https://arxiv.org/abs/2610.22732) | 18.4–30.9% lower mean cost on SWE-Bench across 5 agent–model combinations, as reported. | | [LLMLingua (arXiv:2310.05736)](https://arxiv.org/abs/2310.05736) | Prompt compression with small language models. | | [tiktoken](https://github.com/openai/tiktoken) | Tokenizer used by our [token counter](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py). | ## Suggest a resource Open an issue or PR with the link, a one-line description in your own words, and how you verified it exists. --- ## 0. 개념: LLM 에이전트 토큰 이코노믹스(Token Economics)의 원리 (ko/agent-tokenomics/00-concepts.md) Canonical URL: > LLM 토큰 이코노믹스(Tokenomics · Token Economics, 토큰 경제학)의 핵심 개념인 stateless 재전송, 요청 구성, 에이전트 루프, 과금 차원, 프롬프트 캐싱, 컨텍스트 열화를 살펴봅니다. [문제 해결 단계](../01-diagnose/)를 시작하기 전에 이 페이지를 읽어 보세요. 이후 단계에서는 여기서 설명하는 **LLM 토큰 이코노믹스(Tokenomics · Token Economics, 토큰 경제학)** 개념을 바탕으로 토큰 비용을 진단합니다. ## 1. 모델은 이전 호출을 기억하지 않습니다 (stateless) 모델은 호출과 호출 사이의 내용을 기억하지 않습니다. 에이전트가 이전 내용을 기억하는 것처럼 보이는 이유는 지침, 도구 정의, 지금까지의 대화를 **요청마다 다시 보내기 때문**입니다. 따라서 토큰 비용은 사용자가 입력한 내용뿐 아니라 프레임워크가 **요청마다 함께 담아 보내는 내용**에도 크게 좌우됩니다. ## 2. 요청 한 건의 구성 요소 | 구성 요소 | 입출력 | 요청마다 바뀌나요? | 흔한 낭비 | |-----------|--------|--------------------|-----------| | 시스템 프롬프트(프레임워크와 사용자 지침) | 입력 | 바뀌지 않음(고정) | 길고 반복되는 규칙 | | 지침 파일 / 기본 프로젝트 정보 | 입력 | 드물게 바뀜 | 코드에서 이미 알 수 있는 정보, 중복된 내용 | | **도구 정의**(스키마) | 입력 | 드물게 바뀜 | 한 번도 호출하지 않는 도구 | | 대화 기록(사용자, 어시스턴트) | 입력 | 턴마다 증가 | 이전 주제, 이미 해결된 우회 작업 | | **도구 결과**(파일 내용, 명령 출력) | 입력 | 단계마다 증가 | 파일 전체, 장황한 로그 | | 첨부 파일 / 검색된 컨텍스트 | 입력 | 작업마다 바뀜 | 관련 없거나 중복된 컨텍스트 | | 현재 사용자 프롬프트 | 입력 | 바뀜 | 보통 요청에서 차지하는 비중이 가장 작음 | | 모델의 텍스트 응답, 도구 호출 | 출력 | 바뀜 | 장황한 답변, 질문 되풀이 | | 추론("thinking") | 출력(보통 출력 토큰으로 과금) | 바뀜 | 작업에 필요한 수준보다 높은 추론 강도 | 표의 위쪽에 있는 구성 요소는 호출마다 거의 바뀌지 않는 **접두부**를 이룹니다. 접두부가 중요한 이유는 [프롬프트 캐싱](#5-프롬프트-캐싱)에서 살펴봅니다. ## 3. 에이전트 루프가 길어질수록 토큰 사용량은 빠르게 불어납니다 ```text step 1: model call ─► tool call ─► result appended step 2: model call (re-sends prefix + history + result 1) ─► tool call ─► result appended step 3: model call (re-sends prefix + history + result 1..2) ─► … ``` 각 단계에서 모델을 호출할 때마다 요금이 발생하고, 이전 내용도 다시 전송합니다. *n*단계로 이루어진 작업의 입력 토큰은 다음과 같이 나타낼 수 있습니다. ```text input tokens ≈ n × prefix + Σ(history and tool results accumulated before each step) ``` 첫 번째 항은 단계 수에 비례해 늘어납니다. 두 번째 항은 단계마다 쌓인 내용을 이후 호출에서 반복해서 보내므로 그보다 빠르게 늘어납니다. 따라서 **단계 수를 줄이고**, **도구 결과를 간결하게 만들고**, **접두부를 줄이면** 비용을 낮출 수 있습니다. 같은 작업을 반복하는 루프에 빠지면 비용이 특히 커집니다. **고정 파이프라인에서도 호출마다 비용이 누적됩니다.** 모든 에이전트가 자유롭게 루프를 돌며 작업하는 것은 아닙니다. 실제 서비스에서는 사용자 요청 하나에 정해진 순서로 모델을 호출하기도 합니다. 예를 들어 안전성 검사 → 쿼리 재작성 → 라우터 → 분류기 → 답변 → 후속 질문 → 최종 응답의 순서로 처리할 수 있습니다. 사용자에게는 질문 하나로 보이지만, 제공자는 **단계마다 모델 호출 한 건**을 과금합니다. 각 단계에서 사용하는 시스템 프롬프트와 참조 문서도 비용에 포함됩니다. 이렇게 사용자 요청 하나에서 발생하는 LLM 호출 수를 **팬아웃**이라고 합니다. 여러 단계에 넣거나 같은 단계를 두 번 호출할 때 사용하는 큰 자료에는 `tokens × calls`만큼의 비용이 발생합니다.
Step 1 (Call #1)
Prefix (System + Tools)
User
9,200 tok
Step 2 (Call #2)
Prefix (재전송)
History
Tool Result 1
13,800 tok
Step 3 (Call #3)
Prefix (재전송)
History + Result 1
Tool Result 2
19,500 tok
그림 1. 에이전트 루프 단계가 진행될수록 고정 접두부(n × prefix)가 반복 전송되고 이전 단계의 대화 기록·도구 결과(Σ)가 누적되어 입력 토큰이 늘어나는 구조. 참조: ReAct (ICLR 2022) 및 microsoft/TokenEconomizer.
**직접 만든 에이전트의 긴 컨텍스트 열화.** 대화 기록과 도구 결과가 쌓이면 모델은 컨텍스트의 중간에 묻힌 정보를 시작이나 끝에 있는 정보보다 덜 안정적으로 활용할 수 있습니다([Lost in the Middle](https://arxiv.org/abs/2307.03172)). [RULER](https://arxiv.org/abs/2404.06654)도 실제로 활용할 수 있는 컨텍스트 길이가 작업에 따라 달라지는지 평가합니다. 제한 없이 기록을 쌓으면 토큰 비용뿐 아니라 작업 정확도에도 영향을 줄 수 있으므로 직접 만든 에이전트에서 확인하세요. ## 4. 요금이 부과되는 토큰 유형 | 항목 | 설명 | 중요한 이유 | |------|------|-------------| | 캐시되지 않은 입력 토큰 | 처음부터 처리한 입력 | 입력 정가 적용 | | **캐시된 입력 토큰** | 제공자의 프롬프트 캐시에서 처리한 입력 | 대부분의 제공자가 할인된 요율로 과금 | | 출력 토큰(추론 포함) | 모델이 생성한 모든 내용 | 보통 입력보다 토큰당 단가가 높음 | 요율은 제공자와 모델에 따라 다르고 수시로 바뀝니다. 기사에 나온 비율에 의존하지 말고 사용하는 모델의 최신 가격표를 확인하세요. 요청 한 건의 총비용은 `uncached_in × p_in + cached_in × p_cached + out × p_out`으로 계산하고, 이를 모든 요청에 대해 합산합니다. **비용 절감만이 유일한 목표는 아닙니다.** 최적화할 대상에 따라 살펴볼 지표도 달라집니다. | 목표 | 일반적인 상황 | 지표 | |------|---------------|------| | 비용 | 종량제 또는 크레딧 | 작업당 유형별 토큰, 성공 작업당 비용 | | 처리 용량 | 예약 / 프로비저닝 처리량, 속도 제한 | 요청당 분당 토큰, 사용률, 동시 처리 사용자 수 | | 지연 시간 | 대화형 사용 | 호출당 입력 토큰, 첫 토큰까지의 시간, p95 종단 간 시간 | 입력 토큰을 줄이면 대체로 세 가지 목표 모두에 도움이 됩니다. 캐싱은 사용하는 배포 유형에서 제공자가 캐시된 토큰을 유리하게 계산하는 경우에만 비용과 처리 용량을 개선합니다. 5절의 점검 목록을 확인하세요. ### 언어별 토큰 계산 방식과 차이 (tiktoken) 모델은 글자나 단어 수를 그대로 세지 않습니다. OpenAI의 [`tiktoken`](https://github.com/openai/tiktoken)처럼 **바이트 페어 인코딩(BPE)**을 사용하는 토크나이저로 UTF-8 바이트를 단어보다 작은 조각으로 나눕니다. `o200k_base`는 GPT-4o, GPT-4.1, GPT-5, o-series에서, `cl100k_base`는 GPT-4와 GPT-3.5에서 사용합니다. BPE 어휘는 주로 영어와 소스 코드로 학습되므로 같은 뜻이라도 언어에 따라 토큰 수가 달라집니다. 다음은 `examples/count_tokens.py`와 `tiktoken` 0.14.0으로 측정한 결과입니다. | 언어 | 예문 | 글자 수 | UTF-8 바이트 | `o200k_base` 토큰 | `cl100k_base` 토큰 | |------|------|--------:|-------------:|------------------:|-------------------:| | 영어 | I met a huge dog | 16 | 16 | **5** (1.0×) | **5** (1.0×) | | 스페인어 | Conocí a un perro enorme | 24 | 25 | **7** (1.4×) | **8** (1.6×) | | 한국어 | 나는 커다란 개를 만났다 | 13 | 35 | **8** (1.6×) | **13** (2.6×) | | 일본어 | 大きな犬に出会った | 9 | 27 | **8** (1.6×) | **11** (2.2×) | | 중국어 | 我遇見了一隻大狗 | 8 | 24 | **8** (1.6×) | **12** (2.4×) |
English (5 tokens) I ·met ·a ·huge ·dog
한국어 o200k_base (8 tokens) 나는 ·커 다 란 ·개 를 ·만 났다
한국어 cl100k_base (13 tokens) 나 는 ·커[1/2] 커[2/2] 다 란[1/2] 란[2/2] ·개 를 ·만 났[1/2] 났[2/2] 다
그림 2. tiktoken에서 같은 의미의 문장이 토큰 조각으로 나뉘는 실제 결과(·는 앞 공백 포함). cl100k_base에서는 커, 란, 났 같은 음절이 UTF-8 바이트 조각 2개로 쪼개져 13토큰이 되지만, o200k_base에서는 자주 쓰이는 한국어 음절·단어가 병합되어 8토큰으로 줄어듭니다. 출처: openai/tiktoken, OpenAI Tokenizer, examples/count_tokens.py.
에이전트를 만들 때 다음 세 가지를 고려하세요. 1. **글자 수가 적다고 토큰 수도 적은 것은 아닙니다.** 위 예문에서 한국어, 일본어, 중국어는 영어보다 글자 수가 적지만, 한 음절이나 한자는 UTF-8에서 2~3바이트를 차지하고 여러 토큰으로 나뉘기도 합니다. 2. **모델에 맞는 토크나이저 인코딩을 선택하세요.** 위 예문에서 새로운 어휘인 `o200k_base`는 `cl100k_base`보다 비영어 텍스트의 토큰 배율을 크게 줄였습니다. 한국어는 `2.6× → 1.6×`로 달라졌습니다. `tokprof`로 로컬에서 측정할 때도 모델에 맞는 인코딩을 지정하세요(예: `tokprof --tokenizer o200k_base`). 3. **반복되는 접두부에는 영어 또는 BPE에 유리한 표기를 고려하세요.** 시스템 프롬프트, 기본 규칙, 도구 설명은 호출마다 다시 전송되므로 언어에 따른 토큰 차이도 `tokens × calls`만큼 누적됩니다. 자세한 프롬프트 작성 방법은 [언어와 토큰화](../../copilot-tokenomics/07-language-and-tokenization/)를 참고하세요. ## 5. 프롬프트 캐싱 제공자는 최근에 처리한 요청과 **앞부분이 가장 길게 일치하는 접두부**를 재사용할 수 있습니다. 캐시가 적중하려면 요청의 시작 부분이 *완전히 동일*해야 합니다. 지침 순서를 바꾸거나 도구 목록을 수정하거나 기록을 다시 쓰면, 달라진 지점부터는 캐시를 재사용할 수 없습니다. 동작은 제공자, 모델, 배포 유형에 따라 다르며 모델을 바꾸면 이전 모델의 캐시를 재사용하지 못합니다. 설계할 때는 **고정된 내용을 앞에 두고, 바뀌는 내용을 뒤에 두며, 기록은 기존 내용을 수정하지 않고 추가**하세요. 직접 개발한 에이전트에서는 [`tokprof`](../01-diagnose/#코드-변경-없이-프로파일링하기-tokprof)로 호출별 `cached_tokens` 비중과 시스템 프롬프트 해시 변동을 확인할 수 있습니다. 제공자의 공식 안내와 가격표도 참고하세요. [Azure OpenAI](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching), [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching), [Anthropic Claude](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), [Google Gemini](https://ai.google.dev/gemini-api/docs/caching), [Azure OpenAI 요금](https://azure.microsoft.com/ko-kr/pricing/details/cognitive-services/openai-service/).
정적 접두부 유지
✓ CACHE HIT: System + Tools + 이전 기록 (≥ 1,024 tok 동일)
신규 턴
적중 (할인)
앞부분 변경 발생
일치
✗ CACHE MISS: 동적 시각·도구 순서 변경 지점부터 전체 재계산
미적중 (정가)
그림 3. 요청 앞부분의 접두부(최소 1,024토큰 이상)가 완전히 동일할 때만 프롬프트 캐시가 적중하며, 앞쪽에 동적 값(현재 시각, 순서가 바뀐 도구 목록 등)이 들어가면 그 지점부터 캐시가 무효화됩니다. 참조: Azure OpenAI 프롬프트 캐싱, OpenAI Prompt Caching, SGLang RadixAttention (NeurIPS 2023).
### 제공자 캐싱: 확인할 사항 캐싱 규칙은 제공자, 모델 계열, 배포 유형에 따라 다르고 수시로 바뀝니다. 캐싱을 전제로 설계하기 전에 다음 질문의 답을 공식 문서에서 확인해 기록하세요. 오른쪽 열은 주로 [Azure OpenAI](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching)와 [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching)의 문서를 2026-11-03 기준으로 정리한 것입니다. 실제 사용하는 모델의 조건은 다시 확인하세요. | 질문 | 중요한 이유 | 문서 내용(2026-11-03 기준) | |------|-------------|----------------------------| | 캐시할 수 있는 최소 접두부 길이는? | 짧은 프롬프트(가드레일, 소형 분류기, 요약기)는 캐시되지 않을 수 있음 | [Azure OpenAI](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching): 요청이 1,024토큰 이상이어야 하고 처음 1,024토큰이 동일해야 하며, 이후 128토큰 단위로 일치 여부를 확인합니다. [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): GPT-5.6 이상은 최소 1,024토큰이며 이전 모델은 기준이 다릅니다. [Anthropic Claude](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): Claude 모델에 따라 1,024~4,096토큰입니다. [Google Gemini](https://ai.google.dev/gemini-api/docs/caching)도 모델별 조건을 확인하세요. | | 어떤 모델과 보존 정책을 지원하나요? | 모델이나 확장 보존 지원 여부에 따라 계획이 달라짐 | [Azure OpenAI 지원 모델](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching#supported-models): GPT-4o 이상에서 인메모리 보존을 지원합니다. 확장 보존은 목록에 있는 일부 모델에서만 지원하므로 `mini` 변형을 포함해 정확한 모델을 확인하세요. | | 적중 여부는 어디에서 확인하나요? | 적중 여부를 확인할 수 있어야 최적화할 수 있음 | [Azure chat completions](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching): `usage.prompt_tokens_details.cached_tokens`에서 확인합니다. 0이면 미적중입니다. GPT-5.6 이상 Standard 배포에서는 `cache_write_tokens`도 제공합니다. | | 캐시 키가 도움이 되나요? | 관련 요청을 함께 라우팅하면 적중률이 높아짐 | [Azure / OpenAI (`prompt_cache_key`)](https://developers.openai.com/api/docs/guides/prompt-caching): GPT-5.6 이상에서는 공유 접두부마다 `prompt_cache_key` 하나를 재사용합니다. 하나의 접두부와 키 조합에서 분당 약 15개 요청을 넘으면 일부 요청이 미적중할 수 있으므로 일정한 매핑 규칙으로 여러 키에 분산하세요. | | 얼마 동안 보관되나요? | 사용하지 않는 동안 캐시가 유지되는지 판단 | [Azure OpenAI 보존 기간](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching): 인메모리 캐시는 보통 5~10분 동안 사용하지 않으면 삭제되며, 최대 1시간 이내에는 항상 삭제됩니다. 확장 보존은 최대 24시간이며 키/값 텐서를 GPU 로컬 저장소로 옮깁니다. GPT-5.6 이상에서는 정책 필드가 사용 중단되고 최소 30분 수명이 적용됩니다. | | 과금과 집계는 어떻게 이루어지나요? | 캐싱으로 비용, 처리 용량 또는 둘 다 절약할 수 있는지 판단 | [Azure OpenAI 요금](https://azure.microsoft.com/ko-kr/pricing/details/cognitive-services/openai-service/): Standard에서는 캐시 읽기에 할인이 적용되고, Provisioned 배포에서는 입력을 최대 100% 할인합니다. GPT-5.6 이상에서는 캐시 쓰기에 요금이 부과될 수 있습니다. [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): 가격은 모델마다 다릅니다. 캐시된 토큰이 처리 용량 사용률에 어떻게 반영되는지도 확인하세요. | | 무엇을 어디에 저장하나요? | 보안과 데이터 보관 위치 검토 | [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching): 캐시에는 원문 텍스트가 아닌 키/값 텐서를 저장합니다. [Azure OpenAI](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching): 구독 간에 캐시를 공유하지 않으며, 확장 보존 데이터는 배포 유형의 지역 또는 데이터 영역 경계 안에 유지됩니다. | | 비활성화하거나 삭제할 수 있나요? | 일부 규정 준수 상황에서 필요 | [Azure OpenAI](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching): GPT-5.6 이상 Standard 배포에서는 중단점 없이 `explicit` 모드를 사용하면 캐싱이 비활성화됩니다. 이전 모델과 관리형 프로비저닝 배포에서는 비활성화할 수 없습니다. | 캐시할 수 없을 만큼 짧은 프롬프트라면 설계를 점검해 보세요. 해당 단계를 인접한 단계와 합치거나, 일반 코드(규칙 기반 검사)로 처리하거나, 작은 비용을 그대로 받아들일 수 있습니다. 캐시 기준을 맞추려고 의미 없는 토큰을 추가하지 마세요. ## 6. 도구가 발생시키는 두 가지 토큰 비용 1. **정의 비용**: 활성화한 모든 도구의 스키마는 실제 사용 여부와 관계없이 매 요청의 접두부에 포함됩니다. 2. **결과 비용**: 도구가 반환한 내용은 기록에 추가되어 이후 단계에서 다시 전송됩니다. 사용하지 않는 도구를 제외하는 **도구 가지치기**로 첫 번째 비용을 줄일 수 있습니다. 결과를 잘라 내거나 페이지로 나누거나 요약하면 두 번째 비용을 줄일 수 있습니다. ## 7. 품질이 뒷받침되지 않는 비용 절감은 의미가 없습니다 비용이 적게 들더라도 작업에 실패했다면 절감이라고 볼 수 없습니다. **성공 작업당 비용**을 추적하세요. 긴 루프에서는 단계별 오류가 누적되므로([입증](../03-prove/#multi-step-reliability)의 표 참조), 루프를 줄이면 성공률을 높이면서 비용도 줄일 수 있습니다. ## 8. 핵심 개념과 낭비 원인 연결하기 | 개념 | 발생하는 낭비 | 진단할 위치 | |------|---------------|-------------| | stateless 재전송, 큰 접두부 | 고정 오버헤드, 프로젝트 정보를 반복해서 다시 파악 | [진단](../01-diagnose/), [원인 분리](../02-isolate/) | | 도구 정의 비용 | 사용하지 않는 도구 | [원인 분리](../02-isolate/) | | 도구 결과 비용 | 과도하게 큰 출력 | [개선](../04-improve/) | | 루프에 따른 비용 증가 | 실패 루프, 재시도 | [입증](../03-prove/) | | 기록 누적 | 기록 증가, 긴 문맥에서의 성능 저하 | [개선: 컨텍스트 압축](../04-improve/#compaction-without-losing-the-cache) | | 캐시 접두부 규칙 | 접두부 변경, 캐시 미적중 | [진단](../01-diagnose/) | | 출력 요금, 추론 | 장황한 출력, 과도한 추론 강도 | [개선](../04-improve/) | ## 적용 예시 합성 로그 [`sample-requests.jsonl`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-requests.jsonl)에서 세션 `s1`의 첫 요청은 입력 토큰 9,200개를 사용합니다. 도구 정의 네 개를 합치면 220 + 180 + 900 + 1,100 = **2,400토큰(해당 요청의 약 26%)**이며, 그중 두 도구는 한 번도 호출되지 않습니다. 두 번째 요청부터는 입력 토큰 9,600개 중 9,000개를 캐시에서 처리합니다. *접두부가 동일하게 유지되었기 때문*입니다. 세션 도중 도구를 제거하거나 지침 순서를 바꾸면 적중률이 떨어집니다. 이 로그에서 접두부의 고정 비용, 도구 정의 비용, 캐싱이라는 세 가지 개념을 확인할 수 있습니다. ## 다음 단계 [1. 진단](../01-diagnose/)에서 측정을 시작하세요. ## 추가 자료(논문) 학회 등급과 인용 수 순으로 정렬했습니다. 논문의 결과는 가설로 보고 자신의 워크로드에서 검증하세요. 전체 목록은 [논문](../../papers/)에서 볼 수 있습니다. - [ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629) — ICLR 2022, 인용 13,383회. 추론과 도구 사용을 번갈아 수행하는 방식으로, 이 가이드에서 비용을 분석하는 에이전트 루프에 해당합니다. - [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) — SOSP 2023, 인용 9,724회. PagedAttention으로 KV 캐시 메모리를 관리해 서빙 처리량을 높이며, vLLM의 기반입니다. - [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) — TACL 2023, 인용 5,818회. 관련 정보가 긴 입력의 중간에 있으면 정확도가 떨어집니다. - [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) — NeurIPS 2023, 인용 1,783회. RadixAttention으로 접두부를 공유하는 호출 간에 KV 캐시를 재사용하며, 접두부 캐싱의 토대입니다. - [RULER: What's the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) — 프리프린트 2024, 인용 1,580회. 실제로 유효한 컨텍스트 길이가 공시된 윈도우보다 짧은 경우가 많음을 보여 주는 벤치마크입니다. ## 출처 - [Lost in the Middle (arXiv:2307.03172)](https://arxiv.org/abs/2307.03172) - [openai/tiktoken — OpenAI 모델용 BPE 토크나이저](https://github.com/openai/tiktoken), [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py) - [Azure OpenAI 프롬프트 캐싱](https://learn.microsoft.com/ko-kr/azure/ai-foundry/openai/how-to/prompt-caching), [Azure OpenAI 요금](https://azure.microsoft.com/ko-kr/pricing/details/cognitive-services/openai-service/) - [OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching), [Anthropic Claude](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), [Google Gemini](https://ai.google.dev/gemini-api/docs/caching)의 프롬프트 캐싱 안내 - [TokenEconomizer](https://github.com/microsoft/TokenEconomizer): 지침, 활성화된 도구, 대화 기록을 요청마다 함께 전송하면서 발생하는 비용을 설명합니다. --- ## 1. 현재 상태 진단 (ko/agent-tokenomics/01-diagnose.md) Canonical URL: > LLM 에이전트 토큰 이코노믹스 1단계(진단): 요청별 입력·캐시·출력·추론 토큰, 첫 호출 고정 오버헤드, 턴별 컨텍스트 증가 곡선을 측정합니다. **목표:** 신뢰할 수 있는 기준선을 확보합니다. 아직 최적화하지 마세요. ## 증상 - 청구액이나 토큰 수가 예상보다 많거나, 사용량 증가 속도보다 빠르게 늘어납니다. - 세션이 길어질수록 느려집니다. - 비슷한 작업인데 비용이 크게 다릅니다. ## 요청 로그 수집 모델 호출마다 한 건씩 기록해야 합니다(필드는 [인덱스](../) 참조). 로그를 얻는 방법은 네 가지입니다. 1. **공급자 사용량 필드** — API 응답마다 반환되는 `usage` 객체(입력, 캐시된 입력, 출력, 추론 토큰)를 기록합니다. 2. **트레이싱 SDK / OpenTelemetry** — 에이전트를 계측해 모델 호출과 도구 호출을 각각 스팬으로 남깁니다. 3. **게이트웨이 / 프록시** — 모델 트래픽을 모든 요청을 기록하는 게이트웨이로 라우팅합니다. 4. **코드 수정 없는 프로파일러** — [`tokprof`](#코드-수정-없이-프로파일링하기-tokprof)는 기존 에이전트를 로컬 게이트웨이 아래에서 실행하고, 호출마다 입력 토큰을 시스템 프롬프트, 이력, 사용자 프롬프트, 도구 항목으로 분해합니다. 아래 플랫폼은 직접 만들거나 운영하는 에이전트에서 2번과 3번 방식을 지원합니다. 하나만 선택하고, 같은 트래픽에 여러 개를 겹쳐 쓰지 마세요. | 플랫폼 | 방식 | 적합한 용도 | 링크 | |--------|------|-------------|------| | **Arize Phoenix** | 트레이싱(OpenTelemetry / OpenInference), 자체 호스팅 가능(라이선스 확인 필요) | 모델, 검색, 도구 호출의 단계별 트레이스를 보고, 평가와 프롬프트 실험을 한곳에서 수행 | [문서](https://arize.com/docs/phoenix), [저장소](https://github.com/Arize-ai/phoenix) | | **Langfuse** | 트레이싱 SDK 및 통합, 오픈 소스, 자체 호스팅 또는 클라우드 | 생성 단위의 사용량과 유형별(입력, 출력, 캐시 등) 비용, 비용 대시보드, 알림, Metrics API | [토큰 및 비용 추적](https://langfuse.com/docs/observability/features/token-and-cost-tracking), [저장소](https://github.com/langfuse/langfuse) | | **LangSmith** | 트레이싱(LangChain의 호스팅 플랫폼) | 트레이스별 토큰 및 비용 내역(캐시 읽기를 포함한 입력, 추론을 포함한 출력), 프로젝트 통계와 대시보드 | [비용 추적](https://docs.langchain.com/langsmith/cost-tracking) | | **Helicone** | 게이트웨이 / 프록시(OpenAI 호환) | 최소한의 코드 변경으로 모든 요청 기록, 공급자 간 대체 경로 | [빠른 시작](https://docs.helicone.ai/getting-started/quick-start), [저장소](https://github.com/Helicone/helicone) | | **Portkey** | 게이트웨이(통합 API) 및 관측 기능 | 여러 모델을 하나의 인터페이스로 사용하면서 모니터링, 제어, 가드레일 적용 | [문서](https://portkey.ai/docs/introduction/what-is-portkey), [저장소](https://github.com/Portkey-AI/gateway) | 선택 기준은 다음과 같습니다. - **트레이싱**은 실행의 *구조*(어떤 단계, 어떤 도구, 중첩 관계)를 보여 주므로 루프와 과도하게 큰 도구 출력을 분리하는 데 가장 적합합니다. 코드나 프레임워크에 계측을 추가해야 합니다. - **게이트웨이**는 추가하기 가장 쉽고(기본 URL만 변경) 모든 호출을 볼 수 있습니다. 하지만 모델 트래픽만 볼 수 있고 호출 사이에 일어난 일은 볼 수 없으며, 프롬프트가 지나가는 경로 위에 위치합니다. - 각 제품의 최신 라이선스, 호스팅 옵션, 가격, 데이터 보존 정책을 확인하고, 필요한 **캐시된 토큰과 추론 토큰** 필드를 기록하는지도 확인하세요. 기능은 바뀔 수 있으므로 도입하기 전에 검증하세요. - 프롬프트와 도구 결과에는 비공개 코드나 데이터가 포함되는 경우가 많습니다. 프로덕션 트래픽을 보내기 전에 **마스킹 / 샘플링**을 설정하고 데이터 처리 약관을 검토하세요. - 모델 가격표를 내장한 도구는 비용을 대신 계산해 주지만 가격이 최신이 아닐 수 있습니다. 금액은 추정치로 보고 **토큰 수**를 기본 지표로 유지하세요. 이 중 어느 플랫폼에서든 [`token_report.py`](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples)를 사용하려면, 플랫폼의 데이터를 내보내거나 쿼리한 다음 JSONL 필드(`session`, `turn`, `input_tokens`, `cached_input_tokens`, `output_tokens`, `tool_defs`, `tool_calls`)에 매핑하세요. **JSONL 스키마 두 가지:** `.tokprof/*.jsonl`에는 세그먼트별 토큰 추정치, 솔트가 적용된 해시, 비밀값을 마스킹한 프롬프트·응답 텍스트를 담은 `tokprof`의 상세 `v: 1` 레코드가 저장됩니다. `--no-content`를 지정하면 텍스트는 저장하지 않습니다. 반면 `examples/sample-requests.jsonl`은 `examples/token_report.py`가 읽는 간결한 요약 스키마를 사용합니다. 해당 스크립트에 기록을 전달하기 전에 변환하세요. ```bash tokprof export run.jsonl --out legacy.jsonl ``` 마스킹만으로 공유 안전이 보장되지는 않으므로 로그를 먼저 검토하세요. VS Code에서 GitHub Copilot을 사용하나요? 위 플랫폼은 Copilot을 계측하지 않습니다. [Agent Debug Logs와 Cache Explorer](../../copilot-tokenomics/02-measure-usage/)를 사용하세요. ## 코드 수정 없이 프로파일링하기: tokprof [`tokprof`](../tokprof/)([PyPI](https://pypi.org/project/tokprof/), 독립 실행형 네이티브 Rust 단일 바이너리, 에이전트 프로젝트에 의존하지 않음)는 이 도구로 시작하거나 연결한 에이전트에 대해 "각 요청에서 어느 부분이 토큰을 쓰는가"에 답합니다. ```bash pip install tokprof # 또는: uv tool install tokprof / uvx tokprof / pipx install tokprof tokprof --lang ko # 상세 사용 가이드 및 예시 출력 (--lang ko | --lang en) tokprof start # 백그라운드 프로파일링 시작 (Linux: 실행 중인 프로세스 및 Docker 자동 수집) tokprof stop # 세션 종료 + 시각적 리포트 출력 + .tokprof/latest.html 생성 tokprof -- python my_agent.py # 단일 명령 실행: 프로파일링 + 시각적 터미널 리포트 + .tokprof/latest.html 생성 tokprof report --format pretty --html --csv # 가장 최근 실행을 요약하고 단일 파일 HTML 대시보드 및 CSV 파일을 생성합니다 tokprof report --format csv # 세션별·턴별·호출별 분해 및 프롬프트 원문을 CSV로 표준 출력합니다 tokprof report --watch # 에이전트 실행 중 실시간으로 터미널 리포트를 갱신합니다 tokprof compare before.jsonl after.jsonl # 부트스트랩 구간, 3단계와 5단계용 ``` 모든 캡처 방식과 CLI 명령어, 사내·온프레미스 엔드포인트 설정은 [tokprof: 설치 및 사용법 가이드](../tokprof/)를 참고하세요. - **수집 방식**: `tokprof start`는 백그라운드 세션을 시작하며, Linux에서는 실행 중인 호스트 프로세스와 Docker 컨테이너에 eBPF 프로브를 자동으로 연결합니다(`tokprof start --comm <이름>`으로 프로세스·작업 디렉터리·컨테이너 이름별 필터링 가능). 작업 후 `tokprof stop`을 실행하면 세션을 멈추고 시각적 리포트와 `.tokprof/latest.html`을 바로 생성합니다. `tokprof run`은 `127.0.0.1`에 게이트웨이를 띄우고, **해당 명령에서만** `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `AZURE_OPENAI_ENDPOINT`와 패턴으로 찾은 기본 URL 변수(`VLLM_BASE_URL`, `OLLAMA_HOST` 등)를 그곳으로 향하게 하며, 프로세스 내부 훅(`sitecustomize`를 통한 Python `httpx`, `requests`, `urllib3`, `aiohttp`, `urllib.request`와 `--require`를 통한 Node `fetch`, `http.request`, `https.request`)도 함께 로드합니다. - **LLM 호출로 인식하는 기준**: 고정된 URL 목록이 아닙니다. `tokprof`는 요청 본문의 형태(`messages` 목록, Gemini `contents`, Responses 방식의 `input`, `prompt`), 경로, 호스트(사설 DNS, RFC 1918, `.svc.cluster.local`, `privatelink`, `vllm`·`ollama` 같은 이름, 관례적인 포트), 그리고 모호한 본문에 대해서는 응답(사용량 카운터, `choices`, Ollama·llama.cpp·TGI 카운터)을 함께 점수화합니다. 그래서 사설 DNS 엔드포인트, 온프레미스 vLLM, Ollama, TGI, llama.cpp, LiteLLM 방식 게이트웨이, Azure 프라이빗 엔드포인트, Gemini를 모두 인식합니다. `tokprof explain --body request.json`은 요청이 기록되었거나 기록되지 않은 이유를 보여 주고, `--llm-host`, `--llm-path`, `--exclude-host`로 판정을 직접 지정할 수 있습니다. 사설 CA는 `SSL_CERT_FILE` 또는 `--upstream-ca`로 신뢰합니다. - **확인할 수 있는 정보**: 세션별·턴별·호출별로 구분된 시스템 프롬프트(구간별), 대화 이력(History), 현재 사용자 프롬프트(`utterance`, `context`/`history`, `capabilities`가 담긴 구조화 JSON 페이로드 자동 분해 포함), 도구 정의·호출·결과 및 응답 스키마별 입력 토큰과 실제 프롬프트·응답 원문 내용, 고정 오버헤드, 단계별 토큰 지도, 요청당 호출 수, 사용되지 않는 도구, 반복되는 정적 블록, 실패 루프(동일 도구 호출 반복 및 에러 재시도), 프롬프트 캐시 깨짐(동적 값 삽입으로 시스템 프롬프트 해시가 매번 바뀌는 현상), 대화 이력 급증입니다. 터미널(`pretty`, `text`, `--full-prompts`), CSV(`--format csv` / `--csv`), Markdown, JSON 및 외부 의존성 없는 단일 파일 HTML 대시보드(`--html`)로 출력합니다. 인자 없이 `tokprof`를 실행하면 상세 설명과 예시를 보여 줍니다(`--lang ko` 또는 `--lang en`). - **저장하는 정보**: 토큰 수, 솔트 해시, 길이, 구간·도구 이름 및 시크릿이 마스킹된 프롬프트·응답 원문입니다(원문을 제외하려면 `--no-content` 사용). HTTP 헤더나 API 키는 저장하지 않습니다. - **정확도**: 제공자는 합계만 알려 주므로 구간별 수치는 로컬 추정치이고 나머지는 *미분류*로 표시됩니다. OpenAI 계열 모델은 `tiktoken`을 설치하세요. 분해 결과를 믿기 전에 잔차를 확인하세요. - **이미 실행 중인 프로세스(Linux)**: `tokprof ebpf --pid `는 프로세스의 TLS 라이브러리(OpenSSL 및 Go `crypto/tls`)와 시스템 콜 트레이스포인트에 eBPF 프로브를 연결해, 재시작이나 변경 없이 LLM 호출을 기록하며, 온프레미스 서버로 가는 평문 `http://` 및 `h2c` 호출도 포함합니다. root 또는 `CAP_BPF` 권한이 필요하며, 관찰을 시작한 뒤 열린 HTTP/1.1과 HTTP/2 연결을 따라갑니다. 자세한 내용은 [profiler README](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler#linux-ebpf-tap-running-processes-no-restart-no-code-change)를 참고하세요. - **현재 한계**: eBPF 관찰을 제외하면 `tokprof`로 시작한 프로세스만 수집합니다. 기본 URL 환경 변수를 따르지 않으면서 `httpx`, `requests`, `urllib3`, `aiohttp`, `urllib.request`, Node `fetch`, Node `http`/`https` 중 어느 것도 쓰지 않는 클라이언트는 `tokprof run`으로 수집되지 않습니다. Windows와 macOS에서는 `tokprof mitm --local <프로세스>`가 mitmproxy의 로컬 캡처를 사용합니다(관리자 권한과 mitmproxy CA 신뢰가 필요합니다). ## 점검 항목 로그에 예제 스크립트를 실행합니다. ```bash python examples/token_report.py requests.jsonl ``` 기준선을 위해 다음 항목을 기록합니다. | 지표 | 확인 방법 | 중요한 이유 | |------|-----------|-------------| | 요청당 입력 / 캐시된 입력 / 출력 토큰 | 제공자 사용량 필드 | 보통 입력이 대부분이며 캐시된 입력은 더 저렴함 | | **캐시 적중률(%)** | 캐시된 입력 ÷ 입력 | 접두부가 고정인데 적중률이 낮으면 접두부 변동을 의심 | | **고정 오버헤드** | 세션에서 *첫 번째* 요청의 입력 토큰 | 시스템 프롬프트 + 지침 + 도구 정의로, 요청마다 비용 발생 | | **사용자 요청당 LLM 호출 수(팬아웃)** | 요청 ID나 트레이스 ID가 같은 모델 호출 수 | 질문 하나가 여러 호출을 일으킬 수 있으며, 호출마다 자체 프롬프트를 포함 | | **단계별 토큰 지도** | 단계마다 모델, 호출 수, 호출당 고정 토큰, 동적 토큰 | 어떤 단계와 구성 요소가 비용을 좌우하는지 확인(아래 참조) | | **커버리지** | 같은 기간 동안 기록된 토큰 합계와 제공자가 청구하거나 모니터링한 토큰 비교 | 차이가 있으면 계측되지 않은 호출(하위 서비스, 임베딩, 백그라운드 작업)이 있음 | | **도구 정의 토큰** | 전송한 도구 스키마의 합계 | 사용 여부와 관계없이 매 요청마다 지불 | | **컨텍스트 증가 곡선** | 요청 순번별 입력 토큰 | 가파른 증가는 기록이나 도구 출력이 누적되고 있다는 뜻 | | **도구별 도구 출력 토큰** | 각 도구 결과가 추가하는 토큰 | 과도하게 큰 결과(대용량 파일 읽기, 장황한 로그)를 찾음 | | **기록 대비 도구 출력 비중** | 요청마다 증가분을 *대화 텍스트*와 *도구 결과*로 분리 | 기록 요약이 효과가 있는지 판단. 도구 결과가 더 큰 비중인 경우가 많음 | | **턴당 재시도 / 오류** | 도구 호출 오류 시그니처 | 반복되는 오류는 낭비되는 루프 | | 성공 작업당 비용 | 비용 ÷ 통과한 작업 수 | 궁극적으로 낮추려는 수치 | ## 단계별 토큰 지도 사용자 요청 하나에 모델 호출을 여러 번 실행하는 에이전트라면 요청 유형마다 표를 하나씩 만드세요. 아래는 합성 파이프라인([`examples/sample-pipeline.json`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-pipeline.json))을 기준으로 작성한 단계별 토큰 지도 예시입니다(실제 로그를 수집하면 `호출당 동적 토큰` 열에 검색 구절·대화 기록·도구 결과 평균치를 함께 채웁니다). | 단계 | 모델 | 호출 수 | 호출당 고정 토큰 | 호출당 동적 토큰 | 고정 합계 | 비중 | 비고 | |------|------|--------:|-----------------:|-----------------:|----------:|-----:|------| | `guardrail` | `small` | 1 | 800 | *(로그에서 측정)* | 800 | 1.0% | `< 1,024 tok`: 캐시 미적용 가능성 | | `rewrite` | `small` | 1 | 2,500 | *(로그에서 측정)* | 2,500 | 3.2% | | | `router` | `large` | 1 | 12,000 | *(로그에서 측정)* | 12,000 | 15.2% | 대형 모델 라우팅 오버헤드 | | `classify` | `small` | 1 | 2,000 | *(로그에서 측정)* | 2,000 | 2.5% | | | **`answer`** | **`large`** | **2** | **28,000** | *(로그에서 측정)* | **56,000** | **71.1%** | `reference_doc`(20k) + `rules_and_tools`(8k) × 2회 | | `follow_up` | `small` | 1 | 3,500 | *(로그에서 측정)* | 3,500 | 4.4% | | | `final_reply` | `large` | 1 | 2,000 | *(로그에서 측정)* | 2,000 | 2.5% | | | **합계 (요청 1건당)** | — | **8** | — | — | **78,800** | **100.0%** | 동적 토큰을 제외한 하한값 | **구성 요소**(시스템 프롬프트, 도구 스키마, 출력 스키마, 참조 문서)를 `tokens × calls` 기준으로 순위를 매기세요(`answer/reference_doc`: `20,000 × 2 = 40,000 tok, 50.8%` → `answer/rules_and_tools`: `8,000 × 2 = 16,000 tok, 20.3%` → `router/fixed`: `12,000 × 1 = 12,000 tok, 15.2%`). 상위 한두 개가 대부분의 낭비를 설명하는 경우가 많습니다. ### 프로덕션에 접근할 수 없다면? 정적으로 추정하기 아직 프로덕션 사용량을 읽을 수 없다면, 토크나이저로 코드에서 고정 프롬프트 부분의 토큰 수를 세세요. [`examples/prompt_budget.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/prompt_budget.py)는 단계를 설명하는 작은 JSON(프롬프트 파일 또는 토큰 수, 요청당 호출 수)을 입력받아 토큰 지도를 출력합니다. ```bash python3 examples/prompt_budget.py examples/sample-pipeline.json ``` 결과는 **하한값**으로 취급하세요. 요청마다 새로 들어오는 모든 내용(사용자 데이터, 검색된 구절, 대화 기록, 도구 결과)이 빠져 있으므로 실제 사용량은 더 많습니다. 후보의 순위를 매기는 데 사용하고, 가능한 한 빨리 실제 측정값으로 확인하세요. 보고서에는 수치가 추정치라는 점을 분명히 밝히세요. 또한 고정 프롬프트가 제공자의 최소 캐시 가능 길이보다 짧은 단계도 표시하세요. ## 해석 | 관찰 | 가능성이 높은 방향(2단계에서 검증) | |------|-------------------------------------| | 요청 #1의 오버헤드가 큼 | 큰 지침 또는 도구 카탈로그 | | 요청 사이의 증가가 가파름 | 큰 도구 출력 또는 정리하지 않은 대화 기록(수정 방법을 고르기 전에 기록 대비 도구 출력 비중을 확인) | | 캐시 적중률이 낮음 | 요청 사이에 접두부가 바뀜 | | 한 턴에서 같은 오류 시그니처가 3회 이상 | 실패 루프 | | 출력 토큰이 많음 | 장황한 답변 또는 과도한 추론 강도 | | 참조 문서 하나가 한 단계에서 큰 비중을 차지하거나 그 단계가 두 번 이상 호출됨 | 긴 고정 프롬프트 × 호출 수 | | 사용자 요청당 LLM 호출이 많고, 그중 여러 개가 작은 분류기나 검사임 | 불필요한 파이프라인 단계(팬아웃) | | 기록된 토큰이 청구된 토큰보다 훨씬 적음 | 계측되지 않은 호출: 결론을 신뢰하기 전에 로그에 추가 | | 세션별 목록(메시지, 보고서, 도구 결과)이 계속 늘어나기만 함 | 제한 없는 상태: 잘라내는 로직을 찾고, 없으면 추가 | ## 측정 결과를 안전하게 공유하기 진단에는 벤더, 플랫폼 팀, 고객이 관여하는 경우가 많습니다. 필요한 것만 공유하고 그 이상은 공유하지 마세요. - **공유 후보인 집계 정보:** 집계된 토큰 수, 프롬프트 크기, 호출 수, 적중률, 오류 시그니처 - **공유 전 확인할 정보:** 프롬프트 텍스트, 도구 결과, 검색된 구절, 사용자 또는 고객 데이터, 내부 명칭 - 내보내기 전에 식별자를 마스킹하고 샘플링하거나 집계하세요. 로그와 트레이스 플랫폼은 전송한 내용을 그대로 저장한다는 점을 기억하세요. - 누가 무엇을 결정할지 미리 합의하세요. 플랫폼 또는 벤더 팀은 구조와 설정을 제안하고, 도메인 책임자는 요약 후에도 남겨야 할 사실을 결정하며, 보안 책임자는 보존 또는 데이터 처리 변경을 승인합니다.
입력 구성
100%
설명용 구성: 시스템 프롬프트 61.4%, 도구 정의 23.0%, 도구 결과 6.3%, 대화 기록과 사용자 입력 9.3%. 샘플 로그의 7개 요청에서 도구 정의는 16,800 / 73,000 입력 토큰으로 23.0%입니다. 나머지 구간은 로그에 기록되지 않아 실제 분해 결과가 아닌 가상의 값입니다. tokprof의 구간별 추정과 token_report.py의 집계를 참고하세요.
## 적용 예시 샘플 로그에서 `s1`은 첫 요청의 오버헤드가 9,200토큰이며, 그중 도구 정의 두 개(`notebook_edit`, `browser_open`)에 해당하는 도구는 한 번도 호출되지 않습니다. `s1`의 턴 1에는 동일한 `pytest: command not found` 오류가 세 번 있습니다. 파이프라인의 경우 합성 파일 [`sample-pipeline.json`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-pipeline.json)에 정적 추정을 실행합니다(설명용으로 만든 가상의 수치). 요청당 LLM 호출은 8회이고 고정 토큰은 약 78,800개입니다. 답변 단계(두 번 호출됨)에 첨부된 참조 문서 하나가 전체 고정 토큰의 약 절반을 차지하며, 가드레일 단계는 1,024토큰 미만이라 캐시되지 않을 가능성이 높습니다. 표 하나만으로도 어디부터 살펴봐야 하는지 알 수 있습니다. ## 다음 단계 가장 **큰** 의심 신호를 골라 [2. 원인 분리](../02-isolate/)로 이동하세요. --- ## 2. 문제 분리 (ko/agent-tokenomics/02-isolate.md) Canonical URL: > LLM 에이전트 토큰 이코노믹스 2단계(분리): 미사용 도구, 실패 루프, 과대한 도구 출력, 대화 기록 누적 중 비용 원인을 변수 하나씩 좁힙니다. **목표:** "비용이 많이 든다"는 막연한 상태를 검증 가능한 하나의 구체적인 원인으로 좁힙니다. ## 원인 범주 | 범주 | 진단에서 나타나는 신호 | 분리 실험 | |------|------------------------|-----------| | **저장소 정보 반복 탐색** | 많은 세션의 시작 부분에서 같은 탐색 호출과 같은 수정된 명령이 반복됨 | 세션 간에 동일한 초기 도구 호출 수를 셉니다 | | **사용하지 않는 도구** | 한 번도 호출되지 않는데 요청마다 전송되는 도구 정의 | 사용하지 않는 도구별로 `definition tokens × requests`를 계산합니다 | | **실패 루프** | 한 턴에서 같은 오류 시그니처가 반복됨 | 턴당 반복 횟수를 세고 대화 기록을 읽습니다 | | **비대한 도구 출력** | 몇 개의 도구가 도구 출력 토큰의 대부분을 차지함 | 출력 토큰 기준으로 도구 순위를 매기고 가장 큰 결과를 살펴봅니다 | | **기록 증가** | 새 정보는 적은데 입력이 가파르게 증가하고, 도구 결과가 아닌 대화 텍스트가 더 큰 비중을 차지함 | 기록을 잘라내거나 요약한 상태로 세션을 재생하고, 캐시 적중률이 급락하지 않는지 확인합니다 | | **접두부 변동(캐시 미스)** | 낮은 캐시 적중률 | 연속된 요청을 비교(diff)해 처음으로 달라지는 지점을 찾습니다 | | **과도하게 큰 모델 / 강도** | 쉬운 단계에서도 가장 큰 모델을 사용함 | 해당 단계를 더 작은 모델로 다시 실행합니다 | | **재시도와 재작업** | 승인된 변경 하나당 도구 호출이 많음 | 되돌리거나 다시 작업하며 끝난 턴을 확인합니다 | | **컨텍스트 열화** | 컨텍스트 윈도우가 차기 전에 긴 세션에서 품질이 떨어지고, 앞부분에 준 지침이 무시됨 | 짧은 요약을 담은 새 세션에서 작업을 다시 실행하고 성공 여부를 비교합니다 | | **도구 수 × 단계 수 승수** | 도구 카탈로그가 크고 *동시에* 작업당 단계 수도 많음 | `schema tokens × steps`를 계산하고, 최소한의 도구 집합으로 다시 실행합니다 | | **큰 정적 문서 × 호출 횟수** | 하나의 참조 문서(규칙, 치트 시트, 정책)가 단계의 고정 토큰 중 큰 비중을 차지하며, 그 단계가 두 번 이상 호출됨 | 구성 요소를 `tokens × calls` 기준으로 정렬하고, 관련 있을 때만 문서를 첨부해 다시 실행한 뒤 비교합니다 | | **중복된 파이프라인 단계(팬아웃)** | 사용자 요청 하나에 LLM 호출이 많고, 일부는 작은 점검 또는 분류기임 | 요청 하나를 끝까지 추적하고, 각 단계를 건너뛰거나 합치거나 규칙으로 대체하면 무엇이 달라지는지 따져 봅니다 | | **세션별 무제한 상태** | 내부 메시지, 보고서, 도구 결과가 잘리지 않아 턴이 지날수록 입력이 증가함 | 코드에서 잘라내기나 윈도 처리 로직을 찾고, 상태에 상한을 둔 채 긴 세션을 재생합니다 | | **짧아서 캐시할 수 없는 프롬프트** | 여러 단계의 고정 프롬프트가 공급자의 최소 캐시 가능 길이보다 짧음 | 각 단계의 고정 토큰을 최소 길이와 비교하고, 해당 단계의 `cached_tokens`가 0인지 확인합니다 | | **지나치게 넓은 프롬프트 / 지침** | 에이전트가 넓게 탐색하거나, 지침이 코드에 이미 있는 내용을 반복함 | 범위를 좁힌 프롬프트와 다듬은 지침 파일로 바꾸고, 단계 수와 성공 여부를 비교합니다 | ## 방법 1. 그럴듯해 보이는지가 아니라 (기준선에서 구한) **영향을 받는 추정 토큰 수**를 기준으로 범주의 순위를 매깁니다. 2. 순위가 가장 높은 범주에 대해 **그 변수만** 바꾸는 실험을 설계합니다(예: 사용하지 않는 도구만 제거하고 다른 것은 바꾸지 않습니다). 3. 가설을 숫자를 넣어 한 문장으로 작성합니다. *"사용하지 않는 도구 정의가 요청 7건에 걸쳐 약 14,000 토큰(입력의 19%)을 차지합니다."*
미사용 도구
2,000 토큰/호출
run_tests 3회
28,800 입력 토큰
read_file 출력
4,200 출력 토큰
샘플의 s1 사례입니다. 도구 정의는 호출당, 오류 루프는 오류를 낸 세 호출의 입력 합계, 파일 출력은 한 read_file 결과의 크기이며 필터링 여부는 로그로 확인할 수 없습니다. 단위와 범위가 달라 막대 길이는 비교 기준이 아니며, 28,800은 전부 절약 가능한 양이 아닙니다. 원인이 겹칠 수 있으므로 합산하지 마세요.
### 프롬프트 캐시 무효화 확인 `.tokprof/*.jsonl` 기록에서 **접두부 해시 변동**을 확인하세요. 시스템 프롬프트에 `datetime.now()`, 요청 UUID 또는 순서가 일정하지 않은 딕셔너리 항목을 넣으면 호출마다 `sysfp`가 바뀌어 캐시 재사용을 방해할 수 있습니다. 도구 순서가 일정하지 않아도 요청 접두부가 달라질 수 있지만, `sysfp`는 **시스템 텍스트만** 식별하므로 도구 세그먼트는 별도로 확인하세요. ```bash jq -r '[.conv, .sysfp, .usage.cached] | @tsv' run.jsonl ``` 같은 기록과 대화 안의 호출을 비교하세요. `sysfp`에는 솔트가 적용되며 값이 없을 수도 있습니다. 해시 변동은 캐시 미스의 단서이지 증거는 아닙니다. 캐시 사용량이 제공되지 않을 수도 있고, 공급자의 최소 길이·라우팅·만료 조건도 영향을 줍니다. 변수를 하나만 바꾸기 전에 접두부가 처음 달라지는 지점과 캐시 사용량을 비교하세요. ## 해석 - 기록을 원인으로 지목하기 전에 **도구 출력**부터 배제합니다. 증가분의 대부분이 도구 결과라면, 대화를 요약하는 것보다 도구 결과를 잘라내거나 나누어 제공하는 편이 더 저렴하고 안전합니다. - 두 원인이 겹치면(예: 실패 루프가 기록도 부풀리는 경우) 토큰을 **근본 원인**(루프)에 할당하고 그것부터 처리합니다. - 어떤 범주도 전체 토큰의 약 10%를 넘게 설명하지 못한다면 기준선이 이미 양호할 수 있습니다. 더 최적화하기 전에 *작업* 자체가 그만큼의 컨텍스트를 정말로 필요로 하는지 확인합니다. ## 추가 자료(논문) 학회 등급 순, 같은 등급 안에서는 인용 수 순으로 정렬했습니다. 각 결과는 자신의 워크로드에서 검증해야 할 가설로 취급합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) — NeurIPS 2024, 인용 2,357회. 간결하고 제한된 관찰을 포함한 인터페이스 설계가 에이전트의 성공률을 좌우함을 보여 줍니다. - [Reducing Cost of LLM Agents with Trajectory Reduction](https://arxiv.org/abs/2509.23586) — PACMSE 2025, 인용 68회. 궤적에서 낭비를 덜어 내 에이전트 비용을 줄입니다. - [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) — 프리프린트 2024, 인용 566회. 위치 파악-수정-검증으로 고정된 파이프라인이 SWE-bench Lite에서 개방형 에이전트 루프에 견줄 만한 성능을 낮은 비용으로 달성합니다. - [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) — 프리프린트 2025, 인용 66회. 에이전트 컨텍스트 관리에서 단순한 관찰 마스킹이 LLM 요약만큼 효율적입니다. - [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) — 프리프린트 2025, 인용 40회. 에이전트 시스템 설계에서 효율과 효과 사이의 절충 관계를 체계적으로 연구합니다. ## 다음 단계 [3. 문제 증명](../03-prove/)에서 재현하고 정량화합니다. --- ## 3. 문제 증명 (ko/agent-tokenomics/03-prove.md) Canonical URL: > LLM 에이전트 토큰 이코노믹스 3단계(증명): 고정된 작업 집합에서 반복 실행을 통해 토큰 낭비 규모와 신뢰구간을 정량적으로 입증합니다. **목표:** 반복 가능한 측정으로 가설을 검증합니다. ## 점검 항목 1. **설정 고정:** 모델, 버전, temperature/effort, 프롬프트, 도구 집합, 작업 목록, 환경을 고정합니다. 2. **기준선 실행:** 모든 작업을 **최소 3회** 실행합니다(출력은 비결정적입니다). 작업별로 다음을 기록합니다. 유형별 총 토큰, 비용, 성공 여부(통과/실패), 소요 시간. 3. **대조 실행:** 2단계의 분리 변경 하나만 적용하고(예: 사용하지 않는 도구를 비활성화), 같은 작업 집합과 같은 반복 횟수로 다시 실행합니다. 4. **비교:** 해당 원인으로 추정한 낭비는 총합뿐 아니라 특정 지표(예: 요청 #1의 입력 토큰)의 감소로 나타나야 합니다. ## 증거 기준 | 질문 | 필요한 증거 | |------|-------------| | 원인이 실재하는가? | 그 변수만 바꿨을 때 지표가 움직입니다. | | 규모는 어느 정도인가? | 작업별, 전체별 반복 실행의 평균과 산포. | | 일반적인 현상인가? | 둘 이상의 작업 / 세션 / 저장소에서 나타납니다. | | 제거해도 안전한가? | 대조 실행의 성공률이 노이즈 범위를 넘어 낮아지지 않습니다. | 반복 실행 간 산포가 효과보다 크면 반복 횟수를 늘리거나 더 큰 대상을 선택합니다. ### 비용 측정과 성공률 가드레일의 표본 크기 예를 들어 **가상 사례**에서 고정 접두부가 결정적으로 2,000토큰 줄었다면, 작업당 3–5회 반복으로 토큰 변화량을 확인할 수 있습니다. 단, 관측한 산포가 작아야 하며 변동이 큰 경우에는 더 반복해야 합니다. 이 정도 반복만으로 성공률이 동등하다고 결론 내릴 수는 없습니다. Pass@1의 3–5%p 차이를 살피려면 훨씬 큰 고정 작업 집합을 사용하고 대응 표본의 신뢰구간 또는 검정력 분석을 먼저 계산하세요. 20–50개 이상의 작업은 탐색을 시작하는 규모일 뿐 **충분한 표본이라는 보장은 없습니다**. 작은 차이를 검출하는 데 필요한 작업 수는 대응 결과, 목표 검정력, 동등성 허용 범위에 따라 수백 개 이상일 수도 있습니다. 불확실성을 보고하고 구간이 너무 넓으면 가드레일 판단을 보류하세요([Adding Error Bars to Evals](https://arxiv.org/abs/2411.00640)). ## 요약이나 압축으로 정보가 손실될 수 있을 때 기록을 압축하면 같은 결과를 *보장*할 수 없습니다. 자신의 작업에서 결과가 동등한지 확인해야 합니다. 실험을 실행하기 전에 "동등"의 기준을 정의합니다. 1. **성공 동등성** — 같은 작업에서 충분한 관측치를 확보해 대응 표본의 신뢰구간이 미리 정한 동등성 허용 범위 안에 들어가는지 확인합니다. 그렇지 않으면 판단을 보류합니다. 2. **보존할 정보** — 반드시 남아야 하는 항목(결정 사항, 제약 조건, 파일 경로, 오류 시그니처, 미해결 TODO)을 목록으로 만듭니다. 압축 후 이 목록에 답이 있는 질문을 던지고 정확하게 기억해 낸 횟수를 셉니다. 3. **새로운 재작업 없음** — 작업당 재질문 횟수와 반복 탐색 횟수가 늘지 않습니다. 4. **순비용** — 절약한 입력 토큰에서 요약 호출 비용과 손실된 프롬프트 캐시 재사용분 ([개선](../04-improve/#compaction-without-losing-the-cache) 참고)을 뺀 값이 양수입니다. 정보를 다시 찾아내지 못했을 때 요약이 무엇을 누락했는지 추적할 수 있도록 원본 대화 기록을 보관합니다. ## 구성 요소 수준 평가(라우터, 분류기, 가드레일) 파이프라인에서는 작은 결정 단계(경로 선택, 분류, 허용 또는 차단)가 최종 답변에 영향을 줄 수 있습니다. 이런 단계의 프롬프트나 도구 설명을 줄이는 수정이라면 엔드 투 엔드 성공률과 함께 **구성 요소 수준 평가 집합**으로 증명합니다. 1. 실제와 유사한 형태의 사례에 레이블을 붙인 집합을 만듭니다(보통 수백 건이며, 프로덕션에서 민감 정보를 가려 샘플링합니다). 2. 같은 사례로 변경 전후의 **결정 정확도**와 혼동 행렬을 측정합니다. 3. 실행하기 **전에** 클래스별 최소 허용 정확도를 정합니다(드물지만 비용이 큰 클래스가 평균보다 더 중요합니다). 4. 이 점검 없이 도구 설명이나 출력 스키마를 줄이지 않습니다. 이 둘은 답변 정확도에 영향을 줍니다. 5. 정적 문서를 수정하는 경우에는 총합뿐 아니라 변경 전후의 `tokens × calls`도 함께 보고합니다. ## 다단계 신뢰도 단계별 오류는 누적됩니다. 각 단계가 확률 *p*로 성공하면 *n*단계 실행이 성공할 확률은 (단계가 서로 독립일 때) *pⁿ*입니다. 이는 에이전트를 측정한 값이 아니라 단순한 산술이지만, 긴 루프가 왜 취약한지 보여 줍니다. | 단계 수 | p = 0.95 | p = 0.99 | |--------:|---------:|---------:| | 5 | 0.774 | 0.951 | | 10 | 0.599 | 0.904 | | 20 | 0.358 | 0.818 | | 50 | 0.077 | 0.605 | 증명 시 고려할 점: 총 토큰이 아니라 **성공한 작업당 비용**을 보고합니다. 또한 루프를 *단축하는* 수정 (명확한 완료 기준, 미리 알려 둔 저장소 사실, 줄어든 재시도)은 비용을 줄이면서 성공률도 높일 수 있습니다.
5단계
77%
10단계
60%
20단계
36%
단계마다 독립적으로 p = 0.95의 성공 확률을 가정한 pn의 반올림 값입니다. 실제 에이전트 측정치는 아닙니다.
## 템플릿 ```text Hypothesis: Variable: Tasks / reps: Baseline: tokens= cost=<> success= Counter-run: tokens= cost=<> success= Conclusion: confirmed | rejected | inconclusive (why) ``` ## 적용 예시 샘플에서 "한 턴에 동일한 `pytest: command not found` 오류가 세 번 발생해 피할 수 있는 추가 요청 두 건과 컨텍스트 재전송이 발생한다"는 가설은, 올바른 명령(`python -m pytest`)을 처음부터 알려 준 채 같은 작업을 실행해 증명합니다. 이때 턴당 요청 수가 줄고 성공률은 같게 유지되는지 확인합니다. ## 추가 자료(논문) 학회 등급 순, 같은 등급 안에서는 인용 수 순으로 정렬했습니다. 각 결과는 자신의 워크로드에서 검증해야 할 가설로 취급합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [Evaluating Very Long-Term Conversational Memory of LLM Agents](https://arxiv.org/abs/2402.17753) — ACL 2024, 인용 1,082회. 매우 장기적인 대화 메모리를 평가하는 벤치마크입니다. - [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) — ICLR 2024, 인용 869회. 채팅 어시스턴트의 장기 메모리를 평가하는 벤치마크로, 회상 점검을 설계할 때 유용합니다. - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — TMLR 2024, 인용 289회. 에이전트 평가는 정확도뿐 아니라 비용도 통제해야 한다고 주장합니다. - [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — 프리프린트 2024, 인용 1,669회. 반복 실행에서 에이전트의 신뢰도를 측정하는 pass^k를 도입한 벤치마크입니다. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — 프리프린트 2024, 인용 194회. LLM 평가에서 불확실성을 보고하기 위한 통계적 지침을 제시합니다. - [Non-Determinism of"Deterministic"LLM Settings](https://arxiv.org/abs/2408.04667) — 프리프린트 2024, 인용 159회. 결정적으로 동작하도록 설정한 경우에도 실행마다 출력이 달라짐을 보여 줍니다. ## 다음 단계 가설이 **확인되면** [4. 개선](../04-improve/)으로 이동하세요. --- ## 4. 개선 (ko/agent-tokenomics/04-improve.md) Canonical URL: > LLM 에이전트 토큰 이코노믹스 4단계(개선): 마이크로 스킬, 도구 가지치기, 루프 가드, 도구 출력 축소, 프롬프트 캐싱을 실험당 하나씩 적용합니다. **목표:** 검증된 낭비를 없애는 최소한의 변경을 적용합니다. 실험당 수정은 하나만 적용합니다. ## 수정 카탈로그 | 증명된 원인 | 수정 | 참고 | |-------------|------|------| | 저장소 정보 반복 탐색 | 확인된 짧은 저장소 사실을 세션 시작 부분에 둡니다(지침 파일 또는 제공하는 "마이크로 스킬"). 예: 올바른 테스트 명령, 필요한 환경 변수, 생성된 파일의 위치 | 사실은 적게, 검증된 것만 유지합니다. 이후 세션에서 반박되면 해당 사실을 삭제합니다 | | 사용하지 않는 도구 | 도구 정의를 **가지치기**합니다. 도구를 필요할 때 로드합니다. 서브에이전트에는 좁은 도구 집합을 부여합니다 | 가지치기한 도구를 쉽게 다시 켤 수 있게 합니다 | | 실패 루프 | 한 턴에서 반복되는 동일한 오류를 감지합니다. **한 번** 방향 전환("다른 접근을 시도하세요")을 제안합니다. 그래도 막혀 있으면 사용자에게 중단하는 방법을 알립니다 | 턴을 조용히 종료하지 않습니다. 턴당 방향 전환 제안 횟수에 상한을 둡니다 | | 비대한 도구 출력 | 결과를 잘라내거나 페이지로 나눕니다. 파일 전체를 읽기 전에 먼저 검색합니다. 요약을 반환합니다. 대량 반복 작업은 스크립트로 실행하고 결과만 반환합니다 | 에이전트가 더 요청할 수 있도록 잘렸다는 사실을 눈에 보이게 표시합니다 | | 기록 증가 | 오래된 턴을 압축/요약합니다. 작업마다 새 세션을 시작합니다. 탐색은 서브에이전트에 격리합니다 | 요약에는 손실이 있습니다. [캐시를 잃지 않는 컨텍스트 압축](#compaction-without-losing-the-cache)을 참고하세요 | | 접두부 변동 | 안정적인 내용(시스템 프롬프트, 지침, 도구 정의)을 앞에, 자주 바뀌는 내용을 뒤에 둡니다. 세션 도중에 접두부를 수정하지 않습니다 | 캐시 diff 뷰로 확인합니다 | | 과도하게 큰 모델 / 강도 | 쉬운 단계는 더 작은 모델로 라우팅합니다. 추론 강도를 기본값으로 낮춥니다 | 3단계의 품질 점검을 통과해야 합니다 | | 재시도와 재작업 | 프롬프트에 더 나은 성공 기준을 제시합니다. 비용이 큰 단계 전에 저렴하게 검증합니다 | 품질도 함께 좋아지는 경우가 많습니다 | | 컨텍스트 열화 | 핵심 규칙을 시작 부분에 두고, 핵심 제약은 끝부분 근처에서도 다시 언급합니다. 컨텍스트 윈도우가 거의 차기 전에 압축하거나 다시 시작합니다 | 모델은 긴 컨텍스트의 중간 부분에 덜 안정적으로 주의를 기울입니다([Lost in the Middle](https://arxiv.org/abs/2307.03172)) | | 도구 수 × 단계 수 승수 | 워크스페이스별 도구 집합을 사용합니다. 사용량을 기준으로 서버를 점검합니다. 단계에 상한(`maxTurns` 방식의 제한)을 두고 완료 기준을 정의합니다 | [MCP 감사](../../copilot-tokenomics/09-mcp-audit/)를 참고하세요 | | 지나치게 넓은 프롬프트 / 지침 | "지뢰 규칙"만 남깁니다. 선언적 규칙을 씁니다. 프롬프트 하나에 작업 하나만 담습니다. 복잡한 작업에는 계획 파일을 사용합니다 | 컨텍스트 파일은 성공률을 높이지 못한 채 비용만 늘리는 경우가 많습니다([arXiv:2602.11988](https://arxiv.org/abs/2602.11988)) | | 모든 프롬프트에 들어가는 길고 안정적인 지식 | 항상 포함하는 텍스트 대신 필요할 때 불러오는 **스킬**로 묶습니다 | 단일 정보 출처(single source of truth)를 유지합니다 | | 장황한 모델 출력 | 상시 적용되는 출력 제한("코드만", 고정 형식)을 두고 구조화된 출력을 사용합니다 | 출력 토큰은 대개 입력보다 비쌉니다 | | 큰 정적 문서 × 호출 횟수 | 질문에 필요할 때만 참조 문서를 첨부합니다(규칙 또는 검색). 섹션으로 나누어 관련 있는 부분만 포함합니다. 도구나 스킬을 통해 필요할 때 로드합니다. 여러 번 호출되는 단계에서는 매번이 아니라 한 번만 첨부합니다 | 조건 판단은 3단계의 구성 요소 수준 평가로 검증합니다. `tokens × calls`를 측정합니다 | | 중복된 파이프라인 단계(팬아웃) | 결정적 검사로 단계를 건너뜁니다. 인접한 분류 단계를 한 번의 호출로 합칩니다. 가드레일과 라우팅에는 더 작은 모델을 사용합니다. 출력이 거의 쓰이지 않는 단계는 제거합니다 | 제거하는 각 단계는 3단계 평가를 통과해야 합니다. 증명될 때까지 기존 경로를 플래그 뒤에 유지합니다 | | 세션별 무제한 상태 | 내부 메시지 수를 제한하거나 최근 메시지만 유지합니다. 이후 단계에 필요한 것만 유지합니다(전체 보고서가 아닌 짧은 결과). 아래의 압축 규칙에 따라 요약합니다 | 먼저 빠진 잘라내기 로직이 없는지 찾습니다. 한 줄 수정으로 끝나는 경우가 많습니다 | | 짧아서 캐시할 수 없는 프롬프트 | 단계를 인접 단계에 합치거나, 규칙으로 대체하거나, 그대로 둡니다(작으므로). 최소 길이를 채우려고 내용을 부풀리지는 않습니다 | 공급자의 현재 최소 길이와 `cached_tokens`를 확인합니다 | | 대량 / 폴링 도구 루프 | 루프를 스크립트로 실행하고 요약만 반환합니다 | 스크립트 방식과 대화형 방식을 벤치마크합니다 |
에이전트 세션의 비용을 제어하는 TokenEconomizer 프레임워크
경험 기반 비용 제어를 위한 참고 프레임워크입니다. 출처: microsoft/TokenEconomizer (Apache 2.0), arXiv:2610.22732.
## 오래된 도구 출력에 관찰 마스킹 적용 [비대한 도구 출력이나 기록 증가](../02-isolate/)가 원인이라면 추가 LLM 호출로 요약하는 대신 최근 `K`단계보다 오래된 큰 도구 결과를 정해진 형식의 자리 표시자로 바꾸세요. 다음은 **가상 예시**입니다. 도구 호출과 결과의 짝을 유지하고 최근 작업 구간은 그대로 보존합니다. ```text current_step = 5; K = 3 # keep results from steps 3–5 unchanged turn 1 read_file result → [omitted 4,200-token read_file output from turn 1; path=src/checkout.py lines=1..180] ``` 마스킹에는 요약 모델 호출이 필요하지 않지만 자리 표시자에도 입력 토큰이 듭니다. 정보가 손실되고 프롬프트 캐시 일부가 무효화될 수 있으므로 원본은 필요할 때 다시 읽도록 안전하게 보관하고 필요한 경우 경로도 마스킹하세요. 기준선과 비용, 캐시 재사용률, 작업 성공률을 비교합니다. 이 방법은 [The Complexity Trap](https://arxiv.org/abs/2508.21433)을 참고했으며, 논문의 결과는 저자가 보고한 것으로 이곳에서 독립적으로 재현하지 않았습니다. ## 캐시를 유지하는 컨텍스트 압축 컨텍스트 압축과 프롬프트 캐싱은 서로 반대 방향으로 작용합니다. 기록의 *앞부분*을 다시 쓰면 요청 접두부가 바뀌어 공급자가 캐시를 재사용할 수 없게 되고, 입력 비용을 정가로 다시 지불하게 됩니다.
접두부 유지
안정적 접두부요약최근 턴
CACHE HIT
전체 재작성
바뀐 접두부
CACHE MISS
개념도: 안정적인 접두부 뒤에 요약과 최근 턴을 배치하면 해당 접두부의 캐시를 재사용할 수 있습니다. 접두부를 다시 쓰면 이전 캐시가 맞지 않습니다. 실제 적중 여부는 공급자의 최소 길이, 보존 기간과 캐시 조건에 따라 달라집니다.
- **접두부를 안정적으로 유지합니다.** 시스템 프롬프트, 지침, 도구 정의를 앞에 두고 변경하지 않습니다. 압축 사이에는 기록에 추가만 합니다. - **드물게, 한 번에 압축합니다.** 임계값(예: 컨텍스트 윈도우의 일정 비율)에 도달했을 때나 작업 경계에서 압축하며, 매 턴마다 하지 않습니다. - **비용을 비교합니다.** 다음 조건에서만 압축합니다. `saved tokens × remaining turns × (1 − cached-input discount)`가 `summarization call cost + cache rebuild cost`를 초과할 때입니다. 남은 세션이 짧으면 비용을 회수하기 어렵습니다. - **요약을 구조화합니다.** 시간순이 아니라 에이전트에게 필요한 기준으로 정리합니다. ```text Goal: Decisions: Constraints: Done / artifacts: Open items: Failures to avoid: ``` 자연어 몇 줄은 필드로 담기 어려운 뉘앙스를 전달할 수 있습니다. 구조를 중심으로 삼고, 맞지 않는 내용에만 서술형 문장을 추가합니다. - **응답을 지연하지 않도록 백그라운드에서 요약합니다.** 컨텍스트가 토큰 임계값을 넘으면 트리거하고, 답변 이후에 비동기로 실행한 뒤 다음 턴부터 결과를 사용합니다. - **요약과 최근 원문을 함께 사용합니다.** 요약과 마지막 몇 턴의 원문을 함께 보내고, 요약 길이에 상한을 둡니다. 요약기 자체의 프롬프트는 대체로 짧아서(캐시 가능 최소 길이보다 짧은 경우가 많음) 비용 대부분이 캐시되지 않는 입력에서 발생합니다. 이후 호출에서 절약하는 양이 이 비용보다 큰지 확인합니다(위의 손익분기 참고). - **무엇을 반드시 남길지는 도메인 담당자가 정합니다**(예: 사람 상담원에게 꼭 필요한 정보). 엔지니어는 이를 구현하고 테스트합니다. 도메인이 바뀌면 목록을 다시 검토합니다. - **가능하면 요약하지 말고 오프로드합니다.** 긴 원본 출력은 파일에 저장하고 한 줄 요약과 경로만 남기면, 에이전트가 필요할 때 다시 읽을 수 있습니다(거의 무손실). - **요약을 보호합니다.** 요약을 반복해서 요약하지 않습니다(오류가 누적됩니다). 원본을 보관하고, 비밀 정보와 개인 데이터는 요약에 들어가기 전에 가립니다. - [손실이 있는 수정의 기준](../03-prove/#when-the-fix-is-lossy-summaries-compaction)으로 검증합니다. ### 실전 예시: 다중 턴 상담 대화 이력 압축 고객지원·상담 에이전트에서는 이전 턴의 인사말, 사과 문구, `` JSON 래퍼, 반복되는 세션 UUID, 마무리 멘트가 매 턴 누적됩니다. 예제에서 완료된 상담 에피소드를 BPE 친화적 상태·조치 수식 체인(`문의 -> tool(인자) => 결과 | ...`)으로 압축하면 고객 ID, 주문번호, 날짜, 금액, 송장번호, 담당자 이관 결과를 **100%** 보존하면서 대화 이력 토큰을 크게 줄일 수 있습니다. 영문 전용 예제는 [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py), 한국어 전용 예제는 [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py)로 분리되어 있습니다(통합 실행: [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) `--lang {en,ko,all}`, 2026-11-04 확인). **영문 다중 턴 채팅·상담 이력 (`examples/formula_prompt_en.py`):** | 영문 다중 턴 채팅·상담 및 Hugging Face 데이터셋 (`row`) | 원본 대화 (`o200k` / `cl100k`) | BPE 수식 압축 (`o200k` / `cl100k`) | `o200k_base` 변화 | `cl100k_base` 변화 | 핵심 슬롯 보존 | |---------------------------------------------------------|-------------------------------:|-----------------------------------:|------------------:|-------------------:|---------------:| | 로그인 인증번호 이메일 전환 상담 (13턴, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[0]`) | 336 / 350 | 57 / 58 | **-83.0%** | **-83.4%** | 7/7 | | 리콜 모니터 반품·환불 안내 (13턴, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[1]`) | 339 / 347 | 53 / 53 | **-84.4%** | **-84.7%** | 8/8 | | 보증기간 교환 신청 및 취소 버튼 오류 상담 (19턴, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[2]`) | 526 / 535 | 81 / 81 | **-84.6%** | **-84.9%** | 9/9 | | 인증번호 횟수 초과 및 비밀번호 재설정 (17턴, [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[3]`) | 460 / 471 | 49 / 49 | **-89.3%** | **-89.6%** | 6/6 | | 심계항진 의료 문진 인테이크 채팅 (10턴, [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) `sessions[0..9]`) | 321 / 322 | 74 / 73 | **-76.9%** | **-77.3%** | 9/9 | | 생산라인 로봇 과열·소음 기술지원 채팅 (4턴, [`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) `train[1,2]`) | 112 / 114 | 35 / 36 | **-68.8%** | **-68.4%** | 6/6 | | **합계 (6개 영문 다중 턴 채팅·상담 대화)** | **2,094 / 2,139** | **349 / 350** | **-83.3%** | **-83.6%** | **45/45 (100%)** | **한국어 다중 턴 채팅·상담 이력 (`examples/formula_prompt_ko.py`):** | 한국어 다중 턴 채팅·상담 및 Hugging Face 데이터셋 (`row`) | 원본 대화 (`o200k` / `cl100k`) | BPE 수식 압축 (`o200k` / `cl100k`) | `o200k_base` 변화 | `cl100k_base` 변화 | 핵심 슬롯 보존 | |-----------------------------------------------------------|-------------------------------:|-----------------------------------:|------------------:|-------------------:|---------------:| | 주소 조회 + 배송 상태 + 스팸 신고 (14턴, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[0]`) | 304 / 460 | 84 / 129 | **-72.4%** | **-72.0%** | 9/9 | | 장바구니 + 노트북 불량 + 영수증 이관 (15턴, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[2]`) | 386 / 565 | 127 / 190 | **-67.1%** | **-66.4%** | 9/9 | | 배송 조회 + 멤버십 + 환불/결제취소 (16턴, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[5]`) | 436 / 638 | 158 / 225 | **-63.8%** | **-64.7%** | 11/11 | | 반품·교환 약관 + 범위 외 거절 + 주문내역 (13턴, [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[6]`) | 368 / 545 | 124 / 194 | **-66.3%** | **-64.4%** | 11/11 | | 택배 조회 및 무인보관함 배송지 변경 채팅 (6턴, [`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[2]`) | 195 / 226 | 55 / 61 | **-71.8%** | **-73.0%** | 5/5 | | 심계항진 의료 문진 인테이크 채팅 (10턴, [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) `sessions[0..9]`) | 402 / 613 | 102 / 144 | **-74.6%** | **-76.5%** | 10/10 | | 멀티세션 페르소나·가족 일상 메신저 채팅 (18턴, [`nayohan/141_korean_multi_session_dialogue`](https://huggingface.co/datasets/nayohan/141_korean_multi_session_dialogue) `train[0]`) | 359 / 567 | 77 / 103 | **-78.6%** | **-81.8%** | 11/11 | | **합계 (7개 한국어 다중 턴 채팅·상담 대화)** | **2,450 / 3,614** | **727 / 1,046** | **-70.3%** | **-71.1%** | **66/66 (100%)** | 나아가 Hugging Face 공개 데이터셋에서 실시간 조회한 **580개 채팅 대화·고객지원·법률·노무 상담 세션**(영문 5개 데이터셋 250건 + 한국어 7개 데이터셋 330건, `python3 examples/formula_prompt.py --hf-live --hf-rows 50`)에 범용 BPE 문법·담화 압축과 무손실 슬롯 복원 가드를 적용한 결과, 법조문·사건번호·이메일·UUID·케밥케이스 ID·주문번호·날짜·금액·플레이스홀더 슬롯 **1,731 / 1,731개(100.0%)** 를 무손실로 보존하면서 전체 토큰을 **`o200k_base` 기준 56.3%**(**`cl100k_base` 기준 54.9%**) 절감했습니다. | 언어 및 Hugging Face 데이터셋 (`--hf-live --hf-rows 50`) | 행 수 | `o200k_base` (원문 → BPE) | `cl100k_base` (원문 → BPE) | 엄밀 슬롯 보존 | |----------------------------------------------------------|------:|--------------------------:|---------------------------:|---------------:| | EN: [`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) | 50 | 23,979 → 11,538 (**-51.9%**) | 24,629 → 11,912 (**-51.6%**) | 124/124 | | EN: [`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) | 50 | 11,431 → 3,390 (**-70.3%**) | 11,639 → 3,406 (**-70.7%**) | 281/281 | | EN: [`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) | 50 | 3,146 → 1,548 (**-50.8%**) | 3,226 → 1,590 (**-50.7%**) | 0/0 (100%) | | EN: [`Kaludi/Customer-Support-Responses`](https://huggingface.co/datasets/Kaludi/Customer-Support-Responses) | 50 | 1,837 → 893 (**-51.4%**) | 1,883 → 919 (**-51.2%**) | 1/1 | | EN: [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions`, 영문) | 50 | 1,462 → 608 (**-58.4%**) | 1,467 → 610 (**-58.4%**) | 11/11 | | **영문 소계 (5개 데이터셋)** | **250** | **41,855 → 17,977 (-57.0%)** | **42,844 → 18,437 (-57.0%)** | **417/417 (100%)** | | KO: [`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) | 50 | 19,243 → 7,774 (**-59.6%**) | 29,172 → 12,468 (**-57.3%**) | 220/220 | | KO: [`jjun123/delivery-app-function-calling-datasets-korean`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) | 30 | 42,129 → 18,182 (**-56.8%**) | 52,592 → 24,433 (**-53.5%**) | 325/325 | | KO: [`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) | 50 | 27,325 → 12,357 (**-54.8%**) | 42,753 → 18,872 (**-55.9%**) | 465/465 | | KO: [`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) | 50 | 5,788 → 2,498 (**-56.8%**) | 9,588 → 4,041 (**-57.9%**) | 38/38 | | KO: [`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) | 50 | 7,437 → 3,119 (**-58.1%**) | 9,405 → 4,478 (**-52.4%**) | 176/176 | | KO: [`nwirandx/Korean-OSCE-history-taking-dialogues`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions`, 한국어) | 50 | 1,854 → 882 (**-52.4%**) | 2,791 → 1,304 (**-53.3%**) | 13/13 | | KO: [`nayohan/141_korean_multi_session_dialogue`](https://huggingface.co/datasets/nayohan/141_korean_multi_session_dialogue) | 50 | 18,307 → 8,914 (**-51.3%**) | 28,868 → 14,252 (**-50.6%**) | 77/77 | | **한국어 소계 (7개 데이터셋)** | **330** | **122,083 → 53,726 (-56.0%)** | **175,169 → 79,848 (-54.4%)** | **1,314/1,314 (100%)** | | **전체 합계 (12개 데이터셋 벤치마크, 580개 채팅·상담 사례)** | **580** | **163,938 → 71,703 (-56.3%)** | **218,013 → 98,285 (-54.9%)** | **1,731/1,731 (100%)** | ## 규칙 - **한 번에 한 가지만 변경합니다.** 변경을 함께 적용하면 어떤 변경의 효과인지 구분할 수 없습니다. - **되돌리기 조건**을 미리 정의합니다(예: 성공률이 노이즈 임계값보다 많이 떨어지는 경우). - 조용한 동작 변경보다 **되돌릴 수 있고 눈에 보이는** 수정(설정/구성)을 선호합니다. - 블랙박스 우선: 에이전트 자체를 수정할 수 없다면 구성, 지침, 도구 설정을 통해 대응합니다. ## 원인별 관련 연구 각 개선 방법과 관련된 발표 연구를 소개합니다. 학회 등급 순, 같은 행 안에서는 인용 수 순으로 정렬했습니다(전체 목록: [논문](../../papers/)). 각 연구는 *자신의* 에이전트에 대한 가설로 취급하고 [3단계](../03-prove/)에서 검증합니다. | 원인 | 논문 | |------|------| | 저장소 사실 재학습 | [Agentic Context Engineering](https://arxiv.org/abs/2510.04618) (ICLR 2025); [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) (ICML 2024); [TokenEconomizer](https://arxiv.org/abs/2610.22732) (프리프린트 2026) | | 사용하지 않는 도구 / 도구 스키마 크기 | [MCP-Zero](https://arxiv.org/abs/2506.01056) (프리프린트 2025); [RAG-MCP](https://arxiv.org/abs/2505.03275) (프리프린트 2025); [Less is More (function calling)](https://arxiv.org/abs/2411.15399) (프리프린트 2024) | | 실패 루프, 에이전트 설계 | [SWE-agent](https://arxiv.org/abs/2405.15793) (NeurIPS 2024); [Agentless](https://arxiv.org/abs/2407.01489) (프리프린트 2024); [Efficient Agents](https://arxiv.org/abs/2508.02694) (프리프린트 2025) | | 비대한 도구 출력 / 궤적 | [SWE-agent](https://arxiv.org/abs/2405.15793) (NeurIPS 2024); [Trajectory Reduction](https://arxiv.org/abs/2509.23586) (PACMSE 2025); [The Complexity Trap (observation masking)](https://arxiv.org/abs/2508.21433) (프리프린트 2025) | | 기록 증가 / 메모리 | [Mem0](https://arxiv.org/abs/2504.19413) (ECAI 2025); [Recursively Summarizing](https://arxiv.org/abs/2308.15022) (Neurocomputing 2023); [MemGPT](https://arxiv.org/abs/2310.08560) (프리프린트 2023); [The Complexity Trap (observation masking)](https://arxiv.org/abs/2508.21433) (프리프린트 2025) | | 컨텍스트 열화 | [Lost in the Middle](https://arxiv.org/abs/2307.03172) (TACL 2023); [LLMs Get Lost in Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) (ICLR 2025); [Same Task, More Tokens](https://arxiv.org/abs/2402.14848) (ACL 2024) | | 접두부 변동 / 캐시 미스 | [SGLang](https://arxiv.org/abs/2312.07104) (NeurIPS 2023); [Prompt Cache](https://arxiv.org/abs/2311.04934) (MLSys 2023); [Don't Break the Cache](https://arxiv.org/abs/2601.06007) (프리프린트 2026) | | 프롬프트 및 컨텍스트 압축 | [LongLLMLingua](https://arxiv.org/abs/2310.06839) (ACL 2023); [LLMLingua-2](https://arxiv.org/abs/2403.12968) (ACL 2024); [LLMLingua](https://arxiv.org/abs/2310.05736) (EMNLP 2023) | | 과도하게 큰 모델 | [FrugalGPT](https://arxiv.org/abs/2305.05176) (TMLR 2023); [Hybrid LLM](https://arxiv.org/abs/2404.14618) (ICLR 2024); [RouteLLM](https://arxiv.org/abs/2406.18665) (프리프린트 2024) | | 추론 길이 / 강도 | [Token-Budget-Aware Reasoning](https://arxiv.org/abs/2412.18547) (ACL 2024); [L1 (length-controlled reasoning)](https://arxiv.org/abs/2503.04697) (프리프린트 2025); [Chain of Draft](https://arxiv.org/abs/2502.18600) (프리프린트 2025) | | 중복된 파이프라인 단계 / 불필요한 모델 크기 | [FrugalGPT](https://arxiv.org/abs/2305.05176) (TMLR 2023); [AutoMix](https://arxiv.org/abs/2310.12963) (NeurIPS 2023); [Agentless](https://arxiv.org/abs/2407.01489) (프리프린트 2024) | | 대량 호출 | [Batch Prompting](https://arxiv.org/abs/2301.08721) (EMNLP 2023) | ## 다음 단계 [5. 결과](../05-result/)에서 다시 측정합니다. --- ## 5. 결과 (ko/agent-tokenomics/05-result.md) Canonical URL: > LLM 에이전트 토큰 이코노믹스 5단계(결과): 기준선과 비교해 토큰 비용, 작업 성공률(품질 가드레일), 지연 시간을 재측정하고 유지 여부를 결정합니다. **목표:** 변경 전후를 공정하게 비교하고 결정을 기록합니다. ## 점검 항목 기준선과 *같은* 작업 집합, 반복 횟수, 환경으로 변경을 적용한 뒤 다시 실행합니다. | 지표 | 기준선 | 수정 적용 후 | 변화 | 허용 가능한가? | |------|--------|--------------|------|----------------| | 작업당 평균 비용 | | | | | | 입력 / 캐시 / 출력 토큰 | | | | | | **성공률(가드레일)** | | | | 노이즈 범위를 넘어 떨어지면 안 됩니다 | | 중앙값 지연 시간 | | | | | | 수정 자체의 비용(추가 모델 호출, 유지 관리) | | | | 반드시 포함합니다(예: 요약 호출) | | 캐시 적중률 | | | | 캐시를 무효화하는 압축은 절감 효과를 상쇄할 수 있습니다 | | 용량과 지연 시간(이것이 목표인 경우) | | | | 요청당 분당 토큰 수, 사용률, p95 지연 시간, 첫 토큰까지의 시간 | | 변경한 구성 요소(라우터, 분류기)의 결정 정확도 | | | | 3단계의 구성 요소 평가 기준. 평균만이 아니라 클래스별로 확인합니다 | | 반드시 보존할 사실의 회상(손실이 있는 수정에만 해당) | | | | 3단계의 회상 점검 기준 | TokenEconomizer가 보고서에서 하는 것처럼, 변경으로 발생하는 비용(예: 판정 모델, 요약기)을 **모두** 포함합니다.
기준선
39,200 입력 토큰
개선 가정
약 15,200 입력 토큰
샘플 s1의 턴 1 기준선은 4회 호출의 입력 합계입니다. 개선 수치는 도구 가지치기와 루프 가드 후 각각 7,200과 8,000 입력 토큰을 쓰는 호출 2회를 가정한 예시이며 측정 결과가 아닙니다. 성공률 유지도 가정일 뿐이므로 같은 작업을 반복해 품질과 비용을 검증해야 합니다. 두 변경은 각각 따로 실험하세요.
## 결정 - 비용이 줄고 성공률이 유지되었다면 **유지**합니다. 변경 내용, 수치, 날짜를 기록합니다. - 성공률이 떨어졌거나 절감 효과가 노이즈 범위 안이라면 **되돌립니다**. - **반복:** 2단계로 돌아가 다음으로 큰 원인을 살펴봅니다. 절감 효과는 대개 하나의 큰 수정이 아니라 여러 개의 작은 수정에서 나옵니다. ## 보고서 템플릿 ```text Change: Cause proven: Cost / task: -> () Success: -> Side costs: Decision: keep | revert Next cause: ``` ## 상태 유지 진단을 주기적으로 다시 실행합니다. 새로운 도구, 길어진 지침, 모델 변경으로 다시 낭비가 생길 수 있습니다. ### 지속적인 변화 감시 수정을 유지하기로 했다면 도구나 지침이 바뀐 뒤 CI 또는 주간 작업에서 고정된 대표 작업 집합을 실행하세요. 기준선을 기록하고 `first_call_input`(첫 호출의 입력 토큰으로 고정 오버헤드를 가늠하는 지표)과 `unused_tool_defs`(선택한 작업 집합에서 사용하지 않은 도구 정의)가 합의한 허용 범위를 벗어나지 않는지 검사합니다. 같은 모델·도구·작업을 비교하고 의도한 변경은 기준선을 무조건 갱신하지 말고 원인을 확인하세요. 작은 작업 집합에서 사용되지 않은 도구는 검토 대상일 뿐 불필요하다는 증거는 아닙니다. 비용과 함께 작업 성공률도 추적해 품질 저하를 놓치지 마세요. ## 추가 자료(논문) 학회 등급 순, 같은 등급 안에서는 인용 수 순으로 정렬했습니다. 각 결과는 자신의 워크로드에서 검증해야 할 가설로 취급합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — TMLR 2024, 인용 289회. 에이전트 평가는 정확도뿐 아니라 비용도 통제해야 한다고 주장합니다. - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — ICLR 2025, 인용 56회. 정답 하나를 얻는 데 드는 기대 비용을 정의하고 이를 기준으로 모델을 비교합니다. - [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — 프리프린트 2024, 인용 1,669회. 반복 실행에서 에이전트의 신뢰도를 측정하는 pass^k를 도입한 벤치마크입니다. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — 프리프린트 2024, 인용 194회. LLM 평가에서 불확실성을 보고하기 위한 통계적 지침을 제시합니다. --- ## 6. 골든 데이터셋과 루브릭 평가 (ko/agent-tokenomics/06-golden-dataset-and-rubric.md) Canonical URL: > 단일 턴·멀티턴 에이전트의 토큰 최적화 전후 품질을 검증하기 위한 엑셀(CSV) 골든 데이터셋 설계, 키워드·의도 하이브리드 채점, 루브릭 평가 방법입니다. **목표:** 토큰을 줄인 뒤에도 에이전트의 답변 정확도와 멀티턴 문맥 유지력이 그대로인지 검증하는 **반복 가능한 품질 기준선**을 만듭니다. --- ## 1. 정답을 어떻게 판정할 것인가: 키워드 일치 vs 의도(의미) 파악 에이전트 응답을 채점할 때 단일 방식만 사용하면 오류가 발생합니다. 질문과 작업의 성격에 따라 **4가지 판정 기준**을 조합하는 **하이브리드(Hybrid) 채점**이 가장 정확하고 비용도 적게 듭니다. | 판정 기준 | 언제 사용하는가? | 작동 방식 (예시) | 평가 토큰 비용 | |-----------|------------------|------------------|----------------| | **1. 필수 키워드·슬롯 일치 (`must_include_all`)** | 특정 식별자, 수치, 경계 조건, 파일 경로가 빠지면 오답인 경우 | `checkout.py;>= 100` (모두 포함되어야 통과) | **0 토큰** (문자열·정규식) | | **2. 동의어 그룹 일치 (`must_include_any`)** | 같은 뜻을 여러 표현으로 말할 수 있지만 핵심 단어군 중 하나는 꼭 들어가야 하는 경우 | `평일\|영업일\|월요일;주말 제외\|토·일 제외` (그룹별 1개 이상 포함 시 통과) | **0 토큰** (문자열·정규식) | | **3. 금지 키워드·금지 행동 (`must_not_include` / `expected_tools`)** | 환각 문구, 규정 위반 약속, 잘못된 명령어, 필수 도구 미호출을 차단할 때 | 금지어: `전액 환불해 드리겠습니다`, 필수 도구: `update_shipping_address` | **0 토큰** (로그·문자열) | | **4. 의도 및 의미 루브릭 평가 (`expected_intent` + Rubric)** | 문장 표현이 완전히 달라도 질문 의도에 맞는 결론을 내렸는지 판단해야 할 때 | `"개봉 후 7일이 지나 단순 변심 환불은 불가함을 안내하고 대안(점검 접수)을 제시함"` | **소량 소비** (LLM-as-a-Judge) |
1단계 (결정적)
필수 키워드(all) · 동의어(any) · 금지어(not) · 호출 도구(tools) 검사 (0 토큰)
즉시 판정
2단계 (루브릭)
1단계 통과 건만 5대 루브릭 축(의도·사실/슬롯·멀티턴 문맥·도구/정책·간결성, 10점 만점) 채점
길이 편향 차단
정밀 검증
그림 1. 비용이 들지 않는 결정적 키워드·도구 검사를 먼저 실행하고, 통과한 응답에 대해서만 의도 기반 루브릭(LLM-as-a-Judge)을 실행하는 2단계 하이브리드 평가 파이프라인.
--- ## 2. 실제 멀티턴(Multi-turn) 대화는 어떻게 평가해야 하는가? 멀티턴 대화(`Turn 1 → Turn 2 → Turn 3`)에서 토큰 최적화(컨텍스트 압축, 관찰 마스킹, 도구 가지치기 등)를 검증할 때 가장 흔히 겪는 문제는 **"1턴의 답변이 달라지면 2턴의 질문 맥락이 어긋나 전후 비교가 불가능해진다"**는 점입니다. 이를 해결하려면 다음 두 가지 방식을 구분해 사용합니다. ### 방식 A: 고정 문맥 주입 평가 (Pinned-History Slicing — 전후 비교 시 기본 권장) - **방법**: `Turn 1 ~ Turn k-1`까지의 대화 기록과 도구 결과를 **고정된 텍스트(`prior_turns_context`)**로 넣어 주고, **측정 대상인 `Turn k`의 응답과 토큰 사용량만 비교**합니다. - **멀티턴 기억 유지(Planted-Fact Retention) 검증**: - **1턴(Setup)**에 중요한 제약 조건을 심어 둡니다. 예: *"주문번호 `ORD-901` 배송지를 바꾸고 싶은데, **주말에는 택배를 절대 못 받아요**."* - **2턴(Memory Check)**에서는 그 제약을 다시 언급하지 않고 질문합니다. 예: *"서울시 강남구 테헤란로 123으로 변경해 주시고, 언제 도착하는지도 알려주세요."* - 컨텍스트를 압축하거나 프롬프트를 줄인 뒤에도 에이전트가 1턴의 **`ORD-901`**과 **`주말 수령 불가(평일/영업일 배송)`** 제약을 잃어버리지 않고 반영하는지 검사합니다. ### 방식 B: 엔드투엔드 시나리오 시뮬레이션 (`pass^k`) - 전체 루프 단축이나 에이전트 자율 실행을 평가할 때는 사용자 역할을 하는 고정 시나리오가 최대 `N`턴 동안 에이전트와 대화하며 최종 목표 달성 여부와 총 세션 토큰을 측정합니다([tau-bench, arXiv:2406.12045](https://arxiv.org/abs/2406.12045)). --- ## 3. 엑셀(`.xlsx` / `.csv`)로 골든 데이터셋 정리·관리하기 엔지니어와 도메인 담당자(기획·QA·현업)가 함께 골든 데이터셋을 관리할 때는 중첩된 JSON보다 **엑셀 통합 문서(`.xlsx`)의 표(1행 = 평가 턴 1건, 같은 대화는 동일한 `session_id`에 `turn_index` 1~5로 연결)** 형태가 훨씬 효율적입니다. - **실제 엑셀 파일 다운로드 (시트 2개: `Golden_Dataset` 16행 + `Rubric_Criteria` 루브릭 기준표)**: - [📥 `sample-golden-dataset.xlsx` 다운로드 (Excel 통합 문서)](https://github.com/dotnetpower/agent-tokenomics/raw/main/examples/sample-golden-dataset.xlsx) · [로컬 데모 파일 열기](/demo/sample-golden-dataset.xlsx) - [📥 `sample-golden-dataset.csv` 다운로드 (UTF-8 BOM CSV)](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-golden-dataset.csv) · [생성·채점 스크립트 `golden_dataset_tool.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/golden_dataset_tool.py) | 열 이름 (Column) | 입력 형식 | 설명 및 작성 요령 | |------------------|-----------|-------------------| | `case_id` | `HF-ECOM5-T2` | 행 고유 ID (`세션ID-턴번호`) | | `session_id` | `HF-ECOM5` | 멀티턴 대화를 묶는 세션 ID | | `turn_index` | `1` ~ `5` | 해당 세션 내의 턴 순서 | | `hf_dataset` / `hf_row` | `iamjoon/...` / `train[5]` | 원본 Hugging Face 데이터셋 이름 및 행 번호 | | `slice` | `multi_turn_tool` | 평가 유형 (`multi_turn_tool`, `multi_turn_memory`, `policy_guardrail`, `legal_statute_qa`) | | `match_mode` | `hybrid` | `keyword_only` / `intent_only` / `hybrid` | | `prior_turns_context` | `[T1 User] ... [T1 Tool] ...` | 멀티턴인 경우 이전 턴까지의 고정 대화·도구 결과 요약 (1턴이면 빈칸) | | `user_input` | 텍스트 | 현재 턴에 사용자가 입력하는 질문 또는 지시 | | `must_include_all` | `;`로 구분 | 반드시 포함되어야 하는 키워드·숫자·식별자 (예: `5월 10일;무선 이어폰;4567891230`) | | `must_include_any` | `;`로 그룹, `\|`로 동의어 | 그룹별 동의어 중 1개 이상 포함 (예: `희망 날짜\|희망하는 날짜;모의 서비스\|가상`) | | `must_not_include` | `;`로 구분 | 포함되면 즉시 오답 처리할 금지 표현 (예: `제가 바로 결제 취소해 드렸습니다`) | | `expected_tools` | `;`로 구분 | 해당 턴에 호출해야 하는 도구 이름 (예: `view_order_history;view_order_details`) | | `expected_intent` | 한 줄 문장 | **의도 기반 채점 기준**: 표현이 달라도 어떤 뜻과 결론이 담겨야 정답인지 명시 | | `baseline_response` / `baseline_tokens` | 텍스트 / 정수 | 최적화 전 에이전트 응답과 소비 토큰 수 | | `candidate_response` / `candidate_tokens` | 텍스트 / 정수 | 최적화 후 에이전트 응답과 소비 토큰 수 | ### Hugging Face 공개 데이터셋 기반 16개 골든 데이터셋 예시 (`sample-golden-dataset.xlsx` 시트 1) 공개된 한국어 Hugging Face 데이터셋 6종에서 추출한 **실제 멀티턴(5턴 연속 세션·4턴 연속 세션·10턴 문진 요약) 및 단일 턴 16개 평가 행**입니다. | 케이스 (턴) | Hugging Face 데이터셋 (`hf_row`) | 방식 / 필수 도구 | `must_include_all` (필수 슬롯) | `must_include_any` (동의어 그룹) | `expected_intent` (의도 채점 기준) | |---|---|---|---|---|---| | **`HF-ECOM5-T1`** (1/5) | [`iamjoon/ecommerce-...`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) (`train[5]`) | `hybrid`
`view_order_history` | `5월 10일`
`무선 이어폰`
`4567891230` | `한진택배`
`배송 중\|배송중` | `U002`의 5월 10일 무선 이어폰 주문이 한진택배(`4567891230`)로 배송 중임을 안내 | | **`HF-ECOM5-T2`** (2/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`view_user_profile` | `Gold`
`10%` | `할인 쿠폰\|쿠폰` | 1턴의 `U002` 문맥을 유지해 `Gold` 등급 및 `10%` 할인 쿠폰 보유 사실을 안내 | | **`HF-ECOM5-T3`** (3/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`search_policy_info` | `7일`
`왕복 배송비` | `수령 후\|수령일`
`고객센터\|신청` | 상품 수령 후 `7일` 이내 환불 신청 가능 조건과 왕복 배송비 규정을 안내 | | **`HF-ECOM5-T4`** (4/5) | `iamjoon/ecommerce-...` (`train[5]`) | `hybrid`
`search_policy_info` | `반품` | `출고되기 전\|출고 전`
`출고 이후\|출고 후`
`주문취소 버튼\|주문내역` | 출고 전에는 주문내역에서 즉시 취소 가능하고 출고 후에는 반품으로 처리됨을 구분 설명 | | **`HF-ECOM5-T5`** (5/5) | `iamjoon/ecommerce-...` (`train[5]`) | `intent_only`
*(도구 없음)* | `담당자` | `직접 처리할 수 없\|직접 처리 불가`
`전달` | AI 상담사가 직접 결제 취소할 권한이 없음을 밝히고 담당자에게 전달해 처리하겠다고 안내 | | **`HF-ECOM2-T1`** (1/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
`show_cart` | `블루투스 이어폰`
`무선 마우스` | `1개;2개` | `U001` 장바구니에 블루투스 이어폰 1개와 무선 마우스 2개가 담겨 있음을 안내 | | **`HF-ECOM2-T2`** (2/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
`view_order_history`
`view_order_details` | `고성능 노트북`
`1,150,000원` | `1대;구매` | 1턴의 `U001`을 기억해 주문 이력·상세(`O102`)를 연쇄 호출하고 고성능 노트북(`1,150,000원`) 확인 | | **`HF-ECOM2-T3`** (3/4) | `iamjoon/ecommerce-...` (`train[2]`) | `intent_only`
*(도구 없음)* | `담당자` | `기술적인 지원\|기술 지원`
`전달` | 노트북 전원 꺼짐 증상이 기술 지원 대상임을 안내하고 담당 부서 전달 약속 | | **`HF-ECOM2-T4`** (4/4) | `iamjoon/ecommerce-...` (`train[2]`) | `hybrid`
*(도구 없음)* | `카드 영수증`
`담당자` | `직접 처리할 수 없\|직접 처리 불가`
`전달` | 카드 영수증 발급은 직접 처리 불가함을 밝히고 담당자에게 전달하겠다고 안내 | | **`HF-DELIV-T1`** (1/1) | [`jjun123/delivery-app-...`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) (`train[0]`) | `hybrid`
`create_delivery_order` | `14,900원;7,000원`
`21,900원;이서준`
`e2a4b1c9-...` | `관악구 관악로 1`
`준비 중\|준비중`
`담당자` | 품목·총액(`21,900원`), 수령인(`이서준`), 주문 UUID, 매장 준비 중 안내 및 도착 시간 담당자 전달 | | **`HF-DFM14-T1`** (1/1) | [`schneiderkamplab/dfm14-...`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) (`train[2]`) | `keyword_only`
`lookup_parcel`
`redirect_parcel` | `parcel-610`
`locker-16`
`redirect-610` | `변경 처리가 완료\|변경 완료` | `tracking-610` 조회로 `parcel-610` 확인 후 `locker-16` 보관함 변경 및 `redirect-610` 반환 | | **`HF-CLINIC-T1`** (1/1) | `schneiderkamplab/dfm14-...` (`train[11]`) | `hybrid`
*(도구 없음)* | `병원 이름`
`서비스 종류` | `희망 날짜\|희망하는 날짜`
`모의 서비스\|가상`
`예약 가능 시간대` | 실제 예약 확정·의료 상담을 하지 않는 가상 모의 서비스임을 밝히고 시간대 조회만 가능함을 안내 | | **`HF-KLAC-T1`** (1/1) | [`jihye-moon/klac_legal_aid...`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) (`train[1]`) | `hybrid`
*(도구 없음)* | `제34조;제4조`
`1년;4주;15시간` | `근로기준법`
`근로자퇴직급여 보장법`
`퇴직연금` | 근로기준법 제34조·퇴직급여법 제4조 및 `1년 미만`·`4주 평균 주 15시간 미만` 제외 요건 제시 | | **`HF-KLAC-T2`** (1/1) | `jihye-moon/klac_legal_aid...` (`train[0]`) | `hybrid`
*(도구 없음)* | `최저임금법`
`제6조;무효;90%` | `3월\|3개월`
`수습` | 최저임금 미달 합의 무효(제6조) 및 수습 `3개월` 이내 최저임금 `90%` 지급 가능 요건 설명 | | **`HF-LABOR-T1`** (1/1) | [`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) (`train[34]`) | `hybrid`
*(도구 없음)* | `30일;30일분`
`통상임금;3개월` | `천재·사변\|부득이한 사유`
`예외` | `30일` 전 해고예고 또는 `30일분` 이상 통상임금 지급 의무와 `3개월` 미만·`천재·사변` 예외 안내 | | **`HF-OSCE-T1`** (2/2) | [`nwirandx/Korean-OSCE-...`](https://huggingface.co/datasets/nwirandx/Korean-OSCE-history-taking-dialogues) (`sessions[0..9]`) | `hybrid`
*(도구 없음)* | `김서현`
`1984년 5월 23일`
`20일;15분;20분;30분` | `과거력 없음\|과거력은 없`
`어지럽고\|어지러움`
`숨이 차\|호흡곤란` | 1~9턴 문진 내역(환자 정보, 20일 전 발병, 15~20분→30분 이상 악화, 과거력 없음, 동반 증상) 요약 | --- ## 4. 루브릭(Rubric) 평가 항목 재검토 및 설계 (5개 축 × 0·1·2점 = 10점 만점) 단일 0~10점 자유 척도는 채점 모델(LLM-as-a-Judge)이 실행할 때마다 점수가 흔들립니다. 반면 에이전트의 실패 원인을 **5개의 독립된(Orthogonal) 평가 축 × 각 0·1·2점 = 총 10점 만점**으로 분리하면, **현재 턴의 수치/슬롯 왜곡(축 2)**과 **이전 턴의 멀티턴 문맥 망각(축 3)**, 그리고 **도구 호출 및 정책 위반(축 4)**을 섞이지 않게 정확히 진단할 수 있습니다. | 평가 축 (5 Axes × 2점 = 10점 만점) | 0점 (Fail — 치명적 결함) | 1점 (Partial — 부분 충족) | 2점 (Pass — 완전 충족) | 왜 이 항목이 필요한가? | |---|---|---|---|---| | **1. 질문 의도 및 핵심 결론 정확성**
(`intent_and_resolution`) | 질문 의도를 오해했거나 `expected_intent`와 반대·무관한 결론을 냄 | 의도는 파악했으나 핵심 결론이나 필요한 후속 조치 안내가 일부 빠짐 | 표현 방식과 무관하게 `expected_intent`의 핵심 결론과 해결책을 정확히 제시함 | 단어 선택이 달라도 의미·결론이 맞는지 평가 (`intent_only` / `hybrid`) | | **2. 필수 사실·슬롯 및 수치 정확성**
(`fact_and_slot_accuracy`) | 필수 식별자·수치·법조문을 누락·왜곡했거나 없는 사실(환각)을 지어냄 | 주요 사실은 맞으나 부차적 수치·조건 표현이 모호하거나 일부 빠짐 | 모든 필수 키워드·수치·식별자·법조문을 왜곡이나 환각 없이 정확히 반영함 | 프롬프트/출력 압축 시 숫자·ID·법조문 손실 감시 (`keyword` / `hybrid`) | | **3. 멀티턴 문맥 및 상태 유지력**
(`multiturn_context_retention`) | 이전 턴(`prior_turns_context`)의 제약·식별자를 잊어 모순되거나 재질문함 | 이전 턴 정보를 일부만 반영하거나 문맥 연결이 불완전함 | 이전 턴에서 누적된 고객 ID·제약 조건·대화 상태를 누락 없이 일관되게 유지함 | 컨텍스트 압축(`/compact`)·관찰 마스킹 후 멀티턴 기억 유지 검증 | | **4. 도구 선택 및 정책·가드레일 준수**
(`tool_and_policy_compliance`) | 필수 도구를 호출하지 않고 결과를 지어내거나 금지어(`must_not_include`)·권한 밖 약속 수행 | 안전·정책 한계는 지켰으나 불필요한 도구를 중복 호출했거나 형식 제약을 어김 | 필요한 도구만 정확히 호출(권한 밖 작업은 담당자 전달)하고 모든 정책·금지 조건 준수 | 도구 가지치기 및 정책 프롬프트 축소 후 안전성·함수 호출 검증 | | **5. 간결한 완결성 (길이 편향 방지)**
(`concise_completeness`) | 필수 설명이 지나치게 생략되어 사용자가 재질문해야 하거나 문장이 깨짐 | 필요한 정보는 담겼으나 불필요한 인사말·사과·질문 되풀이로 토큰을 낭비함 | **필수 사실과 의도를 모두 충족하면서 군더더기 없이 간결하고 명확함 (짧은 답변 만점)** | **LLM Judge의 긴 답변 선호 편향(Verbosity Bias) 차단** | > **권장 통과 기준**: 1단계 결정적 검사(`must_include_all`, `must_include_any`, `must_not_include`, `expected_tools`)를 모두 통과하고, 2단계 루브릭 5개 축 합계가 **8점 이상(10점 만점)**이며 **어느 한 축도 `0점`이 아닐 때** 최종 `PASS`로 판정합니다. --- ## 5. 엑셀(`.xlsx` / `.csv`) 생성 및 하이브리드 채점 파이썬 코드 [`examples/golden_dataset_tool.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/golden_dataset_tool.py)는 외부 패키지 설치 없이 표준 라이브러리만으로 **2개 시트(`Golden_Dataset`, `Rubric_Criteria` 10점 만점 기준표)와 헤더 서식·열 너비가 적용된 실제 엑셀 파일([`examples/sample-golden-dataset.xlsx`](https://github.com/dotnetpower/agent-tokenomics/raw/main/examples/sample-golden-dataset.xlsx))** 및 [`examples/sample-golden-dataset.csv`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/sample-golden-dataset.csv)를 생성하고, `.xlsx` 또는 `.csv`를 직접 읽어 16개 Hugging Face 케이스를 평가합니다. ```bash # 1. 2개 시트(Golden_Dataset + Rubric_Criteria 10점 만점 기준표)가 포함된 실제 .xlsx 및 .csv 생성 python3 examples/golden_dataset_tool.py --write-sample # 2. 생성된 엑셀(.xlsx) 파일을 직접 읽어 Baseline vs Candidate 하이브리드 채점 실행 python3 examples/golden_dataset_tool.py --eval examples/sample-golden-dataset.xlsx # 3. 특정 멀티턴 케이스(HF-ECOM5-T5)의 10점 만점 LLM-as-a-Judge 루브릭 채점 프롬프트 출력 python3 examples/golden_dataset_tool.py --print-judge-prompt HF-ECOM5-T5 ``` ### 실제 실행 결과 (`examples/sample-golden-dataset.xlsx`, 16개 행) ```text case_id turn hf_dataset base_ok cand_ok base_tok cand_tok delta rubric -------------------------------------------------------------------------------------------------------- HF-ECOM5-T1 1 iamjoon/ecommerce-function-calli PASS PASS 4,200 2,350 -44.0% 10/10 HF-ECOM5-T2 2 iamjoon/ecommerce-function-calli PASS PASS 5,800 3,100 -46.6% 10/10 HF-ECOM5-T3 3 iamjoon/ecommerce-function-calli PASS PASS 7,400 3,850 -48.0% 10/10 HF-ECOM5-T4 4 iamjoon/ecommerce-function-calli PASS PASS 9,100 4,500 -50.5% 10/10 HF-ECOM5-T5 5 iamjoon/ecommerce-function-calli PASS PASS 10,800 4,950 -54.2% 10/10 HF-ECOM2-T1 1 iamjoon/ecommerce-function-calli PASS PASS 4,100 2,200 -46.3% 10/10 HF-ECOM2-T2 2 iamjoon/ecommerce-function-calli PASS PASS 6,900 3,600 -47.8% 10/10 HF-ECOM2-T3 3 iamjoon/ecommerce-function-calli PASS PASS 8,300 4,100 -50.6% 10/10 HF-ECOM2-T4 4 iamjoon/ecommerce-function-calli PASS PASS 9,600 4,450 -53.6% 10/10 HF-DELIV-T1 1 jjun123/delivery-app-function-ca PASS PASS 12,400 6,800 -45.2% 10/10 HF-DFM14-T1 1 schneiderkamplab/dfm14-ko-synthe PASS PASS 5,400 2,900 -46.3% 10/10 HF-CLINIC-T1 1 schneiderkamplab/dfm14-ko-synthe PASS PASS 4,900 2,700 -44.9% 10/10 HF-KLAC-T1 1 jihye-moon/klac_legal_aid_counse PASS PASS 6,400 3,300 -48.4% 10/10 HF-KLAC-T2 1 jihye-moon/klac_legal_aid_counse PASS PASS 5,900 3,100 -47.5% 10/10 HF-LABOR-T1 1 seventy4/labor-counsel-qa PASS PASS 5,200 2,850 -45.2% 10/10 HF-OSCE-T1 2 nwirandx/Korean-OSCE-history-tak PASS PASS 9,400 4,600 -51.1% 10/10 -------------------------------------------------------------------------------------------------------- Pass rate : Baseline 16/16 (100.0%) -> Candidate 16/16 (100.0%) Mean rubric score : Baseline 9.62/10 -> Candidate 10.00/10 Total tokens : Baseline 115,800 -> Candidate 59,350 (-48.7%) Cost-of-Pass (tok) : Baseline 7,238 tok/pass -> Candidate 3,709 tok/pass Decision : KEEP (Quality held & tokens reduced) ``` --- ## 관련 연구(논문) - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — 프리프린트 2025. 단일 호출 비용이 아니라 성공한 작업 1건당 기대 비용(`Cost-of-Pass`)으로 모델을 평가합니다. - [$\tau$-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) — 프리프린트 2024. 멀티턴 도구 호출과 정책 준수를 반복 실행 일관성(`pass^k`)으로 평가합니다. - [AI Agents That Matter](https://arxiv.org/abs/2407.01502) — 프리프린트 2024. 에이전트 벤치마크에서 비용과 정확도를 함께 보고하고 데이터 오염을 방지하는 평가 원칙을 정리합니다. - [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) — 프리프린트 2024. 대응 표본 평가에서 신뢰구간과 표본 크기를 계산하는 방법을 다룹니다. - [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) — ICLR 2025. 멀티턴 대화에서 이전 턴에 심어 둔 사실 회상과 갱신 능력을 측정합니다. --- ## 사례 연구: TokenEconomizer (ko/agent-tokenomics/case-tokeneconomizer.md) Canonical URL: > microsoft/TokenEconomizer의 작동 방식과 이 가이드의 문제 해결 단계와의 관계를 설명합니다. [TokenEconomizer](https://github.com/microsoft/TokenEconomizer)는 코딩 에이전트(Claude Code, Codex, GitHub Copilot CLI, Pi, 실험적으로 opencode와 Cursor Agent)를 위한 경험 기반의 블랙박스 비용 제어 플러그인입니다. **같은 저장소**에서 에이전트가 진행한 이전 세션으로부터 학습하며, 에이전트의 모델이나 코드는 변경하지 않습니다. 이 페이지는 공개된 설계를 우리의 표현으로 요약합니다. ## 세 가지 메커니즘 | 메커니즘 | 하는 일 | 보고된 기본값 | |----------|---------|---------------| | **마이크로 스킬** | 반복되는 실패와, 최근 세션을 검토하는 모델로부터 저장소 사실(명령 철자, 환경 변수, 빌드 순서, 파일 위치)을 학습합니다. 확인된 사실은 세션 시작 시 한 번 알려 주고, 반박되면 삭제합니다 | 세션 *k* = 3개마다 검토, 세션 3개에 걸쳐 확인 | | **도구 가지치기** | 프롬프트 *p*개 동안 세션 *m*개 이상에서, 또는 세션 *s*개 동안 사용되지 않은 도구 정의를 에이전트 자체 설정으로 제외합니다. 명령 하나로 복원할 수 있습니다 | *p* = 10, *m* = 2, *s* = 5 | | **실패 루프 대응(루프 가드)** | 판정 모델이 막힌 턴을 점검합니다. 확신도가 *c* 이상이면 방향 전환을 한 번 제안하고, 그래도 막혀 있으면 사용자에게 중단하는 방법을 알립니다. 턴을 직접 중단하지는 않습니다 | *c* = 0.7, 턴당 리디렉션 *r* = 1회 |
저장소 사실
마이크로 스킬
도구 선택
가지치기
실패 대응
루프 가드
TokenEconomizer의 세 가지 블랙박스 방식입니다. 저자는 SWE-Bench의 에이전트–모델 조합 5개에서 평균 비용이 18.4–30.9% 낮아졌다고 보고합니다. 독립적으로 재현한 결과는 아니며, 논문과 본문에서 품질 결과를 함께 확인하세요.
TokenEconomizer 비용 제어 작업 과정을 보여 주는 데모 TokenEconomizer 비용 제어 프레임워크 개요
프로젝트의 공식 시각 자료입니다. 출처: microsoft/TokenEconomizer (Apache 2.0), Experience-Driven Black-Box Cost Control for Coding Agents (arXiv:2610.22732).
## 보고된 결과 저자들은 여섯 개 저장소의 SWE-Bench 작업 277개와 에이전트–모델 조합 5개에서 평균 비용이 **18.4–30.9% 낮아졌다**고 보고합니다. 저장소 × 조합 30개 셀 모두에서 비용이 더 낮았고, 조합 5개 중 4개에서 Pass@1이 더 높았습니다. 비용에는 TokenEconomizer 자체가 수행하는 모든 모델 호출이 포함됩니다. 자세한 내용은 [논문](https://arxiv.org/abs/2610.22732)과 [프로젝트 페이지](https://tokeneconomizer.github.io)를 참고하세요. ## 이 가이드와의 대응 | TokenEconomizer | 낭비 범주([2단계](../02-isolate/)) | 수정([4단계](../04-improve/)) | |-----------------|-------------------------------------|-------------------------------| | 마이크로 스킬 | 저장소 정보 반복 탐색 | 확인된 짧은 사실을 세션 시작 시 제공 | | 도구 가지치기 | 사용하지 않는 도구 | 도구 정의 가지치기 | | 루프 가드 | 실패 루프 | 방향 전환을 한 번 제안한 뒤 사용자에게 알림 | 참고할 만한 설계 원칙은 다음과 같습니다. 에이전트의 **자체 설정**을 통해 동작합니다. 학습한 사실을 알려 주기 전에 **확인**을 요구합니다. 개입 횟수에 **상한**을 둡니다. **최적화 도구 자체의 비용**을 집계에 포함합니다. **실패해도 작업을 계속**(fail open)합니다. 최적화 도구가 실패하면 세션은 설치되지 않은 것처럼 계속 진행됩니다. ## 직접 만든 에이전트에 권장하는 도입 순서 1. **실패 루프 가드:** 현재 턴의 반복 오류를 감지해 한 번 방향을 바꾸고, 계속 실패하면 사용자에게 알립니다. 세션 간 학습 상태가 필요 없으며 비용이 크게 늘어나는 장시간 실행을 제한할 수 있습니다. 2. **사용하지 않는 도구 가지치기:** 사람이 검토한 작업별 도구 집합부터 시작합니다. 세션 간 학습 상태 없이도 반복되는 스키마 오버헤드를 줄일 수 있습니다. 드물게 필요한 도구를 복원할 방법은 남겨 두세요. 위 표의 TokenEconomizer *자동* 가지치기는 여러 세션의 사용 기록을 활용합니다. 3. **저장소 마이크로 스킬:** 세션 로그가 쌓이면 반복적으로 확인되는 사실을 검증한 뒤, 짧고 되돌릴 수 있는 지침으로 세션 시작 시 제공합니다. 이 순서는 실용적인 출발점이지 모든 에이전트에서 가장 큰 절감을 보장하지는 않습니다. 각 변경의 비용과 작업 성공률을 따로 측정하고, 기준선에서 다른 원인의 낭비가 더 크다면 그 원인부터 처리하세요. ## 추가 자료(논문) 학회 등급 순, 같은 등급 안에서는 인용 수 순으로 정렬했습니다. 각 결과는 자신의 워크로드에서 검증해야 할 가설로 취급합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) — NeurIPS 2024, 인용 2,357회. 간결하고 제한된 관찰을 포함한 인터페이스 설계가 에이전트의 성공률을 좌우함을 보여 줍니다. - [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) — ICML 2024, 인용 451회. 에이전트가 과거 궤적에서 재사용 가능한 워크플로를 유도해 다시 활용합니다. 취지가 마이크로 스킬과 비슷합니다. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — 프리프린트 2025, 인용 41회. 모든 도구를 로드하는 대신 관련 있는 MCP 도구 설명만 검색해 가져와 프롬프트 비대화를 줄입니다. - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) — 프리프린트 2026, 인용 36회. 저장소 수준 컨텍스트 파일은 대체로 작업 성공률을 높이지 못했고 추론 비용은 평균 20% 넘게 늘렸습니다. - [TokenEconomizer: Experience-Driven Black-Box Cost Control for Coding Agents](https://arxiv.org/abs/2610.22732) — 프리프린트 2026, 인용 0회. 마이크로 스킬, 도구 가지치기, 루프 가드가 이전 세션의 경험을 활용해 코딩 에이전트의 비용을 줄입니다. --- ## 에이전트 토큰 이코노믹스 (Tokenomics · Token Economics) (ko/agent-tokenomics/index.md) Canonical URL: > LLM 에이전트의 토큰 이코노믹스(Token Economics, 토큰 경제학) 6단계 문제 해결 절차와 tokprof 프로파일링 및 골든 데이터셋 평가 가이드입니다. Track B는 LLM 에이전트를 **직접 만들거나 운영하는** 엔지니어를 위한 **에이전트 토큰 이코노믹스(Agent Tokenomics · Token Economics)** 가이드입니다. 토큰 비용이 높은 상황을 운영 장애처럼 다룹니다. 추측에 의존하지 말고 절차에 따라 원인을 확인하세요. 처음이라면 에이전트가 토큰을 쓰는 방식을 설명하는 [0. 개념](00-concepts/)부터 읽은 다음 절차를 따라가세요. ```text Diagnose → Isolate → Prove → Improve → Result └────────── repeat with the next biggest cause ──────────┘ ``` | 단계 | 질문 | 산출물 | |------|------|--------| | [0. 개념](00-concepts/) | 에이전트는 토큰을 어떻게 쓰는가? | 공통 개념 | | [1. 진단](01-diagnose/) | 지금 토큰이 어디에 쓰이는가? | 측정된 기준선 | | [2. 원인 분리](02-isolate/) | 어떤 원인 때문에 비용이 드는가? | 우선순위를 매긴 가설 하나 | | [3. 입증](03-prove/) | 그 원인이 실제로 존재하며 규모는 얼마인가? | 재현하고 수치화한 낭비 | | [4. 개선](04-improve/) | 원인에 맞는 어떤 변경으로 낭비를 줄일 수 있는가? | 변경 하나, 실험 하나 | | [5. 결과](05-result/) | 품질 저하 없이 비용이 줄었는가? | 유지 / 되돌리기 결정 | | [6. 골든 데이터셋과 루브릭 평가](06-golden-dataset-and-rubric/) | 단일·멀티턴 정답(키워드·의도)과 품질을 어떻게 채점하는가? | 엑셀(CSV) 평가셋 및 하이브리드 루브릭 | 이 외에 [tokprof: 설치 및 사용법](tokprof/), [TokenEconomizer 사례 연구](case-tokeneconomizer/), 개선 방법과 관련된 [논문 순위 목록](../papers/), 실행 가능한 [측정 스크립트](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples)도 제공합니다.
에이전트가 도구와 그 결과를 반복해서 활용해 작업을 진행하는 과정
에이전트 루프에서는 지침, 도구, 대화 기록, 도구 결과가 다음 모델 호출에 영향을 줍니다. 0–5단계에서 이 비용을 진단하고 최적화합니다. 출처: VS Code Docs — Agents Overview, microsoft/TokenEconomizer.
## 준비물 - **요청 로그**: 모델 호출마다 한 건씩 기록한 로그입니다. 입력 / 캐시된 입력 / 출력 토큰, 전송한 도구 정의, 도구 호출과 오류, 해당 호출이 속한 사용자 프롬프트(턴)와 세션을 포함합니다. 대부분의 에이전트 프레임워크가 이 로그를 내보낼 수 있습니다. 그렇지 않다면 모델 클라이언트를 감싸서 직접 기록하세요. - 다시 실행할 수 있는 **작업 세트**(대표 작업 5–20개)와 자동 성공 판정 기준 - 한 번에 변수 하나만 바꾸는 원칙 ## 기본 원칙 토큰을 줄이는 것은 **작업 성공률이 떨어지지 않을 때만** 성과입니다. 항상 비용과 품질 지표를 함께 보고하세요. --- ## tokprof: 설치 및 사용법 (ko/agent-tokenomics/tokprof.md) Canonical URL: > PyPI에서 tokprof를 설치하고 에이전트 코드 수정 없이 세션별, 턴별, 호출별 LLM 토큰 사용량을 분석합니다. [`tokprof`](https://pypi.org/project/tokprof/)는 에이전트 코드를 수정하거나 에이전트 프로젝트에 패키지를 추가하지 않고 **모든 LLM 호출의 입력 토큰**을 시스템 프롬프트, 대화 이력, 현재 사용자 프롬프트, 도구 관련 항목(정의, 호출, 결과, 응답 스키마)으로 분해하는 독립 실행형 네이티브 Rust 단일 바이너리 프로파일러입니다. ## 1. 설치 `tokprof`는 Linux(`x86_64`, `aarch64`), macOS(`arm64`, `x86_64`), Windows(`x64`)용 프리빌트 네이티브 Wheel로 [PyPI](https://pypi.org/project/tokprof/)에 배포되어 있습니다. 사용자 PC에 Rust나 Go 컴파일러가 설치되어 있지 않아도 바로 설치됩니다. ```bash # 독립된 전역 CLI 도구로 설치 (권장) uv tool install tokprof # 또는 pipx install tokprof # 일반 Python 환경에서 pip로 설치 pip install tokprof # 설치 없이 즉시 실행 uvx tokprof --lang ko ``` ### 플랫폼별 배포 패키지 | 플랫폼 | 패키지 형식 | 포함 바이너리 | |--------|-------------|---------------| | Linux `x86_64` 및 `aarch64` | `manylinux2014` Wheel | `tokprof` + 정적 빌드된 `tokprof-ebpf` 헬퍼 | | macOS Apple Silicon(`arm64`) 및 Intel(`x86_64`) | `macosx` Wheel | `tokprof` | | Windows `x64`(`amd64`) | `win_amd64` Wheel | `tokprof.exe` | | 소스 배포판(`sdist`) / Cargo | `tokprof-*.tar.gz` | Rust 소스에서 직접 빌드 (`cargo install --path ./profiler`) | 설치 후 버전과 현재 머신에서 사용할 수 있는 캡처 기능을 확인합니다. ```bash tokprof --version tokprof doctor # 토크나이저, Linux eBPF 커널 BTF/uprobe 지원, mitmproxy, Node 설치 여부 점검 tokprof selftest # 로컬 모의(mock) LLM으로 수집·분해 파이프라인 전체 자체 검증 ``` 한국어 또는 영어로 상세 도움말과 예시를 확인할 수 있습니다. ```bash tokprof --lang ko # 한국어 상세 도움말 및 사용 예시 출력 tokprof --help # 영어 도움말 출력 (기본값) ``` --- ## 2. 빠른 시작 워크플로 ### 워크플로 A — 이미 실행 중인 서비스 및 Docker 컨테이너 측정 (`start` / `status` / `stop`) Linux에서 `tokprof start`를 실행하면 백그라운드 세션을 시작하고, root 권한이나 비밀번호 없는 `sudo`를 사용할 수 있을 때 실행 중인 호스트 프로세스와 Docker 컨테이너에 eBPF 프로브를 자동으로 연결합니다. ```bash # 1. 백그라운드 측정 시작 (특정 프로세스·폴더·컨테이너만 보려면: tokprof start --comm my_agent) tokprof start # 2. 측정할 에이전트 작업, API 요청 또는 테스트를 실행합니다 pytest tests/test_agent.py # 3. 진행 중 지금까지 기록된 LLM 호출 수를 확인합니다 tokprof status # 4. 세션을 종료하고 터미널 요약 리포트 출력 및 .tokprof/latest.html 생성을 수행합니다 tokprof stop ``` > **팁(비 Linux 환경 또는 eBPF 권한이 없는 경우):** eBPF를 사용할 수 없는 환경에서는 `tokprof start`가 `eval "$(tokprof env)"` 안내를 출력합니다. 에이전트를 실행할 터미널에서 해당 명령을 실행하면 하위 프로세스의 요청이 로컬 게이트웨이로 전달됩니다. ### 워크플로 B — 단일 명령어 원스텝 측정 (`tokprof -- <명령>`) Linux, macOS, Windows 어디서나 `--` 뒤에 실행할 명령을 적으면 로컬 게이트웨이와 프로세스 내부 훅을 통해 실행한 뒤, 종료 시 터미널 리포트와 `.tokprof/latest.html`을 바로 생성합니다. ```bash tokprof -- python my_agent.py tokprof -- pytest tests/ tokprof -- node agent.js ``` ### 워크플로 C — 대화형 서브셸 (`tokprof shell`) 하위에서 실행하는 모든 명령을 하나의 세션으로 묶어 기록하는 서브셸을 엽니다. ```bash tokprof shell # 서브셸 안에서 여러 에이전트 명령을 실행한 뒤 종료합니다: exit ``` --- ## 3. 캡처 방식 비교 | 캡처 방식 | 명령어 | 지원 OS | 프로세스 재시작 필요 여부 | 동작 원리 | |-----------|--------|---------|---------------------------|-----------| | **로컬 게이트웨이 + 프로세스 내부 훅** | `tokprof -- `
`tokprof run -- `
`tokprof shell` | Linux, macOS, Windows | 필요 (`tokprof`가 하위 프로세스 시작) | `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `AZURE_OPENAI_ENDPOINT` 및 패턴으로 찾은 `*_BASE_URL` / `*_ENDPOINT` 변수를 `127.0.0.1` 게이트웨이로 라우팅하고, 엔드포인트를 하드코딩한 클라이언트를 위해 Python(`httpx`, `requests`, `urllib3`, `aiohttp`, `urllib.request`) 및 Node(`fetch`, `http`, `https`) 훅을 함께 로드합니다. | | **Linux eBPF 탭** | `tokprof start`
`tokprof ebpf --comm <이름>`
`tokprof ebpf --pid ` | Linux (`x86_64`, `ARM64`) | **불필요** (실행 중인 프로세스에 즉시 연결) | 호스트 프로세스와 Docker 컨테이너의 OpenSSL 및 Go `crypto/tls` 라이브러리에 uprobe를 연결하고, 평문 `http://` 및 `h2c` 호출은 시스템 콜 트레이스포인트로 수집합니다. root 또는 `CAP_BPF` 권한이 필요합니다. | | **mitmproxy 로컬 캡처** | `tokprof mitm --local <프로세스>` | Windows, macOS, Linux | **불필요** (`--local` 모드 사용 시) | `mitmdump`와 `tokprof` 애드온 스크립트로 트래픽을 수집합니다. 프로세스별 CA 인증서 신뢰 설정은 `tokprof mitm --trust-help`로 확인하세요. | | **Azure Application Insights / Log Analytics** | `tokprof pull --workspace `
`tokprof pull --app-insights `
`tokprof import <파일>` | 모든 OS 및 **Azure Cloud Shell** | **불필요** (수집된 텔레메트리 조회) | `AppDependencies`와 `AppTraces`(OpenTelemetry GenAI, OpenInference, APIM, 또는 `[TOKPROF_CHUNK]` 로그)를 조인해 프롬프트·도구 스키마를 역조립하고 7대 세그먼트 분해 또는 Usage-Only 폴백 리포트를 생성합니다. | --- ## 4. 리포트 조회, HTML 대시보드, CSV 내보내기 및 전후 비교 측정이 끝나면 타임스탬프가 붙은 JSONL 로그가 저장되고 `.tokprof/latest.html`이 갱신됩니다. ```bash # .tokprof/에 기록된 가장 최근 실행의 터미널 요약 리포트 출력 tokprof report # 잘림 없이 전체 프롬프트와 응답 원문을 터미널에 출력 tokprof report --full-prompts # 단일 파일 HTML 대시보드(.tokprof/latest.html) 생성 및 브라우저 열기 tokprof report --html --open # 세션별·턴별·호출별 토큰 분해와 프롬프트 원문을 CSV로 저장 tokprof report --format csv --out run.csv tokprof report --csv # 에이전트 실행 중 1초 간격으로 갱신되는 실시간 터미널 대시보드 tokprof report --watch # 사용자 정의 가격표(1M 토큰당 단가)를 적용해 예상 비용 계산 tokprof report --prices prices.json # 최적화 전(before)과 후(after) 두 실행을 95% 부트스트랩 신뢰구간으로 비교 (3단계·5단계) tokprof compare before.jsonl after.jsonl ``` ### HTML 및 CLI 리포트에서 확인할 수 있는 정보 1. **입력 토큰 상세 분해(Input token breakdown)**: 시스템 프롬프트(마크다운 제목 및 XML 태그 단위 분할), 도구 정의, 도구 결과, 도구 호출, 대화 이력(이전 사용자·어시스턴트 턴), 현재 사용자 프롬프트(`utterance`, `context`/`history`, `capabilities` 구조화 JSON 페이로드 자동 분리 포함), 응답 스키마, 미분류 템플릿 오버헤드 비중을 보여 줍니다. 2. **세션별·턴별 흐름(Per-Session & Per-Turn lineage)**: 고정 접두부 토큰, 대화 이력 누적, 캐시 적중률, 턴당 호출 수(`calls/turn`)가 턴이 진행됨에 따라 어떻게 변하는지 시각화합니다. 3. **프롬프트 및 도구 스키마 원문 뷰어(Call & Turn Prompt Dossier)**: 각 턴과 개별 호출에서 실제로 전송된 시스템 프롬프트, 대화 이력, 사용자 프롬프트, 도구 스키마, 모델 응답 원문을 확인할 수 있습니다. 4. **자동 진단 결과(Findings & recommendations)**: 호출되지 않은 도구 정의, 동일한 도구 호출·오류가 반복되는 실패 루프, 시스템 프롬프트 내 동적 값으로 인한 프롬프트 캐시 깨짐, 급격한 대화 이력 증가를 자동으로 감지하고 해당하는 트랙 B 단계로 안내합니다. --- ## 5. 사내·온프레미스 엔드포인트 및 프라이버시 ### 사내 DNS, vLLM, Ollama, TGI, LiteLLM 및 사설 CA 인증서 `tokprof`는 고정된 도메인 목록에 의존하지 않고 요청 본문 구조, URL 경로, 호스트·포트 힌트, 응답 사용량 필드를 종합해 점수를 매깁니다. ```bash # 특정 URL과 요청 본문 JSON이 LLM 호출로 분류되는지 점수와 판정 이유 확인 tokprof explain http://vllm.internal:8000/v1/chat/completions --body request.json # 특정 호스트·경로를 강제로 포함하거나 사내 CA 인증서를 신뢰하도록 지정 tokprof start --llm-host 'gpu*.corp' --llm-path '/internal/ask$' --upstream-ca corp-ca.pem tokprof run --exclude-host telemetry.corp -- python my_agent.py ``` ### 프라이버시 및 마스킹 - **저장하지 않는 항목**: HTTP 헤더(`Authorization`, `x-api-key`)와 API 키는 절대 기록하지 않습니다. - **파일 권한**: `.tokprof/` 아래의 모든 파일은 `0600`(소유자만 읽기·쓰기) 권한으로 생성됩니다. - **프롬프트 원문 제외**: `--no-content`(`tokprof start --no-content` 또는 `tokprof run --no-content -- ...`)를 지정하면 프롬프트·응답 원문을 저장하지 않고 토큰 수, 길이, 솔트 처리된 SHA-256 해시만 기록합니다. --- ## 6. 이미 Azure에 배포된 에이전트 프로파일링 (Cloud Shell & Application Insights) 이미 Azure에 배포되어 운영 중인 에이전트의 경우, 커널 수준 eBPF(`CAP_BPF`)는 Linux VM이나 특권(privileged) AKS 노드에서만 사용할 수 있습니다. App Service, Container Apps(ACA), Azure Functions, Foundry Hosted Agent 같은 관리형 PaaS/Serverless 환경을 위해 `tokprof`는 `tokprof pull`, `tokprof import`, 그리고 무손실 청크 로그 브리지(`TOKPROF_STDOUT_LOG=1`)를 제공합니다. ### Azure 호스팅 환경별 가능 / 불가능 매트릭스 | Azure 호스팅 환경 | `tokprof ebpf` | `tokprof run` / 훅 주입 | `tokprof pull` / `import` (App Insights) | 권장 수집 방식 | |-------------------|----------------|-------------------------|------------------------------------------|----------------| | **Azure VM / VMSS (Linux)** | **가능 (O)** | **가능 (O)** | **가능 (O)** | SSH/Bastion 접속 후 `sudo tokprof start` (재시작 불필요) | | **AKS (Kubernetes)** | **조건부 (△)** (`CAP_BPF` 및 `/sys/kernel/btf` 필요) | **가능 (O)** | **가능 (O)** | 특권 디버그 컨테이너/DaemonSet, 사이드카 게이트웨이, 또는 `tokprof pull` | | **Azure App Service / Container Apps (ACA)** | **불가능 (X)** (커널 샌드박스 격리) | **가능 (O)** (시작 명령 또는 `PYTHONPATH` / `NODE_OPTIONS`) | **가능 (O)** | Application Insights에서 `tokprof pull` 실행 또는 `TOKPROF_STDOUT_LOG=1` 훅 | | **Azure Functions** | **불가능 (X)** | **훅만 가능 (△)** (`PYTHONPATH` / `NODE_OPTIONS`) | **가능 (O)** | Application Insights에서 `tokprof pull` 실행 또는 `TOKPROF_STDOUT_LOG=1` 훅 | | **Azure AI Foundry Hosted Agent** | **불가능 (X)** (완전 관리형 런타임) | **불가능 (X)** | **가능 (O)** | Foundry 프로젝트에 연결된 Application Insights / Log Analytics에서 `tokprof pull` 실행 | ### Azure Cloud Shell에서 `tokprof` 설치 및 실행 `tokprof`는 PyPI에 정적 빌드된 `manylinux2014_x86_64` 네이티브 바이너리 Wheel로 배포되어 있어, Azure Cloud Shell에서 Rust나 Go 컴파일러 없이 수 초 내에 설치되며 `$HOME` 영구 스토리지에 유지됩니다. ```bash # Azure Cloud Shell에 설치 pip install --user tokprof export PATH="$HOME/.local/bin:$PATH" # Log Analytics 또는 Application Insights에서 최근 6시간 LLM 호출 수집 및 분석 # (Cloud Shell의 기존 `az` 로그인 세션을 자동으로 사용합니다) tokprof pull --workspace --since 6h tokprof pull --app-insights --since 2h --conv # Azure Portal Logs에 붙여넣어 확인할 수 있는 KQL 쿼리 출력 tokprof pull --print-kql --since 24h # 내보낸 JSON, NDJSON, 컨테이너 로그 파일을 오프라인으로 변환 및 분석 tokprof import appinsights_export.json --report ``` `tokprof`가 Azure Cloud Shell 환경(`CLOUD_SHELL=true` 또는 `ACC_CLOUD`)을 감지하면 HTML 리포트 서버 포트를 기본 `18765` 대신 Cloud Shell **Web Preview 허용 포트(`8080`, `8000~8090`, `8888`)**로 자동 바인딩하고, 상단 **[Web Preview] → [Configure] → 포트 8080** 열기 또는 `download .tokprof/latest.html` 명령 안내를 출력합니다. ### Application Insights 수집 단계(Tier) 및 32KB 한계 우회 브리지 | 텔레메트리 수집 모드 | 7대 입력 세그먼트 분해 (`system`, `tool_def`, `history_*`, `user_prompt`) | 활성화 방법 | |----------------------|---------------------------------------------------------------------------|-------------| | **Tier 1 — OTel GenAI 프롬프트 원문 기록** | **가능 (7대 세그먼트 + `sysfp` 지문 완벽 지원)** | 에이전트 환경변수에 `AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=true` 또는 `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true`를 설정하여 `AppTraces`에 `gen_ai.*.message` 및 `gen_ai.choice` 이벤트가 기록되도록 합니다. | | **Tier 2 — Usage-Only 폴백 (OTel 기본값)** | **불가 (총 토큰, 비용, 지연 시간, 턴별 추이만 표시)** | 기본 `gen_ai.usage.*` 속성만 있을 때도 에러 없이 `usage_only` 모드로 리포트를 생성하며, 원문 로깅 활성화 방법을 진단 배너로 안내합니다. | | **Tier 3 — 무손실 청크 브리지 (32KB 초과 대형 프롬프트)** | **가능 (100% 무손실 복원, App Insights 32KB 잘림 우회)** | `tokprof`의 Python/Node 훅(`PYTHONPATH` / `NODE_OPTIONS`)과 함께 `TOKPROF_STDOUT_LOG=1`을 설정하면 20KB 단위로 Gzip+Base64 분할된 `[TOKPROF_CHUNK]` 라인을 컨테이너 로그로 출력하며, `tokprof pull` / `import`가 이를 자동으로 병합·복원합니다. | ### 운영 환경 보호 장치: RBAC 권한 분리, Log Analytics 수집 지연(LAW Lag), Cloud Shell 30분 타임아웃 대응 | 운영 환경 문제 상황 | `tokprof` 내장 자동 대응 메커니즘 | CLI 옵션 및 사용법 | |---------------------|-----------------------------------|--------------------| | **워크스페이스 권한 없음 (App Insights 리소스 권한만 보유)** | Log Analytics 워크스페이스 전체 권한 없이 Application Insights 리소스에 대한 `Monitoring Reader`만 있을 때 `/v1/subscriptions/.../query` 경로로 리소스 중심 직접 쿼리 수행 | `tokprof pull --resource-id /subscriptions//.../components/` | | **`AppTraces` 테이블 권한 차단 (Table-level RBAC)** | 보안 정책으로 `AppTraces`만 `403` / `InsufficientAccessError`가 발생할 때 자동으로 `AppDependencies` 전용 쿼리로 폴백하여 `usage_only` 리포트 생성 | `tokprof pull` 실행 시 자동 동작 | | **구독/테넌트 불일치 및 권한 부족 진단** | `401` / `403` / `404`(`InvalidAuthenticationTokenTenant`, `InsufficientAccessError`, `WorkspaceNotFound`) 원인을 분류하고 즉시 실행 가능한 `az account set` / `az role assignment create` 명령 안내 | `tokprof pull` 실행 시 자동 동작 | | **Log Analytics 수집 지연(2~15분) 및 비동기 도착** | `IngestionTime - TimeGenerated` 지연을 계산하고, 먼저 도착한 `AppDependencies`(`usage_only`)가 나중에 도착한 `AppTraces`와 만날 때 **제자리에서 7대 세그먼트(`tier1_full`)로 자동 승격** | `tokprof pull --workspace --wait-ingest 5m --poll-interval 15s` | | **Azure Cloud Shell 20~30분 유휴 타임아웃** | `~/clouddrive/.tokprof`(Azure Files 영구 볼륨)에 `.tokprof/pull-checkpoint.json`과 JSONL을 매 폴링마다 원자적 저장하고, 대기 상한을 25분으로 제한하며 세션 재연결 시 이어받기 지원 | `tokprof pull --resume` | | **HTTP 429 스로틀링 및 소버린 클라우드** | `Retry-After` / `x-ms-retry-after-ms` 헤더 기반 자동 재시도 및 미국 정부/중국 클라우드(`api.loganalytics.us`, `api.loganalytics.azure.cn`) 지원 | `tokprof pull --cloud {public,usgov,china}` | | **멀티 인스턴스 중복 로깅 및 Azure 시크릿 마스킹** | `(OperationId, SpanId)` 기준 중복 Span 병합(토큰 이중 합산 방지) 및 Azure `AccountKey=`, `SharedAccessKey=`, SAS `sig=` 토큰 자동 마스킹 | 자동 동작 | #### 운영 상황별 실전 명령어 예시 (RBAC 우회, LAW 수집 지연 대기, Cloud Shell 재개, 포털 CSV) ```bash # 1) 리소스 중심 RBAC: 공유 Log Analytics 워크스페이스 권한은 없고 # 개별 Application Insights 리소스에 대한 Monitoring Reader 권한만 있을 때 tokprof pull \ --resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-agent/providers/Microsoft.Insights/components/my-agent-ai \ --since 6h # 2) Log Analytics 수집 지연(2~15분) 대기: 지연 도착하는 AppTraces 메시지 이벤트가 모두 들어올 때까지 # 15초 간격으로 폴링하며 usage_only 레코드를 제자리에서 7대 세그먼트(tier1_full)로 자동 승격 tokprof pull --workspace --since 30m --wait-ingest 5m --poll-interval 15s # 3) Azure Cloud Shell 30분 타임아웃 복구: 세션 재접속 후 ~/clouddrive/.tokprof/pull-checkpoint.json의 # 타임스탬프 워터마크부터 이어받아 중복 없이 병합 tokprof pull --resume # 4) Azure Portal CSV 내보내기 파일 오프라인 임포트 (조건부 액세스 등으로 CLI 토큰 발급이 제한된 환경) tokprof import portal_query_export.csv --out .tokprof/portal.jsonl --report # 5) 소버린 클라우드 (Azure US Government 또는 Azure China) 조회 tokprof pull --workspace --cloud usgov --since 24h ``` ### 대용량 로그 처리, 프롬프트 포함/제외 제어 및 검증 방법 #### 로그나 프롬프트가 매우 큰 경우 어떻게 처리되나요? `tokprof`는 단일 프롬프트가 수십만 글자이거나 워크스페이스에 수십만 행의 로그가 쌓여 있어도 토큰 계산과 파이프라인이 중단되지 않도록 **4계층 보호 장치**를 적용합니다. | 보호 계층 | 한도 / 임계치 | 한도 초과 시 동작 방식 | 토큰 수 및 해시 정확도 영향 | |-----------|---------------|------------------------|------------------------------| | **1. 게이트웨이 및 훅 캡처** | 게이트웨이: **64 MB** (`MAX_BODY`)
Python/Node 훅: **32 MB** (`_CAP`) | 최대 32~64 MB 크기의 요청 본문과 SSE 스트리밍 응답을 유실 없이 수집합니다. | **100% 정확** | | **2. 세그먼트별 저장 텍스트 상한** | 세그먼트당 **32,768 문자** (`MAX_SEGMENT_TEXT_CHARS`) | **토큰 수(`tokens`), 글자 수(`chars`), SHA-256 해시(`hash`)를 절단 전 원본 전체에 대해 먼저 계산**한 뒤, 디스크(`.jsonl`/`.html`)에 저장하는 미리보기 텍스트(`text`)만 32,768자에서 자르고 `... [truncated, N chars total]` 표시를 남깁니다. | **100% 정확** (미리보기 절단 전에 토큰 계산 완료) | | **3. App Insights 32KB 컬럼 한도** | `Properties` / `Message` 컬럼당 **32 KB (32,768 B)** | • 단일 패스 `parse_or_repair_json`이 문자열/객체 중간에서 잘린 JSON을 복구해 앞부분 세그먼트를 살리고 `... [truncated by App Insights]`를 표시합니다.
• 에이전트에 `TOKPROF_STDOUT_LOG=1`을 켜면 20KB 단위 Gzip+Base64 `[TOKPROF_CHUNK]` 브리지로 **100KB+ 대형 프롬프트도 손실 0%로 복원**합니다. | 기본 로깅 시 절단 이후 구간은 `residual`로 귀속 / 청크 브리지 사용 시 **100% 정확** | | **4. Log Analytics 쿼리 결과 한도** | 단일 쿼리당 **500,000 행** 또는 **64 MB** (`ResponsePayloadTooLarge`) | • `Accept-Encoding: gzip, deflate, br`로 응답을 수신해 네트워크 전송 크기를 **약 97.7% 축소**합니다.
• `ResponsePayloadTooLarge` 발생 시 자동으로 `\| take 20000` 상한을 붙여 재시도하고, 그래도 초과하면 `AppDependencies` 전용 쿼리로 안전하게 폴백합니다.
• `--limit <행수>` 및 `--usage-only` 수동 제한도 지원합니다. | 안전 폴백으로 쿼리 실패 방지 | #### 프롬프트 원문 포함 / 제외 3단계 제어 모드 보안 정책이나 파일 크기 제약에 따라 **수집(`pull`/`start`/`run`) · 변환(`import`) · 리포트(`report`) 모든 단계**에서 프롬프트 포함 여부를 3단계로 선택할 수 있습니다. | 제어 모드 | CLI 플래그 / 환경변수 | 디스크에 프롬프트 원문 저장 여부 | 7대 세그먼트 분해 및 `sysfp` 해시 | 생성 파일 크기 실측치 (200 호출 / 1,400 세그먼트 기준) | |-----------|-----------------------|----------------------------------|-----------------------------------|--------------------------------------------------------| | **1. 프롬프트 포함 (`full-prompts`)** | *(기본값)*
터미널 전체 출력: `--full-prompts` | **저장함 (O)** (시크릿 자동 마스킹) | **지원 (7대 세그먼트 + `sysfp`)** | JSONL: `1.50 MB`
HTML: `1.90 MB`
CSV: `1.17 MB` | | **2. 세그먼트 분해만 유지 + 원문 제거 (`no-content`)** | `--no-content` 또는 `TOKPROF_NO_CONTENT=1` | **저장 안 함 (`0자`)** | **지원 (모드 1과 토큰·해시 100% 동일)** | JSONL: `384 KB` (**-74.4%**)
HTML: `245 KB` (**-87.1%**)
CSV: `25.6 KB` (**-97.8%**) | | **3. 총량만 수집 (`usage-only`)** | `tokprof pull --usage-only`
`tokprof import --usage-only` | **저장 안 함 (`0자`, `AppTraces` 미조회)** | **생략** (총 토큰·비용·지연 시간·턴 추이만 집계) | JSONL: `138 KB` (**-90.8%**)
HTML: `186 KB` (**-90.2%**)
CSV: `27.8 KB` (**-97.6%**) | ```bash # 모드 1: 프롬프트 및 응답 원문 포함 (기본값) + 터미널에서 생략 없이 전체 원문 출력 tokprof pull --workspace --since 6h tokprof report --full-prompts # 모드 2: 7대 세그먼트 토큰 수와 캐시 해시(sysfp)는 100% 계산하되 프롬프트/응답 텍스트만 완전히 제외 (--no-content) tokprof pull --workspace --since 6h --no-content tokprof import appinsights_export.json --no-content --out .tokprof/no-content.jsonl # 이미 프롬프트가 포함되어 저장된 JSONL에서 원문만 제거하여 외부 공유용 HTML / CSV / JSONL 생성 tokprof report .tokprof/full.jsonl --no-content --html shareable.html --csv shareable.csv tokprof import .tokprof/full.jsonl --no-content --out .tokprof/stripped.jsonl # 모드 3: 초대형 워크스페이스에서 AppTraces 테이블을 아예 쿼리하지 않고 토큰 총량만 고속 수집 (--usage-only / --limit) tokprof pull --workspace --since 7d --usage-only --limit 50000 ``` #### 프롬프트 포함·제외 및 절단 여부를 실제로 확인(검증)하는 방법 1. **`tokprof pull` / `tokprof import` 실행 시 자동 출력되는 `content verification` 요약 확인:** 실행 직후 터미널(`stderr`)에 현재 모드, 텍스트가 포함된 세그먼트 비율, 저장된 프롬프트·응답 글자 수, 32KB 절단 복구 건수가 즉시 출력됩니다. ```text # 기본(full-prompts) 실행 시: tokprof: content verification — mode=full-prompts, segments_with_text=1400/1400, stored_prompt_chars=1000580, stored_response_chars=74890, 32k_preview_capped=0, appinsights_32kb_repaired=0 # --no-content 실행 시 (1,400개 세그먼트는 그대로 유지되면서 저장된 글자 수가 0자임을 즉시 증명): tokprof: content verification — mode=no-content, segments_with_text=0/1400, stored_prompt_chars=0, stored_response_chars=0, 32k_preview_capped=0, appinsights_32kb_repaired=0 # --usage-only 실행 시: tokprof: content verification — mode=usage-only, segments_with_text=0/0, stored_prompt_chars=0, stored_response_chars=0, 32k_preview_capped=0, appinsights_32kb_repaired=0 ``` 2. **`jq` 원라이너로 `.jsonl` 파일 내 원문 존재 여부 및 절단 건수 직접 감사:** 생성된 `.tokprof/*.jsonl` 파일에 프롬프트(`text`)나 응답(`response_text`) 필드가 단 1건이라도 남아 있는지 아래 명령으로 즉시 검증할 수 있습니다. ```bash jq -s '{ calls: length, total_segments: ([.[].segments | length] | add), segments_with_text: ([.[].segments[] | select(.text != null)] | length), responses_with_text: ([.[] | select(.response_text != null)] | length), appinsights_32kb_repaired: ([.[] | select(.detect.truncated_repaired == true)] | length), preview_32k_capped: ([.[].segments[] | select(.text != null and (.text | contains("[truncated,")))] | length) }' .tokprof/no-content.jsonl ``` --- ## 7. 주요 CLI 명령어 요약 | 명령어 | 설명 | |--------|------| | `tokprof start [--comm 이름] [--no-content]` | 백그라운드 측정 세션을 시작합니다(Linux에서는 eBPF 자동 연결). | | `tokprof status` | 활성 백그라운드 세션 상태와 기록된 LLM 호출 수를 확인합니다. | | `tokprof stop` | 세션을 종료하고 터미널 요약 리포트와 `.tokprof/latest.html`을 생성합니다. | | `tokprof -- <명령> [인자...]` | 단일 명령을 실행해 프로파일링하고 터미널 및 HTML 리포트를 출력합니다. | | `tokprof profile [--comm 이름 \| -- <명령>]` | 실행 중인 프로세스 또는 하위 명령을 포그라운드에서 측정합니다. | | `tokprof report [파일] [--format 형식] [--html] [--csv]` | 기록된 JSONL 로그를 리포트로 출력합니다(`pretty`, `text`, `html`, `csv`, `md`, `json`). | | `tokprof compare ` | 두 실행 기록을 95% 부트스트랩 신뢰구간으로 비교합니다. | | `tokprof run -- <명령> [인자...]` | 로컬 게이트웨이와 프로세스 내부 훅을 통해 명령을 실행합니다. | | `tokprof shell` | 하위 프로세스가 모두 측정되는 대화형 서브셸을 엽니다. | | `tokprof ebpf (--pid PID \| --comm 이름 \| --all)` | 이미 실행 중인 프로세스에 Linux eBPF 프로브를 연결합니다. | | `tokprof mitm [--local 프로세스 \| --trust-help]` | Windows, macOS, Linux에서 `mitmproxy`로 트래픽을 캡처합니다. | | `tokprof pull (--workspace ID \| --app-insights ID \| --resource-id ARM_ID) [옵션]` | Azure Application Insights / Log Analytics에서 배포된 에이전트 호출을 수집·분해합니다(`--since`, `--wait-ingest`, `--resume`, `--no-content`, `--usage-only`, `--limit`, `--cloud`). | | `tokprof import <파일> [--no-content] [--usage-only] [--report]` | 내보낸 App Insights JSON/CSV, OTel GenAI, APIM, `[TOKPROF_CHUNK]` 로그를 JSONL로 변환합니다. | | `tokprof explain [--body 파일]` | 특정 URL과 요청 본문이 LLM 호출로 판별되는 점수와 이유를 설명합니다. | | `tokprof export --out ` | 기록을 `examples/token_report.py` 호환 요약 스키마로 변환합니다. | | `tokprof doctor` | 로컬 토크나이저, 커널 eBPF 지원, 헬퍼 바이너리 상태를 점검합니다. | | `tokprof selftest` | 로컬 모의 LLM 서버를 띄워 전체 파이프라인을 자체 테스트합니다. | ## 출처 - PyPI 패키지: [PyPI의 `tokprof`](https://pypi.org/project/tokprof/) (2026-11-06 확인) - 소스 코드 및 구조: [`dotnetpower/agent-tokenomics`의 `profiler/`](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler) --- ## Copilot 사용량은 어떻게 과금되는가 (ko/copilot-tokenomics/01-how-usage-is-charged.md) Canonical URL: > VS Code GitHub Copilot 토큰 이코노믹스 과금 가이드: AI 크레딧 기반 사용량 과금(입력·캐시·출력 토큰 요율)과 프리미엄 요청 배수를 설명합니다. ## 문제 비용을 줄이려면 먼저 과금 방식을 알아야 합니다. 현재 두 가지 과금 모델이 있으며, 각 모델에 맞는 절약 방법이 다릅니다. ## 달라진 점 - **사용량 기반 과금(현재).** GitHub은 **2026년 6월 1일**부터 Copilot 사용량에 **GitHub AI 크레딧**을 차감한다고 발표했습니다. 크레딧은 **모델**과 **처리한 토큰 수**에 따라 다른 비율로 차감됩니다. 각 플랜에는 월별 기본 제공량이 포함됩니다. - **기존 프리미엄 요청 과금.** 기존 연간 플랜을 사용하던 일부 Pro/Pro+ 구독자는 요청 기반 과금을 유지했습니다. 이 방식에서는 채팅에서 보낸 프롬프트 하나가 모델 배수를 곱한 프리미엄 요청 1건으로 계산되며, 에이전트 실행 중의 자율적인 도구 호출은 따로 계산하지 않습니다. | | 사용량 기반(AI 크레딧) | 기존 방식(프리미엄 요청) | |---|---|---| | 단위 | 토큰 × 모델 요율 | 프롬프트 × 모델 배수 | | 긴 채팅 기록 | 비용 증가(입력으로 다시 전송) | 토큰 단위로 과금하지 않음 | | 큰 도구 목록/지침 | 비용 증가(요청마다 전송) | 토큰 단위로 과금하지 않음 | | 가장 효과적인 방법 | 컨텍스트 축소, 적절한 모델 선택 | 프롬프트 수 감소, 배수가 낮은 모델 선택 | 절약 방법을 고르기 전에 GitHub Copilot 청구 설정에서 사용 중인 플랜을 확인하세요.
VS Code Copilot 상태 대시보드에서 사용량을 확인하는 화면
Copilot 상태 대시보드에서 사용량을 확인합니다. 출처: VS Code Docs — Optimize AI credit usage in VS Code.
## 모든 요청에서 토큰이 중요한 이유 요청할 때마다 **입력 토큰**(시스템 프롬프트, 지침, 도구 정의, 지금까지의 전체 대화, 첨부 파일, 도구 결과)을 보내고 **출력 토큰**(추론 토큰 포함)을 받습니다. 대화가 길어질수록 입력이 늘어나므로, 오래된 컨텍스트에도 비용이 반복해서 듭니다. 제공자는 변경되지 않은 요청 접두부를 재사용할 수 있으며(**프롬프트 캐싱**), 요청의 앞부분이 안정적으로 유지되면 비용과 지연 시간이 줄어듭니다. ### 캐시된 입력과 과금 접두부 캐시에 적중하면 AI 크레딧 과금에서는 `cached_input_tokens`에 일반 입력 요율 대신 해당 모델의 할인된 캐시 읽기 요율이 적용됩니다. 기존 프리미엄 요청 과금에서는 캐시 적중 여부와 관계없이 프롬프트당 `1 × 모델 배수`만큼 요청을 사용합니다. 다만 캐싱은 지연 시간과 속도 제한 부담을 줄이는 데 도움이 될 수 있습니다. 모델 선택기에 마우스를 올려 적용 요율을 확인하고 Agent Debug Logs에서 요청의 캐시 사용량을 살펴보세요. 실제 청구 내용은 플랜의 사용량 보고서에서도 확인합니다. ## 트레이드오프 이 가이드의 방법은 *컨텍스트*와 *비용* 사이에서 균형을 잡는 데 도움이 됩니다. 모델에 필요한 컨텍스트를 제거하면 재시도와 재작업이 생기고, 절약한 것보다 비용이 더 들 수 있습니다. ## 출처 - [GitHub Copilot is moving to usage-based billing (GitHub Blog, 2026-04-27)](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/) - [Usage-based billing for individuals (GitHub Docs)](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals) - [Requests in GitHub Copilot — legacy (GitHub Docs)](https://docs.github.com/en/copilot/concepts/billing/copilot-requests) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) --- ## 사용량 측정 (ko/copilot-tokenomics/02-measure-usage.md) Canonical URL: > VS Code Agent Debug Logs, Cache Explorer, 컨텍스트 윈도우 컨트롤, cctx usage 대시보드로 Copilot 토큰과 AI 크레딧 소비를 측정합니다. ## 문제 "Copilot이 비싸다"는 느낌만으로는 원인을 알 수 없습니다. *어떤* 세션, 요청, 구성 요소에 비용이 가장 많이 드는지 확인해야 합니다. ## 조치 1. **요청별** — 채팅 응답 위에 마우스를 올리면 해당 턴에서 사용한 크레딧을 볼 수 있습니다. 2. **세션별** — 채팅 입력란의 **컨텍스트 윈도우 컨트롤**에 마우스를 올리거나 컨트롤을 선택합니다. 팝오버에 세션 전체 비용(크레딧)과 누적 컨텍스트 윈도우 토큰 사용량이 표시됩니다. 3. **월별** — VS Code 상태 표시줄에서 **Copilot 상태 대시보드**를 열면 월 기본 제공량 중 사용한 비율을 볼 수 있습니다. GitHub의 사용량 세부 정보로 연결되는 링크도 있습니다. 4. **세션 내부 확인** — **Agent Debug Logs**를 엽니다(채팅 뷰의 `...` 메뉴 → *Show Agent Debug Logs*). **Summary** 뷰에서는 전체 토큰 사용량, 도구 호출, 소요 시간을 확인하고, **Logs** 뷰에서는 개별 요청, 오류, 도구 호출을 확인합니다. 5. **프롬프트 캐싱** — Summary에서 캐시 재사용률은 낮은데 소요 시간이나 입력 토큰이 예상보다 클 때 **Cache Explorer**(Agent Debug Logs → Summary → *Cache Explorer*)를 사용합니다. 연속된 요청을 비교하면 프롬프트 시그니처(시스템 지침, 도구 정의, 메시지)에서 *처음 달라진 지점*을 확인할 수 있습니다. 6. **맞춤 팁** — 채팅 세션에서 `/chronicle:cost-tips`를 실행하면 최근 활동을 바탕으로 한 권장 사항을 받을 수 있습니다. Chronicle cost-tips 참가자가 활성화된 최신 VS Code / Copilot Chat 빌드가 필요합니다. 사용할 수 없다면 Agent Debug Logs → **Summary**와 **Cache Explorer**를 직접 이용하세요. 7. **모델 비용** — 모델 선택기에 마우스를 올리면 토큰 유형별 비용과 Low / Medium / High 등급이 표시됩니다. 8. **실시간 코드 탐색 및 멀티 세션 절감 대시보드(`cctx`)** — VS Code Marketplace에서 [Code Context (`cctx`) 확장](../cctx/)(`dotnetpower.code-context-native`)을 설치하면, 하단 상태 표시줄의 `CCTX N` 배지 호버 툴팁이나 터미널의 `cctx usage --hours 24` 명령으로 최근 세션 전체의 모델별 토큰 소비, 프롬프트 캐시 적중률, 탐색 속도, 추정 절감 금액(AIC/USD)을 바로 확인할 수 있습니다.
VS Code Agent Logs Summary 뷰에서 전체 토큰 사용량과 도구 호출 요약을 보여주는 화면 VS Code Cache Explorer에서 연속된 두 요청의 캐시된 접두부와 첫 불일치 지점을 비교하는 화면
VS Code Agent Debug Logs의 Summary 뷰(왼쪽)와 연속된 요청의 프롬프트 캐시 불일치 지점을 비교하는 Cache Explorer(오른쪽). 출처: VS Code Docs — Agent Debug View 및 Cache Explorer.
## 확인 방법 대표적인 작업 하나를 골라 같은 모델로 두 번 실행합니다. 요청별 크레딧, 세션 합계, 캐시 적중률(%)을 기록합니다. 이 값을 이후 변경 사항을 비교할 기준선으로 삼습니다. 변경 전후를 비교하려면 요청 또는 세션 요약 값을 기준선 기록에 복사하세요. Agent Debug Logs에서 세션을 선택하고 **Export**로 OpenTelemetry JSON을 저장할 수도 있습니다. 같은 작업과 모델로 실행한 두 결과를 비교하고, 내보낸 파일을 공유하기 전에는 민감한 내용이 없는지 확인하세요. ## 트레이드오프와 주의 사항 - Cache Explorer의 비교 결과는 보고된 캐시 지표를 설명할 뿐, 제공자가 요청을 실제로 어떻게 처리하고 과금했는지를 **증명하지는 않습니다**. 일부 모델에서는 캐시 정보가 없을 수도 있습니다. - 캐시 재사용률을 높이려고 꼭 필요한 지침이나 도구를 제거하지 않습니다. 품질을 우선하세요. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 논문의 결과는 각자의 워크로드에서 검증해야 하는 가설입니다. 전체 목록은 [논문](../../papers/)을 참조합니다. - [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) — NeurIPS 2023, 인용 1,783회. RadixAttention으로 접두부를 공유하는 호출 간에 KV 캐시를 재사용합니다. 접두부 캐싱의 기반이 되는 연구입니다. - [Prompt Cache: Modular Attention Reuse for Low-Latency Inference](https://arxiv.org/abs/2311.04934) — MLSys 2023, 인용 417회. 반복되는 프롬프트 모듈의 사전 계산된 어텐션 상태를 재사용해 지연 시간을 줄입니다. - [Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks](https://arxiv.org/abs/2601.06007) — 프리프린트 2026, 인용 25회. 장기 에이전트 작업에서 프롬프트 캐싱의 효과를 평가합니다. ## 출처 - [Optimize AI credit usage in VS Code — Monitor and Inspect sections](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) - [Debug chat interactions](https://code.visualstudio.com/docs/agents/agent-troubleshooting/chat-debug-view) --- ## 컨텍스트를 가볍게 유지하기 (ko/copilot-tokenomics/03-context-hygiene.md) Canonical URL: > 새 채팅, /fork, /compact 컨텍스트 압축, #file 첨부, 제외 설정, cctx 블록 클램핑 조회로 VS Code Copilot 토큰 낭비를 줄입니다. ## 문제 대화가 이어지면 메시지, 도구 출력, 파일 내용이 쌓입니다. 새 요청을 보낼 때마다 이 기록이 입력으로 다시 전송되므로, 관련 없는 이전 주제에도 토큰이 계속 소비됩니다. ### 컨텍스트 윈도우와 컨텍스트 열화 **컨텍스트 윈도우**는 모델이 한 요청에서 처리할 수 있는 최대 범위이며, 입력과 출력이 이 범위를 함께 사용합니다. 컨텍스트 윈도우에는 최대 한도가 있지만, 그 한도에 도달하기 훨씬 전부터 답변 품질이 떨어질 수 있습니다. 모델이 긴 컨텍스트의 중간에 있는 정보를 처음이나 끝에 있는 정보보다 덜 안정적으로 활용하기 때문입니다([Lost in the Middle](https://arxiv.org/abs/2307.03172)). 따라서 비용과 품질을 모두 고려해 작업에 필요한 정보는 충분히 제공하되 불필요한 컨텍스트는 제거해야 합니다.
VS Code 채팅에서 항목별 토큰 사용량을 보여 주는 컨텍스트 윈도우 컨트롤 VS Code 채팅에서 필요한 컨텍스트를 추가하는 선택기
컨텍스트 사용량을 확인하고(왼쪽) 필요한 컨텍스트를 추가합니다(오른쪽). 출처: VS Code Docs — Add context to chat 및 Optimize AI credit usage.
## 조치 | 상황 | 조치 | |-----------|--------| | 관련 없는 작업으로 전환할 때 | **새 채팅 세션**을 시작합니다(`Ctrl+N` / `⌘N`). | | 다른 방법을 시도하거나 곁가지 질문을 하고 싶을 때 | 다시 설명하는 대신 대화를 **포크**합니다(`/fork` 또는 메시지에 마우스를 올린 뒤 *Fork Conversation*). | | 긴 세션을 계속 사용해야 할 때 | `/compact`를 실행해 이전 턴을 요약합니다(`/compact focus on the API design decisions`처럼 초점을 지정할 수도 있습니다). | | 관련 코드를 알고 있을 때 | 에이전트가 넓게 검색하도록 두지 말고 파일, 폴더, 심볼을 **#으로 직접 지정**합니다. | | 코드베이스 검색이 필요할 때 | `#codebase`는 검색을 실행합니다. 코드베이스 전체를 컨텍스트에 추가하지는 **않습니다**. | | 반복적인 `grep` + `view` 왕복으로 작업이 느려지고 이력이 비대해질 때 | VS Code Marketplace에서 [Code Context (`cctx`)](../cctx/)를 설치해 블록 단위로 클램핑된 `#cctxNativeContext` 1회 조회(`<8 KiB` 인라인 예산, 웜 탐색 15.20배 가속 및 작업 완료 시간 24.7% 단축 보고)를 사용합니다. | | 검색 결과에 로그, 빌드 출력, 생성된 파일이 많이 섞일 때 | 제외합니다. `.gitignore`(인덱스와 에이전트 검색), `files.exclude`(완전히 숨김), `search.exclude`(에이전트 검색에서만 숨김)를 사용합니다. | | 웹 참조가 필요할 때 | URL과 함께 `#fetch`는 필요할 때만 사용합니다. 가져온 페이지는 컨텍스트에 들어갑니다. | | 독립적인 조사가 필요할 때 | **서브에이전트**에 위임해 탐색 과정이 메인 대화에 남지 않게 합니다. | 검색에서 일치한 스니펫은 에이전트가 해당 파일을 열지 않아도 컨텍스트 윈도우에 포함됩니다. 따라서 노이즈가 많은 경로를 제외하면 곧바로 효과가 있습니다. ### 서브에이전트 위임의 손익분기 기준 서브에이전트에 위임하면 탐색 중간 결과가 메인 채팅의 컨텍스트 윈도우에 쌓이지 않지만, 서브에이전트의 첫 턴에도 자체 시스템 프롬프트와 도구 스키마 접두부 비용이 듭니다. 실용적인 기준으로 도구 호출 5회 이하의 짧은 조회는 메인 채팅에서 직접 처리하세요. 이후 메인 세션의 턴마다 중간 출력이 불어날 수 있는 광범위한 조사나 여러 파일 탐색만 위임합니다. 격리에는 비용이 드므로 작업 성공 여부와 비용을 함께 측정하세요. ## 확인 방법 변경 후 [사용량 측정](../02-measure-usage/)의 기준선 작업을 다시 실행하고, 세션 크레딧과 컨텍스트 윈도우 토큰 수를 비교합니다. 답변 품질이 유지되는지도 확인합니다. ## 트레이드오프 - `/compact`로 요약하면 일부 정보가 사라질 수 있습니다. 계속 필요한 세부 정보가 요약 과정에서 사라질 수 있습니다. 초점 지시를 추가하고, 반드시 남겨야 할 내용(결정 사항, 제약 조건, 파일 경로, 미해결 항목)을 명시합니다. - 컨텍스트 압축은 기록의 시작 부분을 바꾸므로 해당 접두부에 대한 제공자의 프롬프트 캐시가 다시 만들어집니다. 반복하지 말고 작업이 자연스럽게 끊기는 시점에 한 번만 압축합니다. 남은 작업이 짧다면 그냥 끝내는 편이 더 저렴한 경우가 많습니다. - 긴 세션에서 큰 도구 결과(파일 읽기, 명령 출력)가 대부분을 차지한다면, 대화를 요약하는 것보다 이러한 결과를 줄이거나 짧은 인수인계 메모와 함께 새 채팅을 시작하는 편이 대체로 더 효과적입니다. - 새 채팅을 시작하면 기록이 사라집니다. 오래 유지할 사실은 [사용자 지정 지침](../04-instructions-and-tools/)에 넣어 매번 다시 설명하지 않도록 합니다. - 가능한 모든 컨텍스트가 아니라, 작업을 성공시키는 데 필요한 **최소한의 신뢰할 수 있는 컨텍스트**만 첨부합니다. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 논문의 결과는 각자의 워크로드에서 검증해야 하는 가설입니다. 전체 목록은 [논문](../../papers/)을 참조합니다. - [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) — TACL 2023, 인용 5,818회. 관련 정보가 긴 입력의 중간에 있으면 정확도가 떨어집니다. - [Large Language Models Can Be Easily Distracted by Irrelevant Context](https://arxiv.org/abs/2302.00093) — ICML 2023, 인용 1,358회. 프롬프트에 관련 없는 컨텍스트가 있으면 모델 정확도가 크게 낮아질 수 있습니다. - [LLMs Get Lost In Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) — ICLR 2025, 인용 562회. 모델은 요구 사항이 불충분한 멀티턴 대화에서 단일 턴보다 성능이 떨어집니다. - [Same Task, More Tokens: the Impact of Input Length on the Reasoning Performance of Large Language Models](https://arxiv.org/abs/2402.14848) — ACL 2024, 인용 270회. 입력 길이만 따로 분리해, 입력이 길어질수록 추론 성능이 떨어짐을 보여 줍니다. - [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) — 프리프린트 2025, 인용 66회. 에이전트 컨텍스트 관리에서 단순한 관찰 마스킹이 LLM 요약만큼 효율적입니다. ## 출처 - [Add context to chat](https://code.visualstudio.com/docs/chat/copilot-chat-context) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) --- ## 지침과 도구 (ko/copilot-tokenomics/04-instructions-and-tools.md) Canonical URL: > 매 요청마다 반복 전송되는 사용자 지정 지침(copilot-instructions.md, AGENTS.md)과 도구 스키마 목록을 줄여 고정 토큰 세금을 낮춥니다. ## 문제 요청에 포함되는 사용자 지정 지침과 도구 정의는 반복적인 입력 비용을 발생시킵니다. 사용하지 않거나 불필요하게 큰 항목은 고정 비용과 같습니다. 일부 도구 스키마는 필요할 때 로드할 수 있습니다([MCP 감사](../09-mcp-audit/) 참조).
범위 없는 지침 + 도구 40개
고정 82%
작업 18%
100%
applyTo 범위 지정 + 도구 가지치기
고정 22%
작업 18%
40%
측정 결과가 아닌 가상의 예시입니다. 변경 전 입력을 기준으로 고정 비용은 82%에서 22%로 줄고 작업은 18%로 유지되어, 변경 후 전체 입력은 기존의 40%가 됩니다. 작업 내용은 유지하면서 지침과 도구의 고정 비용을 줄이는 모습을 보여 주며, 실제 절감량은 다릅니다. 색상은 구성의 차이를 나타낼 뿐 캐시 적중 여부를 뜻하지 않습니다.
VS Code의 에이전트 지침 설정을 보여 주는 채팅 사용자 지정 편집기
VS Code에서 에이전트 사용자 지정을 관리합니다. 출처: VS Code Docs — Agent Customization Overview.
## 조치 **사용자 지정 지침**(`.github/copilot-instructions.md`, `*.instructions.md`, `AGENTS.md`) - *안정적이고 가치가 높은* 사실만 남깁니다. 기본값과 다른 빌드/테스트 명령, 필수 환경 변수, 생성된 파일의 위치, 에이전트가 추론할 수 없는 규칙이 해당합니다. - `*.instructions.md`의 `applyTo`로 범위를 지정해, 언어나 폴더에 한정된 규칙이 해당 위치에서만 로드되게 합니다. 지침은 세 단계로 나누어 생각합니다. **상시 적용**(항상 적용되는 소수의 규칙), **조건부 적용**(`applyTo` 경로 규칙), **필요 시 적용**(PR 검토처럼 가끔 쓰는 워크플로를 위한 스킬이나 메모)입니다. - 에이전트가 코드에서 쉽게 알아낼 수 있는 내용은 삭제합니다. 긴 스타일 가이드를 붙여 넣지 않습니다. - 지침에 사실을 한 번 적어 두면 에이전트가 세션마다 다시 찾을 필요가 없습니다. - `copilot-instructions.md`, `AGENTS.md`, `CLAUDE.md`, `*.instructions.md`에 같은 규칙을 중복하지 마세요. 적용 대상 파일이 함께 주입되면 고정 접두부 토큰이 중복됩니다. 범위마다 기준이 되는 원본 하나만 유지하고 실제로 로드된 지침을 확인하세요. - 규칙은 간결하게 씁니다(군더더기 없는 선언형 규칙). 이 파일은 모든 요청에서 다시 전송됩니다. - 도구 선택 우선순위나 폴백 조건을 정의할 때는 **BPE 친화적 수식 표기법**(`조건 => 도구`, `상황 -> 조치`, `>` 우선순위 체인; [프롬프트와 출력 스타일](../06-prompt-and-output-style/#4-bpe-aligned-formula-notation) 참조)을 고려합니다. VS Code용 참고 사례로, [dotnetpower/code-context](https://github.com/dotnetpower/code-context)의 자동 로드 지침(`*.instructions.md`)을 106줄 줄글(9,127바이트, `o200k_base` 2,048토큰)에서 26줄 BPE 정렬 수식 명세(2,688바이트, 718토큰)로 변환했을 때 12개 엣지케이스 시나리오의 규칙 인식률 **100% (31/31)**를 유지하면서 매 턴 전송되는 지침 토큰을 **64.9%** 줄였습니다. **자동 생성한 지침을 그대로 방치하지 마세요.** 리포지토리 컨텍스트 파일을 다룬 ETH Zurich 연구(arXiv 2602.11988)에 따르면, 컨텍스트 파일은 대체로 작업 성공률을 높이지 못하면서 추론 비용을 평균 20% 넘게 늘렸습니다. 리포지토리 개요는 도움이 되지 않았고, **표준에서 벗어난 관행**에 대한 지침은 에이전트가 잘 따랐습니다. 이 파일을 버그 트래커처럼 다룹니다. 에이전트가 실제 "지뢰"를 밟았을 때 한 줄을 추가하고, 코드에서 알아낼 수 있는 줄은 삭제하며, 코드가 바뀌면 다시 평가합니다. | 유지(지뢰 규칙) | 삭제(스스로 파악 가능) | |------------------|----------------------------| | "`pip`가 아니라 `uv`를 사용한다" | "이 프로젝트는 Python 프로젝트다" | | "테스트는 `--no-cache`로 실행한다" | "테스트는 `tests/`에 있다" | | "`auth/`는 리팩터링하지 않는다 — 감사 진행 중" | "PostgreSQL을 사용한다" | | "배포하려면 VPN이 필요하다" | "코드 품질이 중요하다"(내용 없는 조언) | **도구 목록** - 채팅 입력란의 **Configure Tools**에서 현재 작업에 필요한 도구나 MCP 서버만 사용 설정합니다. - 사용자 지정 에이전트에서는 `tools` 속성을 작업에 맞는 좁은 목록으로 지정합니다. - 단일 목적의 MCP 도구 수십 개를 로드하기보다, 터미널 도구로 호출하는 집중된 CLI 하나를 우선 고려합니다. 조직에서 이를 유지 관리하고 보안을 확보할 수 있는 경우에 해당합니다. - 세션을 시작하기 **전에** 도구를 선택합니다. 세션 도중에 MCP 서버를 사용 설정하면 도구 정의가 바뀌어 프롬프트 캐시 재사용이 깨질 수 있습니다(Cache Explorer에서 처음 달라진 지점으로 확인됩니다). **결정적 반복 작업 묶기** - 대량 작업이나 폴링 워크플로는 검토를 마친 스크립트를 터미널에서 실행하고, 모델에는 요약만 전달합니다. 여러 번 도구를 호출해 출력이 컨텍스트에 쌓이는 일을 피합니다. ## 확인 방법 Agent Debug Logs에서 줄이기 전후의 첫 요청 입력 토큰을 비교합니다. 그런 다음 기준선 작업을 실행해 세션 크레딧을 비교합니다. 품질도 다시 확인합니다. 에이전트가 지침에서 제거한 내용을 다시 찾고 있지는 않은지 살펴봅니다. ## 트레이드오프 - 지침을 지나치게 줄이면 같은 내용을 반복해서 탐색하게 되고, 도구를 지나치게 줄이면 작업이 실패하거나 수동으로 우회해야 합니다. - 스크립트 방식과 대화형 방식을 비교해 측정합니다. 절감 효과는 도구와 결과에 따라 달라집니다. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 논문의 결과는 각자의 워크로드에서 검증해야 하는 가설입니다. 전체 목록은 [논문](../../papers/)을 참조합니다. - [Batch Prompting: Efficient Inference with Large Language Model APIs](https://arxiv.org/abs/2301.08721) — EMNLP 2023, 인용 154회. 여러 샘플을 하나의 프롬프트에 담아 지침 토큰을 공유합니다. - [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) — 프리프린트 2025, 인용 55회. 모든 도구 스키마를 주입하는 대신 에이전트가 필요한 도구를 요청하게 합니다. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — 프리프린트 2025, 인용 41회. 모든 도구를 로드하는 대신 관련 있는 MCP 도구 설명만 검색해 가져옵니다(프롬프트 비대화 완화). - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) — 프리프린트 2026, 인용 36회. 리포지토리 컨텍스트 파일은 대체로 작업 성공률을 높이지 못했고 추론 비용을 평균 20% 넘게 늘렸습니다. ## 출처 - [Optimize AI credit usage — Keep the tool catalog focused, Batch repetitive operations, Ground the agent](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) - [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents? (arXiv:2602.11988)](https://arxiv.org/abs/2602.11988) - 도구 목록을 더 깊이 다루는 절차는 [MCP 점검](../09-mcp-audit/)을 참조합니다. --- ## 모델, 계획, 위임 (ko/copilot-tokenomics/05-models-and-planning.md) Canonical URL: > 측정 결과를 바탕으로 모델을 고르고, 코딩 전에 계획하며, 범위가 정해진 작업을 위임합니다. ## 문제 토큰당 가장 저렴한 모델이 작업 결과를 얻는 데도 가장 저렴한 것은 아닙니다. 잘못된 접근으로 곧바로 코드를 작성하면 세션 전체가 낭비될 수도 있습니다.
VS Code 언어 모델 선택 메뉴 VS Code 사고 강도 선택 메뉴
모델(왼쪽)과 사고 강도(오른쪽)를 선택합니다. 출처: VS Code Docs — Language Models.
## 조치 1. **측정 결과를 바탕으로 모델을 선택합니다.** 기대하는 결과와 평가 방법을 먼저 정의합니다. 출력은 비결정적이므로 후보 모델마다 두 번 이상 실행합니다. 완료 여부, 품질, 안정성, 소요 시간, 크레딧을 비교하고, 기준을 꾸준히 충족하는 가장 저렴한 모델을 고릅니다. 모델이 바뀌면 다시 평가합니다. 2. **관리하기 쉬운 기본 설정:** **자동 모델 선택**을 사용합니다. 반복되는 워크플로에서는 **사용자 지정 에이전트**에 모델을 고정합니다. 3. **사고 강도는 기본값으로 둡니다.** 강도를 높이면 사고 토큰이 늘어나 비용과 지연 시간이 커집니다. 아키텍처 계획이나 여러 단계의 디버깅처럼 정말 복잡한 작업에서만 높입니다. 4. **계획한 다음 구현합니다.** 성능이 높은 모델로 Plan 에이전트를 실행하고 계획을 검토한 뒤, 범위가 명확한 작업으로 나눕니다. 각 작업은 더 저렴한 모델, 작업에 맞는 지침, 최소한의 도구를 갖춘 **사용자 지정 서브에이전트**에 위임합니다. 기본 에이전트가 결과를 검토합니다. ### 실패와 재시도의 역설 단순화하면 `total cost = rate × calls × accumulated context`입니다(`accumulated context`는 호출당 평균 토큰 수). 가상의 예로 토큰 요율이 프런티어 모델의 3분의 1인 모델이 테스트 루프에서 네 번 실패한 뒤 성공하면, 호출당 평균 컨텍스트가 같더라도 한 번에 성공한 프런티어 모델 비용의 최소 `1/3 × 5`가 듭니다. 도구 출력이 쌓여 컨텍스트가 커지면 비용은 더 늘 수 있습니다. 실제 청구에서는 입력, 캐시된 입력, 출력의 요율도 구분합니다. 모델을 비교할 때는 작업 성공 기준을 같게 유지하고 재시도, 도구 출력, 최종 성공 실행까지 포함하세요. ## 확인 방법 반복되는 작업 유형에서 (a) 성능이 높은 모델 하나로 처음부터 끝까지 수행한 경우와 (b) 성능이 높은 모델로 계획하고 더 저렴한 모델로 작업자를 구성한 경우를 비교합니다. 크레딧, 재시도 횟수, 결과가 인수 기준을 충족하는지 기록합니다. ## 트레이드오프 - 위임 자체도 토큰을 사용합니다. 격리와 저렴한 모델의 이점이 오케스트레이션 오버헤드를 상쇄하지 못하는 작은 작업은 메인 세션에서 처리합니다. - 저렴한 모델을 사용하더라도 재시도나 재작업이 필요하면 전체 비용이 더 커질 수 있습니다. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 논문의 결과는 각자의 워크로드에서 검증해야 하는 가설입니다. 전체 목록은 [논문](../../papers/)을 참조합니다. - [FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance](https://arxiv.org/abs/2305.05176) — TMLR 2023, 인용 1,247회. LLM을 선택하고 연쇄 호출해 더 낮은 비용으로 강력한 모델에 가까운 품질을 얻습니다. - [Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing](https://arxiv.org/abs/2404.14618) — ICLR 2024, 인용 519회. 라우터가 질의의 난이도를 예측해 쉬운 질의를 더 작은 모델로 보냅니다. - [AutoMix: Automatically Mixing Language Models](https://arxiv.org/abs/2310.12963) — NeurIPS 2023, 인용 169회. 작은 모델이 자신의 답을 스스로 검증하게 하고, 필요할 때만 더 큰 모델로 넘깁니다. - [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) — ICLR 2025, 인용 56회. 정답을 얻는 데 드는 기대 비용을 정의하고, 이를 기준으로 모델을 비교합니다. - [RouteLLM: Learning to Route LLMs with Preference Data](https://arxiv.org/abs/2406.18665) — 프리프린트 2024, 인용 922회. 선호도 데이터로 학습해 질의를 강력한 모델과 더 저렴한 모델 사이에서 라우팅합니다. ## 출처 - [Optimize AI credit usage — Choose models, Plan and delegate, Thinking effort](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [AI model comparison (GitHub Docs)](https://docs.github.com/en/copilot/reference/ai-models/model-comparison) --- ## 프롬프트와 출력 스타일 (ko/copilot-tokenomics/06-prompt-and-output-style.md) Canonical URL: > 간결한 프롬프트, 구조화된 요청, 출력 제한으로 입력과 출력 비용을 줄이는 방법을 설명합니다. ## 문제 보낸 토큰과 모델이 생성한 토큰 **모두**에 비용이 듭니다. 프롬프트의 군더더기는 한 번에 그치지만, *답변*의 군더더기는 요청마다 반복됩니다. 대부분의 모델에서 출력 토큰은 입력 토큰보다 단가도 높습니다. 따라서 응답 길이를 조절하는 것이 들인 노력 대비 가장 효과가 큰 방법인 경우가 많습니다. 모델별 요금은 GitHub Docs의 모델 가격 정보에서 확인하세요. 입력과 출력의 요금 비율은 모델마다 다릅니다.
VS Code에서 프롬프트 파일을 만드는 화면
재사용할 프롬프트 파일을 만듭니다. 출처: VS Code Docs — Prompt Files.
## 조치 ### 1. 출력을 제한합니다(효과가 가장 큼) `copilot-instructions.md`에 상시 규칙을 추가하거나, 프롬프트 끝에 형식 제한을 덧붙입니다. | 지시문 | 효과 | |-------------|--------| | `Code only, no explanation.` | 변경 내용 주변의 설명 문장이 사라집니다. 이유가 필요하면 "왜"를 명시적으로 물어봅니다. | | `Answer in one sentence.` | 장황한 답변을 막습니다. | | `3 bullet points max.` | 항목 수를 제한합니다. | | `Yes or no, then one line why.` | 답변과 이유를 짧게 받습니다. | | `Reply as JSON.` / `Table format.` | 서술 없이 구조화된 출력만 받습니다. | *프롬프트*가 간결하다고 *답변*도 간결해지지는 않습니다. 프롬프트도 간결하게 쓰고 답변 길이도 지정합니다. **구조화된 출력의 트레이드오프.** `response_format`이나 엄격한 JSON 스키마는 결과 파싱을 쉽게 하지만, 추론까지 고정된 형식에 맞추면 여러 단계가 필요한 작업의 정확도가 떨어질 수 있습니다. [Let Me Speak Freely?](https://arxiv.org/abs/2408.02442)는 평가한 모델과 작업에서 이 현상을 보고했으며, 모든 모델이나 스키마에 일반화할 수는 없습니다. 정확도가 떨어지면 형식을 적용하기 전에 짧게 추론하도록 허용하거나 마지막 단계에서 구조화된 필드를 추출하세요. 스키마 유효성과 작업 성공 여부를 함께 확인합니다. 이 설정의 사용 가능 여부는 클라이언트와 제공자에 따라 다릅니다. ### 2. 프롬프트를 다듬습니다 - 공손한 표현, 완곡한 표현, 군더더기(`please`, `I think maybe`, `basically`)를 뺍니다. 기술 용어, 코드, 구체적인 내용은 그대로 둡니다. - 줄글보다 **구조화된** 입력(글머리 기호, `key: value`)을 사용합니다. - 절차보다 **선언형** 규칙을 사용합니다. "먼저 파일을 읽고, 그다음 …를 찾아서" 같은 단계별 설명 대신 `All exported functions: JSDoc required.`처럼 씁니다. - 가장 짧고 정확한 형태는 코드에 가까운 경우가 많습니다. 타입 시그니처, 의사 코드, 또는 "`getUserById`와 비슷하게, 이메일로 조회. 없으면 404 반환" 같은 식입니다. - 일반적인 약어(`DB`, `auth`, `config`, `env`, `repo`)는 모델이 이미 아는 경우에만 사용합니다. 프로젝트 고유의 약어는 지침에서 먼저 정의합니다. - **프롬프트 하나에는 작업 하나만 담습니다.** 리팩터링, 테스트, 문서, 보안을 한 프롬프트에 섞으면 각 부분이 불완전하게 처리되기 쉽습니다. 작업을 나누고 단계마다 검토하여, 실패한 단계만 다시 수행합니다. ### 3. 간결한 스타일 지침 커뮤니티의 "caveman" 스타일 스킬은 *관사와 군더더기 생략, 단편적 문장 허용, 코드는 그대로 유지*와 같은 짧은 규칙으로 입력과 출력을 모두 압축합니다. [caveman](https://github.com/JuliusBrussee/caveman)과 [측정 평가](https://github.com/danielle34/cavewoman)를 참고하세요. 압축 수준이 높을수록 토큰은 줄지만 명확성이 떨어집니다. 복잡한 지시가 모호해질 수 있으므로, 고객 대상 문서나 온보딩 문서에는 가볍게만 적용합니다. ### 4. BPE 친화적 수식 표기법 도구 분기 조건이나 다단계 워크플로를 적을 때 **BPE 친화적 ASCII 수식**을 쓰면 줄글보다 짧고 모호성도 줄어듭니다. 다만 **유니코드 수학 기호(`∀`, `∈`, `∪`, `≻`, `∘`)는 오히려 함정**입니다. `o200k_base`와 `cl100k_base`에서 이러한 다중 바이트 기호는 2~3토큰으로 쪼개질 뿐 아니라, 뒤에 오는 영단어의 선행 공백 병합까지 깨뜨려 바이트가 절반으로 줄어도 토큰 수는 거의 줄지 않습니다. 반면 공백을 둔 ASCII 연산자(` ->`, ` =>`, ` >`, ` <=`, ` >=`, ` &`, ` |`)는 선행 공백을 포함해 각각 **단일 1토큰**으로 병합됩니다. [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py)(또는 `python3 examples/formula_prompt.py --lang en`)로 측정한 결과입니다(`tiktoken` 0.14.0, 2026-11-04 확인). | 표현 방식 | 텍스트 | 바이트 | `o200k_base` | 줄글 대비 | `cl100k_base` | |-------|------|------:|-------------:|----------:|--------------:| | 줄글 (백틱 포함) | ``When you need to find a symbol or literal and read its surrounding lines, use `code_context` in one call instead of searching first and reading later.`` | 150 | 31 | 0.0% | 31 | | 유니코드 수학 수식 (붙여쓰기) | `∀x∈Sym∪Lit: need(x+ctx) ⇒ code_context(x) ≻ (grep(x) ∘ read(x))` | 75 | 30 | -3.2% | 31 | | ASCII 수식 (붙여쓰기) | `δ(symbol\|literal+surrounding_lines)=>code_context(root,pattern,radius<=20)` | 75 | 20 | -35.5% | 20 | | **BPE 정렬 수식 (띄어쓰기)** | `symbol + context => code_context (1 call > grep + read)` | **55** | **14** | **-54.8%** | **14** | BPE 정렬 수식 작성 원칙은 다음과 같습니다. - 유니코드 수학 기호(`∀`, `∈`, `≻`, `∘`) 대신 **앞에 공백을 둔 ASCII 연산자**(` ->`, ` =>`, ` >=`, ` <=`, ` !=`, ` &`, ` |`)를 사용합니다. - 모든 식별자를 인라인 백틱(`` `name` ``)으로 감싸지 않습니다(식별자마다 양쪽 백틱에 2토큰씩 추가 소모됩니다). - 연산자 앞뒤에 공백을 두어 `" 단어"`가 하나의 BPE 토큰으로 묶이게 합니다. Hugging Face 공개 데이터셋의 영문 고객지원 SOP 및 실시간 라이브챗 안내문 7종(`examples/formula_prompt_en.py`)에 이 규칙을 적용하면 필수 슬롯과 플레이스홀더를 **43/43 (100%)** 보존하면서 토큰 수를 **`o200k_base` 기준 75.9%** 줄일 수 있습니다(한국어 전용 채팅·상담 예제는 `examples/formula_prompt_ko.py` 및 [언어와 토큰화](../07-language-and-tokenization/#hugging-face-customer-support-and-counseling-benchmark)를 참고하세요). | 영문 고객지원 SOP·채팅 사례 및 Hugging Face 데이터셋 (`row`) | 원문 (`o200k` / `cl100k`) | BPE 수식 (`o200k` / `cl100k`) | `o200k_base` 변화 | `cl100k_base` 변화 | 핵심 슬롯 보존 | |--------------------------------------------------------------|--------------------------:|------------------------------:|------------------:|-------------------:|---------------:| | 주문 취소 절차 안내 ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[2]`) | 223 / 226 | 55 / 55 | **-75.3%** | **-75.7%** | 9/9 | | 주문 변경 절차 안내 ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[1001]`) | 225 / 230 | 54 / 54 | **-76.0%** | **-76.5%** | 9/9 | | 위약금·취소 수수료 조회 ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[3001]`) | 98 / 100 | 26 / 27 | **-73.5%** | **-73.0%** | 5/5 | | 환불 소요 기간 및 주문번호 조회 ([`bitext/Bitext-customer-support-llm-chatbot-training-dataset`](https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset) `train[6000]`) | 221 / 225 | 34 / 34 | **-84.6%** | **-84.9%** | 5/5 | | 리콜 모니터 반품·환불 안내 ([`NebulaByte/E-Commerce_Customer_Support_Conversations`](https://huggingface.co/datasets/NebulaByte/E-Commerce_Customer_Support_Conversations) `train[1]`) | 131 / 131 | 42 / 42 | **-67.9%** | **-67.9%** | 6/6 | | 로봇 암 보정 기술지원 채팅 ([`FunDialogues/customer-service-robot-support`](https://huggingface.co/datasets/FunDialogues/customer-service-robot-support) `train[0]`) | 60 / 61 | 18 / 18 | **-70.0%** | **-70.5%** | 5/5 | | 배송 지연 실시간 라이브챗 응답 ([`Kaludi/Customer-Support-Responses`](https://huggingface.co/datasets/Kaludi/Customer-Support-Responses) `train[0]`) | 28 / 29 | 9 / 9 | **-67.9%** | **-69.0%** | 4/4 | | **합계 (7개 영문 고객지원 SOP·채팅 사례)** | **986 / 1,002** | **238 / 239** | **-75.9%** | **-76.1%** | **43/43 (100%)** | ## 확인 방법 효과를 가정하지 말고 직접 측정하세요. `o200k_base` 인코딩으로 [토큰 카운터](../07-language-and-tokenization/)를 실행하면, 예시 프롬프트 하나가 38토큰에서 11토큰으로 줄어듭니다. ```text Hey, could you please help me refactor this function? I think it might have some issues with how it handles the authentication, and I'd really like it to be more efficient. Thanks! -> 38 tokens Refactor function. Fix auth handling. Make efficient. -> 11 tokens ``` 그런 다음 실제 작업 하나에서 적용 전후의 **세션 크레딧**을 비교하고, 출력이 여전히 수락 기준을 충족하는지 확인합니다. ## 트레이드오프 - 학습이나 디버깅에는 설명이 필요합니다. 필요할 때 요청합니다(`Explain why this beats X`). - 지나치게 압축한 프롬프트는 제약 조건을 잃습니다. 정확한 기술 용어와 구체적인 내용은 유지합니다. - 이 문서의 바탕이 된 발표 자료는 이러한 지침으로 출력이 크게 줄었다고 보고합니다(수십 퍼센트이며, 예/아니오 형식에서는 더 큽니다). 이 수치는 독립적으로 재현하지 못했습니다. 방향성만 참고하고, 직접 작업에서 측정하세요. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 각 연구 결과는 가설이므로 자신의 워크로드에서 검증해야 합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression](https://arxiv.org/abs/2310.06839) — ACL 2023, 인용 658회. 긴 컨텍스트를 질문 기반으로 압축해, 정확도를 유지하거나 높이면서 비용을 줄이는 것을 목표로 합니다. - [LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression](https://arxiv.org/abs/2403.12968) — ACL 2024, 인용 487회. 더 빠르고 작업에 구애받지 않는 프롬프트 압축기를 증류하여, 여러 작업에 일반화합니다. - [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736) — EMNLP 2023, 인용 418회. 작은 언어 모델로 정보량이 낮은 토큰을 프롬프트에서 제거하며, 예산을 조절할 수 있습니다. - [Compressing Context to Enhance Inference Efficiency of Large Language Models](https://arxiv.org/abs/2310.06201) — EMNLP 2023, 인용 272회. 자기 정보량(self-information)을 기준으로 중복된 어휘 단위를 제거해, 추론 전에 입력을 줄입니다. - [Let Me Speak Freely? A Study On The Impact Of Format Restrictions On Large Language Model Performance.](https://arxiv.org/abs/2408.02442) — EMNLP 2024, 인용 142회. 출력 형식을 엄격하게 제한하면 추론 성능이 떨어질 수 있음을 보여 줍니다. - [Chain of Draft: Thinking Faster by Writing Less](https://arxiv.org/abs/2502.18600) — 프리프린트 2025, 인용 324회. 장황한 chain-of-thought 대신 최소한의 초안 단계만 쓰도록 모델에 유도합니다. ## 출처 - Token Efficiency and Context Engineering — 개발자 발표 자료(2026년 6월), 프롬프트 압축 및 출력 제어 부분(수치는 보고된 그대로이며 독립적으로 검증하지 않음) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [`examples/formula_prompt_en.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_en.py), [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) — 재현 가능한 영문 BPE 수식 토큰 측정 및 프롬프트 변환 스크립트 - [caveman](https://github.com/JuliusBrussee/caveman), [cavewoman](https://github.com/danielle34/cavewoman) --- ## 언어와 토큰화 (ko/copilot-tokenomics/07-language-and-tokenization.md) Canonical URL: > 같은 문장도 언어에 따라 토큰 수가 달라지는 이유와 대응 방법을 설명합니다. ## 문제 "프롬프트를 모국어로 쓰는 편이 저렴할까요, 아니면 번역해서 보내는 편이 저렴할까요?" 토큰 수는 토크나이저에 따라 달라지는데, 토크나이저는 대부분 영어 텍스트로 학습됩니다. 같은 의미를 표현하더라도 영어가 아닌 언어에 **더 많은 토큰**이 필요한 경우가 많습니다. 따라서 언어를 선택하기 전에 사용하는 모델로 직접 측정하는 편이 좋습니다. ## 직접 측정하기 [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py)는 한 문장("I met a huge dog")을 여러 언어로 바꿔 [tiktoken](https://github.com/openai/tiktoken)으로 토큰 수를 셉니다. 측정 결과는 다음과 같습니다(tiktoken 0.14.0, 2026-11-03). | 언어 | 문자 수 | o200k_base 토큰 | × 영어 | cl100k_base 토큰 | × 영어 | |----------|-----------:|------------------:|----------:|-------------------:|----------:| | English | 16 | 5 | 1.0 | 5 | 1.0 | | Spanish | 24 | 7 | 1.4 | 8 | 1.6 | | Korean | 13 | 8 | 1.6 | 13 | 2.6 | | Chinese | 8 | 8 | 1.6 | 12 | 2.4 | | Japanese | 9 | 8 | 1.6 | 11 | 2.2 | | Russian | 26 | 7 | 1.4 | 14 | 2.8 | | Hebrew | 13 | 7 | 1.4 | 16 | 3.2 | 이 예제에서 확인할 수 있는 점은 두 가지입니다. 1. **문자 수가 적다고 토큰 수가 적은 것은 아닙니다.** 중국어, 일본어, 한국어는 문자 수가 적지만 문자 하나가 토큰 하나 이상을 차지할 수 있습니다. 2. **차이는 토크나이저에 따라 달라집니다.** 새 어휘(`o200k_base`)를 사용하면 이전 어휘(`cl100k_base`)보다 차이가 크게 줄어듭니다. Copilot은 여러 공급자로 요청을 라우팅할 수 있으므로, 사용하는 모델과 가까운 인코딩으로 스크립트를 실행하거나 해당 공급자의 토큰 계산 API를 사용해 정확한 수치를 확인합니다. ## 조치 - **지침 파일과 상시 규칙은 영어로 작성합니다.** 이 내용은 모든 요청에 전송되므로, 여기서 발생하는 지속적인 배수 차이가 가장 큰 영향을 줍니다. - **토큰을 아끼려고 프롬프트를 번역하지 않습니다.** 번역 비용이 절감액보다 클 수 있고 의미가 바뀔 수도 있습니다. 먼저 직접 측정하세요. - **한국어 요청·답변 워크플로에서는 한국어 핵심 명사·동사를 유지하고 연결 어미·조사만 BPE 수식 연산자로 바꿉니다.** 한국어 프롬프트에서 토큰을 많이 쓰는 부분은 도메인 명사가 아니라 서술어 어미와 보조용언(`~을 완료할수 있도록`, `~에 대한 계획을 세워서`, `~한 다음`)입니다. 핵심 한글 어근(`남은작업 계획수립`, `보강점 >=100 발굴`, `모두조치`, `수치표 보고`)은 그대로 두고 연결부만 공백을 둔 ASCII 수식 연산자(` ->`, ` =>`, ` >=`, ` <=`, ` &`)와 `[ko]` 응답 언어 태그로 치환하면, 의미 왜곡 없이 입력 토큰을 **`o200k_base` 기준 22~39%**(**`cl100k_base` 기준 31~49%**) 줄이면서 한국어 답변을 100% 유지할 수 있습니다. - 채팅에 사용하는 언어와 관계없이 **코드, 식별자, 주석, 커밋 메시지는 영어로 유지합니다**. - 비라틴 문자는 라틴 문자로 음역하면 토큰이 줄어들 수 있지만, 가독성이 떨어집니다. 도입하기 전에 측정합니다. - 가장 읽기 편한 언어로 *답변*하도록 요청하는 것은 꼭 필요할 때만 합니다. 답변은 출력 토큰이며 단가가 더 높습니다. ### 한국어 핵심어 보존 + BPE 수식 실측 비교 [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py)(또는 `python3 examples/formula_prompt.py --lang ko`)로 측정한 결과입니다(`tiktoken` 0.14.0, 2026-11-04 확인). | 작업 유형 | 한국어 원문 (`o200k` / `cl100k`) | 한국어 핵심어 + BPE 수식 (`[ko] :: ...`) | `o200k_base` 변화 | `cl100k_base` 변화 | |------------------|----------------------------------:|---------------------------------------------|-------------------:|--------------------:| | 이슈 완결 파이프라인 | 44 / 72 | `[ko] :: #1945 남은작업 계획수립 -> 모두조치 -> push & merge -> 이슈닫기` | **27 (-38.6%)** | **37 (-48.6%)** | | 대량 발굴 및 반복 보강 | 46 / 74 | `[ko] :: 보강점 >=100 발굴 -> 모두조치 -> loop 10x -> 수치표 보고 -> commit & push & merge` | **31 (-32.6%)** | **38 (-48.6%)** | | 조건부 하드닝 루프 | 54 / 91 | `[ko] :: 모두적용 -> loop(비평 >=10 하드닝, until 심각도 <= Low) -> 개선점 >=100 발굴 -> 모두보강 -> push & merge -> 보고` | **42 (-22.2%)** | **57 (-37.4%)** | | 최적화 발굴 및 목록화 | 31 / 51 | `[ko] :: 절감액 기반 최적화 >=30 발굴 -> 계획수립 -> 목록 보고` | **22 (-29.0%)** | **35 (-31.4%)** | | **합계 (4개 프롬프트)** | **175 / 288** | — | **122 (-30.3%)** | **167 (-42.0%)** | 한국어 명사까지 억지로 영문 약어로 바꾸면 어떤 문제가 생길까요? 실제 한국어 Copilot 요청 8종(세부 제약 47개 항목)으로 검증한 결과, `"보강점 100개 이상 찾아서"`를 단순히 영문 `gaps >=100`으로 치환하면 모델이 이를 **"100개 이상 발굴하라(명령)"**가 아니라 **"갭이 100개 이상인지 확인하라(조건문)"**로 오독하여 제약 준수율이 **81.5% (44/54)**로 떨어졌습니다. 반면 한국어 핵심 동작 명사(`보강점 >=100 발굴`, `남은작업 계획수립`)를 보존하고 연산자만 수식화했을 때는 **제약 준수율 100.0% (47/47)**와 **한국어 응답 100%**를 달성했습니다. **한국어 핵심 명사 앞에는 공백을 두고 불필요한 따옴표·괄호를 제거합니다.** `o200k_base` 어휘 사전에는 `" 고객"`, `" 담당"`, `" 주문"`, `" 완료"`, `" 직접"`, `" 처리"`, `" 확인"`, `" 전달"`, `" 안내"`, `" 기준"` 등을 포함해 **앞에 공백이 있을 때만 단일 1토큰으로 병합되는 2음절 이상 한국어 단어가 643개** 있습니다. 공백 없이 붙여 쓰거나(`직접처리` 3토큰 vs `직접 처리` 2토큰, `주문완료` 3토큰 vs `주문 완료` 2토큰) 따옴표·낫표(`'무선 이어폰'`, `‘무선 이어폰’`, `「근로기준법」`)로 감싸면 선행 공백 병합이 깨져 오히려 토큰 수가 늘어납니다. ### Hugging Face 공개 상담·고객지원 데이터셋 실측 비교 이 원칙은 인사말, 사과 표현, 반복적인 약관·법령 안내문이 토큰의 상당 부분을 차지하는 한국어 고객센터·법률·노무 상담 데이터에서도 동일하게 작동합니다. [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py)와 [`examples/test_formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/test_formula_prompt.py)로 측정·검증한 결과입니다(`tiktoken` 0.14.0, 2026-11-04 확인. 영문 SOP 전용 예제는 `examples/formula_prompt_en.py` 및 [프롬프트와 출력 스타일](../06-prompt-and-output-style/#4-bpe-aligned-formula-notation)을 참고하세요). | 한국어 채팅·상담 사례 및 Hugging Face 데이터셋 (`row`) | 원문 (`o200k` / `cl100k`) | BPE 수식 (`o200k` / `cl100k`) | `o200k_base` 변화 | `cl100k_base` 변화 | 핵심 슬롯 보존 | |--------------------------------------------------------|--------------------------:|------------------------------:|------------------:|-------------------:|---------------:| | 이커머스 배송 조회·환불/취소 약관 ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[5]`) | 103 / 158 | 64 / 94 | **-37.9%** | **-40.5%** | 11/11 | | 노트북 불량 기술지원·영수증 이관 ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[2]`) | 90 / 147 | 45 / 73 | **-50.0%** | **-50.3%** | 8/8 | | 이커머스 반품·교환 약관 안내 ([`iamjoon/ecommerce-function-calling-datasets-korean`](https://huggingface.co/datasets/iamjoon/ecommerce-function-calling-datasets-korean) `train[6]`) | 101 / 173 | 59 / 99 | **-41.6%** | **-42.8%** | 9/9 | | 배달 앱 주문 요약·결제·도착시간 이관 ([`jjun123/delivery-app-function-calling-datasets-korean`](https://huggingface.co/datasets/jjun123/delivery-app-function-calling-datasets-korean) `train[0]`) | 173 / 229 | 127 / 162 | **-26.6%** | **-29.3%** | 11/11 | | 퇴직급여제도 설정 의무·예외 요건 ([`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) `train[1]`) | 173 / 256 | 73 / 109 | **-57.8%** | **-57.4%** | 7/7 | | 최저임금법 제6조 및 수습 90% 특례 ([`jihye-moon/klac_legal_aid_counseling`](https://huggingface.co/datasets/jihye-moon/klac_legal_aid_counseling) `train[0]`) | 124 / 189 | 65 / 101 | **-47.6%** | **-46.6%** | 7/7 | | 평균임금 산정 및 최저기준 원칙 ([`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) `train[2,3]`) | 104 / 177 | 65 / 113 | **-37.5%** | **-36.2%** | 6/6 | | 해고 30일 전 예고 의무 및 예외 요건 ([`seventy4/labor-counsel-qa`](https://huggingface.co/datasets/seventy4/labor-counsel-qa) `train[34]`) | 90 / 142 | 51 / 74 | **-43.3%** | **-47.9%** | 7/7 | | 무인보관함 배송지 변경 채팅 상담 ([`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[2]`) | 51 / 68 | 30 / 36 | **-41.2%** | **-47.1%** | 4/4 | | 병원 검진 슬롯 조회 채팅 안내 ([`schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1`](https://huggingface.co/datasets/schneiderkamplab/dfm14-ko-synthetic-tool-dialogue-r1) `train[11]`) | 91 / 164 | 42 / 68 | **-53.8%** | **-58.5%** | 7/7 | | **합계 (10개 한국어 채팅·상담·법률 사례)** | **1,100 / 1,703** | **621 / 929** | **-43.5%** | **-45.4%** | **77/77 (100%)** | 평가한 벤치마크에서 이 하이브리드 방식은 한국어 Copilot 요청 8건의 제약 조건 47개를 모두 유지했습니다. 별도의 실시간 벤치마크에서는 Hugging Face 데이터셋 7개의 한국어 사례 330건에서 추출한 엄격한 슬롯 1,314개를 모두 보존했고, 시험한 두 토크나이저에서 토큰 수도 늘리지 않았습니다([실시간 벤치마크](../../agent-tokenomics/04-improve/#compaction-without-losing-the-cache) 참조). 이는 시험한 집합의 결과일 뿐 의미 정확성이나 임의의 입력에 대한 보장이 아닙니다. 실제 도메인의 프롬프트에서도 슬롯 보존, 작업 정확도, 토큰 수를 확인하세요. 누락을 줄이기 위해 `examples/formula_prompt_ko.py`와 `examples/formula_prompt_en.py`는 압축 전 인식 가능한 법조문(`제N조`, `제N항`, `제N호`), 대법원 사건번호(`98다46198`), 이메일, 전화번호, 케밥케이스 엔티티 ID(`parcel-610`, `locker-16`), 고객·주문·상품 ID, 수량, 금액, 날짜, 템플릿 플레이스홀더(`{{...}}`)를 전수 추출해 누락된 슬롯을 자동 복원(`ensure_slot_preservation`)하며, 압축 후보가 `o200k_base` 토큰 수를 줄이지 못하면 원문으로 폴백합니다. 다중 턴 채팅·상담 대화 이력 압축과 580건 실시간 벤치마크(`--compress-dialogue`, `--hf-live --hf-rows 50`)는 [트랙 B — 4. 개선](../../agent-tokenomics/04-improve/#compaction-without-losing-the-cache)을 참고하세요. ## 트레이드오프 명확성과 정확성이 작은 토큰 절감보다 중요합니다. 한국어(또는 다른 언어)로 생각할 때 더 정확하다면, 복잡한 요구 사항은 그 언어로 작성합니다. 지침이나 도구 설명처럼 *상시* 전송되는 파일만 영어로 유지합니다. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 각 연구 결과는 가설이므로 사용자의 워크로드에서 검증해야 합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909) — ACL 2015, 인용 9,243회. 대부분의 LLM 토크나이저의 기반이 되는 서브워드(BPE) 단위를 제안했습니다. - [Language Model Tokenizers Introduce Unfairness Between Languages](https://arxiv.org/abs/2305.15425) — NeurIPS 2023, 인용 319회. 같은 텍스트라도 언어에 따라 토큰 길이가 크게 달라짐을 보여 줍니다. - [Do All Languages Cost the Same? Tokenization in the Era of Commercial Language Models](https://arxiv.org/abs/2305.13707) — EMNLP 2023, 인용 278회. 토큰화 차이 때문에 상용 API 사용 비용이 언어마다 다르다는 점을 보여 줍니다. ## 출처 - [`examples/count_tokens.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py) — 재현 가능한 측정 - [`examples/formula_prompt_ko.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt_ko.py), [`examples/formula_prompt.py`](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/formula_prompt.py) — 재현 가능한 한국어 + BPE 수식 측정 및 프롬프트 변환 스크립트 - [tiktoken](https://github.com/openai/tiktoken) - Token Efficiency and Context Engineering — 개발자 발표 자료(2026년 6월). 다른 토크나이저를 사용했지만 같은 방향(영어 외 텍스트에 더 많은 토큰이 듦)을 보고합니다. 이 문서의 표는 직접 측정한 결과입니다. --- ## 에이전트 모드와 예산 가드 (ko/copilot-tokenomics/08-agent-modes-and-budget.md) Canonical URL: > Ask, Plan, Agent 모드의 차이, 에이전트 루프 제한, 추론 강도, 클라우드 에이전트 설정을 설명합니다. ## 문제 에이전트 실행은 **루프**입니다. 각 단계가 모델 호출이며, 호출할 때마다 지침, 도구 정의, 지금까지의 대화가 다시 전송됩니다. 프롬프트가 모호하면 에이전트가 오래 탐색한 끝에 의도를 잘못 이해해 처음부터 다시 시작해야 할 수 있습니다.
모델 요청과 도구 호출을 보여 주는 Agent Debug View 흐름도 VS Code에서 사용자 지정 에이전트를 만드는 화면
에이전트 실행을 살펴보고(왼쪽) 사용자 지정 에이전트를 만듭니다(오른쪽). 출처: Agent Debug View 및 Custom Agents.
## 조치 ### 상황에 맞는 가장 저렴한 모드를 선택합니다 | 모드 | 일반적인 형태 | 용도 | |------|---------------|---------| | Ask | 모델 호출 1회 | 질문, 설명, 조회 | | Plan | 계획 단계 1회 | 코드를 작성하기 전에 변경 범위 정리 | | Agent | 다수의 호출(도구 루프) | 여러 파일에 걸친 리팩터링, 처음부터 기능 구현 | 질문에는 Ask를 기본으로 사용하고, 범위를 명확히 할 때는 Plan을 사용합니다. 작업에 정말로 도구가 필요할 때만 Agent를 사용합니다. 비용이 큰 패턴은 모호한 프롬프트로 Agent를 실행하는 것입니다. ### 루프를 제한합니다 - **`chat.agent.maxRequests`** — 한 번의 실행에서 에이전트가 보낼 수 있는 최대 요청 수입니다(2026-11-03 기준으로 확인한 VS Code 설정 참조 문서의 기본값은 25). 루프가 걷잡을 수 없이 늘어나는 것이 걱정되면 값을 낮추고, 긴 작업이 필요한 경우에만 높입니다. - 에이전트가 탐색을 멈추도록 **명확한 완료 기준**을 지정합니다(예: "완료 = 테스트 통과, lint 오류 없음"). - 복잡한 작업은 에이전트가 먼저 **계획 파일**을 작성한 뒤 실행하게 합니다. - 사용할 도구를 알고 있다면 이름을 지정해("GitHub create-PR 도구만 사용") 도구 탐색을 줄입니다. - **구체적인 컨텍스트**(파일, 오류 메시지, 제약 조건)를 제공합니다([컨텍스트를 간결하게 유지하기](../03-context-hygiene/) 참조). Autopilot이나 백그라운드 에이전트에는 작업 프롬프트에 명시적인 루프 가드를 추가하세요. ```text 먼저 관련 범위의 테스트를 실행하세요. 같은 명령이나 테스트가 같은 오류로 두 번 실패하면 반복 재시도하지 말고 멈춰서 장애 원인을 보고하세요. ``` 이는 강제 실행 제한이 아닌 지시입니다. 로그를 확인하고 요청 또는 예산 한도도 추가 안전장치로 사용하세요. ### 모델과 추론 - 기본값으로 **자동 모델 선택**을 사용합니다. 계획 단계에는 더 강력한 모델을, 범위가 정해진 구현에는 더 저렴한 모델을 지정합니다([모델, 계획, 위임](../05-models-and-planning/) 참조). - 자동 선택은 편리하지만 **비용 최적화 도구는 아닙니다**. 지출을 제어하는 데 의존하기 전에 모델 선택 방식을 문서에서 확인합니다. - **추론 강도(thinking effort)**는 기본값으로 둡니다. 어려운 문제에서만 높입니다. 강도가 높을수록 추론 토큰이 늘어나 비용과 지연 시간이 커집니다. - 모델을 바꾸면 프롬프트 캐시가 새로 시작됩니다. 캐싱은 공급자, 모델, 배포마다 별도로 동작하므로, 세션 중간에 모델을 바꾸면 이전 캐시를 재사용하지 못합니다. ### Copilot 클라우드 에이전트(이슈 → PR) 클라우드 에이전트 작업 하나가 많은 토큰을 사용할 수 있습니다. 시작 비용을 줄이는 방법은 다음과 같습니다. - 이슈를 정확하게 작성합니다. "이거 고쳐줘"가 아니라 수락 기준(테스트 또는 동작), 재현 단계, 관련 파일 링크, 명확한 범위를 포함합니다. - 리포지토리의 **Copilot setup steps** 워크플로(`.github/workflows/copilot-setup-steps.yml`)에서 종속성을 미리 설치하고 빌드를 미리 실행합니다. 에이전트가 매번 환경을 새로 파악하지 않아도 됩니다. ### 한도가 적용되는 위치 사용량 기반 청구에서는 편집기 내 루프 제한 외에 GitHub의 계정 수준 예산 제어(예: 사용자별 또는 코스트 센터별 지출 한도)도 사용할 수 있습니다. 요금제에서 현재 지원하는 옵션은 [GitHub Docs](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals)에서 확인하세요. Copilot을 호출하는 자동화(CI 리뷰, 생성된 테스트, 검사)는 실행할 때마다 크레딧을 소비한다는 점에 유의합니다. ## 확인 방법 각 모드가 적합한 작업을 골라 여러 단계로 이루어진 작업을 Ask, Plan, Agent로 한 번씩 실행하고, 세션 크레딧과 **Agent Debug Logs**의 도구 호출 수를 비교합니다. 루프가 요청 한도에 걸려서가 아니라 사용자가 정한 완료 기준에서 끝나는지 확인합니다. ## 트레이드오프 `maxRequests`를 너무 낮게 설정하면 정당한 긴 작업이 중간에 끊겨, 이미 쓴 토큰이 낭비될 수 있습니다. 한도를 지나치게 낮추기보다 명확한 완료 기준과 계획 파일을 우선합니다. ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 각 연구 결과는 가설이므로 자신의 워크로드에서 검증해야 합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [Training Language Models to Reason Efficiently](https://arxiv.org/abs/2502.04463) — NeurIPS 2025, 인용 285회. 정확도와 추론 길이 사이의 균형을 조절하도록 추론 모델을 학습시킵니다. - [Token-Budget-Aware LLM Reasoning](https://arxiv.org/abs/2412.18547) — ACL 2024, 인용 259회. 문제마다 토큰 예산을 추정해 chain-of-thought 추론을 짧게 만듭니다. - [Do NOT Think That Much for 2+3=? On the Overthinking of o1-Like LLMs](https://arxiv.org/abs/2412.21187) — 프리프린트 2024, 인용 605회. o1 계열 모델이 단순한 질문에도 지나치게 많은 토큰을 쓴다는 점을 보이고, 이를 줄이는 방법을 제안합니다. - [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) — 프리프린트 2024, 인용 566회. 위치 파악, 수정, 검증으로 이루어진 고정 파이프라인이 낮은 비용으로 SWE-bench Lite에서 개방형 에이전트 루프와 경쟁할 수 있음을 보여 줍니다. - [L1: Controlling How Long A Reasoning Model Thinks With Reinforcement Learning](https://arxiv.org/abs/2503.04697) — 프리프린트 2025, 인용 416회. 사용자가 지정한 길이 예산을 따르도록 추론 모델을 학습시킵니다. - [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) — 프리프린트 2025, 인용 40회. 에이전트 시스템을 설계할 때 효율과 효과 사이의 트레이드오프를 체계적으로 연구합니다. ## 출처 - [VS Code Copilot settings reference](https://code.visualstudio.com/docs/copilot/reference/copilot-settings) (`chat.agent.maxRequests`) - [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Customize the cloud agent environment (copilot-setup-steps.yml)](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/customize-the-agent-environment) - Token Efficiency and Context Engineering — 개발자 발표 자료(2026년 6월). 모드 비교와 클라우드 에이전트 팁(정성적인 내용만 참고했으며, 발표 자료의 토큰 수치는 이 문서에 재현하지 않음) --- ## MCP 감사 (ko/copilot-tokenomics/09-mcp-audit.md) Canonical URL: > 사용량을 기준으로 MCP 서버를 점검하고 작업 영역별로 필요한 도구만 사용합니다. ## 문제 요청에 포함된 MCP **도구 정의(스키마)**는 사용하지 않아도 입력 비용을 발생시킵니다. 아래에서 설명하듯 일부 클라이언트는 가상 도구 그룹으로 스키마 로딩을 늦춥니다. 모든 스키마를 에이전트 루프의 매 단계에 전송하는 경우에는 비용이 단계 수만큼 곱해집니다. ```text tokens per task ≈ (tool schema tokens × steps) + accumulated conversation + tool responses ``` 사용하지 않는 서버라도 전체 스키마가 로드되어 있으면 단계마다 토큰을 소비합니다. 스키마 로딩이 지연되면 이 기준 비용은 달라질 수 있습니다.
MCP 서버 5개
도구 65%
기타 35%
100%
필요한 서버 1개
도구 15%
기타 35%
50%
측정 결과가 아닌 가상의 예시입니다. 변경 전 접두부를 기준으로 도구 정의는 65%에서 15%로 줄고 나머지는 35%로 유지되어, 변경 후 접두부는 기존의 50%가 됩니다. 필요한 서버 하나만 남기면 매 턴 전송하는 도구 정의가 줄어들지만, 실제 절감량은 다릅니다. 초록색은 도구를 줄인 구성일 뿐 캐시 적중을 뜻하지 않습니다.
## 조치 ### 매월 감사를 실행합니다 1. 모든 MCP 서버와 서버별 도구 수를 나열합니다(도구 선택기인 **Configure Tools**에서 확인할 수 있습니다). 2. 서버마다 지난달에 얼마나 자주 사용했는지 기록합니다(Agent Debug Logs에서 도구 호출을 볼 수 있습니다). 3. 서버별로 다음과 같이 결정합니다. | 사용량 | 결정 | |-------|----------| | 거의 매일 사용 | 유지 | | 가끔 사용 | 기본적으로 **비활성화**, 필요한 작업에서만 활성화 | | 거의 또는 전혀 사용하지 않음, 또는 다른 도구와 중복 | 제거 | | 필요한 도구는 두 개뿐인 대형 서버 | 더 작은 서버 또는 터미널에서 호출하는 CLI 사용 | 4. 첫 요청의 입력 크기와 기준선 작업을 다시 측정합니다([사용량 측정하기](../02-measure-usage/)). ### 필요 시 도구 로딩과 가상 도구 그룹 최근 VS Code Copilot 빌드는 도구 목록이 크면 가상 도구로 묶고 그룹이 활성화될 때까지 전체 스키마 로딩을 늦출 수 있습니다. 지원되는 환경에서는 `tool_search` 같은 도구 검색 단계를 거칩니다. 활성화된 그룹의 스키마는 이후 세션 요청에도 남을 수 있으며, 동작은 빌드와 모델에 따라 다릅니다. 그룹화가 비활성화되었거나 지원되지 않으면 처음부터 전체 스키마가 전송될 수 있습니다. 캐시 절감을 가정하지 말고 Agent Debug Logs와 Cache Explorer에서 확인하세요. 실험적 설정 `github.copilot.chat.virtualTools.threshold`는 그룹화가 시작되는 도구 수를 지정합니다([VS Code 설정 참조](https://code.visualstudio.com/docs/copilot/reference/copilot-settings)). 작업 영역별로 사용하지 않는 MCP 서버를 비활성화하는 것이 사용 가능한 목록을 줄이는 가장 확실한 기본 방법입니다. ### 전역이 아니라 작업 영역별로 범위를 정합니다 MCP 구성을 리포지토리(`.vscode/mcp.json`)에 두면 프로젝트마다 필요한 서버만 로드됩니다. 백엔드 리포지토리에는 디자인 도구 서버가, 프런트엔드 리포지토리에는 데이터베이스 스키마 도구가 필요하지 않습니다. 리포지토리별 파일은 전역 목록보다 검토하기도 쉽습니다. ### 긴 지식은 스킬로 대체합니다 반복되거나 분량이 큰 참고 자료(사내 스타일 가이드, 런북, API 메모)는 상시 로드되는 지침에 두는 대신 필요할 때 로드되는 **에이전트 스킬**로 패키징할 수 있습니다. 반복해서 전송하는 입력을 줄이고 한 곳에서 내용을 관리할 수 있습니다. ### 도구 출력을 작게 유지합니다 도구 결과(파일 읽기, grep, 셸 출력)는 컨텍스트에서 가장 큰 부분을 차지하는 경우가 많습니다. 파일 전체를 읽기보다 대상을 좁혀 검색하고, 노이즈가 많은 경로는 제외합니다([컨텍스트를 간결하게 유지하기](../03-context-hygiene/) 참조). ## 확인 방법 도구를 가지치기하기 전후로 Agent Debug Logs에서 첫 요청의 입력 토큰을 기록합니다. 그런 다음 같은 작업을 실행해 크레딧과 성공 여부를 비교합니다. 품질이 유지된 경우에만 변경을 유지합니다. ## 트레이드오프 작업에 필요한 도구를 가지치기하면 우회 방법을 찾느라 단계가 늘어납니다. 도구를 빠르게 다시 활성화할 방법을 마련해 두고, 추측이 아니라 실제 사용량을 확인한 뒤 도구를 가지치기합니다. ## 참고용 수치 이 문서의 바탕이 된 발표 자료에는 도구를 187개에서 52개로 줄인 팀이 나오며, 에이전트 작업의 토큰 사용량이 약 72% 감소했다고 보고합니다. 이 사례는 독립적으로 검증하지 못했습니다. *방법*의 예시로만 참고하고, 결과는 직접 측정하세요. TokenEconomizer는 여러 세션에 걸쳐 사용되지 않는 도구를 가지치기하는 방식으로 같은 아이디어를 자동화합니다([사례 연구](../../agent-tokenomics/case-tokeneconomizer/) 참조). ## 추가 자료(논문) 학회 등급, 인용 수 순으로 정렬했습니다. 각 연구 결과는 가설이므로 자신의 워크로드에서 검증해야 합니다. 전체 목록은 [논문](../../papers/)을 참고하세요. - [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) — 프리프린트 2025, 인용 55회. 모든 도구 스키마를 주입하지 않고, 에이전트가 필요한 도구를 직접 요청하게 합니다. - [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) — 프리프린트 2025, 인용 41회. 모든 도구를 로드하는 대신 관련 있는 MCP 도구 설명만 검색해 가져옵니다(프롬프트 비대화 완화). - [Less is More: Optimizing Function Calling for LLM Execution on Edge Devices](https://arxiv.org/abs/2411.15399) — 프리프린트 2024, 인용 33회. 함수 호출 시점에 선별한 소규모 도구 집합만 제시해 엣지 디바이스의 비용을 줄입니다. ## 출처 - [Optimize AI credit usage — Keep the tool catalog focused](https://code.visualstudio.com/docs/agents/guides/optimize-usage) - [Use tools with agents (VS Code)](https://code.visualstudio.com/docs/agents/run/tools) - Token Efficiency and Context Engineering — 개발자 발표 자료(2026년 6월), MCP 부분(수치는 보고된 그대로) --- ## 체크리스트 (ko/copilot-tokenomics/10-checklist.md) Canonical URL: > VS Code GitHub Copilot 토큰과 AI 크레딧 비용을 낮추기 위해 세션 시작 전·중·후에 점검하는 한 페이지 토큰 이코노믹스 루틴입니다. 효과 등급은 측정된 절감액이 아니라 우선순위를 정하기 위한 정성적 기준입니다. 플랜과 작업에 따라 달라지므로 기준선과 비교해 비용과 품질을 확인하세요. ## 세션을 시작하기 전에 - [ ] [효과: 상] 새 작업이면 새 채팅을 시작합니다. 별도 질문에는 `/fork`를 사용합니다. - [ ] [효과: 상] 이 작업에 필요한 도구와 MCP 서버만 활성화했습니다. - [ ] [효과: 상] 모델을 의도적으로 선택했습니다(기본은 자동). 추론 강도는 기본값으로 두었습니다. - [ ] [효과: 중] 노이즈가 많은 경로를 제외했습니다(`.gitignore`, `files.exclude`, `search.exclude`). - [ ] [효과: 상] 프롬프트에 파일, 오류, 제약 조건, 성공 기준을 명시했습니다. - [ ] [효과: 중] 프롬프트 끝에 출력 제한(`Code only.` / `3 bullets max.`)을 붙였고, 프롬프트 하나에는 작업 하나만 담았습니다. - [ ] [효과: 중] 상시 지침과 규칙은 영어로, 간결하게, 중복 없이 작성했습니다. ## 작업 중 - [ ] [효과: 중] 알고 있는 파일에는 #-멘션을 사용합니다. `#codebase`는 검색이 필요할 때만 사용합니다. - [ ] [효과: 상] 복잡한 변경은 먼저 계획하고 구현합니다. 범위가 정해진 작업은 더 저렴한 서브에이전트에 위임합니다. - [ ] [효과: 상] 모호한 작업은 Agent를 실행하기 전에 Ask 또는 Plan으로 범위를 정하고, 명확한 완료 기준을 제시합니다. - [ ] [효과: 상] 세션이 길어졌지만 계속 필요하면 `/compact`를 실행할 때 요약의 초점을 지정합니다. - [ ] [효과: 중] 대량 작업이나 폴링 작업은 스크립트로 실행하고, 모델에는 요약만 전달합니다. ## 주간 검토 - [ ] [효과: 하] Copilot 상태 대시보드를 엽니다. 월간 허용량을 얼마나 사용했나요? - [ ] [효과: 중] 비용이 가장 컸던 세션 세 개를 찾아 원인을 확인합니다(컨텍스트 윈도우 팝오버). - [ ] [효과: 하] 사용할 수 있으면 `/chronicle:cost-tips`를 실행하고, 없으면 Agent Debug Logs의 Summary와 Cache Explorer를 확인합니다. - [ ] [효과: 상] 필요하지 않았던 지침과 도구를 가지치기합니다([MCP 감사](../09-mcp-audit/)). ## 판단이 서지 않을 때 [2페이지에서 사용량을 측정](../02-measure-usage/)하고 한 가지만 바꾼 뒤 다시 측정합니다. 품질이 유지된 경우에만 변경을 유지합니다. --- ## cctx: VS Code Copilot 토큰 절감 및 개발 가속 (ko/copilot-tokenomics/cctx.md) Canonical URL: > VS Code Marketplace에서 Code Context(cctx)를 설치해 코드 탐색 토큰을 줄이고, 에이전트 개발 속도를 가속하며, 실시간 AIC/USD 절감량을 확인합니다. [Code Context (`cctx`)](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native)는 공유 로컬 Rust 트라이그램 인덱스를 기반으로 동작하는 **VS Code 전용 네이티브 Language Model Tools 확장**(`dotnetpower.code-context-native`)입니다. VS Code Marketplace에서 바로 설치할 수 있으며, 여러 번 반복되던 `grep` + 전체 파일 `view` 루프를 **단일 블록 클램핑 조회 1회**로 대체해 **Copilot 토큰·AI 크레딧 비용을 아끼는 동시에 에이전트 개발 속도를 크게 가속**합니다. 또한 절감된 토큰과 비용(AIC/USD)을 VS Code 상태 표시줄과 터미널 대시보드에서 실시간으로 보여 줍니다. ## 문제 GitHub Copilot 에이전트 모드가 기본 검색·파일 읽기 도구만으로 저장소를 탐색할 때는 **개발 속도를 늦추고 AI 크레딧을 소모하는 두 가지 비용**이 함께 발생합니다. 1. **다단계 탐색으로 인한 지연(개발 속도 저하):** 심볼 하나를 찾고 정의와 호출부를 확인하기 위해 `grep` → `view` → 다시 `grep`을 여러 턴 왕복하면, 추가되는 매 LLM 턴마다 네트워크 왕복과 프리필(Prefill) 대기 시간이 누적됩니다. 2. **대화 이력 비대화(토큰 비용 증가):** 함수 경계 없이 읽어 들인 넓은 범위의 코드(`100~200줄` 이상 또는 문서 전체)는 대화 이력(History)에 남아 **세션이 끝날 때까지 매 턴 다시 전송**됩니다. 여기에 서술형(Prose) 지침 파일까지 길면 매 턴 고정 입력 비용이 반복 청구됩니다. --- ## 조치: VS Code에서 설치 및 사용하기 (Marketplace) `cctx`는 **Linux, 네이티브 Windows(`cctx.exe`), WSL, SSH** 환경의 VS Code(`1.140+`)에서 별도의 MCP JSON 설정이나 실험적(proposed) API 플래그 없이 네이티브 확장으로 동작합니다. ### 1. VS Code Marketplace에서 확장 설치 VS Code 확장(Extensions) 탭에서 **[Code Context by dotnetpower](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native)**를 검색해 설치하거나 다음 명령을 실행합니다. ```bash code --install-extension dotnetpower.code-context-native ``` ### 2. 로컬 Rust 백엔드(`cctx`) 설치 VS Code 확장은 로컬에서 동작하는 초고속 Rust 데몬(`cctx`)과 통신합니다. ```bash # Linux / WSL / macOS / SSH: git clone https://github.com/dotnetpower/code-context.git cd code-context && bash scripts/install.sh && ~/.local/bin/cctx ping # 네이티브 Windows (PowerShell, WSL 불필요): cargo build --locked --release copy target\release\cctx.exe $HOME\.local\bin\cctx.exe ``` ### 3. 프로젝트 열기 및 Getting Started 실행 VS Code 명령 팔레트(`Ctrl+Shift+P` / `⌘Shift+P`)에서 **Code Context: Getting Started**를 실행합니다. 네이티브 Windows에서는 첫 사용 시 `cctx.exe daemon`이 백그라운드에서 자동으로 시작됩니다. 확장이 설치되면 BPE 토큰 경계에 맞춰 압축된 수식형 에이전트 지침(`applyTo: "**"`)이 자동으로 연결되어, 사용자가 매번 지시하지 않아도 Copilot이 아래 네이티브 도구를 우선 사용합니다. | VS Code 네이티브 도구 | Copilot 활용 목적 | 더 빠르고 저렴한 이유 | |---|---|---| | `#cctxNativeContext` | **심볼/패턴 검색 + 주변 코드 1회 조회** | 별도의 `grep` + `view` 왕복을 1회 호출로 통합하고, `<8 KiB` 인라인 예산 안에서 함수·블록 경계에 맞춰 필요한 코드만 반환합니다. | | `#cctxNativeGrep` | **트라이그램 인덱스 기반 문자열/정규식 검색** | 노이즈가 많은 단순 일치 목록 대신 심볼 정의부(`max_matches_per_file`)를 우선 반환합니다. | | `#cctxNativeFiles` | **초고속 파일명·경로 글롭 탐색** | 인메모리 인덱스에서 평균 `0.307 ms`(웜 캐시 중앙값) 만에 경로를 찾습니다. | | `#cctxNativeRead` | **해시 검증 라인 범위 및 문서 앵커 읽기** | 필요한 줄 범위만 정확히 읽거나 `.md`, `.docx`, `.pptx`, `.pdf`의 `#toc` / `#slide-N-M` / `#heading` 앵커만 선택 조회합니다. | --- ## 비용 절감과 개발 속도 가속이 동시에 일어나는 이유 `aks-store-demo`와 Copilot A/B 코딩 실험을 대상으로 수행된 [8세션·40라운드·8,960쌍 벤치마크 리포트](https://github.com/dotnetpower/code-context/blob/main/docs/BENCHMARKS.md)(`dotnetpower/code-context` 보고 수치)에 따르면, `cctx`는 답변 정확도(100%)를 그대로 유지하면서 **개발 완료 속도**와 **토큰 효율**을 동시에 끌어올립니다. ### 1. 개발 속도 가속 (Developer Velocity) - **웜 캐시 기준 코드 탐색 속도 15.20배 가속** (혼합 탐색 스위트 평균 `4.450 ms → 0.293 ms`, 95% 신뢰구간 `14.53–15.84×`, 콜드 싱크 중앙값 `29.115 ms`): - 문자열 검색(Literal search): **20.35배 빠름** (`5.885 ms → 0.289 ms`) - 검색 + 주변 컨텍스트(Search + context): **18.70배 빠름** (`5.935 ms → 0.317 ms`) - 파일명 탐색(Filename discovery): **16.03배 빠름** (`4.923 ms → 0.307 ms`) - **도구 호출 횟수 61.9% 감소** (`7.00회 → 2.67회`) 및 **LLM 왕복 턴 수 26.7% 감소** (`5.00턴 → 3.67턴`): 불필요한 탐색 왕복이 줄어들어 에이전트가 코드 수정과 검증 단계에 훨씬 빨리 도달합니다. - **전체 코딩 작업 완료 시간(Wall time) 24.7% 단축** (`20.31초 → 15.30초`, 정답률 100% 동일 유지). - **논블로킹 콜드 캐시(Nonblocking Root Cache):** 인덱스가 아직 준비되지 않은 저장소에서도 에이전트가 멈춰 기다리지 않도록 즉시 `CACHE_MISS`를 반환해 기본 도구로 작업을 이어가며 백그라운드에서 인덱싱을 완료합니다. ### 2. 토큰 및 AI 크레딧 비용 절감 | 벤치마크 항목 | 기본 도구 (`rg` + `view`) | VS Code `cctx` 적용 시 | 보고된 절감 및 가속 효과 | |---|---:|---:|---| | **Rust 6개 심볼 연속 조회 토큰** | 15,028 tok (100줄) / 25,133 tok (200줄) | **4,031 tok** (20회 → 6회 호출) | **토큰 -73.2% ~ -84.0%** (**10.3배** 빠름) | | **Python 6개 심볼 연속 조회 토큰** | 13,997 tok (100줄) / 24,609 tok (200줄) | **2,141 tok** (15회 → 6회 호출) | **토큰 -84.7% ~ -91.3%** (**13.16배** 빠름) | | **문서 파일 (`.pptx` / `.docx` / `.md`)** | 문서 전체 읽기 | 가상 `#toc` + `#slide-N-M` 앵커 조회 | **토큰 -86.3% ~ -98.9%** | | **자동 로드 에이전트 지침** | 서술형 2,048 tok | **BPE 정렬 수식 지침 756 tok** | **지침 고정 토큰 -63.1%** | | **Copilot A/B 세션 과금 비용** | 페이로드 6,360 tok / 4.76B nanoAIU | **페이로드 3,177 tok / 3.55B nanoAIU** | **페이로드 -50.0% · AIU 과금 -25.4%** | --- ## 확인 방법: VS Code에서 실시간 Usage 및 절감 비용 보기 `cctx`가 실제로 얼마나 호출되었고 내 Copilot 비용을 얼마나 아껴 주었는지 VS Code 안에서 두 가지 화면으로 즉시 확인할 수 있습니다. ### 1. VS Code 하단 상태 표시줄(Status Bar) 배지 및 마크다운 팝오버 VS Code 하단 상태 표시줄에 네이티브 도구 성공 횟수(`S`), 활성 모델, 추정 절감 토큰 및 절감 금액(`+$USD`)이 실시간으로 표시됩니다. ```text $(database) CCTX N S:382 C:4 P:0 E:0 · Claude Sonnet 4.6 · ~142.8K tok (+$0.48) ``` 상태 표시줄 항목 위에 마우스를 올리면 모델별 토큰 소비량, 캐시 적중률, 네이티브 도구별 절감 내역을 정리한 마크다운 툴팁이 열립니다(합성 예시): | 💰 Cost Saved (@$0.001) | 💎 API Value (@$0.01) | 🔥 Tokens Saved | 🎯 Warm Hit Rate | ⚡ Avg Latency | | :---: | :---: | :---: | :---: | :---: | | **+$0.48** (`~480.0 AIC`) | **+$4.80** | **~142.8K tok** | **99.0%** (`382/386`) | **0.31 ms** | | Operation | Calls (OK/Miss) | Delivered | Saved Tok | Avg ms | | :--- | ---: | ---: | ---: | ---: | | `cctxNativeContext` | 142 (140/2) | ~68.4K | ~94.2K | 0.32 ms | | `cctxNativeRead` | 128 (127/1) | ~52.1K | ~31.5K | 0.26 ms | | `cctxNativeGrep` | 74 (73/1) | ~16.8K | ~12.4K | 0.29 ms | | `cctxNativeFiles` | 42 (42/0) | ~5.5K | ~4.7K | 0.30 ms | ### 2. 멀티 세션 통합 대시보드 (`cctx usage --hours 24`) VS Code 통합 터미널에서 `cctx usage --hours 24`(또는 최근 7일은 `--hours 168`)를 실행하면, 최근 Copilot 세션 전체의 모델별 지출, 프롬프트 캐시 적중률, 소스 탐색 채택률, 그리고 누적 절감 금액(AIC 및 API 정가 환산)을 한눈에 볼 수 있습니다(합성 예시): ```text $ cctx usage --hours 24 ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗ ║ ⚡ CODE CONTEXT (cctx) — MODEL, TOKEN & COST SAVINGS DASHBOARD (Window: 24.0h) ║ ╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣ ║ 💰 COST SAVED (@$0.001/AIC) : +$24.80 USD (-23.5% of baseline bill · ~24800.0 AIC saved) ║ ║ 💎 API LIST VALUE (@$0.01) : +$248.00 USD (Frontier API list price: $2/$0.10/$10 per 1M) ║ ║ 🔥 TOKENS SAVED : ~740.20M tok (Payload ~7.42M + 35x Cache ~259.7M + ~2040 Turns ~450.1M + BPE ~22.98M) ║ ║ 🧬 BPE FORMULA COMPRESSION : ██████████ 100.0% (4/4 surfaces: ext·mcp·subagent·global · ~2100 tok/turn · +$12.30) ║ ║ 🎯 WARM CACHE HIT RATE : ██████████ 97.2% (4680 warm hits / 4815 CCTX lookups) ║ ║ 🚀 ELIGIBLE SOURCE ADOPTION : ███████░░░ 74.8% (4815/6437 · excl. 920 /tmp & 680 pre-edit) ║ ╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝ 1. LLM MODEL USAGE, CACHE HIT & COST SAVINGS ┌──────────────────────────┬────────────┬─────────────────┬───────────────┬───────────────┬───────────┬────────────────────────┬──────────────────────────────────────────┐ │ Model (Effort) │ Sess/Turns │ Input (Cache%) │ Out+Rsn Tok │ CCTX (Warm%) │ Src Adopt │ LLM Spend (@$0.001) │ COST SAVED (@$0.001 / API @$0.01) │ ├──────────────────────────┼────────────┼─────────────────┼───────────────┼───────────────┼───────────┼────────────────────────┼──────────────────────────────────────────┤ │ Claude Sonnet 4.6 (high) │ 18/4120 │ 1.84B (96.2%) │ 4.12M+1.90M │ 3410 (97.5%) │ 76.4% │ $58.40 (58400.0 AIC) │ +$18.20 / API +$182.00 (~18200.0 AIC) │ │ GPT-5.4 (medium) │ 24/1980 │ 640.00M (97.4%) │ 2.10M+1.15M │ 1405 (96.5%) │ 71.2% │ $22.10 (22100.0 AIC) │ +$6.60 / API +$66.00 (~6600.0 AIC) │ │ TOTAL (All Models) │ 42/6100 │ 2.48B (96.5%) │ 6.22M+3.05M │ 4815 (97.2%) │ 74.8% │ $80.50 (80500.0 AIC) │ +$24.80 / API +$248.00 (~24800.0 AIC) │ └──────────────────────────┴────────────┴─────────────────┴───────────────┴───────────────┴───────────┴────────────────────────┴──────────────────────────────────────────┘ ``` VS Code 기본 제공 [Agent Debug Logs](../02-measure-usage/)와 함께 사용하면 동일한 작업의 `cctx` 적용 전후 턴 수, 소요 시간, 소비 크레딧을 직접 비교할 수 있습니다. --- ## 트레이드오프와 주의 사항 - **아주 작은 단일 파일 구간 읽기:** `cctx`는 로컬 데몬과 IPC로 통신하므로, 이미 파일과 줄 번호를 알고 있는 아주 짧은 단일 구간 읽기는 직접 파일 시스템을 읽는 것보다 미세 지연 시간 자체는 조금 더 걸릴 수 있습니다(`0.251 ms` vs `0.083 ms`). 다만 `#cctxNativeRead`는 SHA-256 해시 검증과 `<8 KiB` 인라인 예산 보호를 함께 제공합니다. - **첫 조회 시 콜드 스타트 폴백:** 새 워크스페이스에서 처음 조회할 때 나오는 `CACHE_MISS`는 검색 결과가 0건이라는 뜻이 **아닙니다**. 에이전트가 기다리지 않도록 해당 턴에만 기본 호스트 도구로 즉시 폴백하고, 백그라운드에서 인덱싱(중형 저장소 중앙값 `~29 ms`)을 마친 뒤 다음 턴부터 캐시를 사용합니다. - **보안 및 제외 경로 경계:** `.github`, `.vscode` 같은 숨김 설정 폴더, `.gitignore` 대상 경로, `/tmp`, 시크릿 파일은 보안 정책에 따라 트라이그램 인덱스에서 제외되며 VS Code의 호스트 정책 도구를 통해 처리됩니다. ## 출처 - [Code Context by dotnetpower — VS Code Marketplace (`dotnetpower.code-context-native`)](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) - [dotnetpower/code-context GitHub 저장소](https://github.com/dotnetpower/code-context) - [Code Context 벤치마크 및 토큰 효율 리포트](https://github.com/dotnetpower/code-context/blob/main/docs/BENCHMARKS.md) - [VS Code 설치 및 문제 해결 가이드](https://github.com/dotnetpower/code-context/blob/main/vscode-extension/docs/SETUP.md) --- ## Copilot 토큰 이코노믹스 (Tokenomics · Token Economics) (ko/copilot-tokenomics/index.md) Canonical URL: > VS Code GitHub Copilot을 위한 실전 토큰 이코노믹스(Token Economics, 토큰 경제학): 토큰과 AI 크레딧 절약, 컨텍스트·MCP 최적화, cctx 개발 가속. Track A는 VS Code에서 GitHub Copilot을 **사용하는** 개발자를 위한 **Copilot 토큰 이코노믹스(Tokenomics · Token Economics)** 가이드입니다. 각 페이지는 *문제 → 조치 → 확인 방법 → 트레이드오프* 순서로 설명합니다. 먼저 Copilot 청구 설정에서 사용 중인 플랜을 확인하세요. 과금 방식에 따라 우선할 절약 방법이 다릅니다. | 과금 방식 | 과금 단위 | 먼저 볼 페이지 | |---|---|---| | AI 크레딧(사용량 기반) | 입력, 캐시된 입력, 출력 토큰 각각에 모델 요율 적용 | [사용량 측정](02-measure-usage/), [컨텍스트](03-context-hygiene/), [도구](04-instructions-and-tools/) | | 기존 프리미엄 요청 | 프롬프트/턴당 모델 배수 적용 | [과금](01-how-usage-is-charged/), [모델](05-models-and-planning/), [예산 가드](08-agent-modes-and-budget/) |
여러 소스에서 에이전트 컨텍스트를 구성하는 과정을 보여 주는 VS Code 다이어그램
에이전트 컨텍스트는 여러 소스에서 구성됩니다. 출처: VS Code Docs — Context in Agents.
| 페이지 | 살펴볼 질문 | |------|---------------------| | [Copilot 사용량은 어떻게 과금되는가](01-how-usage-is-charged/) | 무엇에 비용이 드는가? | | [사용량 측정](02-measure-usage/) | 어떤 채팅과 요청의 비용이 큰가? | | [컨텍스트를 가볍게 유지하기](03-context-hygiene/) | 불필요한 대화 기록에 드는 비용을 어떻게 막을 수 있는가? | | [지침과 도구](04-instructions-and-tools/) | 요청마다 전송되는 내용을 어떻게 줄일 수 있는가? | | [모델, 계획, 위임](05-models-and-planning/) | 저렴한 모델이나 계획 우선 방식은 언제 효과가 있는가? | | [프롬프트와 출력 스타일](06-prompt-and-output-style/) | 프롬프트를 어떻게 줄이고 답변 길이를 제한하는가? | | [언어와 토큰화](07-language-and-tokenization/) | 한국어 등 다른 언어로 작성하면 비용이 더 드는가? | | [에이전트 모드와 예산 가드](08-agent-modes-and-budget/) | Ask, Plan, Agent는 어떻게 다르며 반복 실행을 어떻게 제한하는가? | | [MCP 점검](09-mcp-audit/) | 어떤 도구 서버를 계속 사용 설정해 둘 것인가? | | [체크리스트](10-checklist/) | 한 페이지로 정리한 점검 루틴입니다. | | [cctx: VS Code 토큰 절감 및 개발 가속](cctx/) | VS Code Marketplace 확장으로 탐색 토큰을 줄이고 개발 속도와 실시간 절감액을 확인하려면? | | [리소스](../resources/) | 알아 두면 좋은 도구와 리포지토리입니다. | | [논문](../papers/) | 이 전략의 바탕이 되는 연구를 신뢰도 순으로 정리했습니다. | :::note Copilot의 과금 방식, UI, 설정은 빠르게 바뀝니다. 각 페이지에는 확인한 날짜와 공식 출처 링크를 함께 적었습니다. 사용 중인 VS Code와 내용이 다르면 공식 문서를 기준으로 확인하세요. ::: --- ## 토큰 이코노믹스(Tokenomics) 용어집 (ko/glossary.md) Canonical URL: > 토큰 이코노믹스(Token Economics, 토큰 경제학), 프롬프트 캐싱, 컨텍스트 윈도우, 도구 가지치기 등 LLM 에이전트 비용 용어 사전입니다(영어 ↔ 한국어). | English | 한국어 | 설명 | |---------|--------|------| | tokenomics / token economics | 토큰 이코노믹스 / 토큰 경제학 | 응답 품질을 유지하면서 LLM 요청과 AI 에이전트 루프 전반의 토큰 과금, 예산, 캐싱, 컨텍스트 효율을 측정하고 최적화하는 엔지니어링 분야입니다. | | token | 토큰 | 모델이 읽거나 쓰는 텍스트 단위이며, 사용량 기반 과금의 기준입니다. | | input / output tokens | 입력 / 출력 토큰 | 모델에 보내는 토큰 / 모델이 생성하는 토큰입니다. | | context window | 컨텍스트 윈도우 | 모델이 한 번의 요청에서 처리할 수 있는 최대 토큰 수입니다. | | prefix | 접두부 | 요청의 앞부분입니다. 변하지 않은 접두부는 공급자의 캐시에서 재사용할 수 있습니다. | | prompt caching | 프롬프트 캐싱 | 공급자가 변하지 않은 요청 앞부분을 재사용해 비용과 지연 시간을 줄이는 기능입니다. | | cache hit rate | 캐시 적중률 | 캐시에서 처리된 입력 토큰의 비율입니다. | | AI credits | AI 크레딧 | GitHub Copilot의 사용량 기반 과금 단위입니다. | | premium request | 프리미엄 요청 | 이전 방식의 Copilot 과금 단위로, 프롬프트 수 × 모델 배수로 계산합니다. | | compaction | 컨텍스트 압축 | 이전 대화를 요약해 컨텍스트 공간을 확보하는 작업입니다. | | observation masking | 관찰 마스킹 | 최근 관찰은 유지하면서 오래된 도구 결과를 간결한 자리 표시자로 바꾸는 방법입니다. | | tokenizer encoding (`o200k_base` / `cl100k_base`) | 토크나이저 인코딩 | 텍스트를 토큰으로 나누는 데 쓰는 어휘와 규칙입니다. 토큰 수는 인코딩에 따라 달라집니다. | | tool definition | 도구 정의 | 요청에 포함되어 모델에 전달되는 도구의 스키마입니다. | | tool pruning | 도구 가지치기 | 사용하지 않는 도구 정의를 요청에서 제외하는 방법입니다. | | micro-skill | 마이크로 스킬 | 세션을 시작할 때 알려 주는, 검증된 짧은 리포지토리 사실입니다. | | failure loop | 실패 루프 | 한 턴에서 같은 실패가 반복되는 상태입니다. | | loop guard | 루프 가드 | 실패 루프를 감지해 에이전트의 방향을 한 번 바로잡는 장치입니다. | | turn | 턴 | 사용자 프롬프트 하나에 대해 에이전트가 수행하는 작업 단위입니다. | | baseline | 기준선 | 비교의 출발점이 되는 측정값입니다. | | subagent | 서브에이전트 | 탐색 과정을 메인 대화와 분리하는 별도의 에이전트 실행입니다. | | context rot | 컨텍스트 열화 | 컨텍스트 윈도우가 가득 차기 전에도 긴 컨텍스트에서 품질이 떨어지는 현상입니다(예: 중간에 있는 내용을 덜 안정적으로 활용함). | | landmine (instruction) | 지뢰 규칙 | 코드만으로는 알기 어려워 놓치기 쉬운 규칙으로, 지침에 명시할 만한 정보입니다. | | tool schema tax | 도구 스키마 세금 | 모든 요청에서 도구 정의를 다시 보내느라 쓰는 토큰입니다. | | agent skill | 에이전트 스킬 | 항상 적용되는 지침 대신 필요할 때 불러오는, 묶어서 제공하는 지식이나 도구입니다. | | reasoning effort | 추론 강도 | 요청마다 모델이 사용하는 사고 토큰의 양을 조절하는 설정입니다. | | fan-out (LLM calls per request) | 팬아웃 (요청당 LLM 호출 수) | 파이프라인이나 에이전트에서 사용자 요청 하나가 일으키는 모델 호출 수입니다. | | token map | 토큰 지도 | 단계별 고정 토큰과 동적 토큰, 호출 수, 전체 대비 비중을 정리한 표입니다. | | cacheable prefix | 캐시 가능 접두부 | 공급자의 최소 길이 조건을 충족해 프롬프트 캐시에서 처리될 수 있는, 요청의 변하지 않는 앞부분입니다. | | provisioned throughput | 프로비저닝 처리량 | 토큰 단위가 아니라 용량 기준으로 청구되는 예약 모델 용량입니다. 이를 최적화할 때는 비용뿐 아니라 용량과 지연 시간도 고려해야 합니다. | --- ## 토큰 이코노믹스(Tokenomics · Token Economics) — LLM 및 AI 에이전트 토큰 절약 가이드 (ko/index.mdx) Canonical URL: > LLM과 AI 에이전트를 위한 토큰 이코노믹스(Tokenomics · Token Economics, 토큰 경제학) 실전 가이드: VS Code Copilot 토큰 절약, cctx 개발 가속, tokprof 프로파일링. (Interactive landing page — see structured index in llms.txt and Track A / Track B sections below.) --- ## 논문 (ko/papers.md) Canonical URL: > 토큰 절약과 관련된 논문 75편을 학회 등급과 인용 수 순으로 정리했습니다. 토큰 절약과 관련된 논문 75편을 **2026-11-03** 기준으로 모아 학회 등급과 인용 수 순으로 정리했습니다. 각 항목은 arXiv 페이지로 연결되며, 핵심 내용은 직접 작성한 한 줄 요약입니다. ## 순위 기준 1. **1등급**: 주요 ML/NLP/시스템 학회(ICLR, NeurIPS, ICML, ACL, EMNLP, NAACL, TACL, TMLR, SOSP, MLSys)에서 심사를 통과한 논문입니다. 2. **2등급**: 그 외 학회·저널에서 심사를 통과한 논문입니다. 3. **3등급**: 프리프린트(게재 학회 정보 없음)입니다. 4. 같은 등급 안에서는 **인용 수가 많은 순**입니다. :::caution[순위는 읽는 순서일 뿐 평가가 아닙니다] - 학회와 인용 수는 2026-11-03에 [Semantic Scholar](https://www.semanticscholar.org/) Graph API에서 가져온 값입니다. 연도는 Semantic Scholar가 표시하는 연도이며 첫 프리프린트 연도일 수 있습니다. 학회 정보는 최종 게재보다 늦게 반영될 수 있고 인용 수는 계속 변합니다. 갱신하려면 `examples/fetch_paper_meta.py`와 `examples/build_papers.py`를 다시 실행합니다. - 인용 수는 오래된 기초 논문에 유리합니다. 최근 프리프린트는 새로운 논문이라는 이유만으로 순위가 낮습니다. - 심사 통과나 인용 수가 사용 중인 에이전트나 모델에서 결과가 재현된다는 뜻은 아닙니다. 모든 결과를 가설로 취급하고 [문제 해결 절차](../agent-tokenomics/)로 직접 검증하세요. - 수치는 옮기지 않고 주장만 요약했습니다. 수치를 인용하기 전에 실험 설정을 논문에서 확인하세요. ::: ## 주제별 적용 위치 | 주제 | 논문 수 | 적용 문서 | |------|-------:|-----------| | 기초 | 3 | [개념](../agent-tokenomics/00-concepts/) | | 토큰화와 언어 | 3 | [언어와 토큰화](../copilot-tokenomics/07-language-and-tokenization/) | | 긴 컨텍스트와 컨텍스트 열화 | 9 | [개념](../agent-tokenomics/00-concepts/), [컨텍스트를 가볍게 유지하기](../copilot-tokenomics/03-context-hygiene/), [개선](../agent-tokenomics/04-improve/) | | 프롬프트/KV 캐싱 | 10 | [개념](../agent-tokenomics/00-concepts/), [사용량 측정](../copilot-tokenomics/02-measure-usage/), [개선](../agent-tokenomics/04-improve/) | | 프롬프트 압축 | 10 | [프롬프트와 출력 스타일](../copilot-tokenomics/06-prompt-and-output-style/), [개선](../agent-tokenomics/04-improve/) | | 출력 형식 | 1 | [프롬프트와 출력 스타일](../copilot-tokenomics/06-prompt-and-output-style/) | | 배치 처리 | 1 | [지침과 도구](../copilot-tokenomics/04-instructions-and-tools/), [개선](../agent-tokenomics/04-improve/) | | 모델 라우팅과 캐스케이드 | 5 | [모델, 계획, 위임](../copilot-tokenomics/05-models-and-planning/), [개선](../agent-tokenomics/04-improve/) | | 효율적인 추론/출력 길이 | 6 | [에이전트 모드와 예산 가드](../copilot-tokenomics/08-agent-modes-and-budget/), [개선](../agent-tokenomics/04-improve/) | | 에이전트 비용과 컨텍스트 관리 | 9 | [원인 분리](../agent-tokenomics/02-isolate/), [개선](../agent-tokenomics/04-improve/), [TokenEconomizer 사례 연구](../agent-tokenomics/case-tokeneconomizer/) | | 도구 선택과 스키마 크기 | 3 | [MCP 감사](../copilot-tokenomics/09-mcp-audit/), [개선](../agent-tokenomics/04-improve/) | | 지침/컨텍스트 파일 | 1 | [지침과 도구](../copilot-tokenomics/04-instructions-and-tools/) | | 메모리와 요약 | 4 | [원인 입증](../agent-tokenomics/03-prove/), [개선: 컨텍스트 압축](../agent-tokenomics/04-improve/#compaction-without-losing-the-cache) | | 평가와 통계 | 5 | [원인 입증](../agent-tokenomics/03-prove/), [결과](../agent-tokenomics/05-result/) | | 서베이 | 5 | [참고 자료](../resources/) | ## 순위표 | # | 논문 | 학회 · 연도 | 인용 | 주제 | 핵심 내용 | |--:|------|-------------|-----:|------|-----------| | 1 | [Chain of Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/abs/2201.11903) | NeurIPS · 2022 | 23,523 | 기초 | 단계별 프롬프트는 추론 성능을 높이지만 출력 토큰도 늘립니다. | | 2 | [ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629) | ICLR · 2022 | 13,383 | 기초 | 추론과 도구 동작을 번갈아 수행하는 방식으로, 이 가이드가 비용을 분석하는 에이전트 루프에 해당합니다. | | 3 | [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) | SOSP · 2023 | 9,724 | 프롬프트/KV 캐싱 | PagedAttention으로 KV cache 메모리를 관리해 서빙 처리량을 높이며, vLLM의 기반이 되는 기술입니다. | | 4 | [Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909) | ACL · 2015 | 9,243 | 토큰화와 언어 | 대부분의 LLM 토크나이저의 기반이 되는 서브워드(BPE) 단위를 처음 제안했습니다. | | 5 | [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) | TACL · 2023 | 5,818 | 긴 컨텍스트와 컨텍스트 열화 | 관련 정보가 긴 입력의 중간에 있을 때 정확도가 떨어짐을 보여 줍니다. | | 6 | [SWE-bench: Can Language Models Resolve Real-World GitHub Issues?](https://arxiv.org/abs/2310.06770) | ICLR · 2023 | 4,683 | 기초 | TokenEconomizer를 비롯해 코딩 에이전트를 평가하는 데 쓰는, 실제 GitHub 이슈 기반 벤치마크입니다. | | 7 | [Efficient Streaming Language Models with Attention Sinks](https://arxiv.org/abs/2309.17453) | ICLR · 2023 | 2,768 | 긴 컨텍스트와 컨텍스트 열화 | 어텐션 싱크 토큰과 최근 윈도우만 유지하여, 전체 기록 없이도 스트리밍 추론을 수행합니다. | | 8 | [SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering](https://arxiv.org/abs/2405.15793) | NeurIPS · 2024 | 2,357 | 에이전트 비용과 컨텍스트 관리 | 간결하고 제한된 관찰 결과를 포함한 인터페이스 설계가 에이전트 성공률을 좌우함을 보여 줍니다. | | 9 | [LongBench: A Bilingual, Multitask Benchmark for Long Context Understanding](https://arxiv.org/abs/2308.14508) | ACL · 2023 | 1,888 | 긴 컨텍스트와 컨텍스트 열화 | 장문 컨텍스트 이해를 평가하는 이중 언어, 다중 작업 벤치마크입니다. | | 10 | [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104) | NeurIPS · 2023 | 1,783 | 프롬프트/KV 캐싱 | RadixAttention으로 접두부를 공유하는 호출 간에 KV cache를 재사용하며, 접두부 캐싱의 기반이 되는 기술입니다. | | 11 | [Large Language Models Can Be Easily Distracted by Irrelevant Context](https://arxiv.org/abs/2302.00093) | ICML · 2023 | 1,358 | 긴 컨텍스트와 컨텍스트 열화 | 프롬프트에 관련 없는 컨텍스트가 있으면 모델 정확도가 크게 떨어질 수 있습니다. | | 12 | [FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance](https://arxiv.org/abs/2305.05176) | TMLR · 2023 | 1,247 | 모델 라우팅과 캐스케이드 | LLM을 선택하고 연쇄 호출하여 더 낮은 비용으로 강력한 모델에 근접한 품질을 얻습니다. | | 13 | [SnapKV: LLM Knows What You are Looking for Before Generation](https://arxiv.org/abs/2404.14469) | NeurIPS · 2024 | 1,132 | 프롬프트/KV 캐싱 | 어텐션 헤드별로 중요한 KV 위치를 선택해 캐시 크기를 줄입니다. | | 14 | [H2O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models](https://arxiv.org/abs/2306.14048) | NeurIPS · 2023 | 1,091 | 프롬프트/KV 캐싱 | KV cache 항목을 제거하되 'heavy hitter' 토큰은 유지해 메모리를 줄입니다. | | 15 | [Evaluating Very Long-Term Conversational Memory of LLM Agents](https://arxiv.org/abs/2402.17753) | ACL · 2024 | 1,082 | 메모리와 요약 | 매우 긴 기간에 걸친 대화 메모리를 평가하는 벤치마크입니다. | | 16 | [LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory](https://arxiv.org/abs/2410.10813) | ICLR · 2024 | 869 | 메모리와 요약 | 채팅 어시스턴트의 장기 메모리를 평가하는 벤치마크로, 회상 검사를 설계할 때 유용합니다. | | 17 | [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache](https://arxiv.org/abs/2402.02750) | ICML · 2024 | 825 | 프롬프트/KV 캐싱 | 별도 튜닝 없이 KV cache를 2비트로 양자화합니다. | | 18 | [LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression](https://arxiv.org/abs/2310.06839) | ACL · 2023 | 658 | 프롬프트 압축 | 질문을 고려해 긴 컨텍스트를 압축하며, 정확도를 유지하거나 높이면서 비용을 줄이는 것을 목표로 합니다. | | 19 | [Scissorhands: Exploiting the Persistence of Importance Hypothesis for LLM KV Cache Compression at Test Time](https://arxiv.org/abs/2305.17118) | NeurIPS · 2023 | 598 | 프롬프트/KV 캐싱 | 토큰 중요도가 지속되는 특성을 활용해 KV cache를 압축합니다. | | 20 | [LLMs Get Lost In Multi-Turn Conversation](https://arxiv.org/abs/2505.06120) | ICLR · 2025 | 562 | 긴 컨텍스트와 컨텍스트 열화 | 모델은 명세가 불충분한 다중 턴 대화에서 단일 턴보다 성능이 낮아집니다. | | 21 | [Learning to Compress Prompts with Gist Tokens](https://arxiv.org/abs/2304.08467) | NeurIPS · 2023 | 534 | 프롬프트 압축 | 프롬프트를 재사용 가능한 소수의 'gist' 토큰으로 압축하도록 모델을 학습합니다. | | 22 | [Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing](https://arxiv.org/abs/2404.14618) | ICLR · 2024 | 519 | 모델 라우팅과 캐스케이드 | 라우터가 쿼리 난이도를 예측해 쉬운 쿼리를 더 작은 모델로 보냅니다. | | 23 | [Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models](https://arxiv.org/abs/2510.04618) | ICLR · 2025 | 505 | 에이전트 비용과 컨텍스트 관리 | 컨텍스트를 점진적으로 갱신되는 플레이북으로 다루어, 다시 쓰기로 인한 컨텍스트 붕괴를 방지합니다. | | 24 | [Stop Overthinking: A Survey on Efficient Reasoning for Large Language Models](https://arxiv.org/abs/2503.16419) | TMLR · 2025 | 499 | 서베이 | 대규모 추론 모델의 효율적인 추론 방법을 정리한 서베이입니다. | | 25 | [LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression](https://arxiv.org/abs/2403.12968) | ACL · 2024 | 487 | 프롬프트 압축 | 작업에 구애받지 않고 여러 작업에 일반화되는, 더 빠른 프롬프트 압축기를 증류해 만듭니다. | | 26 | [Adapting Language Models to Compress Contexts](https://arxiv.org/abs/2305.14788) | EMNLP · 2023 | 465 | 프롬프트 압축 | 모델을 파인튜닝해 긴 컨텍스트를 짧은 요약 벡터로 압축하고, 이를 소프트 프롬프트로 재사용합니다. | | 27 | [Agent Workflow Memory](https://arxiv.org/abs/2409.07429) | ICML · 2024 | 451 | 에이전트 비용과 컨텍스트 관리 | 에이전트가 과거 궤적에서 재사용 가능한 워크플로를 도출해 다시 활용하며, 마이크로 스킬과 취지가 비슷합니다. | | 28 | [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736) | EMNLP · 2023 | 418 | 프롬프트 압축 | 프롬프트에서 정보량이 적은 토큰을 작은 언어 모델로 제거하며, 압축 예산을 조절할 수 있습니다. | | 29 | [Prompt Cache: Modular Attention Reuse for Low-Latency Inference](https://arxiv.org/abs/2311.04934) | MLSys · 2023 | 417 | 프롬프트/KV 캐싱 | 반복되는 프롬프트 모듈의 사전 계산된 어텐션 상태를 재사용해 지연 시간을 줄입니다. | | 30 | [RECOMP: Improving Retrieval-Augmented LMs with Compression and Selective Augmentation](https://arxiv.org/abs/2310.04408) | ICLR · 2023 | 340 | 프롬프트 압축 | 검색한 문서를 짧은 요약으로 압축한 뒤 검색 증강 프롬프트에 넣습니다. | | 31 | [Language Model Tokenizers Introduce Unfairness Between Languages](https://arxiv.org/abs/2305.15425) | NeurIPS · 2023 | 319 | 토큰화와 언어 | 같은 텍스트라도 언어에 따라 토큰화 길이가 크게 달라집니다. | | 32 | [AI Agents That Matter](https://arxiv.org/abs/2407.01502) | TMLR · 2024 | 289 | 평가와 통계 | 에이전트 평가는 정확도뿐 아니라 비용도 통제해야 한다고 주장합니다. | | 33 | [Training Language Models to Reason Efficiently](https://arxiv.org/abs/2502.04463) | NeurIPS · 2025 | 285 | 효율적인 추론/출력 길이 | 추론 모델이 정확도와 추론 길이 사이에서 균형을 잡도록 학습합니다. | | 34 | [Do All Languages Cost the Same? Tokenization in the Era of Commercial Language Models](https://arxiv.org/abs/2305.13707) | EMNLP · 2023 | 278 | 토큰화와 언어 | 토큰화 방식의 차이로 상용 API의 사용 비용이 언어별로 달라짐을 보여 줍니다. | | 35 | [Compressing Context to Enhance Inference Efficiency of Large Language Models](https://arxiv.org/abs/2310.06201) | EMNLP · 2023 | 272 | 프롬프트 압축 | 자기 정보량(self-information)을 기준으로 중복된 어휘 단위를 제거해 추론 전에 입력을 줄입니다. | | 36 | [Same Task, More Tokens: the Impact of Input Length on the Reasoning Performance of Large Language Models](https://arxiv.org/abs/2402.14848) | ACL · 2024 | 270 | 긴 컨텍스트와 컨텍스트 열화 | 입력 길이만 따로 분리해, 입력이 길어질수록 추론 성능이 떨어짐을 보여 줍니다. | | 37 | [Token-Budget-Aware LLM Reasoning](https://arxiv.org/abs/2412.18547) | ACL · 2024 | 259 | 효율적인 추론/출력 길이 | 문제별 토큰 예산을 추정해 chain-of-thought 추론을 짧게 만듭니다. | | 38 | [In-context Autoencoder for Context Compression in a Large Language Model](https://arxiv.org/abs/2307.06945) | ICLR · 2023 | 242 | 프롬프트 압축 | 긴 컨텍스트를 소수의 메모리 슬롯으로 인코딩하여, 고정된 디코더가 이를 읽도록 합니다. | | 39 | [xRAG: Extreme Context Compression for Retrieval-augmented Generation with One Token](https://arxiv.org/abs/2405.13792) | NeurIPS · 2024 | 174 | 프롬프트 압축 | 검색한 문서 하나를 임베딩 토큰 하나로 표현해 RAG 컨텍스트를 줄입니다. | | 40 | [AutoMix: Automatically Mixing Language Models](https://arxiv.org/abs/2310.12963) | NeurIPS · 2023 | 169 | 모델 라우팅과 캐스케이드 | 작은 모델이 자신의 답을 검증하고, 필요할 때만 더 큰 모델로 넘깁니다. | | 41 | [Retrieval meets Long Context Large Language Models](https://arxiv.org/abs/2310.03025) | ICLR · 2023 | 159 | 긴 컨텍스트와 컨텍스트 열화 | 검색 증강과 긴 컨텍스트 윈도우를 비교하며, 검색이 더 적은 연산으로 긴 윈도우에 맞먹을 수 있음을 보여 줍니다. | | 42 | [Batch Prompting: Efficient Inference with Large Language Model APIs](https://arxiv.org/abs/2301.08721) | EMNLP · 2023 | 154 | 배치 처리 | 여러 샘플을 프롬프트 하나에 담아 지시문 토큰을 공유합니다. | | 43 | [Found in the Middle: Calibrating Positional Attention Bias Improves Long Context Utilization](https://arxiv.org/abs/2406.16008) | ACL · 2024 | 151 | 긴 컨텍스트와 컨텍스트 열화 | 위치 어텐션 편향을 보정해 lost-in-the-middle 현상을 줄입니다. | | 44 | [Let Me Speak Freely? A Study On The Impact Of Format Restrictions On Large Language Model Performance.](https://arxiv.org/abs/2408.02442) | EMNLP · 2024 | 142 | 출력 형식 | 엄격한 출력 형식 제한은 추론 성능을 떨어뜨릴 수 있습니다. | | 45 | [Prompt Compression for Large Language Models: A Survey](https://arxiv.org/abs/2410.12388) | NAACL · 2024 | 96 | 서베이 | 하드(토큰 수준) 및 소프트 프롬프트 압축 방법을 정리한 서베이입니다. | | 46 | [500xCompressor: Generalized Prompt Compression for Large Language Models](https://arxiv.org/abs/2408.03094) | ACL · 2024 | 57 | 프롬프트 압축 | 프롬프트를 아주 적은 수의 특수 토큰으로 극단적으로 압축하는 것을 목표로 합니다. | | 47 | [Cost-of-Pass: An Economic Framework for Evaluating Language Models](https://arxiv.org/abs/2504.13359) | ICLR · 2025 | 56 | 평가와 통계 | 정답을 얻는 데 드는 기대 비용을 정의하고, 이를 기준으로 모델을 비교합니다. | | 48 | [Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory](https://arxiv.org/abs/2504.19413) | ECAI · 2025 | 868 | 메모리와 요약 | 전체 기록을 다시 보내는 대신, 핵심 사실을 추출하고 검색하는 메모리 계층입니다. | | 49 | [CacheBlend: Fast Large Language Model Serving for RAG with Cached Knowledge Fusion](https://arxiv.org/abs/2405.16444) | ACM TOCS · 2024 | 342 | 프롬프트/KV 캐싱 | 공유 접두부가 아니더라도 RAG에서 검색된 청크의 KV cache를 재사용합니다. | | 50 | [Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving](https://arxiv.org/abs/2407.00079) | ACM ToS · 2024 | 313 | 프롬프트/KV 캐싱 | 캐시된 KV 접두부를 재사용하는 스케줄러를 중심으로 구성한 Kimi의 프로덕션 서빙 아키텍처입니다. | | 51 | [Recursively Summarizing Enables Long-Term Dialogue Memory in Large Language Models](https://arxiv.org/abs/2308.15022) | Neurocomputing · 2023 | 114 | 메모리와 요약 | 재귀적 요약을 긴 대화의 메모리로 활용합니다. | | 52 | [Reducing Cost of LLM Agents with Trajectory Reduction](https://arxiv.org/abs/2509.23586) | PACMSE · 2025 | 68 | 에이전트 비용과 컨텍스트 관리 | 궤적에서 낭비 요소를 덜어 내어 에이전트 비용을 줄입니다. | | 53 | [MemGPT: Towards LLMs as Operating Systems](https://arxiv.org/abs/2310.08560) | 프리프린트 · 2023 | 1,764 | 에이전트 비용과 컨텍스트 관리 | 메모리 계층을 관리해 에이전트가 컨텍스트 윈도우를 넘어서는 작업을 수행하도록 합니다. | | 54 | [τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains](https://arxiv.org/abs/2406.12045) | 프리프린트 · 2024 | 1,669 | 평가와 통계 | 반복 실행에서 에이전트의 신뢰성을 측정하는 pass^k를 도입한 벤치마크입니다. | | 55 | [RULER: What's the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) | 프리프린트 · 2024 | 1,580 | 긴 컨텍스트와 컨텍스트 열화 | 실제로 활용할 수 있는 컨텍스트 길이가 광고된 윈도우보다 짧은 경우가 많음을 보여 주는 벤치마크입니다. | | 56 | [RouteLLM: Learning to Route LLMs with Preference Data](https://arxiv.org/abs/2406.18665) | 프리프린트 · 2024 | 922 | 모델 라우팅과 캐스케이드 | 선호도 데이터로 학습해 쿼리를 강력한 모델과 저렴한 모델 사이에서 라우팅합니다. | | 57 | [Do NOT Think That Much for 2+3=? On the Overthinking of o1-Like LLMs](https://arxiv.org/abs/2412.21187) | 프리프린트 · 2024 | 605 | 효율적인 추론/출력 길이 | o1 계열 모델이 단순한 질문에도 토큰을 과도하게 쓰는 문제를 보이고, 이를 줄이는 방법을 제안합니다. | | 58 | [Agentless: Demystifying LLM-based Software Engineering Agents](https://arxiv.org/abs/2407.01489) | 프리프린트 · 2024 | 566 | 에이전트 비용과 컨텍스트 관리 | 위치 파악, 수정, 검증으로 이어지는 고정 파이프라인이 SWE-bench Lite에서 개방형 에이전트 루프에 견줄 만한 성능을 낮은 비용으로 냅니다. | | 59 | [L1: Controlling How Long A Reasoning Model Thinks With Reinforcement Learning](https://arxiv.org/abs/2503.04697) | 프리프린트 · 2025 | 416 | 효율적인 추론/출력 길이 | 사용자가 지정한 길이 예산을 따르도록 추론 모델을 학습합니다. | | 60 | [Chain of Draft: Thinking Faster by Writing Less](https://arxiv.org/abs/2502.18600) | 프리프린트 · 2025 | 324 | 효율적인 추론/출력 길이 | 장황한 chain-of-thought 대신 최소한의 초안 단계만 작성하도록 모델에 요청합니다. | | 61 | [RouterBench: A Benchmark for Multi-LLM Routing System](https://arxiv.org/abs/2403.12031) | 프리프린트 · 2024 | 300 | 모델 라우팅과 캐스케이드 | 다중 LLM 라우팅 시스템을 위한 벤치마크 및 평가 프레임워크입니다. | | 62 | [Efficient Large Language Models: A Survey](https://arxiv.org/abs/2312.03863) | 프리프린트 · 2023 | 276 | 서베이 | 데이터, 모델, 시스템 수준에 걸친 효율화 기법을 폭넓게 정리한 서베이입니다. | | 63 | [Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations](https://arxiv.org/abs/2411.00640) | 프리프린트 · 2024 | 194 | 평가와 통계 | LLM 평가에서 불확실성을 보고하는 통계적 방법을 안내합니다. | | 64 | [A Survey of Context Engineering for Large Language Models](https://arxiv.org/abs/2507.13334) | 프리프린트 · 2025 | 171 | 서베이 | LLM 컨텍스트를 선택, 압축, 관리하는 기법을 체계적으로 정리한 서베이입니다. | | 65 | [Non-Determinism of"Deterministic"LLM Settings](https://arxiv.org/abs/2408.04667) | 프리프린트 · 2024 | 159 | 평가와 통계 | 결정적으로 동작하도록 설정한 환경에서도 실행마다 출력이 달라질 수 있음을 보여 줍니다. | | 66 | [Efficient Prompting Methods for Large Language Models: A Survey](https://arxiv.org/abs/2404.01077) | 프리프린트 · 2024 | 71 | 서베이 | 효율성을 위한 프롬프트 압축과 프롬프트 최적화 방법을 정리한 서베이입니다. | | 67 | [Concise Reasoning via Reinforcement Learning](https://arxiv.org/abs/2504.05185) | 프리프린트 · 2025 | 69 | 효율적인 추론/출력 길이 | 강화 학습으로 간결한 추론을 유도합니다. | | 68 | [The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management](https://arxiv.org/abs/2508.21433) | 프리프린트 · 2025 | 66 | 에이전트 비용과 컨텍스트 관리 | 에이전트 컨텍스트 관리에서 단순한 관찰 마스킹이 LLM 요약만큼 효율적입니다. | | 69 | [MCP-Zero: Active Tool Discovery for Autonomous LLM Agents](https://arxiv.org/abs/2506.01056) | 프리프린트 · 2025 | 55 | 도구 선택과 스키마 크기 | 모든 도구 스키마를 주입하는 대신, 에이전트가 필요할 때 도구를 요청하도록 합니다. | | 70 | [RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation](https://arxiv.org/abs/2505.03275) | 프리프린트 · 2025 | 41 | 도구 선택과 스키마 크기 | 모든 도구를 로드하지 않고 관련 있는 MCP 도구 설명만 검색해 가져오므로, 프롬프트 비대화를 막을 수 있습니다. | | 71 | [Efficient Agents: Building Effective Agents While Reducing Cost](https://arxiv.org/abs/2508.02694) | 프리프린트 · 2025 | 40 | 에이전트 비용과 컨텍스트 관리 | 에이전트 시스템을 설계할 때 효율성과 효과성 사이의 트레이드오프를 체계적으로 연구합니다. | | 72 | [Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?](https://arxiv.org/abs/2602.11988) | 프리프린트 · 2026 | 36 | 지침/컨텍스트 파일 | 리포지토리 컨텍스트 파일은 대체로 작업 성공률을 높이지 못했고, 추론 비용은 평균 20% 넘게 늘렸습니다. | | 73 | [Less is More: Optimizing Function Calling for LLM Execution on Edge Devices](https://arxiv.org/abs/2411.15399) | 프리프린트 · 2024 | 33 | 도구 선택과 스키마 크기 | 함수 호출 시점에 선별한 더 작은 도구 집합만 제시해 엣지 기기에서 비용을 줄입니다. | | 74 | [Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks](https://arxiv.org/abs/2601.06007) | 프리프린트 · 2026 | 25 | 프롬프트/KV 캐싱 | 장기 에이전트 작업에서 프롬프트 캐싱의 효과를 평가합니다. | | 75 | [TokenEconomizer: Experience-Driven Black-Box Cost Control for Coding Agents](https://arxiv.org/abs/2610.22732) | 프리프린트 · 2026 | 0 | 에이전트 비용과 컨텍스트 관리 | 이전 세션의 경험을 바탕으로 마이크로 스킬, 도구 가지치기, 루프 가드를 적용해 코딩 에이전트의 비용을 줄입니다. | ## 논문 제안하기 `examples/papers.json`에 항목(arXiv ID, 주제 하나, 직접 작성한 한 줄 요약)과 `examples/papers-ko.json`에 한국어 요약을 추가한 뒤 스크립트 두 개를 실행하고 PR을 엽니다. 알 수 없는 ID는 메타데이터 수집 단계에서 실패하므로 오타를 방지할 수 있습니다. --- ## 리소스 (ko/resources.md) Canonical URL: > 토큰을 절약하는 데 도움이 되는 리포지토리, 논문, 문서입니다. 2026-11-03에 존재 여부를 확인하여 엄선했습니다. 엄선한 목록입니다. 모든 링크는 **2026-11-03**에 확인했습니다. 목록에 포함했다고 해서 **추천하는 것은 아닙니다**. 각 프로젝트의 절감 수치는 제작자가 직접 밝힌 주장이며, 이 문서에서 재현하지 않았습니다. 사용할 때는 자신의 작업으로 벤치마크하고, 비용과 함께 품질 지표도 추적하세요([Agent Tokenomics](../agent-tokenomics/) 참조). :::caution 프록시, 게이트웨이, 압축 도구는 에이전트와 모델 사이에 위치하므로 **프롬프트와 코드를 볼 수 있습니다**. 라이선스와 데이터 처리 방침을 읽어 보고, 비공개 리포지토리에서 사용하기 전에 검토하세요. ::: ## 시작하기 | 리소스 | 설명 | |----------|-----| | [microsoft/TokenEconomizer](https://github.com/microsoft/TokenEconomizer) | 경험 기반으로 코딩 에이전트의 비용을 제어합니다(마이크로 스킬, 도구 가지치기, 루프 가드). 논문: [arXiv:2610.22732](https://arxiv.org/abs/2610.22732), [프로젝트 페이지](https://tokeneconomizer.github.io). | | [Optimize AI credit usage in VS Code](https://code.visualstudio.com/docs/agents/guides/optimize-usage) | 공식 실무 가이드입니다. | | [Diagnose prompt caching with the Cache Explorer](https://code.visualstudio.com/docs/agents/agent-troubleshooting/cache-explorer) | 공식 문서로, 요청 간에 접두부가 처음 달라지는 지점을 찾는 방법을 설명합니다. | | [Azure OpenAI prompt caching](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/prompt-caching) | Azure OpenAI의 최소 길이, `cached_tokens`, `prompt_cache_key`, 보존 기간, 과금 및 데이터 상주 규칙을 설명합니다. | | [OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) | 캐시 가능 접두부 규칙, 캐시를 무효화하는 설정, 진단 방법을 설명합니다. | | [Usage-based billing for individuals](https://docs.github.com/en/copilot/concepts/billing/usage-based-billing-for-individuals) | AI 크레딧이 청구되는 방식을 설명합니다. | | [github/awesome-copilot](https://github.com/github/awesome-copilot) | 커뮤니티가 만든 Copilot용 지침, 에이전트, 스킬 모음입니다. | | [pleasedodisturb/awesome-llm-token-optimization](https://github.com/pleasedodisturb/awesome-llm-token-optimization) | 전략, 도구, 논문을 정리한 또 다른 큐레이션 목록입니다. | ## 도구 출력과 명령 노이즈 줄이기 | 프로젝트 | 기능 | |---------|--------------| | [rtk-ai/rtk](https://github.com/rtk-ai/rtk) | 일반적인 개발 명령의 출력을 모델에 전달하기 전에 요약하는 CLI 프록시입니다. | | [headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) | 도구 출력, 로그, 파일, RAG 청크를 LLM에 전달하기 전에 압축합니다. | | [gglucass/headroom-desktop](https://github.com/gglucass/headroom-desktop) | 같은 방식을 코딩 에이전트용 데스크톱 앱으로 제공하는 도구입니다. | | [Dave-London/Pare](https://github.com/Dave-London/Pare) | git, 테스트 러너, npm, Docker용 구조화된 토큰 효율적 MCP 서버입니다. | | [claw-compactor](https://github.com/open-compress/claw-compactor) | 코드 분석을 활용하는 다단계 가역 압축 파이프라인입니다. | | [optscale-kompressor](https://github.com/hystax/optscale-kompressor) | 코딩 에이전트를 위한 결정적 프롬프트 압축을 Rust 바이너리 하나로 제공합니다. | | [fkiene/llmtrim](https://github.com/fkiene/llmtrim) | API 요청의 프롬프트, 기록, 도구 출력을 줄이는 로컬 프록시입니다. | | [Paritok-official/paritok-4b-v1](https://github.com/Paritok-official/paritok-4b-v1) | 코딩 에이전트를 위한 비파괴 압축 게이트웨이입니다. | ## 프롬프트와 데이터 압축 | 프로젝트 | 기능 | |---------|--------------| | [microsoft/LLMLingua](https://github.com/microsoft/LLMLingua) | 프롬프트 압축 연구(LLMLingua, LLMLingua-2)입니다. 논문: [arXiv:2310.05736](https://arxiv.org/abs/2310.05736). | | [jia-gao/leanctx](https://github.com/jia-gao/leanctx) | 프로덕션 앱에 바로 적용할 수 있는 프롬프트 압축 SDK입니다(LLMLingua-2 기반). | | [3DAgentWorld/Toolkit-for-Prompt-Compression](https://github.com/3DAgentWorld/Toolkit-for-Prompt-Compression) | 여러 프롬프트 압축 방법을 모아 둔 툴킷입니다. | | [ZongqianLi/Prompt-Compression-Survey](https://github.com/ZongqianLi/Prompt-Compression-Survey) | 프롬프트 압축 방법을 정리한 서베이입니다(NAACL 2025). | | [sriinnu/clipforge-PAKT](https://github.com/sriinnu/clipforge-PAKT) | JSON, YAML, CSV, Markdown을 무손실 방식을 우선하여 압축합니다. | | [ISON-format/ison](https://github.com/ISON-format/ison) | LLM 데이터용으로 토큰 효율이 높은 JSON 대체 형식입니다. | ## 간결한 응답 스타일과 측정 기반 평가 | 프로젝트 | 기능 | |---------|--------------| | [JuliusBrussee/caveman](https://github.com/JuliusBrussee/caveman) | 에이전트가 간결하게 답하도록 만드는 스킬/프록시입니다. | | [danielle34/cavewoman](https://github.com/danielle34/cavewoman) | 입력 압축과 출력 압축이 실제로 얼마나 절약하는지 측정하는 평가 프레임워크입니다. | | [YangJunMan/claude-code-token-savings-benchmark](https://github.com/YangJunMan/claude-code-token-savings-benchmark) | 여러 토큰 절약 도구를 비교하는 재현 가능한 벤치마크입니다. | ## 코드는 적게 가져오고 메모리는 작게 유지하기 | 프로젝트 | 기능 | |---------|--------------| | [dotnetpower/code-context](https://github.com/dotnetpower/code-context) ([Marketplace](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) · [트랙 A 가이드](../copilot-tokenomics/cctx/)) | VS Code 전용 네이티브 Language Model Tools + 공유 로컬 Rust 트라이그램 인덱스(`cctx`)로, `<8 KiB` 인라인 예산 코드 읽기, BPE 수식 지침, 웜 탐색 15.20배 가속, 상태 표시줄·`cctx usage` 실시간 AIC/USD 절감 대시보드를 제공합니다. | | [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify) | 폴더(코드, 문서, PDF, 이미지)를 질의할 수 있는 지식 그래프로 변환합니다. | | [jgravelle/jcodemunch-mcp](https://github.com/jgravelle/jcodemunch-mcp) | 심볼 단위로 검색합니다. 파일 전체가 아니라 필요한 함수만 가져옵니다. | | [redhat-et/ripwire](https://github.com/redhat-et/ripwire) | 리포지토리를 읽지 않고도 관련 코드를 찾는 CLI + MCP 서버입니다. | | [yamadashy/repomix](https://github.com/yamadashy/repomix) | 리포지토리를 AI가 읽기 쉬운 파일 하나로 묶습니다(선택적으로 사용하세요. 큰 묶음은 토큰이 많이 듭니다). | | [radimsem/remindb](https://github.com/radimsem/remindb) | SQLite 파일 하나로 휴대할 수 있는 에이전트 메모리입니다. | | [cytostack/openwolf](https://github.com/cytostack/openwolf) | 에이전트 간에 공유하는 프로젝트 메모리로, 대화 기록에서 토큰을 집계합니다. | | [fajarhide/contexere](https://github.com/fajarhide/contexere) | 여러 에이전트의 스킬, 키, 메모리를 한곳에서 관리합니다. | ## 토큰, 도구, 비용 감사 | 프로젝트 | 기능 | |---------|--------------| | [tokprof](https://github.com/dotnetpower/agent-tokenomics/tree/main/profiler)(이 저장소) | 코드를 수정하지 않고 호출마다 입력 토큰을 시스템 프롬프트, 이력, 사용자 프롬프트, 도구 항목으로 분해합니다. 초기 개발 단계입니다. | | [alexgreensh/token-optimizer](https://github.com/alexgreensh/token-optimizer) | 에이전트 세션에서 "유령 토큰"과 컨텍스트 품질 저하를 찾아냅니다. | | [activeing123/mcptoon](https://github.com/activeing123/mcptoon) | 도구 검색과 컨텍스트 압축을 목표로 하는 MCP 게이트웨이 CLI입니다. | | [ccusage/ccusage](https://github.com/ccusage/ccusage) | 로컬 Claude Code 로그로 사용량과 비용 보고서를 만듭니다. | | [Maciek-roboblog/Claude-Code-Usage-Monitor](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor) | 예측 기능을 갖춘 실시간 사용량 모니터입니다. | | [junhoyeo/tokscale](https://github.com/junhoyeo/tokscale) | 터미널에서 여러 AI 코딩 에이전트의 토큰 사용량을 확인합니다. | ## 관측 도구와 게이트웨이(직접 운영하는 에이전트용) | 프로젝트 | 기능 | |---------|--------------| | [langfuse/langfuse](https://github.com/langfuse/langfuse) | LLM 앱을 위한 오픈 소스 트레이싱, 평가, 비용 추적 도구입니다. | | [Arize-ai/phoenix](https://github.com/Arize-ai/phoenix) | OpenTelemetry 기반의 AI 관측 가능성 및 평가 도구입니다([문서](https://arize.com/docs/phoenix)). | | [Helicone/helicone](https://github.com/Helicone/helicone) | LLM 관측 플랫폼이자 OpenAI 호환 게이트웨이입니다([문서](https://docs.helicone.ai/getting-started/quick-start)). | | [LangSmith](https://docs.langchain.com/langsmith/cost-tracking) | 토큰과 비용 내역을 제공하는 LangChain의 호스팅 트레이싱 및 평가 플랫폼입니다(SDK: [Python](https://github.com/langchain-ai/langsmith-python), [JS](https://github.com/langchain-ai/langsmith-javascript)). | | [Portkey-AI/gateway](https://github.com/Portkey-AI/gateway) | 가드레일을 갖춘 AI 게이트웨이이며, Portkey 플랫폼에서 모니터링을 추가로 제공합니다([문서](https://portkey.ai/docs/introduction/what-is-portkey)). | | [openlit/openlit](https://github.com/openlit/openlit) | 에이전트를 위한 OpenTelemetry 기반 트레이싱 및 평가 도구입니다. | | [AgentOps-AI/agentops](https://github.com/AgentOps-AI/agentops) | 에이전트 모니터링과 LLM 비용 추적용 SDK입니다. | | [BerriAI/litellm](https://github.com/BerriAI/litellm) | 100개 이상의 공급자에 대한 비용 추적과 라우팅을 제공하는 게이트웨이입니다. | | [maximhq/bifrost](https://github.com/maximhq/bifrost) | 장애 조치를 지원하는 LLM / MCP / 에이전트 게이트웨이입니다. | 이 도구들은 [1단계(진단)](../agent-tokenomics/01-diagnose/#collect-the-request-log)와 연결되며, 해당 단계에서 Phoenix, Langfuse, LangSmith, Helicone, Portkey를 비교합니다. 이 도구로 요청별 로그를 수집하면 [예제 스크립트](https://github.com/dotnetpower/agent-tokenomics/tree/main/examples)에서 분석할 수 있습니다. ## 컨텍스트 엔지니어링과 스펙 주도 워크플로 | 프로젝트 | 기능 | |---------|--------------| | [github/spec-kit](https://github.com/github/spec-kit) | 스펙 주도 개발 툴킷입니다. 먼저 계획하고 나서 구현합니다. | | [Fission-AI/OpenSpec](https://github.com/Fission-AI/OpenSpec) | AI 코딩 도우미를 위한 스펙 주도 개발 도구입니다. | | [shanraisshan/claude-code-best-practice](https://github.com/shanraisshan/claude-code-best-practice) | Claude Code로 에이전트 엔지니어링을 하는 방법을 정리한 모범 사례입니다. | | [microsoft/vscode-copilot-chat](https://github.com/microsoft/vscode-copilot-chat) | VS Code Copilot Chat 확장의 소스 코드입니다. | ## 논문 전체 순위 목록(학회 등급, 인용 수 순)은 [논문](../papers/) 페이지에 있습니다. 주요 논문은 다음과 같습니다. | 논문 | 핵심 내용 | |-------|----------| | [Evaluating AGENTS.md (arXiv:2602.11988)](https://arxiv.org/abs/2602.11988) | 컨텍스트 파일은 대체로 작업 성공률을 높이지 못했고 비용은 평균 20% 넘게 늘렸습니다. 표준에서 벗어난 관행을 알려 줄 때 유용합니다. | | [Lost in the Middle (arXiv:2307.03172)](https://arxiv.org/abs/2307.03172) | 모델은 긴 컨텍스트의 중간에 있는 정보를 시작이나 끝에 있는 정보보다 덜 안정적으로 활용합니다. | | [TokenEconomizer (arXiv:2610.22732)](https://arxiv.org/abs/2610.22732) | 보고된 바에 따르면 에이전트–모델 조합 5개에서 SWE-Bench 평균 비용이 18.4–30.9% 낮아졌습니다. | | [LLMLingua (arXiv:2310.05736)](https://arxiv.org/abs/2310.05736) | 소형 언어 모델을 이용한 프롬프트 압축입니다. | | [tiktoken](https://github.com/openai/tiktoken) | 이 프로젝트의 [토큰 카운터](https://github.com/dotnetpower/agent-tokenomics/blob/main/examples/count_tokens.py)가 사용하는 토크나이저입니다. | ## 리소스 제안하기 링크, 직접 쓴 한 줄 설명, 존재 여부를 확인한 방법을 적어 이슈나 PR로 보내 주세요.