Skip to main content

Tracer Core

@accordkit/tracer is the foundation of the AccordKit SDK. It provides the Tracer class, event helpers, middleware support, and sinks for delivering JSONL traces.

Constructing a tracer

src/tracer.ts
import { FileSink, Tracer } from '@accordkit/tracer';

const tracer = new Tracer({
sink: new FileSink({ delivery: 'buffered' }),
defaultLevel: 'info',
service: 'support-bot',
env: 'dev',
});

Options

OptionTypeDescription
sinkSink | BufferedSinkRequired destination for emitted events.
middlewares?TraceMiddleware[]Transform, enrich, sample, or drop events before they reach the sink.
sessionId?stringOverride the auto-generated session identifier.
defaultLevel?'debug' | 'info' | 'warn' | 'error'Default level stamped on events ('info' by default).
service?/env?/region?stringTags propagated to every event.

Emitting events

src/events.ts
await tracer.message({ role: 'user', content: 'Trace me.' });
await tracer.toolCall({ tool: 'search', input: { query: 'AccordKit' } });
await tracer.toolResult({ tool: 'search', output: { hits: 5 }, ok: true, latencyMs: 42 });
await tracer.usage({ inputTokens: 120, outputTokens: 48, cost: 0.0025 });

Each helper injects timestamps, a trace context, the configured level, and service/environment tags.

Working with spans

src/spans.ts
const request = tracer.spanStart({ operation: 'http.request', attrs: { path: '/chat' } });

const db = tracer.spanStart({ operation: 'db.query', parent: request });
// ... query ...
await tracer.spanEnd(db, { attrs: { rows: 3 } });

await tracer.spanEnd(request, { status: 'ok' });
  • spanStart returns a token { ctx, operation, t0, attrs? }.
  • Passing parent (a SpanToken or { traceId, spanId }) keeps spans on the same trace.
  • spanEnd computes durationMs, merges attributes, and marks status ('ok' by default).
  • Call tracer.flush() / tracer.close() to drain sinks that buffer.

Middleware examples

src/middleware.ts
import type { TraceMiddleware } from '@accordkit/tracer';

const sampler: TraceMiddleware = (event) => (Math.random() < 0.25 ? event : null);

const tagModel: TraceMiddleware = (event) => {
if (event.provider && !event.model) {
event.model = 'fallback-model';
}
return event;
};

const tracer = new Tracer({
sink: new FileSink(),
middlewares: [sampler, tagModel],
});
  • Middleware can be synchronous or async.
  • Returning null drops the event (useful for sampling).
  • The helper sample(rate) in @accordkit/tracer/core/middleware produces the sampling middleware above.

Utilities

  • newTraceCtx(parentSpanId?) creates a fresh trace context when you need to emit events manually.
  • randomId(prefix?) builds AccordKit-style IDs (tr_…, sp_…).
  • resolveIngestEndpoint({ baseUrl?, region? }) constructs URLs such as https://api.accordkit.dev/auto/ingest for use with the HTTP sink or other tooling.