Build an LLM Cost & Latency Tracker with Python

Many teams discover issues with their LLM applications only after users report slow performance or unexpected costs appear, often without sufficient data to investigate. The solution is to record every request and analyze the results. In this tutorial, you’ll build an LLM cost and latency tracker that logs tokens, latency, cost, and status for each call, along with a dashboard for analysis.

All components run locally using Ollama, SQLite, and Streamlit, so you will not need paid APIs or external tools.

LLM Cost & Latency Tracker with Python

The project has two files:

  1. track.py calls the model and logs each request to SQLite.
  2. dashboard.py reads the database and displays it in Streamlit.

Your application writes data while the dashboard only reads it, allowing you to modify either component independently.

Step 1: Set Up Your Environment

Install Ollama, download a small model, and install the required Python packages:

ollama pull llama3.2
pip install requests pandas streamlit

SQLite is included with Python, so no additional installation is required.

Step 2: Create the Database

Identify the information you will need later and ensure it is stored now. Create track.py, beginning with the necessary imports, constants, and a table where each request is represented by one row:

import sqlite3
import time
from datetime import datetime

import requests


DB_NAME = "llm_metrics.db"
OLLAMA_URL = "http://localhost:11434/api/generate"


# Database

def init_db():
    conn = sqlite3.connect(DB_NAME)

    conn.execute("""
        CREATE TABLE IF NOT EXISTS llm_requests (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT,
            model TEXT,
            prompt_tokens INTEGER,
            completion_tokens INTEGER,
            total_tokens INTEGER,
            latency_ms REAL,
            cost REAL,
            prompt TEXT,
            response TEXT,
            status TEXT
        )
    """)

    conn.commit()
    conn.close()

Storing the prompt and response alongside the metrics is important. When you encounter a slow or costly call, you can review the exact cause.

Step 3: Calculate Cost Per Request

Providers price input and output tokens separately, usually per million tokens. A small rate table handles that:

# Model Pricing

# Ollama runs locally, so there is no API cost.
# You can add pricing for other models later.

MODEL_RATES = {
    "llama3.2": {
        "input": 0.0,
        "output": 0.0
    }
}


def calculate_cost(model, prompt_tokens, completion_tokens):

    rates = MODEL_RATES.get(
        model,
        {
            "input": 0.0,
            "output": 0.0
        }
    )

    input_cost = (
        prompt_tokens / 1_000_000
    ) * rates["input"]

    output_cost = (
        completion_tokens / 1_000_000
    ) * rates["output"]

    return input_cost + output_cost

The cost is zero in this example because Ollama runs locally. The structure is valuable for future use. When you transition to a hosted model, you can add its rates, and all charts will reflect actual spending. Unknown models default to zero cost rather than causing errors.

Step 4: Call the Model and Measure Latency

This function starts a timer, calls Ollama, and reads the token counts from the response:

# Call Ollama

def call_llm(prompt, model="llama3.2"):

    start_time = time.perf_counter()

    try:

        response = requests.post(
            OLLAMA_URL,
            json={
                "model": model,
                "prompt": prompt,
                "stream": False
            },
            timeout=120
        )

        latency_ms = (
            time.perf_counter() - start_time
        ) * 1000

        response.raise_for_status()

        data = response.json()

        return {
            "response": data.get("response", ""),
            "prompt_tokens": data.get(
                "prompt_eval_count",
                0
            ),
            "completion_tokens": data.get(
                "eval_count",
                0
            ),
            "latency_ms": latency_ms,
            "status": "success"
        }

    except requests.exceptions.RequestException as e:

        latency_ms = (
            time.perf_counter() - start_time
        ) * 1000

        return {
            "response": str(e),
            "prompt_tokens": 0,
            "completion_tokens": 0,
            "latency_ms": latency_ms,
            "status": "error"
        }

Two details are important for your own projects: perf_counter is the appropriate tool for measuring durations, and failures should be logged with an error status. Tracking only successful requests can obscure reliability issues.

Step 5: Log Every Request

Next, save each result. Total tokens and cost are calculated here, and the insert statement uses placeholders instead of string formatting. This approach prevents errors from prompts containing strings:

# Save Request

def log_request(model, prompt, result):

    total_tokens = (
        result["prompt_tokens"]
        + result["completion_tokens"]
    )

    cost = calculate_cost(
        model,
        result["prompt_tokens"],
        result["completion_tokens"]
    )

    conn = sqlite3.connect(DB_NAME)

    conn.execute("""
        INSERT INTO llm_requests (
            timestamp,
            model,
            prompt_tokens,
            completion_tokens,
            total_tokens,
            latency_ms,
            cost,
            prompt,
            response,
            status
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        datetime.now().isoformat(),
        model,
        result["prompt_tokens"],
        result["completion_tokens"],
        total_tokens,
        result["latency_ms"],
        cost,
        prompt,
        result["response"],
        result["status"]
    ))

    conn.commit()
    conn.close()


# Run LLM Request

def run_request(
    prompt,
    model="llama3.2"
):

    result = call_llm(
        prompt,
        model
    )

    log_request(
        model,
        prompt,
        result
    )

    return result

Your application should call the run_request function, which handles both making the request and logging it in a single step.

Preparing for AI/ML Interviews?
If you are building practical AI projects, it is also important to prepare to explain your systems in interviews. Cracking Your First AI/ML Interview is a recommended resource for those preparing for their first AI or machine learning interview.

Step 6: Load Metrics and Run the Tracker

The final section of track.py includes a helper function to load the table into pandas and a main block that can be executed from the terminal:

# Load Metrics

def load_metrics():

    conn = sqlite3.connect(DB_NAME)

    cursor = conn.execute("""
        SELECT name
        FROM sqlite_master
        WHERE type='table'
        AND name='llm_requests'
    """)

    table_exists = cursor.fetchone()

    if not table_exists:
        conn.close()
        return None

    import pandas as pd

    df = pd.read_sql_query(
        "SELECT * FROM llm_requests",
        conn
    )

    conn.close()

    return df


# Main

if __name__ == "__main__":

    # Create database and table
    init_db()

    print("LLM Cost & Latency Tracker")
    print("-" * 40)

    prompt = input(
        "\nEnter your prompt: "
    )

    print("\nCalling Ollama...")

    result = run_request(
        prompt=prompt,
        model="llama3.2"
    )

    print("\nResponse:")
    print(result["response"])

    print("\nMetrics:")
    print(
        f"Prompt tokens: "
        f"{result['prompt_tokens']}"
    )

    print(
        f"Completion tokens: "
        f"{result['completion_tokens']}"
    )

    total_tokens = (
        result["prompt_tokens"]
        + result["completion_tokens"]
    )

    print(
        f"Total tokens: "
        f"{total_tokens}"
    )

    print(
        f"Latency: "
        f"{result['latency_ms']:.2f} ms"
    )

    cost = calculate_cost(
        "llama3.2",
        result["prompt_tokens"],
        result["completion_tokens"]
    )

    print(
        f"Cost: ${cost:.6f}"
    )

    print(
        f"Status: {result['status']}"
    )

Run python track.py several times with both short and long prompts to ensure the dashboard has data to display.

Step 7: Create the Dashboard

Next, create dashboard.py. It sets up the page, loads the data, and exits gracefully if the database is missing or empty. Streamlit’s cache prevents unnecessary re-queries on each interaction:

import sqlite3

import pandas as pd
import streamlit as st


DB_NAME = "llm_metrics.db"


# Page Configuration

st.set_page_config(
    page_title="LLM Cost & Latency Tracker",
    page_icon="📊",
    layout="wide"
)


# Load Data

@st.cache_data
def load_metrics():

    conn = sqlite3.connect(DB_NAME)

    df = pd.read_sql_query(
        "SELECT * FROM llm_requests",
        conn
    )

    conn.close()

    return df


# Title

st.title("📊 LLM Cost & Latency Tracker")

st.write(
    "Monitor LLM requests, token usage, "
    "latency, model usage, and cost."
)


# Load Database

try:

    df = load_metrics()

except Exception as e:

    st.error(
        "Could not load the database."
    )

    st.code(str(e))

    st.stop()


# Empty Database

if df.empty:

    st.warning(
        "No LLM requests recorded yet."
    )

    st.info(
        "Run tracker.py first to create "
        "some LLM requests."
    )

    st.stop()


# Convert Timestamp

df["timestamp"] = pd.to_datetime(
    df["timestamp"]
)


# Sidebar Filters

st.sidebar.header("Filters")


models = sorted(
    df["model"].dropna().unique()
)


selected_models = st.sidebar.multiselect(
    "Models",
    models,
    default=models
)


statuses = sorted(
    df["status"].dropna().unique()
)


selected_statuses = st.sidebar.multiselect(
    "Status",
    statuses,
    default=statuses
)


filtered_df = df[
    df["model"].isin(selected_models)
    & df["status"].isin(selected_statuses)
]


if filtered_df.empty:

    st.warning(
        "No requests match the selected filters."
    )

    st.stop()


# Key Metrics

total_requests = len(filtered_df)

total_tokens = int(
    filtered_df["total_tokens"].sum()
)

total_cost = filtered_df["cost"].sum()

average_latency = filtered_df[
    "latency_ms"
].mean()

average_tokens = filtered_df[
    "total_tokens"
].mean()


col1, col2, col3, col4 = st.columns(4)


col1.metric(
    "Requests",
    total_requests
)


col2.metric(
    "Total Tokens",
    f"{total_tokens:,}"
)


col3.metric(
    "Total Cost",
    f"${total_cost:.6f}"
)


col4.metric(
    "Avg Latency",
    f"{average_latency:.0f} ms"
)


# Token Metrics

st.subheader("Token Usage")


col1, col2, col3 = st.columns(3)


col1.metric(
    "Prompt Tokens",
    f"{int(filtered_df['prompt_tokens'].sum()):,}"
)


col2.metric(
    "Completion Tokens",
    f"{int(filtered_df['completion_tokens'].sum()):,}"
)


col3.metric(
    "Average Tokens / Request",
    f"{average_tokens:.0f}"
)


# Latency Chart

st.subheader("Latency Over Time")


latency_df = (
    filtered_df
    .sort_values("timestamp")
    .set_index("timestamp")
)


st.line_chart(
    latency_df["latency_ms"]
)


# Model Usage

st.subheader("Model Usage")


model_usage = (
    filtered_df["model"]
    .value_counts()
)


st.bar_chart(
    model_usage
)


# Token Usage by Model

st.subheader("Token Usage by Model")


token_usage = (
    filtered_df
    .groupby("model")["total_tokens"]
    .sum()
    .sort_values(ascending=False)
)


st.bar_chart(
    token_usage
)


# Cost by Model

st.subheader("Cost by Model")


cost_by_model = (
    filtered_df
    .groupby("model")["cost"]
    .sum()
    .sort_values(ascending=False)
)


st.bar_chart(
    cost_by_model
)


# Slowest Requests

st.subheader("🐌 Slowest Requests")


slowest = (
    filtered_df
    .sort_values(
        "latency_ms",
        ascending=False
    )
    .head(10)
)


st.dataframe(
    slowest[
        [
            "timestamp",
            "model",
            "prompt_tokens",
            "completion_tokens",
            "total_tokens",
            "latency_ms",
            "cost",
            "status"
        ]
    ],
    use_container_width=True
)


# Most Expensive Requests

st.subheader("💰 Most Expensive Requests")


expensive = (
    filtered_df
    .sort_values(
        "cost",
        ascending=False
    )
    .head(10)
)


st.dataframe(
    expensive[
        [
            "timestamp",
            "model",
            "prompt_tokens",
            "completion_tokens",
            "total_tokens",
            "latency_ms",
            "cost",
            "status"
        ]
    ],
    use_container_width=True
)


# Request History

st.subheader("Request History")


st.dataframe(
    filtered_df.sort_values(
        "timestamp",
        ascending=False
    ),
    use_container_width=True
)


# Request Details

st.subheader("Request Details")


request_id = st.selectbox(
    "Select a request",
    filtered_df["id"].tolist()
)


selected_request = filtered_df[
    filtered_df["id"] == request_id
].iloc[0]


st.markdown("### Prompt")

st.code(
    selected_request["prompt"],
    language="text"
)


st.markdown("### Response")

st.code(
    selected_request["response"],
    language="text"
)


# Refresh

if st.button("🔄 Refresh Dashboard"):

    st.cache_data.clear()

    st.rerun()

Launch it with:

streamlit run dashboard.py

Here’s what your dashboard will look like:

LLM Cost & Latency Tracker

This setup is suitable for local models, prototypes, and small internal tools. For production use, you may transition from SQLite to Postgres and incorporate percentile latency metrics, such as p95, in addition to averages. The core design remains: log every call, store context, and analyze outliers.

The Takeaway

You do not need a dedicated observability platform to begin measuring your LLM application. Two Python files and a free local model can help you identify what is slow, costly, or failing.

Direct your application to use run_request, review the dashboard after a week, and you will be able to optimize based on actual data rather than assumptions.

Thank you for reading this article on building an LLM cost and latency tracker with Python. For additional AI and machine learning insights, you are welcome to follow me on Instagram.

Aman Kharwal
Aman Kharwal

AI/ML Engineer | Published Author. My aim is to decode data science for the real world in the most simple words.

Articles: 2269

One comment

Leave a Reply