@elasticdash/tracing 0.0.1 → 0.0.3

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.cjs ADDED
@@ -0,0 +1,800 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ LangfuseAgent: () => LangfuseAgent,
24
+ LangfuseChain: () => LangfuseChain,
25
+ LangfuseEmbedding: () => LangfuseEmbedding,
26
+ LangfuseEvaluator: () => LangfuseEvaluator,
27
+ LangfuseEvent: () => LangfuseEvent,
28
+ LangfuseGeneration: () => LangfuseGeneration,
29
+ LangfuseGuardrail: () => LangfuseGuardrail,
30
+ LangfuseOtelSpanAttributes: () => import_core5.LangfuseOtelSpanAttributes,
31
+ LangfuseRetriever: () => LangfuseRetriever,
32
+ LangfuseSpan: () => LangfuseSpan,
33
+ LangfuseTool: () => LangfuseTool,
34
+ createObservationAttributes: () => createObservationAttributes,
35
+ createTraceAttributes: () => createTraceAttributes,
36
+ createTraceId: () => createTraceId,
37
+ getActiveSpanId: () => getActiveSpanId,
38
+ getActiveTraceId: () => getActiveTraceId,
39
+ getLangfuseTracer: () => getLangfuseTracer,
40
+ getLangfuseTracerProvider: () => getLangfuseTracerProvider,
41
+ observe: () => observe,
42
+ propagateAttributes: () => import_core4.propagateAttributes,
43
+ setLangfuseTracerProvider: () => setLangfuseTracerProvider,
44
+ startActiveObservation: () => startActiveObservation,
45
+ startObservation: () => startObservation,
46
+ updateActiveObservation: () => updateActiveObservation,
47
+ updateActiveTrace: () => updateActiveTrace
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+ var import_core3 = require("@elasticdash/core");
51
+ var import_api2 = require("@opentelemetry/api");
52
+
53
+ // src/attributes.ts
54
+ var import_core = require("@elasticdash/core");
55
+ function createTraceAttributes({
56
+ name,
57
+ userId,
58
+ sessionId,
59
+ version,
60
+ release,
61
+ input,
62
+ output,
63
+ metadata,
64
+ tags,
65
+ environment,
66
+ public: isPublic
67
+ } = {}) {
68
+ const attributes = {
69
+ [import_core.LangfuseOtelSpanAttributes.TRACE_NAME]: name,
70
+ [import_core.LangfuseOtelSpanAttributes.TRACE_USER_ID]: userId,
71
+ [import_core.LangfuseOtelSpanAttributes.TRACE_SESSION_ID]: sessionId,
72
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
73
+ [import_core.LangfuseOtelSpanAttributes.RELEASE]: release,
74
+ [import_core.LangfuseOtelSpanAttributes.TRACE_INPUT]: _serialize(input),
75
+ [import_core.LangfuseOtelSpanAttributes.TRACE_OUTPUT]: _serialize(output),
76
+ [import_core.LangfuseOtelSpanAttributes.TRACE_TAGS]: tags,
77
+ [import_core.LangfuseOtelSpanAttributes.ENVIRONMENT]: environment,
78
+ [import_core.LangfuseOtelSpanAttributes.TRACE_PUBLIC]: isPublic,
79
+ ..._flattenAndSerializeMetadata(metadata, "trace")
80
+ };
81
+ return Object.fromEntries(
82
+ Object.entries(attributes).filter(([_, v]) => v != null)
83
+ );
84
+ }
85
+ function createObservationAttributes(type, attributes) {
86
+ const {
87
+ metadata,
88
+ input,
89
+ output,
90
+ level,
91
+ statusMessage,
92
+ version,
93
+ completionStartTime,
94
+ model,
95
+ modelParameters,
96
+ usageDetails,
97
+ costDetails,
98
+ prompt
99
+ } = attributes;
100
+ let otelAttributes = {
101
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: type,
102
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
103
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
104
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
105
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
106
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
107
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_MODEL]: model,
108
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]: _serialize(usageDetails),
109
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS]: _serialize(costDetails),
110
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME]: _serialize(completionStartTime),
111
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]: _serialize(modelParameters),
112
+ ...prompt && !prompt.isFallback ? {
113
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]: prompt.name,
114
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]: prompt.version
115
+ } : {},
116
+ ..._flattenAndSerializeMetadata(metadata, "observation")
117
+ };
118
+ return Object.fromEntries(
119
+ Object.entries(otelAttributes).filter(([_, v]) => v != null)
120
+ );
121
+ }
122
+ function _serialize(obj) {
123
+ try {
124
+ if (typeof obj === "string") return obj;
125
+ return obj != null ? JSON.stringify(obj) : void 0;
126
+ } catch {
127
+ return "<failed to serialize>";
128
+ }
129
+ }
130
+ function _flattenAndSerializeMetadata(metadata, type) {
131
+ const prefix = type === "observation" ? import_core.LangfuseOtelSpanAttributes.OBSERVATION_METADATA : import_core.LangfuseOtelSpanAttributes.TRACE_METADATA;
132
+ const metadataAttributes = {};
133
+ if (metadata === void 0 || metadata === null) {
134
+ return metadataAttributes;
135
+ }
136
+ if (typeof metadata !== "object" || Array.isArray(metadata)) {
137
+ const serialized = _serialize(metadata);
138
+ if (serialized) {
139
+ metadataAttributes[prefix] = serialized;
140
+ }
141
+ } else {
142
+ for (const [key, value] of Object.entries(metadata)) {
143
+ const serialized = typeof value === "string" ? value : _serialize(value);
144
+ if (serialized) {
145
+ metadataAttributes[`${prefix}.${key}`] = serialized;
146
+ }
147
+ }
148
+ }
149
+ return metadataAttributes;
150
+ }
151
+
152
+ // src/tracerProvider.ts
153
+ var import_core2 = require("@elasticdash/core");
154
+ var import_api = require("@opentelemetry/api");
155
+ var LANGFUSE_GLOBAL_SYMBOL = Symbol.for("langfuse");
156
+ function createState() {
157
+ return {
158
+ isolatedTracerProvider: null
159
+ };
160
+ }
161
+ function getGlobalState() {
162
+ const initialState = createState();
163
+ try {
164
+ const g = globalThis;
165
+ if (typeof g !== "object" || g === null) {
166
+ (0, import_core2.getGlobalLogger)().warn(
167
+ "globalThis is not available, using fallback state"
168
+ );
169
+ return initialState;
170
+ }
171
+ if (!g[LANGFUSE_GLOBAL_SYMBOL]) {
172
+ Object.defineProperty(g, LANGFUSE_GLOBAL_SYMBOL, {
173
+ value: initialState,
174
+ writable: false,
175
+ // lock the slot (not the contents)
176
+ configurable: false,
177
+ enumerable: false
178
+ });
179
+ }
180
+ return g[LANGFUSE_GLOBAL_SYMBOL];
181
+ } catch (err) {
182
+ if (err instanceof Error) {
183
+ (0, import_core2.getGlobalLogger)().error(`Failed to access global state: ${err.message}`);
184
+ } else {
185
+ (0, import_core2.getGlobalLogger)().error(`Failed to access global state: ${String(err)}`);
186
+ }
187
+ return initialState;
188
+ }
189
+ }
190
+ function setLangfuseTracerProvider(provider) {
191
+ getGlobalState().isolatedTracerProvider = provider;
192
+ }
193
+ function getLangfuseTracerProvider() {
194
+ const { isolatedTracerProvider } = getGlobalState();
195
+ if (isolatedTracerProvider) return isolatedTracerProvider;
196
+ return import_api.trace.getTracerProvider();
197
+ }
198
+ function getLangfuseTracer() {
199
+ return getLangfuseTracerProvider().getTracer(
200
+ import_core2.LANGFUSE_TRACER_NAME,
201
+ import_core2.LANGFUSE_SDK_VERSION
202
+ );
203
+ }
204
+
205
+ // src/spanWrapper.ts
206
+ var LangfuseBaseObservation = class {
207
+ constructor(params) {
208
+ this.otelSpan = params.otelSpan;
209
+ this.id = params.otelSpan.spanContext().spanId;
210
+ this.traceId = params.otelSpan.spanContext().traceId;
211
+ this.type = params.type;
212
+ if (params.attributes) {
213
+ this.otelSpan.setAttributes(
214
+ createObservationAttributes(params.type, params.attributes)
215
+ );
216
+ }
217
+ }
218
+ /** Gets the Langfuse OpenTelemetry tracer instance */
219
+ get tracer() {
220
+ return getLangfuseTracer();
221
+ }
222
+ /**
223
+ * Ends the observation, marking it as complete.
224
+ *
225
+ * @param endTime - Optional end time, defaults to current time
226
+ */
227
+ end(endTime) {
228
+ this.otelSpan.end(endTime);
229
+ }
230
+ updateOtelSpanAttributes(attributes) {
231
+ this.otelSpan.setAttributes(
232
+ createObservationAttributes(this.type, attributes)
233
+ );
234
+ }
235
+ /**
236
+ * Updates the parent trace with new attributes.
237
+ */
238
+ updateTrace(attributes) {
239
+ this.otelSpan.setAttributes(createTraceAttributes(attributes));
240
+ return this;
241
+ }
242
+ startObservation(name, attributes, options) {
243
+ const { asType = "span" } = options || {};
244
+ return startObservation(name, attributes, {
245
+ asType,
246
+ // typecast necessary as ts cannot narrow the type correctly
247
+ parentSpanContext: this.otelSpan.spanContext()
248
+ });
249
+ }
250
+ };
251
+ var LangfuseSpan = class extends LangfuseBaseObservation {
252
+ constructor(params) {
253
+ super({ ...params, type: "span" });
254
+ }
255
+ /**
256
+ * Updates this span with new attributes.
257
+ *
258
+ * @param attributes - Span attributes to set
259
+ * @returns This span for method chaining
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * span.update({
264
+ * output: { result: 'success' },
265
+ * level: 'DEFAULT',
266
+ * metadata: { duration: 150 }
267
+ * });
268
+ * ```
269
+ */
270
+ update(attributes) {
271
+ super.updateOtelSpanAttributes(attributes);
272
+ return this;
273
+ }
274
+ };
275
+ var LangfuseAgent = class extends LangfuseBaseObservation {
276
+ constructor(params) {
277
+ super({ ...params, type: "agent" });
278
+ }
279
+ /**
280
+ * Updates this agent observation with new attributes.
281
+ *
282
+ * @param attributes - Agent attributes to set
283
+ * @returns This agent for method chaining
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * agent.update({
288
+ * output: {
289
+ * taskCompleted: true,
290
+ * iterationsUsed: 5,
291
+ * toolsInvoked: ['web-search', 'calculator', 'summarizer'],
292
+ * finalResult: 'Research completed with high confidence'
293
+ * },
294
+ * metadata: {
295
+ * efficiency: 0.85,
296
+ * qualityScore: 0.92,
297
+ * resourcesConsumed: { tokens: 15000, apiCalls: 12 }
298
+ * }
299
+ * });
300
+ * ```
301
+ */
302
+ update(attributes) {
303
+ super.updateOtelSpanAttributes(attributes);
304
+ return this;
305
+ }
306
+ };
307
+ var LangfuseTool = class extends LangfuseBaseObservation {
308
+ constructor(params) {
309
+ super({ ...params, type: "tool" });
310
+ }
311
+ /**
312
+ * Updates this tool observation with new attributes.
313
+ *
314
+ * @param attributes - Tool attributes to set
315
+ * @returns This tool for method chaining
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * tool.update({
320
+ * output: {
321
+ * result: searchResults,
322
+ * count: searchResults.length,
323
+ * relevanceScore: 0.89,
324
+ * executionTime: 1250
325
+ * },
326
+ * metadata: {
327
+ * cacheHit: false,
328
+ * apiCost: 0.025,
329
+ * rateLimitRemaining: 950
330
+ * }
331
+ * });
332
+ * ```
333
+ */
334
+ update(attributes) {
335
+ super.updateOtelSpanAttributes(attributes);
336
+ return this;
337
+ }
338
+ };
339
+ var LangfuseChain = class extends LangfuseBaseObservation {
340
+ constructor(params) {
341
+ super({ ...params, type: "chain" });
342
+ }
343
+ /**
344
+ * Updates this chain observation with new attributes.
345
+ *
346
+ * @param attributes - Chain attributes to set
347
+ * @returns This chain for method chaining
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * chain.update({
352
+ * output: {
353
+ * stepsCompleted: 5,
354
+ * stepsSuccessful: 4,
355
+ * finalResult: processedData,
356
+ * pipelineEfficiency: 0.87
357
+ * },
358
+ * metadata: {
359
+ * bottleneckStep: 'data-validation',
360
+ * parallelizationOpportunities: ['step-2', 'step-3'],
361
+ * optimizationSuggestions: ['cache-intermediate-results']
362
+ * }
363
+ * });
364
+ * ```
365
+ */
366
+ update(attributes) {
367
+ super.updateOtelSpanAttributes(attributes);
368
+ return this;
369
+ }
370
+ };
371
+ var LangfuseRetriever = class extends LangfuseBaseObservation {
372
+ constructor(params) {
373
+ super({ ...params, type: "retriever" });
374
+ }
375
+ /**
376
+ * Updates this retriever observation with new attributes.
377
+ *
378
+ * @param attributes - Retriever attributes to set
379
+ * @returns This retriever for method chaining
380
+ */
381
+ update(attributes) {
382
+ super.updateOtelSpanAttributes(attributes);
383
+ return this;
384
+ }
385
+ };
386
+ var LangfuseEvaluator = class extends LangfuseBaseObservation {
387
+ constructor(params) {
388
+ super({ ...params, type: "evaluator" });
389
+ }
390
+ /**
391
+ * Updates this evaluator observation with new attributes.
392
+ *
393
+ * @param attributes - Evaluator attributes to set
394
+ * @returns This evaluator for method chaining
395
+ */
396
+ update(attributes) {
397
+ super.updateOtelSpanAttributes(attributes);
398
+ return this;
399
+ }
400
+ };
401
+ var LangfuseGuardrail = class extends LangfuseBaseObservation {
402
+ constructor(params) {
403
+ super({ ...params, type: "guardrail" });
404
+ }
405
+ /**
406
+ * Updates this guardrail observation with new attributes.
407
+ *
408
+ * @param attributes - Guardrail attributes to set
409
+ * @returns This guardrail for method chaining
410
+ */
411
+ update(attributes) {
412
+ super.updateOtelSpanAttributes(attributes);
413
+ return this;
414
+ }
415
+ };
416
+ var LangfuseGeneration = class extends LangfuseBaseObservation {
417
+ constructor(params) {
418
+ super({ ...params, type: "generation" });
419
+ }
420
+ update(attributes) {
421
+ this.updateOtelSpanAttributes(attributes);
422
+ return this;
423
+ }
424
+ };
425
+ var LangfuseEmbedding = class extends LangfuseBaseObservation {
426
+ constructor(params) {
427
+ super({ ...params, type: "embedding" });
428
+ }
429
+ /**
430
+ * Updates this embedding observation with new attributes.
431
+ *
432
+ * @param attributes - Embedding attributes to set
433
+ * @returns This embedding for method chaining
434
+ */
435
+ update(attributes) {
436
+ this.updateOtelSpanAttributes(attributes);
437
+ return this;
438
+ }
439
+ };
440
+ var LangfuseEvent = class extends LangfuseBaseObservation {
441
+ constructor(params) {
442
+ super({ ...params, type: "event" });
443
+ this.otelSpan.end(params.timestamp);
444
+ }
445
+ };
446
+
447
+ // src/index.ts
448
+ var import_core4 = require("@elasticdash/core");
449
+ var import_core5 = require("@elasticdash/core");
450
+ function createOtelSpan(params) {
451
+ return getLangfuseTracer().startSpan(
452
+ params.name,
453
+ { startTime: params.startTime },
454
+ createParentContext(params.parentSpanContext)
455
+ );
456
+ }
457
+ function createParentContext(parentSpanContext) {
458
+ if (!parentSpanContext) return;
459
+ return import_api2.trace.setSpanContext(import_api2.context.active(), parentSpanContext);
460
+ }
461
+ function wrapPromise(promise, span, endOnExit) {
462
+ return promise.then(
463
+ (value) => {
464
+ if (endOnExit !== false) {
465
+ span.end();
466
+ }
467
+ return value;
468
+ },
469
+ (err) => {
470
+ span.setStatus({
471
+ code: import_api2.SpanStatusCode.ERROR,
472
+ message: err instanceof Error ? err.message : "Unknown error"
473
+ });
474
+ if (endOnExit !== false) {
475
+ span.end();
476
+ }
477
+ throw err;
478
+ }
479
+ );
480
+ }
481
+ function startObservation(name, attributes, options) {
482
+ var _a;
483
+ const { asType = "span", ...observationOptions } = options || {};
484
+ const otelSpan = createOtelSpan({
485
+ name,
486
+ ...observationOptions
487
+ });
488
+ switch (asType) {
489
+ case "generation":
490
+ return new LangfuseGeneration({
491
+ otelSpan,
492
+ attributes
493
+ });
494
+ case "embedding":
495
+ return new LangfuseEmbedding({
496
+ otelSpan,
497
+ attributes
498
+ });
499
+ case "agent":
500
+ return new LangfuseAgent({
501
+ otelSpan,
502
+ attributes
503
+ });
504
+ case "tool":
505
+ return new LangfuseTool({
506
+ otelSpan,
507
+ attributes
508
+ });
509
+ case "chain":
510
+ return new LangfuseChain({
511
+ otelSpan,
512
+ attributes
513
+ });
514
+ case "retriever":
515
+ return new LangfuseRetriever({
516
+ otelSpan,
517
+ attributes
518
+ });
519
+ case "evaluator":
520
+ return new LangfuseEvaluator({
521
+ otelSpan,
522
+ attributes
523
+ });
524
+ case "guardrail":
525
+ return new LangfuseGuardrail({
526
+ otelSpan,
527
+ attributes
528
+ });
529
+ case "event": {
530
+ const timestamp = (_a = observationOptions == null ? void 0 : observationOptions.startTime) != null ? _a : /* @__PURE__ */ new Date();
531
+ return new LangfuseEvent({
532
+ otelSpan,
533
+ attributes,
534
+ timestamp
535
+ });
536
+ }
537
+ case "span":
538
+ default:
539
+ return new LangfuseSpan({
540
+ otelSpan,
541
+ attributes
542
+ });
543
+ }
544
+ }
545
+ function startActiveObservation(name, fn, options) {
546
+ var _a;
547
+ const { asType = "span", ...observationOptions } = options || {};
548
+ return getLangfuseTracer().startActiveSpan(
549
+ name,
550
+ { startTime: observationOptions == null ? void 0 : observationOptions.startTime },
551
+ (_a = createParentContext(observationOptions == null ? void 0 : observationOptions.parentSpanContext)) != null ? _a : import_api2.context.active(),
552
+ (span) => {
553
+ var _a2;
554
+ try {
555
+ let observation;
556
+ switch (asType) {
557
+ case "generation":
558
+ observation = new LangfuseGeneration({
559
+ otelSpan: span
560
+ });
561
+ break;
562
+ case "embedding":
563
+ observation = new LangfuseEmbedding({
564
+ otelSpan: span
565
+ });
566
+ break;
567
+ case "agent":
568
+ observation = new LangfuseAgent({
569
+ otelSpan: span
570
+ });
571
+ break;
572
+ case "tool":
573
+ observation = new LangfuseTool({
574
+ otelSpan: span
575
+ });
576
+ break;
577
+ case "chain":
578
+ observation = new LangfuseChain({
579
+ otelSpan: span
580
+ });
581
+ break;
582
+ case "retriever":
583
+ observation = new LangfuseRetriever({
584
+ otelSpan: span
585
+ });
586
+ break;
587
+ case "evaluator":
588
+ observation = new LangfuseEvaluator({
589
+ otelSpan: span
590
+ });
591
+ break;
592
+ case "guardrail":
593
+ observation = new LangfuseGuardrail({
594
+ otelSpan: span
595
+ });
596
+ break;
597
+ case "event": {
598
+ const timestamp = (_a2 = observationOptions == null ? void 0 : observationOptions.startTime) != null ? _a2 : /* @__PURE__ */ new Date();
599
+ observation = new LangfuseEvent({
600
+ otelSpan: span,
601
+ timestamp
602
+ });
603
+ break;
604
+ }
605
+ case "span":
606
+ default:
607
+ observation = new LangfuseSpan({
608
+ otelSpan: span
609
+ });
610
+ }
611
+ const result = fn(observation);
612
+ if (result instanceof Promise) {
613
+ return wrapPromise(
614
+ result,
615
+ span,
616
+ observationOptions == null ? void 0 : observationOptions.endOnExit
617
+ );
618
+ } else {
619
+ if ((observationOptions == null ? void 0 : observationOptions.endOnExit) !== false) {
620
+ span.end();
621
+ }
622
+ return result;
623
+ }
624
+ } catch (err) {
625
+ span.setStatus({
626
+ code: import_api2.SpanStatusCode.ERROR,
627
+ message: err instanceof Error ? err.message : "Unknown error"
628
+ });
629
+ if ((observationOptions == null ? void 0 : observationOptions.endOnExit) !== false) {
630
+ span.end();
631
+ }
632
+ throw err;
633
+ }
634
+ }
635
+ );
636
+ }
637
+ function updateActiveTrace(attributes) {
638
+ const span = import_api2.trace.getActiveSpan();
639
+ if (!span) {
640
+ (0, import_core3.getGlobalLogger)().warn(
641
+ "No active OTEL span in context. Skipping trace update."
642
+ );
643
+ return;
644
+ }
645
+ span.setAttributes(createTraceAttributes(attributes));
646
+ }
647
+ function updateActiveObservation(attributes, options) {
648
+ var _a;
649
+ const span = import_api2.trace.getActiveSpan();
650
+ if (!span) {
651
+ (0, import_core3.getGlobalLogger)().warn(
652
+ "No active OTEL span in context. Skipping span update."
653
+ );
654
+ return;
655
+ }
656
+ const otelAttributes = createObservationAttributes(
657
+ (_a = options == null ? void 0 : options.asType) != null ? _a : "span",
658
+ attributes
659
+ );
660
+ if (!(options == null ? void 0 : options.asType)) {
661
+ otelAttributes[import_core3.LangfuseOtelSpanAttributes.OBSERVATION_TYPE] = void 0;
662
+ }
663
+ span.setAttributes(otelAttributes);
664
+ }
665
+ function observe(fn, options = {}) {
666
+ const {
667
+ name = fn.name || "anonymous-function",
668
+ asType = "span",
669
+ captureInput = true,
670
+ captureOutput = true,
671
+ parentSpanContext = void 0
672
+ } = options;
673
+ const wrappedFunction = function(...args) {
674
+ const inputData = captureInput ? _captureArguments(args) : void 0;
675
+ const observation = startObservation(
676
+ name,
677
+ inputData ? { input: inputData } : {},
678
+ {
679
+ asType,
680
+ // typecast necessary as ts cannot narrow down type
681
+ parentSpanContext
682
+ }
683
+ );
684
+ const activeContext = import_api2.trace.setSpan(import_api2.context.active(), observation.otelSpan);
685
+ try {
686
+ const result = import_api2.context.with(activeContext, () => fn.apply(this, args));
687
+ if (result instanceof Promise) {
688
+ return result.then(
689
+ (value) => {
690
+ if (captureOutput) {
691
+ observation.update({ output: _captureOutput(value) });
692
+ }
693
+ if ((options == null ? void 0 : options.endOnExit) !== false) {
694
+ observation.end();
695
+ }
696
+ return value;
697
+ },
698
+ (error) => {
699
+ observation.update({
700
+ level: "ERROR",
701
+ statusMessage: (error instanceof Error ? error.message : String(error)) || "Function threw an error",
702
+ output: captureOutput ? { error: String(error) } : void 0
703
+ });
704
+ if ((options == null ? void 0 : options.endOnExit) !== false) {
705
+ observation.end();
706
+ }
707
+ throw error;
708
+ }
709
+ );
710
+ } else {
711
+ if (captureOutput) {
712
+ observation.update({ output: _captureOutput(result) });
713
+ }
714
+ if ((options == null ? void 0 : options.endOnExit) !== false) {
715
+ observation.end();
716
+ }
717
+ return result;
718
+ }
719
+ } catch (error) {
720
+ observation.update({
721
+ level: "ERROR",
722
+ statusMessage: (error instanceof Error ? error.message : String(error)) || "Function threw an error",
723
+ output: captureOutput ? { error: String(error) } : void 0
724
+ });
725
+ if ((options == null ? void 0 : options.endOnExit) !== false) {
726
+ observation.end();
727
+ }
728
+ throw error;
729
+ }
730
+ };
731
+ return wrappedFunction;
732
+ }
733
+ function _captureArguments(args) {
734
+ try {
735
+ if (args.length === 0) return void 0;
736
+ if (args.length === 1) return args[0];
737
+ return args;
738
+ } catch {
739
+ return "<failed to capture arguments>";
740
+ }
741
+ }
742
+ function _captureOutput(value) {
743
+ try {
744
+ if (value === void 0 || value === null) return value;
745
+ if (typeof value !== "object") return value;
746
+ return value;
747
+ } catch {
748
+ return "<failed to capture output>";
749
+ }
750
+ }
751
+ async function createTraceId(seed) {
752
+ if (seed) {
753
+ const data = new TextEncoder().encode(seed);
754
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
755
+ const hashArray = new Uint8Array(hashBuffer);
756
+ return uint8ArrayToHex(hashArray).slice(0, 32);
757
+ }
758
+ const randomValues = crypto.getRandomValues(new Uint8Array(16));
759
+ return uint8ArrayToHex(randomValues);
760
+ }
761
+ function uint8ArrayToHex(array) {
762
+ return Array.from(array).map((b) => b.toString(16).padStart(2, "0")).join("");
763
+ }
764
+ function getActiveTraceId() {
765
+ var _a;
766
+ return (_a = import_api2.trace.getActiveSpan()) == null ? void 0 : _a.spanContext().traceId;
767
+ }
768
+ function getActiveSpanId() {
769
+ var _a;
770
+ return (_a = import_api2.trace.getActiveSpan()) == null ? void 0 : _a.spanContext().spanId;
771
+ }
772
+ // Annotate the CommonJS export names for ESM import in node:
773
+ 0 && (module.exports = {
774
+ LangfuseAgent,
775
+ LangfuseChain,
776
+ LangfuseEmbedding,
777
+ LangfuseEvaluator,
778
+ LangfuseEvent,
779
+ LangfuseGeneration,
780
+ LangfuseGuardrail,
781
+ LangfuseOtelSpanAttributes,
782
+ LangfuseRetriever,
783
+ LangfuseSpan,
784
+ LangfuseTool,
785
+ createObservationAttributes,
786
+ createTraceAttributes,
787
+ createTraceId,
788
+ getActiveSpanId,
789
+ getActiveTraceId,
790
+ getLangfuseTracer,
791
+ getLangfuseTracerProvider,
792
+ observe,
793
+ propagateAttributes,
794
+ setLangfuseTracerProvider,
795
+ startActiveObservation,
796
+ startObservation,
797
+ updateActiveObservation,
798
+ updateActiveTrace
799
+ });
800
+ //# sourceMappingURL=index.cjs.map