@lmnr-ai/client 0.8.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/dist/index.mjs ADDED
@@ -0,0 +1,663 @@
1
+ import { config } from "dotenv";
2
+ import * as path from "path";
3
+ import pino from "pino";
4
+ import { PinoPretty } from "pino-pretty";
5
+ import { v4 } from "uuid";
6
+
7
+ //#region package.json
8
+ var version = "0.8.1";
9
+
10
+ //#endregion
11
+ //#region src/version.ts
12
+ function getLangVersion() {
13
+ if (typeof process !== "undefined" && process.versions && process.versions.node) return `node-${process.versions.node}`;
14
+ if (typeof navigator !== "undefined" && navigator.userAgent) return `browser-${navigator.userAgent}`;
15
+ return null;
16
+ }
17
+
18
+ //#endregion
19
+ //#region src/resources/index.ts
20
+ var BaseResource = class {
21
+ constructor(baseHttpUrl, projectApiKey) {
22
+ this.baseHttpUrl = baseHttpUrl;
23
+ this.projectApiKey = projectApiKey;
24
+ }
25
+ headers() {
26
+ return {
27
+ Authorization: `Bearer ${this.projectApiKey}`,
28
+ "Content-Type": "application/json",
29
+ Accept: "application/json"
30
+ };
31
+ }
32
+ async handleError(response) {
33
+ const errorMsg = await response.text();
34
+ throw new Error(`${response.status} ${errorMsg}`);
35
+ }
36
+ };
37
+
38
+ //#endregion
39
+ //#region src/resources/browser-events.ts
40
+ var BrowserEventsResource = class extends BaseResource {
41
+ constructor(baseHttpUrl, projectApiKey) {
42
+ super(baseHttpUrl, projectApiKey);
43
+ }
44
+ async send({ sessionId, traceId, events }) {
45
+ const payload = {
46
+ sessionId,
47
+ traceId,
48
+ events,
49
+ source: getLangVersion() ?? "javascript",
50
+ sdkVersion: version
51
+ };
52
+ const jsonString = JSON.stringify(payload);
53
+ const compressedStream = new Blob([jsonString], { type: "application/json" }).stream().pipeThrough(new CompressionStream("gzip"));
54
+ const compressedData = await new Response(compressedStream).arrayBuffer();
55
+ const response = await fetch(this.baseHttpUrl + "/v1/browser-sessions/events", {
56
+ method: "POST",
57
+ headers: {
58
+ ...this.headers(),
59
+ "Content-Encoding": "gzip"
60
+ },
61
+ body: compressedData
62
+ });
63
+ if (!response.ok) await this.handleError(response);
64
+ }
65
+ };
66
+
67
+ //#endregion
68
+ //#region src/utils.ts
69
+ function initializeLogger(options) {
70
+ const colorize = options?.colorize ?? true;
71
+ const level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? "info";
72
+ return pino({ level }, PinoPretty({
73
+ colorize,
74
+ minimumLevel: level
75
+ }));
76
+ }
77
+ const logger$2 = initializeLogger();
78
+ const isStringUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
79
+ const newUUID = () => {
80
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
81
+ else return v4();
82
+ };
83
+ const otelSpanIdToUUID = (spanId) => {
84
+ let id = spanId.toLowerCase();
85
+ if (id.startsWith("0x")) id = id.slice(2);
86
+ if (id.length !== 16) logger$2.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);
87
+ if (!/^[0-9a-f]+$/.test(id)) {
88
+ logger$2.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);
89
+ return newUUID();
90
+ }
91
+ return id.padStart(32, "0").replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, "$1-$2-$3-$4-$5");
92
+ };
93
+ const otelTraceIdToUUID = (traceId) => {
94
+ let id = traceId.toLowerCase();
95
+ if (id.startsWith("0x")) id = id.slice(2);
96
+ if (id.length !== 32) logger$2.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);
97
+ if (!/^[0-9a-f]+$/.test(id)) {
98
+ logger$2.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);
99
+ return newUUID();
100
+ }
101
+ return id.replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, "$1-$2-$3-$4-$5");
102
+ };
103
+ const slicePayload = (value, length) => {
104
+ if (value === null || value === void 0) return value;
105
+ const str = JSON.stringify(value);
106
+ if (str.length <= length) return value;
107
+ return str.slice(0, length) + "...";
108
+ };
109
+ const loadEnv = (options) => {
110
+ const nodeEnv = process.env.NODE_ENV || "development";
111
+ const envDir = process.cwd();
112
+ const envFiles = [
113
+ ".env",
114
+ ".env.local",
115
+ `.env.${nodeEnv}`,
116
+ `.env.${nodeEnv}.local`
117
+ ];
118
+ const logLevel = process.env.LMNR_LOG_LEVEL ?? "info";
119
+ const verbose = ["debug", "trace"].includes(logLevel.trim().toLowerCase());
120
+ const quiet = options?.quiet ?? !verbose;
121
+ config({
122
+ path: options?.paths ?? envFiles.map((envFile) => path.resolve(envDir, envFile)),
123
+ quiet
124
+ });
125
+ };
126
+
127
+ //#endregion
128
+ //#region src/resources/datasets.ts
129
+ const logger$1 = initializeLogger();
130
+ const DEFAULT_DATASET_PULL_LIMIT = 100;
131
+ const DEFAULT_DATASET_PUSH_BATCH_SIZE = 100;
132
+ var DatasetsResource = class extends BaseResource {
133
+ constructor(baseHttpUrl, projectApiKey) {
134
+ super(baseHttpUrl, projectApiKey);
135
+ }
136
+ /**
137
+ * List all datasets.
138
+ *
139
+ * @returns {Promise<Dataset[]>} Array of datasets
140
+ */
141
+ async listDatasets() {
142
+ const response = await fetch(this.baseHttpUrl + "/v1/datasets", {
143
+ method: "GET",
144
+ headers: this.headers()
145
+ });
146
+ if (!response.ok) await this.handleError(response);
147
+ return response.json();
148
+ }
149
+ /**
150
+ * Get a dataset by name.
151
+ *
152
+ * @param {string} name - Name of the dataset
153
+ * @returns {Promise<Dataset[]>} Array of datasets with matching name
154
+ */
155
+ async getDatasetByName(name) {
156
+ const params = new URLSearchParams({ name });
157
+ const response = await fetch(this.baseHttpUrl + `/v1/datasets?${params.toString()}`, {
158
+ method: "GET",
159
+ headers: this.headers()
160
+ });
161
+ if (!response.ok) await this.handleError(response);
162
+ return response.json();
163
+ }
164
+ /**
165
+ * Push datapoints to a dataset.
166
+ *
167
+ * @param {Object} options - Push options
168
+ * @param {Datapoint<D, T>[]} options.points - Datapoints to push
169
+ * @param {string} [options.name] - Name of the dataset (either name or id must be provided)
170
+ * @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)
171
+ * @param {number} [options.batchSize] - Batch size for pushing (default: 100)
172
+ * @param {boolean} [options.createDataset] - Whether to create the dataset if it doesn't exist
173
+ * @returns {Promise<PushDatapointsResponse | undefined>}
174
+ */
175
+ async push({ points, name, id, batchSize = DEFAULT_DATASET_PUSH_BATCH_SIZE, createDataset = false }) {
176
+ if (!name && !id) throw new Error("Either name or id must be provided");
177
+ if (name && id) throw new Error("Only one of name or id must be provided");
178
+ if (createDataset && !name) throw new Error("Name must be provided when creating a new dataset");
179
+ const identifier = name ? { name } : { datasetId: id };
180
+ const totalBatches = Math.ceil(points.length / batchSize);
181
+ let response;
182
+ for (let i = 0; i < points.length; i += batchSize) {
183
+ const batchNum = Math.floor(i / batchSize) + 1;
184
+ logger$1.debug(`Pushing batch ${batchNum} of ${totalBatches}`);
185
+ const batch = points.slice(i, i + batchSize);
186
+ const fetchResponse = await fetch(this.baseHttpUrl + "/v1/datasets/datapoints", {
187
+ method: "POST",
188
+ headers: this.headers(),
189
+ body: JSON.stringify({
190
+ ...identifier,
191
+ datapoints: batch.map((point) => ({
192
+ data: point.data,
193
+ target: point.target ?? {},
194
+ metadata: point.metadata ?? {}
195
+ })),
196
+ createDataset
197
+ })
198
+ });
199
+ if (fetchResponse.status !== 200 && fetchResponse.status !== 201) await this.handleError(fetchResponse);
200
+ response = await fetchResponse.json();
201
+ }
202
+ return response;
203
+ }
204
+ /**
205
+ * Pull datapoints from a dataset.
206
+ *
207
+ * @param {Object} options - Pull options
208
+ * @param {string} [options.name] - Name of the dataset (either name or id must be provided)
209
+ * @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)
210
+ * @param {number} [options.limit] - Maximum number of datapoints to return (default: 100)
211
+ * @param {number} [options.offset] - Offset for pagination (default: 0)
212
+ * @returns {Promise<GetDatapointsResponse<D, T>>}
213
+ */
214
+ async pull({ name, id, limit = DEFAULT_DATASET_PULL_LIMIT, offset = 0 }) {
215
+ if (!name && !id) throw new Error("Either name or id must be provided");
216
+ if (name && id) throw new Error("Only one of name or id must be provided");
217
+ const paramsObj = {
218
+ offset: offset.toString(),
219
+ limit: limit.toString()
220
+ };
221
+ if (name) paramsObj.name = name;
222
+ else paramsObj.datasetId = id;
223
+ const params = new URLSearchParams(paramsObj);
224
+ const response = await fetch(this.baseHttpUrl + `/v1/datasets/datapoints?${params.toString()}`, {
225
+ method: "GET",
226
+ headers: this.headers()
227
+ });
228
+ if (!response.ok) await this.handleError(response);
229
+ return response.json();
230
+ }
231
+ };
232
+
233
+ //#endregion
234
+ //#region src/resources/evals.ts
235
+ const logger = initializeLogger();
236
+ const INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH = 16e6;
237
+ var EvalsResource = class extends BaseResource {
238
+ constructor(baseHttpUrl, projectApiKey) {
239
+ super(baseHttpUrl, projectApiKey);
240
+ }
241
+ /**
242
+ * Initialize an evaluation.
243
+ *
244
+ * @param {string} name - Name of the evaluation
245
+ * @param {string} groupName - Group name of the evaluation
246
+ * @param {Record<string, any>} metadata - Optional metadata
247
+ * @returns {Promise<InitEvaluationResponse>} Response from the evaluation initialization
248
+ */
249
+ async init(name, groupName, metadata) {
250
+ const response = await fetch(this.baseHttpUrl + "/v1/evals", {
251
+ method: "POST",
252
+ headers: this.headers(),
253
+ body: JSON.stringify({
254
+ name: name ?? null,
255
+ groupName: groupName ?? null,
256
+ metadata: metadata ?? null
257
+ })
258
+ });
259
+ if (!response.ok) await this.handleError(response);
260
+ return response.json();
261
+ }
262
+ /**
263
+ * Create a new evaluation and return its ID.
264
+ *
265
+ * @param {string} [name] - Optional name of the evaluation
266
+ * @param {string} [groupName] - An identifier to group evaluations
267
+ * @param {Record<string, any>} [metadata] - Optional metadata
268
+ * @returns {Promise<StringUUID>} The evaluation ID
269
+ */
270
+ async create(args) {
271
+ return (await this.init(args?.name, args?.groupName, args?.metadata)).id;
272
+ }
273
+ /**
274
+ * Create a new evaluation and return its ID.
275
+ * @deprecated use `create` instead.
276
+ */
277
+ async createEvaluation(name, groupName, metadata) {
278
+ return (await this.init(name, groupName, metadata)).id;
279
+ }
280
+ /**
281
+ * Create a datapoint for an evaluation.
282
+ *
283
+ * @param {Object} options - Create datapoint options
284
+ * @param {string} options.evalId - The evaluation ID
285
+ * @param {D} options.data - The input data for the executor
286
+ * @param {T} [options.target] - The target/expected output for evaluators
287
+ * @param {Record<string, any>} [options.metadata] - Optional metadata
288
+ * @param {number} [options.index] - Optional index of the datapoint
289
+ * @param {string} [options.traceId] - Optional trace ID
290
+ * @returns {Promise<StringUUID>} The datapoint ID
291
+ */
292
+ async createDatapoint({ evalId, data, target, metadata, index, traceId }) {
293
+ const datapointId = newUUID();
294
+ const partialDatapoint = {
295
+ id: datapointId,
296
+ data,
297
+ target,
298
+ index: index ?? 0,
299
+ traceId: traceId ?? newUUID(),
300
+ executorSpanId: newUUID(),
301
+ metadata
302
+ };
303
+ await this.saveDatapoints({
304
+ evalId,
305
+ datapoints: [partialDatapoint]
306
+ });
307
+ return datapointId;
308
+ }
309
+ /**
310
+ * Update a datapoint with evaluation results.
311
+ *
312
+ * @param {Object} options - Update datapoint options
313
+ * @param {string} options.evalId - The evaluation ID
314
+ * @param {string} options.datapointId - The datapoint ID
315
+ * @param {Record<string, number>} options.scores - The scores
316
+ * @param {O} [options.executorOutput] - The executor output
317
+ * @returns {Promise<void>}
318
+ */
319
+ async updateDatapoint({ evalId, datapointId, scores, executorOutput }) {
320
+ const response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints/${datapointId}`, {
321
+ method: "POST",
322
+ headers: this.headers(),
323
+ body: JSON.stringify({
324
+ executorOutput,
325
+ scores
326
+ })
327
+ });
328
+ if (!response.ok) await this.handleError(response);
329
+ }
330
+ /**
331
+ * Save evaluation datapoints.
332
+ *
333
+ * @param {Object} options - Save datapoints options
334
+ * @param {string} options.evalId - ID of the evaluation
335
+ * @param {EvaluationDatapoint<D, T, O>[]} options.datapoints - Datapoint to add
336
+ * @param {string} [options.groupName] - Group name of the evaluation
337
+ * @returns {Promise<void>} Response from the datapoint addition
338
+ */
339
+ async saveDatapoints({ evalId, datapoints, groupName }) {
340
+ const response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {
341
+ method: "POST",
342
+ headers: this.headers(),
343
+ body: JSON.stringify({
344
+ points: datapoints.map((d) => ({
345
+ ...d,
346
+ data: slicePayload(d.data, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),
347
+ target: slicePayload(d.target, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),
348
+ executorOutput: slicePayload(d.executorOutput, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH)
349
+ })),
350
+ groupName: groupName ?? null
351
+ })
352
+ });
353
+ if (response.status === 413) return await this.retrySaveDatapoints({
354
+ evalId,
355
+ datapoints,
356
+ groupName
357
+ });
358
+ if (!response.ok) await this.handleError(response);
359
+ }
360
+ /**
361
+ * Get evaluation datapoints.
362
+ *
363
+ * @deprecated Use `client.datasets.pull()` instead.
364
+ * @param {Object} options - Get datapoints options
365
+ * @param {string} options.datasetName - Name of the dataset
366
+ * @param {number} options.offset - Offset at which to start the query
367
+ * @param {number} options.limit - Maximum number of datapoints to return
368
+ * @returns {Promise<GetDatapointsResponse>} Response from the datapoint retrieval
369
+ */
370
+ async getDatapoints({ datasetName, offset, limit }) {
371
+ logger.warn("evals.getDatapoints() is deprecated. Use client.datasets.pull() instead.");
372
+ const params = new URLSearchParams({
373
+ name: datasetName,
374
+ offset: offset.toString(),
375
+ limit: limit.toString()
376
+ });
377
+ const response = await fetch(this.baseHttpUrl + `/v1/datasets/datapoints?${params.toString()}`, {
378
+ method: "GET",
379
+ headers: this.headers()
380
+ });
381
+ if (!response.ok) await this.handleError(response);
382
+ return await response.json();
383
+ }
384
+ async retrySaveDatapoints({ evalId, datapoints, groupName, maxRetries = 25, initialLength = INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH }) {
385
+ let length = initialLength;
386
+ let lastResponse = null;
387
+ for (let i = 0; i < maxRetries; i++) {
388
+ logger.debug(`Retrying save datapoints... ${i + 1} of ${maxRetries}, length: ${length}`);
389
+ const response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {
390
+ method: "POST",
391
+ headers: this.headers(),
392
+ body: JSON.stringify({
393
+ points: datapoints.map((d) => ({
394
+ ...d,
395
+ data: slicePayload(d.data, length),
396
+ target: slicePayload(d.target, length),
397
+ executorOutput: slicePayload(d.executorOutput, length)
398
+ })),
399
+ groupName: groupName ?? null
400
+ })
401
+ });
402
+ lastResponse = response;
403
+ length = Math.floor(length / 2);
404
+ if (response.status !== 413) break;
405
+ }
406
+ if (lastResponse && !lastResponse.ok) await this.handleError(lastResponse);
407
+ }
408
+ };
409
+
410
+ //#endregion
411
+ //#region src/resources/evaluators.ts
412
+ var EvaluatorScoreSourceType = /* @__PURE__ */ function(EvaluatorScoreSourceType$1) {
413
+ EvaluatorScoreSourceType$1["Evaluator"] = "Evaluator";
414
+ EvaluatorScoreSourceType$1["Code"] = "Code";
415
+ return EvaluatorScoreSourceType$1;
416
+ }(EvaluatorScoreSourceType || {});
417
+ /**
418
+ * Resource for creating evaluator scores
419
+ */
420
+ var EvaluatorsResource = class extends BaseResource {
421
+ constructor(baseHttpUrl, projectApiKey) {
422
+ super(baseHttpUrl, projectApiKey);
423
+ }
424
+ /**
425
+ * Create a score for a span or trace
426
+ *
427
+ * @param {ScoreOptions} options - Score creation options
428
+ * @param {string} options.name - Name of the score
429
+ * @param {string} [options.traceId] - The trace ID to score (will be attached to top-level span)
430
+ * @param {string} [options.spanId] - The span ID to score
431
+ * @param {Record<string, any>} [options.metadata] - Additional metadata
432
+ * @param {number} options.score - The score value (float)
433
+ * @returns {Promise<void>}
434
+ *
435
+ * @example
436
+ * // Score by trace ID (will attach to root span)
437
+ * await evaluators.score({
438
+ * name: "quality",
439
+ * traceId: "trace-id-here",
440
+ * score: 0.95,
441
+ * metadata: { model: "gpt-4" }
442
+ * });
443
+ *
444
+ * @example
445
+ * // Score by span ID
446
+ * await evaluators.score({
447
+ * name: "relevance",
448
+ * spanId: "span-id-here",
449
+ * score: 0.87
450
+ * });
451
+ */
452
+ async score(options) {
453
+ const { name, metadata, score } = options;
454
+ let payload;
455
+ if ("traceId" in options && options.traceId) {
456
+ const formattedTraceId = isStringUUID(options.traceId) ? options.traceId : otelTraceIdToUUID(options.traceId);
457
+ payload = {
458
+ name,
459
+ metadata,
460
+ score,
461
+ source: EvaluatorScoreSourceType.Code,
462
+ traceId: formattedTraceId
463
+ };
464
+ } else if ("spanId" in options && options.spanId) {
465
+ const formattedSpanId = isStringUUID(options.spanId) ? options.spanId : otelSpanIdToUUID(options.spanId);
466
+ payload = {
467
+ name,
468
+ metadata,
469
+ score,
470
+ source: EvaluatorScoreSourceType.Code,
471
+ spanId: formattedSpanId
472
+ };
473
+ } else throw new Error("Either 'traceId' or 'spanId' must be provided.");
474
+ const response = await fetch(this.baseHttpUrl + "/v1/evaluators/score", {
475
+ method: "POST",
476
+ headers: this.headers(),
477
+ body: JSON.stringify(payload)
478
+ });
479
+ if (!response.ok) await this.handleError(response);
480
+ }
481
+ };
482
+
483
+ //#endregion
484
+ //#region src/resources/rollout-sessions.ts
485
+ var RolloutSessionsResource = class extends BaseResource {
486
+ constructor(baseHttpUrl, projectApiKey) {
487
+ super(baseHttpUrl, projectApiKey);
488
+ }
489
+ /**
490
+ * Connects to the SSE stream for rollout debugging sessions
491
+ * Returns the Response object for streaming SSE events
492
+ */
493
+ async connect({ sessionId, name, params, signal }) {
494
+ const response = await fetch(`${this.baseHttpUrl}/v1/rollouts/${sessionId}`, {
495
+ method: "POST",
496
+ headers: {
497
+ ...this.headers(),
498
+ "Accept": "text/event-stream"
499
+ },
500
+ body: JSON.stringify({
501
+ name,
502
+ params
503
+ }),
504
+ signal
505
+ });
506
+ if (!response.ok) throw new Error(`SSE connection failed: ${response.status} ${response.statusText}`);
507
+ if (!response.body) throw new Error("No response body");
508
+ return response;
509
+ }
510
+ async delete({ sessionId }) {
511
+ const response = await fetch(`${this.baseHttpUrl}/v1/rollouts/${sessionId}`, {
512
+ method: "DELETE",
513
+ headers: this.headers()
514
+ });
515
+ if (!response.ok) await this.handleError(response);
516
+ }
517
+ async setStatus({ sessionId, status }) {
518
+ const response = await fetch(`${this.baseHttpUrl}/v1/rollouts/${sessionId}/status`, {
519
+ method: "PATCH",
520
+ headers: this.headers(),
521
+ body: JSON.stringify({ status })
522
+ });
523
+ if (!response.ok) await this.handleError(response);
524
+ }
525
+ async sendSpanUpdate({ sessionId, span }) {
526
+ const response = await fetch(`${this.baseHttpUrl}/v1/rollouts/${sessionId}/update`, {
527
+ method: "PATCH",
528
+ headers: this.headers(),
529
+ body: JSON.stringify({
530
+ type: "spanStart",
531
+ spanId: otelSpanIdToUUID(span.spanId),
532
+ traceId: otelTraceIdToUUID(span.traceId),
533
+ parentSpanId: span.parentSpanId ? otelSpanIdToUUID(span.parentSpanId) : void 0,
534
+ attributes: span.attributes,
535
+ startTime: span.startTime,
536
+ name: span.name,
537
+ spanType: span.spanType
538
+ })
539
+ });
540
+ if (!response.ok) await this.handleError(response);
541
+ }
542
+ };
543
+
544
+ //#endregion
545
+ //#region src/resources/sql.ts
546
+ var SqlResource = class extends BaseResource {
547
+ constructor(baseHttpUrl, projectApiKey) {
548
+ super(baseHttpUrl, projectApiKey);
549
+ }
550
+ async query(sql, parameters = {}) {
551
+ const response = await fetch(`${this.baseHttpUrl}/v1/sql/query`, {
552
+ method: "POST",
553
+ headers: { ...this.headers() },
554
+ body: JSON.stringify({
555
+ query: sql,
556
+ parameters
557
+ })
558
+ });
559
+ if (!response.ok) await this.handleError(response);
560
+ return (await response.json()).data;
561
+ }
562
+ };
563
+
564
+ //#endregion
565
+ //#region src/resources/tags.ts
566
+ /** Resource for tagging traces. */
567
+ var TagsResource = class extends BaseResource {
568
+ /** Resource for tagging traces. */
569
+ constructor(baseHttpUrl, projectApiKey) {
570
+ super(baseHttpUrl, projectApiKey);
571
+ }
572
+ /**
573
+ * Tag a trace with a list of tags. Note that the trace must be ended before
574
+ * tagging it. You may want to call `await Laminar.flush()` after the trace
575
+ * that you want to tag.
576
+ *
577
+ * @param {string | StringUUID} trace_id - The trace id to tag.
578
+ * @param {string[] | string} tags - The tag or list of tags to add to the trace.
579
+ * @returns {Promise<any>} The response from the server.
580
+ * @example
581
+ * ```javascript
582
+ * import { Laminar, observe, LaminarClient } from "@lmnr-ai/lmnr";
583
+ * Laminar.initialize();
584
+ * const client = new LaminarClient();
585
+ * let traceId: StringUUID | null = null;
586
+ * // Make sure this is called outside of traced context.
587
+ * await observe(
588
+ * {
589
+ * name: "my-trace",
590
+ * },
591
+ * async () => {
592
+ * traceId = await Laminar.getTraceId();
593
+ * await foo();
594
+ * },
595
+ * );
596
+ *
597
+ * // or make sure the trace is ended by this point.
598
+ * await Laminar.flush();
599
+ * if (traceId) {
600
+ * await client.tags.tag(traceId, ["tag1", "tag2"]);
601
+ * }
602
+ * ```
603
+ */
604
+ async tag(trace_id, tags) {
605
+ const traceTags = Array.isArray(tags) ? tags : [tags];
606
+ const formattedTraceId = isStringUUID(trace_id) ? trace_id : otelTraceIdToUUID(trace_id);
607
+ const url = this.baseHttpUrl + "/v1/tag";
608
+ const payload = {
609
+ "traceId": formattedTraceId,
610
+ "names": traceTags
611
+ };
612
+ const response = await fetch(url, {
613
+ method: "POST",
614
+ headers: this.headers(),
615
+ body: JSON.stringify(payload)
616
+ });
617
+ if (!response.ok) await this.handleError(response);
618
+ return response.json();
619
+ }
620
+ };
621
+
622
+ //#endregion
623
+ //#region src/index.ts
624
+ var LaminarClient = class {
625
+ constructor({ baseUrl, projectApiKey, port } = {}) {
626
+ loadEnv();
627
+ this.projectApiKey = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;
628
+ const httpPort = port ?? (baseUrl?.match(/:\d{1,5}$/g) ? parseInt(baseUrl.match(/:\d{1,5}$/g)[0].slice(1)) : 443);
629
+ this.baseUrl = `${(baseUrl ?? process.env.LMNR_BASE_URL)?.replace(/\/$/, "").replace(/:\d{1,5}$/g, "") ?? "https://api.lmnr.ai"}:${httpPort}`;
630
+ this._browserEvents = new BrowserEventsResource(this.baseUrl, this.projectApiKey);
631
+ this._datasets = new DatasetsResource(this.baseUrl, this.projectApiKey);
632
+ this._evals = new EvalsResource(this.baseUrl, this.projectApiKey);
633
+ this._evaluators = new EvaluatorsResource(this.baseUrl, this.projectApiKey);
634
+ this._rolloutSessions = new RolloutSessionsResource(this.baseUrl, this.projectApiKey);
635
+ this._sql = new SqlResource(this.baseUrl, this.projectApiKey);
636
+ this._tags = new TagsResource(this.baseUrl, this.projectApiKey);
637
+ }
638
+ get browserEvents() {
639
+ return this._browserEvents;
640
+ }
641
+ get datasets() {
642
+ return this._datasets;
643
+ }
644
+ get evals() {
645
+ return this._evals;
646
+ }
647
+ get evaluators() {
648
+ return this._evaluators;
649
+ }
650
+ get rolloutSessions() {
651
+ return this._rolloutSessions;
652
+ }
653
+ get sql() {
654
+ return this._sql;
655
+ }
656
+ get tags() {
657
+ return this._tags;
658
+ }
659
+ };
660
+
661
+ //#endregion
662
+ export { LaminarClient };
663
+ //# sourceMappingURL=index.mjs.map