|
| 1 | +// tracing/tracer.ts |
| 2 | + |
| 3 | +import { Trace } from './traces'; |
| 4 | +import { Step, UserCallStep, ChatCompletionStep } from './steps'; |
| 5 | +import { StepType } from './enums'; |
| 6 | +import Openlayer from '../../index'; |
| 7 | + |
| 8 | +let currentTrace: Trace | null = null; |
| 9 | + |
| 10 | +const publish = process.env['OPENLAYER_DISABLE_PUBLISH'] != 'true'; |
| 11 | +let client: Openlayer | null = null; |
| 12 | +if (publish) { |
| 13 | + console.log('Publishing is enabled'); |
| 14 | + client = new Openlayer(); |
| 15 | +} |
| 16 | + |
| 17 | +function getCurrentTrace(): Trace | null { |
| 18 | + return currentTrace; |
| 19 | +} |
| 20 | + |
| 21 | +function setCurrentTrace(trace: Trace | null) { |
| 22 | + currentTrace = trace; |
| 23 | +} |
| 24 | + |
| 25 | +// Function to create a new step |
| 26 | +const stepStack: Step[] = []; |
| 27 | + |
| 28 | +function createStep( |
| 29 | + name: string, |
| 30 | + stepType: StepType = StepType.USER_CALL, |
| 31 | + inputs?: any, |
| 32 | + output?: any, |
| 33 | + metadata: Record<string, any> | null = null, |
| 34 | +): [Step, () => void] { |
| 35 | + metadata = metadata || {}; |
| 36 | + let newStep: Step; |
| 37 | + if (stepType === StepType.CHAT_COMPLETION) { |
| 38 | + newStep = new ChatCompletionStep(name, inputs, output, metadata); |
| 39 | + } else { |
| 40 | + newStep = new UserCallStep(name, inputs, output, metadata); |
| 41 | + } |
| 42 | + newStep.startTime = performance.now(); |
| 43 | + |
| 44 | + const parentStep = getCurrentStep(); |
| 45 | + const isRootStep = parentStep === null; |
| 46 | + |
| 47 | + if (isRootStep) { |
| 48 | + console.log('Starting a new trace...'); |
| 49 | + console.log(`Adding step ${name} as the root step`); |
| 50 | + const currentTrace = new Trace(); |
| 51 | + setCurrentTrace(currentTrace); |
| 52 | + currentTrace.addStep(newStep); |
| 53 | + } else { |
| 54 | + console.log(`Adding step ${name} as a nested step to ${parentStep!.name}`); |
| 55 | + currentTrace = getCurrentTrace()!; |
| 56 | + parentStep!.addNestedStep(newStep); |
| 57 | + } |
| 58 | + |
| 59 | + stepStack.push(newStep); |
| 60 | + |
| 61 | + const endStep = () => { |
| 62 | + newStep.endTime = performance.now(); |
| 63 | + newStep.latency = newStep.endTime - newStep.startTime; |
| 64 | + |
| 65 | + stepStack.pop(); // Remove the current step from the stack |
| 66 | + |
| 67 | + if (isRootStep) { |
| 68 | + console.log('Ending the trace...'); |
| 69 | + const traceData = getCurrentTrace(); |
| 70 | + // Post process trace and get the input variable names |
| 71 | + const { traceData: processedTraceData, inputVariableNames } = postProcessTrace(traceData!); |
| 72 | + console.log('Processed trace data:', JSON.stringify(processedTraceData, null, 2)); |
| 73 | + console.log('Input variable names:', inputVariableNames); |
| 74 | + |
| 75 | + if (publish && process.env['OPENLAYER_INFERENCE_PIPELINE_ID']) { |
| 76 | + client!.inferencePipelines.data.stream(process.env['OPENLAYER_INFERENCE_PIPELINE_ID'], { |
| 77 | + config: { |
| 78 | + outputColumnName: 'output', |
| 79 | + inputVariableNames: inputVariableNames, |
| 80 | + groundTruthColumnName: 'groundTruth', |
| 81 | + latencyColumnName: 'latency', |
| 82 | + costColumnName: 'cost', |
| 83 | + timestampColumnName: 'inferenceTimestamp', |
| 84 | + inferenceIdColumnName: 'inferenceId', |
| 85 | + numOfTokenColumnName: 'tokens', |
| 86 | + }, |
| 87 | + rows: [processedTraceData], |
| 88 | + }); |
| 89 | + } |
| 90 | + console.log('Trace data ready for upload:', JSON.stringify(traceData, null, 2)); |
| 91 | + |
| 92 | + // Reset the entire trace state |
| 93 | + setCurrentTrace(null); |
| 94 | + stepStack.length = 0; // Clear the step stack |
| 95 | + } else { |
| 96 | + console.log(`Ending step ${name}`); |
| 97 | + } |
| 98 | + }; |
| 99 | + |
| 100 | + return [newStep, endStep]; |
| 101 | +} |
| 102 | + |
| 103 | +function getCurrentStep(): Step | null | undefined { |
| 104 | + const currentStep = stepStack.length > 0 ? stepStack[stepStack.length - 1] : null; |
| 105 | + return currentStep; |
| 106 | +} |
| 107 | + |
| 108 | +function getParamNames(func: Function): string[] { |
| 109 | + const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm; |
| 110 | + const ARGUMENT_NAMES = /([^\s,]+)/g; |
| 111 | + const fnStr = func.toString().replace(STRIP_COMMENTS, ''); |
| 112 | + const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); |
| 113 | + return result || []; |
| 114 | +} |
| 115 | + |
| 116 | +// Higher-order function to trace synchronous or asynchronous functions |
| 117 | +function trace(fn: Function, stepType: StepType = StepType.USER_CALL, stepName?: string): Function { |
| 118 | + return async function (...args: any[]) { |
| 119 | + const name = stepName || fn.name; |
| 120 | + const paramNames = getParamNames(fn); |
| 121 | + const inputs = Object.fromEntries(paramNames.map((name, index) => [name, args[index]])); |
| 122 | + const [step, endStep] = createStep(name, stepType, args); |
| 123 | + |
| 124 | + try { |
| 125 | + const result = await fn(...args); |
| 126 | + step.log({ inputs, output: result }); |
| 127 | + return result; |
| 128 | + } catch (error: any) { |
| 129 | + step.log({ inputs, metadata: { error: error.message } }); |
| 130 | + throw error; |
| 131 | + } finally { |
| 132 | + endStep(); |
| 133 | + } |
| 134 | + }; |
| 135 | +} |
| 136 | + |
| 137 | +// Example usage of specialized function to add a chat completion step |
| 138 | +export function addChatCompletionStepToTrace( |
| 139 | + name: string, |
| 140 | + inputs: any, |
| 141 | + output: any, |
| 142 | + metadata?: Record<string, any>, |
| 143 | +) { |
| 144 | + const [step, endStep] = createStep(name, StepType.CHAT_COMPLETION, inputs, output, metadata); |
| 145 | + step.log({ inputs, output }); |
| 146 | + endStep(); |
| 147 | +} |
| 148 | + |
| 149 | +function postProcessTrace(traceObj: Trace): { traceData: any; inputVariableNames: string[] } { |
| 150 | + const rootStep = traceObj.steps[0]; |
| 151 | + |
| 152 | + const input_variables = rootStep!.inputs; |
| 153 | + const inputVariableNames = input_variables ? Object.keys(input_variables) : []; |
| 154 | + |
| 155 | + const processed_steps = traceObj.toJSON(); |
| 156 | + |
| 157 | + const traceData = { |
| 158 | + inferenceTimestamp: Date.now(), |
| 159 | + inferenceId: rootStep!.id.toString(), |
| 160 | + output: rootStep!.output, |
| 161 | + groundTruth: rootStep!.groundTruth, |
| 162 | + latency: rootStep!.latency, |
| 163 | + cost: 0, // fix |
| 164 | + tokens: 0, // fix |
| 165 | + steps: processed_steps, |
| 166 | + }; |
| 167 | + |
| 168 | + if (input_variables) { |
| 169 | + Object.assign(traceData, input_variables); |
| 170 | + } |
| 171 | + |
| 172 | + return { traceData, inputVariableNames }; |
| 173 | +} |
| 174 | + |
| 175 | +export default trace; |
0 commit comments