Skip to main content Skills Marketplace Descubra e explore skills de IA criadas pela comunidade.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Copiar promptMostrar detalhes do prompt Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
npx skills add https://github.com/tools-only/X-Skills --skill engineeringO comando permanece em uma só linha. Role horizontalmente para revisá-lo antes de copiar.
Prefere uma cópia local? Baixe os arquivos disponíveis atualmente no SkillsMP.
Baixar Zip Baixando... Ocupações relacionadas SOC
Baseado na classificação ocupacional SOC
title Cost Caps & Budget Management description Hard budget controls for AI spending. Real-time spend tracking, automatic shutoffs, team quotas, and financial safeguards to prevent runaway costs. category Cost wordCount 3200 readTime 16 featured false order 2 tags ["cost","budget","spending","quotas","optimization"] prerequisites [] relatedPlaybooks ["01-multi-agent-rate-limits","09-cost-attribution"]
API costs can spiral quickly when running multi-agent workflows at scale. This playbook provides proven strategies for implementing cost controls, monitoring spend in real-time, and optimizing Claude API usage without sacrificing quality.
Understanding API Costs
Anthropic Claude Pricing (January 2025)
Model Input (per 1M tokens) Output (per 1M tokens) Context Window Claude 3.5 Sonnet $3.00 $15.00 200K Claude 3.5 Haiku $0.80 $4.00 200K Claude 3 Opus $15.00 $75.00 200K
Reality Check : A single code review session can cost:
Small file (500 tokens): $0.0075 (Sonnet)
Large file (5,000 tokens): $0.075 (Sonnet)
Full repository (50,000 tokens): $0.75 (Sonnet)
Hidden Cost Drivers
const response = await claude.messages .create ({
model : 'claude-3-5-sonnet-20241022' ,
max_tokens : 4096 ,
messages : [{
role : 'user' ,
content : `Review this entire codebase: ${fs.readFileSync('monorepo.txt' )} `
}]
});
Cost Tracking
1. Real-Time Token Counting import Anthropic from '@anthropic-ai/sdk' ;
interface CostMetrics {
inputTokens : number ;
outputTokens : number ;
inputCost : number ;
outputCost : number ;
totalCost : number ;
model : string ;
}
class CostTracker {
private costs : CostMetrics [] = [];
private pricing = {
'claude-3-5-sonnet-20241022' : { input : 3.00 , output : 15.00 },
'claude-3-5-haiku-20241022' : { input : 0.80 , output : 4.00 },
'claude-3-opus-20240229' : { input : 15.00 , output : 75.00 },
};
track (usage : Anthropic .Usage , model : string ): CostMetrics {
const prices = this .pricing [model];
const metrics : CostMetrics = {
inputTokens : usage.input_tokens ,
outputTokens : usage.output_tokens ,
inputCost : (usage.input_tokens / 1_000_000 ) * prices.input ,
outputCost : (usage.output_tokens / 1_000_000 ) * prices.output ,
totalCost : 0 ,
model
};
metrics.totalCost = metrics.inputCost + metrics.outputCost ;
this .costs .push (metrics);
return metrics;
}
getTotalCost (): number {
return this .costs .reduce ((sum, c ) => sum + c.totalCost , 0 );
}
getCostByModel (model : string ): number {
return this .costs
.filter (c => c.model === model)
.reduce ((sum, c ) => sum + c.totalCost , 0 );
}
getAverageCostPerRequest (): number {
return this .getTotalCost () / this .costs .length ;
}
}
const tracker = new CostTracker ();
const response = await claude.messages .create ({
model : 'claude-3-5-sonnet-20241022' ,
messages : [...]
});
const cost = tracker.track (response.usage , response.model );
console .log (`Request cost: $${cost.totalCost.toFixed(4 )} ` );
console .log (`Total spent: $${tracker.getTotalCost().toFixed(2 )} ` );
2. Analytics Daemon Integration The @claude-code-plugins/analytics-daemon emits cost events:
interface CostUpdateEvent {
type : 'cost.update' ;
timestamp : number ;
conversationId : string ;
model : 'claude-3-5-sonnet-20241022' ;
inputCost : 0.0045 ;
outputCost : 0.012 ;
totalCost : 0.0165 ;
currency : 'USD' ;
}
const ws = new WebSocket ('ws://localhost:3456' );
ws.onmessage = (event ) => {
const data = JSON .parse (event.data );
if (data.type === 'cost.update' ) {
updateBudget (data.totalCost );
}
};
3. Daily Budget Dashboard Query costs via HTTP API:
curl http://localhost:3333/api/sessions | jq '.sessions[] | {id, plugins, totalCost}'
curl http://localhost:3333/api/status | jq '.watcher'
Budget Enforcement
Strategy 1: Hard Caps with Circuit Breakers class BudgetEnforcer {
private spent = 0 ;
private dailyBudget : number ;
private lastReset : Date ;
constructor (dailyBudgetUSD : number ) {
this .dailyBudget = dailyBudgetUSD;
this .lastReset = new Date ();
}
async executeWithBudget (
fn : () => Promise <{ result : T; cost : number }>
): Promise {
if (this .isNewDay ()) {
this .spent = 0 ;
this .lastReset = new Date ();
}
if (this .spent >= this .dailyBudget ) {
throw new Error (
`Daily budget exceeded: $${this .spent.toFixed(2 )} / $${this .dailyBudget} `
);
}
const { result, cost } = await fn ();
this .spent += cost;
if (this .spent >= this .dailyBudget * 0.8 ) {
console .warn (
`⚠️ 80% of daily budget used: $${this .spent.toFixed(2 )} / $${this .dailyBudget} `
);
}
return result;
}
private isNewDay (): boolean {
const now = new Date ();
return now.toDateString () !== this .lastReset .toDateString ();
}
getRemainingBudget (): number {
return Math .max (0 , this .dailyBudget - this .spent );
}
getSpendPercentage (): number {
return (this .spent / this .dailyBudget ) * 100 ;
}
}
const budget = new BudgetEnforcer (50.00 );
try {
await budget.executeWithBudget (async () => {
const response = await claude.messages .create (...);
const cost = calculateCost (response.usage );
return { result : response, cost };
});
} catch (error) {
console .error ('Budget exhausted for today' );
}
Strategy 2: Tiered Budgets by Priority enum Priority {
CRITICAL = 'critical' ,
HIGH = 'high' ,
MEDIUM = 'medium' ,
LOW = 'low'
}
class TieredBudget {
private budgets = new Map ([
[Priority .CRITICAL , new BudgetEnforcer (100 )],
[Priority .HIGH , new BudgetEnforcer (50 )],
[Priority .MEDIUM , new BudgetEnforcer (20 )],
[Priority .LOW , new BudgetEnforcer (5 )],
]);
async execute (
priority : Priority ,
fn : () => Promise <{ result : T; cost : number }>
): Promise {
const budget = this .budgets .get (priority)!;
return await budget.executeWithBudget (fn);
}
getStatus ( ) {
return Array .from (this .budgets .entries ()).map (([priority, budget] ) => ({
priority,
spent : budget.getSpendPercentage ().toFixed (1 ) + '%' ,
remaining : '$' + budget.getRemainingBudget ().toFixed (2 )
}));
}
}
const tiered = new TieredBudget ();
await tiered.execute (Priority .CRITICAL , async () => {
const result = await debugIncident ();
return { result, cost : 0.50 };
});
await tiered.execute (Priority .LOW , async () => {
const result = await reviewCode ();
return { result, cost : 0.05 };
});
Strategy 3: Per-User Quotas class UserQuotaManager {
private userBudgets = new Map ();
private userSpent = new Map ();
constructor (private defaultQuota : number = 10 ) {}
setQuota (userId : string , quotaUSD : number ) {
this .userBudgets .set (userId, quotaUSD);
}
async executeForUser (
userId : string ,
fn : () => Promise <{ result : T; cost : number }>
): Promise {
const quota = this .userBudgets .get (userId) || this .defaultQuota ;
const spent = this .userSpent .get (userId) || 0 ;
if (spent >= quota) {
throw new Error (
`User ${userId} quota exceeded: $${spent.toFixed(2 )} / $${quota} `
);
}
const { result, cost } = await fn ();
this .userSpent .set (userId, spent + cost);
return result;
}
getUserStatus (userId : string ) {
const quota = this .userBudgets .get (userId) || this .defaultQuota ;
const spent = this .userSpent .get (userId) || 0 ;
return {
userId,
quota : `$${quota} ` ,
spent : `$${spent.toFixed(2 )} ` ,
remaining : `$${(quota - spent).toFixed(2 )} ` ,
percentage : `${((spent / quota) * 100 ).toFixed(1 )} %`
};
}
}
Optimization Strategies
1. Model Selection by Task
const models = {
sonnet : {
input : (10_000 / 1_000_000 ) * 3.00 ,
output : (1_000 / 1_000_000 ) * 15.00 ,
total : 0.045
},
haiku : {
input : (10_000 / 1_000_000 ) * 0.80 ,
output : (1_000 / 1_000_000 ) * 4.00 ,
total : 0.012
},
opus : {
input : (10_000 / 1_000_000 ) * 15.00 ,
output : (1_000 / 1_000_000 ) * 75.00 ,
total : 0.225
}
};
function selectModel (task : AgentTask ): string {
if (task.requiresReasoning ) {
return 'claude-3-5-sonnet-20241022' ;
} else if (task.isSimple ) {
return 'claude-3-5-haiku-20241022' ;
} else {
return 'claude-3-5-sonnet-20241022' ;
}
}
2. Context Window Optimization
async function reviewFile (file : string , codebase : string ) {
return await claude.messages .create ({
model : 'claude-3-5-sonnet-20241022' ,
messages : [{
role : 'user' ,
content : `Codebase context:\n${codebase} \n\nReview:\n${file} `
}]
});
}
async function reviewFileOptimized (file : string , relatedFiles : string [] ) {
const context = relatedFiles.join ('\n' );
return await claude.messages .create ({
model : 'claude-3-5-sonnet-20241022' ,
messages : [{
role : 'user' ,
content : `Related files:\n${context} \n\nReview:\n${file} `
}]
});
}
3. Caching Strategy class ResponseCache {
private cache = new Map ();
private ttl = 3600000 ;
async execute (
cacheKey : string ,
fn : () => Promise <{ result : T; cost : number }>
): Promise <{ result : T; cost : number ; cached : boolean }> {
const cached = this .cache .get (cacheKey);
if (cached && Date .now () - cached.timestamp < this .ttl ) {
console .log (`Cache hit: $${cached.cost.toFixed(4 )} saved` );
return { result : cached.response , cost : 0 , cached : true };
}
const { result, cost } = await fn ();
this .cache .set (cacheKey, {
response : result,
cost,
timestamp : Date .now ()
});
return { result, cost, cached : false };
}
getCacheStats ( ) {
const entries = Array .from (this .cache .values ());
return {
entries : entries.length ,
totalSavings : entries.reduce ((sum, e ) => sum + e.cost , 0 ),
hitRate : 0
};
}
}
const cache = new ResponseCache ();
const { result, cost, cached } = await cache.execute (
`code-review-${fileHash} ` ,
async () => {
const response = await claude.messages .create (...);
return { result : response, cost : calculateCost (response.usage ) };
}
);
4. Batch Processing
async function reviewFiles (files : string [] ) {
for (const file of files) {
await claude.messages .create ({
messages : [{ role : 'user' , content : `Review: ${file} ` }]
});
}
}
async function reviewFilesBatch (files : string [] ) {
const batches = chunk (files, 10 );
for (const batch of batches) {
await claude.messages .create ({
messages : [{
role : 'user' ,
content : `Review these files:\n${batch.map((f, i) => `${i+1 } . ${f} ` ).join('\n' )} `
}]
});
}
}
Production Examples
Example 1: Plugin Marketplace Review
const budget = new BudgetEnforcer (10.00 );
const cache = new ResponseCache ();
const tracker = new CostTracker ();
async function reviewPlugins ( ) {
const plugins = await getPlugins ();
const results = [];
for (const plugin of plugins) {
try {
await budget.executeWithBudget (async () => {
const { result, cost, cached } = await cache.execute (
`security-review-${plugin.id} ` ,
async () => {
const response = await claude.messages .create ({
model : 'claude-3-5-haiku-20241022' ,
max_tokens : 500 ,
messages : [{
role : 'user' ,
content : `Security review:\n${plugin.code} `
}]
});
const metrics = tracker.track (response.usage , response.model );
return { result : response, cost : metrics.totalCost };
}
);
results.push ({ plugin : plugin.name , review : result, cached });
return { result, cost };
});
} catch (error) {
console .error (`Budget exceeded at plugin ${plugin.name} ` );
break ;
}
}
return results;
}
Example 2: Cost Attribution by Team interface Team {
name : string ;
members : string [];
monthlyBudget : number ;
}
class TeamBudgetManager {
private teams = new Map ();
private teamSpend = new Map ();
addTeam (team : Team ) {
this .teams .set (team.name , team);
this .teamSpend .set (team.name , 0 );
}
async executeForTeam (
teamName : string ,
userId : string ,
fn : () => Promise <{ result : T; cost : number }>
): Promise {
const team = this .teams .get (teamName);
if (!team) throw new Error (`Unknown team: ${teamName} ` );
if (!team.members .includes (userId)) {
throw new Error (`User ${userId} not in team ${teamName} ` );
}
const spent = this .teamSpend .get (teamName) || 0 ;
if (spent >= team.monthlyBudget ) {
throw new Error (`Team ${teamName} budget exceeded` );
}
const { result, cost } = await fn ();
this .teamSpend .set (teamName, spent + cost);
return result;
}
getTeamReport (teamName : string ) {
const team = this .teams .get (teamName)!;
const spent = this .teamSpend .get (teamName) || 0 ;
return {
team : teamName,
members : team.members .length ,
budget : `$${team.monthlyBudget} ` ,
spent : `$${spent.toFixed(2 )} ` ,
remaining : `$${(team.monthlyBudget - spent).toFixed(2 )} ` ,
percentageUsed : `${((spent / team.monthlyBudget) * 100 ).toFixed(1 )} %` ,
daysRemaining : 30 - new Date ().getDate (),
projectedOverage : spent / new Date ().getDate () * 30 > team.monthlyBudget
};
}
}
const manager = new TeamBudgetManager ();
manager.addTeam ({
name : 'Engineering' ,
members : ['alice@example.com' , 'bob@example.com' ],
monthlyBudget : 500
});
manager.addTeam ({
name : 'QA' ,
members : ['charlie@example.com' ],
monthlyBudget : 100
});
await manager.executeForTeam ('Engineering' , 'alice@example.com' , async () => {
const result = await runTests ();
return { result, cost : 2.50 };
});
console .log (manager.getTeamReport ('Engineering' ));
ROI Analysis
Cost vs. Value Metrics interface WorkflowMetrics {
name : string ;
costPerRun : number ;
timesSaved : number ;
errorsPrevented : number ;
manualCost : number ;
}
function calculateROI (metrics : WorkflowMetrics ): number {
const timeSavingsValue = (metrics.timesSaved / 60 ) * metrics.manualCost ;
const errorCostSavings = metrics.errorsPrevented * 100 ;
const totalValue = timeSavingsValue + errorCostSavings;
const totalCost = metrics.costPerRun ;
return ((totalValue - totalCost) / totalCost) * 100 ;
}
const codeReviewMetrics : WorkflowMetrics = {
name : 'Automated Code Review' ,
costPerRun : 0.50 ,
timesSaved : 30 ,
errorsPrevented : 3 ,
manualCost : 100
};
const roi = calculateROI (codeReviewMetrics);
console .log (`ROI: ${roi.toFixed(0 )} %` );
Break-Even Analysis Workflow API Cost/Run Manual Cost/Run Runs to Break Even Code Review $0.50 $50 1 Test Generation $2.00 $200 1 Documentation $1.00 $80 1 Bug Triage $0.25 $25 1
Key Insight : Even "expensive" AI workflows pay for themselves in the first run.
Best Practices
DO ✅ const tracker = new CostTracker ();
const budget = new BudgetEnforcer (50 ); const model = task.isComplex ? 'sonnet' : 'haiku' ; const cache = new ResponseCache ();
DON'T ❌
Don't use Opus for everything
model : 'claude-3-opus-20240229'
Don't send full codebase every time
content : fs.readFileSync ('entire-repo.txt' )
await claude.messages .create ({...});
Don't run without budgets
while (true ) { await expensiveCall (); }
Tools & Resources
Analytics Daemon Monitor costs in real-time:
cd packages/analytics-daemon
pnpm start
Anthropic Dashboard
Plugins with Built-in Cost Optimization
performance-engineer - Automatic model selection
cost-optimizer - Budget tracking
cache-manager - Response caching
Summary
Sonnet : $3/1M input, $15/1M output - Production standard
Haiku : 73% cheaper - Use for simple tasks
Context optimization : 85% cost savings
Caching : 30% cost savings
Budget enforcement : Prevents runaway costs
[ ] Implement CostTracker
[ ] Set daily budget limits
[ ] Use Haiku for simple tasks
[ ] Optimize context windows
[ ] Enable response caching
[ ] Monitor with analytics daemon
[ ] Calculate ROI for workflows
[ ] Set up team quotas