Skip to main content

Overview

A Span represents a single operation in your application, such as an API call, database query, or LLM completion. Spans can be nested to form traces that represent the full execution path of a request. You typically create spans using the @span decorator or tracer.startSpan(), but you can also instantiate the Span class directly.
import { Span } from 'zeroeval';

const span = new Span('my-operation');
span.setIO({ input: 'data' }, { output: 'result' });
span.end();

Constructor

new Span(name: string, traceId?: string)

Parameters

name
string
required
The name of the span (e.g., "openai-completion", "database-query").
traceId
string
The trace ID to associate with this span. If not provided, a new UUID is generated, making this span the root of a new trace.

Properties

Read-only Properties

spanId
string
Unique identifier for this span (UUID v4).
traceId
string
The trace ID that groups related spans together.
name
string
The name of the span.
startTime
number
Timestamp when the span was created (milliseconds since epoch).

Mutable Properties

parentId
string | undefined
The span ID of the parent span, or undefined for root spans.
endTime
number | undefined
Timestamp when the span ended (milliseconds since epoch), or undefined if the span is still active.
sessionId
string | undefined
Session ID for grouping related traces across multiple requests.
sessionName
string | undefined
Human-readable name for the session.
attributes
Record<string, unknown>
Custom attributes for this span (e.g., { model: "gpt-4", temperature: 0.7 }).
tags
Record<string, string>
Tags for filtering and categorizing spans (e.g., { environment: "production" }).
inputData
string | undefined
The input data for this operation, stored as a JSON string.
outputData
string | undefined
The output data for this operation, stored as a JSON string.
error
ErrorInfo | undefined
Error information if the operation failed.
interface ErrorInfo {
  code?: string;
  message?: string;
  stack?: string;
}
status
'ok' | 'error'
The status of the span. Defaults to "ok", set to "error" when setError() is called.
signals
Record<string, Signal>
Signals (metrics) attached to this span.
interface Signal {
  value: string | boolean | number;
  type: 'boolean' | 'numerical';
}

Methods

end()

Mark the span as completed by setting the end time.
end(): void
Example:
const span = new Span('operation');
// ... do work ...
span.end();

setIO()

Set the input and/or output data for this span. Values are automatically serialized to JSON if they are not already strings.
setIO(input?: unknown, output?: unknown): void

Parameters

input
unknown
The input data for this operation. Can be any JSON-serializable value.
output
unknown
The output data for this operation. Can be any JSON-serializable value.
Example:
span.setIO(
  { query: 'What is the weather?' },
  { answer: 'The weather is sunny.' }
);

setError()

Mark the span as failed and record error information. This automatically sets status to "error".
setError(info: ErrorInfo): void

Parameters

info
ErrorInfo
required
Error information to record
Example:
try {
  // ... operation ...
} catch (error) {
  span.setError({
    message: error.message,
    stack: error.stack
  });
}

addSignal()

Attach a signal (metric) to this span. Signals are used for tracking custom metrics like accuracy, latency, or cost.
addSignal(
  name: string,
  value: string | boolean | number,
  type?: 'boolean' | 'numerical'
): void

Parameters

name
string
required
The name of the signal (e.g., "accuracy", "cost").
value
string | boolean | number
required
The value of the signal.
type
'boolean' | 'numerical'
The type of signal. If not provided, the type is auto-detected from the value.
Example:
span.addSignal('accuracy', 0.95, 'numerical');
span.addSignal('is_cached', true, 'boolean');
span.addSignal('model_version', 'v2.1'); // Type auto-detected

durationMs

Get the duration of the span in milliseconds.
get durationMs(): number | undefined
Returns: The duration in milliseconds, or undefined if the span hasn’t ended yet. Example:
span.end();
console.log(`Operation took ${span.durationMs}ms`);

toJSON()

Serialize the span to a JSON-compatible object for sending to the backend.
toJSON(): Record<string, unknown>
Example:
const json = span.toJSON();
console.log(json);
// {
//   span_id: "...",
//   trace_id: "...",
//   name: "operation",
//   start_time: "2024-03-03T12:00:00.000Z",
//   end_time: "2024-03-03T12:00:01.000Z",
//   duration_ms: 1000,
//   ...
// }

Usage Patterns

Manual span creation

import { tracer, Span } from 'zeroeval';

const span = tracer.startSpan('my-operation');
try {
  const result = await doWork();
  span.setIO({ input: 'data' }, { output: result });
} catch (error) {
  span.setError({
    message: error.message,
    stack: error.stack
  });
  throw error;
} finally {
  tracer.endSpan(span);
}

Adding metadata

const span = tracer.startSpan('llm-completion', {
  attributes: {
    model: 'gpt-4',
    temperature: 0.7,
    max_tokens: 1000
  },
  tags: {
    environment: 'production',
    version: '1.0'
  }
});

Tracking custom metrics

span.addSignal('token_count', 150, 'numerical');
span.addSignal('cache_hit', true, 'boolean');
span.addSignal('cost_usd', 0.003, 'numerical');

Notes

  • Spans are automatically linked to their parent via parentId when created with tracer.startSpan()
  • The inputData and outputData fields are stored as JSON strings internally
  • Signals support auto-type detection: booleans, numbers, and string representations of numbers are automatically typed
  • Span IDs and trace IDs are UUID v4 strings

Build docs developers (and LLMs) love