Skip to Content
AI

Usage to spans and spend

Put AI token usage and cost on the active OpenTelemetry span, and record spend per user or org.

Usage

import { createExtractor } from "@dapplelight/signet-ai"
import { onUsageAll, otelUsage, spendUsage } from "@dapplelight/signet-ai/otel"
import { createAiSpend } from "@dapplelight/signet-db/ai-spend"
import { db, usageCounters, aiSpendCaps } from "./db"
import { providers, schema, instructions } from "./ai"

const input = "Where is order A1042?"

// Build where env exists (a request handler), not at module scope.
const spend = createAiSpend(db, { tables: { usageCounters, aiSpendCaps } })

const ai = createExtractor({
  providers,
  onUsage: onUsageAll(
    otelUsage(),
    spendUsage({ spend, subject: (r) => ({ userId: r.key, orgId: "org_1" }) }),
  ),
})
await ai.extract({ schema, input, instructions, budget: { key: "user_1" } })

API

ExportWhat it does
otelUsage(cfg?)onUsage that sets usage attributes on the active span
onUsageAll(...hooks)One onUsage that runs each hook, isolated from the others
spendUsage(cfg)onUsage that records each call's cost per subject
OtelUsageConfig, SpendUsageConfigConfig types
SpendRecorder, SpendSubjectTypes: what spendUsage needs from createAiSpend

Attributes set by otelUsage

AttributeFromNotes
gen_ai.systemprovider
gen_ai.request.modelmodel
gen_ai.usage.input_tokensusageLeft out when usage is missing
gen_ai.usage.output_tokensusageLeft out when usage is missing
signet.cost_usdcostUsd0 when unpriced or a cache hit
signet.cache_hitcacheHittrue or false
signet.saved_usdsavedUsdOnly on a cache hit
signet.keykeyOnly with includeKey

When usage is missing, the token attributes are left out and the cost is still set. With no active span, nothing happens and nothing throws.

otelUsage(cfg)

OptionTypeDefault
attributes(report)(UsageReport) => Record<string, string | number | boolean>noneExtra attributes per report
includeKeybooleanfalseAlso set signet.key

spendUsage(cfg)

OptionTypeDefault
spend.record(subject, units) => unknownrequiredPass createAiSpend(...); any object with record works
subject(report)(UsageReport) => { userId?, orgId? }requiredWho to charge

Cost is converted to units, rounded up. An unpriced call or a cache hit records 0 units, which the ledger ignores.

@opentelemetry/api is an optional peer. Without an SDK registered, otelUsage does nothing. Signet ships no exporter.

./otel imports @opentelemetry/api by its literal name, so a bundler (esbuild, wrangler, Vite) resolves it at build time and fails if it is missing. If you bundle ./otel, install @opentelemetry/api or mark it external (for example --external:@opentelemetry/api). The runtime fallback only covers unbundled use. Apps that never import ./otel are not affected.

includeKey puts the budget key (often a user id) on the span. Prompts and outputs are never added.

Do not pass spendUsage to an extractor that also has ledger, or spend counts twice.

Examples

Adding your own attributes

import { otelUsage } from "@dapplelight/signet-ai/otel"

const onUsage = otelUsage({
  attributes: (r) => ({ "app.operation": r.operation, "app.duration_ms": r.durationMs }),
})

One hook throws, the others still run

import { onUsageAll } from "@dapplelight/signet-ai/otel"

const onUsage = onUsageAll(
  () => {
    throw new Error("broken hook")
  },
  (r) => console.log(r.model), // still runs
)

Each hook is isolated: a throwing hook never stops the others or fails the call.