Track per-request costs across Claude Opus 4.7, Sonnet 4.6, and Haiku 4.5. Attribute spend by developer and feature.
npm install costlens @anthropic-ai/sdkWrap your Anthropic client for automatic tracking and cost optimization:
import { CostLens } from 'costlens';
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const costlens = new CostLens({
apiKey: process.env.COSTLENS_API_KEY,
smartRouting: true
});
const tracked = costlens.wrapAnthropic(anthropic);
const result = await tracked.messages.create({
model: 'claude-sonnet-4.6',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Summarize this document' }]
});CostLens classifies prompt complexity and routes to the cheapest adequate model:
| Task | Routing |
|---|---|
| Simple (fix typo, explain concept) | Sonnet → Haiku |
| Medium (code generation, multi-step) | Stays on Sonnet |
| Complex (architecture, multi-file) | No routing — quality preserved |
Attribute costs to features or users:
await costlens.trackAnthropic(
params,
result,
Date.now() - start,
'content-generation-v1' // promptId
);const costlens = new CostLens({
apiKey: process.env.COSTLENS_API_KEY,
enableCache: true
});
const tracked = costlens.wrapAnthropic(anthropic);
const result = await tracked.messages.create(
{ model: 'claude-sonnet-4.6', max_tokens: 1024, messages: [...] },
{ cacheTTL: 3600000 }
);const start = Date.now();
try {
const result = await anthropic.messages.create(params);
await costlens.trackAnthropic(params, result, Date.now() - start);
return result;
} catch (error) {
await costlens.trackError(
'anthropic', params.model,
JSON.stringify(params.messages),
error, Date.now() - start
);
throw error;
}| Model | Input | Output |
|---|---|---|
| Claude Sonnet 4.6 | $3/1M | $15/1M |
| Claude Haiku 4.5 | $1/1M | $4/1M |
| Claude Opus 4.7 | $5/1M | $25/1M |