74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
import {
|
|
SpanStatusCode,
|
|
trace,
|
|
type Attributes,
|
|
type Span,
|
|
} from '@opentelemetry/api';
|
|
|
|
import { getServiceName } from '../config.js';
|
|
|
|
function compactAttributes(attributes?: Attributes): Attributes {
|
|
if (!attributes) {
|
|
return {};
|
|
}
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(attributes).filter(([, value]) => value !== undefined),
|
|
);
|
|
}
|
|
|
|
export async function withSpan<T>(
|
|
name: string,
|
|
attributes: Attributes | undefined,
|
|
fn: (span: Span) => Promise<T> | T,
|
|
): Promise<T> {
|
|
const tracer = trace.getTracer(getServiceName());
|
|
return tracer.startActiveSpan(name, async (span) => {
|
|
span.setAttributes(compactAttributes(attributes));
|
|
try {
|
|
const result = await fn(span);
|
|
span.setStatus({ code: SpanStatusCode.OK });
|
|
return result;
|
|
} catch (error) {
|
|
span.setStatus({
|
|
code: SpanStatusCode.ERROR,
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
span.recordException(error instanceof Error ? error : new Error(String(error)));
|
|
throw error;
|
|
} finally {
|
|
span.end();
|
|
}
|
|
});
|
|
}
|
|
|
|
export function withSkillSpan<T>(
|
|
skillName: string,
|
|
attributes: Attributes | undefined,
|
|
fn: (span: Span) => Promise<T> | T,
|
|
): Promise<T> {
|
|
return withSpan(`skill.${skillName}.handle`, attributes, fn);
|
|
}
|
|
|
|
export function withClassifierSpan<T>(
|
|
attributes: Attributes | undefined,
|
|
fn: (span: Span) => Promise<T> | T,
|
|
): Promise<T> {
|
|
return withSpan('classifier.run', attributes, fn);
|
|
}
|
|
|
|
export function withToolSpan<T>(
|
|
toolName: string,
|
|
attributes: Attributes | undefined,
|
|
fn: (span: Span) => Promise<T> | T,
|
|
): Promise<T> {
|
|
return withSpan(`tool.${toolName}`, attributes, fn);
|
|
}
|
|
|
|
export function withLlmSpan<T>(
|
|
attributes: Attributes | undefined,
|
|
fn: (span: Span) => Promise<T> | T,
|
|
): Promise<T> {
|
|
return withSpan('llm.chat_completion', attributes, fn);
|
|
}
|