Claude Code Context Usage: Diagnose Unnecessary Tokens

Iniciado por joomlamz, Hoje at 10:25

Respostas: 1   |   Visualizações: 4

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações, caros colegas do **webmastersmz.com**! Como especialista em tecnologia, analisei recentemente o tópico em inglês entitulado *"Claude Code Context Usage: Diagnose Unnecessary Tokens"* (Uso de Contexto do Claude Code: Diagnóstico de Tokens Desnecessários), e trago aqui uma análise técnica direcionada para a nossa realidade de desenvolvimento.

A discussão central gira em torno da otimização do uso de tokens por assistentes de IA (neste caso, o Claude Code) durante o processo de desenvolvimento. O principal problema apontado é o consumo excessivo e muitas vezes desnecessário de tokens devido ao envio de contexto redundante — como ficheiros inteiros de configuração, logs extensos ou dependências desnecessárias — quando apenas uma pequena fração do código precisa de ser analisada.

### Os Pontos Principais da Análise:

1. **Inchaço de Contexto (*Context Bloat*):** Enviar bases de código completas para a IA consome largura de banda, aumenta a latência da resposta e eleva drasticamente os custos operacionais (quando se utilizam APIs baseadas no consumo de tokens).
2. **Perda de Precisão:** Curiosamente, quanto mais informação irrelevante é alimentada no prompt, maior é a probabilidade de a IA se "perder" nos detalhes cruciais, resultando em soluções menos precisas ou alucinações de código.
3. **Boas Práticas de Diagnóstico:** O tópico sugere o uso rigoroso de ficheiros de exclusão (semelhantes ao `.gitignore`, mas aplicados à IA, como `.claudecodeignore`), além de uma curadoria manual estrita do que realmente importa para resolver o *bug* ou implementar a nova funcionalidade.

Esta é uma discussão fundamental para nós, programadores e administradores de sistemas, pois a eficiência no uso de ferramentas de IA traduz-se diretamente em poupança de tempo e recursos computacionais.

Como é que vocês têm lidado com a gestão de tokens nos vossos fluxos de trabalho diários? Já implementaram alguma estratégia para filtrar o contexto enviado para as vossas IAs? **Deixem as vossas opiniões e experiências aqui no fórum webmastersmz.com para enriquecermos este debate!**

---

Para garantir que os vossos projetos, aplicações e fóruns rodam sem falhas e com a máxima velocidade, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

Claude Code Context Usage: Diagnose Unnecessary Tokens



Tópico: Claude Code Context Usage: Diagnose Unnecessary Tokens
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------


Claude Code Context Usage: Diagnose Unnecessary Tokens


In the Claude Code community, a user reported that a fresh session started at roughly 35,000 tokens and later dropped to about 13,000 after cleaning up repository instructions. That is a useful reminder to inspect your own project setup, but not a universal benchmark: codebase size, instruction length, MCP tools, and measurement methods differ across projects.

You can inspect your setup in two controlled runs. Measure baseline context using native Claude Code commands and API metadata, modify exactly one reversible context source, and repeat the same request. Then compare token usage, cost, and task correctness.



Measure baseline context with built-in commands


You do not need to guess context sizes. Claude Code provides native commands:


/context — displays the breakdown of active context: project instructions, connected MCP tools, cached files, and conversation history;


/cost — outputs token consumption (input, output, cache) and estimated cost for the current session.

For a separate API workflow, the API Dashboard provides per-request accounting: input tokens, output tokens, cache hits, HTTP status, and actual balance charges.



Use one task with a checkable answer


Start with a small read-only query that does not modify files:

Find where validateInvoice is defined.
Name the function file and one test that checks an empty amount.
Do not edit anything.

This request produces a clear binary outcome: two correct file paths or a failure.

Before running, fix the baseline variables:

• identical Git branch and commit revision;

• identical prompt text;

• identical model selection;

• identical project instructions, skills, and MCP tools;

• expected target paths for the function and test.



Run A: record the baseline metrics


Open a fresh session, execute /context to inspect baseline load, run the test query, and record the metadata:

Field
Run A

Request status
200 OK

Input tokens
18,420

Output tokens
310

Cache tokens
0

Cost / charge
$0.026

Result
correct function and test identified

These figures illustrate the comparison worksheet and format verified on August 18, 2026 against current BetterToken pricing. In your own project, record the live numbers from /cost or your dashboard.

Do not include API keys, private source code, full proprietary prompts, or sensitive logs in notes. Metadata, source names, and task outcomes are sufficient.



Prioritized diagnostics order


Do not disable all configuration at once. Investigate context sources in priority order:


Project Instructions (CLAUDE.md) — check for outdated build logs, duplicated API specs, and oversized reference blocks.


MCP Servers and Skills — disconnect heavy external tools that are not needed for the current isolated task.


Session History — ensure old tasks or long terminal outputs are not polluting context (use /compact or start fresh with a handoff if needed).


File Read Scope — restrict search scope to specific directories if the agent scans the entire repository tree.

Suppose CLAUDE.md contains a 12,000-line build log. Make one reversible change: move the log to docs/build.log and keep a concise pointer in CLAUDE.md. Do not change the model, MCP tools, or prompt at the same time.



Run B: repeat the query and compare metrics


Keep the revision, model, and prompt unchanged. After the single modification, rerun the request and complete the A/B comparison table:

Field
Run A
Run B
Difference

Request status
200 OK
200 OK
Success

Input tokens
18,420
6,180
-12,240

Output tokens
310
295
-15

Cache tokens
0
0
0

Cost / charge
$0.026
$0.009
-$0.017

Function found
yes
yes
unchanged

Test found
yes
yes
unchanged

If input tokens dropped but Run B identified the wrong test or ignored a mandatory project constraint, the change degraded performance. Restore the original instruction.



Step-by-step verification


Retain configuration changes only when all five criteria are met:


Single variable per test: exactly one context source changed.


Maintained accuracy: the function and test are correctly located.


Constraint preservation: safety, styling, and architectural rules remain enforced.


Usage confirmation: /cost and the dashboard confirm expected metadata changes.


Secondary confirmation: the result is reproduced on one more small task.



Compare API usage in BetterToken Dashboard


For your own API workflow, the BetterToken Dashboard displays balance, active model, exact timestamp, HTTP status, input, output, and cache tokens, along with the resulting charge. Match records by timestamps from Runs A and B and record them in your comparison table. The dashboard stores request metadata without storing complete private prompt text or responses.

BetterToken provides independent Anthropic-compatible API access with pay-as-you-go billing, separate from Claude.ai subscriptions. Check the current BetterToken documentation for Claude Code, generate an API Key in your workspace, and track token usage directly in the dashboard.



Diagnostic summary


The purpose of context optimization is removing irrelevant noise without losing essential context. Measure baseline context with /context and /cost, adjust one source at a time, verify task accuracy, and cross-reference API usage metadata.



Sources


• Claude Code documentation

• User observation about 35K and 13K tokens

• BetterToken Docs: Claude Code

Originally published on the BetterToken blog.

BetterToken provides pay-as-you-go access to AI model APIs through

OpenAI-compatible and Anthropic-compatible endpoints — useful if you are wiring

Claude Code, Codex, or your own tooling to a custom base URL.

See the docs to get started.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: