Generated banner for Exploring LLM Costs
Generated logo for Exploring LLM Costs

Exploring LLM Costs

PostHogOfficialPublished by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • No issues found

From the author

Investigate LLM spend in PostHog — total cost over time, cost by model, provider, user, trace, or custom dimension, token and cache-hit economics, and cost regressions. Use when the user asks "how much are we spending on LLMs?", "which model / user / feature is most expensive?", "why did cost spike?", wants to build a cost dashboard or alert, or pastes a trace URL and asks about its cost.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to investigating LLM costs within PostHog by leveraging per-call metadata attached to AI generation and embedding events. It enables users to perform granular cost analysis, including breakdowns by model, provider, user, or custom dimensions, as well as token and cache-hit economics. The skill includes workflows for debugging cost regressions, inspecting individual trace costs, and materializing findings into dashboards or alerts.

What it does

  • Aggregates total LLM spend over time using event metadata.
  • Provides SQL templates for breaking down costs by model, user, or custom properties.
  • Analyzes token usage and cache-hit economics to optimize spending.
  • Facilitates debugging of unexpected cost spikes or regressions.
  • Enables materialization of cost insights into saved dashboards and alerts.
  • Supports deep-dive inspection of individual trace costs.

When to use it

  • When you need to answer questions like 'How much are we spending on LLMs?'
  • When identifying which models, users, or features are driving the highest costs.
  • When investigating the root cause of a sudden spike in LLM expenditure.
  • When you need to build a recurring cost dashboard or set up cost-threshold alerts.
  • When a user provides a specific trace URL and requires a cost breakdown for that interaction.

Advantages

  • Uses authoritative per-call cost metadata for accurate reporting.
  • Provides standardized SQL recipes for consistent cost analysis.
  • Helps distinguish between different provider cache-reporting styles.
  • Reduces manual effort by offering pre-built patterns for common cost investigations.
  • Ensures cost data is correctly aggregated by including both generation and embedding events.

Usage examples

“How much are we spending on LLMs this month?”
The agent executes a SQL query summing the $ai_total_cost_usd property for all $ai_generation and $ai_embedding events within the last 30 days.
“Which user is our biggest LLM spender?”
The agent runs a breakdown query grouping by distinct_id and ordering by total cost to identify the top spenders.
“Why did our LLM costs spike yesterday?”
The agent follows the 5-step regression debugging playbook to check for changes in call volume, prompt size, model usage, or cache-hit rates.
“Can you show me the cost breakdown for this trace: [URL]?”
The agent uses the trace ID to fetch the specific event breakdown, surfacing which spans or models contributed most to the total cost.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/exploring-llm-costs/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip exploring-llm-costs.zip -d .agents/skills

Documentation by PostHog

Exploring LLM costs

PostHog attaches per-call cost metadata to every $ai_generation and $ai_embedding event at ingestion time. Every cost question reduces to an aggregation over those two event types — the interesting variation is only in how you group, filter, and compare.

This skill covers the common cost investigations: total spend, breakdowns (model, provider, user, trace, custom property), token and cache-hit analysis, regression debugging, and materializing results as insights, dashboards, or alerts.

Tools

ToolPurpose
posthog:query-trendsNative cost trends with supported sums, breakdowns, and comparisons
posthog:execute-sqlAd-hoc HogQL for any cost aggregation — the workhorse of this skill
posthog:query-llm-traces-listList traces with rolled-up cost, token, and error metrics
posthog:query-llm-traceCost breakdown of a single trace across all its events
posthog:read-data-schemaDiscover which custom properties exist for breakdowns
posthog:insight-createMaterialize a cost chart as a saved insight
posthog:dashboard-createBundle cost insights into a dashboard
posthog:alert-createAlert when cost crosses a threshold
posthog:generate-app-urlBuild region- and project-qualified links back to the UI

Core rules

Three rules cover most of what goes wrong:

  • Sum $ai_total_cost_usd for rollups, never the components. Components drop request and web-search fees. The UI's cost cells sum $ai_total_cost_usd over event IN ('$ai_generation', '$ai_embedding'); mirror that. Full schema and rationale in cost properties.

  • Always include both $ai_generation and $ai_embedding in cost queries unless the project demonstrably does not use embeddings — missing them silently under-counts. $ai_trace and $ai_span carry no rollup cost; some SDK wrappers duplicate $ai_total_cost_usd onto $ai_trace so don't include it in rollups or you'll double-count.

  • Always set a time range. Cost queries without one scan the full events table.

$ai_total_cost_usd is set at ingestion via one of three paths (passthrough, custom pricing, automatic lookup). When a cost looks wrong, read $ai_cost_model_source first — see cost sources for the precedence rules and a diagnostic query.

Cache-hit math depends on whether the provider reports cache tokens inclusively or exclusively of $ai_input_tokens. Always branch on the per-event $ai_cache_reporting_exclusive flag, never on provider name — see cache accounting for the exclusive-vs-inclusive formula.

distinct_id is the canonical user dimension. Customers often attach custom properties (feature, tenant_id, workflow_name) — discover them with posthog:read-data-schema before grouping. Don't guess names.

Workflow: total spend in a window

posthog:execute-sql
SELECT round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS total_cost_usd
FROM events
WHERE event IN ('$ai_generation', '$ai_embedding')
    AND timestamp >= now() - INTERVAL 30 DAY

Workflow: cost breakdowns

Every cost question is a variation of the same template — group by a dimension, aggregate $ai_total_cost_usd. See breakdown patterns for ready-to-run recipes:

  • Cost over time (daily)

  • Cost by model

  • Cost by user (top spenders)

  • Cost by trace (top expensive traces)

  • Cost by custom dimension

  • Cost-per-call distribution

  • Input vs output vs cache economics

Workflow: inspect a single trace's cost

When the user pastes a trace URL and asks about its cost, fetch the trace and surface the per-event breakdown:

posthog:query-llm-trace
{ "traceId": "<trace_id>", "dateRange": {"date_from": "-30d"} }

Sum $ai_total_cost_usd across the returned events, grouped by span name or model, to show which step(s) drove the cost. The trace response already includes totalCost as a convenience.

Workflow: debug a cost regression

"Our LLM bill jumped — why?" is almost always one of: more calls, bigger prompts, a new model, or a change in cache-hit rate. Work through them in order — see regression debugging for the 5-step playbook.

Workflow: materialize as an insight, dashboard, or alert

After ad-hoc queries answer the question, persist them as insights, bundle into a dashboard, or wire up alerts. See materializing for ready-to-run JSON for posthog:insight-create, posthog:dashboard-create, and posthog:alert-create.

Never hand-write https://app.posthog.com/... links. That host drops the region and the project prefix, so the user is redirected to login instead of the page you meant.

  • Prefer the canonical URL the tool returns. query-llm-traces-list and query-llm-trace return _posthogUrl — surface that value. For a single trace, append ?timestamp=<url_encoded_iso> (the trace's earliest event time) to that URL; the returned link carries no timestamp, and without one the trace page scans from a fixed early date instead of the ten-minute window around the trace.

  • Otherwise build the link with generate-app-url. It resolves the correct region host and /project/<id>/ prefix (e.g. https://us.posthog.com/project/2/ai-observability/traces). Pass concrete ids via params, never inline them into the path.

    • Dashboard: generate-app-url {url: "/ai-observability/dashboard"}

    • Traces list (sort by cost): generate-app-url {url: "/ai-observability/traces"}

    • Generations list: generate-app-url {url: "/ai-observability/generations"}

    • Users list (per-user cost): generate-app-url {url: "/ai-observability/users"}

    • Single trace: generate-app-url {url: "/ai-observability/traces/{id}", params: {id: "<trace_id>"}}

generate-app-url cannot express query params, so append the ?timestamp=<url_encoded_iso> described above to a single-trace link yourself.

Always surface a UI link so the user can verify visually.

Keeping this skill current

Provider reporting behavior (which tokens are inclusive vs exclusive, which costs show up where) shifts over time and can differ between SDK versions for the same provider. To avoid rot:

  • Branch on event-level flags ($ai_cache_reporting_exclusive, $ai_cost_model_source) rather than hardcoded provider or model names. When set, those flags are ingestion's resolved answer for the specific event. $ai_cache_reporting_exclusive is often missing; see cache accounting for the fallback.

  • $ai_total_cost_usd is always authoritative for rollups — prefer it over summing components, which can drift as new cost categories are added.

  • For anything not covered here (new cost categories, changes to pricing lookup, provider additions), run posthog:docs-search for "calculating costs" or "AI observability" first rather than trusting a hardcoded rule in this file.

  • If you find this skill contradicting the UI, trust the UI and flag the skill for an update.

Tips

  • Always set a time range — cost queries without one scan the full events table

  • Token, cost, model, and $ai_trace_id properties are on events — but message content ($ai_input / $ai_output_choices) lives only on the posthog.ai_events table; load the exploring-llm-traces skill if you need content alongside cost

  • Always include $ai_embedding alongside $ai_generation when summing cost; embeddings are cheap per-call but add up at scale

  • Costs are written at ingestion (see Calculating LLM costs) — if $ai_total_cost_usd is missing or zero, read $ai_cost_model_source first: passthrough means the SDK supplied costs; custom means custom token prices; openrouter / manual mean automatic lookup; missing means the model wasn't matched (unusual custom model, fine-tune). Grep: countIf(properties.$ai_total_cost_usd IS NULL) per (model, source)

  • Custom pricing uses per-token prices, not per-million — if a custom-priced model looks ~1M× too expensive or too cheap, that's almost always the bug

  • Exclude errored calls from cost totals only when explicitly asked — providers still charge for many error modes, and including them gives the truthful bill

  • For per-user totals, exclude rows where distinct_id = properties.$ai_trace_id — some SDKs default distinct_id to the trace ID when no user is set

  • Cost is additive across $ai_generation + $ai_embedding events within a trace; summing on $ai_span gives zero. $ai_trace may carry $ai_total_cost_usd from some SDK wrappers — don't include it in rollups or you'll double-count. $ai_evaluation events also carry cost but are not part of the stock UI rollups; include them only when the user explicitly wants evaluation spend in the total

  • Cache-hit rate depends on $ai_cache_reporting_exclusive — resolve it per event, never per group. Most events with a precomputed cost carry no flag, so never default a missing flag to inclusive; use the fallback in cache accounting

  • When answering "why is X expensive?", show the cost and the token split — the user almost always wants to know whether to shrink prompts, shrink outputs, or switch models

  • Before building a custom dashboard, check whether the stock /ai-observability/dashboard tiles already answer the question — re-creating them is churn

  • For large tenants, materialize common cost queries as insights and reuse via insight-query; ad-hoc SQL is fine for one-offs but re-running it on every dashboard load is expensive

References

  • analyzing-expensive-users — who drives the spend, and whether their usage pattern explains it

  • exploring-llm-traces — inspect the expensive traces the breakdowns point at

Files

references/regression-debugging.md

Debugging a cost regression

"Our LLM bill jumped — why?" is almost always one of: more calls, bigger prompts, a new model, or a change in cache-hit rate. Work through them in order.

Step 1 — Confirm and scope the regression

posthog:execute-sql
SELECT
    toDate(timestamp) AS day,
    round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS cost_usd,
    count() AS calls,
    round(sum(toFloat(properties.$ai_total_cost_usd)) / count(), 6) AS avg_cost_per_call
FROM events
WHERE event IN ('$ai_generation', '$ai_embedding')
    AND timestamp >= now() - INTERVAL 60 DAY
GROUP BY day
ORDER BY day

Compare calls vs avg_cost_per_call before and after the jump. If calls doubled, it's volume; if cost-per-call rose, it's prompt size, model, or cache.

Step 2 — Look for a model mix shift

posthog:execute-sql
SELECT
    toDate(timestamp) AS day,
    properties.$ai_model AS model,
    count() AS calls,
    round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS cost_usd,
    round(avg(toFloat(properties.$ai_total_cost_usd)), 6) AS avg_cost_per_call
FROM events
WHERE event IN ('$ai_generation', '$ai_embedding')
    AND timestamp >= now() - INTERVAL 60 DAY
GROUP BY day, model
ORDER BY day, model

A model appearing or disappearing around the jump is a strong signal. So is a model taking a bigger share of calls or cost_usd after it, even when its own avg_cost_per_call held steady.

Step 3 — Look for prompt bloat

posthog:execute-sql
SELECT
    toDate(timestamp) AS day,
    properties.$ai_model AS model,
    round(avg(toInt(properties.$ai_input_tokens)), 1) AS avg_input_tokens,
    round(avg(toInt(properties.$ai_output_tokens)), 1) AS avg_output_tokens
FROM events
WHERE event = '$ai_generation'
    AND timestamp >= now() - INTERVAL 30 DAY
GROUP BY day, model
ORDER BY day, model

Step 4 — Look for cache degradation

posthog:execute-sql
SELECT
    day,
    model,
    round(sum(cache_read) / nullIf(sum(if(exclusive, input + cache_read + cache_write, input)), 0), 3) AS cache_hit_rate,
    sum(input) AS input_tokens,
    sum(cache_read) AS cache_read_tokens,
    countIf(flag_missing) AS calls_with_inferred_flag,
    count() AS calls
FROM (
    SELECT
        toDate(timestamp) AS day,
        properties.$ai_model AS model,
        ifNull(toInt(properties.$ai_input_tokens), 0) AS input,
        ifNull(toInt(properties.$ai_cache_read_input_tokens), 0) AS cache_read,
        ifNull(toInt(properties.$ai_cache_creation_input_tokens), 0) AS cache_write,
        lower(ifNull(properties.$ai_provider, '')) AS provider,
        properties.$ai_cache_reporting_exclusive IS NULL AS flag_missing,
        (provider = 'anthropic'
            OR positionCaseInsensitive(ifNull(properties.$ai_model, ''), 'anthropic') > 0
            OR startsWith(lower(ifNull(properties.$ai_model, '')), 'claude'))
            AND NOT (provider = 'gateway' AND lower(ifNull(properties.$ai_framework, '')) = 'vercel') AS anthropic_style,
        if(flag_missing, anthropic_style, toString(properties.$ai_cache_reporting_exclusive) = 'true')
            OR input < cache_read + cache_write AS exclusive
    FROM events
    WHERE event = '$ai_generation'
        AND timestamp >= now() - INTERVAL 30 DAY
)
GROUP BY day, model
ORDER BY day, model

A drop often follows a system-prompt change that invalidated the cached prefix. The rate resolves the reporting style per event; see cache accounting for why, and for how to read calls_with_inferred_flag.

Step 5 — Isolate the feature

Once you've identified the mechanism (more calls / bigger prompts / new model / worse cache), group by the custom property that separates features (e.g. feature, workflow_name) to find which surface is responsible. Then drill into a representative trace via posthog:query-llm-trace.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/omnibus/exploring-llm-costs · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download exploring-llm-costs.zip