Documentation menu
DocsReference

TypeScript API Reference

Public @traice/sdk functions, classes, adapters, integrations, analytics, guardrails, and types.

View source

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.

TypeScript
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

APISignatureBehaviorSource
configure(config: Partial<GlobalConfig>) => voidMerge process-wide SDK configuration and rebuild adapters on the next useindex.ts
getConfig() => GlobalConfigReturn a shallow copy of the current global configurationindex.ts
resetConfig() => voidRestore default global configurationindex.ts
meter<T>(fn, options?) => Promise<T>Run one provider call, return its response, and emit a cost eventindex.ts
meterStream<T extends AsyncIterable>(fn, options?) => Promise<T>Return a provider stream and record usage after it completesindex.ts
flush() => Promise<void>Wait for pending adapter writes and adapter buffersindex.ts
getMeterStats() => { eventsTracked, eventsDropped, adapterErrors, unknownModels }Read process-local metering health countersindex.ts
resetStats() => voidReset process-local metering countersindex.ts
CostMeternew CostMeter(config?)Create an instance-scoped meter with track, trackStream, record, and flush methodsindex.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

APISignatureBehaviorSource
cachedMeter<T>(fn, options & { ttlMs?, cacheKey? }) => Promise<T>Cache a provider response in the process-local LRU cache and record zero cost on hitsindex.ts
getCacheStats() => CacheStatsReturn hit, miss, size, hit-rate, and savings statisticsindex.ts
resetCache() => voidClear the global process-local response cacheindex.ts
globalCacheLRUCache<any>Export the global cache used by cachedMetercache.ts
LRUCachenew LRUCache<T>(maxSize?)Create a bounded TTL cache with savings metricscache.ts
configureBudget(config: BudgetConfig) => voidConfigure process-local daily feature budget callbacksindex.ts
getBudgetStatus() => BudgetStatus[]Read current process-local budget accumulatorsindex.ts
resetBudget() => voidClear process-local budget rules and accumulatorsindex.ts

These helpers are process-local. For cached workspace-wide budget advice, use the CloudAdapter policy methods below.

Pricing APIs

APISignatureBehaviorSource
calculateCost(provider, model, inputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?)Calculate input, output, and total cost in USD from local pricingpricing/index.ts
normalizeCacheTokens(inputTokens, cacheReadTokens?, cacheWriteTokens?)Bound cache token subsets to the supplied input-token totalpricing/index.ts
configurePricing(provider, model, { input, output }) => voidAdd or replace pricing for one modelpricing/index.ts
setPricingTable(provider, table) => voidReplace one provider pricing tablepricing/index.ts
removePricing(provider, model) => booleanRemove one model and report whether it existedpricing/index.ts
getAvailableModels(provider) => string[]List models with local pricing for a providerpricing/index.ts
getAllPricing() => Record<string, PricingTable>Return a deep copy of all current pricing tablespricing/index.ts

Adapters

Every adapter implements CostAdapter with an asynchronous write(event) method and an optional flush() method.

Class or factoryConstructorBehaviorSource
ConsoleAdapternew ConsoleAdapter()Print formatted eventsconsole.ts
LocalAdapternew LocalAdapter(filePath)Append newline-delimited JSON and serialize writeslocal.ts
CloudAdapternew CloudAdapter(config)Batch cloud events and execute supported active request rulescloud.ts
WebhookAdapternew WebhookAdapter(config)Batch and POST full local cost events to a custom endpointwebhook.ts
OTelAdapternew OTelAdapter(config?)Record cost, token, and duration metrics through OpenTelemetryotel.ts
createAdapter(name, options?) => CostAdapterResolve a built-in adapter by nameadapters/index.ts

CloudAdapter request methods

MethodBehavior
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

APIPurposeSource
decidePure synchronous rule planner with no network or file I/Oenforcement.ts
TraiceEnforcementErrorStructured refusal for active DENY and CAP_RETRIES decisionscloud.ts
CloudAdapter.enforceRequestExecutor for exact or semantic cache, deny, retry cap, evidence-gated model actions, and fallbackcloud.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

APISignatureSource
createExpressMiddleware(config) => (req, res, next) => voidmiddleware/express.ts
withCostTracking(config, routeHandler) => routeHandlerintegrations/nextjs.ts
withMeteredAction(config, serverAction) => serverActionintegrations/nextjs.ts
createNextApiHandler(config, pagesHandler) => pagesHandlerintegrations/nextjs.ts
LangChainCostHandlernew LangChainCostHandler(config?)integrations/langchain.ts

Analytics and read APIs

APISignatureSource
forecast(events: CostEvent[]) => ForecastResult[]analytics/forecast.ts
detectAnomalies(events, options?) => AnomalyResult[]analytics/anomalies.ts
comparePromptVersions(events, promptName?) => VersionComparison[]analytics/compare.ts
optimizeModels(events) => ModelRecommendation[]analytics/optimizer.ts
detectTokenAbuse(events, options?) => TokenAbuseResult[]analytics/token-abuse.ts
askTraice(question, { apiKey, serverUrl?, signal? }) => Promise<AskTraiceResponse>ask.ts
normalizeServerUrl(value) => stringask.ts
DEFAULT_TRAICE_SERVER_URL"https://www.runtraice.com"ask.ts

Vendor import APIs

APISignatureBehaviorSource
importLiteLlm(options: LiteLlmImportOptions) => Promise<VendorImportResult>Import bounded LiteLLM spend-log windows with retry-safe identitiesvendor-imports.ts
importLangfuse(options: LangfuseImportOptions) => Promise<VendorImportResult>Import bounded Langfuse generation observations without prompt or outputvendor-imports.ts
mapLiteLlmSpendLog(value: unknown) => ImportedEvent | nullNormalize one LiteLLM spend logvendor-imports.ts
mapLangfuseObservation(value: unknown) => ImportedEvent | nullNormalize one Langfuse observationvendor-imports.ts
parseImportRange(since, until?, now?) => ImportRangeParse an ISO boundary or duration such as 7dvendor-imports.ts

Portable policy API

APISignatureBehaviorSource
exportPolicy(options: ExportPolicyOptions) => Promise<PortablePolicyBundle>Fetch and validate user-authored rules, evidence, and budget snapshots as JSONpolicy.ts

Exported types

GroupPublic typesSource
Events and meteringEventMetadata, CostEvent, MeterOptions, CostMeterConfig, CostAdapter, GlobalConfig, ErrorHandler, MeterStatstypes.ts
Pricing and reportsModelPricing, PricingTable, SummaryRow, ReportOptionstypes.ts
Middleware and adaptersExpressMiddlewareOptions, WebhookAdapterConfig, OTelAdapterConfig, CloudAdapterConfig, SemanticCacheConfigtypes.ts, cloud.ts
Budgets and cacheBudgetRule, BudgetConfig, BudgetStatus, CacheStatstypes.ts, cache.ts
Request cacheExactCacheContext, ExactCacheRequest, ExactCacheStats, SemanticCacheStatscloud.ts
Request enforcementBlockingRuleAction, ModelRuleAction, RequestEnforcementContext, EnforcementEvidencecloud.ts
Rule planningEnforcementBudgetScope, EnforcementContext, EnforcementDecision, EnforcementRequest, EnforcementRule, RuleAction, RuleCondition, RuleStateenforcement.ts
AnalyticsForecastResult, AnomalyResult, AnomalyOptions, VersionComparison, ModelRecommendation, TokenAbuseOptions, TokenAbuseResultanalytics
Ask trAIceAskTraiceResponseask.ts
Vendor importsImportCredential, ImportRange, ImportedEvent, LiteLlmImportOptions, LangfuseImportOptions, VendorImportResultvendor-imports.ts
Portable policyExportPolicyOptions, PortablePolicyBundle, PortablePolicyBudget, PortablePolicyEvidencepolicy.ts