API Reference

Complete API documentation for @orka-js/collector

collector()

Start the collector dashboard server. Returns a promise that resolves when the server is ready.

import { collector } from '@orka-js/collector';
const { tracer, server, stop } = await collector({
port: 3001,
host: 'localhost',
open: true,
cors: true,
maxTraces: 1000,
retentionMs: 24 * 60 * 60 * 1000, // 24 hours
});
// Later, stop the server
await stop();

Returns

PropertyTypeDescription
tracerTraceCollectorThe tracer instance (TraceCollector)
serverDevToolsServerThe Express server instance
stop() => Promise<void>Function to stop the server

Configuration

Configure the collector server with custom port, host, and other options when calling collector().

import { collector } from '@orka-js/collector';
// Start collector with custom configuration
const { tracer, server, stop } = await collector({
port: 3001, // Custom port (default: 3001)
host: 'localhost', // Custom host (default: 'localhost')
open: true, // Auto-open browser (default: false)
cors: true, // Enable CORS (default: true)
maxTraces: 1000, // Max traces to keep in memory (default: 1000)
retentionMs: 86400000, // Trace retention time in ms (default: 24h)
});
console.log(`DevTools running at http://${host}:${port}`);
// Stop the server when done
await stop();

Configuration Options

OptionTypeDefaultDescription
portnumber3001Port number for the DevTools server
hoststring'localhost'Host address to bind the server (use "0.0.0.0" for external access)
openbooleanfalseAutomatically open the dashboard in your default browser
corsbooleantrueEnable Cross-Origin Resource Sharing for API access
maxTracesnumber1000Maximum number of traces to keep in memory before eviction
retentionMsnumber86400000Trace retention time in milliseconds (24 hours by default)

Common Use Cases

Development: Use default settings with port: 3001 and {host: 'localhost'}
Docker/Remote: Set {host: '0.0.0.0'} to allow external connections
CI/CD: Set open: false to prevent browser auto-launch in headless environments
High-volume apps: Increase maxTraces and adjust retentionMs based on your needs

Remote TracingNEW

Debug production AI apps by sending traces to a central collector, then view them in real-time from anywhere.

Agent Mode (Production)

Send traces from your production app to a remote collector service.

import { collector } from '@orka-js/collector';
// Production: Send traces to remote collector
const { tracer, stop } = await collector({
source: 'remote',
mode: 'agent',
remote: {
endpoint: 'https://traces.mycompany.com',
apiKey: process.env.COLLECTOR_API_KEY,
projectId: 'my-ai-app',
environment: 'production',
sampling: 0.1 // Sample 10% of traces
}
});
// Your app runs normally - traces are sent automatically

Viewer Mode (Monitoring)

View production traces in real-time from your local machine.

import { collector } from '@orka-js/collector';
// Viewer: Watch production traces locally
const { tracer, server, stop } = await collector({
source: 'remote',
mode: 'viewer',
remote: {
endpoint: 'https://traces.mycompany.com',
apiKey: process.env.COLLECTOR_API_KEY,
projectId: 'my-ai-app',
filters: {
environment: 'production',
timeRange: 'last-1h'
}
},
port: 3001,
open: true
});
// Dashboard at localhost:3001 shows live production traces!

Remote Configuration Options

OptionTypeDescription
source'local' | 'remote'Mode: local dashboard or remote collector
mode'agent' | 'viewer'Agent sends traces, viewer receives them
remote.endpointstringRemote collector URL
remote.apiKeystringAuthentication token
remote.projectIdstringProject identifier
remote.environmentstringEnvironment tag (production, staging, etc.)
remote.samplingnumberSampling rate 0-1 (agent mode only)
remote.filtersobjectFilter traces (viewer mode only)

trace.start()

Start a new trace run. Returns a run ID that you can use with trace.end() or trace.error().

import { trace } from '@orka-js/collector';
const runId = trace.start('llm', 'generate-response', {
prompt: 'Hello, world!'
}, {
model: 'gpt-4',
temperature: 0.7
});
// ... do work ...
trace.end(runId, { content: 'Response text' });

Parameters

typeTraceRunTypeType of run (agent, llm, tool, retrieval, etc.)
namestringName of the run
input?unknownInput data (optional)
metadata?TraceMetadataAdditional metadata (optional)

trace.end()

End a trace run successfully with output data.

import { trace } from '@orka-js/collector';
const runId = trace.start('llm', 'generate', { prompt: 'Hello' });
// ... perform operation ...
const result = await llm.generate('Hello');
// End the trace with output
trace.end(runId, { content: result.content }, {
promptTokens: result.usage.promptTokens,
completionTokens: result.usage.completionTokens,
model: 'gpt-4'
});

Parameters

runIdstringThe run ID returned by trace.start()
output?unknownOutput data from the operation
metadata?TraceMetadataAdditional metadata (tokens, model, etc.)

trace.error()

End a trace run with an error. Records the error message and stack trace.

import { trace } from '@orka-js/collector';
const runId = trace.start('tool', 'web-search', { query: 'AI news' });
try {
const results = await searchTool.execute({ query: 'AI news' });
trace.end(runId, results);
} catch (error) {
// Record the error
trace.error(runId, error, {
toolName: 'web-search',
retryCount: 3
});
}

Parameters

runIdstringThe run ID returned by trace.start()
errorError | stringThe error object or message
metadata?TraceMetadataAdditional error context

trace.wrap()

Wrap an async function to automatically trace its execution. Handles start, end, and error automatically.

import { trace } from '@orka-js/collector';
const result = await trace.wrap('agent', 'research', async () => {
const agent = new ReActAgent({ llm, tools });
return agent.run("Analyze market trends");
}, {
model: 'gpt-4',
userId: 'user-123'
});

trace.session()

Create a session to group related traces together. Useful for tracking user requests or workflows.

import { trace } from '@orka-js/collector';
// Start a session for a user request
const sessionId = trace.session('User Request #123', {
userId: 'user-456',
requestType: 'research'
});
// All traces within this session are grouped
await trace.wrap('agent', 'step1', async () => {
return agent.analyze(input);
});
await trace.wrap('agent', 'step2', async () => {
return agent.synthesize(results);
});
// End the session
trace.endSession(sessionId);

Parameters

name?stringOptional session name for identification
metadata?Record<string, unknown>Additional session metadata

@Trace

TypeScript decorator for automatically tracing class methods.

import { Trace } from '@orka-js/collector';
class MyAgent {
@Trace({ type: 'agent', name: 'process' })
async process(input: string) {
// Automatically traced
return this.llm.generate(input);
}
@Trace({ type: 'llm' }) // name defaults to method name
async generateResponse(prompt: string) {
return this.llm.generate(prompt);
}
}

withTrace()

Higher-order function to wrap any function with tracing. Alternative to the @Trace decorator for non-class functions.

import { withTrace } from '@orka-js/collector';
// Wrap a function with tracing
const tracedGenerate = withTrace(
async (prompt: string) => {
return llm.generate(prompt);
},
{ type: 'llm', name: 'generate' }
);
// Use the traced function
const result = await tracedGenerate('Hello, world!');
// Works with any async function
const tracedSearch = withTrace(searchTool.execute, {
type: 'tool',
name: 'web-search'
});

createDevToolsHook()

Create a hook to integrate DevTools with the @orka-js/observability Tracer.

import { Tracer } from '@orka-js/observability';
import { createDevToolsHook, collector } from '@orka-js/collector';
// Start collector first
await collector();
// Create tracer with DevTools hook
const tracer = new Tracer({
hooks: [createDevToolsHook()]
});
// All tracer events now appear in DevTools
const trace = tracer.startTrace('my-operation');
tracer.addEvent(trace.id, { type: 'llm', name: 'generate' });
tracer.endTrace(trace.id);

TraceCollector

The central collector that manages all trace sessions, runs, and metrics. Access it via getCollector().

import { getCollector } from '@orka-js/collector';
const tracer = getCollector();
// Get all sessions
const sessions = tracer.getSessions();
console.log(`Total sessions: ${sessions.length}`);
// Get metrics summary
const metrics = tracer.getMetrics();
console.log(`Total runs: ${metrics.totalRuns}`);
console.log(`Avg latency: ${metrics.avgLatencyMs}ms`);
console.log(`Error rate: ${metrics.errorRate * 100}%`);
// Find a specific session
const session = sessions.find(s => s.name === 'User Request #123');
// Export traces as JSON
const exportData = tracer.export();
fs.writeFileSync('traces.json', JSON.stringify(exportData, null, 2));
// Import traces
tracer.import(JSON.parse(fs.readFileSync('traces.json', 'utf-8')));
// Clear all traces
tracer.clear();

Methods

getSessions()TraceSession[]Get all trace sessions
getMetrics()TraceMetricsGet aggregated metrics
export()ExportDataExport all traces as JSON
import(data)voidImport traces from JSON
clear()voidClear all traces and sessions
on(event, handler)voidSubscribe to trace events

TypeScript Types

type TraceRunType =
| 'agent'
| 'llm'
| 'tool'
| 'retrieval'
| 'chain'
| 'workflow'
| 'graph'
| 'node'
| 'embedding'
| 'custom';
interface TraceMetadata {
model?: string;
provider?: string;
promptTokens?: number;
completionTokens?: number;
totalTokens?: number;
cost?: number;
temperature?: number;
maxTokens?: number;
toolName?: string;
toolArgs?: Record<string, unknown>;
nodeId?: string;
threadId?: string;
[key: string]: unknown;
}
interface TraceRun {
id: string;
parentId?: string;
type: TraceRunType;
name: string;
startTime: number;
endTime?: number;
latencyMs?: number;
status: 'running' | 'success' | 'error';
input?: unknown;
output?: unknown;
error?: string;
metadata?: TraceMetadata;
children: TraceRun[];
}
interface TraceSession {
id: string;
name?: string;
startTime: number;
endTime?: number;
runs: TraceRun[];
metadata?: Record<string, unknown>;
}