Skip to content

TypeScript Types

The Ladger SDK is written in TypeScript and provides full type definitions. This page documents all exported types.

Importing Types

import type {
LadgerConfig,
LadgerSpan,
SpanOptions,
SpanAttributes,
CostEvent,
SerializedSpan,
} from '@ladger/sdk';

LadgerConfig

Configuration options for the LadgerTracer constructor.

interface LadgerConfig {
/**
* API key for authentication.
* Must start with 'ladger_'
* @example 'ladger_sk_live_abc123...'
*/
apiKey: string;
/**
* Flow name to group traces under.
* All spans will be associated with this flow.
* @example 'customer-support-agent'
*/
flowName: string;
/**
* Project URL for the Ladger API.
* @default 'https://ladger.pages.dev/api'
* @example 'https://ladger.your-company.com/api'
*/
projectUrl?: string;
/**
* Number of spans to batch before sending.
* @default 10
*/
batchSize?: number;
/**
* Auto-flush interval in milliseconds.
* @default 5000
*/
flushInterval?: number;
/**
* Enable debug logging to console.
* @default false
*/
debug?: boolean;
}

Usage

const config: LadgerConfig = {
apiKey: process.env.LADGER_API_KEY!,
flowName: 'my-chatbot',
projectUrl: 'https://ladger.pages.dev/api',
batchSize: 20,
flushInterval: 10000,
debug: true,
};
const tracer = new LadgerTracer(config);

LadgerSpan

Interface representing a span instance returned by startSpan().

interface LadgerSpan {
/** Unique span identifier */
id: string;
/** Human-readable span name */
name: string;
/** Parent span ID (if any) */
parentId?: string;
/** Start timestamp in milliseconds */
startTime: number;
/** End timestamp in milliseconds (set when span.end() is called) */
endTime?: number;
/** Custom attributes */
attributes: SpanAttributes;
/** Cost event (if recorded) */
costEvent?: CostEvent;
/** Set attributes on the span */
setAttributes(attrs: SpanAttributes): void;
/** Record a cost event */
recordCost(cost: CostEvent): void;
/** End the span and queue for export */
end(): void;
}

Usage

function processSpan(span: LadgerSpan) {
console.log('Span ID:', span.id);
console.log('Duration:', span.endTime! - span.startTime, 'ms');
console.log('Attributes:', span.attributes);
}

SpanOptions

Options for creating a span via startSpan().

interface SpanOptions {
/**
* Parent span for creating trace hierarchies.
* Pass a LadgerSpan to make the new span a child.
*/
parent?: LadgerSpan;
}

Usage

const parent = tracer.startSpan('parent-operation');
const child = tracer.startSpan('child-operation', {
parent
} satisfies SpanOptions);

SpanAttributes

Flexible key-value attributes that can be attached to spans.

interface SpanAttributes {
[key: string]: string | number | boolean | undefined;
}

Allowed Value Types

TypeExample
string'user-123'
number150
booleantrue
undefinedundefined (removes key)

Usage

const attrs: SpanAttributes = {
'user.id': 'user-123',
'request.type': 'chat',
'prompt.tokens': 150,
'is_premium': true,
'optional.field': undefined,
};
span.setAttributes(attrs);

Naming Conventions

// Recommended attribute naming
const attributes: SpanAttributes = {
// User context
'user.id': 'user-123',
'user.tier': 'premium',
// Request metadata
'request.method': 'POST',
'request.path': '/api/chat',
// AI-specific
'prompt.length': 500,
'prompt.system_length': 100,
'response.length': 200,
// Model config
'model.temperature': 0.7,
'model.max_tokens': 1000,
// Error info
'error.type': 'RateLimitError',
'error.message': 'Too many requests',
};

CostEvent

Cost and usage data for AI API calls.

interface CostEvent {
/**
* AI provider name.
* @example 'openai', 'anthropic', 'google'
*/
provider: string;
/**
* Model identifier.
* @example 'gpt-4o', 'claude-3-opus', 'gemini-pro'
*/
model: string;
/**
* Number of input/prompt tokens.
*/
inputTokens?: number;
/**
* Number of output/completion tokens.
*/
outputTokens?: number;
/**
* Cost in USD.
* If not provided, Ladger estimates based on tokens.
*/
costUsd?: number;
}

Usage

const cost: CostEvent = {
provider: 'openai',
model: 'gpt-4o',
inputTokens: 150,
outputTokens: 50,
costUsd: 0.0015,
};
span.recordCost(cost);

SerializedSpan

Serialized span format for API transport.

interface SerializedSpan {
id: string;
name: string;
parentId?: string;
startTime: number;
endTime?: number;
attributes: SpanAttributes;
costEvent?: CostEvent;
}

This is the format sent to the /v1/ingest endpoint.

Example Payload

{
"flowName": "my-chatbot",
"sessionId": "sess-lz4k2m8-abc123",
"spans": [
{
"id": "lz4k2m8-def456",
"name": "chat-completion",
"startTime": 1705123456789,
"endTime": 1705123457123,
"attributes": {
"user.id": "user-123"
},
"costEvent": {
"provider": "openai",
"model": "gpt-4o",
"inputTokens": 150,
"outputTokens": 50
}
}
]
}

Type Guards

Helper functions for runtime type checking:

function isCostEvent(obj: unknown): obj is CostEvent {
return (
typeof obj === 'object' &&
obj !== null &&
'provider' in obj &&
'model' in obj
);
}
function isSpanAttributes(obj: unknown): obj is SpanAttributes {
if (typeof obj !== 'object' || obj === null) return false;
for (const value of Object.values(obj)) {
if (
value !== undefined &&
typeof value !== 'string' &&
typeof value !== 'number' &&
typeof value !== 'boolean'
) {
return false;
}
}
return true;
}

Generic Types

The trace() method is generic:

class LadgerTracer {
trace<T>(
name: string,
fn: (span: LadgerSpan) => Promise<T>,
options?: SpanOptions
): Promise<T>;
}

Usage

// Return type is inferred as string
const response = await tracer.trace('chat', async (span) => {
return 'Hello, world!';
});
// Explicit type annotation
const data = await tracer.trace<{ message: string; tokens: number }>(
'process',
async (span) => {
return { message: 'Hello', tokens: 5 };
}
);