@latitude-data/telemetry 0.0.1

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,157 @@
1
+ # GNU LESSER GENERAL PUBLIC LICENSE
2
+
3
+ Version 3, 29 June 2007
4
+
5
+ Copyright (C) 2007 Free Software Foundation, Inc.
6
+ <https://fsf.org/>
7
+
8
+ Everyone is permitted to copy and distribute verbatim copies of this
9
+ license document, but changing it is not allowed.
10
+
11
+ This version of the GNU Lesser General Public License incorporates the
12
+ terms and conditions of version 3 of the GNU General Public License,
13
+ supplemented by the additional permissions listed below.
14
+
15
+ ## 0. Additional Definitions.
16
+
17
+ As used herein, "this License" refers to version 3 of the GNU Lesser
18
+ General Public License, and the "GNU GPL" refers to version 3 of the
19
+ GNU General Public License.
20
+
21
+ "The Library" refers to a covered work governed by this License, other
22
+ than an Application or a Combined Work as defined below.
23
+
24
+ An "Application" is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A "Combined Work" is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the "Linked
32
+ Version".
33
+
34
+ The "Minimal Corresponding Source" for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The "Corresponding Application Code" for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ ## 1. Exception to Section 3 of the GNU GPL.
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ ## 2. Conveying Modified Versions.
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ - a) under this License, provided that you make a good faith effort
58
+ to ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+ - b) under the GNU GPL, with none of the additional permissions of
62
+ this License applicable to that copy.
63
+
64
+ ## 3. Object Code Incorporating Material from Library Header Files.
65
+
66
+ The object code form of an Application may incorporate material from a
67
+ header file that is part of the Library. You may convey such object
68
+ code under terms of your choice, provided that, if the incorporated
69
+ material is not limited to numerical parameters, data structure
70
+ layouts and accessors, or small macros, inline functions and templates
71
+ (ten or fewer lines in length), you do both of the following:
72
+
73
+ - a) Give prominent notice with each copy of the object code that
74
+ the Library is used in it and that the Library and its use are
75
+ covered by this License.
76
+ - b) Accompany the object code with a copy of the GNU GPL and this
77
+ license document.
78
+
79
+ ## 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that, taken
82
+ together, effectively do not restrict modification of the portions of
83
+ the Library contained in the Combined Work and reverse engineering for
84
+ debugging such modifications, if you also do each of the following:
85
+
86
+ - a) Give prominent notice with each copy of the Combined Work that
87
+ the Library is used in it and that the Library and its use are
88
+ covered by this License.
89
+ - b) Accompany the Combined Work with a copy of the GNU GPL and this
90
+ license document.
91
+ - c) For a Combined Work that displays copyright notices during
92
+ execution, include the copyright notice for the Library among
93
+ these notices, as well as a reference directing the user to the
94
+ copies of the GNU GPL and this license document.
95
+ - d) Do one of the following:
96
+ - 0) Convey the Minimal Corresponding Source under the terms of
97
+ this License, and the Corresponding Application Code in a form
98
+ suitable for, and under terms that permit, the user to
99
+ recombine or relink the Application with a modified version of
100
+ the Linked Version to produce a modified Combined Work, in the
101
+ manner specified by section 6 of the GNU GPL for conveying
102
+ Corresponding Source.
103
+ - 1) Use a suitable shared library mechanism for linking with
104
+ the Library. A suitable mechanism is one that (a) uses at run
105
+ time a copy of the Library already present on the user's
106
+ computer system, and (b) will operate properly with a modified
107
+ version of the Library that is interface-compatible with the
108
+ Linked Version.
109
+ - e) Provide Installation Information, but only if you would
110
+ otherwise be required to provide such information under section 6
111
+ of the GNU GPL, and only to the extent that such information is
112
+ necessary to install and execute a modified version of the
113
+ Combined Work produced by recombining or relinking the Application
114
+ with a modified version of the Linked Version. (If you use option
115
+ 4d0, the Installation Information must accompany the Minimal
116
+ Corresponding Source and Corresponding Application Code. If you
117
+ use option 4d1, you must provide the Installation Information in
118
+ the manner specified by section 6 of the GNU GPL for conveying
119
+ Corresponding Source.)
120
+
121
+ ## 5. Combined Libraries.
122
+
123
+ You may place library facilities that are a work based on the Library
124
+ side by side in a single library together with other library
125
+ facilities that are not Applications and are not covered by this
126
+ License, and convey such a combined library under terms of your
127
+ choice, if you do both of the following:
128
+
129
+ - a) Accompany the combined library with a copy of the same work
130
+ based on the Library, uncombined with any other library
131
+ facilities, conveyed under the terms of this License.
132
+ - b) Give prominent notice with the combined library that part of it
133
+ is a work based on the Library, and explaining where to find the
134
+ accompanying uncombined form of the same work.
135
+
136
+ ## 6. Revised Versions of the GNU Lesser General Public License.
137
+
138
+ The Free Software Foundation may publish revised and/or new versions
139
+ of the GNU Lesser General Public License from time to time. Such new
140
+ versions will be similar in spirit to the present version, but may
141
+ differ in detail to address new problems or concerns.
142
+
143
+ Each version is given a distinguishing version number. If the Library
144
+ as you received it specifies that a certain numbered version of the
145
+ GNU Lesser General Public License "or any later version" applies to
146
+ it, you have the option of following the terms and conditions either
147
+ of that published version or of any later version published by the
148
+ Free Software Foundation. If the Library as you received it does not
149
+ specify a version number of the GNU Lesser General Public License, you
150
+ may choose any version of the GNU Lesser General Public License ever
151
+ published by the Free Software Foundation.
152
+
153
+ If the Library as you received it specifies that a proxy can decide
154
+ whether future versions of the GNU Lesser General Public License shall
155
+ apply, that proxy's public statement of acceptance of any version is
156
+ permanent authorization for you to choose that version for the
157
+ Library.
package/dist/index.cjs ADDED
@@ -0,0 +1,487 @@
1
+ 'use strict';
2
+
3
+ var core = require('@opentelemetry/core');
4
+ var otlpExporterBase = require('@opentelemetry/otlp-exporter-base');
5
+ var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
6
+ var sdkNode = require('@opentelemetry/sdk-node');
7
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
8
+ var instrumentationAnthropic = require('@traceloop/instrumentation-anthropic');
9
+ var instrumentationOpenai = require('@traceloop/instrumentation-openai');
10
+ var instrumentationAzure = require('@traceloop/instrumentation-azure');
11
+ var instrumentationVertexai = require('@traceloop/instrumentation-vertexai');
12
+ var instrumentationBedrock = require('@traceloop/instrumentation-bedrock');
13
+ var instrumentationCohere = require('@traceloop/instrumentation-cohere');
14
+ var resources = require('@opentelemetry/resources');
15
+ var api = require('@opentelemetry/api');
16
+
17
+ const DOMAIN = 'gateway.latitude.so'
18
+ ;
19
+ const PROTOCOL = 'https' ;
20
+ class LatitudeExporter extends otlpExporterBase.OTLPExporterBase {
21
+ url;
22
+ headers;
23
+ constructor(config) {
24
+ super(config);
25
+ this.url = config.endpoint || this.__defaultUrl;
26
+ this.headers = {
27
+ Authorization: `Bearer ${config.apiKey}`,
28
+ };
29
+ }
30
+ async export(spans, resultCallback) {
31
+ await this.send(spans, () => resultCallback({ code: core.ExportResultCode.SUCCESS }), (error) => {
32
+ resultCallback({ code: core.ExportResultCode.FAILED, error });
33
+ });
34
+ }
35
+ async shutdown() {
36
+ // No-op
37
+ }
38
+ async onShutdown() {
39
+ // No-op
40
+ }
41
+ async onInit() {
42
+ // No-op
43
+ }
44
+ async send(spans, onSuccess, onError) {
45
+ if (spans.length === 0) {
46
+ onSuccess();
47
+ return;
48
+ }
49
+ const serviceRequest = this.convert(spans);
50
+ const body = JSON.stringify(serviceRequest);
51
+ try {
52
+ const response = await fetch(this.url, {
53
+ method: 'POST',
54
+ headers: {
55
+ 'Content-Type': 'application/json',
56
+ ...this.headers,
57
+ },
58
+ body,
59
+ });
60
+ if (!response.ok || response.status >= 400) {
61
+ throw new Error(`${response.status} ${response.statusText}`);
62
+ }
63
+ onSuccess();
64
+ }
65
+ catch (error) {
66
+ onError(error);
67
+ }
68
+ }
69
+ convert(spans) {
70
+ return {
71
+ resourceSpans: [
72
+ {
73
+ resource: {
74
+ attributes: this.convertAttributes(spans[0]?.resource?.attributes || {}),
75
+ },
76
+ scopeSpans: [
77
+ {
78
+ spans: spans.map((span) => ({
79
+ traceId: span.spanContext().traceId,
80
+ spanId: span.spanContext().spanId,
81
+ parentSpanId: span.parentSpanId,
82
+ name: span.name,
83
+ kind: span.kind,
84
+ startTimeUnixNano: core.hrTimeToNanoseconds(span.startTime).toString(),
85
+ endTimeUnixNano: span.endTime
86
+ ? core.hrTimeToNanoseconds(span.endTime).toString()
87
+ : undefined,
88
+ attributes: this.convertAttributes(span.attributes),
89
+ status: span.status && {
90
+ code: span.status.code,
91
+ message: span.status.message,
92
+ },
93
+ events: span.events?.map((event) => ({
94
+ timeUnixNano: core.hrTimeToNanoseconds(event.time).toString(),
95
+ name: event.name,
96
+ attributes: this.convertAttributes(event.attributes),
97
+ })),
98
+ links: span.links?.map((link) => ({
99
+ traceId: link.context.traceId,
100
+ spanId: link.context.spanId,
101
+ attributes: this.convertAttributes(link.attributes),
102
+ })),
103
+ })),
104
+ },
105
+ ],
106
+ },
107
+ ],
108
+ };
109
+ }
110
+ getDefaultUrl(config) {
111
+ return config.endpoint || this.__defaultUrl;
112
+ }
113
+ get __defaultUrl() {
114
+ return `${PROTOCOL}://${DOMAIN}/v1/traces`;
115
+ }
116
+ convertAttributes(attributes = {}) {
117
+ return Object.entries(attributes).map(([key, value]) => ({
118
+ key,
119
+ value: this.convertAttributeValue(value),
120
+ }));
121
+ }
122
+ convertAttributeValue(value) {
123
+ if (typeof value === 'string')
124
+ return { stringValue: value };
125
+ if (typeof value === 'number')
126
+ return { intValue: value };
127
+ if (typeof value === 'boolean')
128
+ return { boolValue: value };
129
+ return { stringValue: String(value) };
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Below are the semantic conventions for the Vercel AI SDK.
135
+ * @see https://sdk.vercel.ai/docs/ai-sdk-core/telemetry#collected-data
136
+ */
137
+ const AI_PREFIX = 'ai';
138
+ const AIPrefixes = {
139
+ settings: 'settings',
140
+ model: 'model',
141
+ usage: 'usage',
142
+ telemetry: 'telemetry',
143
+ prompt: 'prompt',
144
+ toolCall: 'toolCall',
145
+ response: 'response',
146
+ };
147
+ const AIUsagePostfixes = {
148
+ completionTokens: 'completionTokens',
149
+ promptTokens: 'promptTokens',
150
+ };
151
+ const AIResultPostfixes = {
152
+ text: 'text',
153
+ toolCalls: 'toolCalls',
154
+ object: 'object',
155
+ };
156
+ const AIPromptPostfixes = {
157
+ messages: 'messages',
158
+ };
159
+ const AIToolCallPostfixes = {
160
+ id: 'id',
161
+ name: 'name',
162
+ args: 'args',
163
+ result: 'result',
164
+ };
165
+ const SETTINGS = `${AI_PREFIX}.${AIPrefixes.settings}`;
166
+ const MODEL_ID = `${AI_PREFIX}.${AIPrefixes.model}.id`;
167
+ const METADATA = `${AI_PREFIX}.${AIPrefixes.telemetry}.metadata`;
168
+ const TOKEN_COUNT_COMPLETION = `${AI_PREFIX}.${AIPrefixes.usage}.${AIUsagePostfixes.completionTokens}`;
169
+ const TOKEN_COUNT_PROMPT = `${AI_PREFIX}.${AIPrefixes.usage}.${AIUsagePostfixes.promptTokens}`;
170
+ const RESPONSE_TEXT = `${AI_PREFIX}.${AIPrefixes.response}.${AIResultPostfixes.text}`;
171
+ const RESPONSE_TOOL_CALLS = `${AI_PREFIX}.${AIPrefixes.response}.${AIResultPostfixes.toolCalls}`;
172
+ const RESULT_OBJECT = `${AI_PREFIX}.${AIPrefixes.response}.${AIResultPostfixes.object}`;
173
+ const PROMPT = `${AI_PREFIX}.${AIPrefixes.prompt}`;
174
+ const PROMPT_MESSAGES = `${PROMPT}.${AIPromptPostfixes.messages}`;
175
+ const EMBEDDING_TEXT = `${AI_PREFIX}.value`;
176
+ const EMBEDDING_VECTOR = `${AI_PREFIX}.embedding`;
177
+ const EMBEDDING_TEXTS = `${AI_PREFIX}.values`;
178
+ const EMBEDDING_VECTORS = `${AI_PREFIX}.embeddings`;
179
+ const TOOL_CALL_ID = `${AI_PREFIX}.${AIPrefixes.toolCall}.${AIToolCallPostfixes.id}`;
180
+ const TOOL_CALL_NAME = `${AI_PREFIX}.${AIPrefixes.toolCall}.${AIToolCallPostfixes.name}`;
181
+ const TOOL_CALL_ARGS = `${AI_PREFIX}.${AIPrefixes.toolCall}.${AIToolCallPostfixes.args}`;
182
+ const TOOL_CALL_RESULT = `${AI_PREFIX}.${AIPrefixes.toolCall}.${AIToolCallPostfixes.result}`;
183
+ /**
184
+ * The semantic conventions used by the Vercel AI SDK.
185
+ * @see https://sdk.vercel.ai/docs/ai-sdk-core/telemetry#collected-data
186
+ */
187
+ const AISemanticConventions = {
188
+ MODEL_ID,
189
+ METADATA,
190
+ SETTINGS,
191
+ TOKEN_COUNT_COMPLETION,
192
+ TOKEN_COUNT_PROMPT,
193
+ RESPONSE_TEXT,
194
+ RESPONSE_TOOL_CALLS,
195
+ RESULT_OBJECT,
196
+ PROMPT,
197
+ PROMPT_MESSAGES,
198
+ EMBEDDING_TEXT,
199
+ EMBEDDING_VECTOR,
200
+ EMBEDDING_TEXTS,
201
+ EMBEDDING_VECTORS,
202
+ TOOL_CALL_ID,
203
+ TOOL_CALL_NAME,
204
+ TOOL_CALL_ARGS,
205
+ TOOL_CALL_RESULT,
206
+ };
207
+ Object.freeze(Object.values(AISemanticConventions));
208
+
209
+ class VercelSpanProcessor extends sdkTraceBase.SimpleSpanProcessor {
210
+ onEnd(span) {
211
+ if (!shouldProcess(span))
212
+ return;
213
+ if (shouldConvertToLatitudeFormat(span))
214
+ convertToLatitudeFormat(span);
215
+ super.onEnd(span);
216
+ }
217
+ }
218
+ class VercelBatchSpanProcessor extends sdkTraceBase.BatchSpanProcessor {
219
+ onEnd(span) {
220
+ if (!shouldProcess(span))
221
+ return;
222
+ if (shouldConvertToLatitudeFormat(span))
223
+ convertToLatitudeFormat(span);
224
+ super.onEnd(span);
225
+ }
226
+ }
227
+ function shouldProcess(span) {
228
+ return (Object.keys(span.attributes).some((k) => k.startsWith('latitude.')) ||
229
+ Object.keys(span.attributes).some((k) => k.startsWith('ai.')));
230
+ }
231
+ function shouldConvertToLatitudeFormat(span) {
232
+ return Object.keys(span.attributes).some((k) => k.startsWith('ai.'));
233
+ }
234
+ function convertToLatitudeFormat(span) {
235
+ try {
236
+ const computedAttrs = computeOpenLLMAttributes(span);
237
+ if (computedAttrs) {
238
+ ;
239
+ span.attributes = {
240
+ ...span.attributes,
241
+ ...computedAttrs,
242
+ };
243
+ }
244
+ }
245
+ catch (e) {
246
+ console.log('Latitude telemetry Error: ', e);
247
+ // do nothing
248
+ }
249
+ }
250
+ function computeOpenLLMAttributes(span) {
251
+ const attrs = span.attributes || {};
252
+ const result = {};
253
+ // Extract model information
254
+ if (attrs[AISemanticConventions.MODEL_ID]) {
255
+ result['gen_ai.request.model'] = String(attrs[AISemanticConventions.MODEL_ID]);
256
+ result['gen_ai.response.model'] = String(attrs[AISemanticConventions.MODEL_ID]);
257
+ }
258
+ // Extract settings
259
+ try {
260
+ const settings = attrs[AISemanticConventions.SETTINGS]
261
+ ? JSON.parse(String(attrs[AISemanticConventions.SETTINGS]))
262
+ : {};
263
+ if (settings) {
264
+ // Add max tokens if present
265
+ if (settings.maxTokens) {
266
+ result['gen_ai.request.max_tokens'] = settings.maxTokens;
267
+ }
268
+ if (!attrs['gen_ai.system'] && settings.provider) {
269
+ result['gen_ai.system'] = String(settings.provider);
270
+ }
271
+ }
272
+ }
273
+ catch (e) {
274
+ console.error('Error parsing settings', e);
275
+ }
276
+ // Set request type to chat as that's what Vercel AI SDK uses
277
+ result['llm.request.type'] = 'chat';
278
+ // Extract messages
279
+ try {
280
+ const messages = attrs['ai.prompt.messages']
281
+ ? JSON.parse(String(attrs['ai.prompt.messages']))
282
+ : [];
283
+ // Process prompt messages
284
+ messages.forEach((msg, index) => {
285
+ result[`gen_ai.prompt.${index}.role`] = msg.role;
286
+ result[`gen_ai.prompt.${index}.content`] =
287
+ typeof msg.content === 'string'
288
+ ? msg.content
289
+ : JSON.stringify(msg.content);
290
+ });
291
+ }
292
+ catch (e) {
293
+ console.error('Error parsing messages', e);
294
+ return undefined;
295
+ }
296
+ // Extract completion/response
297
+ const responseText = attrs['ai.response.text'];
298
+ const responseObject = attrs['ai.response.object'];
299
+ const responseToolCalls = attrs['ai.response.toolCalls'];
300
+ if (responseText) {
301
+ result[`gen_ai.completion.0.role`] = 'assistant';
302
+ result[`gen_ai.completion.0.content`] = String(responseText);
303
+ }
304
+ else if (responseToolCalls) {
305
+ try {
306
+ const toolCalls = JSON.parse(String(responseToolCalls));
307
+ if (toolCalls.length > 0) {
308
+ result['gen_ai.completion.0.finish_reason'] = 'tool_calls';
309
+ result[`gen_ai.completion.0.role`] = 'assistant';
310
+ toolCalls.forEach((toolCall, toolCallIndex) => {
311
+ result[`gen_ai.completion.0.tool_calls.${toolCallIndex}.id`] =
312
+ toolCall.toolCallId;
313
+ result[`gen_ai.completion.0.tool_calls.${toolCallIndex}.name`] =
314
+ toolCall.toolName;
315
+ result[`gen_ai.completion.0.tool_calls.${toolCallIndex}.arguments`] =
316
+ toolCall.args;
317
+ });
318
+ }
319
+ }
320
+ catch (e) {
321
+ console.error('Error parsing tool calls', e);
322
+ }
323
+ }
324
+ else if (responseObject) {
325
+ result['gen_ai.completion.0.role'] = 'assistant';
326
+ result['gen_ai.completion.0.content'] = String(responseObject);
327
+ }
328
+ // Extract token usage
329
+ const completionTokens = attrs['ai.usage.completionTokens'];
330
+ const promptTokens = attrs['ai.usage.promptTokens'];
331
+ if (typeof completionTokens === 'number') {
332
+ result['gen_ai.usage.completion_tokens'] = completionTokens;
333
+ }
334
+ if (typeof promptTokens === 'number') {
335
+ result['gen_ai.usage.prompt_tokens'] = promptTokens;
336
+ }
337
+ if (typeof completionTokens === 'number' &&
338
+ typeof promptTokens === 'number') {
339
+ result['llm.usage.total_tokens'] = completionTokens + promptTokens;
340
+ }
341
+ return result;
342
+ }
343
+
344
+ class LatitudeTelemetrySDK {
345
+ exporter;
346
+ constructor({ exporter, modules = {}, disableBatch = false, processors = [], }) {
347
+ this.exporter = exporter;
348
+ this._init(modules, { disableBatch, processors });
349
+ }
350
+ _init(modules, options) {
351
+ const instrumentations = [];
352
+ if (modules?.openAI) {
353
+ const openAIInstrumentation = new instrumentationOpenai.OpenAIInstrumentation({
354
+ enrichTokens: true,
355
+ });
356
+ // @ts-ignore
357
+ openAIInstrumentation.manuallyInstrument(modules.openAI);
358
+ instrumentations.push(openAIInstrumentation);
359
+ }
360
+ if (modules?.anthropic) {
361
+ const anthropicInstrumentation = new instrumentationAnthropic.AnthropicInstrumentation();
362
+ anthropicInstrumentation.manuallyInstrument(modules.anthropic);
363
+ instrumentations.push(new instrumentationAnthropic.AnthropicInstrumentation());
364
+ }
365
+ if (modules?.azureOpenAI) {
366
+ const azureOpenAIInstrumentation = new instrumentationAzure.AzureOpenAIInstrumentation();
367
+ azureOpenAIInstrumentation.manuallyInstrument(modules.azureOpenAI);
368
+ instrumentations.push(azureOpenAIInstrumentation);
369
+ }
370
+ if (modules?.cohere) {
371
+ const cohereInstrumentation = new instrumentationCohere.CohereInstrumentation();
372
+ cohereInstrumentation.manuallyInstrument(modules.cohere);
373
+ instrumentations.push(cohereInstrumentation);
374
+ }
375
+ if (modules?.google_vertexai) {
376
+ const vertexAIInstrumentation = new instrumentationVertexai.VertexAIInstrumentation();
377
+ vertexAIInstrumentation.manuallyInstrument(modules.google_vertexai);
378
+ instrumentations.push(vertexAIInstrumentation);
379
+ }
380
+ if (modules?.google_aiplatform) {
381
+ const aiplatformInstrumentation = new instrumentationVertexai.AIPlatformInstrumentation();
382
+ aiplatformInstrumentation.manuallyInstrument(modules.google_aiplatform);
383
+ instrumentations.push(aiplatformInstrumentation);
384
+ }
385
+ if (modules?.bedrock) {
386
+ const bedrockInstrumentation = new instrumentationBedrock.BedrockInstrumentation();
387
+ bedrockInstrumentation.manuallyInstrument(modules.bedrock);
388
+ instrumentations.push(bedrockInstrumentation);
389
+ }
390
+ // TODO: Enable these once we have manually tested them
391
+ //if (modules?.langchain) {
392
+ // const langchainInstrumentation = new LangChainInstrumentation()
393
+ // langchainInstrumentation.manuallyInstrument(modules.langchain!)
394
+ // instrumentations.push(langchainInstrumentation)
395
+ //}
396
+ //
397
+ //if (modules?.llamaIndex) {
398
+ // const llamaindexInstrumentation = new LlamaIndexInstrumentation()
399
+ // llamaindexInstrumentation.manuallyInstrument(modules.llamaIndex!)
400
+ // instrumentations.push(llamaindexInstrumentation)
401
+ //}
402
+ //if (modules?.pinecone) {
403
+ // const pineconeInstrumentation = new PineconeInstrumentation()
404
+ // pineconeInstrumentation.manuallyInstrument(modules.pinecone!)
405
+ // instrumentations.push(pineconeInstrumentation)
406
+ //}
407
+ //if (modules?.chromadb) {
408
+ // const chromadbInstrumentation = new ChromaDBInstrumentation()
409
+ // chromadbInstrumentation.manuallyInstrument(modules.chromadb!)
410
+ // instrumentations.push(chromadbInstrumentation)
411
+ //}
412
+ //if (modules?.qdrant) {
413
+ // const qdrantInstrumentation = new QdrantInstrumentation()
414
+ // qdrantInstrumentation.manuallyInstrument(modules.qdrant!)
415
+ // instrumentations.push(qdrantInstrumentation)
416
+ //}
417
+ if (!instrumentations.length && !options?.processors?.length) {
418
+ console.warn('Latitude: No instrumentations or processors to initialize');
419
+ return;
420
+ }
421
+ const processors = options?.disableBatch
422
+ ? [
423
+ new sdkTraceNode.SimpleSpanProcessor(this.exporter),
424
+ ...(options?.processors?.map((processor) => new processor(this.exporter)) || []),
425
+ ]
426
+ : [
427
+ new sdkTraceNode.BatchSpanProcessor(this.exporter),
428
+ ...(options?.processors?.map((processor) => new processor(this.exporter)) || []),
429
+ ];
430
+ const sdk = new sdkNode.NodeSDK({
431
+ resource: new resources.Resource({
432
+ 'service.name': process.env.npm_package_name,
433
+ }),
434
+ instrumentations,
435
+ traceExporter: this.exporter,
436
+ // @ts-ignore
437
+ spanProcessors: processors,
438
+ });
439
+ sdk.start();
440
+ }
441
+ span(s, fn) {
442
+ const c = api.context.active();
443
+ return api.context.with(c, () => api.trace
444
+ .getTracer('latitude')
445
+ .startActiveSpan(s.name ?? 'latitude.span', {}, c, async (span) => {
446
+ try {
447
+ if (s.prompt) {
448
+ try {
449
+ span.setAttribute('latitude.prompt', JSON.stringify(s.prompt));
450
+ }
451
+ catch (e) {
452
+ console.error('Latitude: Could not serialize latitude.prompt attribute', e);
453
+ }
454
+ }
455
+ if (s.distinctId) {
456
+ span.setAttribute('latitude.distinctId', s.distinctId);
457
+ }
458
+ if (s.metadata) {
459
+ try {
460
+ span.setAttribute('latitude.metadata', JSON.stringify(s.metadata));
461
+ }
462
+ catch (e) {
463
+ console.error('Latitude: Could not serialize latitude.metadata attribute', e);
464
+ }
465
+ }
466
+ }
467
+ catch (error) {
468
+ console.error(error);
469
+ }
470
+ const res = fn(span);
471
+ if (res instanceof Promise) {
472
+ return res.then((resolvedRes) => {
473
+ span.end();
474
+ return resolvedRes;
475
+ });
476
+ }
477
+ span.end();
478
+ return res;
479
+ }));
480
+ }
481
+ }
482
+
483
+ exports.LatitudeExporter = LatitudeExporter;
484
+ exports.LatitudeTelemetrySDK = LatitudeTelemetrySDK;
485
+ exports.VercelBatchSpanProcessor = VercelBatchSpanProcessor;
486
+ exports.VercelSpanProcessor = VercelSpanProcessor;
487
+ //# sourceMappingURL=index.cjs.map