dexcost
Python

Quickstart

Initialize the Python SDK and capture your first attributed LLM cost in under a minute.

Two lines start tracking every LLM call with customer attribution — no changes to your existing call sites.

Initialize

Call dexcost.init() once at application startup, then call dexcost.set_context() with the customer you want costs attributed to:

import dexcost

dexcost.init(api_key="dx_live_...")        # or set DEXCOST_API_KEY env var
dexcost.set_context(customer_id="acme-corp")

dexcost.init() patches the LLM provider SDKs that are installed in your environment. dexcost.set_context() stores customer_id (and optionally project_id) in a contextvar so every subsequent call in the same async task or thread inherits the attribution automatically.

Your first tracked call

After init() and set_context(), use your LLM client exactly as you normally would. dexcost captures cost, tokens, latency, model, and provider without any changes to the call site:

import dexcost
from openai import OpenAI

dexcost.init(api_key="dx_live_...")
dexcost.set_context(customer_id="acme-corp")

client = OpenAI()

with dexcost.task(task_type="summarise_doc") as t:
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Summarise this document"}],
    )
    # Record a non-LLM cost alongside the auto-captured LLM cost
    t.record_cost(service="pdf_parser", cost_usd="0.002")

Once the with block exits, the task is closed and its aggregated cost — total_cost_usd, llm_cost_usd, external_cost_usd, token counts — is written to the local SQLite buffer and synced to the Control Layer in the background.

Run it locally

Pass environment="development" to dexcost.init() to enable dev mode. In dev mode, every cost event is printed to your terminal and no data is sent to the cloud — useful for local development and debugging:

import dexcost
from openai import OpenAI

dexcost.init(environment="development")
dexcost.set_context(customer_id="acme-corp")

client = OpenAI()

with dexcost.task(task_type="summarise_doc") as t:
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Summarise this document"}],
    )

You can also set the DEXCOST_ENV=development environment variable instead of passing the argument to init().

Next steps

  • Instrumentation — details on all 6 LLM providers, HTTP library patching, and how to limit which providers are instrumented.
  • Configuration — all dexcost.init() parameters, environment variables, privacy options, and the local SQLite buffer.

On this page