TypeScript SDK API Reference
BothComplete API reference for the Traccia TypeScript SDK.
This page documents all public functions, classes, and decorators in the @traccia/sdk package.
Initialization
Traccia.init()
Initializes the Traccia SDK with options and registers it globally. Must be awaited before creating traces.
static async init(config?: SDKConfig): Promise<ITracerProvider>Parameters:
apiKey — API key for Traccia Platform (optional if set in env)endpoint — OTLP endpoint (default: env or http://localhost:4318/v1/traces)sampleRate — Ratio of traces to sample (default: 1.0)maxQueueSize — Max number of buffered spansenableConsoleExporter — Print spans to console for debuggingautoInstrument — Automatically instrument supported libraries like Axios/Express (default: false)enableTokenCounting — Count tokens for LLM operationsenableCostTracking — Calculate LLM costs based on tokenspricingOverride — Override pricing tablesredactPii — Mask sensitive patterns automatically before exportReturns:
Promise resolving to the ITracerProvider.
Example:
import { Traccia } from "@traccia/sdk";
// Minimal initializationawait Traccia.init();
// With configurationawait Traccia.init({ apiKey: "tr_live_xxxxxxxxxxxx", sampleRate: 0.1, autoInstrument: true, enableTokenCounting: true});stopTracing()
Gracefully shutdown the TracerProvider, flush pending spans, and clean up resources.
import { stopTracing } from "@traccia/sdk";
// Flush and shutdownawait stopTracing();Tracing API
@observe()
Decorator to automatically create spans around method execution. Note: Requires TypeScript experimentalDecorators or Babel.
function observe(options?: ObserveOptions): MethodDecoratorParameters:
name — Override the span name (defaults to class.methodName)attributes — Static attributes to add to the spanskipArgs — Array of argument names to omit from the spanskipResult — Boolean, if true the return value is not capturedSee @observe() Documentation for detailed usage.
Traccia.getTracer()
Get a tracer instance to start spans manually.
static getTracer(name?: string, version?: string): ITracerimport { Traccia } from "@traccia/sdk";
const tracer = Traccia.getTracer("my-service");
await tracer.startActiveSpan("operation", async (span) => { span.setAttribute("custom", "value"); await doWork(); span.end();});Traccia.getCurrentSpan()
Retrieve the currently active span in the async context.
import { Traccia } from "@traccia/sdk";
const span = Traccia.getCurrentSpan();span?.setAttribute("step", "validation");spanScope()
Start a span with explicit lifecycle control. Unlike startActiveSpan, the span is not ended automatically — call scope.end() when the operation completes. Use for long-lived operations such as streaming chat turns.
import { spanScope } from "@traccia/sdk";
async function handleStream() { const turn = spanScope("chat.turn", { attributes: { "span.type": "llm" } }); try { await turn.runAsync(async () => { for await (const chunk of streamTokens()) { // child spans created here attach to chat.turn } }); } catch (error) { turn.end(error); throw error; } turn.end();}runWithSpan() / runWithSpanAsync()
Run a function with a specific span set as the active parent. Used internally by spanScope().run() and spanScope().runAsync().
import { Traccia, runWithSpan, runWithSpanAsync } from "@traccia/sdk";
const tracer = Traccia.getTracer();const span = tracer.startSpan("background_job");
// SyncrunWithSpan(span, () => processBatch());
// Asyncawait runWithSpanAsync(span, async () => processBatchAsync());span.end();Runtime Configuration
Functions to attach metadata (Session ID, User ID, Tenant ID) directly to the active root context.
import { Traccia } from "@traccia/sdk";
// Attach context to the active span context globallyTraccia.setSessionId("session-123");Traccia.setUserId("user-456");Traccia.setTenantId("tenant-789");Instrumentation & HTTP Middlewares
expressMiddleware
Express middleware to auto-create spans for HTTP routes and extract incoming trace contexts.
import express from "express";import { expressMiddleware } from "@traccia/sdk";
const app = express();app.use(expressMiddleware());patchAxios / createTracedAxios
Instrument Axios to inject trace context into outgoing HTTP headers.
import axios from "axios";import { patchAxios } from "@traccia/sdk";
// Patch the global axios instancepatchAxios();patchOpenAI / patchAnthropic
Manual instrumentation for LLM clients (automatically enabled if autoInstrument: true).
Prompts
Fetch versioned prompts from the Traccia library at runtime, compile {{variables}}, and stamp the active span with prompt identity. Narrative guide: Prompts in the SDK. Platform workflow: Platform Prompts.
Requires Traccia platform
compile an explicit fallback body.loadPrompt()
async function loadPrompt(options: { name: string; label?: string; // default "production" version?: number; // mutually exclusive with label fallback?: Record<string, unknown>; forceRefresh?: boolean;}): Promise<LoadedPrompt>LoadedPrompt
name, type, version, versionId, labeltext / messages — uncompiled body by typeconfig — model hint from the versionisFallback, isStalecompile(vars) — substitutes {{var}}; missing required → CompileErrorspanAttributes() / applySpanAttributes() — also applied on successful compileimport { init, loadPrompt, observe } from "@traccia/sdk";
await init({ apiKey: "tr_…", endpoint: "https://api.traccia.ai/v2/traces", promptCacheTtlS: 60,});
const reply = observe({ type: "llm" })(async (question: string) => { const prompt = await loadPrompt({ name: "support-reply", label: "production", fallback: { type: "chat", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "{{question}}" }, ], }, }); const messages = prompt.compile({ question }); return callLlm(messages);});prefetchPrompts()
Warm the client cache at startup. Optional jitter spreads multi-replica stampedes.
async function prefetchPrompts( names: string[], opts?: { label?: string; jitterMs?: number },): Promise<LoadedPrompt[]>
await prefetchPrompts(["support-reply", "billing-triage"], { jitterMs: 500 });Cache, SWR, and init options
- Default TTL ~60s; key is name + label or version
- After expiry: return last good and refresh in the background (
isStale) - Fetch failure with cache → last good. Without cache →
fallbackor throwPromptFetchError
promptCacheTtlS / TRACCIA_PROMPT_CACHE_TTL_SSpan attributes
Redaction allowlists these keys. Full catalog: Span Events & Attributes.
Evaluate
Offline experiments from code. Narrative guide: Evaluate in the SDK. Also available as Traccia.evaluate.
Requires Traccia platform
evaluate()
async function evaluate(opts: EvaluateOptions): Promise<EvaluateResult>
type EvaluateOptions = { name: string; data: string | Array<Record<string, unknown>>; task: (input: any) => unknown | Promise<unknown>; scorers?: Array<string | ScorerFn>; prompt?: string; maxConcurrency?: number; // default 10 persist?: boolean; // default true providerKeys?: Record<string, string>; apiKey?: string; promptApiBase?: string; progress?: boolean; // default true onItemComplete?: (done: number, total: number, row: Record<string, unknown>) => void;};
type ScorerFn = (args: { input: unknown; output: unknown; expected?: unknown; metadata?: unknown;}) => unknown | Promise<unknown>;Parameters
name — Experiment name (required)data — Dataset name/UUID, or inline rows { input, expected, metadata }. expected_output is an alias of expected. Task always receives input only.task — (input) => output. Async is awaited.scorers — Builtin ids exact_match, contains, json_valid; platform names/ids; and/or functions.prompt — Optional prompt name for version ids and cell label (otherwise Task).maxConcurrency — Parallel workers (default 10, must be ≥ 1)persist — Create an Experiment (default true). Inline + persist creates sdk-eval/<name>/<id>.providerKeys — BYO keys for platform LLM-as-judgeprogress — Print N/M to stderr (default true)onItemComplete — (done, total, row)EvaluateResult
name, rows, aggregates, errorsurl, experimentId, datasetIdpersistError — scoring finished but save failedsummary()item_id, latency_ms, trace_id).Throws EvaluateError for configuration and API failures. Per-item failures are captured on the row.
import { init, evaluate, loadPrompt, EvaluateError } from "@traccia/sdk";
await init({ apiKey: "tr_…" });const prompt = await loadPrompt({ name: "support-reply", label: "production" });
try { const result = await evaluate({ name: "support-reply-v3", data: "support-golden", task: async (inp) => callModel(prompt.compile(inp)), scorers: ["exact_match", "Helpfulness"], prompt: "support-reply", providerKeys: { gemini: process.env.GEMINI_API_KEY! }, }); console.log(result.summary()); console.log(result.url);} catch (e) { if (e instanceof EvaluateError) throw e; throw e;}Governance
govern() requires Traccia platform
observe() works with any OTLP backend. govern() calls the Traccia agent-status API before each run. Tracing-only users should use observe().govern()
Decorator or function wrapper combining observability with runtime policy enforcement. Policy URLs default from your tracing endpoint.
import { Traccia, govern, AgentBlockedError } from "@traccia/sdk";
await Traccia.init({ apiKey: "...", endpoint: "https://api.traccia.ai/v2/traces" });
const runAgent = govern({ agentId: "my-agent", failOpen: false, name: "run_agent",})(async (prompt: string) => callLlm(prompt));disclosure()
Record Art. 50 transparency evidence on the current span after your UI informed the user.
import { disclosure } from "@traccia/sdk";
disclosure({ channel: "ui", disclosedToUser: true });governanceHooks
Register lifecycle hooks for pre/post execution and policy violations.
import { governanceHooks } from "@traccia/sdk";
governanceHooks.registerHooks({ onBeforeExecute: (span) => { /* ... */ }, onAfterExecute: (span) => { /* ... */ },});guardrailSpan()
Wrapper to track guardrail evaluations.
import { guardrailSpan } from "@traccia/sdk";
await guardrailSpan("PII_Check", async (span) => { // Evaluation logic}, { action: "block" });RedactionSpanProcessor
Automatically strips configured sensitive patterns from attributes. Registered automatically via init({ redactPii: true }).
redactString / redactAttributes
Utility functions for manual redaction.
import { redactString, redactAttributes } from "@traccia/sdk";
const safeText = redactString("Email me at user@example.com");// "Email me at [REDACTED_EMAIL]"
const safeObj = redactAttributes({ phone: "555-0199" });Span Methods
When you have a span object (from tracer.startActiveSpan or getCurrentSpan), you can use these methods:
span.setAttribute(key: string, value: any)span.addEvent(name: string, attributes?: Record<string, any>)span.recordException(exception: Error)span.setStatus(status: SpanStatus, description?: string)span.end()Next Steps
© 2026 Traccia.