Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 9x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 9x 9x 9x 9x 9x 10x 8x 8x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x 10x 1x 1x 1x 1x 10x 8x 8x 8x 8x 8x 8x 8x 10x 10x 10x 9x 4x 4x 4x 4x 4x 4x 4x 4x 9x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x | /**
* AgentKits — Observability / Tracing Module
*
* OpenTelemetry-compatible tracing for LLM pipelines.
* Trace LLM calls, tool executions, RAG retrievals.
* Export to console, JSON file, or OTLP endpoint.
*
* Usage:
* import { createTracer } from 'agentkits/tracing';
* const tracer = createTracer({ serviceName: 'my-agent' });
* const span = tracer.startSpan('llm.chat', { provider: 'openai' });
* span.end({ tokens: 150 });
*/
// ── Types ──────────────────────────────────────────────────────────
export type SpanKind = 'llm' | 'tool' | 'retrieval' | 'embedding' | 'internal';
export type ExportTarget = 'console' | 'json' | 'otlp';
export interface SpanAttributes {
[key: string]: string | number | boolean | undefined;
}
export interface Span {
/** Span ID */
readonly id: string;
/** Trace ID (shared across spans in same trace) */
readonly traceId: string;
/** Parent span ID */
readonly parentId?: string;
/** Span name */
readonly name: string;
/** Span kind */
readonly kind: SpanKind;
/** Start time (epoch ms) */
readonly startTime: number;
/** Add attributes to span */
setAttribute(key: string, value: string | number | boolean): void;
/** Record an error */
recordError(error: Error | string): void;
/** End the span with optional final attributes */
end(attributes?: SpanAttributes): void;
/** Duration in ms (available after end) */
readonly duration?: number;
}
export interface TraceExport {
traceId: string;
spans: Array<{
id: string;
traceId: string;
parentId?: string;
name: string;
kind: SpanKind;
startTime: number;
endTime?: number;
duration?: number;
attributes: SpanAttributes;
errors: string[];
status: 'ok' | 'error' | 'unset';
}>;
}
export interface TracerConfig {
/** Service name for trace identification */
serviceName?: string;
/** Export targets (default: ['console']) */
exportTo?: ExportTarget[];
/** OTLP endpoint URL (env: AGENTKITS_TRACE_ENDPOINT) */
otlpEndpoint?: string;
/** JSON file path for json exporter */
jsonFilePath?: string;
/** Enable/disable (default: true) */
enabled?: boolean;
/** Sample rate 0-1 (default: 1.0) */
sampleRate?: number;
}
export interface Tracer {
/** Start a new span */
startSpan(name: string, attributes?: SpanAttributes & { kind?: SpanKind; parentId?: string; traceId?: string }): Span;
/** Get all completed traces */
getTraces(): TraceExport[];
/** Flush/export all pending traces */
flush(): Promise<void>;
/** Whether tracing is enabled */
readonly enabled: boolean;
}
// ── Helpers ───────────────────────────────────────────────────────
function generateId(): string {
const bytes = new Uint8Array(8);
for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256);
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
function generateTraceId(): string {
const bytes = new Uint8Array(16);
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
// ── Internal Span ─────────────────────────────────────────────────
interface InternalSpan {
id: string;
traceId: string;
parentId?: string;
name: string;
kind: SpanKind;
startTime: number;
endTime?: number;
duration?: number;
attributes: SpanAttributes;
errors: string[];
status: 'ok' | 'error' | 'unset';
}
// ── Factory ───────────────────────────────────────────────────────
export function createTracer(config: TracerConfig = {}): Tracer {
const serviceName = config.serviceName ?? 'agentkits';
const enabled = config.enabled !== false;
const sampleRate = config.sampleRate ?? 1.0;
const exportTo = config.exportTo ?? ['console'];
const otlpEndpoint = config.otlpEndpoint ?? process.env.AGENTKITS_TRACE_ENDPOINT;
const jsonFilePath = config.jsonFilePath ?? 'traces.json';
const completedSpans: InternalSpan[] = [];
const activeSpans = new Map<string, InternalSpan>();
function shouldSample(): boolean {
if (sampleRate >= 1.0) return true;
return Math.random() < sampleRate;
}
function createNoopSpan(name: string): Span {
return {
id: '',
traceId: '',
name,
kind: 'internal',
startTime: 0,
setAttribute() {},
recordError() {},
end() {},
get duration() { return 0; },
};
}
async function exportConsole(spans: InternalSpan[]): Promise<void> {
for (const s of spans) {
const dur = s.duration != null ? `${s.duration}ms` : 'pending';
const status = s.errors.length > 0 ? '❌' : '✅';
console.log(`[${serviceName}] ${status} ${s.kind}:${s.name} (${dur}) trace=${s.traceId.slice(0, 8)}`);
if (Object.keys(s.attributes).length > 0) {
console.log(` attrs:`, s.attributes);
}
for (const err of s.errors) {
console.log(` error: ${err}`);
}
}
}
async function exportJson(spans: InternalSpan[]): Promise<void> {
try {
const fs = await import('fs');
let existing: InternalSpan[] = [];
try {
const data = fs.readFileSync(jsonFilePath, 'utf-8');
existing = JSON.parse(data);
} catch {}
existing.push(...spans);
fs.writeFileSync(jsonFilePath, JSON.stringify(existing, null, 2));
} catch {}
}
async function exportOtlp(spans: InternalSpan[]): Promise<void> {
if (!otlpEndpoint) return;
try {
const payload = {
resourceSpans: [{
resource: { attributes: [{ key: 'service.name', value: { stringValue: serviceName } }] },
scopeSpans: [{
spans: spans.map(s => ({
traceId: s.traceId,
spanId: s.id,
parentSpanId: s.parentId,
name: s.name,
kind: s.kind === 'internal' ? 1 : s.kind === 'llm' ? 3 : 2,
startTimeUnixNano: String(s.startTime * 1_000_000),
endTimeUnixNano: s.endTime ? String(s.endTime * 1_000_000) : undefined,
attributes: Object.entries(s.attributes)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => ({
key: k,
value: typeof v === 'string' ? { stringValue: v }
: typeof v === 'number' ? { intValue: String(v) }
: { boolValue: v },
})),
status: { code: s.errors.length > 0 ? 2 : 1 },
})),
}],
}],
};
await fetch(`${otlpEndpoint}/v1/traces`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
} catch {}
}
return {
startSpan(name, attrs = {}): Span {
if (!enabled || !shouldSample()) return createNoopSpan(name);
const { kind = 'internal', parentId, traceId: customTraceId, ...restAttrs } = attrs;
const id = generateId();
const traceId = customTraceId as string ?? (parentId ? activeSpans.get(parentId)?.traceId : undefined) ?? generateTraceId();
const internal: InternalSpan = {
id,
traceId,
parentId: parentId as string | undefined,
name,
kind: kind as SpanKind,
startTime: Date.now(),
attributes: restAttrs as SpanAttributes,
errors: [],
status: 'unset',
};
activeSpans.set(id, internal);
const span: Span = {
get id() { return internal.id; },
get traceId() { return internal.traceId; },
get parentId() { return internal.parentId; },
get name() { return internal.name; },
get kind() { return internal.kind; },
get startTime() { return internal.startTime; },
get duration() { return internal.duration; },
setAttribute(key, value) {
internal.attributes[key] = value;
},
recordError(error) {
const msg = error instanceof Error ? error.message : String(error);
internal.errors.push(msg);
internal.status = 'error';
},
end(finalAttrs) {
internal.endTime = Date.now();
internal.duration = internal.endTime - internal.startTime;
if (internal.status === 'unset') internal.status = 'ok';
if (finalAttrs) Object.assign(internal.attributes, finalAttrs);
activeSpans.delete(id);
completedSpans.push(internal);
},
};
return span;
},
getTraces(): TraceExport[] {
const traceMap = new Map<string, InternalSpan[]>();
for (const s of completedSpans) {
const arr = traceMap.get(s.traceId) ?? [];
arr.push(s);
traceMap.set(s.traceId, arr);
}
return Array.from(traceMap.entries()).map(([traceId, spans]) => ({ traceId, spans }));
},
async flush(): Promise<void> {
const spans = completedSpans.splice(0);
if (spans.length === 0) return;
const promises: Promise<void>[] = [];
if (exportTo.includes('console')) promises.push(exportConsole(spans));
if (exportTo.includes('json')) promises.push(exportJson(spans));
if (exportTo.includes('otlp')) promises.push(exportOtlp(spans));
await Promise.all(promises);
},
get enabled() { return enabled; },
};
}
|