Skip to content
Konstera
Docs · Reference
Konstera documentation.

Getting started, SDK quickstart, manifest reference, kernel MCP services, deploy guide and FAQ — everything you need to build and run agents on Konstera.

Cost metering

Konstera meters cost on every kernel-side side effect that spends money. LLM calls get full token + USD accounting automatically. Non-LLM spend (external APIs, GPU rentals, scoring services) is recorded with ctx.cost.record().

This page covers both the agent-author surface (what you call, what you read) and the mechanics (what the kernel records, how it attributes).

What gets metered automatically#

Every ctx.llm.complete() call is metered without agent intervention:

  • Input tokens (prompt tokens, including system prompt)
  • Output tokens (completion tokens)
  • Cached input tokens (Anthropic + OpenAI cache hits — separate column so cost reports show cached-vs-fresh split)
  • Cost USD (computed server-side from the model's price-per-million tokens, with provider cache discounts applied)

The agent gets this back on the LlmResult:

Python
result = await ctx.llm.complete(prompt="hi", purpose="narrator")
print(result.cost_usd)         # 0.0003
print(result.input_tokens)     # 10
print(result.output_tokens)    # 5
print(result.cached_input_tokens)  # 0

No separate ctx.cost.record() call needed for LLM spend — the kernel has already written the row.

What you record manually#

Anything that spent money but isn't an LLM call:

Python
# Example: Cohere rerank API via a connector
reranked = await ctx.connector.call(
    "cohere", "rerank",
    {"query": q, "documents": docs, "model": "rerank-english-v3.0"}
)
await ctx.cost.record(
    kind="tool",                  # labels: llm | tool | connector | other
    cost_usd=0.0023,              # computed from Cohere's billing (per-call fee)
    model="cohere-rerank-english-v3.0",
    input_tokens=sum(len(d) for d in docs),   # if you track tokens
    metadata={"candidates": len(docs)},
)

Fire-and-forget — doesn't block, doesn't raise.

Reading your own cost#

An agent can self-govern against its own budget:

Python
# Hourly backlog agent — stop before blowing the daily cap
summary = await ctx.cost.summary(window_hours=24)  # since-24h window
if summary and summary.total_usd > 50.0:
    await ctx.log.warn("daily cap near", spent=summary.total_usd)
    return AgentResponse(content="", structured={"deferred": "daily cap"})

Available in Python v0.6.0, TypeScript v0.4.0, and .NET v0.3.0. Returns None on tenants whose kernel hasn't yet enabled the cost_summary tool, so you can adopt the method today — agents branch on data availability rather than special-casing the rollout. In the meantime, falling back on ctx.state.set("hourly-spend", running_sum) is the right approximation.

Attribution model#

Every cost event is attributed to five dimensions:

DimensionSource
Tenantfrom the caller's instance → tenant mapping (M8 multi-tenancy)
Instancethe specific agent-instance that made the call
Agent packagederived from instance; aggregates across all tenants' instances of this agent
ModelLLM: provider's model name; tool: user-supplied model string
Invocationthe current invocation's UUID (ambient; auto-injected)

Portal views slice on any of these — "LLM spend per tenant last month", "GPT-5 vs Claude Sonnet 4.6 cost on the refund-approval agent", "total cost of invocation inv-abc123".

The usage_events table#

Kernel-side, every metered call writes one row:

SQL
CREATE TABLE usage_events (
    id            uuid PRIMARY KEY,
    tenant_id     uuid NOT NULL,
    instance_id   uuid NOT NULL,
    agent_id      uuid NOT NULL,       -- package id, derived from instance
    invocation_id uuid,                -- null for direct-run / startup calls
    kind          text NOT NULL,       -- 'llm' | 'tool' | 'connector' | 'other'
    model_id      text,                -- optional
    input_tokens  integer DEFAULT 0,
    output_tokens integer DEFAULT 0,
    cached_input_tokens integer DEFAULT 0,
    cost_usd      numeric(12,6) NOT NULL,
    metadata_json jsonb DEFAULT '{}',
    recorded_at   timestamptz NOT NULL DEFAULT now()
);

RLS enforces that an agent's instance can only read its own tenant's rows. Admin reports use a BYPASSRLS role for cross-tenant aggregations.

Caps + policies#

Admins set caps per tenant in the portal:

  • Monthly budget — hard stop; kernel refuses llm_complete with [KERN-002] when exceeded
  • Per-model caps — "max $100/month on GPT-5"
  • Per-agent caps — "the demand-forecaster can spend at most $20/day"

See the error catalog for the agent-side exception shape when a cap trips mid-invocation.

Common patterns#

Report structured spend after an invocation#

Python
return AgentResponse(
    content=reply,
    structured={
        "cost_usd": round(result.cost_usd, 6),
        "model": result.model,
        "tokens": result.input_tokens + result.output_tokens,
    },
)

The structured block is visible in the invocation trace alongside the kernel-recorded usage_events row. Having both lets you spot discrepancies (e.g. your code's estimate vs. the kernel's authoritative record).

Charge spend to a different invocation#

Rare, but if your agent runs a batch and attributes each item to a different logical invocation (e.g. per-ticket in a hourly backlog), pass invocation_id explicitly:

Python
for ticket in tickets:
    inv_id = str(uuid4())
    result = await ctx.llm.complete(
        prompt=ticket.body, purpose="drafter", invocation_id=inv_id
    )
    await ctx.cost.record(
        kind="other", cost_usd=0.001, invocation_id=inv_id,
        metadata={"source": "backlog-draft"},
    )

Now each ticket shows up as a separate invocation in cost reports.

Zero-cost events for audit#

Record cost_usd=0 for things the audit should see but didn't cost money (cache hits, degraded-mode fallbacks). Keeps the usage_events table complete so dashboards aren't gappy.

See also#