Import every API on this page from @traice/sdk. The package ships ES module, CommonJS, and TypeScript declaration outputs for Node.js 20.9 or newer.
import { configure, flush, meter } from "@traice/sdk";
The package entrypoint is packages/sdk/src/index.ts . The published declaration file is also available from the installed package as dist/index.d.ts.
Global configuration and metering
API Signature Behavior Source configure(config: Partial<GlobalConfig>) => voidMerge process-wide SDK configuration and rebuild adapters on the next use index.ts getConfig() => GlobalConfigReturn a shallow copy of the current global configuration index.ts resetConfig() => voidRestore default global configuration index.ts meter<T>(fn, options?) => Promise<T>Run one provider call, return its response, and emit a cost event index.ts meterStream<T extends AsyncIterable>(fn, options?) => Promise<T>Return a provider stream and record usage after it completes index.ts flush() => Promise<void>Wait for pending adapter writes and adapter buffers index.ts getMeterStats() => { eventsTracked, eventsDropped, adapterErrors, unknownModels }Read process-local metering health counters index.ts resetStats() => voidReset process-local metering counters index.ts CostMeternew CostMeter(config?)Create an instance-scoped meter with track, trackStream, record, and flush methods index.ts
meter() and CostMeter.track() rethrow provider errors and record an error event when possible. Adapter writes are fire-and-forget unless MeterOptions.awaitWrites is true.
MeterOptions.provider and CostMeterConfig.provider accept explicit string identifiers such as google-vertex. Explicit identifiers override response-shape detection and are honored by stream metering. CamelCase AI SDK token usage is read from usage or totalUsage.
Cache and budget APIs
API Signature Behavior Source cachedMeter<T>(fn, options & { ttlMs?, cacheKey? }) => Promise<T>Cache a provider response in the process-local LRU cache and record zero cost on hits index.ts getCacheStats() => CacheStatsReturn hit, miss, size, hit-rate, and savings statistics index.ts resetCache() => voidClear the global process-local response cache index.ts globalCacheLRUCache<any>Export the global cache used by cachedMeter cache.ts LRUCachenew LRUCache<T>(maxSize?)Create a bounded TTL cache with savings metrics cache.ts configureBudget(config: BudgetConfig) => voidConfigure process-local daily feature budget callbacks index.ts getBudgetStatus() => BudgetStatus[]Read current process-local budget accumulators index.ts resetBudget() => voidClear process-local budget rules and accumulators index.ts
These helpers are process-local. For cached workspace-wide budget advice, use
the CloudAdapter policy methods below.
Pricing APIs
API Signature Behavior Source calculateCost(provider, model, inputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?)Calculate input, output, and total cost in USD from local pricing pricing/index.ts normalizeCacheTokens(inputTokens, cacheReadTokens?, cacheWriteTokens?)Bound cache token subsets to the supplied input-token total pricing/index.ts configurePricing(provider, model, { input, output }) => voidAdd or replace pricing for one model pricing/index.ts setPricingTable(provider, table) => voidReplace one provider pricing table pricing/index.ts removePricing(provider, model) => booleanRemove one model and report whether it existed pricing/index.ts getAvailableModels(provider) => string[]List models with local pricing for a provider pricing/index.ts getAllPricing() => Record<string, PricingTable>Return a deep copy of all current pricing tables pricing/index.ts
Adapters
Every adapter implements CostAdapter with an asynchronous write(event) method and an optional flush() method.
Class or factory Constructor Behavior Source ConsoleAdapternew ConsoleAdapter()Print formatted events console.ts LocalAdapternew LocalAdapter(filePath)Append newline-delimited JSON and serialize writes local.ts CloudAdapternew CloudAdapter(config)Batch cloud events and execute supported active request rules cloud.ts WebhookAdapternew WebhookAdapter(config)Batch and POST full local cost events to a custom endpoint webhook.ts OTelAdapternew OTelAdapter(config?)Record cost, token, and duration metrics through OpenTelemetry otel.ts createAdapter(name, options?) => CostAdapterResolve a built-in adapter by name adapters/index.ts
CloudAdapter request methods
Method Behavior write(event)Buffer a local CostEvent for cloud delivery flush()Send buffered events and wait for pending decision telemetry warmEnforcement()Fetch and cache current rules and experiment evidence before serving traffic warmPolicy()Fetch and cache workspace, feature, and user budget status getBudgetAdvice(context?)Return cached matches, utilization, reason, and advisory downgrade/block booleans shouldDowngrade(context?)Return cached advice at the 80% warning threshold; cold/error policy returns false isBlocked(context?)Return cached advice at the 100% exceeded threshold; cold/error policy returns false enforceRequest(request, providerCall, context?)Execute supported active rules for one opted-in request path enforceExactCache(request, providerCall, context?)Execute only an active exact-cache rule and otherwise pass through getExactCacheStats()Return process-local exact-cache hits, misses, bypasses, size, hit rate, and savings getSemanticCacheStats()Return process-local semantic-cache health, hit rate, and estimated savings getDeliveryStats()Return queue, acknowledgement, retry, failure, and delivery timestamp counters
CloudAdapterConfig supports a bounded memory queue, request timeout, retry
attempt and delay caps, delivery observers, privacy-safe prompt
fingerprinting, opt-in content capture, and an optional durableQueuePath.
Global configuration exposes
cloudMaxQueueSize, cloudCaptureContent, and cloudDurableQueuePath.
Request enforcement
API Purpose Source decidePure synchronous rule planner with no network or file I/O enforcement.ts TraiceEnforcementErrorStructured refusal for active DENY and CAP_RETRIES decisions cloud.ts CloudAdapter.enforceRequestExecutor for exact or semantic cache, deny, retry cap, evidence-gated model actions, and fallback cloud.ts
TraiceEnforcementError exposes code, action, ruleId, ruleName, requestedModel, reason, and toJSON(). Route requires a non-empty allowlist and passing experiment evidence. Semantic cache requires an opt-in customer-supplied embedder and remains process-local. Shadow semantic-cache rules always call the provider, then report only qualifying similarity and cost evidence.
Framework integrations
Analytics and read APIs
Vendor import APIs
API Signature Behavior Source importLiteLlm(options: LiteLlmImportOptions) => Promise<VendorImportResult>Import bounded LiteLLM spend-log windows with retry-safe identities vendor-imports.ts importLangfuse(options: LangfuseImportOptions) => Promise<VendorImportResult>Import bounded Langfuse generation observations without prompt or output vendor-imports.ts mapLiteLlmSpendLog(value: unknown) => ImportedEvent | nullNormalize one LiteLLM spend log vendor-imports.ts mapLangfuseObservation(value: unknown) => ImportedEvent | nullNormalize one Langfuse observation vendor-imports.ts parseImportRange(since, until?, now?) => ImportRangeParse an ISO boundary or duration such as 7d vendor-imports.ts
Portable policy API
API Signature Behavior Source exportPolicy(options: ExportPolicyOptions) => Promise<PortablePolicyBundle>Fetch and validate user-authored rules, evidence, and budget snapshots as JSON policy.ts
Exported types
Group Public types Source Events and metering EventMetadata, CostEvent, MeterOptions, CostMeterConfig, CostAdapter, GlobalConfig, ErrorHandler, MeterStatstypes.ts Pricing and reports ModelPricing, PricingTable, SummaryRow, ReportOptionstypes.ts Middleware and adapters ExpressMiddlewareOptions, WebhookAdapterConfig, OTelAdapterConfig, CloudAdapterConfig, SemanticCacheConfigtypes.ts , cloud.ts Budgets and cache BudgetRule, BudgetConfig, BudgetStatus, CacheStatstypes.ts , cache.ts Request cache ExactCacheContext, ExactCacheRequest, ExactCacheStats, SemanticCacheStatscloud.ts Request enforcement BlockingRuleAction, ModelRuleAction, RequestEnforcementContext, EnforcementEvidencecloud.ts Rule planning EnforcementBudgetScope, EnforcementContext, EnforcementDecision, EnforcementRequest, EnforcementRule, RuleAction, RuleCondition, RuleStateenforcement.ts Analytics ForecastResult, AnomalyResult, AnomalyOptions, VersionComparison, ModelRecommendation, TokenAbuseOptions, TokenAbuseResultanalytics Ask trAIce AskTraiceResponseask.ts Vendor imports ImportCredential, ImportRange, ImportedEvent, LiteLlmImportOptions, LangfuseImportOptions, VendorImportResultvendor-imports.ts Portable policy ExportPolicyOptions, PortablePolicyBundle, PortablePolicyBudget, PortablePolicyEvidencepolicy.ts