@lmnr-ai/lmnr 0.4.9-alpha → 0.4.10-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@ var require_package = __commonJS({
35
35
  "package.json"(exports2, module2) {
36
36
  module2.exports = {
37
37
  name: "@lmnr-ai/lmnr",
38
- version: "0.4.9-alpha",
38
+ version: "0.4.10-alpha",
39
39
  description: "TypeScript SDK for Laminar AI",
40
40
  main: "dist/index.js",
41
41
  types: "dist/index.d.ts",
@@ -88,7 +88,6 @@ var require_package = __commonJS({
88
88
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.53.0",
89
89
  "@opentelemetry/exporter-trace-otlp-proto": "^0.53.0",
90
90
  "@opentelemetry/instrumentation": "^0.53.0",
91
- "@opentelemetry/resources": "^1.26.0",
92
91
  "@opentelemetry/sdk-node": "^0.53.0",
93
92
  "@opentelemetry/sdk-trace-base": "^1.26.0",
94
93
  "@opentelemetry/sdk-trace-node": "^1.26.0",
@@ -145,14 +144,10 @@ var InitializationError = class extends TraceloopError {
145
144
  };
146
145
 
147
146
  // src/sdk/tracing/index.ts
148
- var import_sdk_node = require("@opentelemetry/sdk-node");
149
147
  var import_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
150
148
  var import_core = require("@opentelemetry/core");
151
149
  var import_api2 = require("@opentelemetry/api");
152
150
  var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
153
- var import_resources = require("@opentelemetry/resources");
154
- var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
155
- var import_resources2 = require("@opentelemetry/resources");
156
151
 
157
152
  // src/sdk/tracing/tracing.ts
158
153
  var import_api = require("@opentelemetry/api");
@@ -240,6 +235,8 @@ var Telemetry = _Telemetry;
240
235
 
241
236
  // src/sdk/tracing/index.ts
242
237
  var import_ai_semantic_conventions = require("@traceloop/ai-semantic-conventions");
238
+ var import_sdk_trace_node2 = require("@opentelemetry/sdk-trace-node");
239
+ var import_instrumentation = require("@opentelemetry/instrumentation");
243
240
  var import_instrumentation_anthropic = require("@traceloop/instrumentation-anthropic");
244
241
  var import_instrumentation_openai = require("@traceloop/instrumentation-openai");
245
242
  var import_instrumentation_azure = require("@traceloop/instrumentation-azure");
@@ -251,7 +248,6 @@ var import_instrumentation_pinecone = require("@traceloop/instrumentation-pineco
251
248
  var import_instrumentation_langchain = require("@traceloop/instrumentation-langchain");
252
249
  var import_instrumentation_chromadb = require("@traceloop/instrumentation-chromadb");
253
250
  var import_instrumentation_qdrant = require("@traceloop/instrumentation-qdrant");
254
- var _sdk;
255
251
  var _spanProcessor;
256
252
  var openAIInstrumentation;
257
253
  var anthropicInstrumentation;
@@ -388,16 +384,6 @@ var manuallyInitInstrumentations = (instrumentModules) => {
388
384
  qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);
389
385
  }
390
386
  };
391
- function awaitAttributes(detector) {
392
- return {
393
- async detect(config) {
394
- var _a;
395
- const resource = detector.detect(config);
396
- await ((_a = resource.waitForAsyncAttributes) == null ? void 0 : _a.call(resource));
397
- return resource;
398
- }
399
- };
400
- }
401
387
  var startTracing = (options) => {
402
388
  var _a, _b;
403
389
  if (options.instrumentModules !== void 0) {
@@ -459,28 +445,13 @@ var startTracing = (options) => {
459
445
  processor: options.disableBatch ? "simple" : "batch"
460
446
  });
461
447
  }
462
- const spanProcessors = [_spanProcessor];
463
- if (options.processor) {
464
- spanProcessors.push(options.processor);
465
- }
466
- _sdk = new import_sdk_node.NodeSDK({
467
- resource: new import_resources.Resource({
468
- [import_semantic_conventions.SEMRESATTRS_SERVICE_NAME]: options.appName || process.env.npm_package_name
469
- }),
470
- spanProcessors,
471
- contextManager: options.contextManager,
472
- textMapPropagator: options.propagator,
473
- traceExporter,
448
+ const provider = new import_sdk_trace_node2.NodeTracerProvider();
449
+ provider.addSpanProcessor(_spanProcessor);
450
+ provider.register();
451
+ (0, import_instrumentation.registerInstrumentations)({
474
452
  instrumentations,
475
- // We should re-consider removing irrelevant spans here in the future
476
- // sampler: new TraceloopSampler(),
477
- resourceDetectors: [
478
- awaitAttributes(import_resources2.envDetectorSync),
479
- awaitAttributes(import_resources2.processDetectorSync),
480
- awaitAttributes(import_resources2.hostDetectorSync)
481
- ]
453
+ tracerProvider: provider
482
454
  });
483
- _sdk.start();
484
455
  };
485
456
  var shouldSendTraces = () => {
486
457
  if (!_configuration) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/index.ts","../src/laminar.ts","../src/sdk/errors/index.ts","../src/sdk/tracing/index.ts","../src/sdk/tracing/tracing.ts","../src/sdk/telemetry/telemetry.ts","../src/sdk/configuration/index.ts","../src/sdk/tracing/decorators.ts","../src/sdk/tracing/manual.ts","../src/sdk/tracing/association.ts","../src/utils.ts","../src/evaluations.ts","../src/decorators.ts"],"sourcesContent":["{\n \"name\": \"@lmnr-ai/lmnr\",\n \"version\": \"0.4.9-alpha\",\n \"description\": \"TypeScript SDK for Laminar AI\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/lmnr-ai/lmnr-ts.git\"\n },\n \"keywords\": [\n \"laminar\",\n \"lmnr\",\n \"sdk\",\n \"lmnr.ai\"\n ],\n \"author\": \"founders@lmnr.ai\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/lmnr-ai/lmnr-ts/issues\"\n },\n \"homepage\": \"https://github.com/lmnr-ai/lmnr-ts#README\",\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@aws-sdk/client-bedrock-runtime\": \"^3.649.0\",\n \"@azure/openai\": \"2.0.0-beta.2\",\n \"@google-cloud/aiplatform\": \"^3.29.0\",\n \"@google-cloud/vertexai\": \"^1.7.0\",\n \"@langchain/core\": \"^0.2.32\",\n \"@pinecone-database/pinecone\": \"^3.0.2\",\n \"@qdrant/js-client-rest\": \"^1.11.0\",\n \"@types/node\": \"^22.5.4\",\n \"@types/uuid\": \"^10.0.0\",\n \"bufferutil\": \"^4.0.8\",\n \"chromadb\": \"^1.8.1\",\n \"cohere-ai\": \"^7.13.0\",\n \"langchain\": \"^0.2.18\",\n \"llamaindex\": \"^0.5.23\",\n \"openai\": \"^4.58.2\",\n \"runnables\": \"link:@langchain/core/runnables\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vectorstores\": \"link:@langchain/core/vectorstores\"\n },\n \"dependencies\": {\n \"@grpc/grpc-js\": \"^1.11.2\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/core\": \"^1.26.0\",\n \"@opentelemetry/exporter-trace-otlp-grpc\": \"^0.53.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.53.0\",\n \"@opentelemetry/instrumentation\": \"^0.53.0\",\n \"@opentelemetry/resources\": \"^1.26.0\",\n \"@opentelemetry/sdk-node\": \"^0.53.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.26.0\",\n \"@opentelemetry/sdk-trace-node\": \"^1.26.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.27.0\",\n \"@traceloop/ai-semantic-conventions\": \"^0.11.0\",\n \"@traceloop/instrumentation-anthropic\": \"^0.11.1\",\n \"@traceloop/instrumentation-azure\": \"^0.11.1\",\n \"@traceloop/instrumentation-bedrock\": \"^0.11.1\",\n \"@traceloop/instrumentation-chromadb\": \"^0.11.1\",\n \"@traceloop/instrumentation-cohere\": \"^0.11.1\",\n \"@traceloop/instrumentation-langchain\": \"^0.11.1\",\n \"@traceloop/instrumentation-llamaindex\": \"^0.11.1\",\n \"@traceloop/instrumentation-openai\": \"^0.11.1\",\n \"@traceloop/instrumentation-pinecone\": \"^0.11.1\",\n \"@traceloop/instrumentation-qdrant\": \"^0.11.1\",\n \"@traceloop/instrumentation-vertexai\": \"^0.11.1\",\n \"posthog-node\": \"^4.2.0\",\n \"uuid\": \"^10.0.0\"\n }\n}","\nexport {\n NodeInput,\n PipelineRunResponse,\n PipelineRunRequest,\n ChatMessage,\n Event,\n EvaluateEvent,\n} from './types';\n\nexport { Laminar } from './laminar';\nexport { Evaluation, Dataset, Datapoint } from './evaluations';\nexport { observe } from './decorators';\n","import { PipelineRunResponse, PipelineRunRequest, EvaluationDatapoint, EvaluationStatus } from './types';\nimport { Attributes, AttributeValue, context, createContextKey, isSpanContextValid, TimeInput, trace } from '@opentelemetry/api';\nimport { InitializeOptions, initialize as traceloopInitialize } from './sdk/node-server-sdk'\nimport { otelSpanIdToUUID, otelTraceIdToUUID } from './utils';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { Metadata } from '@grpc/grpc-js';\nimport { ASSOCIATION_PROPERTIES_KEY } from './sdk/tracing/tracing';\nimport { forceFlush } from './sdk/node-server-sdk';\n\n// quick patch to get the traceloop's default tracer, since their \n// `getTracer` function is not exported.\n// Another option would be to import directly \n// like so: `import { getTracer } from '@traceloop/node-server-sdk/dist/src/lib/tracing/tracing';`\n// which isn't too nice either.\nconst DEFAULT_TRACER_NAME = 'traceloop.tracer';\n\ninterface LaminarInitializeProps {\n projectApiKey?: string;\n env?: Record<string, string>;\n baseUrl?: string;\n instrumentModules?: InitializeOptions[\"instrumentModules\"];\n}\n\nexport class Laminar {\n private static baseUrl: string = 'https://api.lmnr.ai:8443';\n private static projectApiKey: string;\n private static env: Record<string, string> = {};\n private static isInitialized: boolean = false;\n\n /**\n * Initialize Laminar context across the application.\n * This method must be called before using any other Laminar methods or decorators.\n *\n * @param project_api_key - Laminar project api key. You can generate one by going\n * to the projects settings page on the Laminar dashboard.\n * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable.\n * @param env - Default environment passed to `run` and `evaluateEvent` requests,\n * unless overriden at request time. Usually, model provider keys are stored here.\n * @param baseUrl - Url of Laminar endpoint, or the custom open telemetry ingester.\n * If not specified, defaults to https://api.lmnr.ai:8443. For locally hosted Laminar,\n * default setting must be http://localhost:8001.\n * @param instrumentModules - List of modules to instrument.\n * If not specified, all auto-instrumentable modules will be instrumented, which include\n * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n * Pass an empty object {} to disable any kind of automatic instrumentation.\n * If you only want to auto-instrument specific modules, then pass them in the object.\n * \n * Example:\n * ```typescript\n * import { Laminar as L } from '@lmnr-ai/lmnr';\n * import { OpenAI } from 'openai';\n * import * as ChainsModule from \"langchain/chains\";\n * \n * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules.\n * L.initialize({ projectApiKey: \"<LMNR_PROJECT_API_KEY>\", instrumentModules: {\n * langchain: {\n * chainsModule: ChainsModule\n * },\n * openAI: OpenAI\n * } });\n * ```\n *\n * @throws {Error} - If project API key is not set\n */\n public static initialize({\n projectApiKey,\n env,\n baseUrl,\n instrumentModules\n }: LaminarInitializeProps) {\n\n let key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n if (key === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n this.projectApiKey = key;\n if (baseUrl) {\n this.baseUrl = baseUrl;\n }\n this.isInitialized = true;\n this.env = env ?? {};\n\n const metadata = new Metadata();\n metadata.set('authorization', `Bearer ${this.projectApiKey}`);\n const exporter = new OTLPTraceExporter({\n url: this.baseUrl,\n metadata,\n });\n\n traceloopInitialize({\n exporter,\n silenceInitializationMessage: true,\n instrumentModules,\n disableBatch: false,\n });\n }\n\n /**\n * Check if Laminar has been initialized. Utility to make sure other methods\n * are called after initialization.\n */\n public static initialized(): boolean {\n return this.isInitialized;\n }\n\n /**\n * Sets the environment that will be sent to Laminar requests.\n * \n * @param env - The environment variables to override. If not provided, the current environment will not be modified.\n */\n public static setEnv(env?: Record<string, string>) {\n if (env) {\n this.env = env;\n }\n }\n\n /**\n * Sets the project API key for authentication with Laminar.\n *\n * @param projectApiKey - The API key to be set. If not provided, the existing API key will not be modified.\n */\n public static setProjectApiKey(projectApiKey?: string) {\n if (projectApiKey) {\n this.projectApiKey = projectApiKey;\n }\n }\n\n /**\n * Runs the pipeline with the given inputs\n *\n * @param pipeline - The name of the Laminar pipeline. Pipeline must have a target version.\n * @param inputs - The inputs for the pipeline. Map from an input node name to input data.\n * @param env - The environment variables for the pipeline execution. Typically used for model provider keys.\n * @param metadata - Additional metadata for the pipeline run.\n * @param currentSpanId - The ID of the current span.\n * @param currentTraceId - The ID of the current trace.\n * @returns A promise that resolves to the response of the pipeline run.\n * @throws An error if the Laminar object is not initialized with a project API key. Or if the request fails.\n */\n public static async run({\n pipeline,\n inputs,\n env,\n metadata = {},\n currentSpanId,\n currentTraceId,\n }: PipelineRunRequest): Promise<PipelineRunResponse> {\n const currentSpan = trace.getActiveSpan();\n let parentSpanId: string | undefined;\n let traceId: string | undefined;\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n parentSpanId = currentSpanId ?? otelSpanIdToUUID(currentSpan.spanContext().spanId);\n traceId = currentTraceId ?? otelTraceIdToUUID(currentSpan.spanContext().traceId);\n } else {\n parentSpanId = currentSpanId;\n traceId = currentTraceId;\n }\n if (this.projectApiKey === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n const envirionment = env === undefined ? this.env : env;\n\n const response = await fetch(`${this.baseUrl}/v1/pipeline/run`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n inputs,\n pipeline,\n env: envirionment,\n metadata,\n parentSpanId,\n traceId,\n })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to run pipeline ${pipeline}. Response: ${response.statusText}`);\n }\n try {\n return await response.json() as PipelineRunResponse;\n } catch (error) {\n throw new Error(`Failed to parse response from pipeline ${pipeline}. Error: ${error}`);\n }\n }\n\n /**\n * Associates an event with the current span. If event with such name never\n * existed, Laminar will create a new event and infer its type from the value.\n * If the event already exists, Laminar will append the value to the event\n * if and only if the value is of a matching type. Otherwise, the event won't\n * be recorded. Supported types are string, number, and boolean. If the value\n * is `null`, event is considered a boolean tag with the value of `true`.\n *\n * @param name - The name of the event.\n * @param value - The value of the event. Must be a primitive type. If not specified, boolean true is assumed in the backend.\n * @param timestamp - The timestamp of the event. If not specified, relies on the underlying OpenTelemetry implementation.\n * If specified as an integer, it must be epoch nanoseconds.\n */\n public static event(\n name: string,\n value?: AttributeValue,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().event()\\` called outside of span context.\" +\n ` Event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event: Attributes = {\n \"lmnr.event.type\": \"default\",\n }\n if (value !== undefined) {\n event[\"lmnr.event.value\"] = value;\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sends an event for evaluation to the Laminar backend.\n * \n * @param name - The name of the event.\n * @param evaluator - The name of the pipeline that evaluates the event.\n * @param data - A map from input node name to its value in the evaluator pipeline.\n * @param env - Environment variables required to run the pipeline.\n * @param timestamp - If specified as an integer, it must be epoch nanoseconds.\n * If not specified, relies on the underlying OpenTelemetry implementation.\n */\n public static evaluateEvent(\n name: string,\n evaluator: string,\n data: Record<string, any>,\n env?: Record<string, string>,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().evaluateEvent()\\` called outside of span context.\" +\n ` Evaluate event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event = {\n \"lmnr.event.type\": \"evaluate\",\n \"lmnr.event.evaluator\": evaluator,\n \"lmnr.event.data\": JSON.stringify(data),\n \"lmnr.event.env\": JSON.stringify(env ?? {}),\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sets the session information for the current span and returns the context to use for the following spans.\n * \n * Example:\n * ```typescript\n * import { context as contextApi } from '@opentelemetry/api';\n * import { Laminar } from '@lmnr-ai/laminar';\n * const context = Laminar.contextWithSession({ sessionId: \"1234\", userId: \"5678\" });\n * contextApi.with(context, () => {\n * // Your code here\n * });\n * ```\n * \n * @param sessionId - The session ID to associate with the span.\n * @param userId - The user ID to associate with the span.\n * @returns The updated context with the association properties.\n */\n public static contextWithSession({ sessionId, userId }: { sessionId?: string, userId?: string }) {\n\n const currentSpan = trace.getActiveSpan();\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n if (sessionId) {\n currentSpan.setAttribute(\"traceloop.association.properties.session_id\", sessionId);\n }\n if (userId) {\n currentSpan.setAttribute(\"traceloop.association.properties.user_id\", userId);\n }\n }\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n let entityContext = context.active();\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n return entityContext;\n }\n\n public static async shutdown() {\n await forceFlush();\n }\n\n public static async createEvaluation(name: string) {\n const response = await fetch(`${this.baseUrl}/v1/evaluations`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n name,\n })\n });\n\n return await response.json();\n }\n\n public static async postEvaluationResults<D, T, O>(\n evaluationName: string,\n data: EvaluationDatapoint<D, T, O>[]\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n points: data,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluation-datapoints`;\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to send evaluation results. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to send evaluation results. Error: \", error);\n };\n }\n\n public static async updateEvaluationStatus(\n evaluationName: string,\n status: EvaluationStatus,\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n status,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluations`;\n try {\n const response = await fetch(url, {\n method: \"PUT\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to update evaluation status. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to update evaluation status. Error: \", error);\n }\n }\n\n private static getHeaders() {\n return {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${this.projectApiKey}`,\n };\n };\n}\n","/**\n * The severity of an error.\n */\nexport const SEVERITY = {\n Warning: \"Warning\",\n Error: \"Error\",\n Critical: \"Critical\",\n} as const;\n\nexport type Severity = (typeof SEVERITY)[keyof typeof SEVERITY];\n\n/**\n * Base class for all Traceloop errors.\n */\nexport class TraceloopError extends Error {\n /**\n * The severity of the error.\n */\n severity: Severity;\n /**\n * The underlying cause of the error.\n */\n underlyingCause?: Error;\n\n constructor(message: string, severity: Severity = SEVERITY.Error) {\n super(message);\n this.severity = severity;\n }\n}\n\nexport class NotInitializedError extends TraceloopError {\n constructor() {\n super(\n `The Traceloop SDK must be initialized by calling the \"initialize\" function prior to use.`,\n SEVERITY.Critical,\n );\n }\n}\n\nexport class InitializationError extends TraceloopError {\n constructor(message?: string, cause?: Error) {\n super(message ?? \"Failed to initialize Traceloop SDK\", SEVERITY.Critical);\n this.underlyingCause = cause;\n }\n}\n\nexport class ArgumentNotProvidedError extends TraceloopError {\n constructor(argumentName: string) {\n super(`The \"${argumentName}\" argument is required and must be a string.`);\n }\n}\n\nexport class PromptNotFoundError extends TraceloopError {\n constructor(key: string) {\n super(`The prompt \"${key}\" was not found in the registry.`);\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n SimpleSpanProcessor,\n BatchSpanProcessor,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-node\";\nimport { baggageUtils } from \"@opentelemetry/core\";\nimport { Span, context, diag } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { Resource } from \"@opentelemetry/resources\";\nimport { SEMRESATTRS_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { InitializeOptions } from \"../interfaces\";\nimport {\n Detector,\n DetectorSync,\n IResource,\n ResourceDetectionConfig,\n envDetectorSync,\n hostDetectorSync,\n processDetectorSync,\n} from \"@opentelemetry/resources\"\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n} from \"./tracing\";\nimport { Telemetry } from \"../telemetry/telemetry\";\nimport { _configuration } from \"../configuration\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { AnthropicInstrumentation } from \"@traceloop/instrumentation-anthropic\";\nimport { OpenAIInstrumentation } from \"@traceloop/instrumentation-openai\";\nimport { AzureOpenAIInstrumentation } from \"@traceloop/instrumentation-azure\";\nimport { LlamaIndexInstrumentation } from \"@traceloop/instrumentation-llamaindex\";\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from \"@traceloop/instrumentation-vertexai\";\nimport { BedrockInstrumentation } from \"@traceloop/instrumentation-bedrock\";\nimport { CohereInstrumentation } from \"@traceloop/instrumentation-cohere\";\nimport { PineconeInstrumentation } from \"@traceloop/instrumentation-pinecone\";\nimport { LangChainInstrumentation } from \"@traceloop/instrumentation-langchain\";\nimport { ChromaDBInstrumentation } from \"@traceloop/instrumentation-chromadb\";\nimport { QdrantInstrumentation } from \"@traceloop/instrumentation-qdrant\";\n\nlet _sdk: NodeSDK;\nlet _spanProcessor: SimpleSpanProcessor | BatchSpanProcessor;\nlet openAIInstrumentation: OpenAIInstrumentation | undefined;\nlet anthropicInstrumentation: AnthropicInstrumentation | undefined;\nlet azureOpenAIInstrumentation: AzureOpenAIInstrumentation | undefined;\nlet cohereInstrumentation: CohereInstrumentation | undefined;\nlet vertexaiInstrumentation: VertexAIInstrumentation | undefined;\nlet aiplatformInstrumentation: AIPlatformInstrumentation | undefined;\nlet bedrockInstrumentation: BedrockInstrumentation | undefined;\nlet langchainInstrumentation: LangChainInstrumentation | undefined;\nlet llamaIndexInstrumentation: LlamaIndexInstrumentation | undefined;\nlet pineconeInstrumentation: PineconeInstrumentation | undefined;\nlet chromadbInstrumentation: ChromaDBInstrumentation | undefined;\nlet qdrantInstrumentation: QdrantInstrumentation | undefined;\n\n\nconst instrumentations: Instrumentation[] = [];\n\nconst initInstrumentations = () => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n\n anthropicInstrumentation = new AnthropicInstrumentation({ exceptionLogger });\n instrumentations.push(anthropicInstrumentation);\n\n azureOpenAIInstrumentation = new AzureOpenAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(azureOpenAIInstrumentation);\n\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n\n pineconeInstrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(pineconeInstrumentation);\n\n langchainInstrumentation = new LangChainInstrumentation({ exceptionLogger });\n instrumentations.push(langchainInstrumentation);\n\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n};\n\nconst manuallyInitInstrumentations = (\n instrumentModules: InitializeOptions[\"instrumentModules\"],\n) => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n instrumentations.length = 0;\n\n if (instrumentModules?.openAI) {\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n openAIInstrumentation.manuallyInstrument(instrumentModules.openAI);\n }\n\n if (instrumentModules?.anthropic) {\n anthropicInstrumentation = new AnthropicInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(anthropicInstrumentation);\n anthropicInstrumentation.manuallyInstrument(instrumentModules.anthropic);\n }\n\n if (instrumentModules?.azureOpenAI) {\n const instrumentation = new AzureOpenAIInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n azureOpenAIInstrumentation = instrumentation;\n instrumentation.manuallyInstrument(instrumentModules.azureOpenAI);\n }\n\n if (instrumentModules?.cohere) {\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n cohereInstrumentation.manuallyInstrument(instrumentModules.cohere);\n }\n\n if (instrumentModules?.google_vertexai) {\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n vertexaiInstrumentation.manuallyInstrument(\n instrumentModules.google_vertexai,\n );\n }\n\n if (instrumentModules?.google_aiplatform) {\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n aiplatformInstrumentation.manuallyInstrument(\n instrumentModules.google_aiplatform,\n );\n }\n\n if (instrumentModules?.bedrock) {\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n bedrockInstrumentation.manuallyInstrument(instrumentModules.bedrock);\n }\n\n if (instrumentModules?.pinecone) {\n const instrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n instrumentation.manuallyInstrument(instrumentModules.pinecone);\n }\n\n if (instrumentModules?.langchain) {\n langchainInstrumentation = new LangChainInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(langchainInstrumentation);\n langchainInstrumentation.manuallyInstrument(instrumentModules.langchain);\n }\n\n if (instrumentModules?.llamaIndex) {\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n llamaIndexInstrumentation.manuallyInstrument(instrumentModules.llamaIndex);\n }\n\n if (instrumentModules?.chromadb) {\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n chromadbInstrumentation.manuallyInstrument(instrumentModules.chromadb);\n }\n\n if (instrumentModules?.qdrant) {\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);\n }\n};\n\nfunction awaitAttributes(detector: DetectorSync): Detector {\n return {\n async detect(config?: ResourceDetectionConfig): Promise<IResource> {\n const resource = detector.detect(config)\n await resource.waitForAsyncAttributes?.()\n\n return resource\n },\n }\n}\n\n/**\n * Initializes the Traceloop SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n */\nexport const startTracing = (options: InitializeOptions) => {\n if (options.instrumentModules !== undefined) {\n // If options.instrumentModules is empty, it will not initialize anything,\n // so empty dict can essentially be passed to disable any kind of automatic instrumentation.\n manuallyInitInstrumentations(options.instrumentModules);\n } else {\n initInstrumentations();\n }\n\n if (!shouldSendTraces()) {\n openAIInstrumentation?.setConfig({\n traceContent: false,\n });\n azureOpenAIInstrumentation?.setConfig({\n traceContent: false,\n });\n llamaIndexInstrumentation?.setConfig({\n traceContent: false,\n });\n vertexaiInstrumentation?.setConfig({\n traceContent: false,\n });\n aiplatformInstrumentation?.setConfig({\n traceContent: false,\n });\n bedrockInstrumentation?.setConfig({\n traceContent: false,\n });\n cohereInstrumentation?.setConfig({\n traceContent: false,\n });\n chromadbInstrumentation?.setConfig({\n traceContent: false,\n });\n }\n\n const headers = process.env.TRACELOOP_HEADERS\n ? baggageUtils.parseKeyPairsIntoRecord(process.env.TRACELOOP_HEADERS)\n : { Authorization: `Bearer ${options.apiKey}` };\n\n const traceExporter =\n options.exporter ??\n new OTLPTraceExporter({\n url: `${options.baseUrl}/v1/traces`,\n headers,\n });\n _spanProcessor = options.disableBatch\n ? new SimpleSpanProcessor(traceExporter)\n : new BatchSpanProcessor(traceExporter);\n\n _spanProcessor.onStart = (span: Span) => {\n // This sets the properties only if the context has them\n const associationProperties = context\n .active()\n .getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(\n `${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`,\n value,\n );\n }\n }\n };\n\n if (options.exporter) {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: \"custom\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n } else {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: options.baseUrl ?? \"\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n }\n\n const spanProcessors: SpanProcessor[] = [_spanProcessor];\n if (options.processor) {\n spanProcessors.push(options.processor);\n }\n\n _sdk = new NodeSDK({\n resource: new Resource({\n [SEMRESATTRS_SERVICE_NAME]:\n options.appName || process.env.npm_package_name,\n }),\n spanProcessors,\n contextManager: options.contextManager,\n textMapPropagator: options.propagator,\n traceExporter,\n instrumentations,\n // We should re-consider removing irrelevant spans here in the future\n // sampler: new TraceloopSampler(),\n resourceDetectors: [\n awaitAttributes(envDetectorSync),\n awaitAttributes(processDetectorSync),\n awaitAttributes(hostDetectorSync),\n ],\n });\n\n _sdk.start();\n};\n\nexport const shouldSendTraces = () => {\n if (!_configuration) {\n diag.warn(\"Traceloop not initialized\");\n return false;\n }\n\n if (\n _configuration.traceContent === false ||\n (process.env.TRACELOOP_TRACE_CONTENT || \"true\").toLowerCase() === \"false\"\n ) {\n return false;\n }\n\n return true;\n};\n\nexport const forceFlush = async () => {\n await _spanProcessor.forceFlush();\n};\n","import { trace, createContextKey } from \"@opentelemetry/api\";\nimport { Context } from \"@opentelemetry/api/build/src/context/types\";\n\nconst TRACER_NAME = \"traceloop.tracer\";\nexport const WORKFLOW_NAME_KEY = createContextKey(\"workflow_name\");\nexport const ENTITY_NAME_KEY = createContextKey(\"entity_name\");\nexport const ASSOCIATION_PROPERTIES_KEY = createContextKey(\n \"association_properties\",\n);\n\nexport const getTracer = () => {\n return trace.getTracer(TRACER_NAME);\n};\n\nexport const getEntityPath = (entityContext: Context): string | undefined => {\n const path = entityContext.getValue(ENTITY_NAME_KEY);\n\n return path ? `${path}` : undefined;\n};\n","import * as os from \"os\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { v4 as uuid } from \"uuid\";\nimport { PostHog } from \"posthog-node\";\nconst { version } = require('../../../package.json');\n\nexport class Telemetry {\n private static instance: Telemetry;\n\n private static readonly ANON_ID_PATH = `${os.homedir()}/.cache/lmnr/telemetry_anon_id`;\n private static readonly UNKNOWN_ANON_ID = \"UNKNOWN\";\n\n private telemetryEnabled: boolean;\n private posthog: PostHog | undefined;\n private anonId: string | undefined;\n\n public static getInstance(): Telemetry {\n if (!Telemetry.instance) {\n Telemetry.instance = new Telemetry();\n }\n return Telemetry.instance;\n }\n\n private constructor() {\n this.telemetryEnabled =\n !process.env.LMNR_TELEMETRY ||\n process.env.LMNR_TELEMETRY.toLowerCase() === \"true\";\n\n if (this.telemetryEnabled) {\n this.posthog = new PostHog(\n \"phc_dUMdjfNKf11jcHgtn7juSnT4P1pO0tafsPUWt4PuwG7\",\n );\n }\n }\n\n private getAnonId() {\n if (this.anonId) {\n return this.anonId;\n }\n\n try {\n if (!fs.existsSync(Telemetry.ANON_ID_PATH)) {\n fs.mkdirSync(path.dirname(Telemetry.ANON_ID_PATH), { recursive: true });\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"w\");\n this.anonId = uuid();\n fs.writeSync(anonIdFile, this.anonId);\n fs.closeSync(anonIdFile);\n } else {\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"r\");\n this.anonId = fs.readFileSync(anonIdFile, \"utf8\");\n fs.closeSync(anonIdFile);\n }\n return this.anonId;\n } catch (e) {\n return Telemetry.UNKNOWN_ANON_ID;\n }\n }\n\n private getContext() {\n return {\n sdk: \"typescript\",\n sdk_version: version,\n };\n }\n\n public capture(event: string, properties?: Record<string, string>) {\n if (this.telemetryEnabled && this.posthog) {\n this.posthog.capture({\n distinctId: this.getAnonId(),\n event,\n properties: {\n ...properties,\n ...this.getContext(),\n },\n });\n this.posthog.flush();\n }\n }\n\n public logException(error: Error) {\n if (this.telemetryEnabled) {\n this.capture(\"error\", { error: error.message, stack: error.stack || \"\" });\n }\n }\n}\n","import { InitializeOptions } from \"../interfaces\";\nimport { startTracing } from \"../tracing\";\nimport { diag, DiagConsoleLogger, DiagLogLevel } from \"@opentelemetry/api\";\nimport { InitializationError } from \"../errors\";\n\nexport let _configuration: InitializeOptions | undefined;\n\n/**\n * Initializes the SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n * @throws {InitializationError} if the configuration is invalid or if failed to fetch feature data.\n */\nexport const initialize = (options: InitializeOptions) => {\n if (_configuration) {\n return;\n }\n\n if (!options.baseUrl) {\n options.baseUrl =\n process.env.LMNR_BASE_URL || \"https://api.lmnr.ai:8443\";\n }\n if (!options.apiKey) {\n options.apiKey = process.env.LMNR_PROJECT_API_KEY;\n }\n if (options.apiKey && typeof options.apiKey !== \"string\") {\n throw new InitializationError('\"apiKey\" must be a string');\n }\n\n if (!options.appName) {\n options.appName = process.env.npm_package_name;\n }\n\n _configuration = Object.freeze(options);\n\n if (options.logLevel) {\n diag.setLogger(\n new DiagConsoleLogger(),\n logLevelToOtelLogLevel(options.logLevel),\n );\n }\n\n if (!options.silenceInitializationMessage) {\n console.log(\n `Laminar exporting traces to ${\n _configuration.exporter ? \"a custom exporter\" : _configuration.baseUrl\n }`,\n );\n }\n\n startTracing(_configuration);\n};\n\nconst logLevelToOtelLogLevel = (\n logLevel: \"debug\" | \"info\" | \"warn\" | \"error\",\n) => {\n switch (logLevel) {\n case \"debug\":\n return DiagLogLevel.DEBUG;\n case \"info\":\n return DiagLogLevel.INFO;\n case \"warn\":\n return DiagLogLevel.WARN;\n case \"error\":\n return DiagLogLevel.ERROR;\n }\n};\n","import { Span, context } from \"@opentelemetry/api\";\nimport { suppressTracing } from \"@opentelemetry/core\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n getTracer,\n} from \"./tracing\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\nimport { Telemetry } from \"../telemetry/telemetry\";\n\nexport type DecoratorConfig = {\n name: string;\n associationProperties?: { [name: string]: string };\n inputParameters?: unknown[];\n suppressTracing?: boolean;\n};\n\nexport function withEntity<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n {\n name,\n associationProperties,\n inputParameters,\n suppressTracing: shouldSuppressTracing,\n }: DecoratorConfig,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n let entityContext = context.active();\n\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n if (shouldSuppressTracing) {\n entityContext = suppressTracing(entityContext);\n }\n\n return context.with(entityContext, () =>\n getTracer().startActiveSpan(\n name,\n {},\n entityContext,\n async (span: Span) => {\n if (shouldSendTraces()) {\n try {\n const input = inputParameters ?? args;\n if (\n input.length === 1 &&\n typeof input[0] === \"object\" &&\n !(input[0] instanceof Map)\n ) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({ args: [], kwargs: input[0] }),\n );\n } else {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({\n args: input,\n kwargs: {},\n }),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n }\n }\n\n const res = fn.apply(thisArg, args);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(resolvedRes),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return resolvedRes;\n });\n }\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(res),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return res;\n },\n ),\n );\n}\n\nfunction cleanInput(input: unknown): unknown {\n if (input instanceof Map) {\n return Array.from(input.entries());\n } else if (Array.isArray(input)) {\n return input.map((value) => cleanInput(value));\n } else if (!input) {\n return input;\n } else if (typeof input === \"object\") {\n // serialize object one by one\n const output: any = {};\n Object.entries(input as any).forEach(([key, value]) => {\n output[key] = cleanInput(value);\n });\n return output;\n }\n\n return input;\n}\n\nfunction serialize(input: unknown): string {\n return JSON.stringify(cleanInput(input));\n}\n","import { Span, context, trace } from \"@opentelemetry/api\";\nimport { getTracer } from \"./tracing\";\nimport {\n Events,\n EventAttributes,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\n\ntype VectorDBCallConfig = {\n vendor: string;\n type: \"query\" | \"upsert\" | \"delete\";\n};\n\ntype LLMCallConfig = {\n vendor: string;\n type: \"chat\" | \"completion\";\n};\n\nexport class VectorSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportQuery({ queryVector }: { queryVector: number[] }) {\n if (!shouldSendTraces()) {\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS);\n }\n\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS, {\n [EventAttributes.DB_QUERY_EMBEDDINGS_VECTOR]: JSON.stringify(queryVector),\n });\n }\n\n reportResults({\n results,\n }: {\n results: {\n ids?: string;\n scores?: number;\n distances?: number;\n metadata?: Record<string, unknown>;\n vectors?: number[];\n documents?: string;\n }[];\n }) {\n for (let i = 0; i < results.length; i++) {\n this.span.addEvent(Events.DB_QUERY_RESULT, {\n [EventAttributes.DB_QUERY_RESULT_ID]: results[i].ids,\n [EventAttributes.DB_QUERY_RESULT_SCORE]: results[i].scores,\n [EventAttributes.DB_QUERY_RESULT_DISTANCE]: results[i].distances,\n [EventAttributes.DB_QUERY_RESULT_METADATA]: JSON.stringify(\n results[i].metadata,\n ),\n [EventAttributes.DB_QUERY_RESULT_VECTOR]: results[i].vectors,\n [EventAttributes.DB_QUERY_RESULT_DOCUMENT]: results[i].documents,\n });\n }\n }\n}\n\nexport class LLMSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportRequest({\n model,\n messages,\n }: {\n model: string;\n messages: {\n role: string;\n content?: string | unknown;\n }[];\n }) {\n this.span.setAttributes({\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n });\n\n messages.forEach((message, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_PROMPTS}.${index}.role`]: message.role,\n [`${SpanAttributes.LLM_PROMPTS}.${index}.content`]:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content),\n });\n });\n }\n\n reportResponse({\n model,\n usage,\n completions,\n }: {\n model: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n completions?: {\n finish_reason: string;\n message: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | null;\n };\n }[];\n }) {\n this.span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, model);\n\n if (usage) {\n this.span.setAttributes({\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: usage.prompt_tokens,\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: usage.completion_tokens,\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: usage.total_tokens,\n });\n }\n\n completions?.forEach((completion, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.finish_reason`]:\n completion.finish_reason,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.role`]:\n completion.message.role,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.content`]:\n completion.message.content || \"\",\n });\n });\n }\n}\n\nexport function withVectorDBCall<\n F extends ({ span }: { span: VectorSpan }) => ReturnType<F>,\n>({ vendor, type }: VectorDBCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const entityContext = context.active();\n\n return getTracer().startActiveSpan(\n `${vendor}.${type}`,\n { [SpanAttributes.LLM_REQUEST_TYPE]: type },\n entityContext,\n (span: Span) => {\n const res = fn.apply(thisArg, [{ span: new VectorSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n },\n );\n}\n\nexport function withLLMCall<\n F extends ({ span }: { span: LLMSpan }) => ReturnType<F>,\n>({ vendor, type }: LLMCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const span = getTracer().startSpan(`${vendor}.${type}`, {}, context.active());\n span.setAttribute(SpanAttributes.LLM_REQUEST_TYPE, type);\n trace.setSpan(context.active(), span);\n\n const res = fn.apply(thisArg, [{ span: new LLMSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n}\n","import { context } from \"@opentelemetry/api\";\nimport { ASSOCIATION_PROPERTIES_KEY } from \"./tracing\";\n\nexport function withAssociationProperties<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context\n .active()\n .setValue(ASSOCIATION_PROPERTIES_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n","import { v4 as uuidv4 } from 'uuid';\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const newUUID = (): StringUUID => {\n // crypto.randomUUID is available in most of the modern browsers and node,\n // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n // so we fallback to uuidv4 in those cases, which is less secure, but works\n // just fine.\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n } else {\n return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n }\n}\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 16) {\n console.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n }\n\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.padStart(32, '0').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n\nexport const otelTraceIdToUUID = (traceId: string): string => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 32) {\n console.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n }\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n","import { Laminar } from \"./laminar\";\nimport { CreateEvaluationResponse, EvaluationDatapoint } from \"./types\";\n\nconst DEFAULT_BATCH_SIZE = 5;\n\n/**\n * Configuration for the Evaluator\n */\ninterface EvaluatorConfig {\n batchSize?: number;\n projectApiKey?: string;\n baseUrl?: string;\n}\n\nexport abstract class Dataset<D, T> {\n public slice(start: number, end: number): Datapoint<D, T>[] {\n const result = [];\n for (let i = Math.max(start, 0); i < Math.min(end, this.size()); i++) {\n result.push(this.get(i));\n }\n return result;\n }\n public abstract size(): number;\n public abstract get(index: number): Datapoint<D, T>;\n}\n\n/**\n * Datapoint is a single data point in the evaluation. `D` is the type of the input data, `T` is the type of the target data.\n */\nexport type Datapoint<D, T> = {\n /**\n * input to the executor function. Must be a record with string keys and any values.\n */\n data: Record<string, any> & D;\n /**\n * input to the evaluator function (alongside the executor output).\n * Must be a record with string keys and any values.\n */\n target: Record<string, any> & T;\n}\n\ntype EvaluatorFunctionReturn = number | Record<string, number>;\n\n/**\n * EvaluatorFunction is a function that takes the output of the executor and the target data, and returns a score.\n * The score can be a single number or a record of string keys and number values. The latter is useful for evaluating\n * multiple criteria in one go instead of running multiple evaluators.\n */\ntype EvaluatorFunction<O, T> = (output: O, target: T, ...args: any[]) => EvaluatorFunctionReturn | Promise<EvaluatorFunctionReturn>;\n\ninterface EvaluatorConstructorProps<D, T, O> {\n /**\n * List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n */\n data: (Datapoint<D, T>[]) | Dataset<D, T>;\n /**\n * The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n */\n executor: (data: D, ...args: any[]) => O | Promise<O>;\n /**\n * List of evaluator functions. Each evaluator function takes the output of the executor _and_ the target data, and returns\n * a score. The score can be a single number or a record of string keys and number values.\n * If the score is a single number, it will be named after the evaluator function. If the function is anonymous, it will be named\n * `evaluator_${index}`, where index is the index of the evaluator function in the list starting from 1.\n */\n evaluators: EvaluatorFunction<O, T>[];\n /**\n * Optional override configurations for the evaluator.\n */\n config?: EvaluatorConfig;\n}\n\nexport class Evaluation<D, T, O> {\n private name: string;\n private data: Datapoint<D, T>[] | Dataset<D, T>;\n private executor: (data: D, ...args: any[]) => O | Promise<O>;\n private evaluators: Record<string, EvaluatorFunction<O, T>>;\n private evaluatorNames: string[];\n private batchSize: number = DEFAULT_BATCH_SIZE;\n\n /**\n * Create a new evaluation and prepare data.\n * @param name Name of the evaluation.\n * @param props.data List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n * @param props.executor The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n * @param props.evaluators List of evaluator functions. Each evaluator function takes the output of the executor and the target data, and returns.\n */\n constructor(name: string, {\n data, executor, evaluators, config\n }: EvaluatorConstructorProps<D, T, O>) {\n this.name = name;\n this.data = data;\n this.executor = executor;\n this.evaluators = Object.fromEntries(evaluators.map((e, i) => [e.name.length > 0 ? e.name : `evaluator_${i + 1}`, e]));\n this.evaluatorNames = evaluators.map((e, i) => e.name.length > 0 ? e.name : `evaluator_${i + 1}`);\n if (config) {\n this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;\n }\n Laminar.initialize({ projectApiKey: config?.projectApiKey, baseUrl: config?.baseUrl });\n }\n\n /** \n * Runs the evaluation.\n *\n * Creates a new evaluation if no evaluation with such name exists, or adds data to an existing one otherwise.\n * Evaluates data points in batches of `batchSize`. The executor function is called on each data point\n * to get the output, and then evaluate it by each evaluator function.\n */\n public async run(): Promise<void> {\n const response = await Laminar.createEvaluation(this.name) as CreateEvaluationResponse;\n const length = this.data instanceof Dataset ? this.data.size() : this.data.length;\n for (let i = 0; i < length; i += this.batchSize) {\n const batch = this.data.slice(i, i + this.batchSize);\n try {\n await this.evaluateBatch(batch);\n } catch (e) {\n console.error(`Error evaluating batch: ${e}`);\n }\n }\n try {\n // After all batches are completed, update the evaluation status\n await Laminar.updateEvaluationStatus(response.name, 'Finished');\n } catch (e) {\n console.error(`Error updating evaluation status: ${e}`);\n }\n }\n \n private async evaluateBatch(batch: Datapoint<D, T>[]): Promise<void> {\n const batchPromises = batch.map(async (datapoint) => {\n const output = await this.executor(datapoint.data);\n const target = datapoint.target;\n \n let scores: Record<string, EvaluatorFunctionReturn> = {};\n for (const evaluatorName of this.evaluatorNames) {\n const evaluator = this.evaluators[evaluatorName];\n const value = await evaluator(output, target);\n \n // If the evaluator returns a single number, use the evaluator name as the key\n if (typeof value === 'number') {\n scores[evaluatorName] = value;\n } else {\n // If the evaluator returns an object, merge its keys with the existing scores (flatten)\n scores = { ...scores, ...value };\n }\n }\n \n return {\n executorOutput: output,\n data: datapoint.data,\n target,\n scores,\n } as EvaluationDatapoint<D, T, O>;\n });\n \n const results = await Promise.all(batchPromises);\n \n return Laminar.postEvaluationResults(this.name, results);\n }\n \n}\n","import { withEntity } from './sdk/node-server-sdk'\n\ninterface ObserveOptions {\n name?: string;\n sessionId?: string;\n userId?: string;\n}\n\n/**\n * The main decorator entrypoint for Laminar. This is used to wrap\n * functions and methods to create spans.\n *\n * @param name - Name of the span. Function name is used if not specified.\n * @param user_id - User ID to associate with the span and the following context.\n * @param session_id - Session ID to associate with the span and the following context.\n * @returns Returns the result of the wrapped function.\n * @throws Exception - Re-throws the exception if the wrapped function throws an exception.\n * \n * @example\n * ```typescript\n * import { observe } from '@lmnr-ai/lmnr';\n * \n * await observe({ name: 'my_function' }, () => {\n * // Your code here\n * });\n */\nexport async function observe<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n {\n name,\n sessionId,\n userId,\n }: ObserveOptions, fn: F, ...args: A): Promise<ReturnType<F>> {\n\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n return await withEntity<A, F>({ name: name ?? fn.name, associationProperties }, fn, undefined, ...args);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iBAAAA,UAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,QAAU;AAAA,MACV,SAAW;AAAA,MACX,MAAQ;AAAA,QACN,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,MACZ,iBAAmB;AAAA,QACjB,qBAAqB;AAAA,QACrB,mCAAmC;AAAA,QACnC,iBAAiB;AAAA,QACjB,4BAA4B;AAAA,QAC5B,0BAA0B;AAAA,QAC1B,mBAAmB;AAAA,QACnB,+BAA+B;AAAA,QAC/B,0BAA0B;AAAA,QAC1B,eAAe;AAAA,QACf,eAAe;AAAA,QACf,YAAc;AAAA,QACd,UAAY;AAAA,QACZ,aAAa;AAAA,QACb,WAAa;AAAA,QACb,YAAc;AAAA,QACd,QAAU;AAAA,QACV,WAAa;AAAA,QACb,MAAQ;AAAA,QACR,YAAc;AAAA,QACd,cAAgB;AAAA,MAClB;AAAA,MACA,cAAgB;AAAA,QACd,iBAAiB;AAAA,QACjB,sB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Q,sBAAsB,KAAK,MAAM,OAAO;AAAA,EAC3D;AAEJ;;;ACrIA,eAAsB,QAClB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AACJ,GAAmB,OAAU,MAAiC;AAE9D,MAAI,wBAAwB,CAAC;AAC7B,MAAI,WAAW;AACX,4BAAwB,EAAE,GAAG,uBAAuB,cAAc,UAAU;AAAA,EAChF;AACA,MAAI,QAAQ;AACR,4BAAwB,EAAE,GAAG,uBAAuB,WAAW,OAAO;AAAA,EAC1E;AAEA,SAAO,MAAM,WAAiB,EAAE,MAAM,sBAAQ,GAAG,MAAM,sBAAsB,GAAG,IAAI,QAAW,GAAG,IAAI;AAC1G;","names":["exports","module","import_api","import_api","import_resources","uuid","import_api","import_api","import_core","import_ai_semantic_conventions","import_api","import_ai_semantic_conventions","import_api","import_uuid","uuidv4"]}
1
+ {"version":3,"sources":["../package.json","../src/index.ts","../src/laminar.ts","../src/sdk/errors/index.ts","../src/sdk/tracing/index.ts","../src/sdk/tracing/tracing.ts","../src/sdk/telemetry/telemetry.ts","../src/sdk/configuration/index.ts","../src/sdk/tracing/decorators.ts","../src/sdk/tracing/manual.ts","../src/sdk/tracing/association.ts","../src/utils.ts","../src/evaluations.ts","../src/decorators.ts"],"sourcesContent":["{\n \"name\": \"@lmnr-ai/lmnr\",\n \"version\": \"0.4.10-alpha\",\n \"description\": \"TypeScript SDK for Laminar AI\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/lmnr-ai/lmnr-ts.git\"\n },\n \"keywords\": [\n \"laminar\",\n \"lmnr\",\n \"sdk\",\n \"lmnr.ai\"\n ],\n \"author\": \"founders@lmnr.ai\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/lmnr-ai/lmnr-ts/issues\"\n },\n \"homepage\": \"https://github.com/lmnr-ai/lmnr-ts#README\",\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@aws-sdk/client-bedrock-runtime\": \"^3.649.0\",\n \"@azure/openai\": \"2.0.0-beta.2\",\n \"@google-cloud/aiplatform\": \"^3.29.0\",\n \"@google-cloud/vertexai\": \"^1.7.0\",\n \"@langchain/core\": \"^0.2.32\",\n \"@pinecone-database/pinecone\": \"^3.0.2\",\n \"@qdrant/js-client-rest\": \"^1.11.0\",\n \"@types/node\": \"^22.5.4\",\n \"@types/uuid\": \"^10.0.0\",\n \"bufferutil\": \"^4.0.8\",\n \"chromadb\": \"^1.8.1\",\n \"cohere-ai\": \"^7.13.0\",\n \"langchain\": \"^0.2.18\",\n \"llamaindex\": \"^0.5.23\",\n \"openai\": \"^4.58.2\",\n \"runnables\": \"link:@langchain/core/runnables\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vectorstores\": \"link:@langchain/core/vectorstores\"\n },\n \"dependencies\": {\n \"@grpc/grpc-js\": \"^1.11.2\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/core\": \"^1.26.0\",\n \"@opentelemetry/exporter-trace-otlp-grpc\": \"^0.53.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.53.0\",\n \"@opentelemetry/instrumentation\": \"^0.53.0\",\n \"@opentelemetry/sdk-node\": \"^0.53.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.26.0\",\n \"@opentelemetry/sdk-trace-node\": \"^1.26.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.27.0\",\n \"@traceloop/ai-semantic-conventions\": \"^0.11.0\",\n \"@traceloop/instrumentation-anthropic\": \"^0.11.1\",\n \"@traceloop/instrumentation-azure\": \"^0.11.1\",\n \"@traceloop/instrumentation-bedrock\": \"^0.11.1\",\n \"@traceloop/instrumentation-chromadb\": \"^0.11.1\",\n \"@traceloop/instrumentation-cohere\": \"^0.11.1\",\n \"@traceloop/instrumentation-langchain\": \"^0.11.1\",\n \"@traceloop/instrumentation-llamaindex\": \"^0.11.1\",\n \"@traceloop/instrumentation-openai\": \"^0.11.1\",\n \"@traceloop/instrumentation-pinecone\": \"^0.11.1\",\n \"@traceloop/instrumentation-qdrant\": \"^0.11.1\",\n \"@traceloop/instrumentation-vertexai\": \"^0.11.1\",\n \"posthog-node\": \"^4.2.0\",\n \"uuid\": \"^10.0.0\"\n }\n}","\nexport {\n NodeInput,\n PipelineRunResponse,\n PipelineRunRequest,\n ChatMessage,\n Event,\n EvaluateEvent,\n} from './types';\n\nexport { Laminar } from './laminar';\nexport { Evaluation, Dataset, Datapoint } from './evaluations';\nexport { observe } from './decorators';\n","import { PipelineRunResponse, PipelineRunRequest, EvaluationDatapoint, EvaluationStatus } from './types';\nimport { Attributes, AttributeValue, context, createContextKey, isSpanContextValid, TimeInput, trace } from '@opentelemetry/api';\nimport { InitializeOptions, initialize as traceloopInitialize } from './sdk/node-server-sdk'\nimport { otelSpanIdToUUID, otelTraceIdToUUID } from './utils';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { Metadata } from '@grpc/grpc-js';\nimport { ASSOCIATION_PROPERTIES_KEY } from './sdk/tracing/tracing';\nimport { forceFlush } from './sdk/node-server-sdk';\n\n// quick patch to get the traceloop's default tracer, since their \n// `getTracer` function is not exported.\n// Another option would be to import directly \n// like so: `import { getTracer } from '@traceloop/node-server-sdk/dist/src/lib/tracing/tracing';`\n// which isn't too nice either.\nconst DEFAULT_TRACER_NAME = 'traceloop.tracer';\n\ninterface LaminarInitializeProps {\n projectApiKey?: string;\n env?: Record<string, string>;\n baseUrl?: string;\n instrumentModules?: InitializeOptions[\"instrumentModules\"];\n}\n\nexport class Laminar {\n private static baseUrl: string = 'https://api.lmnr.ai:8443';\n private static projectApiKey: string;\n private static env: Record<string, string> = {};\n private static isInitialized: boolean = false;\n\n /**\n * Initialize Laminar context across the application.\n * This method must be called before using any other Laminar methods or decorators.\n *\n * @param project_api_key - Laminar project api key. You can generate one by going\n * to the projects settings page on the Laminar dashboard.\n * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable.\n * @param env - Default environment passed to `run` and `evaluateEvent` requests,\n * unless overriden at request time. Usually, model provider keys are stored here.\n * @param baseUrl - Url of Laminar endpoint, or the custom open telemetry ingester.\n * If not specified, defaults to https://api.lmnr.ai:8443. For locally hosted Laminar,\n * default setting must be http://localhost:8001.\n * @param instrumentModules - List of modules to instrument.\n * If not specified, all auto-instrumentable modules will be instrumented, which include\n * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n * Pass an empty object {} to disable any kind of automatic instrumentation.\n * If you only want to auto-instrument specific modules, then pass them in the object.\n * \n * Example:\n * ```typescript\n * import { Laminar as L } from '@lmnr-ai/lmnr';\n * import { OpenAI } from 'openai';\n * import * as ChainsModule from \"langchain/chains\";\n * \n * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules.\n * L.initialize({ projectApiKey: \"<LMNR_PROJECT_API_KEY>\", instrumentModules: {\n * langchain: {\n * chainsModule: ChainsModule\n * },\n * openAI: OpenAI\n * } });\n * ```\n *\n * @throws {Error} - If project API key is not set\n */\n public static initialize({\n projectApiKey,\n env,\n baseUrl,\n instrumentModules\n }: LaminarInitializeProps) {\n\n let key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n if (key === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n this.projectApiKey = key;\n if (baseUrl) {\n this.baseUrl = baseUrl;\n }\n this.isInitialized = true;\n this.env = env ?? {};\n\n const metadata = new Metadata();\n metadata.set('authorization', `Bearer ${this.projectApiKey}`);\n const exporter = new OTLPTraceExporter({\n url: this.baseUrl,\n metadata,\n });\n\n traceloopInitialize({\n exporter,\n silenceInitializationMessage: true,\n instrumentModules,\n disableBatch: false,\n });\n }\n\n /**\n * Check if Laminar has been initialized. Utility to make sure other methods\n * are called after initialization.\n */\n public static initialized(): boolean {\n return this.isInitialized;\n }\n\n /**\n * Sets the environment that will be sent to Laminar requests.\n * \n * @param env - The environment variables to override. If not provided, the current environment will not be modified.\n */\n public static setEnv(env?: Record<string, string>) {\n if (env) {\n this.env = env;\n }\n }\n\n /**\n * Sets the project API key for authentication with Laminar.\n *\n * @param projectApiKey - The API key to be set. If not provided, the existing API key will not be modified.\n */\n public static setProjectApiKey(projectApiKey?: string) {\n if (projectApiKey) {\n this.projectApiKey = projectApiKey;\n }\n }\n\n /**\n * Runs the pipeline with the given inputs\n *\n * @param pipeline - The name of the Laminar pipeline. Pipeline must have a target version.\n * @param inputs - The inputs for the pipeline. Map from an input node name to input data.\n * @param env - The environment variables for the pipeline execution. Typically used for model provider keys.\n * @param metadata - Additional metadata for the pipeline run.\n * @param currentSpanId - The ID of the current span.\n * @param currentTraceId - The ID of the current trace.\n * @returns A promise that resolves to the response of the pipeline run.\n * @throws An error if the Laminar object is not initialized with a project API key. Or if the request fails.\n */\n public static async run({\n pipeline,\n inputs,\n env,\n metadata = {},\n currentSpanId,\n currentTraceId,\n }: PipelineRunRequest): Promise<PipelineRunResponse> {\n const currentSpan = trace.getActiveSpan();\n let parentSpanId: string | undefined;\n let traceId: string | undefined;\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n parentSpanId = currentSpanId ?? otelSpanIdToUUID(currentSpan.spanContext().spanId);\n traceId = currentTraceId ?? otelTraceIdToUUID(currentSpan.spanContext().traceId);\n } else {\n parentSpanId = currentSpanId;\n traceId = currentTraceId;\n }\n if (this.projectApiKey === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n const envirionment = env === undefined ? this.env : env;\n\n const response = await fetch(`${this.baseUrl}/v1/pipeline/run`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n inputs,\n pipeline,\n env: envirionment,\n metadata,\n parentSpanId,\n traceId,\n })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to run pipeline ${pipeline}. Response: ${response.statusText}`);\n }\n try {\n return await response.json() as PipelineRunResponse;\n } catch (error) {\n throw new Error(`Failed to parse response from pipeline ${pipeline}. Error: ${error}`);\n }\n }\n\n /**\n * Associates an event with the current span. If event with such name never\n * existed, Laminar will create a new event and infer its type from the value.\n * If the event already exists, Laminar will append the value to the event\n * if and only if the value is of a matching type. Otherwise, the event won't\n * be recorded. Supported types are string, number, and boolean. If the value\n * is `null`, event is considered a boolean tag with the value of `true`.\n *\n * @param name - The name of the event.\n * @param value - The value of the event. Must be a primitive type. If not specified, boolean true is assumed in the backend.\n * @param timestamp - The timestamp of the event. If not specified, relies on the underlying OpenTelemetry implementation.\n * If specified as an integer, it must be epoch nanoseconds.\n */\n public static event(\n name: string,\n value?: AttributeValue,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().event()\\` called outside of span context.\" +\n ` Event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event: Attributes = {\n \"lmnr.event.type\": \"default\",\n }\n if (value !== undefined) {\n event[\"lmnr.event.value\"] = value;\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sends an event for evaluation to the Laminar backend.\n * \n * @param name - The name of the event.\n * @param evaluator - The name of the pipeline that evaluates the event.\n * @param data - A map from input node name to its value in the evaluator pipeline.\n * @param env - Environment variables required to run the pipeline.\n * @param timestamp - If specified as an integer, it must be epoch nanoseconds.\n * If not specified, relies on the underlying OpenTelemetry implementation.\n */\n public static evaluateEvent(\n name: string,\n evaluator: string,\n data: Record<string, any>,\n env?: Record<string, string>,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().evaluateEvent()\\` called outside of span context.\" +\n ` Evaluate event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event = {\n \"lmnr.event.type\": \"evaluate\",\n \"lmnr.event.evaluator\": evaluator,\n \"lmnr.event.data\": JSON.stringify(data),\n \"lmnr.event.env\": JSON.stringify(env ?? {}),\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sets the session information for the current span and returns the context to use for the following spans.\n * \n * Example:\n * ```typescript\n * import { context as contextApi } from '@opentelemetry/api';\n * import { Laminar } from '@lmnr-ai/laminar';\n * const context = Laminar.contextWithSession({ sessionId: \"1234\", userId: \"5678\" });\n * contextApi.with(context, () => {\n * // Your code here\n * });\n * ```\n * \n * @param sessionId - The session ID to associate with the span.\n * @param userId - The user ID to associate with the span.\n * @returns The updated context with the association properties.\n */\n public static contextWithSession({ sessionId, userId }: { sessionId?: string, userId?: string }) {\n\n const currentSpan = trace.getActiveSpan();\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n if (sessionId) {\n currentSpan.setAttribute(\"traceloop.association.properties.session_id\", sessionId);\n }\n if (userId) {\n currentSpan.setAttribute(\"traceloop.association.properties.user_id\", userId);\n }\n }\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n let entityContext = context.active();\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n return entityContext;\n }\n\n public static async shutdown() {\n await forceFlush();\n }\n\n public static async createEvaluation(name: string) {\n const response = await fetch(`${this.baseUrl}/v1/evaluations`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n name,\n })\n });\n\n return await response.json();\n }\n\n public static async postEvaluationResults<D, T, O>(\n evaluationName: string,\n data: EvaluationDatapoint<D, T, O>[]\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n points: data,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluation-datapoints`;\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to send evaluation results. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to send evaluation results. Error: \", error);\n };\n }\n\n public static async updateEvaluationStatus(\n evaluationName: string,\n status: EvaluationStatus,\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n status,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluations`;\n try {\n const response = await fetch(url, {\n method: \"PUT\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to update evaluation status. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to update evaluation status. Error: \", error);\n }\n }\n\n private static getHeaders() {\n return {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${this.projectApiKey}`,\n };\n };\n}\n","/**\n * The severity of an error.\n */\nexport const SEVERITY = {\n Warning: \"Warning\",\n Error: \"Error\",\n Critical: \"Critical\",\n} as const;\n\nexport type Severity = (typeof SEVERITY)[keyof typeof SEVERITY];\n\n/**\n * Base class for all Traceloop errors.\n */\nexport class TraceloopError extends Error {\n /**\n * The severity of the error.\n */\n severity: Severity;\n /**\n * The underlying cause of the error.\n */\n underlyingCause?: Error;\n\n constructor(message: string, severity: Severity = SEVERITY.Error) {\n super(message);\n this.severity = severity;\n }\n}\n\nexport class NotInitializedError extends TraceloopError {\n constructor() {\n super(\n `The Traceloop SDK must be initialized by calling the \"initialize\" function prior to use.`,\n SEVERITY.Critical,\n );\n }\n}\n\nexport class InitializationError extends TraceloopError {\n constructor(message?: string, cause?: Error) {\n super(message ?? \"Failed to initialize Traceloop SDK\", SEVERITY.Critical);\n this.underlyingCause = cause;\n }\n}\n\nexport class ArgumentNotProvidedError extends TraceloopError {\n constructor(argumentName: string) {\n super(`The \"${argumentName}\" argument is required and must be a string.`);\n }\n}\n\nexport class PromptNotFoundError extends TraceloopError {\n constructor(key: string) {\n super(`The prompt \"${key}\" was not found in the registry.`);\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n SimpleSpanProcessor,\n BatchSpanProcessor,\n} from \"@opentelemetry/sdk-trace-node\";\nimport { baggageUtils } from \"@opentelemetry/core\";\nimport { Span, context, diag } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { InitializeOptions } from \"../interfaces\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n} from \"./tracing\";\nimport { Telemetry } from \"../telemetry/telemetry\";\nimport { _configuration } from \"../configuration\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport {NodeTracerProvider} from \"@opentelemetry/sdk-trace-node\";\nimport {registerInstrumentations} from \"@opentelemetry/instrumentation\";\nimport { AnthropicInstrumentation } from \"@traceloop/instrumentation-anthropic\";\nimport { OpenAIInstrumentation } from \"@traceloop/instrumentation-openai\";\nimport { AzureOpenAIInstrumentation } from \"@traceloop/instrumentation-azure\";\nimport { LlamaIndexInstrumentation } from \"@traceloop/instrumentation-llamaindex\";\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from \"@traceloop/instrumentation-vertexai\";\nimport { BedrockInstrumentation } from \"@traceloop/instrumentation-bedrock\";\nimport { CohereInstrumentation } from \"@traceloop/instrumentation-cohere\";\nimport { PineconeInstrumentation } from \"@traceloop/instrumentation-pinecone\";\nimport { LangChainInstrumentation } from \"@traceloop/instrumentation-langchain\";\nimport { ChromaDBInstrumentation } from \"@traceloop/instrumentation-chromadb\";\nimport { QdrantInstrumentation } from \"@traceloop/instrumentation-qdrant\";\n\nlet _spanProcessor: SimpleSpanProcessor | BatchSpanProcessor;\nlet openAIInstrumentation: OpenAIInstrumentation | undefined;\nlet anthropicInstrumentation: AnthropicInstrumentation | undefined;\nlet azureOpenAIInstrumentation: AzureOpenAIInstrumentation | undefined;\nlet cohereInstrumentation: CohereInstrumentation | undefined;\nlet vertexaiInstrumentation: VertexAIInstrumentation | undefined;\nlet aiplatformInstrumentation: AIPlatformInstrumentation | undefined;\nlet bedrockInstrumentation: BedrockInstrumentation | undefined;\nlet langchainInstrumentation: LangChainInstrumentation | undefined;\nlet llamaIndexInstrumentation: LlamaIndexInstrumentation | undefined;\nlet pineconeInstrumentation: PineconeInstrumentation | undefined;\nlet chromadbInstrumentation: ChromaDBInstrumentation | undefined;\nlet qdrantInstrumentation: QdrantInstrumentation | undefined;\n\n\nconst instrumentations: Instrumentation[] = [];\n\nconst initInstrumentations = () => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n\n anthropicInstrumentation = new AnthropicInstrumentation({ exceptionLogger });\n instrumentations.push(anthropicInstrumentation);\n\n azureOpenAIInstrumentation = new AzureOpenAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(azureOpenAIInstrumentation);\n\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n\n pineconeInstrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(pineconeInstrumentation);\n\n langchainInstrumentation = new LangChainInstrumentation({ exceptionLogger });\n instrumentations.push(langchainInstrumentation);\n\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n};\n\nconst manuallyInitInstrumentations = (\n instrumentModules: InitializeOptions[\"instrumentModules\"],\n) => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n instrumentations.length = 0;\n\n if (instrumentModules?.openAI) {\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n openAIInstrumentation.manuallyInstrument(instrumentModules.openAI);\n }\n\n if (instrumentModules?.anthropic) {\n anthropicInstrumentation = new AnthropicInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(anthropicInstrumentation);\n anthropicInstrumentation.manuallyInstrument(instrumentModules.anthropic);\n }\n\n if (instrumentModules?.azureOpenAI) {\n const instrumentation = new AzureOpenAIInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n azureOpenAIInstrumentation = instrumentation;\n instrumentation.manuallyInstrument(instrumentModules.azureOpenAI);\n }\n\n if (instrumentModules?.cohere) {\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n cohereInstrumentation.manuallyInstrument(instrumentModules.cohere);\n }\n\n if (instrumentModules?.google_vertexai) {\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n vertexaiInstrumentation.manuallyInstrument(\n instrumentModules.google_vertexai,\n );\n }\n\n if (instrumentModules?.google_aiplatform) {\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n aiplatformInstrumentation.manuallyInstrument(\n instrumentModules.google_aiplatform,\n );\n }\n\n if (instrumentModules?.bedrock) {\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n bedrockInstrumentation.manuallyInstrument(instrumentModules.bedrock);\n }\n\n if (instrumentModules?.pinecone) {\n const instrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n instrumentation.manuallyInstrument(instrumentModules.pinecone);\n }\n\n if (instrumentModules?.langchain) {\n langchainInstrumentation = new LangChainInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(langchainInstrumentation);\n langchainInstrumentation.manuallyInstrument(instrumentModules.langchain);\n }\n\n if (instrumentModules?.llamaIndex) {\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n llamaIndexInstrumentation.manuallyInstrument(instrumentModules.llamaIndex);\n }\n\n if (instrumentModules?.chromadb) {\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n chromadbInstrumentation.manuallyInstrument(instrumentModules.chromadb);\n }\n\n if (instrumentModules?.qdrant) {\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);\n }\n};\n\n/**\n * Initializes the Traceloop SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n */\nexport const startTracing = (options: InitializeOptions) => {\n if (options.instrumentModules !== undefined) {\n // If options.instrumentModules is empty, it will not initialize anything,\n // so empty dict can essentially be passed to disable any kind of automatic instrumentation.\n manuallyInitInstrumentations(options.instrumentModules);\n } else {\n initInstrumentations();\n }\n\n if (!shouldSendTraces()) {\n openAIInstrumentation?.setConfig({\n traceContent: false,\n });\n azureOpenAIInstrumentation?.setConfig({\n traceContent: false,\n });\n llamaIndexInstrumentation?.setConfig({\n traceContent: false,\n });\n vertexaiInstrumentation?.setConfig({\n traceContent: false,\n });\n aiplatformInstrumentation?.setConfig({\n traceContent: false,\n });\n bedrockInstrumentation?.setConfig({\n traceContent: false,\n });\n cohereInstrumentation?.setConfig({\n traceContent: false,\n });\n chromadbInstrumentation?.setConfig({\n traceContent: false,\n });\n }\n\n const headers = process.env.TRACELOOP_HEADERS\n ? baggageUtils.parseKeyPairsIntoRecord(process.env.TRACELOOP_HEADERS)\n : { Authorization: `Bearer ${options.apiKey}` };\n\n const traceExporter =\n options.exporter ??\n new OTLPTraceExporter({\n url: `${options.baseUrl}/v1/traces`,\n headers,\n });\n _spanProcessor = options.disableBatch\n ? new SimpleSpanProcessor(traceExporter)\n : new BatchSpanProcessor(traceExporter);\n\n _spanProcessor.onStart = (span: Span) => {\n // This sets the properties only if the context has them\n const associationProperties = context\n .active()\n .getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(\n `${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`,\n value,\n );\n }\n }\n };\n\n if (options.exporter) {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: \"custom\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n } else {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: options.baseUrl ?? \"\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n }\n\n const provider = new NodeTracerProvider();\n provider.addSpanProcessor(_spanProcessor);\n provider.register();\n registerInstrumentations({\n instrumentations,\n tracerProvider: provider,\n });\n};\n\nexport const shouldSendTraces = () => {\n if (!_configuration) {\n diag.warn(\"Traceloop not initialized\");\n return false;\n }\n\n if (\n _configuration.traceContent === false ||\n (process.env.TRACELOOP_TRACE_CONTENT || \"true\").toLowerCase() === \"false\"\n ) {\n return false;\n }\n\n return true;\n};\n\nexport const forceFlush = async () => {\n await _spanProcessor.forceFlush();\n};\n","import { trace, createContextKey } from \"@opentelemetry/api\";\nimport { Context } from \"@opentelemetry/api/build/src/context/types\";\n\nconst TRACER_NAME = \"traceloop.tracer\";\nexport const WORKFLOW_NAME_KEY = createContextKey(\"workflow_name\");\nexport const ENTITY_NAME_KEY = createContextKey(\"entity_name\");\nexport const ASSOCIATION_PROPERTIES_KEY = createContextKey(\n \"association_properties\",\n);\n\nexport const getTracer = () => {\n return trace.getTracer(TRACER_NAME);\n};\n\nexport const getEntityPath = (entityContext: Context): string | undefined => {\n const path = entityContext.getValue(ENTITY_NAME_KEY);\n\n return path ? `${path}` : undefined;\n};\n","import * as os from \"os\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { v4 as uuid } from \"uuid\";\nimport { PostHog } from \"posthog-node\";\nconst { version } = require('../../../package.json');\n\nexport class Telemetry {\n private static instance: Telemetry;\n\n private static readonly ANON_ID_PATH = `${os.homedir()}/.cache/lmnr/telemetry_anon_id`;\n private static readonly UNKNOWN_ANON_ID = \"UNKNOWN\";\n\n private telemetryEnabled: boolean;\n private posthog: PostHog | undefined;\n private anonId: string | undefined;\n\n public static getInstance(): Telemetry {\n if (!Telemetry.instance) {\n Telemetry.instance = new Telemetry();\n }\n return Telemetry.instance;\n }\n\n private constructor() {\n this.telemetryEnabled =\n !process.env.LMNR_TELEMETRY ||\n process.env.LMNR_TELEMETRY.toLowerCase() === \"true\";\n\n if (this.telemetryEnabled) {\n this.posthog = new PostHog(\n \"phc_dUMdjfNKf11jcHgtn7juSnT4P1pO0tafsPUWt4PuwG7\",\n );\n }\n }\n\n private getAnonId() {\n if (this.anonId) {\n return this.anonId;\n }\n\n try {\n if (!fs.existsSync(Telemetry.ANON_ID_PATH)) {\n fs.mkdirSync(path.dirname(Telemetry.ANON_ID_PATH), { recursive: true });\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"w\");\n this.anonId = uuid();\n fs.writeSync(anonIdFile, this.anonId);\n fs.closeSync(anonIdFile);\n } else {\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"r\");\n this.anonId = fs.readFileSync(anonIdFile, \"utf8\");\n fs.closeSync(anonIdFile);\n }\n return this.anonId;\n } catch (e) {\n return Telemetry.UNKNOWN_ANON_ID;\n }\n }\n\n private getContext() {\n return {\n sdk: \"typescript\",\n sdk_version: version,\n };\n }\n\n public capture(event: string, properties?: Record<string, string>) {\n if (this.telemetryEnabled && this.posthog) {\n this.posthog.capture({\n distinctId: this.getAnonId(),\n event,\n properties: {\n ...properties,\n ...this.getContext(),\n },\n });\n this.posthog.flush();\n }\n }\n\n public logException(error: Error) {\n if (this.telemetryEnabled) {\n this.capture(\"error\", { error: error.message, stack: error.stack || \"\" });\n }\n }\n}\n","import { InitializeOptions } from \"../interfaces\";\nimport { startTracing } from \"../tracing\";\nimport { diag, DiagConsoleLogger, DiagLogLevel } from \"@opentelemetry/api\";\nimport { InitializationError } from \"../errors\";\n\nexport let _configuration: InitializeOptions | undefined;\n\n/**\n * Initializes the SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n * @throws {InitializationError} if the configuration is invalid or if failed to fetch feature data.\n */\nexport const initialize = (options: InitializeOptions) => {\n if (_configuration) {\n return;\n }\n\n if (!options.baseUrl) {\n options.baseUrl =\n process.env.LMNR_BASE_URL || \"https://api.lmnr.ai:8443\";\n }\n if (!options.apiKey) {\n options.apiKey = process.env.LMNR_PROJECT_API_KEY;\n }\n if (options.apiKey && typeof options.apiKey !== \"string\") {\n throw new InitializationError('\"apiKey\" must be a string');\n }\n\n if (!options.appName) {\n options.appName = process.env.npm_package_name;\n }\n\n _configuration = Object.freeze(options);\n\n if (options.logLevel) {\n diag.setLogger(\n new DiagConsoleLogger(),\n logLevelToOtelLogLevel(options.logLevel),\n );\n }\n\n if (!options.silenceInitializationMessage) {\n console.log(\n `Laminar exporting traces to ${\n _configuration.exporter ? \"a custom exporter\" : _configuration.baseUrl\n }`,\n );\n }\n\n startTracing(_configuration);\n};\n\nconst logLevelToOtelLogLevel = (\n logLevel: \"debug\" | \"info\" | \"warn\" | \"error\",\n) => {\n switch (logLevel) {\n case \"debug\":\n return DiagLogLevel.DEBUG;\n case \"info\":\n return DiagLogLevel.INFO;\n case \"warn\":\n return DiagLogLevel.WARN;\n case \"error\":\n return DiagLogLevel.ERROR;\n }\n};\n","import { Span, context } from \"@opentelemetry/api\";\nimport { suppressTracing } from \"@opentelemetry/core\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n getTracer,\n} from \"./tracing\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\nimport { Telemetry } from \"../telemetry/telemetry\";\n\nexport type DecoratorConfig = {\n name: string;\n associationProperties?: { [name: string]: string };\n inputParameters?: unknown[];\n suppressTracing?: boolean;\n};\n\nexport function withEntity<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n {\n name,\n associationProperties,\n inputParameters,\n suppressTracing: shouldSuppressTracing,\n }: DecoratorConfig,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n let entityContext = context.active();\n\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n if (shouldSuppressTracing) {\n entityContext = suppressTracing(entityContext);\n }\n\n return context.with(entityContext, () =>\n getTracer().startActiveSpan(\n name,\n {},\n entityContext,\n async (span: Span) => {\n if (shouldSendTraces()) {\n try {\n const input = inputParameters ?? args;\n if (\n input.length === 1 &&\n typeof input[0] === \"object\" &&\n !(input[0] instanceof Map)\n ) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({ args: [], kwargs: input[0] }),\n );\n } else {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({\n args: input,\n kwargs: {},\n }),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n }\n }\n\n const res = fn.apply(thisArg, args);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(resolvedRes),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return resolvedRes;\n });\n }\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(res),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return res;\n },\n ),\n );\n}\n\nfunction cleanInput(input: unknown): unknown {\n if (input instanceof Map) {\n return Array.from(input.entries());\n } else if (Array.isArray(input)) {\n return input.map((value) => cleanInput(value));\n } else if (!input) {\n return input;\n } else if (typeof input === \"object\") {\n // serialize object one by one\n const output: any = {};\n Object.entries(input as any).forEach(([key, value]) => {\n output[key] = cleanInput(value);\n });\n return output;\n }\n\n return input;\n}\n\nfunction serialize(input: unknown): string {\n return JSON.stringify(cleanInput(input));\n}\n","import { Span, context, trace } from \"@opentelemetry/api\";\nimport { getTracer } from \"./tracing\";\nimport {\n Events,\n EventAttributes,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\n\ntype VectorDBCallConfig = {\n vendor: string;\n type: \"query\" | \"upsert\" | \"delete\";\n};\n\ntype LLMCallConfig = {\n vendor: string;\n type: \"chat\" | \"completion\";\n};\n\nexport class VectorSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportQuery({ queryVector }: { queryVector: number[] }) {\n if (!shouldSendTraces()) {\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS);\n }\n\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS, {\n [EventAttributes.DB_QUERY_EMBEDDINGS_VECTOR]: JSON.stringify(queryVector),\n });\n }\n\n reportResults({\n results,\n }: {\n results: {\n ids?: string;\n scores?: number;\n distances?: number;\n metadata?: Record<string, unknown>;\n vectors?: number[];\n documents?: string;\n }[];\n }) {\n for (let i = 0; i < results.length; i++) {\n this.span.addEvent(Events.DB_QUERY_RESULT, {\n [EventAttributes.DB_QUERY_RESULT_ID]: results[i].ids,\n [EventAttributes.DB_QUERY_RESULT_SCORE]: results[i].scores,\n [EventAttributes.DB_QUERY_RESULT_DISTANCE]: results[i].distances,\n [EventAttributes.DB_QUERY_RESULT_METADATA]: JSON.stringify(\n results[i].metadata,\n ),\n [EventAttributes.DB_QUERY_RESULT_VECTOR]: results[i].vectors,\n [EventAttributes.DB_QUERY_RESULT_DOCUMENT]: results[i].documents,\n });\n }\n }\n}\n\nexport class LLMSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportRequest({\n model,\n messages,\n }: {\n model: string;\n messages: {\n role: string;\n content?: string | unknown;\n }[];\n }) {\n this.span.setAttributes({\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n });\n\n messages.forEach((message, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_PROMPTS}.${index}.role`]: message.role,\n [`${SpanAttributes.LLM_PROMPTS}.${index}.content`]:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content),\n });\n });\n }\n\n reportResponse({\n model,\n usage,\n completions,\n }: {\n model: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n completions?: {\n finish_reason: string;\n message: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | null;\n };\n }[];\n }) {\n this.span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, model);\n\n if (usage) {\n this.span.setAttributes({\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: usage.prompt_tokens,\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: usage.completion_tokens,\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: usage.total_tokens,\n });\n }\n\n completions?.forEach((completion, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.finish_reason`]:\n completion.finish_reason,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.role`]:\n completion.message.role,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.content`]:\n completion.message.content || \"\",\n });\n });\n }\n}\n\nexport function withVectorDBCall<\n F extends ({ span }: { span: VectorSpan }) => ReturnType<F>,\n>({ vendor, type }: VectorDBCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const entityContext = context.active();\n\n return getTracer().startActiveSpan(\n `${vendor}.${type}`,\n { [SpanAttributes.LLM_REQUEST_TYPE]: type },\n entityContext,\n (span: Span) => {\n const res = fn.apply(thisArg, [{ span: new VectorSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n },\n );\n}\n\nexport function withLLMCall<\n F extends ({ span }: { span: LLMSpan }) => ReturnType<F>,\n>({ vendor, type }: LLMCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const span = getTracer().startSpan(`${vendor}.${type}`, {}, context.active());\n span.setAttribute(SpanAttributes.LLM_REQUEST_TYPE, type);\n trace.setSpan(context.active(), span);\n\n const res = fn.apply(thisArg, [{ span: new LLMSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n}\n","import { context } from \"@opentelemetry/api\";\nimport { ASSOCIATION_PROPERTIES_KEY } from \"./tracing\";\n\nexport function withAssociationProperties<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context\n .active()\n .setValue(ASSOCIATION_PROPERTIES_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n","import { v4 as uuidv4 } from 'uuid';\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const newUUID = (): StringUUID => {\n // crypto.randomUUID is available in most of the modern browsers and node,\n // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n // so we fallback to uuidv4 in those cases, which is less secure, but works\n // just fine.\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n } else {\n return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n }\n}\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 16) {\n console.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n }\n\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.padStart(32, '0').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n\nexport const otelTraceIdToUUID = (traceId: string): string => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 32) {\n console.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n }\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n","import { Laminar } from \"./laminar\";\nimport { CreateEvaluationResponse, EvaluationDatapoint } from \"./types\";\n\nconst DEFAULT_BATCH_SIZE = 5;\n\n/**\n * Configuration for the Evaluator\n */\ninterface EvaluatorConfig {\n batchSize?: number;\n projectApiKey?: string;\n baseUrl?: string;\n}\n\nexport abstract class Dataset<D, T> {\n public slice(start: number, end: number): Datapoint<D, T>[] {\n const result = [];\n for (let i = Math.max(start, 0); i < Math.min(end, this.size()); i++) {\n result.push(this.get(i));\n }\n return result;\n }\n public abstract size(): number;\n public abstract get(index: number): Datapoint<D, T>;\n}\n\n/**\n * Datapoint is a single data point in the evaluation. `D` is the type of the input data, `T` is the type of the target data.\n */\nexport type Datapoint<D, T> = {\n /**\n * input to the executor function. Must be a record with string keys and any values.\n */\n data: Record<string, any> & D;\n /**\n * input to the evaluator function (alongside the executor output).\n * Must be a record with string keys and any values.\n */\n target: Record<string, any> & T;\n}\n\ntype EvaluatorFunctionReturn = number | Record<string, number>;\n\n/**\n * EvaluatorFunction is a function that takes the output of the executor and the target data, and returns a score.\n * The score can be a single number or a record of string keys and number values. The latter is useful for evaluating\n * multiple criteria in one go instead of running multiple evaluators.\n */\ntype EvaluatorFunction<O, T> = (output: O, target: T, ...args: any[]) => EvaluatorFunctionReturn | Promise<EvaluatorFunctionReturn>;\n\ninterface EvaluatorConstructorProps<D, T, O> {\n /**\n * List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n */\n data: (Datapoint<D, T>[]) | Dataset<D, T>;\n /**\n * The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n */\n executor: (data: D, ...args: any[]) => O | Promise<O>;\n /**\n * List of evaluator functions. Each evaluator function takes the output of the executor _and_ the target data, and returns\n * a score. The score can be a single number or a record of string keys and number values.\n * If the score is a single number, it will be named after the evaluator function. If the function is anonymous, it will be named\n * `evaluator_${index}`, where index is the index of the evaluator function in the list starting from 1.\n */\n evaluators: EvaluatorFunction<O, T>[];\n /**\n * Optional override configurations for the evaluator.\n */\n config?: EvaluatorConfig;\n}\n\nexport class Evaluation<D, T, O> {\n private name: string;\n private data: Datapoint<D, T>[] | Dataset<D, T>;\n private executor: (data: D, ...args: any[]) => O | Promise<O>;\n private evaluators: Record<string, EvaluatorFunction<O, T>>;\n private evaluatorNames: string[];\n private batchSize: number = DEFAULT_BATCH_SIZE;\n\n /**\n * Create a new evaluation and prepare data.\n * @param name Name of the evaluation.\n * @param props.data List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n * @param props.executor The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n * @param props.evaluators List of evaluator functions. Each evaluator function takes the output of the executor and the target data, and returns.\n */\n constructor(name: string, {\n data, executor, evaluators, config\n }: EvaluatorConstructorProps<D, T, O>) {\n this.name = name;\n this.data = data;\n this.executor = executor;\n this.evaluators = Object.fromEntries(evaluators.map((e, i) => [e.name.length > 0 ? e.name : `evaluator_${i + 1}`, e]));\n this.evaluatorNames = evaluators.map((e, i) => e.name.length > 0 ? e.name : `evaluator_${i + 1}`);\n if (config) {\n this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;\n }\n Laminar.initialize({ projectApiKey: config?.projectApiKey, baseUrl: config?.baseUrl });\n }\n\n /** \n * Runs the evaluation.\n *\n * Creates a new evaluation if no evaluation with such name exists, or adds data to an existing one otherwise.\n * Evaluates data points in batches of `batchSize`. The executor function is called on each data point\n * to get the output, and then evaluate it by each evaluator function.\n */\n public async run(): Promise<void> {\n const response = await Laminar.createEvaluation(this.name) as CreateEvaluationResponse;\n const length = this.data instanceof Dataset ? this.data.size() : this.data.length;\n for (let i = 0; i < length; i += this.batchSize) {\n const batch = this.data.slice(i, i + this.batchSize);\n try {\n await this.evaluateBatch(batch);\n } catch (e) {\n console.error(`Error evaluating batch: ${e}`);\n }\n }\n try {\n // After all batches are completed, update the evaluation status\n await Laminar.updateEvaluationStatus(response.name, 'Finished');\n } catch (e) {\n console.error(`Error updating evaluation status: ${e}`);\n }\n }\n \n private async evaluateBatch(batch: Datapoint<D, T>[]): Promise<void> {\n const batchPromises = batch.map(async (datapoint) => {\n const output = await this.executor(datapoint.data);\n const target = datapoint.target;\n \n let scores: Record<string, EvaluatorFunctionReturn> = {};\n for (const evaluatorName of this.evaluatorNames) {\n const evaluator = this.evaluators[evaluatorName];\n const value = await evaluator(output, target);\n \n // If the evaluator returns a single number, use the evaluator name as the key\n if (typeof value === 'number') {\n scores[evaluatorName] = value;\n } else {\n // If the evaluator returns an object, merge its keys with the existing scores (flatten)\n scores = { ...scores, ...value };\n }\n }\n \n return {\n executorOutput: output,\n data: datapoint.data,\n target,\n scores,\n } as EvaluationDatapoint<D, T, O>;\n });\n \n const results = await Promise.all(batchPromises);\n \n return Laminar.postEvaluationResults(this.name, results);\n }\n \n}\n","import { withEntity } from './sdk/node-server-sdk'\n\ninterface ObserveOptions {\n name?: string;\n sessionId?: string;\n userId?: string;\n}\n\n/**\n * The main decorator entrypoint for Laminar. This is used to wrap\n * functions and methods to create spans.\n *\n * @param name - Name of the span. Function name is used if not specified.\n * @param user_id - User ID to associate with the span and the following context.\n * @param session_id - Session ID to associate with the span and the following context.\n * @returns Returns the result of the wrapped function.\n * @throws Exception - Re-throws the exception if the wrapped function throws an exception.\n * \n * @example\n * ```typescript\n * import { observe } from '@lmnr-ai/lmnr';\n * \n * await observe({ name: 'my_function' }, () => {\n * // Your code here\n * });\n */\nexport async function observe<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n {\n name,\n sessionId,\n userId,\n }: ObserveOptions, fn: F, ...args: A): Promise<ReturnType<F>> {\n\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n return await withEntity<A, F>({ name: name ?? fn.name, associationProperties }, fn, undefined, ...args);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iBAAAA,UAAA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BAAO,aAAa,IAAI;AAAA,QAC5B,OAAO;AAEH,mBAAS,EAAE,GAAG,QAAQ,GAAG,MAAM;AAAA,QACnC;AAAA,MACJ;AAEA,aAAO;AAAA,QACH,gBAAgB;AAAA,QAChB,MAAM,UAAU;AAAA,QAChB;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAED,UAAM,UAAU,MAAM,QAAQ,IAAI,aAAa;AAE/C,WAAO,QAAQ,sBAAsB,KAAK,MAAM,OAAO;AAAA,EAC3D;AAEJ;;;ACrIA,eAAsB,QAClB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AACJ,GAAmB,OAAU,MAAiC;AAE9D,MAAI,wBAAwB,CAAC;AAC7B,MAAI,WAAW;AACX,4BAAwB,EAAE,GAAG,uBAAuB,cAAc,UAAU;AAAA,EAChF;AACA,MAAI,QAAQ;AACR,4BAAwB,EAAE,GAAG,uBAAuB,WAAW,OAAO;AAAA,EAC1E;AAEA,SAAO,MAAM,WAAiB,EAAE,MAAM,sBAAQ,GAAG,MAAM,sBAAsB,GAAG,IAAI,QAAW,GAAG,IAAI;AAC1G;","names":["exports","module","import_api","import_api","uuid","import_sdk_trace_node","import_api","import_api","import_core","import_ai_semantic_conventions","import_api","import_ai_semantic_conventions","import_api","import_uuid","uuidv4"]}
package/dist/index.mjs CHANGED
@@ -8,7 +8,7 @@ var require_package = __commonJS({
8
8
  "package.json"(exports, module) {
9
9
  module.exports = {
10
10
  name: "@lmnr-ai/lmnr",
11
- version: "0.4.9-alpha",
11
+ version: "0.4.10-alpha",
12
12
  description: "TypeScript SDK for Laminar AI",
13
13
  main: "dist/index.js",
14
14
  types: "dist/index.d.ts",
@@ -61,7 +61,6 @@ var require_package = __commonJS({
61
61
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.53.0",
62
62
  "@opentelemetry/exporter-trace-otlp-proto": "^0.53.0",
63
63
  "@opentelemetry/instrumentation": "^0.53.0",
64
- "@opentelemetry/resources": "^1.26.0",
65
64
  "@opentelemetry/sdk-node": "^0.53.0",
66
65
  "@opentelemetry/sdk-trace-base": "^1.26.0",
67
66
  "@opentelemetry/sdk-trace-node": "^1.26.0",
@@ -108,7 +107,6 @@ var InitializationError = class extends TraceloopError {
108
107
  };
109
108
 
110
109
  // src/sdk/tracing/index.ts
111
- import { NodeSDK } from "@opentelemetry/sdk-node";
112
110
  import {
113
111
  SimpleSpanProcessor,
114
112
  BatchSpanProcessor
@@ -116,13 +114,6 @@ import {
116
114
  import { baggageUtils } from "@opentelemetry/core";
117
115
  import { context, diag } from "@opentelemetry/api";
118
116
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
119
- import { Resource } from "@opentelemetry/resources";
120
- import { SEMRESATTRS_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
121
- import {
122
- envDetectorSync,
123
- hostDetectorSync,
124
- processDetectorSync
125
- } from "@opentelemetry/resources";
126
117
 
127
118
  // src/sdk/tracing/tracing.ts
128
119
  import { trace, createContextKey } from "@opentelemetry/api";
@@ -212,6 +203,8 @@ var Telemetry = _Telemetry;
212
203
  import {
213
204
  SpanAttributes
214
205
  } from "@traceloop/ai-semantic-conventions";
206
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
207
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
215
208
  import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
216
209
  import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
217
210
  import { AzureOpenAIInstrumentation } from "@traceloop/instrumentation-azure";
@@ -226,7 +219,6 @@ import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
226
219
  import { LangChainInstrumentation } from "@traceloop/instrumentation-langchain";
227
220
  import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
228
221
  import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
229
- var _sdk;
230
222
  var _spanProcessor;
231
223
  var openAIInstrumentation;
232
224
  var anthropicInstrumentation;
@@ -363,16 +355,6 @@ var manuallyInitInstrumentations = (instrumentModules) => {
363
355
  qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);
364
356
  }
365
357
  };
366
- function awaitAttributes(detector) {
367
- return {
368
- async detect(config) {
369
- var _a;
370
- const resource = detector.detect(config);
371
- await ((_a = resource.waitForAsyncAttributes) == null ? void 0 : _a.call(resource));
372
- return resource;
373
- }
374
- };
375
- }
376
358
  var startTracing = (options) => {
377
359
  var _a, _b;
378
360
  if (options.instrumentModules !== void 0) {
@@ -434,28 +416,13 @@ var startTracing = (options) => {
434
416
  processor: options.disableBatch ? "simple" : "batch"
435
417
  });
436
418
  }
437
- const spanProcessors = [_spanProcessor];
438
- if (options.processor) {
439
- spanProcessors.push(options.processor);
440
- }
441
- _sdk = new NodeSDK({
442
- resource: new Resource({
443
- [SEMRESATTRS_SERVICE_NAME]: options.appName || process.env.npm_package_name
444
- }),
445
- spanProcessors,
446
- contextManager: options.contextManager,
447
- textMapPropagator: options.propagator,
448
- traceExporter,
419
+ const provider = new NodeTracerProvider();
420
+ provider.addSpanProcessor(_spanProcessor);
421
+ provider.register();
422
+ registerInstrumentations({
449
423
  instrumentations,
450
- // We should re-consider removing irrelevant spans here in the future
451
- // sampler: new TraceloopSampler(),
452
- resourceDetectors: [
453
- awaitAttributes(envDetectorSync),
454
- awaitAttributes(processDetectorSync),
455
- awaitAttributes(hostDetectorSync)
456
- ]
424
+ tracerProvider: provider
457
425
  });
458
- _sdk.start();
459
426
  };
460
427
  var shouldSendTraces = () => {
461
428
  if (!_configuration) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/laminar.ts","../src/sdk/errors/index.ts","../src/sdk/tracing/index.ts","../src/sdk/tracing/tracing.ts","../src/sdk/telemetry/telemetry.ts","../src/sdk/configuration/index.ts","../src/sdk/tracing/decorators.ts","../src/sdk/tracing/manual.ts","../src/sdk/tracing/association.ts","../src/utils.ts","../src/evaluations.ts","../src/decorators.ts"],"sourcesContent":["{\n \"name\": \"@lmnr-ai/lmnr\",\n \"version\": \"0.4.9-alpha\",\n \"description\": \"TypeScript SDK for Laminar AI\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/lmnr-ai/lmnr-ts.git\"\n },\n \"keywords\": [\n \"laminar\",\n \"lmnr\",\n \"sdk\",\n \"lmnr.ai\"\n ],\n \"author\": \"founders@lmnr.ai\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/lmnr-ai/lmnr-ts/issues\"\n },\n \"homepage\": \"https://github.com/lmnr-ai/lmnr-ts#README\",\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@aws-sdk/client-bedrock-runtime\": \"^3.649.0\",\n \"@azure/openai\": \"2.0.0-beta.2\",\n \"@google-cloud/aiplatform\": \"^3.29.0\",\n \"@google-cloud/vertexai\": \"^1.7.0\",\n \"@langchain/core\": \"^0.2.32\",\n \"@pinecone-database/pinecone\": \"^3.0.2\",\n \"@qdrant/js-client-rest\": \"^1.11.0\",\n \"@types/node\": \"^22.5.4\",\n \"@types/uuid\": \"^10.0.0\",\n \"bufferutil\": \"^4.0.8\",\n \"chromadb\": \"^1.8.1\",\n \"cohere-ai\": \"^7.13.0\",\n \"langchain\": \"^0.2.18\",\n \"llamaindex\": \"^0.5.23\",\n \"openai\": \"^4.58.2\",\n \"runnables\": \"link:@langchain/core/runnables\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vectorstores\": \"link:@langchain/core/vectorstores\"\n },\n \"dependencies\": {\n \"@grpc/grpc-js\": \"^1.11.2\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/core\": \"^1.26.0\",\n \"@opentelemetry/exporter-trace-otlp-grpc\": \"^0.53.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.53.0\",\n \"@opentelemetry/instrumentation\": \"^0.53.0\",\n \"@opentelemetry/resources\": \"^1.26.0\",\n \"@opentelemetry/sdk-node\": \"^0.53.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.26.0\",\n \"@opentelemetry/sdk-trace-node\": \"^1.26.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.27.0\",\n \"@traceloop/ai-semantic-conventions\": \"^0.11.0\",\n \"@traceloop/instrumentation-anthropic\": \"^0.11.1\",\n \"@traceloop/instrumentation-azure\": \"^0.11.1\",\n \"@traceloop/instrumentation-bedrock\": \"^0.11.1\",\n \"@traceloop/instrumentation-chromadb\": \"^0.11.1\",\n \"@traceloop/instrumentation-cohere\": \"^0.11.1\",\n \"@traceloop/instrumentation-langchain\": \"^0.11.1\",\n \"@traceloop/instrumentation-llamaindex\": \"^0.11.1\",\n \"@traceloop/instrumentation-openai\": \"^0.11.1\",\n \"@traceloop/instrumentation-pinecone\": \"^0.11.1\",\n \"@traceloop/instrumentation-qdrant\": \"^0.11.1\",\n \"@traceloop/instrumentation-vertexai\": \"^0.11.1\",\n \"posthog-node\": \"^4.2.0\",\n \"uuid\": \"^10.0.0\"\n }\n}","import { PipelineRunResponse, PipelineRunRequest, EvaluationDatapoint, EvaluationStatus } from './types';\nimport { Attributes, AttributeValue, context, createContextKey, isSpanContextValid, TimeInput, trace } from '@opentelemetry/api';\nimport { InitializeOptions, initialize as traceloopInitialize } from './sdk/node-server-sdk'\nimport { otelSpanIdToUUID, otelTraceIdToUUID } from './utils';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { Metadata } from '@grpc/grpc-js';\nimport { ASSOCIATION_PROPERTIES_KEY } from './sdk/tracing/tracing';\nimport { forceFlush } from './sdk/node-server-sdk';\n\n// quick patch to get the traceloop's default tracer, since their \n// `getTracer` function is not exported.\n// Another option would be to import directly \n// like so: `import { getTracer } from '@traceloop/node-server-sdk/dist/src/lib/tracing/tracing';`\n// which isn't too nice either.\nconst DEFAULT_TRACER_NAME = 'traceloop.tracer';\n\ninterface LaminarInitializeProps {\n projectApiKey?: string;\n env?: Record<string, string>;\n baseUrl?: string;\n instrumentModules?: InitializeOptions[\"instrumentModules\"];\n}\n\nexport class Laminar {\n private static baseUrl: string = 'https://api.lmnr.ai:8443';\n private static projectApiKey: string;\n private static env: Record<string, string> = {};\n private static isInitialized: boolean = false;\n\n /**\n * Initialize Laminar context across the application.\n * This method must be called before using any other Laminar methods or decorators.\n *\n * @param project_api_key - Laminar project api key. You can generate one by going\n * to the projects settings page on the Laminar dashboard.\n * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable.\n * @param env - Default environment passed to `run` and `evaluateEvent` requests,\n * unless overriden at request time. Usually, model provider keys are stored here.\n * @param baseUrl - Url of Laminar endpoint, or the custom open telemetry ingester.\n * If not specified, defaults to https://api.lmnr.ai:8443. For locally hosted Laminar,\n * default setting must be http://localhost:8001.\n * @param instrumentModules - List of modules to instrument.\n * If not specified, all auto-instrumentable modules will be instrumented, which include\n * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n * Pass an empty object {} to disable any kind of automatic instrumentation.\n * If you only want to auto-instrument specific modules, then pass them in the object.\n * \n * Example:\n * ```typescript\n * import { Laminar as L } from '@lmnr-ai/lmnr';\n * import { OpenAI } from 'openai';\n * import * as ChainsModule from \"langchain/chains\";\n * \n * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules.\n * L.initialize({ projectApiKey: \"<LMNR_PROJECT_API_KEY>\", instrumentModules: {\n * langchain: {\n * chainsModule: ChainsModule\n * },\n * openAI: OpenAI\n * } });\n * ```\n *\n * @throws {Error} - If project API key is not set\n */\n public static initialize({\n projectApiKey,\n env,\n baseUrl,\n instrumentModules\n }: LaminarInitializeProps) {\n\n let key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n if (key === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n this.projectApiKey = key;\n if (baseUrl) {\n this.baseUrl = baseUrl;\n }\n this.isInitialized = true;\n this.env = env ?? {};\n\n const metadata = new Metadata();\n metadata.set('authorization', `Bearer ${this.projectApiKey}`);\n const exporter = new OTLPTraceExporter({\n url: this.baseUrl,\n metadata,\n });\n\n traceloopInitialize({\n exporter,\n silenceInitializationMessage: true,\n instrumentModules,\n disableBatch: false,\n });\n }\n\n /**\n * Check if Laminar has been initialized. Utility to make sure other methods\n * are called after initialization.\n */\n public static initialized(): boolean {\n return this.isInitialized;\n }\n\n /**\n * Sets the environment that will be sent to Laminar requests.\n * \n * @param env - The environment variables to override. If not provided, the current environment will not be modified.\n */\n public static setEnv(env?: Record<string, string>) {\n if (env) {\n this.env = env;\n }\n }\n\n /**\n * Sets the project API key for authentication with Laminar.\n *\n * @param projectApiKey - The API key to be set. If not provided, the existing API key will not be modified.\n */\n public static setProjectApiKey(projectApiKey?: string) {\n if (projectApiKey) {\n this.projectApiKey = projectApiKey;\n }\n }\n\n /**\n * Runs the pipeline with the given inputs\n *\n * @param pipeline - The name of the Laminar pipeline. Pipeline must have a target version.\n * @param inputs - The inputs for the pipeline. Map from an input node name to input data.\n * @param env - The environment variables for the pipeline execution. Typically used for model provider keys.\n * @param metadata - Additional metadata for the pipeline run.\n * @param currentSpanId - The ID of the current span.\n * @param currentTraceId - The ID of the current trace.\n * @returns A promise that resolves to the response of the pipeline run.\n * @throws An error if the Laminar object is not initialized with a project API key. Or if the request fails.\n */\n public static async run({\n pipeline,\n inputs,\n env,\n metadata = {},\n currentSpanId,\n currentTraceId,\n }: PipelineRunRequest): Promise<PipelineRunResponse> {\n const currentSpan = trace.getActiveSpan();\n let parentSpanId: string | undefined;\n let traceId: string | undefined;\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n parentSpanId = currentSpanId ?? otelSpanIdToUUID(currentSpan.spanContext().spanId);\n traceId = currentTraceId ?? otelTraceIdToUUID(currentSpan.spanContext().traceId);\n } else {\n parentSpanId = currentSpanId;\n traceId = currentTraceId;\n }\n if (this.projectApiKey === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n const envirionment = env === undefined ? this.env : env;\n\n const response = await fetch(`${this.baseUrl}/v1/pipeline/run`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n inputs,\n pipeline,\n env: envirionment,\n metadata,\n parentSpanId,\n traceId,\n })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to run pipeline ${pipeline}. Response: ${response.statusText}`);\n }\n try {\n return await response.json() as PipelineRunResponse;\n } catch (error) {\n throw new Error(`Failed to parse response from pipeline ${pipeline}. Error: ${error}`);\n }\n }\n\n /**\n * Associates an event with the current span. If event with such name never\n * existed, Laminar will create a new event and infer its type from the value.\n * If the event already exists, Laminar will append the value to the event\n * if and only if the value is of a matching type. Otherwise, the event won't\n * be recorded. Supported types are string, number, and boolean. If the value\n * is `null`, event is considered a boolean tag with the value of `true`.\n *\n * @param name - The name of the event.\n * @param value - The value of the event. Must be a primitive type. If not specified, boolean true is assumed in the backend.\n * @param timestamp - The timestamp of the event. If not specified, relies on the underlying OpenTelemetry implementation.\n * If specified as an integer, it must be epoch nanoseconds.\n */\n public static event(\n name: string,\n value?: AttributeValue,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().event()\\` called outside of span context.\" +\n ` Event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event: Attributes = {\n \"lmnr.event.type\": \"default\",\n }\n if (value !== undefined) {\n event[\"lmnr.event.value\"] = value;\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sends an event for evaluation to the Laminar backend.\n * \n * @param name - The name of the event.\n * @param evaluator - The name of the pipeline that evaluates the event.\n * @param data - A map from input node name to its value in the evaluator pipeline.\n * @param env - Environment variables required to run the pipeline.\n * @param timestamp - If specified as an integer, it must be epoch nanoseconds.\n * If not specified, relies on the underlying OpenTelemetry implementation.\n */\n public static evaluateEvent(\n name: string,\n evaluator: string,\n data: Record<string, any>,\n env?: Record<string, string>,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().evaluateEvent()\\` called outside of span context.\" +\n ` Evaluate event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event = {\n \"lmnr.event.type\": \"evaluate\",\n \"lmnr.event.evaluator\": evaluator,\n \"lmnr.event.data\": JSON.stringify(data),\n \"lmnr.event.env\": JSON.stringify(env ?? {}),\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sets the session information for the current span and returns the context to use for the following spans.\n * \n * Example:\n * ```typescript\n * import { context as contextApi } from '@opentelemetry/api';\n * import { Laminar } from '@lmnr-ai/laminar';\n * const context = Laminar.contextWithSession({ sessionId: \"1234\", userId: \"5678\" });\n * contextApi.with(context, () => {\n * // Your code here\n * });\n * ```\n * \n * @param sessionId - The session ID to associate with the span.\n * @param userId - The user ID to associate with the span.\n * @returns The updated context with the association properties.\n */\n public static contextWithSession({ sessionId, userId }: { sessionId?: string, userId?: string }) {\n\n const currentSpan = trace.getActiveSpan();\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n if (sessionId) {\n currentSpan.setAttribute(\"traceloop.association.properties.session_id\", sessionId);\n }\n if (userId) {\n currentSpan.setAttribute(\"traceloop.association.properties.user_id\", userId);\n }\n }\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n let entityContext = context.active();\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n return entityContext;\n }\n\n public static async shutdown() {\n await forceFlush();\n }\n\n public static async createEvaluation(name: string) {\n const response = await fetch(`${this.baseUrl}/v1/evaluations`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n name,\n })\n });\n\n return await response.json();\n }\n\n public static async postEvaluationResults<D, T, O>(\n evaluationName: string,\n data: EvaluationDatapoint<D, T, O>[]\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n points: data,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluation-datapoints`;\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to send evaluation results. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to send evaluation results. Error: \", error);\n };\n }\n\n public static async updateEvaluationStatus(\n evaluationName: string,\n status: EvaluationStatus,\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n status,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluations`;\n try {\n const response = await fetch(url, {\n method: \"PUT\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to update evaluation status. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to update evaluation status. Error: \", error);\n }\n }\n\n private static getHeaders() {\n return {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${this.projectApiKey}`,\n };\n };\n}\n","/**\n * The severity of an error.\n */\nexport const SEVERITY = {\n Warning: \"Warning\",\n Error: \"Error\",\n Critical: \"Critical\",\n} as const;\n\nexport type Severity = (typeof SEVERITY)[keyof typeof SEVERITY];\n\n/**\n * Base class for all Traceloop errors.\n */\nexport class TraceloopError extends Error {\n /**\n * The severity of the error.\n */\n severity: Severity;\n /**\n * The underlying cause of the error.\n */\n underlyingCause?: Error;\n\n constructor(message: string, severity: Severity = SEVERITY.Error) {\n super(message);\n this.severity = severity;\n }\n}\n\nexport class NotInitializedError extends TraceloopError {\n constructor() {\n super(\n `The Traceloop SDK must be initialized by calling the \"initialize\" function prior to use.`,\n SEVERITY.Critical,\n );\n }\n}\n\nexport class InitializationError extends TraceloopError {\n constructor(message?: string, cause?: Error) {\n super(message ?? \"Failed to initialize Traceloop SDK\", SEVERITY.Critical);\n this.underlyingCause = cause;\n }\n}\n\nexport class ArgumentNotProvidedError extends TraceloopError {\n constructor(argumentName: string) {\n super(`The \"${argumentName}\" argument is required and must be a string.`);\n }\n}\n\nexport class PromptNotFoundError extends TraceloopError {\n constructor(key: string) {\n super(`The prompt \"${key}\" was not found in the registry.`);\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n SimpleSpanProcessor,\n BatchSpanProcessor,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-node\";\nimport { baggageUtils } from \"@opentelemetry/core\";\nimport { Span, context, diag } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { Resource } from \"@opentelemetry/resources\";\nimport { SEMRESATTRS_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { InitializeOptions } from \"../interfaces\";\nimport {\n Detector,\n DetectorSync,\n IResource,\n ResourceDetectionConfig,\n envDetectorSync,\n hostDetectorSync,\n processDetectorSync,\n} from \"@opentelemetry/resources\"\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n} from \"./tracing\";\nimport { Telemetry } from \"../telemetry/telemetry\";\nimport { _configuration } from \"../configuration\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { AnthropicInstrumentation } from \"@traceloop/instrumentation-anthropic\";\nimport { OpenAIInstrumentation } from \"@traceloop/instrumentation-openai\";\nimport { AzureOpenAIInstrumentation } from \"@traceloop/instrumentation-azure\";\nimport { LlamaIndexInstrumentation } from \"@traceloop/instrumentation-llamaindex\";\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from \"@traceloop/instrumentation-vertexai\";\nimport { BedrockInstrumentation } from \"@traceloop/instrumentation-bedrock\";\nimport { CohereInstrumentation } from \"@traceloop/instrumentation-cohere\";\nimport { PineconeInstrumentation } from \"@traceloop/instrumentation-pinecone\";\nimport { LangChainInstrumentation } from \"@traceloop/instrumentation-langchain\";\nimport { ChromaDBInstrumentation } from \"@traceloop/instrumentation-chromadb\";\nimport { QdrantInstrumentation } from \"@traceloop/instrumentation-qdrant\";\n\nlet _sdk: NodeSDK;\nlet _spanProcessor: SimpleSpanProcessor | BatchSpanProcessor;\nlet openAIInstrumentation: OpenAIInstrumentation | undefined;\nlet anthropicInstrumentation: AnthropicInstrumentation | undefined;\nlet azureOpenAIInstrumentation: AzureOpenAIInstrumentation | undefined;\nlet cohereInstrumentation: CohereInstrumentation | undefined;\nlet vertexaiInstrumentation: VertexAIInstrumentation | undefined;\nlet aiplatformInstrumentation: AIPlatformInstrumentation | undefined;\nlet bedrockInstrumentation: BedrockInstrumentation | undefined;\nlet langchainInstrumentation: LangChainInstrumentation | undefined;\nlet llamaIndexInstrumentation: LlamaIndexInstrumentation | undefined;\nlet pineconeInstrumentation: PineconeInstrumentation | undefined;\nlet chromadbInstrumentation: ChromaDBInstrumentation | undefined;\nlet qdrantInstrumentation: QdrantInstrumentation | undefined;\n\n\nconst instrumentations: Instrumentation[] = [];\n\nconst initInstrumentations = () => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n\n anthropicInstrumentation = new AnthropicInstrumentation({ exceptionLogger });\n instrumentations.push(anthropicInstrumentation);\n\n azureOpenAIInstrumentation = new AzureOpenAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(azureOpenAIInstrumentation);\n\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n\n pineconeInstrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(pineconeInstrumentation);\n\n langchainInstrumentation = new LangChainInstrumentation({ exceptionLogger });\n instrumentations.push(langchainInstrumentation);\n\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n};\n\nconst manuallyInitInstrumentations = (\n instrumentModules: InitializeOptions[\"instrumentModules\"],\n) => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n instrumentations.length = 0;\n\n if (instrumentModules?.openAI) {\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n openAIInstrumentation.manuallyInstrument(instrumentModules.openAI);\n }\n\n if (instrumentModules?.anthropic) {\n anthropicInstrumentation = new AnthropicInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(anthropicInstrumentation);\n anthropicInstrumentation.manuallyInstrument(instrumentModules.anthropic);\n }\n\n if (instrumentModules?.azureOpenAI) {\n const instrumentation = new AzureOpenAIInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n azureOpenAIInstrumentation = instrumentation;\n instrumentation.manuallyInstrument(instrumentModules.azureOpenAI);\n }\n\n if (instrumentModules?.cohere) {\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n cohereInstrumentation.manuallyInstrument(instrumentModules.cohere);\n }\n\n if (instrumentModules?.google_vertexai) {\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n vertexaiInstrumentation.manuallyInstrument(\n instrumentModules.google_vertexai,\n );\n }\n\n if (instrumentModules?.google_aiplatform) {\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n aiplatformInstrumentation.manuallyInstrument(\n instrumentModules.google_aiplatform,\n );\n }\n\n if (instrumentModules?.bedrock) {\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n bedrockInstrumentation.manuallyInstrument(instrumentModules.bedrock);\n }\n\n if (instrumentModules?.pinecone) {\n const instrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n instrumentation.manuallyInstrument(instrumentModules.pinecone);\n }\n\n if (instrumentModules?.langchain) {\n langchainInstrumentation = new LangChainInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(langchainInstrumentation);\n langchainInstrumentation.manuallyInstrument(instrumentModules.langchain);\n }\n\n if (instrumentModules?.llamaIndex) {\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n llamaIndexInstrumentation.manuallyInstrument(instrumentModules.llamaIndex);\n }\n\n if (instrumentModules?.chromadb) {\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n chromadbInstrumentation.manuallyInstrument(instrumentModules.chromadb);\n }\n\n if (instrumentModules?.qdrant) {\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);\n }\n};\n\nfunction awaitAttributes(detector: DetectorSync): Detector {\n return {\n async detect(config?: ResourceDetectionConfig): Promise<IResource> {\n const resource = detector.detect(config)\n await resource.waitForAsyncAttributes?.()\n\n return resource\n },\n }\n}\n\n/**\n * Initializes the Traceloop SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n */\nexport const startTracing = (options: InitializeOptions) => {\n if (options.instrumentModules !== undefined) {\n // If options.instrumentModules is empty, it will not initialize anything,\n // so empty dict can essentially be passed to disable any kind of automatic instrumentation.\n manuallyInitInstrumentations(options.instrumentModules);\n } else {\n initInstrumentations();\n }\n\n if (!shouldSendTraces()) {\n openAIInstrumentation?.setConfig({\n traceContent: false,\n });\n azureOpenAIInstrumentation?.setConfig({\n traceContent: false,\n });\n llamaIndexInstrumentation?.setConfig({\n traceContent: false,\n });\n vertexaiInstrumentation?.setConfig({\n traceContent: false,\n });\n aiplatformInstrumentation?.setConfig({\n traceContent: false,\n });\n bedrockInstrumentation?.setConfig({\n traceContent: false,\n });\n cohereInstrumentation?.setConfig({\n traceContent: false,\n });\n chromadbInstrumentation?.setConfig({\n traceContent: false,\n });\n }\n\n const headers = process.env.TRACELOOP_HEADERS\n ? baggageUtils.parseKeyPairsIntoRecord(process.env.TRACELOOP_HEADERS)\n : { Authorization: `Bearer ${options.apiKey}` };\n\n const traceExporter =\n options.exporter ??\n new OTLPTraceExporter({\n url: `${options.baseUrl}/v1/traces`,\n headers,\n });\n _spanProcessor = options.disableBatch\n ? new SimpleSpanProcessor(traceExporter)\n : new BatchSpanProcessor(traceExporter);\n\n _spanProcessor.onStart = (span: Span) => {\n // This sets the properties only if the context has them\n const associationProperties = context\n .active()\n .getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(\n `${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`,\n value,\n );\n }\n }\n };\n\n if (options.exporter) {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: \"custom\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n } else {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: options.baseUrl ?? \"\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n }\n\n const spanProcessors: SpanProcessor[] = [_spanProcessor];\n if (options.processor) {\n spanProcessors.push(options.processor);\n }\n\n _sdk = new NodeSDK({\n resource: new Resource({\n [SEMRESATTRS_SERVICE_NAME]:\n options.appName || process.env.npm_package_name,\n }),\n spanProcessors,\n contextManager: options.contextManager,\n textMapPropagator: options.propagator,\n traceExporter,\n instrumentations,\n // We should re-consider removing irrelevant spans here in the future\n // sampler: new TraceloopSampler(),\n resourceDetectors: [\n awaitAttributes(envDetectorSync),\n awaitAttributes(processDetectorSync),\n awaitAttributes(hostDetectorSync),\n ],\n });\n\n _sdk.start();\n};\n\nexport const shouldSendTraces = () => {\n if (!_configuration) {\n diag.warn(\"Traceloop not initialized\");\n return false;\n }\n\n if (\n _configuration.traceContent === false ||\n (process.env.TRACELOOP_TRACE_CONTENT || \"true\").toLowerCase() === \"false\"\n ) {\n return false;\n }\n\n return true;\n};\n\nexport const forceFlush = async () => {\n await _spanProcessor.forceFlush();\n};\n","import { trace, createContextKey } from \"@opentelemetry/api\";\nimport { Context } from \"@opentelemetry/api/build/src/context/types\";\n\nconst TRACER_NAME = \"traceloop.tracer\";\nexport const WORKFLOW_NAME_KEY = createContextKey(\"workflow_name\");\nexport const ENTITY_NAME_KEY = createContextKey(\"entity_name\");\nexport const ASSOCIATION_PROPERTIES_KEY = createContextKey(\n \"association_properties\",\n);\n\nexport const getTracer = () => {\n return trace.getTracer(TRACER_NAME);\n};\n\nexport const getEntityPath = (entityContext: Context): string | undefined => {\n const path = entityContext.getValue(ENTITY_NAME_KEY);\n\n return path ? `${path}` : undefined;\n};\n","import * as os from \"os\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { v4 as uuid } from \"uuid\";\nimport { PostHog } from \"posthog-node\";\nconst { version } = require('../../../package.json');\n\nexport class Telemetry {\n private static instance: Telemetry;\n\n private static readonly ANON_ID_PATH = `${os.homedir()}/.cache/lmnr/telemetry_anon_id`;\n private static readonly UNKNOWN_ANON_ID = \"UNKNOWN\";\n\n private telemetryEnabled: boolean;\n private posthog: PostHog | undefined;\n private anonId: string | undefined;\n\n public static getInstance(): Telemetry {\n if (!Telemetry.instance) {\n Telemetry.instance = new Telemetry();\n }\n return Telemetry.instance;\n }\n\n private constructor() {\n this.telemetryEnabled =\n !process.env.LMNR_TELEMETRY ||\n process.env.LMNR_TELEMETRY.toLowerCase() === \"true\";\n\n if (this.telemetryEnabled) {\n this.posthog = new PostHog(\n \"phc_dUMdjfNKf11jcHgtn7juSnT4P1pO0tafsPUWt4PuwG7\",\n );\n }\n }\n\n private getAnonId() {\n if (this.anonId) {\n return this.anonId;\n }\n\n try {\n if (!fs.existsSync(Telemetry.ANON_ID_PATH)) {\n fs.mkdirSync(path.dirname(Telemetry.ANON_ID_PATH), { recursive: true });\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"w\");\n this.anonId = uuid();\n fs.writeSync(anonIdFile, this.anonId);\n fs.closeSync(anonIdFile);\n } else {\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"r\");\n this.anonId = fs.readFileSync(anonIdFile, \"utf8\");\n fs.closeSync(anonIdFile);\n }\n return this.anonId;\n } catch (e) {\n return Telemetry.UNKNOWN_ANON_ID;\n }\n }\n\n private getContext() {\n return {\n sdk: \"typescript\",\n sdk_version: version,\n };\n }\n\n public capture(event: string, properties?: Record<string, string>) {\n if (this.telemetryEnabled && this.posthog) {\n this.posthog.capture({\n distinctId: this.getAnonId(),\n event,\n properties: {\n ...properties,\n ...this.getContext(),\n },\n });\n this.posthog.flush();\n }\n }\n\n public logException(error: Error) {\n if (this.telemetryEnabled) {\n this.capture(\"error\", { error: error.message, stack: error.stack || \"\" });\n }\n }\n}\n","import { InitializeOptions } from \"../interfaces\";\nimport { startTracing } from \"../tracing\";\nimport { diag, DiagConsoleLogger, DiagLogLevel } from \"@opentelemetry/api\";\nimport { InitializationError } from \"../errors\";\n\nexport let _configuration: InitializeOptions | undefined;\n\n/**\n * Initializes the SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n * @throws {InitializationError} if the configuration is invalid or if failed to fetch feature data.\n */\nexport const initialize = (options: InitializeOptions) => {\n if (_configuration) {\n return;\n }\n\n if (!options.baseUrl) {\n options.baseUrl =\n process.env.LMNR_BASE_URL || \"https://api.lmnr.ai:8443\";\n }\n if (!options.apiKey) {\n options.apiKey = process.env.LMNR_PROJECT_API_KEY;\n }\n if (options.apiKey && typeof options.apiKey !== \"string\") {\n throw new InitializationError('\"apiKey\" must be a string');\n }\n\n if (!options.appName) {\n options.appName = process.env.npm_package_name;\n }\n\n _configuration = Object.freeze(options);\n\n if (options.logLevel) {\n diag.setLogger(\n new DiagConsoleLogger(),\n logLevelToOtelLogLevel(options.logLevel),\n );\n }\n\n if (!options.silenceInitializationMessage) {\n console.log(\n `Laminar exporting traces to ${\n _configuration.exporter ? \"a custom exporter\" : _configuration.baseUrl\n }`,\n );\n }\n\n startTracing(_configuration);\n};\n\nconst logLevelToOtelLogLevel = (\n logLevel: \"debug\" | \"info\" | \"warn\" | \"error\",\n) => {\n switch (logLevel) {\n case \"debug\":\n return DiagLogLevel.DEBUG;\n case \"info\":\n return DiagLogLevel.INFO;\n case \"warn\":\n return DiagLogLevel.WARN;\n case \"error\":\n return DiagLogLevel.ERROR;\n }\n};\n","import { Span, context } from \"@opentelemetry/api\";\nimport { suppressTracing } from \"@opentelemetry/core\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n getTracer,\n} from \"./tracing\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\nimport { Telemetry } from \"../telemetry/telemetry\";\n\nexport type DecoratorConfig = {\n name: string;\n associationProperties?: { [name: string]: string };\n inputParameters?: unknown[];\n suppressTracing?: boolean;\n};\n\nexport function withEntity<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n {\n name,\n associationProperties,\n inputParameters,\n suppressTracing: shouldSuppressTracing,\n }: DecoratorConfig,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n let entityContext = context.active();\n\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n if (shouldSuppressTracing) {\n entityContext = suppressTracing(entityContext);\n }\n\n return context.with(entityContext, () =>\n getTracer().startActiveSpan(\n name,\n {},\n entityContext,\n async (span: Span) => {\n if (shouldSendTraces()) {\n try {\n const input = inputParameters ?? args;\n if (\n input.length === 1 &&\n typeof input[0] === \"object\" &&\n !(input[0] instanceof Map)\n ) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({ args: [], kwargs: input[0] }),\n );\n } else {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({\n args: input,\n kwargs: {},\n }),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n }\n }\n\n const res = fn.apply(thisArg, args);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(resolvedRes),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return resolvedRes;\n });\n }\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(res),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return res;\n },\n ),\n );\n}\n\nfunction cleanInput(input: unknown): unknown {\n if (input instanceof Map) {\n return Array.from(input.entries());\n } else if (Array.isArray(input)) {\n return input.map((value) => cleanInput(value));\n } else if (!input) {\n return input;\n } else if (typeof input === \"object\") {\n // serialize object one by one\n const output: any = {};\n Object.entries(input as any).forEach(([key, value]) => {\n output[key] = cleanInput(value);\n });\n return output;\n }\n\n return input;\n}\n\nfunction serialize(input: unknown): string {\n return JSON.stringify(cleanInput(input));\n}\n","import { Span, context, trace } from \"@opentelemetry/api\";\nimport { getTracer } from \"./tracing\";\nimport {\n Events,\n EventAttributes,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\n\ntype VectorDBCallConfig = {\n vendor: string;\n type: \"query\" | \"upsert\" | \"delete\";\n};\n\ntype LLMCallConfig = {\n vendor: string;\n type: \"chat\" | \"completion\";\n};\n\nexport class VectorSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportQuery({ queryVector }: { queryVector: number[] }) {\n if (!shouldSendTraces()) {\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS);\n }\n\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS, {\n [EventAttributes.DB_QUERY_EMBEDDINGS_VECTOR]: JSON.stringify(queryVector),\n });\n }\n\n reportResults({\n results,\n }: {\n results: {\n ids?: string;\n scores?: number;\n distances?: number;\n metadata?: Record<string, unknown>;\n vectors?: number[];\n documents?: string;\n }[];\n }) {\n for (let i = 0; i < results.length; i++) {\n this.span.addEvent(Events.DB_QUERY_RESULT, {\n [EventAttributes.DB_QUERY_RESULT_ID]: results[i].ids,\n [EventAttributes.DB_QUERY_RESULT_SCORE]: results[i].scores,\n [EventAttributes.DB_QUERY_RESULT_DISTANCE]: results[i].distances,\n [EventAttributes.DB_QUERY_RESULT_METADATA]: JSON.stringify(\n results[i].metadata,\n ),\n [EventAttributes.DB_QUERY_RESULT_VECTOR]: results[i].vectors,\n [EventAttributes.DB_QUERY_RESULT_DOCUMENT]: results[i].documents,\n });\n }\n }\n}\n\nexport class LLMSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportRequest({\n model,\n messages,\n }: {\n model: string;\n messages: {\n role: string;\n content?: string | unknown;\n }[];\n }) {\n this.span.setAttributes({\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n });\n\n messages.forEach((message, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_PROMPTS}.${index}.role`]: message.role,\n [`${SpanAttributes.LLM_PROMPTS}.${index}.content`]:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content),\n });\n });\n }\n\n reportResponse({\n model,\n usage,\n completions,\n }: {\n model: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n completions?: {\n finish_reason: string;\n message: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | null;\n };\n }[];\n }) {\n this.span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, model);\n\n if (usage) {\n this.span.setAttributes({\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: usage.prompt_tokens,\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: usage.completion_tokens,\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: usage.total_tokens,\n });\n }\n\n completions?.forEach((completion, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.finish_reason`]:\n completion.finish_reason,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.role`]:\n completion.message.role,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.content`]:\n completion.message.content || \"\",\n });\n });\n }\n}\n\nexport function withVectorDBCall<\n F extends ({ span }: { span: VectorSpan }) => ReturnType<F>,\n>({ vendor, type }: VectorDBCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const entityContext = context.active();\n\n return getTracer().startActiveSpan(\n `${vendor}.${type}`,\n { [SpanAttributes.LLM_REQUEST_TYPE]: type },\n entityContext,\n (span: Span) => {\n const res = fn.apply(thisArg, [{ span: new VectorSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n },\n );\n}\n\nexport function withLLMCall<\n F extends ({ span }: { span: LLMSpan }) => ReturnType<F>,\n>({ vendor, type }: LLMCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const span = getTracer().startSpan(`${vendor}.${type}`, {}, context.active());\n span.setAttribute(SpanAttributes.LLM_REQUEST_TYPE, type);\n trace.setSpan(context.active(), span);\n\n const res = fn.apply(thisArg, [{ span: new LLMSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n}\n","import { context } from \"@opentelemetry/api\";\nimport { ASSOCIATION_PROPERTIES_KEY } from \"./tracing\";\n\nexport function withAssociationProperties<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context\n .active()\n .setValue(ASSOCIATION_PROPERTIES_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n","import { v4 as uuidv4 } from 'uuid';\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const newUUID = (): StringUUID => {\n // crypto.randomUUID is available in most of the modern browsers and node,\n // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n // so we fallback to uuidv4 in those cases, which is less secure, but works\n // just fine.\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n } else {\n return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n }\n}\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 16) {\n console.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n }\n\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.padStart(32, '0').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n\nexport const otelTraceIdToUUID = (traceId: string): string => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 32) {\n console.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n }\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n","import { Laminar } from \"./laminar\";\nimport { CreateEvaluationResponse, EvaluationDatapoint } from \"./types\";\n\nconst DEFAULT_BATCH_SIZE = 5;\n\n/**\n * Configuration for the Evaluator\n */\ninterface EvaluatorConfig {\n batchSize?: number;\n projectApiKey?: string;\n baseUrl?: string;\n}\n\nexport abstract class Dataset<D, T> {\n public slice(start: number, end: number): Datapoint<D, T>[] {\n const result = [];\n for (let i = Math.max(start, 0); i < Math.min(end, this.size()); i++) {\n result.push(this.get(i));\n }\n return result;\n }\n public abstract size(): number;\n public abstract get(index: number): Datapoint<D, T>;\n}\n\n/**\n * Datapoint is a single data point in the evaluation. `D` is the type of the input data, `T` is the type of the target data.\n */\nexport type Datapoint<D, T> = {\n /**\n * input to the executor function. Must be a record with string keys and any values.\n */\n data: Record<string, any> & D;\n /**\n * input to the evaluator function (alongside the executor output).\n * Must be a record with string keys and any values.\n */\n target: Record<string, any> & T;\n}\n\ntype EvaluatorFunctionReturn = number | Record<string, number>;\n\n/**\n * EvaluatorFunction is a function that takes the output of the executor and the target data, and returns a score.\n * The score can be a single number or a record of string keys and number values. The latter is useful for evaluating\n * multiple criteria in one go instead of running multiple evaluators.\n */\ntype EvaluatorFunction<O, T> = (output: O, target: T, ...args: any[]) => EvaluatorFunctionReturn | Promise<EvaluatorFunctionReturn>;\n\ninterface EvaluatorConstructorProps<D, T, O> {\n /**\n * List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n */\n data: (Datapoint<D, T>[]) | Dataset<D, T>;\n /**\n * The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n */\n executor: (data: D, ...args: any[]) => O | Promise<O>;\n /**\n * List of evaluator functions. Each evaluator function takes the output of the executor _and_ the target data, and returns\n * a score. The score can be a single number or a record of string keys and number values.\n * If the score is a single number, it will be named after the evaluator function. If the function is anonymous, it will be named\n * `evaluator_${index}`, where index is the index of the evaluator function in the list starting from 1.\n */\n evaluators: EvaluatorFunction<O, T>[];\n /**\n * Optional override configurations for the evaluator.\n */\n config?: EvaluatorConfig;\n}\n\nexport class Evaluation<D, T, O> {\n private name: string;\n private data: Datapoint<D, T>[] | Dataset<D, T>;\n private executor: (data: D, ...args: any[]) => O | Promise<O>;\n private evaluators: Record<string, EvaluatorFunction<O, T>>;\n private evaluatorNames: string[];\n private batchSize: number = DEFAULT_BATCH_SIZE;\n\n /**\n * Create a new evaluation and prepare data.\n * @param name Name of the evaluation.\n * @param props.data List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n * @param props.executor The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n * @param props.evaluators List of evaluator functions. Each evaluator function takes the output of the executor and the target data, and returns.\n */\n constructor(name: string, {\n data, executor, evaluators, config\n }: EvaluatorConstructorProps<D, T, O>) {\n this.name = name;\n this.data = data;\n this.executor = executor;\n this.evaluators = Object.fromEntries(evaluators.map((e, i) => [e.name.length > 0 ? e.name : `evaluator_${i + 1}`, e]));\n this.evaluatorNames = evaluators.map((e, i) => e.name.length > 0 ? e.name : `evaluator_${i + 1}`);\n if (config) {\n this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;\n }\n Laminar.initialize({ projectApiKey: config?.projectApiKey, baseUrl: config?.baseUrl });\n }\n\n /** \n * Runs the evaluation.\n *\n * Creates a new evaluation if no evaluation with such name exists, or adds data to an existing one otherwise.\n * Evaluates data points in batches of `batchSize`. The executor function is called on each data point\n * to get the output, and then evaluate it by each evaluator function.\n */\n public async run(): Promise<void> {\n const response = await Laminar.createEvaluation(this.name) as CreateEvaluationResponse;\n const length = this.data instanceof Dataset ? this.data.size() : this.data.length;\n for (let i = 0; i < length; i += this.batchSize) {\n const batch = this.data.slice(i, i + this.batchSize);\n try {\n await this.evaluateBatch(batch);\n } catch (e) {\n console.error(`Error evaluating batch: ${e}`);\n }\n }\n try {\n // After all batches are completed, update the evaluation status\n await Laminar.updateEvaluationStatus(response.name, 'Finished');\n } catch (e) {\n console.error(`Error updating evaluation status: ${e}`);\n }\n }\n \n private async evaluateBatch(batch: Datapoint<D, T>[]): Promise<void> {\n const batchPromises = batch.map(async (datapoint) => {\n const output = await this.executor(datapoint.data);\n const target = datapoint.target;\n \n let scores: Record<string, EvaluatorFunctionReturn> = {};\n for (const evaluatorName of this.evaluatorNames) {\n const evaluator = this.evaluators[evaluatorName];\n const value = await evaluator(output, target);\n \n // If the evaluator returns a single number, use the evaluator name as the key\n if (typeof value === 'number') {\n scores[evaluatorName] = value;\n } else {\n // If the evaluator returns an object, merge its keys with the existing scores (flatten)\n scores = { ...scores, ...value };\n }\n }\n \n return {\n executorOutput: output,\n data: datapoint.data,\n target,\n scores,\n } as EvaluationDatapoint<D, T, O>;\n });\n \n const results = await Promise.all(batchPromises);\n \n return Laminar.postEvaluationResults(this.name, results);\n }\n \n}\n","import { withEntity } from './sdk/node-server-sdk'\n\ninterface ObserveOptions {\n name?: string;\n sessionId?: string;\n userId?: string;\n}\n\n/**\n * The main decorator entrypoint for Laminar. This is used to wrap\n * functions and methods to create spans.\n *\n * @param name - Name of the span. Function name is used if not specified.\n * @param user_id - User ID to associate with the span and the following context.\n * @param session_id - Session ID to associate with the span and the following context.\n * @returns Returns the result of the wrapped function.\n * @throws Exception - Re-throws the exception if the wrapped function throws an exception.\n * \n * @example\n * ```typescript\n * import { observe } from '@lmnr-ai/lmnr';\n * \n * await observe({ name: 'my_function' }, () => {\n * // Your code here\n * });\n */\nexport async function observe<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n {\n name,\n sessionId,\n userId,\n }: ObserveOptions, fn: F, ...args: A): Promise<ReturnType<F>> {\n\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n return await withEntity<A, F>({ name: name ?? fn.name, associationProperties }, fn, undefined, ...args);\n}\n"],"mappings":";;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,QAAU;AAAA,MACV,SAAW;AAAA,MACX,MAAQ;AAAA,QACN,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,MACZ,iBAAmB;AAAA,QACjB,qBAAqB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AEA,YAAM,QAAQ,uBAAuB,SAAS,MAAM,UAAU;AAAA,IAClE,SAAS,GAAG;AACR,cAAQ,MAAM,qCAAqC,CAAC,EAAE;AAAA,IAC1D;AAAA,EACJ;AAAA,EAEA,MAAc,cAAc,OAAyC;AACjE,UAAM,gBAAgB,MAAM,IAAI,OAAO,cAAc;AACjD,YAAM,SAAS,MAAM,KAAK,SAAS,UAAU,IAAI;AACjD,YAAM,SAAS,UAAU;AAEzB,UAAI,SAAkD,CAAC;AACvD,iBAAW,iBAAiB,KAAK,gBAAgB;AAC7C,cAAM,YAAY,KAAK,WAAW,aAAa;AAC/C,cAAM,QAAQ,MAAM,UAAU,QAAQ,MAAM;AAG5C,YAAI,OAAO,UAAU,UAAU;AAC3B,iBAAO,aAAa,IAAI;AAAA,QAC5B,OAAO;AAEH,mBAAS,EAAE,GAAG,QAAQ,GAAG,MAAM;AAAA,QACnC;AAAA,MACJ;AAEA,aAAO;AAAA,QACH,gBAAgB;AAAA,QAChB,MAAM,UAAU;AAAA,QAChB;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAED,UAAM,UAAU,MAAM,QAAQ,IAAI,aAAa;AAE/C,WAAO,QAAQ,sBAAsB,KAAK,MAAM,OAAO;AAAA,EAC3D;AAEJ;;;ACrIA,eAAsB,QAClB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AACJ,GAAmB,OAAU,MAAiC;AAE9D,MAAI,wBAAwB,CAAC;AAC7B,MAAI,WAAW;AACX,4BAAwB,EAAE,GAAG,uBAAuB,cAAc,UAAU;AAAA,EAChF;AACA,MAAI,QAAQ;AACR,4BAAwB,EAAE,GAAG,uBAAuB,WAAW,OAAO;AAAA,EAC1E;AAEA,SAAO,MAAM,WAAiB,EAAE,MAAM,sBAAQ,GAAG,MAAM,sBAAsB,GAAG,IAAI,QAAW,GAAG,IAAI;AAC1G;","names":["context","trace","diag","diag","context","SpanAttributes","context","SpanAttributes","context","trace","SpanAttributes","context","OTLPTraceExporter","OTLPTraceExporter","trace","context"]}
1
+ {"version":3,"sources":["../package.json","../src/laminar.ts","../src/sdk/errors/index.ts","../src/sdk/tracing/index.ts","../src/sdk/tracing/tracing.ts","../src/sdk/telemetry/telemetry.ts","../src/sdk/configuration/index.ts","../src/sdk/tracing/decorators.ts","../src/sdk/tracing/manual.ts","../src/sdk/tracing/association.ts","../src/utils.ts","../src/evaluations.ts","../src/decorators.ts"],"sourcesContent":["{\n \"name\": \"@lmnr-ai/lmnr\",\n \"version\": \"0.4.10-alpha\",\n \"description\": \"TypeScript SDK for Laminar AI\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/lmnr-ai/lmnr-ts.git\"\n },\n \"keywords\": [\n \"laminar\",\n \"lmnr\",\n \"sdk\",\n \"lmnr.ai\"\n ],\n \"author\": \"founders@lmnr.ai\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/lmnr-ai/lmnr-ts/issues\"\n },\n \"homepage\": \"https://github.com/lmnr-ai/lmnr-ts#README\",\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@aws-sdk/client-bedrock-runtime\": \"^3.649.0\",\n \"@azure/openai\": \"2.0.0-beta.2\",\n \"@google-cloud/aiplatform\": \"^3.29.0\",\n \"@google-cloud/vertexai\": \"^1.7.0\",\n \"@langchain/core\": \"^0.2.32\",\n \"@pinecone-database/pinecone\": \"^3.0.2\",\n \"@qdrant/js-client-rest\": \"^1.11.0\",\n \"@types/node\": \"^22.5.4\",\n \"@types/uuid\": \"^10.0.0\",\n \"bufferutil\": \"^4.0.8\",\n \"chromadb\": \"^1.8.1\",\n \"cohere-ai\": \"^7.13.0\",\n \"langchain\": \"^0.2.18\",\n \"llamaindex\": \"^0.5.23\",\n \"openai\": \"^4.58.2\",\n \"runnables\": \"link:@langchain/core/runnables\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vectorstores\": \"link:@langchain/core/vectorstores\"\n },\n \"dependencies\": {\n \"@grpc/grpc-js\": \"^1.11.2\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/core\": \"^1.26.0\",\n \"@opentelemetry/exporter-trace-otlp-grpc\": \"^0.53.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.53.0\",\n \"@opentelemetry/instrumentation\": \"^0.53.0\",\n \"@opentelemetry/sdk-node\": \"^0.53.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.26.0\",\n \"@opentelemetry/sdk-trace-node\": \"^1.26.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.27.0\",\n \"@traceloop/ai-semantic-conventions\": \"^0.11.0\",\n \"@traceloop/instrumentation-anthropic\": \"^0.11.1\",\n \"@traceloop/instrumentation-azure\": \"^0.11.1\",\n \"@traceloop/instrumentation-bedrock\": \"^0.11.1\",\n \"@traceloop/instrumentation-chromadb\": \"^0.11.1\",\n \"@traceloop/instrumentation-cohere\": \"^0.11.1\",\n \"@traceloop/instrumentation-langchain\": \"^0.11.1\",\n \"@traceloop/instrumentation-llamaindex\": \"^0.11.1\",\n \"@traceloop/instrumentation-openai\": \"^0.11.1\",\n \"@traceloop/instrumentation-pinecone\": \"^0.11.1\",\n \"@traceloop/instrumentation-qdrant\": \"^0.11.1\",\n \"@traceloop/instrumentation-vertexai\": \"^0.11.1\",\n \"posthog-node\": \"^4.2.0\",\n \"uuid\": \"^10.0.0\"\n }\n}","import { PipelineRunResponse, PipelineRunRequest, EvaluationDatapoint, EvaluationStatus } from './types';\nimport { Attributes, AttributeValue, context, createContextKey, isSpanContextValid, TimeInput, trace } from '@opentelemetry/api';\nimport { InitializeOptions, initialize as traceloopInitialize } from './sdk/node-server-sdk'\nimport { otelSpanIdToUUID, otelTraceIdToUUID } from './utils';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';\nimport { Metadata } from '@grpc/grpc-js';\nimport { ASSOCIATION_PROPERTIES_KEY } from './sdk/tracing/tracing';\nimport { forceFlush } from './sdk/node-server-sdk';\n\n// quick patch to get the traceloop's default tracer, since their \n// `getTracer` function is not exported.\n// Another option would be to import directly \n// like so: `import { getTracer } from '@traceloop/node-server-sdk/dist/src/lib/tracing/tracing';`\n// which isn't too nice either.\nconst DEFAULT_TRACER_NAME = 'traceloop.tracer';\n\ninterface LaminarInitializeProps {\n projectApiKey?: string;\n env?: Record<string, string>;\n baseUrl?: string;\n instrumentModules?: InitializeOptions[\"instrumentModules\"];\n}\n\nexport class Laminar {\n private static baseUrl: string = 'https://api.lmnr.ai:8443';\n private static projectApiKey: string;\n private static env: Record<string, string> = {};\n private static isInitialized: boolean = false;\n\n /**\n * Initialize Laminar context across the application.\n * This method must be called before using any other Laminar methods or decorators.\n *\n * @param project_api_key - Laminar project api key. You can generate one by going\n * to the projects settings page on the Laminar dashboard.\n * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable.\n * @param env - Default environment passed to `run` and `evaluateEvent` requests,\n * unless overriden at request time. Usually, model provider keys are stored here.\n * @param baseUrl - Url of Laminar endpoint, or the custom open telemetry ingester.\n * If not specified, defaults to https://api.lmnr.ai:8443. For locally hosted Laminar,\n * default setting must be http://localhost:8001.\n * @param instrumentModules - List of modules to instrument.\n * If not specified, all auto-instrumentable modules will be instrumented, which include\n * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n * Pass an empty object {} to disable any kind of automatic instrumentation.\n * If you only want to auto-instrument specific modules, then pass them in the object.\n * \n * Example:\n * ```typescript\n * import { Laminar as L } from '@lmnr-ai/lmnr';\n * import { OpenAI } from 'openai';\n * import * as ChainsModule from \"langchain/chains\";\n * \n * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules.\n * L.initialize({ projectApiKey: \"<LMNR_PROJECT_API_KEY>\", instrumentModules: {\n * langchain: {\n * chainsModule: ChainsModule\n * },\n * openAI: OpenAI\n * } });\n * ```\n *\n * @throws {Error} - If project API key is not set\n */\n public static initialize({\n projectApiKey,\n env,\n baseUrl,\n instrumentModules\n }: LaminarInitializeProps) {\n\n let key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n if (key === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n this.projectApiKey = key;\n if (baseUrl) {\n this.baseUrl = baseUrl;\n }\n this.isInitialized = true;\n this.env = env ?? {};\n\n const metadata = new Metadata();\n metadata.set('authorization', `Bearer ${this.projectApiKey}`);\n const exporter = new OTLPTraceExporter({\n url: this.baseUrl,\n metadata,\n });\n\n traceloopInitialize({\n exporter,\n silenceInitializationMessage: true,\n instrumentModules,\n disableBatch: false,\n });\n }\n\n /**\n * Check if Laminar has been initialized. Utility to make sure other methods\n * are called after initialization.\n */\n public static initialized(): boolean {\n return this.isInitialized;\n }\n\n /**\n * Sets the environment that will be sent to Laminar requests.\n * \n * @param env - The environment variables to override. If not provided, the current environment will not be modified.\n */\n public static setEnv(env?: Record<string, string>) {\n if (env) {\n this.env = env;\n }\n }\n\n /**\n * Sets the project API key for authentication with Laminar.\n *\n * @param projectApiKey - The API key to be set. If not provided, the existing API key will not be modified.\n */\n public static setProjectApiKey(projectApiKey?: string) {\n if (projectApiKey) {\n this.projectApiKey = projectApiKey;\n }\n }\n\n /**\n * Runs the pipeline with the given inputs\n *\n * @param pipeline - The name of the Laminar pipeline. Pipeline must have a target version.\n * @param inputs - The inputs for the pipeline. Map from an input node name to input data.\n * @param env - The environment variables for the pipeline execution. Typically used for model provider keys.\n * @param metadata - Additional metadata for the pipeline run.\n * @param currentSpanId - The ID of the current span.\n * @param currentTraceId - The ID of the current trace.\n * @returns A promise that resolves to the response of the pipeline run.\n * @throws An error if the Laminar object is not initialized with a project API key. Or if the request fails.\n */\n public static async run({\n pipeline,\n inputs,\n env,\n metadata = {},\n currentSpanId,\n currentTraceId,\n }: PipelineRunRequest): Promise<PipelineRunResponse> {\n const currentSpan = trace.getActiveSpan();\n let parentSpanId: string | undefined;\n let traceId: string | undefined;\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n parentSpanId = currentSpanId ?? otelSpanIdToUUID(currentSpan.spanContext().spanId);\n traceId = currentTraceId ?? otelTraceIdToUUID(currentSpan.spanContext().traceId);\n } else {\n parentSpanId = currentSpanId;\n traceId = currentTraceId;\n }\n if (this.projectApiKey === undefined) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable'\n );\n }\n const envirionment = env === undefined ? this.env : env;\n\n const response = await fetch(`${this.baseUrl}/v1/pipeline/run`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n inputs,\n pipeline,\n env: envirionment,\n metadata,\n parentSpanId,\n traceId,\n })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to run pipeline ${pipeline}. Response: ${response.statusText}`);\n }\n try {\n return await response.json() as PipelineRunResponse;\n } catch (error) {\n throw new Error(`Failed to parse response from pipeline ${pipeline}. Error: ${error}`);\n }\n }\n\n /**\n * Associates an event with the current span. If event with such name never\n * existed, Laminar will create a new event and infer its type from the value.\n * If the event already exists, Laminar will append the value to the event\n * if and only if the value is of a matching type. Otherwise, the event won't\n * be recorded. Supported types are string, number, and boolean. If the value\n * is `null`, event is considered a boolean tag with the value of `true`.\n *\n * @param name - The name of the event.\n * @param value - The value of the event. Must be a primitive type. If not specified, boolean true is assumed in the backend.\n * @param timestamp - The timestamp of the event. If not specified, relies on the underlying OpenTelemetry implementation.\n * If specified as an integer, it must be epoch nanoseconds.\n */\n public static event(\n name: string,\n value?: AttributeValue,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().event()\\` called outside of span context.\" +\n ` Event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event: Attributes = {\n \"lmnr.event.type\": \"default\",\n }\n if (value !== undefined) {\n event[\"lmnr.event.value\"] = value;\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sends an event for evaluation to the Laminar backend.\n * \n * @param name - The name of the event.\n * @param evaluator - The name of the pipeline that evaluates the event.\n * @param data - A map from input node name to its value in the evaluator pipeline.\n * @param env - Environment variables required to run the pipeline.\n * @param timestamp - If specified as an integer, it must be epoch nanoseconds.\n * If not specified, relies on the underlying OpenTelemetry implementation.\n */\n public static evaluateEvent(\n name: string,\n evaluator: string,\n data: Record<string, any>,\n env?: Record<string, string>,\n timestamp?: TimeInput,\n ) {\n const currentSpan = trace.getActiveSpan();\n\n if (currentSpan === undefined || !isSpanContextValid(currentSpan.spanContext())) {\n console.warn(\"Laminar().evaluateEvent()\\` called outside of span context.\" +\n ` Evaluate event '${name}' will not be recorded in the trace.` +\n \" Make sure to annotate the function with a decorator\"\n );\n return;\n }\n\n const event = {\n \"lmnr.event.type\": \"evaluate\",\n \"lmnr.event.evaluator\": evaluator,\n \"lmnr.event.data\": JSON.stringify(data),\n \"lmnr.event.env\": JSON.stringify(env ?? {}),\n }\n\n currentSpan.addEvent(name, event, timestamp);\n }\n\n /**\n * Sets the session information for the current span and returns the context to use for the following spans.\n * \n * Example:\n * ```typescript\n * import { context as contextApi } from '@opentelemetry/api';\n * import { Laminar } from '@lmnr-ai/laminar';\n * const context = Laminar.contextWithSession({ sessionId: \"1234\", userId: \"5678\" });\n * contextApi.with(context, () => {\n * // Your code here\n * });\n * ```\n * \n * @param sessionId - The session ID to associate with the span.\n * @param userId - The user ID to associate with the span.\n * @returns The updated context with the association properties.\n */\n public static contextWithSession({ sessionId, userId }: { sessionId?: string, userId?: string }) {\n\n const currentSpan = trace.getActiveSpan();\n if (currentSpan !== undefined && isSpanContextValid(currentSpan.spanContext())) {\n if (sessionId) {\n currentSpan.setAttribute(\"traceloop.association.properties.session_id\", sessionId);\n }\n if (userId) {\n currentSpan.setAttribute(\"traceloop.association.properties.user_id\", userId);\n }\n }\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n let entityContext = context.active();\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n return entityContext;\n }\n\n public static async shutdown() {\n await forceFlush();\n }\n\n public static async createEvaluation(name: string) {\n const response = await fetch(`${this.baseUrl}/v1/evaluations`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({\n name,\n })\n });\n\n return await response.json();\n }\n\n public static async postEvaluationResults<D, T, O>(\n evaluationName: string,\n data: EvaluationDatapoint<D, T, O>[]\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n points: data,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluation-datapoints`;\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to send evaluation results. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to send evaluation results. Error: \", error);\n };\n }\n\n public static async updateEvaluationStatus(\n evaluationName: string,\n status: EvaluationStatus,\n ): Promise<void> {\n const body = JSON.stringify({\n name: evaluationName,\n status,\n });\n const headers = this.getHeaders();\n const url = `${this.baseUrl}/v1/evaluations`;\n try {\n const response = await fetch(url, {\n method: \"PUT\",\n headers,\n body,\n });\n if (!response.ok) {\n console.error(\"Failed to update evaluation status. Response: \");\n response.text().then((text) => console.error(text));\n }\n } catch (error) {\n console.error(\"Failed to update evaluation status. Error: \", error);\n }\n }\n\n private static getHeaders() {\n return {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${this.projectApiKey}`,\n };\n };\n}\n","/**\n * The severity of an error.\n */\nexport const SEVERITY = {\n Warning: \"Warning\",\n Error: \"Error\",\n Critical: \"Critical\",\n} as const;\n\nexport type Severity = (typeof SEVERITY)[keyof typeof SEVERITY];\n\n/**\n * Base class for all Traceloop errors.\n */\nexport class TraceloopError extends Error {\n /**\n * The severity of the error.\n */\n severity: Severity;\n /**\n * The underlying cause of the error.\n */\n underlyingCause?: Error;\n\n constructor(message: string, severity: Severity = SEVERITY.Error) {\n super(message);\n this.severity = severity;\n }\n}\n\nexport class NotInitializedError extends TraceloopError {\n constructor() {\n super(\n `The Traceloop SDK must be initialized by calling the \"initialize\" function prior to use.`,\n SEVERITY.Critical,\n );\n }\n}\n\nexport class InitializationError extends TraceloopError {\n constructor(message?: string, cause?: Error) {\n super(message ?? \"Failed to initialize Traceloop SDK\", SEVERITY.Critical);\n this.underlyingCause = cause;\n }\n}\n\nexport class ArgumentNotProvidedError extends TraceloopError {\n constructor(argumentName: string) {\n super(`The \"${argumentName}\" argument is required and must be a string.`);\n }\n}\n\nexport class PromptNotFoundError extends TraceloopError {\n constructor(key: string) {\n super(`The prompt \"${key}\" was not found in the registry.`);\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n SimpleSpanProcessor,\n BatchSpanProcessor,\n} from \"@opentelemetry/sdk-trace-node\";\nimport { baggageUtils } from \"@opentelemetry/core\";\nimport { Span, context, diag } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { InitializeOptions } from \"../interfaces\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n} from \"./tracing\";\nimport { Telemetry } from \"../telemetry/telemetry\";\nimport { _configuration } from \"../configuration\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport {NodeTracerProvider} from \"@opentelemetry/sdk-trace-node\";\nimport {registerInstrumentations} from \"@opentelemetry/instrumentation\";\nimport { AnthropicInstrumentation } from \"@traceloop/instrumentation-anthropic\";\nimport { OpenAIInstrumentation } from \"@traceloop/instrumentation-openai\";\nimport { AzureOpenAIInstrumentation } from \"@traceloop/instrumentation-azure\";\nimport { LlamaIndexInstrumentation } from \"@traceloop/instrumentation-llamaindex\";\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from \"@traceloop/instrumentation-vertexai\";\nimport { BedrockInstrumentation } from \"@traceloop/instrumentation-bedrock\";\nimport { CohereInstrumentation } from \"@traceloop/instrumentation-cohere\";\nimport { PineconeInstrumentation } from \"@traceloop/instrumentation-pinecone\";\nimport { LangChainInstrumentation } from \"@traceloop/instrumentation-langchain\";\nimport { ChromaDBInstrumentation } from \"@traceloop/instrumentation-chromadb\";\nimport { QdrantInstrumentation } from \"@traceloop/instrumentation-qdrant\";\n\nlet _spanProcessor: SimpleSpanProcessor | BatchSpanProcessor;\nlet openAIInstrumentation: OpenAIInstrumentation | undefined;\nlet anthropicInstrumentation: AnthropicInstrumentation | undefined;\nlet azureOpenAIInstrumentation: AzureOpenAIInstrumentation | undefined;\nlet cohereInstrumentation: CohereInstrumentation | undefined;\nlet vertexaiInstrumentation: VertexAIInstrumentation | undefined;\nlet aiplatformInstrumentation: AIPlatformInstrumentation | undefined;\nlet bedrockInstrumentation: BedrockInstrumentation | undefined;\nlet langchainInstrumentation: LangChainInstrumentation | undefined;\nlet llamaIndexInstrumentation: LlamaIndexInstrumentation | undefined;\nlet pineconeInstrumentation: PineconeInstrumentation | undefined;\nlet chromadbInstrumentation: ChromaDBInstrumentation | undefined;\nlet qdrantInstrumentation: QdrantInstrumentation | undefined;\n\n\nconst instrumentations: Instrumentation[] = [];\n\nconst initInstrumentations = () => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n\n anthropicInstrumentation = new AnthropicInstrumentation({ exceptionLogger });\n instrumentations.push(anthropicInstrumentation);\n\n azureOpenAIInstrumentation = new AzureOpenAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(azureOpenAIInstrumentation);\n\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n\n pineconeInstrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(pineconeInstrumentation);\n\n langchainInstrumentation = new LangChainInstrumentation({ exceptionLogger });\n instrumentations.push(langchainInstrumentation);\n\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n};\n\nconst manuallyInitInstrumentations = (\n instrumentModules: InitializeOptions[\"instrumentModules\"],\n) => {\n const exceptionLogger = (e: Error) => Telemetry.getInstance().logException(e);\n const enrichTokens =\n (process.env.TRACELOOP_ENRICH_TOKENS || \"true\").toLowerCase() === \"true\";\n\n instrumentations.length = 0;\n\n if (instrumentModules?.openAI) {\n openAIInstrumentation = new OpenAIInstrumentation({\n enrichTokens,\n exceptionLogger,\n });\n instrumentations.push(openAIInstrumentation);\n openAIInstrumentation.manuallyInstrument(instrumentModules.openAI);\n }\n\n if (instrumentModules?.anthropic) {\n anthropicInstrumentation = new AnthropicInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(anthropicInstrumentation);\n anthropicInstrumentation.manuallyInstrument(instrumentModules.anthropic);\n }\n\n if (instrumentModules?.azureOpenAI) {\n const instrumentation = new AzureOpenAIInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n azureOpenAIInstrumentation = instrumentation;\n instrumentation.manuallyInstrument(instrumentModules.azureOpenAI);\n }\n\n if (instrumentModules?.cohere) {\n cohereInstrumentation = new CohereInstrumentation({ exceptionLogger });\n instrumentations.push(cohereInstrumentation);\n cohereInstrumentation.manuallyInstrument(instrumentModules.cohere);\n }\n\n if (instrumentModules?.google_vertexai) {\n vertexaiInstrumentation = new VertexAIInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(vertexaiInstrumentation);\n vertexaiInstrumentation.manuallyInstrument(\n instrumentModules.google_vertexai,\n );\n }\n\n if (instrumentModules?.google_aiplatform) {\n aiplatformInstrumentation = new AIPlatformInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(aiplatformInstrumentation);\n aiplatformInstrumentation.manuallyInstrument(\n instrumentModules.google_aiplatform,\n );\n }\n\n if (instrumentModules?.bedrock) {\n bedrockInstrumentation = new BedrockInstrumentation({ exceptionLogger });\n instrumentations.push(bedrockInstrumentation);\n bedrockInstrumentation.manuallyInstrument(instrumentModules.bedrock);\n }\n\n if (instrumentModules?.pinecone) {\n const instrumentation = new PineconeInstrumentation({ exceptionLogger });\n instrumentations.push(instrumentation as Instrumentation);\n instrumentation.manuallyInstrument(instrumentModules.pinecone);\n }\n\n if (instrumentModules?.langchain) {\n langchainInstrumentation = new LangChainInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(langchainInstrumentation);\n langchainInstrumentation.manuallyInstrument(instrumentModules.langchain);\n }\n\n if (instrumentModules?.llamaIndex) {\n llamaIndexInstrumentation = new LlamaIndexInstrumentation({\n exceptionLogger,\n });\n instrumentations.push(llamaIndexInstrumentation);\n llamaIndexInstrumentation.manuallyInstrument(instrumentModules.llamaIndex);\n }\n\n if (instrumentModules?.chromadb) {\n chromadbInstrumentation = new ChromaDBInstrumentation({ exceptionLogger });\n instrumentations.push(chromadbInstrumentation);\n chromadbInstrumentation.manuallyInstrument(instrumentModules.chromadb);\n }\n\n if (instrumentModules?.qdrant) {\n qdrantInstrumentation = new QdrantInstrumentation({ exceptionLogger });\n instrumentations.push(qdrantInstrumentation);\n qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);\n }\n};\n\n/**\n * Initializes the Traceloop SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n */\nexport const startTracing = (options: InitializeOptions) => {\n if (options.instrumentModules !== undefined) {\n // If options.instrumentModules is empty, it will not initialize anything,\n // so empty dict can essentially be passed to disable any kind of automatic instrumentation.\n manuallyInitInstrumentations(options.instrumentModules);\n } else {\n initInstrumentations();\n }\n\n if (!shouldSendTraces()) {\n openAIInstrumentation?.setConfig({\n traceContent: false,\n });\n azureOpenAIInstrumentation?.setConfig({\n traceContent: false,\n });\n llamaIndexInstrumentation?.setConfig({\n traceContent: false,\n });\n vertexaiInstrumentation?.setConfig({\n traceContent: false,\n });\n aiplatformInstrumentation?.setConfig({\n traceContent: false,\n });\n bedrockInstrumentation?.setConfig({\n traceContent: false,\n });\n cohereInstrumentation?.setConfig({\n traceContent: false,\n });\n chromadbInstrumentation?.setConfig({\n traceContent: false,\n });\n }\n\n const headers = process.env.TRACELOOP_HEADERS\n ? baggageUtils.parseKeyPairsIntoRecord(process.env.TRACELOOP_HEADERS)\n : { Authorization: `Bearer ${options.apiKey}` };\n\n const traceExporter =\n options.exporter ??\n new OTLPTraceExporter({\n url: `${options.baseUrl}/v1/traces`,\n headers,\n });\n _spanProcessor = options.disableBatch\n ? new SimpleSpanProcessor(traceExporter)\n : new BatchSpanProcessor(traceExporter);\n\n _spanProcessor.onStart = (span: Span) => {\n // This sets the properties only if the context has them\n const associationProperties = context\n .active()\n .getValue(ASSOCIATION_PROPERTIES_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(\n `${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`,\n value,\n );\n }\n }\n };\n\n if (options.exporter) {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: \"custom\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n } else {\n Telemetry.getInstance().capture(\"tracer:init\", {\n exporter: options.baseUrl ?? \"\",\n processor: options.disableBatch ? \"simple\" : \"batch\",\n });\n }\n\n const provider = new NodeTracerProvider();\n provider.addSpanProcessor(_spanProcessor);\n provider.register();\n registerInstrumentations({\n instrumentations,\n tracerProvider: provider,\n });\n};\n\nexport const shouldSendTraces = () => {\n if (!_configuration) {\n diag.warn(\"Traceloop not initialized\");\n return false;\n }\n\n if (\n _configuration.traceContent === false ||\n (process.env.TRACELOOP_TRACE_CONTENT || \"true\").toLowerCase() === \"false\"\n ) {\n return false;\n }\n\n return true;\n};\n\nexport const forceFlush = async () => {\n await _spanProcessor.forceFlush();\n};\n","import { trace, createContextKey } from \"@opentelemetry/api\";\nimport { Context } from \"@opentelemetry/api/build/src/context/types\";\n\nconst TRACER_NAME = \"traceloop.tracer\";\nexport const WORKFLOW_NAME_KEY = createContextKey(\"workflow_name\");\nexport const ENTITY_NAME_KEY = createContextKey(\"entity_name\");\nexport const ASSOCIATION_PROPERTIES_KEY = createContextKey(\n \"association_properties\",\n);\n\nexport const getTracer = () => {\n return trace.getTracer(TRACER_NAME);\n};\n\nexport const getEntityPath = (entityContext: Context): string | undefined => {\n const path = entityContext.getValue(ENTITY_NAME_KEY);\n\n return path ? `${path}` : undefined;\n};\n","import * as os from \"os\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { v4 as uuid } from \"uuid\";\nimport { PostHog } from \"posthog-node\";\nconst { version } = require('../../../package.json');\n\nexport class Telemetry {\n private static instance: Telemetry;\n\n private static readonly ANON_ID_PATH = `${os.homedir()}/.cache/lmnr/telemetry_anon_id`;\n private static readonly UNKNOWN_ANON_ID = \"UNKNOWN\";\n\n private telemetryEnabled: boolean;\n private posthog: PostHog | undefined;\n private anonId: string | undefined;\n\n public static getInstance(): Telemetry {\n if (!Telemetry.instance) {\n Telemetry.instance = new Telemetry();\n }\n return Telemetry.instance;\n }\n\n private constructor() {\n this.telemetryEnabled =\n !process.env.LMNR_TELEMETRY ||\n process.env.LMNR_TELEMETRY.toLowerCase() === \"true\";\n\n if (this.telemetryEnabled) {\n this.posthog = new PostHog(\n \"phc_dUMdjfNKf11jcHgtn7juSnT4P1pO0tafsPUWt4PuwG7\",\n );\n }\n }\n\n private getAnonId() {\n if (this.anonId) {\n return this.anonId;\n }\n\n try {\n if (!fs.existsSync(Telemetry.ANON_ID_PATH)) {\n fs.mkdirSync(path.dirname(Telemetry.ANON_ID_PATH), { recursive: true });\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"w\");\n this.anonId = uuid();\n fs.writeSync(anonIdFile, this.anonId);\n fs.closeSync(anonIdFile);\n } else {\n const anonIdFile = fs.openSync(Telemetry.ANON_ID_PATH, \"r\");\n this.anonId = fs.readFileSync(anonIdFile, \"utf8\");\n fs.closeSync(anonIdFile);\n }\n return this.anonId;\n } catch (e) {\n return Telemetry.UNKNOWN_ANON_ID;\n }\n }\n\n private getContext() {\n return {\n sdk: \"typescript\",\n sdk_version: version,\n };\n }\n\n public capture(event: string, properties?: Record<string, string>) {\n if (this.telemetryEnabled && this.posthog) {\n this.posthog.capture({\n distinctId: this.getAnonId(),\n event,\n properties: {\n ...properties,\n ...this.getContext(),\n },\n });\n this.posthog.flush();\n }\n }\n\n public logException(error: Error) {\n if (this.telemetryEnabled) {\n this.capture(\"error\", { error: error.message, stack: error.stack || \"\" });\n }\n }\n}\n","import { InitializeOptions } from \"../interfaces\";\nimport { startTracing } from \"../tracing\";\nimport { diag, DiagConsoleLogger, DiagLogLevel } from \"@opentelemetry/api\";\nimport { InitializationError } from \"../errors\";\n\nexport let _configuration: InitializeOptions | undefined;\n\n/**\n * Initializes the SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions} for details.\n * @throws {InitializationError} if the configuration is invalid or if failed to fetch feature data.\n */\nexport const initialize = (options: InitializeOptions) => {\n if (_configuration) {\n return;\n }\n\n if (!options.baseUrl) {\n options.baseUrl =\n process.env.LMNR_BASE_URL || \"https://api.lmnr.ai:8443\";\n }\n if (!options.apiKey) {\n options.apiKey = process.env.LMNR_PROJECT_API_KEY;\n }\n if (options.apiKey && typeof options.apiKey !== \"string\") {\n throw new InitializationError('\"apiKey\" must be a string');\n }\n\n if (!options.appName) {\n options.appName = process.env.npm_package_name;\n }\n\n _configuration = Object.freeze(options);\n\n if (options.logLevel) {\n diag.setLogger(\n new DiagConsoleLogger(),\n logLevelToOtelLogLevel(options.logLevel),\n );\n }\n\n if (!options.silenceInitializationMessage) {\n console.log(\n `Laminar exporting traces to ${\n _configuration.exporter ? \"a custom exporter\" : _configuration.baseUrl\n }`,\n );\n }\n\n startTracing(_configuration);\n};\n\nconst logLevelToOtelLogLevel = (\n logLevel: \"debug\" | \"info\" | \"warn\" | \"error\",\n) => {\n switch (logLevel) {\n case \"debug\":\n return DiagLogLevel.DEBUG;\n case \"info\":\n return DiagLogLevel.INFO;\n case \"warn\":\n return DiagLogLevel.WARN;\n case \"error\":\n return DiagLogLevel.ERROR;\n }\n};\n","import { Span, context } from \"@opentelemetry/api\";\nimport { suppressTracing } from \"@opentelemetry/core\";\nimport {\n ASSOCIATION_PROPERTIES_KEY,\n getTracer,\n} from \"./tracing\";\nimport {\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\nimport { Telemetry } from \"../telemetry/telemetry\";\n\nexport type DecoratorConfig = {\n name: string;\n associationProperties?: { [name: string]: string };\n inputParameters?: unknown[];\n suppressTracing?: boolean;\n};\n\nexport function withEntity<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n {\n name,\n associationProperties,\n inputParameters,\n suppressTracing: shouldSuppressTracing,\n }: DecoratorConfig,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n let entityContext = context.active();\n\n const currentAssociationProperties = entityContext.getValue(ASSOCIATION_PROPERTIES_KEY);\n\n if (associationProperties) {\n entityContext = entityContext.setValue(\n ASSOCIATION_PROPERTIES_KEY,\n { ...(currentAssociationProperties ?? {}), ...associationProperties },\n );\n }\n\n if (shouldSuppressTracing) {\n entityContext = suppressTracing(entityContext);\n }\n\n return context.with(entityContext, () =>\n getTracer().startActiveSpan(\n name,\n {},\n entityContext,\n async (span: Span) => {\n if (shouldSendTraces()) {\n try {\n const input = inputParameters ?? args;\n if (\n input.length === 1 &&\n typeof input[0] === \"object\" &&\n !(input[0] instanceof Map)\n ) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({ args: [], kwargs: input[0] }),\n );\n } else {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_INPUT,\n serialize({\n args: input,\n kwargs: {},\n }),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n }\n }\n\n const res = fn.apply(thisArg, args);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(resolvedRes),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return resolvedRes;\n });\n }\n try {\n if (shouldSendTraces()) {\n span.setAttribute(\n SpanAttributes.TRACELOOP_ENTITY_OUTPUT,\n serialize(res),\n );\n }\n } catch (error) {\n Telemetry.getInstance().logException(error as any);\n } finally {\n span.end();\n }\n\n return res;\n },\n ),\n );\n}\n\nfunction cleanInput(input: unknown): unknown {\n if (input instanceof Map) {\n return Array.from(input.entries());\n } else if (Array.isArray(input)) {\n return input.map((value) => cleanInput(value));\n } else if (!input) {\n return input;\n } else if (typeof input === \"object\") {\n // serialize object one by one\n const output: any = {};\n Object.entries(input as any).forEach(([key, value]) => {\n output[key] = cleanInput(value);\n });\n return output;\n }\n\n return input;\n}\n\nfunction serialize(input: unknown): string {\n return JSON.stringify(cleanInput(input));\n}\n","import { Span, context, trace } from \"@opentelemetry/api\";\nimport { getTracer } from \"./tracing\";\nimport {\n Events,\n EventAttributes,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { shouldSendTraces } from \".\";\n\ntype VectorDBCallConfig = {\n vendor: string;\n type: \"query\" | \"upsert\" | \"delete\";\n};\n\ntype LLMCallConfig = {\n vendor: string;\n type: \"chat\" | \"completion\";\n};\n\nexport class VectorSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportQuery({ queryVector }: { queryVector: number[] }) {\n if (!shouldSendTraces()) {\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS);\n }\n\n this.span.addEvent(Events.DB_QUERY_EMBEDDINGS, {\n [EventAttributes.DB_QUERY_EMBEDDINGS_VECTOR]: JSON.stringify(queryVector),\n });\n }\n\n reportResults({\n results,\n }: {\n results: {\n ids?: string;\n scores?: number;\n distances?: number;\n metadata?: Record<string, unknown>;\n vectors?: number[];\n documents?: string;\n }[];\n }) {\n for (let i = 0; i < results.length; i++) {\n this.span.addEvent(Events.DB_QUERY_RESULT, {\n [EventAttributes.DB_QUERY_RESULT_ID]: results[i].ids,\n [EventAttributes.DB_QUERY_RESULT_SCORE]: results[i].scores,\n [EventAttributes.DB_QUERY_RESULT_DISTANCE]: results[i].distances,\n [EventAttributes.DB_QUERY_RESULT_METADATA]: JSON.stringify(\n results[i].metadata,\n ),\n [EventAttributes.DB_QUERY_RESULT_VECTOR]: results[i].vectors,\n [EventAttributes.DB_QUERY_RESULT_DOCUMENT]: results[i].documents,\n });\n }\n }\n}\n\nexport class LLMSpan {\n private span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n reportRequest({\n model,\n messages,\n }: {\n model: string;\n messages: {\n role: string;\n content?: string | unknown;\n }[];\n }) {\n this.span.setAttributes({\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n });\n\n messages.forEach((message, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_PROMPTS}.${index}.role`]: message.role,\n [`${SpanAttributes.LLM_PROMPTS}.${index}.content`]:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content),\n });\n });\n }\n\n reportResponse({\n model,\n usage,\n completions,\n }: {\n model: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n completions?: {\n finish_reason: string;\n message: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | null;\n };\n }[];\n }) {\n this.span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, model);\n\n if (usage) {\n this.span.setAttributes({\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: usage.prompt_tokens,\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: usage.completion_tokens,\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: usage.total_tokens,\n });\n }\n\n completions?.forEach((completion, index) => {\n this.span.setAttributes({\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.finish_reason`]:\n completion.finish_reason,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.role`]:\n completion.message.role,\n [`${SpanAttributes.LLM_COMPLETIONS}.${index}.content`]:\n completion.message.content || \"\",\n });\n });\n }\n}\n\nexport function withVectorDBCall<\n F extends ({ span }: { span: VectorSpan }) => ReturnType<F>,\n>({ vendor, type }: VectorDBCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const entityContext = context.active();\n\n return getTracer().startActiveSpan(\n `${vendor}.${type}`,\n { [SpanAttributes.LLM_REQUEST_TYPE]: type },\n entityContext,\n (span: Span) => {\n const res = fn.apply(thisArg, [{ span: new VectorSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n },\n );\n}\n\nexport function withLLMCall<\n F extends ({ span }: { span: LLMSpan }) => ReturnType<F>,\n>({ vendor, type }: LLMCallConfig, fn: F, thisArg?: ThisParameterType<F>) {\n const span = getTracer().startSpan(`${vendor}.${type}`, {}, context.active());\n span.setAttribute(SpanAttributes.LLM_REQUEST_TYPE, type);\n trace.setSpan(context.active(), span);\n\n const res = fn.apply(thisArg, [{ span: new LLMSpan(span) }]);\n if (res instanceof Promise) {\n return res.then((resolvedRes) => {\n span.end();\n return resolvedRes;\n });\n }\n\n span.end();\n return res;\n}\n","import { context } from \"@opentelemetry/api\";\nimport { ASSOCIATION_PROPERTIES_KEY } from \"./tracing\";\n\nexport function withAssociationProperties<\n A extends unknown[],\n F extends (...args: A) => ReturnType<F>,\n>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n) {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context\n .active()\n .setValue(ASSOCIATION_PROPERTIES_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n","import { v4 as uuidv4 } from 'uuid';\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const newUUID = (): StringUUID => {\n // crypto.randomUUID is available in most of the modern browsers and node,\n // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n // so we fallback to uuidv4 in those cases, which is less secure, but works\n // just fine.\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n } else {\n return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n }\n}\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 16) {\n console.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n }\n\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.padStart(32, '0').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n\nexport const otelTraceIdToUUID = (traceId: string): string => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 32) {\n console.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n }\n if (!/^[0-9a-f]+$/.test(id)) {\n console.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n return newUUID();\n }\n\n return id.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n}\n","import { Laminar } from \"./laminar\";\nimport { CreateEvaluationResponse, EvaluationDatapoint } from \"./types\";\n\nconst DEFAULT_BATCH_SIZE = 5;\n\n/**\n * Configuration for the Evaluator\n */\ninterface EvaluatorConfig {\n batchSize?: number;\n projectApiKey?: string;\n baseUrl?: string;\n}\n\nexport abstract class Dataset<D, T> {\n public slice(start: number, end: number): Datapoint<D, T>[] {\n const result = [];\n for (let i = Math.max(start, 0); i < Math.min(end, this.size()); i++) {\n result.push(this.get(i));\n }\n return result;\n }\n public abstract size(): number;\n public abstract get(index: number): Datapoint<D, T>;\n}\n\n/**\n * Datapoint is a single data point in the evaluation. `D` is the type of the input data, `T` is the type of the target data.\n */\nexport type Datapoint<D, T> = {\n /**\n * input to the executor function. Must be a record with string keys and any values.\n */\n data: Record<string, any> & D;\n /**\n * input to the evaluator function (alongside the executor output).\n * Must be a record with string keys and any values.\n */\n target: Record<string, any> & T;\n}\n\ntype EvaluatorFunctionReturn = number | Record<string, number>;\n\n/**\n * EvaluatorFunction is a function that takes the output of the executor and the target data, and returns a score.\n * The score can be a single number or a record of string keys and number values. The latter is useful for evaluating\n * multiple criteria in one go instead of running multiple evaluators.\n */\ntype EvaluatorFunction<O, T> = (output: O, target: T, ...args: any[]) => EvaluatorFunctionReturn | Promise<EvaluatorFunctionReturn>;\n\ninterface EvaluatorConstructorProps<D, T, O> {\n /**\n * List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n */\n data: (Datapoint<D, T>[]) | Dataset<D, T>;\n /**\n * The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n */\n executor: (data: D, ...args: any[]) => O | Promise<O>;\n /**\n * List of evaluator functions. Each evaluator function takes the output of the executor _and_ the target data, and returns\n * a score. The score can be a single number or a record of string keys and number values.\n * If the score is a single number, it will be named after the evaluator function. If the function is anonymous, it will be named\n * `evaluator_${index}`, where index is the index of the evaluator function in the list starting from 1.\n */\n evaluators: EvaluatorFunction<O, T>[];\n /**\n * Optional override configurations for the evaluator.\n */\n config?: EvaluatorConfig;\n}\n\nexport class Evaluation<D, T, O> {\n private name: string;\n private data: Datapoint<D, T>[] | Dataset<D, T>;\n private executor: (data: D, ...args: any[]) => O | Promise<O>;\n private evaluators: Record<string, EvaluatorFunction<O, T>>;\n private evaluatorNames: string[];\n private batchSize: number = DEFAULT_BATCH_SIZE;\n\n /**\n * Create a new evaluation and prepare data.\n * @param name Name of the evaluation.\n * @param props.data List of data points to evaluate. `data` is the input to the executor function, `target` is the input to the evaluator function.\n * @param props.executor The executor function. Takes the data point + any additional arguments and returns the output to evaluate.\n * @param props.evaluators List of evaluator functions. Each evaluator function takes the output of the executor and the target data, and returns.\n */\n constructor(name: string, {\n data, executor, evaluators, config\n }: EvaluatorConstructorProps<D, T, O>) {\n this.name = name;\n this.data = data;\n this.executor = executor;\n this.evaluators = Object.fromEntries(evaluators.map((e, i) => [e.name.length > 0 ? e.name : `evaluator_${i + 1}`, e]));\n this.evaluatorNames = evaluators.map((e, i) => e.name.length > 0 ? e.name : `evaluator_${i + 1}`);\n if (config) {\n this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;\n }\n Laminar.initialize({ projectApiKey: config?.projectApiKey, baseUrl: config?.baseUrl });\n }\n\n /** \n * Runs the evaluation.\n *\n * Creates a new evaluation if no evaluation with such name exists, or adds data to an existing one otherwise.\n * Evaluates data points in batches of `batchSize`. The executor function is called on each data point\n * to get the output, and then evaluate it by each evaluator function.\n */\n public async run(): Promise<void> {\n const response = await Laminar.createEvaluation(this.name) as CreateEvaluationResponse;\n const length = this.data instanceof Dataset ? this.data.size() : this.data.length;\n for (let i = 0; i < length; i += this.batchSize) {\n const batch = this.data.slice(i, i + this.batchSize);\n try {\n await this.evaluateBatch(batch);\n } catch (e) {\n console.error(`Error evaluating batch: ${e}`);\n }\n }\n try {\n // After all batches are completed, update the evaluation status\n await Laminar.updateEvaluationStatus(response.name, 'Finished');\n } catch (e) {\n console.error(`Error updating evaluation status: ${e}`);\n }\n }\n \n private async evaluateBatch(batch: Datapoint<D, T>[]): Promise<void> {\n const batchPromises = batch.map(async (datapoint) => {\n const output = await this.executor(datapoint.data);\n const target = datapoint.target;\n \n let scores: Record<string, EvaluatorFunctionReturn> = {};\n for (const evaluatorName of this.evaluatorNames) {\n const evaluator = this.evaluators[evaluatorName];\n const value = await evaluator(output, target);\n \n // If the evaluator returns a single number, use the evaluator name as the key\n if (typeof value === 'number') {\n scores[evaluatorName] = value;\n } else {\n // If the evaluator returns an object, merge its keys with the existing scores (flatten)\n scores = { ...scores, ...value };\n }\n }\n \n return {\n executorOutput: output,\n data: datapoint.data,\n target,\n scores,\n } as EvaluationDatapoint<D, T, O>;\n });\n \n const results = await Promise.all(batchPromises);\n \n return Laminar.postEvaluationResults(this.name, results);\n }\n \n}\n","import { withEntity } from './sdk/node-server-sdk'\n\ninterface ObserveOptions {\n name?: string;\n sessionId?: string;\n userId?: string;\n}\n\n/**\n * The main decorator entrypoint for Laminar. This is used to wrap\n * functions and methods to create spans.\n *\n * @param name - Name of the span. Function name is used if not specified.\n * @param user_id - User ID to associate with the span and the following context.\n * @param session_id - Session ID to associate with the span and the following context.\n * @returns Returns the result of the wrapped function.\n * @throws Exception - Re-throws the exception if the wrapped function throws an exception.\n * \n * @example\n * ```typescript\n * import { observe } from '@lmnr-ai/lmnr';\n * \n * await observe({ name: 'my_function' }, () => {\n * // Your code here\n * });\n */\nexport async function observe<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n {\n name,\n sessionId,\n userId,\n }: ObserveOptions, fn: F, ...args: A): Promise<ReturnType<F>> {\n\n let associationProperties = {};\n if (sessionId) {\n associationProperties = { ...associationProperties, \"session_id\": sessionId };\n }\n if (userId) {\n associationProperties = { ...associationProperties, \"user_id\": userId };\n }\n\n return await withEntity<A, F>({ name: name ?? fn.name, associationProperties }, fn, undefined, ...args);\n}\n"],"mappings":";;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,QAAU;AAAA,MACV,SAAW;AAAA,MACX,MAAQ;AAAA,QACN,KAAO;AAAA,MACT;AAAA,MACA,UAAY;AAAA,MACZ,iBAAmB;AAAA,QACjB,qBAAqB;AAAA,QACrB,mCAAmC;AAAA,QACnC,iBAAiB;AAAA,QACjB,4BAA4B;AAAA,QAC5B,0BAA0B;AAAA,QAC1B,mBAAmB;AAAA,QACnB,+BAA+B;AAAA,QAC/B,0BAA0B;AAAA,QAC1B,eAAe;AAAA,QACf,eAAe;AAAA,QACf,YAAc;AAAA,QACd,UAAY;AAAA,QACZ,aAAa;AAAA,QACb,WAAa;AAAA,QACb,YAAc;AAAA,QACd,QAAU;AAAA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,4BAAwB,EAAE,GAAG,uBAAuB,cAAc,UAAU;AAAA,EAChF;AACA,MAAI,QAAQ;AACR,4BAAwB,EAAE,GAAG,uBAAuB,WAAW,OAAO;AAAA,EAC1E;AAEA,SAAO,MAAM,WAAiB,EAAE,MAAM,sBAAQ,GAAG,MAAM,sBAAsB,GAAG,IAAI,QAAW,GAAG,IAAI;AAC1G;","names":["context","trace","diag","diag","context","SpanAttributes","context","SpanAttributes","context","trace","SpanAttributes","context","OTLPTraceExporter","OTLPTraceExporter","trace","context"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmnr-ai/lmnr",
3
- "version": "0.4.9-alpha",
3
+ "version": "0.4.10-alpha",
4
4
  "description": "TypeScript SDK for Laminar AI",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -49,7 +49,6 @@
49
49
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.53.0",
50
50
  "@opentelemetry/exporter-trace-otlp-proto": "^0.53.0",
51
51
  "@opentelemetry/instrumentation": "^0.53.0",
52
- "@opentelemetry/resources": "^1.26.0",
53
52
  "@opentelemetry/sdk-node": "^0.53.0",
54
53
  "@opentelemetry/sdk-trace-base": "^1.26.0",
55
54
  "@opentelemetry/sdk-trace-node": "^1.26.0",
@@ -3,24 +3,12 @@ import { NodeSDK } from "@opentelemetry/sdk-node";
3
3
  import {
4
4
  SimpleSpanProcessor,
5
5
  BatchSpanProcessor,
6
- SpanProcessor,
7
6
  } from "@opentelemetry/sdk-trace-node";
8
7
  import { baggageUtils } from "@opentelemetry/core";
9
8
  import { Span, context, diag } from "@opentelemetry/api";
10
9
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
11
- import { Resource } from "@opentelemetry/resources";
12
- import { SEMRESATTRS_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
13
10
  import { Instrumentation } from "@opentelemetry/instrumentation";
14
11
  import { InitializeOptions } from "../interfaces";
15
- import {
16
- Detector,
17
- DetectorSync,
18
- IResource,
19
- ResourceDetectionConfig,
20
- envDetectorSync,
21
- hostDetectorSync,
22
- processDetectorSync,
23
- } from "@opentelemetry/resources"
24
12
  import {
25
13
  ASSOCIATION_PROPERTIES_KEY,
26
14
  } from "./tracing";
@@ -29,6 +17,8 @@ import { _configuration } from "../configuration";
29
17
  import {
30
18
  SpanAttributes,
31
19
  } from "@traceloop/ai-semantic-conventions";
20
+ import {NodeTracerProvider} from "@opentelemetry/sdk-trace-node";
21
+ import {registerInstrumentations} from "@opentelemetry/instrumentation";
32
22
  import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
33
23
  import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
34
24
  import { AzureOpenAIInstrumentation } from "@traceloop/instrumentation-azure";
@@ -44,7 +34,6 @@ import { LangChainInstrumentation } from "@traceloop/instrumentation-langchain";
44
34
  import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
45
35
  import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
46
36
 
47
- let _sdk: NodeSDK;
48
37
  let _spanProcessor: SimpleSpanProcessor | BatchSpanProcessor;
49
38
  let openAIInstrumentation: OpenAIInstrumentation | undefined;
50
39
  let anthropicInstrumentation: AnthropicInstrumentation | undefined;
@@ -215,17 +204,6 @@ const manuallyInitInstrumentations = (
215
204
  }
216
205
  };
217
206
 
218
- function awaitAttributes(detector: DetectorSync): Detector {
219
- return {
220
- async detect(config?: ResourceDetectionConfig): Promise<IResource> {
221
- const resource = detector.detect(config)
222
- await resource.waitForAsyncAttributes?.()
223
-
224
- return resource
225
- },
226
- }
227
- }
228
-
229
207
  /**
230
208
  * Initializes the Traceloop SDK.
231
209
  * Must be called once before any other SDK methods.
@@ -309,31 +287,13 @@ export const startTracing = (options: InitializeOptions) => {
309
287
  });
310
288
  }
311
289
 
312
- const spanProcessors: SpanProcessor[] = [_spanProcessor];
313
- if (options.processor) {
314
- spanProcessors.push(options.processor);
315
- }
316
-
317
- _sdk = new NodeSDK({
318
- resource: new Resource({
319
- [SEMRESATTRS_SERVICE_NAME]:
320
- options.appName || process.env.npm_package_name,
321
- }),
322
- spanProcessors,
323
- contextManager: options.contextManager,
324
- textMapPropagator: options.propagator,
325
- traceExporter,
290
+ const provider = new NodeTracerProvider();
291
+ provider.addSpanProcessor(_spanProcessor);
292
+ provider.register();
293
+ registerInstrumentations({
326
294
  instrumentations,
327
- // We should re-consider removing irrelevant spans here in the future
328
- // sampler: new TraceloopSampler(),
329
- resourceDetectors: [
330
- awaitAttributes(envDetectorSync),
331
- awaitAttributes(processDetectorSync),
332
- awaitAttributes(hostDetectorSync),
333
- ],
295
+ tracerProvider: provider,
334
296
  });
335
-
336
- _sdk.start();
337
297
  };
338
298
 
339
299
  export const shouldSendTraces = () => {