@langfuse/tracing 4.0.0-alpha.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2023 Finto Technologies GmbH
2
+
3
+ Copyright (c) 2022 PostHog (part of Hiberly Inc)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,7 @@
1
+ import { type Attributes } from "@opentelemetry/api";
2
+ import { LangfuseGenerationAttributes, LangfuseSpanAttributes, LangfuseTraceAttributes } from "./types.js";
3
+ export declare function createTraceAttributes({ name, userId, sessionId, version, release, input, output, metadata, tags, environment, public: isPublic, }?: LangfuseTraceAttributes): Attributes;
4
+ export declare function createSpanAttributes({ metadata, input, output, level, statusMessage, version, }: LangfuseSpanAttributes): Attributes;
5
+ export declare function createGenerationAttributes({ completionStartTime, metadata, level, statusMessage, version, model, modelParameters, input, output, usageDetails, costDetails, prompt, }: LangfuseGenerationAttributes): Attributes;
6
+ export declare function createEventAttributes({ metadata, input, output, level, statusMessage, version, }: LangfuseSpanAttributes): Attributes;
7
+ //# sourceMappingURL=attributes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attributes.d.ts","sourceRoot":"","sources":["../src/attributes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EACL,4BAA4B,EAC5B,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAEpB,wBAAgB,qBAAqB,CAAC,EACpC,IAAI,EACJ,MAAM,EACN,SAAS,EACT,OAAO,EACP,OAAO,EACP,KAAK,EACL,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,MAAM,EAAE,QAAQ,GACjB,GAAE,uBAA4B,GAAG,UAAU,CAkB3C;AAED,wBAAgB,oBAAoB,CAAC,EACnC,QAAQ,EACR,KAAK,EACL,MAAM,EACN,KAAK,EACL,aAAa,EACb,OAAO,GACR,EAAE,sBAAsB,GAAG,UAAU,CAcrC;AAED,wBAAgB,0BAA0B,CAAC,EACzC,mBAAmB,EACnB,QAAQ,EACR,KAAK,EACL,aAAa,EACb,OAAO,EACP,KAAK,EACL,eAAe,EACf,KAAK,EACL,MAAM,EACN,YAAY,EACZ,WAAW,EACX,MAAM,GACP,EAAE,4BAA4B,GAAG,UAAU,CA8B3C;AAED,wBAAgB,qBAAqB,CAAC,EACpC,QAAQ,EACR,KAAK,EACL,MAAM,EACN,KAAK,EACL,aAAa,EACb,OAAO,GACR,EAAE,sBAAsB,GAAG,UAAU,CAcrC"}
@@ -0,0 +1,96 @@
1
+ import { LangfuseOtelSpanAttributes } from "@langfuse/core";
2
+ export function createTraceAttributes({ name, userId, sessionId, version, release, input, output, metadata, tags, environment, public: isPublic, } = {}) {
3
+ const attributes = {
4
+ [LangfuseOtelSpanAttributes.TRACE_NAME]: name,
5
+ [LangfuseOtelSpanAttributes.TRACE_USER_ID]: userId,
6
+ [LangfuseOtelSpanAttributes.TRACE_SESSION_ID]: sessionId,
7
+ [LangfuseOtelSpanAttributes.VERSION]: version,
8
+ [LangfuseOtelSpanAttributes.RELEASE]: release,
9
+ [LangfuseOtelSpanAttributes.TRACE_INPUT]: _serialize(input),
10
+ [LangfuseOtelSpanAttributes.TRACE_OUTPUT]: _serialize(output),
11
+ [LangfuseOtelSpanAttributes.TRACE_TAGS]: tags,
12
+ [LangfuseOtelSpanAttributes.ENVIRONMENT]: environment,
13
+ [LangfuseOtelSpanAttributes.TRACE_PUBLIC]: isPublic,
14
+ ..._flattenAndSerializeMetadata(metadata, "trace"),
15
+ };
16
+ return Object.fromEntries(Object.entries(attributes).filter(([_, v]) => v != null));
17
+ }
18
+ export function createSpanAttributes({ metadata, input, output, level, statusMessage, version, }) {
19
+ const attributes = {
20
+ [LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "span",
21
+ [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
22
+ [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
23
+ [LangfuseOtelSpanAttributes.VERSION]: version,
24
+ [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
25
+ [LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
26
+ ..._flattenAndSerializeMetadata(metadata, "observation"),
27
+ };
28
+ return Object.fromEntries(Object.entries(attributes).filter(([_, v]) => v != null));
29
+ }
30
+ export function createGenerationAttributes({ completionStartTime, metadata, level, statusMessage, version, model, modelParameters, input, output, usageDetails, costDetails, prompt, }) {
31
+ const attributes = {
32
+ [LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "generation",
33
+ [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
34
+ [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
35
+ [LangfuseOtelSpanAttributes.VERSION]: version,
36
+ [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
37
+ [LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
38
+ [LangfuseOtelSpanAttributes.OBSERVATION_MODEL]: model,
39
+ [LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]: _serialize(usageDetails),
40
+ [LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS]: _serialize(costDetails),
41
+ [LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME]: _serialize(completionStartTime),
42
+ [LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]: _serialize(modelParameters),
43
+ ...(prompt && !prompt.isFallback
44
+ ? {
45
+ [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]: prompt.name,
46
+ [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]: prompt.version,
47
+ }
48
+ : {}),
49
+ ..._flattenAndSerializeMetadata(metadata, "observation"),
50
+ };
51
+ return Object.fromEntries(Object.entries(attributes).filter(([_, v]) => v != null));
52
+ }
53
+ export function createEventAttributes({ metadata, input, output, level, statusMessage, version, }) {
54
+ const attributes = {
55
+ [LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "event",
56
+ [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
57
+ [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
58
+ [LangfuseOtelSpanAttributes.VERSION]: version,
59
+ [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
60
+ [LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
61
+ ..._flattenAndSerializeMetadata(metadata, "observation"),
62
+ };
63
+ return Object.fromEntries(Object.entries(attributes).filter(([_, v]) => v != null));
64
+ }
65
+ function _serialize(obj) {
66
+ try {
67
+ return obj != null ? JSON.stringify(obj) : undefined;
68
+ }
69
+ catch {
70
+ return "<failed to serialize>";
71
+ }
72
+ }
73
+ function _flattenAndSerializeMetadata(metadata, type) {
74
+ const prefix = type === "observation"
75
+ ? LangfuseOtelSpanAttributes.OBSERVATION_METADATA
76
+ : LangfuseOtelSpanAttributes.TRACE_METADATA;
77
+ const metadataAttributes = {};
78
+ if (metadata === undefined || metadata === null) {
79
+ return metadataAttributes;
80
+ }
81
+ if (typeof metadata !== "object" || Array.isArray(metadata)) {
82
+ const serialized = _serialize(metadata);
83
+ if (serialized) {
84
+ metadataAttributes[prefix] = serialized;
85
+ }
86
+ }
87
+ else {
88
+ for (const [key, value] of Object.entries(metadata)) {
89
+ const serialized = typeof value === "string" ? value : _serialize(value);
90
+ if (serialized) {
91
+ metadataAttributes[`${prefix}.${key}`] = serialized;
92
+ }
93
+ }
94
+ }
95
+ return metadataAttributes;
96
+ }
package/dist/index.cjs ADDED
@@ -0,0 +1,497 @@
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
+ LangfuseEvent: () => LangfuseEvent,
24
+ LangfuseGeneration: () => LangfuseGeneration,
25
+ LangfuseOtelSpanAttributes: () => import_core4.LangfuseOtelSpanAttributes,
26
+ LangfuseSpan: () => LangfuseSpan,
27
+ createEvent: () => createEvent,
28
+ createGenerationAttributes: () => createGenerationAttributes,
29
+ createSpanAttributes: () => createSpanAttributes,
30
+ createTraceAttributes: () => createTraceAttributes,
31
+ createTraceId: () => createTraceId,
32
+ observe: () => observe,
33
+ startActiveGeneration: () => startActiveGeneration,
34
+ startActiveSpan: () => startActiveSpan,
35
+ startGeneration: () => startGeneration,
36
+ startSpan: () => startSpan,
37
+ updateActiveGeneration: () => updateActiveGeneration,
38
+ updateActiveSpan: () => updateActiveSpan,
39
+ updateActiveTrace: () => updateActiveTrace
40
+ });
41
+ module.exports = __toCommonJS(index_exports);
42
+ var import_core3 = require("@langfuse/core");
43
+ var import_api2 = require("@opentelemetry/api");
44
+
45
+ // src/attributes.ts
46
+ var import_core = require("@langfuse/core");
47
+ function createTraceAttributes({
48
+ name,
49
+ userId,
50
+ sessionId,
51
+ version,
52
+ release,
53
+ input,
54
+ output,
55
+ metadata,
56
+ tags,
57
+ environment,
58
+ public: isPublic
59
+ } = {}) {
60
+ const attributes = {
61
+ [import_core.LangfuseOtelSpanAttributes.TRACE_NAME]: name,
62
+ [import_core.LangfuseOtelSpanAttributes.TRACE_USER_ID]: userId,
63
+ [import_core.LangfuseOtelSpanAttributes.TRACE_SESSION_ID]: sessionId,
64
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
65
+ [import_core.LangfuseOtelSpanAttributes.RELEASE]: release,
66
+ [import_core.LangfuseOtelSpanAttributes.TRACE_INPUT]: _serialize(input),
67
+ [import_core.LangfuseOtelSpanAttributes.TRACE_OUTPUT]: _serialize(output),
68
+ [import_core.LangfuseOtelSpanAttributes.TRACE_TAGS]: tags,
69
+ [import_core.LangfuseOtelSpanAttributes.ENVIRONMENT]: environment,
70
+ [import_core.LangfuseOtelSpanAttributes.TRACE_PUBLIC]: isPublic,
71
+ ..._flattenAndSerializeMetadata(metadata, "trace")
72
+ };
73
+ return Object.fromEntries(
74
+ Object.entries(attributes).filter(([_, v]) => v != null)
75
+ );
76
+ }
77
+ function createSpanAttributes({
78
+ metadata,
79
+ input,
80
+ output,
81
+ level,
82
+ statusMessage,
83
+ version
84
+ }) {
85
+ const attributes = {
86
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "span",
87
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
88
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
89
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
90
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
91
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
92
+ ..._flattenAndSerializeMetadata(metadata, "observation")
93
+ };
94
+ return Object.fromEntries(
95
+ Object.entries(attributes).filter(([_, v]) => v != null)
96
+ );
97
+ }
98
+ function createGenerationAttributes({
99
+ completionStartTime,
100
+ metadata,
101
+ level,
102
+ statusMessage,
103
+ version,
104
+ model,
105
+ modelParameters,
106
+ input,
107
+ output,
108
+ usageDetails,
109
+ costDetails,
110
+ prompt
111
+ }) {
112
+ const attributes = {
113
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "generation",
114
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
115
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
116
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
117
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
118
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
119
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_MODEL]: model,
120
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]: _serialize(usageDetails),
121
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS]: _serialize(costDetails),
122
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME]: _serialize(completionStartTime),
123
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]: _serialize(modelParameters),
124
+ ...prompt && !prompt.isFallback ? {
125
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]: prompt.name,
126
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]: prompt.version
127
+ } : {},
128
+ ..._flattenAndSerializeMetadata(metadata, "observation")
129
+ };
130
+ return Object.fromEntries(
131
+ Object.entries(attributes).filter(([_, v]) => v != null)
132
+ );
133
+ }
134
+ function createEventAttributes({
135
+ metadata,
136
+ input,
137
+ output,
138
+ level,
139
+ statusMessage,
140
+ version
141
+ }) {
142
+ const attributes = {
143
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: "event",
144
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level,
145
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
146
+ [import_core.LangfuseOtelSpanAttributes.VERSION]: version,
147
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
148
+ [import_core.LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output),
149
+ ..._flattenAndSerializeMetadata(metadata, "observation")
150
+ };
151
+ return Object.fromEntries(
152
+ Object.entries(attributes).filter(([_, v]) => v != null)
153
+ );
154
+ }
155
+ function _serialize(obj) {
156
+ try {
157
+ return obj != null ? JSON.stringify(obj) : void 0;
158
+ } catch {
159
+ return "<failed to serialize>";
160
+ }
161
+ }
162
+ function _flattenAndSerializeMetadata(metadata, type) {
163
+ const prefix = type === "observation" ? import_core.LangfuseOtelSpanAttributes.OBSERVATION_METADATA : import_core.LangfuseOtelSpanAttributes.TRACE_METADATA;
164
+ const metadataAttributes = {};
165
+ if (metadata === void 0 || metadata === null) {
166
+ return metadataAttributes;
167
+ }
168
+ if (typeof metadata !== "object" || Array.isArray(metadata)) {
169
+ const serialized = _serialize(metadata);
170
+ if (serialized) {
171
+ metadataAttributes[prefix] = serialized;
172
+ }
173
+ } else {
174
+ for (const [key, value] of Object.entries(metadata)) {
175
+ const serialized = typeof value === "string" ? value : _serialize(value);
176
+ if (serialized) {
177
+ metadataAttributes[`${prefix}.${key}`] = serialized;
178
+ }
179
+ }
180
+ }
181
+ return metadataAttributes;
182
+ }
183
+
184
+ // src/utils.ts
185
+ var import_core2 = require("@langfuse/core");
186
+ var import_api = require("@opentelemetry/api");
187
+ function getLangfuseTracer() {
188
+ return import_api.trace.getTracer(import_core2.LANGFUSE_TRACER_NAME, import_core2.LANGFUSE_SDK_VERSION);
189
+ }
190
+
191
+ // src/spanWrapper.ts
192
+ var LangfuseSpanWrapper = class {
193
+ constructor(params) {
194
+ this.otelSpan = params.otelSpan;
195
+ this.id = params.otelSpan.spanContext().spanId;
196
+ this.traceId = params.otelSpan.spanContext().traceId;
197
+ }
198
+ get tracer() {
199
+ return getLangfuseTracer();
200
+ }
201
+ end(endTime) {
202
+ this.otelSpan.end(endTime);
203
+ }
204
+ updateTrace(attributes) {
205
+ this.otelSpan.setAttributes(createTraceAttributes(attributes));
206
+ return this;
207
+ }
208
+ };
209
+ var LangfuseSpan = class extends LangfuseSpanWrapper {
210
+ constructor(params) {
211
+ super(params);
212
+ if (params.attributes) {
213
+ this.otelSpan.setAttributes(createSpanAttributes(params.attributes));
214
+ }
215
+ }
216
+ update(attributes) {
217
+ this.otelSpan.setAttributes(createSpanAttributes(attributes));
218
+ return this;
219
+ }
220
+ startSpan(name, attributes) {
221
+ return startSpan(name, attributes, {
222
+ parentSpanContext: this.otelSpan.spanContext()
223
+ });
224
+ }
225
+ startGeneration(name, attributes) {
226
+ return startGeneration(name, attributes, {
227
+ parentSpanContext: this.otelSpan.spanContext()
228
+ });
229
+ }
230
+ createEvent(name, attributes) {
231
+ return createEvent(name, attributes, {
232
+ parentSpanContext: this.otelSpan.spanContext()
233
+ });
234
+ }
235
+ };
236
+ var LangfuseGeneration = class extends LangfuseSpanWrapper {
237
+ constructor(params) {
238
+ super(params);
239
+ if (params.attributes) {
240
+ this.otelSpan.setAttributes(
241
+ createGenerationAttributes(params.attributes)
242
+ );
243
+ }
244
+ }
245
+ update(attributes) {
246
+ this.otelSpan.setAttributes(createGenerationAttributes(attributes));
247
+ return this;
248
+ }
249
+ createEvent(name, attributes) {
250
+ return createEvent(name, attributes, {
251
+ parentSpanContext: this.otelSpan.spanContext()
252
+ });
253
+ }
254
+ };
255
+ var LangfuseEvent = class extends LangfuseSpanWrapper {
256
+ constructor(params) {
257
+ super(params);
258
+ if (params.attributes) {
259
+ this.otelSpan.setAttributes(createEventAttributes(params.attributes));
260
+ }
261
+ this.otelSpan.end(params.timestamp);
262
+ }
263
+ };
264
+
265
+ // src/index.ts
266
+ var import_core4 = require("@langfuse/core");
267
+ function createOtelSpan(params) {
268
+ return getLangfuseTracer().startSpan(
269
+ params.name,
270
+ { startTime: params.startTime },
271
+ createParentContext(params.parentSpanContext)
272
+ );
273
+ }
274
+ function createParentContext(parentSpanContext) {
275
+ if (!parentSpanContext) return;
276
+ return import_api2.trace.setSpanContext(import_api2.context.active(), parentSpanContext);
277
+ }
278
+ function wrapPromise(promise, span) {
279
+ return promise.then(
280
+ (value) => {
281
+ span.end();
282
+ return value;
283
+ },
284
+ (err) => {
285
+ span.setStatus({
286
+ code: import_api2.SpanStatusCode.ERROR,
287
+ message: err instanceof Error ? err.message : "Unknown error"
288
+ }).end();
289
+ throw err;
290
+ }
291
+ );
292
+ }
293
+ function startSpan(name, attributes, options) {
294
+ const otelSpan = createOtelSpan({
295
+ name,
296
+ ...options
297
+ });
298
+ return new LangfuseSpan({ otelSpan, attributes });
299
+ }
300
+ function startGeneration(name, attributes, options) {
301
+ const otelSpan = createOtelSpan({
302
+ name,
303
+ ...options
304
+ });
305
+ return new LangfuseGeneration({ otelSpan, attributes });
306
+ }
307
+ function createEvent(name, attributes, options) {
308
+ var _a;
309
+ const timestamp = (_a = options == null ? void 0 : options.startTime) != null ? _a : /* @__PURE__ */ new Date();
310
+ const otelSpan = createOtelSpan({
311
+ name,
312
+ ...options,
313
+ startTime: timestamp
314
+ });
315
+ return new LangfuseEvent({ otelSpan, attributes, timestamp });
316
+ }
317
+ function startActiveSpan(name, fn, options) {
318
+ var _a;
319
+ return getLangfuseTracer().startActiveSpan(
320
+ name,
321
+ { startTime: options == null ? void 0 : options.startTime },
322
+ (_a = createParentContext(options == null ? void 0 : options.parentSpanContext)) != null ? _a : import_api2.context.active(),
323
+ (span) => {
324
+ try {
325
+ const result = fn(new LangfuseSpan({ otelSpan: span }));
326
+ if (result instanceof Promise) {
327
+ return wrapPromise(result, span);
328
+ } else {
329
+ span.end();
330
+ return result;
331
+ }
332
+ } catch (err) {
333
+ span.setStatus({
334
+ code: import_api2.SpanStatusCode.ERROR,
335
+ message: err instanceof Error ? err.message : "Unknown error"
336
+ }).end();
337
+ throw err;
338
+ }
339
+ }
340
+ );
341
+ }
342
+ function startActiveGeneration(name, fn, options) {
343
+ var _a;
344
+ return getLangfuseTracer().startActiveSpan(
345
+ name,
346
+ { startTime: options == null ? void 0 : options.startTime },
347
+ (_a = createParentContext(options == null ? void 0 : options.parentSpanContext)) != null ? _a : import_api2.context.active(),
348
+ (span) => {
349
+ try {
350
+ const result = fn(new LangfuseGeneration({ otelSpan: span }));
351
+ if (result instanceof Promise) {
352
+ return wrapPromise(result, span);
353
+ } else {
354
+ span.end();
355
+ return result;
356
+ }
357
+ } catch (err) {
358
+ span.setStatus({
359
+ code: import_api2.SpanStatusCode.ERROR,
360
+ message: err instanceof Error ? err.message : "Unknown error"
361
+ }).end();
362
+ throw err;
363
+ }
364
+ }
365
+ );
366
+ }
367
+ function updateActiveTrace(attributes) {
368
+ const span = import_api2.trace.getActiveSpan();
369
+ if (!span) {
370
+ (0, import_core3.getGlobalLogger)().warn(
371
+ "No active OTEL span in context. Skipping trace update."
372
+ );
373
+ return;
374
+ }
375
+ span.setAttributes(createTraceAttributes(attributes));
376
+ }
377
+ function updateActiveSpan(attributes) {
378
+ const span = import_api2.trace.getActiveSpan();
379
+ if (!span) {
380
+ (0, import_core3.getGlobalLogger)().warn(
381
+ "No active OTEL span in context. Skipping span update."
382
+ );
383
+ return;
384
+ }
385
+ span.setAttributes(createSpanAttributes(attributes));
386
+ }
387
+ function updateActiveGeneration(attributes) {
388
+ const span = import_api2.trace.getActiveSpan();
389
+ if (!span) {
390
+ (0, import_core3.getGlobalLogger)().warn(
391
+ "No active OTEL span in context. Skipping generation update."
392
+ );
393
+ return;
394
+ }
395
+ span.setAttributes(createGenerationAttributes(attributes));
396
+ }
397
+ function observe(fn, options = {}) {
398
+ const {
399
+ name = fn.name || "anonymous-function",
400
+ asType = "span",
401
+ captureInput = true,
402
+ captureOutput = true
403
+ } = options;
404
+ const wrappedFunction = (...args) => {
405
+ const inputData = captureInput ? _captureArguments(args) : void 0;
406
+ const observation = asType === "generation" ? startGeneration(name, inputData ? { input: inputData } : {}) : startSpan(name, inputData ? { input: inputData } : {});
407
+ const activeContext = import_api2.trace.setSpan(import_api2.context.active(), observation.otelSpan);
408
+ try {
409
+ const result = import_api2.context.with(activeContext, () => fn(...args));
410
+ if (result instanceof Promise) {
411
+ return result.then(
412
+ (value) => {
413
+ if (captureOutput) {
414
+ observation.update({ output: _captureOutput(value) });
415
+ }
416
+ observation.end();
417
+ return value;
418
+ },
419
+ (error) => {
420
+ observation.update({
421
+ level: "ERROR",
422
+ statusMessage: (error instanceof Error ? error.message : String(error)) || "Function threw an error",
423
+ output: captureOutput ? { error: String(error) } : void 0
424
+ }).end();
425
+ throw error;
426
+ }
427
+ );
428
+ } else {
429
+ if (captureOutput) {
430
+ observation.update({ output: _captureOutput(result) });
431
+ }
432
+ observation.end();
433
+ return result;
434
+ }
435
+ } catch (error) {
436
+ observation.update({
437
+ level: "ERROR",
438
+ statusMessage: (error instanceof Error ? error.message : String(error)) || "Function threw an error",
439
+ output: captureOutput ? { error: String(error) } : void 0
440
+ }).end();
441
+ throw error;
442
+ }
443
+ };
444
+ return wrappedFunction;
445
+ }
446
+ function _captureArguments(args) {
447
+ try {
448
+ if (args.length === 0) return void 0;
449
+ if (args.length === 1) return args[0];
450
+ return args;
451
+ } catch {
452
+ return "<failed to capture arguments>";
453
+ }
454
+ }
455
+ function _captureOutput(value) {
456
+ try {
457
+ if (value === void 0 || value === null) return value;
458
+ if (typeof value !== "object") return value;
459
+ return value;
460
+ } catch {
461
+ return "<failed to capture output>";
462
+ }
463
+ }
464
+ async function createTraceId(seed) {
465
+ if (seed) {
466
+ const data = new TextEncoder().encode(seed);
467
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
468
+ const hashArray = new Uint8Array(hashBuffer);
469
+ return uint8ArrayToHex(hashArray).slice(0, 32);
470
+ }
471
+ const randomValues = crypto.getRandomValues(new Uint8Array(16));
472
+ return uint8ArrayToHex(randomValues);
473
+ }
474
+ function uint8ArrayToHex(array) {
475
+ return Array.from(array).map((b) => b.toString(16).padStart(2, "0")).join("");
476
+ }
477
+ // Annotate the CommonJS export names for ESM import in node:
478
+ 0 && (module.exports = {
479
+ LangfuseEvent,
480
+ LangfuseGeneration,
481
+ LangfuseOtelSpanAttributes,
482
+ LangfuseSpan,
483
+ createEvent,
484
+ createGenerationAttributes,
485
+ createSpanAttributes,
486
+ createTraceAttributes,
487
+ createTraceId,
488
+ observe,
489
+ startActiveGeneration,
490
+ startActiveSpan,
491
+ startGeneration,
492
+ startSpan,
493
+ updateActiveGeneration,
494
+ updateActiveSpan,
495
+ updateActiveTrace
496
+ });
497
+ //# sourceMappingURL=index.cjs.map