Agent skill

Langfuse Cost Tuning

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Monitor and optimize LLM costs using Langfuse analytics and dashboards.

MITAuto-check passedAI & LLM Engineering

Install Langfuse Cost Tuning

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-cost-tuning -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace langfuse-cost-tuning --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/langfuse-cost-tuning .claude/skills/langfuse-cost-tuning && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
langfuse-cost-tuning
GitHub stars
2.8k
Token cost
~2.4k tokens
SKILL.md length
412 words
Files
2 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Monitor and optimize LLM costs using Langfuse analytics and dashboards.

  • Works in 4 steps: Ensure Token Usage is Captured → Query Costs via Metrics API → Implement Smart Model Routing → …
  • Tracking LLM spending
  • SKILL.md covers Overview, Prerequisites, How Langfuse Tracks Costs and Instructions, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Langfuse Cost Tuning is an agent skill from jeremylongshore/tons-of-skills-marketplace. 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".

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/implementation.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering LLM observability, LLM cost and token optimization and Budgeting and forecasting. It works with Langfuse and OpenAI. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Tracking LLM spending
  • Identifying cost anomalies
  • Implementing cost controls for AI applications
  • With phrases like langfuse costs

Example prompts

  • “langfuse costs”
  • “LLM spending”
  • “track AI costs”
  • “/langfuse-cost-tuning”

Requirements

  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. Ensure Token Usage is Captured
  2. Query Costs via Metrics API
  3. Implement Smart Model Routing
  4. Budget Alerts

What it can do on your machine

Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • langfuse.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Langfuse Cost Tuning loads about 2.4k tokens when it runs, and up to ~4.2k if it reads all its reference files. Until then it costs about 82 tokens; SKILL.md has 412 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~82
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~4.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 412 words, ~2,384 tokens.

Download SKILL.mdSave it as .claude/skills/langfuse-cost-tuning/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
langfuse-cost-tuning
description
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".
allowed-tools
Read, Write, Edit
compatibility
Designed for Claude Code
version
1.17.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, langfuse, monitoring, llm, analytics

Langfuse Cost Tuning

Overview

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.

Prerequisites

  • Langfuse tracing with token usage captured (via observeOpenAI or manual usage fields)
  • For Metrics API: @langfuse/client installed
  • Understanding of LLM pricing models

How Langfuse Tracks Costs

Langfuse 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.

Instructions

Step 1: Ensure Token Usage is Captured
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,
    });
  }
);
Step 2: Query Costs via Metrics API
typescript
import { 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);
Step 3: Implement Smart Model Routing

Route requests to cheaper models when appropriate:

typescript
import { 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;
  }
);
Step 4: Budget Alerts
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 Dashboard Features

Langfuse provides built-in cost analytics in the UI:

  • Cost Dashboard: Tracks token usage and costs over time by model, user, and session
  • Latency Dashboard: Response times across models and user segments
  • Custom Dashboards: Build custom views with multi-level aggregations
  • Pricing Tiers: Supports complex pricing (cached tokens, audio tokens, per-model tiers)

Cost Optimization Strategies

StrategySavingsEffortHow
Model downgrade50-95%LowRoute simple tasks to gpt-4o-mini
Prompt optimization10-30%LowRemove filler words, use structured prompts
Response caching20-80%MediumCache identical prompts with TTL
Batch processing50%MediumUse OpenAI Batch API for offline tasks
Token limits10-40%LowSet max_tokens on all calls
Show full SKILL.md (159 more words)Show less

Error Handling

IssueCauseSolution
Missing cost dataNo usage in generationEnsure usage is included with promptTokens/completionTokens
Wrong cost calculationModel name mismatchUse exact model ID (e.g., gpt-4o-2024-08-06)
Custom model no costNo pricing configuredAdd model pricing in Langfuse Settings > Model Definitions
Stale pricingModel prices changedUpdate model definitions periodically

Output

Produce a dated cost report showing total spend, calls, tokens, and cost by model, plus the selected budget threshold and any alert state. When routing changes, record the before/after model mix and quality guardrail used to ensure savings did not reduce acceptable output quality.

Examples

Run getCostReport(7) after a deployment, compare the report with the prior seven-day baseline, and investigate any model whose cost per request rises unexpectedly. For a simple classification path, route a sampled cohort to the lower-cost model and retain the quality evaluation result before making the route the default.

Resources

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in skills/.curated/langfuse-cost-tuning of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/implementation.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Langfuse Cost Tuning next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Langfuse Cost Tuning compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Langfuse Cost Tuning this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.4kAutomated safety check: PassMIT
Langfuse and LLM Gateway LogsKonghaYao/peri229—~4.3kAutomated safety check: NotesApache-2.0
Langfusedavila7/claude-code-templates33k5 repos~1.4kAutomated safety check: PassMIT
Langfusesickn33/agentic-awesome-skills47k2 repos~1.4kAutomated safety check: PassMIT
Sentry Instrumentgetsentry/sentry-for-ai268—~3.2kAutomated safety check: PassApache-2.0
AI Observabilityomer-metin/skills-for-antigravity163—~578Automated safety check: PassApache-2.0

Similar skills

  • Queries Langfuse traces, prompts, datasets and sessions, and analyzes local LLM gateway logs for requests, context growth, token use and cache hits.

    229 GitHub stars~4.3k tokensUpdated today
    AI & LLM EngineeringAuto-check: notes
  • Langfuse

    davila7/claude-code-templates

    Expert in Langfuse - the open-source LLM observability platform.

    33k GitHub starsUsed in 5 repos~1.4k tokens
    AI & LLM EngineeringAuto-check passed
  • Langfuse

    sickn33/agentic-awesome-skills

    Expert in Langfuse - the open-source LLM observability platform.

    47k GitHub starsUsed in 2 repos~1.4k tokens
    AI & LLM EngineeringAuto-check passed
  • Sentry Instrument

    getsentry/sentry-for-ai

    Official

    Instrument an application with Sentry — detect the platform, install and initialize the SDK if needed, and wire up any signal — error monitoring, tracing/performance, logging, metrics, profiling…

    268 GitHub stars~3.2k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • AI Observability

    omer-metin/skills-for-antigravity

    Implement comprehensive observability for LLM applications including tracing (Langfuse/Helicone), cost tracking, token optimization, RAG evaluation metrics (RAGAS), hallucination detection, and…

    163 GitHub stars~578 tokensUpdated 8 mo ago
    AI & LLM EngineeringAuto-check passed
  • Caveman Gateway Setup

    JuliusBrussee/caveman

    Routes every LLM call in a repository through the Caveman Cloud gateway in record mode, so requests and costs are measured without changing behavior.

    111k GitHub starsUsed in 1 repo~2.6k tokens
    DevOps & CloudAuto-check: warnings

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Works with

Questions about Langfuse Cost Tuning

What does Langfuse Cost Tuning do?

Monitor and optimize LLM costs using Langfuse analytics and dashboards. Langfuse Cost Tuning is an agent skill from jeremylongshore/tons-of-skills-marketplace. Monitor and optimize LLM costs using Langfuse analytics and dashboards.

When should I use Langfuse Cost Tuning?

Langfuse Cost Tuning fits situations like: tracking LLM spending; identifying cost anomalies; implementing cost controls for AI applications; with phrases like langfuse costs.

How do I install Langfuse Cost Tuning in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-cost-tuning -a claude-code`. Or copy the skill folder (skills/.curated/langfuse-cost-tuning in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/langfuse-cost-tuning in your project. Claude Code loads it when a task matches its description.

How do I install Langfuse Cost Tuning in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-cost-tuning -a codex`. Or copy the skill folder (skills/.curated/langfuse-cost-tuning in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/langfuse-cost-tuning in your project. Codex loads it when a task matches its description.

Can I use Langfuse Cost Tuning in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-cost-tuning -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/langfuse-cost-tuning, .gemini/skills/langfuse-cost-tuning, .github/skills/langfuse-cost-tuning and .opencode/skills/langfuse-cost-tuning in your project.

What does Langfuse Cost Tuning need to run?

SKILL.md names no scripts, command-line tools or credentials: Langfuse Cost Tuning is instructions for the agent only. Its frontmatter pre-approves these tools: Read, Write, Edit. Compatibility (from SKILL.md): Designed for Claude Code.

Does Langfuse Cost Tuning access the network?

SKILL.md names 1 domain. As links in the text: langfuse.com. This is read from the text; nothing was executed.

Is Langfuse Cost Tuning safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Langfuse Cost Tuning use?

Langfuse Cost Tuning is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Langfuse Cost Tuning use?

About 2.4k tokens (SKILL.md is roughly 9.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 1.8k tokens, read only when the agent opens those files.

What are the alternatives to Langfuse Cost Tuning?

Skills that share tags, products or a category with Langfuse Cost Tuning: Langfuse and LLM Gateway Logs (KonghaYao/peri, 229 stars), Langfuse (davila7/claude-code-templates, 33k stars), Langfuse (sickn33/agentic-awesome-skills, 47k stars) and Sentry Instrument (getsentry/sentry-for-ai, 268 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Langfuse Cost Tuning?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.