AiCredits
LLM FinOps

Cost Monitoring Dashboards for LLM APIs: Track Spend per Feature

Build a practical per-feature cost monitoring dashboard for LLM APIs: log token usage, attribute spend, and catch runaway features before the invoice arrives.

Published 2026-10-30 Updated 2026-10-30 9 min

Your invoice is a lagging indicator

Most LLM spend problems do not start with a huge bill. They start with a small feature quietly making an extra call per request, a retry loop that never trips an alert, or a temporary switch to the stronger model that ships to production. A provider invoice shows the total after the fact and cannot tell you which product surface caused it.

If several features share one API key, every request looks the same at the account level. The fix is not a more detailed invoice; it is attribution at the call site. Add a feature key to every request, log token usage, and build a dashboard that answers three questions: what spent money yesterday, which feature is trending up, and which model tier is responsible.

The minimum useful schema

You do not need a data warehouse to start. One table with one row per model call is enough to expose the patterns that matter. Include the fields that let you slice by product surface, model, and failure mode.

  • feature: a stable key such as summary, support-reply, or code-review. Never use free-text prompt labels.

  • model: the exact string, deepseek-v4-flash or deepseek-v4-pro, so tier changes are visible.

  • prompt_tokens, completion_tokens, total_tokens: read these from the response usage object. Do not estimate from character count.

  • status and error: failed calls can still consume tokens if the request reached the provider. Log retries too.

  • latency_ms: helps separate slow-and-expensive from slow-but-cheap.

  • rate_card_version: keeps historical rows stable when rates change.

  • Optional tenant_id, user_id, and prompt_prefix_hash: useful for per-customer reporting and spotting repeated context.

DimensionWhy it belongs in the dashboard
FeatureShows which product surface to optimize, cap, or route differently.
ModelSeparates flash volume from pro volume; pro costs more than flash.
Day and hourExposes peak vs off-peak patterns and batch jobs that can move.
Status and retriesFailed and retried calls can spend tokens without producing user value.
Rate-card versionKeeps spend history comparable when pricing changes.

Instrument once, at the feature boundary

The worst place to add tracking is a generic HTTP wrapper every service imports. It can see the request, but not why it happened. Pass a feature name explicitly from the product code. The snippet below writes one row per call to SQLite and works with the OpenAI SDK against AiCredits. Set AICREDITS_API_KEY first.

import os
import sqlite3
import time
import uuid

from openai import OpenAI

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)
DB_PATH = os.environ.get('LLM_DB', 'llm_spend.db')


def init_db():
    con = sqlite3.connect(DB_PATH)
    con.execute('''
        CREATE TABLE IF NOT EXISTS calls (
            id TEXT PRIMARY KEY,
            ts INTEGER NOT NULL,
            feature TEXT NOT NULL,
            model TEXT NOT NULL,
            prompt_tokens INTEGER NOT NULL,
            completion_tokens INTEGER NOT NULL,
            total_tokens INTEGER NOT NULL,
            latency_ms INTEGER NOT NULL,
            status TEXT NOT NULL,
            error TEXT
        )
    ''')
    con.execute('CREATE INDEX IF NOT EXISTS idx_calls_feature_ts ON calls(feature, ts)')
    con.commit()
    con.close()


def _log(row):
    con = sqlite3.connect(DB_PATH)
    con.execute('''
        INSERT INTO calls
        (id, ts, feature, model, prompt_tokens, completion_tokens, total_tokens, latency_ms, status, error)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ''', row)
    con.commit()
    con.close()


def tracked_chat(feature: str, prompt: str, model: str = 'deepseek-v4-flash') -> str:
    call_id = str(uuid.uuid4())
    started = time.time()
    try:
        resp = client.chat.completions.create(
            model=model,
            messages=[{'role': 'user', 'content': prompt}],
            temperature=0.2,
        )
        usage = resp.usage
        pt = usage.prompt_tokens if usage else 0
        ct = usage.completion_tokens if usage else 0
        tt = usage.total_tokens if usage and usage.total_tokens is not None else pt + ct
        _log((
            call_id, int(time.time()), feature, model, pt, ct, tt,
            int((time.time() - started) * 1000), 'ok', None,
        ))
        return resp.choices[0].message.content
    except Exception as exc:
        _log((
            call_id, int(time.time()), feature, model, 0, 0, 0,
            int((time.time() - started) * 1000), 'error', str(exc)[:500],
        ))
        raise


if __name__ == '__main__':
    init_db()
    print(tracked_chat('summarizer', 'Summarize this support thread in one sentence.'))

Convert tokens to spend without freezing today's rates

Store tokens, not only dollar amounts. Rates change, off-peak pricing applies, cache hits are cheaper, and pro costs more than flash. If you write a rate into every row, you lose the ability to ask what this month would cost under current rates. Keep a rate-card version and recompute spend from tokens.

Load current per-token rates from aicreditsapi.com/pricing into environment variables or a small config table. Do not paste rates into application code. The dashboard below groups by feature and model and uses the rate variables you provide.

import os
import sqlite3
import time

import pandas as pd
import streamlit as st

DB_PATH = os.environ.get('LLM_DB', 'llm_spend.db')

# Rates are per token. Set these from the current pricing page.
RATES = {
    'deepseek-v4-flash': (
        float(os.environ.get('FLASH_INPUT_RATE', '0')),
        float(os.environ.get('FLASH_OUTPUT_RATE', '0')),
    ),
    'deepseek-v4-pro': (
        float(os.environ.get('PRO_INPUT_RATE', '0')),
        float(os.environ.get('PRO_OUTPUT_RATE', '0')),
    ),
}

st.set_page_config(page_title='LLM Spend by Feature', layout='wide')
days = st.sidebar.slider('Lookback (days)', 1, 90, 7)

con = sqlite3.connect(DB_PATH)
df = pd.read_sql_query(
    '''
    SELECT feature, model, prompt_tokens, completion_tokens, total_tokens, status
    FROM calls
    WHERE ts >= ?
    ''',
    con,
    params=(int(time.time()) - days * 86400,),
)
con.close()

if df.empty:
    st.warning('No calls logged yet. Run one tracked_chat() call first.')
    st.stop()


def row_cost(row):
    input_rate, output_rate = RATES.get(row['model'], (0.0, 0.0))
    return row['prompt_tokens'] * input_rate + row['completion_tokens'] * output_rate


df['spend'] = df.apply(row_cost, axis=1)
by_feature = (
    df.groupby('feature', as_index=False)
    .agg(calls=('feature', 'count'), tokens=('total_tokens', 'sum'), spend=('spend', 'sum'))
    .sort_values('spend', ascending=False)
)

total = by_feature['spend'].sum()
st.metric('Total spend at configured rates', f'{total:,.2f}')
st.bar_chart(by_feature.set_index('feature')['spend'])
st.dataframe(by_feature, use_container_width=True)

errors = df[df['status'] == 'error'].groupby('feature').size()
if not errors.empty:
    st.subheader('Error calls by feature')
    st.dataframe(errors.rename('errors'), use_container_width=True)

What to do once the dashboard works

  • Set token budgets per feature, not just an account budget. One shared cap lets a noisy feature starve every other feature.

  • Alert on week-over-week token growth and error-rate spikes. Retries are silent spend.

  • Route by value: use deepseek-v4-flash for classification, extraction, and summaries; reserve deepseek-v4-pro for tasks that genuinely need the stronger model. Track pro features separately.

  • Move offline jobs into off-peak windows. Off-peak costs less, and batch work is usually the easiest demand to shift.

  • Add a feature owner to the schema. A dashboard without an owner becomes a museum exhibit.

If a feature cannot be named in your logs, it cannot be budgeted.

Platform dashboards vs your dashboard

AiCredits account billing shows what you bought and when. It cannot know that support-reply is most of your spend. That is not a shortcoming; it is the boundary of the data. Provider and reseller dashboards see keys, models, and time. Your application sees features, tenants, and product outcomes. You need both.

If your team is outside China and does not want to deal with a Chinese phone number or bank account, buying DeepSeek credits through AiCredits with a card or PayPal removes one billing headache. It does not remove the need for per-feature instrumentation. Keep the feature key in your own logs, and use the platform invoice as the reconciliation source.

FAQ

Should I log cost or tokens?

Log tokens and the exact model. Compute spend later with a versioned rate card. Rates change, off-peak pricing applies, and cache hits are cheaper, so baking a fixed amount into every row makes history harder to compare.

How do I attribute shared context to one feature?

Pass a stable feature key from the product layer. If several features share a prompt template, add a sub-feature or prompt-version column instead of guessing from the text.

How should I handle deepseek-v4-pro?

Track it as a separate model dimension and give it its own budget. Pro costs more than flash, so a small number of pro calls can dominate spend. Route only tasks that need the stronger model.

Can I use this with another gateway?

Yes. The schema is gateway-agnostic. Change the base URL and keep the same logging. You may lose provider-specific cache fields if the gateway does not expose them.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×