Skip to content
reaatechREAATECH

@reaatech/llm-cost-telemetry-observability

npm v0.1.0

Instruments LLM applications with OpenTelemetry tracing, cost-tracking metrics, and PII-redacting Pino logging. It provides `TracingManager` and `MetricsManager` classes to handle OTLP exports and Gen AI semantic conventions.

@reaatech/llm-cost-telemetry-observability

npm version License: MIT CI

Status: Pre-1.0 — APIs may change in minor versions. Pin to a specific version in production.

OpenTelemetry tracing, metrics instrumentation, and structured logging for LLM cost telemetry. Provides ready-to-use managers for distributed tracing (OTLP), cost-specific metrics (tokens, duration, budget), and Pino-based logging with PII redaction.

Installation

terminal
npm install @reaatech/llm-cost-telemetry-observability
# or
pnpm add @reaatech/llm-cost-telemetry-observability

Feature Overview

  • OTLP tracing — automatic span creation with Gen AI semantic conventions
  • Cost metrics — counters and histograms for token usage, cost amount, API calls, errors, and budget utilization
  • Structured logging — Pino-based with PII redaction (API keys, bearer tokens)
  • Singleton loggersgetLogger() returns the same instance across your application
  • Configurable sampling — control trace sample rate via environment or code

Quick Start

typescript
import { TracingManager, MetricsManager, getLogger } from "@reaatech/llm-cost-telemetry-observability";
 
const tracer = new TracingManager({
  serviceName: "my-llm-app",
  otlpEndpoint: "http://localhost:4318/v1/traces",
});
await tracer.init();
 
const metrics = new MetricsManager({
  serviceName: "my-llm-app",
  otlpEndpoint: "http://localhost:4318/v1/metrics",
});
await metrics.init();
 
const logger = getLogger({ name: "llm-cost" });
logger.logCostSpan(span);

API Reference

TracingManager

OpenTelemetry tracing with OTLP export:

typescript
import { TracingManager, type TracingOptions } from "@reaatech/llm-cost-telemetry-observability";
 
const tracer = new TracingManager({
  serviceName: "my-llm-app",
  serviceVersion: "1.0.0",
  environment: "production",
  otlpEndpoint: "https://otlp.example.com/v1/traces",
  traceSampleRate: 0.1,
});

TracingOptions

PropertyTypeDefaultDescription
serviceNamestringllm-cost-telemetryService name for telemetry attribution
serviceVersionstringService version tag
environmentstringDeployment environment tag
otlpEndpointstringOTLP collector endpoint
traceSampleRatenumber1.0Sampling rate (0.0–1.0)
resourceAttributesRecord<string, string>Additional resource attributes

Methods

MethodDescription
init()Initialize the tracer provider and exporter
startSpan(name, options?)Create and return a new span
recordCostSpan(span)Create a span with Gen AI semantic convention attributes
getCurrentContext()Get the current propagation context
close()Shutdown — flushes pending spans

Gen AI Semantic Conventions

recordCostSpan() automatically sets OTel attributes:

code
gen_ai.system           → span.provider
gen_ai.request.model    → span.model
gen_ai.usage.input_tokens   → span.inputTokens
gen_ai.usage.output_tokens  → span.outputTokens
llm.cost.amount         → span.costUsd

MetricsManager

OpenTelemetry metrics with OTLP periodic export:

typescript
import { MetricsManager, type MetricsOptions } from "@reaatech/llm-cost-telemetry-observability";
 
const metrics = new MetricsManager({
  serviceName: "my-llm-app",
  otlpEndpoint: "https://otlp.example.com/v1/metrics",
  exportIntervalMs: 60000,
});

MetricsOptions

PropertyTypeDefaultDescription
serviceNamestringllm-cost-telemetryService name for telemetry attribution
otlpEndpointstringOTLP collector endpoint
exportIntervalMsnumber60000Metric export interval

Instrument Types

InstrumentTypeLabelsDescription
gen_ai.client.token.useCounterprovider, model, typeToken usage (input/output)
gen_ai.client.operation.durationHistogramprovider, model, tenantCost amount in USD
gen_ai.client.operation.callsCounterprovider, model, statusAPI call count
gen_ai.client.operation.errorsCounterprovider, modelError count
llm.budget.utilizationUpDownCountertenantBudget utilization percentage

Methods

MethodDescription
init()Initialize the meter provider and exporter
recordTokens(provider, model, type, tokens)Record token usage
recordCost(provider, model, tenant, costUsd)Record cost as a histogram
recordCall(provider, model, status)Record an API call
recordError(provider, model)Record an error
recordBudgetUtilization(tenant, percent)Record budget utilization
recordCostSpan(span)Convenience — records all metrics from a CostSpan
close()Shutdown — flushes pending metrics

CostLogger / getLogger()

Structured logging with Pino and PII redaction:

typescript
import { CostLogger, getLogger, type LoggerOptions } from "@reaatech/llm-cost-telemetry-observability";
 
// Pre-configured singleton
const logger = getLogger({ name: "llm-cost" });
 
// Custom logger
const logger = new CostLogger({
  name: "llm-cost",
  level: "debug",
  redactPii: true,
});

LoggerOptions

PropertyTypeDefaultDescription
namestringllm-cost-telemetryLogger name
levelstringinfoMinimum log level
redactPiibooleantrueEnable API key / bearer token redaction

Methods

MethodDescription
logCostSpan(span)Log a cost span at info level
logAggregation(record)Log an aggregated cost record
logBudgetAlert(tenant, status)Log a budget threshold alert
logExport(exporter, count, result)Log an export operation
logError(error, context?)Log an error with optional context
logInfo(msg, data?)Log at info level
logDebug(msg, data?)Log at debug level
logWarn(msg, data?)Log at warn level

Log Format

Every cost event is logged as structured JSON:

json
{
  "timestamp": "2026-04-30T17:00:00.000Z",
  "service": "llm-cost-telemetry",
  "span_id": "abc123",
  "level": "info",
  "message": "Cost span recorded",
  "provider": "openai",
  "model": "gpt-4",
  "input_tokens": 150,
  "output_tokens": 45,
  "cost_usd": 0.0123,
  "tenant": "acme-corp"
}

Usage Patterns

PII Redaction

The logger automatically redacts secrets from log output:

typescript
logger.logInfo("Request", {
  authorization: "Bearer sk-abc123xyz",
  api_key: "secret-key-456",
  model: "gpt-4",
});
// Logs: { authorization: "[REDACTED]", api_key: "[REDACTED]", model: "gpt-4" }

Patterns matched for redaction: authorization, api_key, api-key, x-api-key, password, secret, token.

License

MIT