Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Monitor and optimize LLM costs using Langfuse analytics and dashboards. Use when tracking LLM spending, identifying cost anomalies, or implementing cost controls for AI applications. Trigger with phrases like "langfuse costs", "LLM spending", "track AI costs", "langfuse token usage", "optimize LLM budget".
.claude/skills/jeremylongshore-langfuse-cost-tuning/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-11 | ✗→✓ | ▲ Improved | 10% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 52% | 0% |
| case-04 | ✗→✓ | ▲ Improved | 17% | 0% |
| case-07 | ✗→✓ | ▲ Improved | 19% | 0% |
| case-08 | ✗→✓ | ▲ Improved | 15% | 0% |
Track, analyze, and optimize LLM costs using Langfuse's built-in token/cost tracking, the Metrics API for programmatic cost analysis, model routing for cost reduction, and automated budget alerts.
observeOpenAI or manual usage fields)@langfuse/client installedLangfuse automatically calculates costs for supported models (OpenAI, Anthropic, Google) when token usage is captured. For custom models, you can configure pricing in the Langfuse UI under Settings > Model Definitions.
Cost tracking works on observations of type generation and embedding. The observeOpenAI wrapper captures usage automatically; for manual tracing, include usage in your observation updates.
typescript// Automatic: observeOpenAI captures everything import { observeOpenAI } from "@langfuse/openai"; const openai = observeOpenAI(new OpenAI()); // Tokens, model, latency, and cost are all auto-tracked // Manual: include usage in generation observations import { startActiveObservation, updateActiveObservation } from "@langfuse/tracing"; await startActiveObservation( { name: "llm-call", asType: "generation" }, async () => { updateActiveObservation({ model: "gpt-4o" }); // Model required for cost calc const response = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: prompt }], }); updateActiveObservation({ output: response.choices[0].message.content, usage: { promptTokens: response.usage?.prompt_tokens, completionTokens: response.usage?.completion_tokens, totalTokens: response.usage?.total_tokens, }, // Optional: override inferred cost (in USD) // costInUsd: 0.0015, }); } );
typescriptimport { LangfuseClient } from "@langfuse/client"; const langfuse = new LangfuseClient(); // Fetch aggregated cost metrics async function getCostReport(days: number) { const fromTimestamp = new Date(Date.now() - days * 86400000).toISOString(); // Use the API to list traces with cost data const traces = await langfuse.api.traces.list({ fromTimestamp, limit: 1000, orderBy: "timestamp", }); const costByModel = new Map<string, { cost: number; tokens: number; count: number }>(); for (const trace of traces.data) { const observations = await langfuse.api.observations.list({ traceId: trace.id, type: "GENERATION", }); for (const obs of observations.data) { const model = obs.model || "unknown"; const existing = costByModel.get(model) || { cost: 0, tokens: 0, count: 0 }; existing.cost += obs.calculatedTotalCost || 0; existing.tokens += obs.totalTokens || 0; existing.count += 1; costByModel.set(model, existing); } } console.log("\n=== LLM Cost Report ==="); console.log(`Period: Last ${days} days\n`); let totalCost = 0; for (const [model, data] of costByModel.entries()) { console.log(`${model}:`); console.log(` Calls: ${data.count}`); console.log(` Tokens: ${data.tokens.toLocaleString()}`); console.log(` Cost: $${data.cost.toFixed(4)}`); totalCost += data.cost; } console.log(`\nTotal: $${totalCost.toFixed(4)}`); } getCostReport(7);
Route requests to cheaper models when appropriate:
typescriptimport { observe, updateActiveObservation } from "@langfuse/tracing"; interface ModelConfig { model: string; costPer1MInput: number; costPer1MOutput: number; maxComplexity: "simple" | "moderate" | "complex"; } const MODELS: ModelConfig[] = [ { model: "gpt-4o-mini", costPer1MInput: 0.15, costPer1MOutput: 0.60, maxComplexity: "simple" }, { model: "gpt-4o", costPer1MInput: 2.50, costPer1MOutput: 10.00, maxComplexity: "moderate" }, { model: "claude-sonnet-4-20250514", costPer1MInput: 3.00, costPer1MOutput: 15.00, maxComplexity: "complex" }, ]; function selectModel(task: string, inputLength: number): ModelConfig { const simpleTasks = ["classify", "extract", "summarize-short", "translate"]; const isSimple = simpleTasks.some((t) => task.includes(t)); const isShort = inputLength < 500; if (isSimple && isShort) return MODELS[0]; // gpt-4o-mini if (isSimple || inputLength < 2000) return MODELS[1]; // gpt-4o return MODELS[2]; // claude-sonnet-4 } const costOptimizedLLM = observe( { name: "cost-optimized-llm", asType: "generation" }, async (task: string, input: string) => { const config = selectModel(task, input.length); updateActiveObservation({ model: config.model, metadata: { task, selectedReason: `${config.maxComplexity} tier`, estimatedCostPer1M: config.costPer1MInput, }, }); const response = await callModel(config.model, input); updateActiveObservation({ output: response.content, usage: response.usage, }); return response; } );
typescript// scripts/cost-alert.ts -- run as cron job import { LangfuseClient } from "@langfuse/client"; const langfuse = new LangfuseClient(); const ALERT_THRESHOLDS = { dailyWarn: 50, // $50/day warning dailyCritical: 200, // $200/day critical perRequestWarn: 1, // $1/request warning }; async function checkCostAlerts() { const since = new Date(Date.now() - 86400000).toISOString(); // Last 24h const traces = await langfuse.api.traces.list({ fromTimestamp: since, limit: 500, }); let dailyCost = 0; let maxRequestCost = 0; for (const trace of traces.data) { const observations = await langfuse.api.observations.list({ traceId: trace.id, type: "GENERATION", }); const traceCost = observations.data.reduce( (sum, obs) => sum + (obs.calculatedTotalCost || 0), 0 ); dailyCost += traceCost; maxRequestCost = Math.max(maxRequestCost, traceCost); } console.log(`Daily cost: $${dailyCost.toFixed(2)}`); console.log(`Max request cost: $${maxRequestCost.toFixed(4)}`); if (dailyCost > ALERT_THRESHOLDS.dailyCritical) { await sendAlert("CRITICAL", `Daily LLM cost: $${dailyCost.toFixed(2)}`); } else if (dailyCost > ALERT_THRESHOLDS.dailyWarn) { await sendAlert("WARNING", `Daily LLM cost: $${dailyCost.toFixed(2)}`); } } checkCostAlerts();
Langfuse provides built-in cost analytics in the UI:
| Strategy | Savings | Effort | How | |----------|---------|--------|-----| | Model downgrade | 50-95% | Low | Route simple tasks to gpt-4o-mini | | Prompt optimization | 10-30% | Low | Remove filler words, use structured prompts | | Response caching | 20-80% | Medium | Cache identical prompts with TTL | | Batch processing | 50% | Medium | Use OpenAI Batch API for offline tasks | | Token limits | 10-40% | Low | Set max_tokens on all calls |
| Issue | Cause | Solution | |-------|-------|----------| | Missing cost data | No usage in generation | Ensure usage is included with promptTokens/completionTokens | | Wrong cost calculation | Model name mismatch | Use exact model ID (e.g., gpt-4o-2024-08-06) | | Custom model no cost | No pricing configured | Add model pricing in Langfuse Settings > Model Definitions | | Stale pricing | Model prices changed | Update model definitions periodically |
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-10 | pass→pass | 15,399 | 9,405 | -39% | 1 | 1 | 0% | 1,455 | 2,891 | +99% | 0 | 0 | — |
case-11 | fail→pass | 21,527 | 9,980 | -54% | 1 | 1 | 0% | 2,975 | 3,268 | +10% | 0 | 0 | — |
case-01 | fail→fail | 37,077 | 27,229 | -27% | 1 | 1 | 0% | 4,598 | 5,964 | +30% | 0 | 0 | — |
case-02 | fail→pass | 21,514 | 15,749 | -27% | 1 | 1 | 0% | 2,622 | 3,997 | +52% | 0 | 0 | — |
case-03 | fail→fail | 26,109 | 21,390 | -18% | 1 | 1 | 0% | 3,354 | 5,798 | +73% | 0 | 0 | — |
case-04 | fail→pass | 21,321 | 7,997 | -62% | 1 | 1 | 0% | 2,461 | 2,883 | +17% | 0 | 0 | — |
case-05 | pass→pass | 14,093 | 11,340 | -20% | 1 | 1 | 0% | 1,674 | 3,622 | +116% | 0 | 0 | — |
case-06 | pass→pass | 17,847 | 8,896 | -50% | 1 | 1 | 0% | 2,151 | 2,923 | +36% | 0 | 0 | — |
case-07 | fail→pass | 38,268 | 11,551 | -70% | 1 | 1 | 0% | 3,093 | 3,690 | +19% | 0 | 0 | — |
case-08 | fail→pass | 19,603 | 7,615 | -61% | 1 | 1 | 0% | 2,456 | 2,814 | +15% | 0 | 0 | — |
case-09 | fail→pass | 32,286 | 9,310 | -71% | 1 | 1 | 0% | 1,713 | 2,876 | +68% | 0 | 0 | — |
case-12 | pass→pass | 17,030 | 8,039 | -53% | 1 | 1 | 0% | 2,042 | 3,459 | +69% | 0 | 0 | — |
case-13 | pass→pass | 13,317 | 8,301 | -38% | 1 | 1 | 0% | 1,782 | 2,683 | +51% | 0 | 0 | — |
case-14 | pass→pass | 20,850 | 11,290 | -46% | 1 | 1 | 0% | 2,688 | 3,591 | +34% | 0 | 0 | — |
case-15 | pass→pass | 18,189 | 15,900 | -13% | 1 | 1 | 0% | 2,362 | 3,993 | +69% | 0 | 0 | — |
case-16 | pass→pass | 10,627 | 3,490 | -67% | 1 | 1 | 0% | 687 | 2,760 | +302% | 0 | 0 | — |
case-17 | fail→pass | 7,810 | 8,387 | +7% | 1 | 1 | 0% | 1,403 | 2,923 | +108% | 0 | 0 | — |
case-18 | fail→pass | 15,667 | 3,165 | -80% | 1 | 1 | 0% | 2,051 | 2,849 | +39% | 0 | 0 | — |
case-19 | fail→pass | 18,649 | 7,694 | -59% | 1 | 1 | 0% | 2,439 | 2,737 | +12% | 0 | 0 | — |
case-20 | pass→pass | 16,263 | 3,902 | -76% | 1 | 1 | 0% | 1,531 | 3,072 | +101% | 0 | 0 | — |
case-21 | pass→pass | 16,675 | 11,506 | -31% | 1 | 1 | 0% | 2,209 | 4,690 | +112% | 0 | 0 | — |
case-22 | pass→pass | 17,992 | 15,257 | -15% | 1 | 1 | 0% | 2,554 | 4,360 | +71% | 0 | 0 | — |
case-23 | pass→pass | 15,099 | 18,678 | +24% | 1 | 1 | 0% | 2,862 | 6,041 | +111% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +39 percentage points is the difference between those two pass rates over the 23 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.