netra-sdk 1.12.2 → 1.13.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/README.md +1 -9
- package/dist/index.cjs +1024 -379
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1025 -380
- package/dist/index.js.map +1 -1
- package/package.json +11 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createContextKey, propagation, trace, context,
|
|
1
|
+
import { createContextKey, SpanKind, propagation, trace, context, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
|
|
2
2
|
import { createRequire } from 'module';
|
|
3
3
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
4
4
|
import { jsonrepair } from 'jsonrepair';
|
|
@@ -569,8 +569,8 @@ var Usage = class {
|
|
|
569
569
|
if (!page) {
|
|
570
570
|
break;
|
|
571
571
|
}
|
|
572
|
-
for (const
|
|
573
|
-
yield
|
|
572
|
+
for (const trace25 of page.traces) {
|
|
573
|
+
yield trace25;
|
|
574
574
|
}
|
|
575
575
|
if (!page.hasNextPage || !page.nextCursor) {
|
|
576
576
|
break;
|
|
@@ -683,7 +683,7 @@ var Usage = class {
|
|
|
683
683
|
};
|
|
684
684
|
|
|
685
685
|
// src/version.ts
|
|
686
|
-
var SDK_VERSION = "1.
|
|
686
|
+
var SDK_VERSION = "1.13.0";
|
|
687
687
|
|
|
688
688
|
// src/config.ts
|
|
689
689
|
var NETRA_API_KEY_HEADER = "x-api-key";
|
|
@@ -697,6 +697,7 @@ var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
|
|
|
697
697
|
NetraInstruments2["VERTEX_AI"] = "vertexai";
|
|
698
698
|
NetraInstruments2["TOGETHER"] = "together";
|
|
699
699
|
NetraInstruments2["ANTHROPIC"] = "anthropic";
|
|
700
|
+
NetraInstruments2["TYPESAFE"] = "typesafe";
|
|
700
701
|
NetraInstruments2["LANGCHAIN"] = "langchain";
|
|
701
702
|
NetraInstruments2["LANGGRAPH"] = "langgraph";
|
|
702
703
|
NetraInstruments2["LLAMA_INDEX"] = "llama_index";
|
|
@@ -720,6 +721,7 @@ var DEFAULT_INSTRUMENTS_FOR_ROOT = /* @__PURE__ */ new Set([
|
|
|
720
721
|
"google_generative_ai" /* GOOGLE_GENERATIVE_AI */,
|
|
721
722
|
"vertexai" /* VERTEX_AI */,
|
|
722
723
|
"together" /* TOGETHER */,
|
|
724
|
+
"typesafe" /* TYPESAFE */,
|
|
723
725
|
// AI frameworks
|
|
724
726
|
"langchain" /* LANGCHAIN */,
|
|
725
727
|
"langgraph" /* LANGGRAPH */,
|
|
@@ -4206,6 +4208,12 @@ function isAsyncIterable(value) {
|
|
|
4206
4208
|
function isPromise(value) {
|
|
4207
4209
|
return value != null && typeof value.then === "function";
|
|
4208
4210
|
}
|
|
4211
|
+
function isAPIPromise(value) {
|
|
4212
|
+
return isPromise(value) && typeof value._thenUnwrap === "function" && isPromise(value.responsePromise);
|
|
4213
|
+
}
|
|
4214
|
+
function isMappableAPIPromise(value) {
|
|
4215
|
+
return isPromise(value) && typeof value.asResponse === "function" && typeof value.map === "function";
|
|
4216
|
+
}
|
|
4209
4217
|
var ITERATOR_METHODS = /* @__PURE__ */ new Set(["next", "return", "throw"]);
|
|
4210
4218
|
function wrapAsyncIterable(source, callbacks) {
|
|
4211
4219
|
function createWrappedIterator() {
|
|
@@ -4283,7 +4291,7 @@ function wrapAsyncIterable(source, callbacks) {
|
|
|
4283
4291
|
}
|
|
4284
4292
|
let directIterator = null;
|
|
4285
4293
|
return new Proxy(source, {
|
|
4286
|
-
get(target, prop) {
|
|
4294
|
+
get(target, prop, receiver) {
|
|
4287
4295
|
if (prop === Symbol.asyncIterator) {
|
|
4288
4296
|
return () => createWrappedIterator();
|
|
4289
4297
|
}
|
|
@@ -4292,6 +4300,9 @@ function wrapAsyncIterable(source, callbacks) {
|
|
|
4292
4300
|
return directIterator[prop].bind(directIterator);
|
|
4293
4301
|
}
|
|
4294
4302
|
const value = target[prop];
|
|
4303
|
+
if (prop === "toReadableStream" && typeof value === "function") {
|
|
4304
|
+
return value.bind(receiver);
|
|
4305
|
+
}
|
|
4295
4306
|
if (typeof value === "function") return value.bind(target);
|
|
4296
4307
|
return value;
|
|
4297
4308
|
}
|
|
@@ -4308,25 +4319,80 @@ function wrapPromise(promise, callbacks, options) {
|
|
|
4308
4319
|
NetraLogger.error("netra: finalize callback error", e);
|
|
4309
4320
|
}
|
|
4310
4321
|
}
|
|
4322
|
+
function safeOnSuccess(value) {
|
|
4323
|
+
try {
|
|
4324
|
+
callbacks.onSuccess?.(value);
|
|
4325
|
+
} catch (e) {
|
|
4326
|
+
NetraLogger.error("netra: onSuccess callback error", e);
|
|
4327
|
+
}
|
|
4328
|
+
}
|
|
4329
|
+
function safeOnError(error) {
|
|
4330
|
+
try {
|
|
4331
|
+
callbacks.onError(error);
|
|
4332
|
+
} catch {
|
|
4333
|
+
NetraLogger.error("netra: onError callback error", error);
|
|
4334
|
+
}
|
|
4335
|
+
}
|
|
4336
|
+
function onDerivedValue(value) {
|
|
4337
|
+
if (isAsyncIterable(value)) {
|
|
4338
|
+
return wrapAsyncIterable(value, { ...callbacks, finalize: safeFinalize });
|
|
4339
|
+
}
|
|
4340
|
+
if (!finalized) {
|
|
4341
|
+
safeOnSuccess(value);
|
|
4342
|
+
safeFinalize("ok");
|
|
4343
|
+
}
|
|
4344
|
+
return value;
|
|
4345
|
+
}
|
|
4346
|
+
function onResponseError(error) {
|
|
4347
|
+
safeOnError(error);
|
|
4348
|
+
safeFinalize("error");
|
|
4349
|
+
}
|
|
4350
|
+
if (options?.deriveAPIPromise && isAPIPromise(promise)) {
|
|
4351
|
+
promise.responsePromise.then(
|
|
4352
|
+
(props) => observeJSONBody(props?.response),
|
|
4353
|
+
onResponseError
|
|
4354
|
+
);
|
|
4355
|
+
return promise._thenUnwrap(onDerivedValue);
|
|
4356
|
+
}
|
|
4357
|
+
if (options?.deriveAPIPromise && isMappableAPIPromise(promise)) {
|
|
4358
|
+
promise.asResponse().then(observeJSONBody, onResponseError);
|
|
4359
|
+
return promise.map(onDerivedValue);
|
|
4360
|
+
}
|
|
4361
|
+
function observeJSONBody(response) {
|
|
4362
|
+
try {
|
|
4363
|
+
const contentType = String(response?.headers?.get?.("content-type") ?? "");
|
|
4364
|
+
if (typeof response?.clone !== "function" || !contentType.includes("json")) {
|
|
4365
|
+
return;
|
|
4366
|
+
}
|
|
4367
|
+
response.clone().json().then(
|
|
4368
|
+
(body) => {
|
|
4369
|
+
if (finalized) return;
|
|
4370
|
+
safeOnSuccess(body);
|
|
4371
|
+
safeFinalize("ok");
|
|
4372
|
+
},
|
|
4373
|
+
// A malformed or truncated body: the caller's own read of the same
|
|
4374
|
+
// bytes fails too, and _thenUnwrap never runs, so end the span here.
|
|
4375
|
+
(error) => {
|
|
4376
|
+
if (finalized) return;
|
|
4377
|
+
safeOnError(error);
|
|
4378
|
+
safeFinalize("error");
|
|
4379
|
+
}
|
|
4380
|
+
);
|
|
4381
|
+
} catch (e) {
|
|
4382
|
+
NetraLogger.debug("netra: could not read a copy of the response body", e);
|
|
4383
|
+
}
|
|
4384
|
+
}
|
|
4311
4385
|
const instrumentedPromise = (async () => {
|
|
4312
4386
|
try {
|
|
4313
4387
|
const value = await promise;
|
|
4314
4388
|
if (isAsyncIterable(value)) {
|
|
4315
4389
|
return wrapAsyncIterable(value, callbacks);
|
|
4316
4390
|
}
|
|
4317
|
-
|
|
4318
|
-
callbacks.onSuccess?.(value);
|
|
4319
|
-
} catch (e) {
|
|
4320
|
-
NetraLogger.error("netra: onSuccess callback error", e);
|
|
4321
|
-
}
|
|
4391
|
+
safeOnSuccess(value);
|
|
4322
4392
|
safeFinalize("ok");
|
|
4323
4393
|
return value;
|
|
4324
4394
|
} catch (error) {
|
|
4325
|
-
|
|
4326
|
-
callbacks.onError(error);
|
|
4327
|
-
} catch {
|
|
4328
|
-
NetraLogger.error("netra: onError callback error", error);
|
|
4329
|
-
}
|
|
4395
|
+
safeOnError(error);
|
|
4330
4396
|
safeFinalize("error");
|
|
4331
4397
|
throw error;
|
|
4332
4398
|
}
|
|
@@ -4334,6 +4400,8 @@ function wrapPromise(promise, callbacks, options) {
|
|
|
4334
4400
|
if (!options?.preserveOriginal) {
|
|
4335
4401
|
return instrumentedPromise;
|
|
4336
4402
|
}
|
|
4403
|
+
instrumentedPromise.catch(() => {
|
|
4404
|
+
});
|
|
4337
4405
|
const original = options.preserveOriginal;
|
|
4338
4406
|
return new Proxy(instrumentedPromise, {
|
|
4339
4407
|
get(target, prop, receiver) {
|
|
@@ -4804,6 +4872,11 @@ function setEmbeddingResponseMeta(span2, response) {
|
|
|
4804
4872
|
const embedding = firstItem?.embedding;
|
|
4805
4873
|
if (Array.isArray(embedding)) {
|
|
4806
4874
|
span2.setAttribute("llm.response.embedding_dimensions", embedding.length);
|
|
4875
|
+
} else if (typeof embedding === "string") {
|
|
4876
|
+
span2.setAttribute(
|
|
4877
|
+
"llm.response.embedding_dimensions",
|
|
4878
|
+
Buffer.byteLength(embedding, "base64") / 4
|
|
4879
|
+
);
|
|
4807
4880
|
}
|
|
4808
4881
|
}
|
|
4809
4882
|
|
|
@@ -5943,7 +6016,8 @@ var __version__2 = "1.0.0";
|
|
|
5943
6016
|
// src/instrumentation/google-genai/types.ts
|
|
5944
6017
|
var SPAN_NAMES2 = {
|
|
5945
6018
|
CHAT: "google_genai.chat",
|
|
5946
|
-
EMBEDDING: "google_genai.embedding"
|
|
6019
|
+
EMBEDDING: "google_genai.embedding",
|
|
6020
|
+
DECISION: "google_genai.decision"
|
|
5947
6021
|
};
|
|
5948
6022
|
|
|
5949
6023
|
// src/instrumentation/google-genai/utils.ts
|
|
@@ -6173,9 +6247,9 @@ function setEmbeddingMeta(span2, response) {
|
|
|
6173
6247
|
span2.setAttribute("gen_ai.response.embedding_dimensions", values2.length);
|
|
6174
6248
|
const stats = singleEmbed.statistics;
|
|
6175
6249
|
if (stats?.tokenCount !== void 0) {
|
|
6176
|
-
const
|
|
6177
|
-
span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS,
|
|
6178
|
-
span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS,
|
|
6250
|
+
const tokenCount2 = Number(stats.tokenCount);
|
|
6251
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, tokenCount2);
|
|
6252
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, tokenCount2);
|
|
6179
6253
|
}
|
|
6180
6254
|
return;
|
|
6181
6255
|
}
|
|
@@ -6328,6 +6402,357 @@ function buildAccumulatedResponse(accumulated) {
|
|
|
6328
6402
|
return response;
|
|
6329
6403
|
}
|
|
6330
6404
|
|
|
6405
|
+
// src/instrumentation/json-budget.ts
|
|
6406
|
+
var DEFAULT_ATTRIBUTE_MAX_SIZE = 3e4;
|
|
6407
|
+
var JSON_ITEM_SEPARATOR = ",";
|
|
6408
|
+
function attributeMaxSize() {
|
|
6409
|
+
const size = Config.SPAN_ATTRIBUTE_MAX_SIZE;
|
|
6410
|
+
return Number.isFinite(size) && size > 0 ? size : DEFAULT_ATTRIBUTE_MAX_SIZE;
|
|
6411
|
+
}
|
|
6412
|
+
function joinJsonArray(encodedItems) {
|
|
6413
|
+
return "[" + encodedItems.join(JSON_ITEM_SEPARATOR) + "]";
|
|
6414
|
+
}
|
|
6415
|
+
function sliceText(text, maxLen) {
|
|
6416
|
+
if (text.length <= maxLen) return text;
|
|
6417
|
+
let end = Math.max(maxLen, 0);
|
|
6418
|
+
const lastCode = text.charCodeAt(end - 1);
|
|
6419
|
+
if (end > 0 && lastCode >= 55296 && lastCode <= 56319) end -= 1;
|
|
6420
|
+
return text.slice(0, end);
|
|
6421
|
+
}
|
|
6422
|
+
function toJson(value) {
|
|
6423
|
+
try {
|
|
6424
|
+
const json = JSON.stringify(value, (_key, val) => {
|
|
6425
|
+
if (typeof val === "bigint") return val.toString();
|
|
6426
|
+
if (typeof val === "function") return `[Function: ${val.name || "anonymous"}]`;
|
|
6427
|
+
if (typeof val === "symbol") return val.toString();
|
|
6428
|
+
return val;
|
|
6429
|
+
});
|
|
6430
|
+
if (json !== void 0) return json;
|
|
6431
|
+
} catch {
|
|
6432
|
+
}
|
|
6433
|
+
return JSON.stringify(safeStringify(value));
|
|
6434
|
+
}
|
|
6435
|
+
function encodeEntryWithin(entry, maxLen) {
|
|
6436
|
+
let content = entry.content;
|
|
6437
|
+
const overhead = JSON.stringify({ ...entry, content: "" }).length;
|
|
6438
|
+
if (overhead > maxLen) return void 0;
|
|
6439
|
+
const contentBudget = maxLen - overhead;
|
|
6440
|
+
for (; ; ) {
|
|
6441
|
+
const encoded = JSON.stringify({ ...entry, content });
|
|
6442
|
+
const encodedContentLen = encoded.length - overhead;
|
|
6443
|
+
if (encodedContentLen <= contentBudget) return encoded;
|
|
6444
|
+
const keep = Math.floor(content.length * contentBudget / encodedContentLen);
|
|
6445
|
+
content = sliceText(content, Math.min(keep, content.length - 1));
|
|
6446
|
+
}
|
|
6447
|
+
}
|
|
6448
|
+
|
|
6449
|
+
// src/instrumentation/openai/utils.ts
|
|
6450
|
+
var DECISION_REQUEST_TYPE = "decision";
|
|
6451
|
+
var INPUT_ATTRIBUTE = "input";
|
|
6452
|
+
var OUTPUT_ATTRIBUTE = "output";
|
|
6453
|
+
var DECISION_TOOL_CALL_ARGUMENT_KEYS = {
|
|
6454
|
+
function_call: "arguments",
|
|
6455
|
+
custom_tool_call: "input"
|
|
6456
|
+
};
|
|
6457
|
+
var DECISION_TOOL_OUTPUT_TYPES = /* @__PURE__ */ new Set(["function_call_output", "custom_tool_call_output"]);
|
|
6458
|
+
var MAX_DATA_URL_HEADER_LEN = 256;
|
|
6459
|
+
var DECISION_QUESTIONS_ROLE = "user";
|
|
6460
|
+
var DECISION_ANSWERS_ROLE = "assistant";
|
|
6461
|
+
var DECISION_QUESTIONS_MAX_SHARE = 2;
|
|
6462
|
+
function setRequestAttributes4(span2, kwargs, requestType) {
|
|
6463
|
+
if (!span2.isRecording()) return;
|
|
6464
|
+
if (requestType === DECISION_REQUEST_TYPE) {
|
|
6465
|
+
const { input: _input, questions: _questions, ...params } = kwargs;
|
|
6466
|
+
setRequestAttributes(span2, params, requestType, "openai");
|
|
6467
|
+
setDecisionRequestAttributes(span2, kwargs);
|
|
6468
|
+
return;
|
|
6469
|
+
}
|
|
6470
|
+
setRequestAttributes(span2, kwargs, requestType, "openai");
|
|
6471
|
+
if (kwargs.dimensions !== void 0) {
|
|
6472
|
+
span2.setAttribute("gen_ai.request.dimensions", Number(kwargs.dimensions));
|
|
6473
|
+
}
|
|
6474
|
+
}
|
|
6475
|
+
function setResponseAttributes4(span2, response) {
|
|
6476
|
+
if (!span2.isRecording()) return;
|
|
6477
|
+
setResponseAttributes(span2, response);
|
|
6478
|
+
setDecisionAnswerAttributes(span2, response);
|
|
6479
|
+
}
|
|
6480
|
+
function setDecisionRequestAttributes(span2, kwargs) {
|
|
6481
|
+
if (!isTraceContentEnabled()) return;
|
|
6482
|
+
let questionsEntry;
|
|
6483
|
+
try {
|
|
6484
|
+
questionsEntry = decisionQuestionsEntry(kwargs.questions);
|
|
6485
|
+
} catch (error) {
|
|
6486
|
+
NetraLogger.warn("Failed to record OpenAI decision questions:", error);
|
|
6487
|
+
}
|
|
6488
|
+
try {
|
|
6489
|
+
const inputJson = buildDecisionInput(kwargs.input, questionsEntry);
|
|
6490
|
+
if (inputJson !== void 0) span2.setAttribute(INPUT_ATTRIBUTE, inputJson);
|
|
6491
|
+
} catch (error) {
|
|
6492
|
+
NetraLogger.warn("Failed to record OpenAI decision input:", error);
|
|
6493
|
+
}
|
|
6494
|
+
}
|
|
6495
|
+
function buildDecisionInput(input, questionsEntry) {
|
|
6496
|
+
let items = [];
|
|
6497
|
+
if (typeof input === "string") {
|
|
6498
|
+
if (input.length > 0) items = [{ role: "user", content: input }];
|
|
6499
|
+
} else if (Array.isArray(input)) {
|
|
6500
|
+
items = input;
|
|
6501
|
+
}
|
|
6502
|
+
const encodedEntries = [];
|
|
6503
|
+
let remaining = attributeMaxSize() - "[]".length;
|
|
6504
|
+
if (questionsEntry) remaining -= questionsEntry.length + JSON_ITEM_SEPARATOR.length;
|
|
6505
|
+
for (const item of items) {
|
|
6506
|
+
const budget = remaining - (encodedEntries.length > 0 ? JSON_ITEM_SEPARATOR.length : 0);
|
|
6507
|
+
if (budget <= 0) break;
|
|
6508
|
+
if (!isDict(item)) continue;
|
|
6509
|
+
const entry = decisionInputEntry(item, budget);
|
|
6510
|
+
if (!entry) continue;
|
|
6511
|
+
const encoded = encodeEntryWithin(entry, budget);
|
|
6512
|
+
if (encoded === void 0) break;
|
|
6513
|
+
encodedEntries.push(encoded);
|
|
6514
|
+
remaining = budget - encoded.length;
|
|
6515
|
+
}
|
|
6516
|
+
if (questionsEntry) encodedEntries.push(questionsEntry);
|
|
6517
|
+
return encodedEntries.length > 0 ? joinJsonArray(encodedEntries) : void 0;
|
|
6518
|
+
}
|
|
6519
|
+
function decisionInputEntry(item, maxContentLen) {
|
|
6520
|
+
const itemType = typeof item.type === "string" && item.type ? item.type : "message";
|
|
6521
|
+
let entry;
|
|
6522
|
+
if (itemType in DECISION_TOOL_CALL_ARGUMENT_KEYS) {
|
|
6523
|
+
let args = item[DECISION_TOOL_CALL_ARGUMENT_KEYS[itemType]] ?? "";
|
|
6524
|
+
if (typeof args === "string") args = sliceText(args, maxContentLen);
|
|
6525
|
+
const call = toJson({ name: item.name ?? "", arguments: args });
|
|
6526
|
+
entry = { role: "assistant", content: sliceText(call, maxContentLen) };
|
|
6527
|
+
} else if (DECISION_TOOL_OUTPUT_TYPES.has(itemType)) {
|
|
6528
|
+
if (!item.output) return void 0;
|
|
6529
|
+
entry = { role: "tool", content: asPromptContent(item.output, maxContentLen) };
|
|
6530
|
+
} else {
|
|
6531
|
+
if (!item.content) return void 0;
|
|
6532
|
+
entry = {
|
|
6533
|
+
role: typeof item.role === "string" && item.role ? item.role : "user",
|
|
6534
|
+
content: asPromptContent(item.content, maxContentLen)
|
|
6535
|
+
};
|
|
6536
|
+
}
|
|
6537
|
+
if (itemType !== "message" && typeof item.call_id === "string" && item.call_id) {
|
|
6538
|
+
entry.tool_call_id = item.call_id;
|
|
6539
|
+
}
|
|
6540
|
+
return entry;
|
|
6541
|
+
}
|
|
6542
|
+
function asPromptContent(content, maxLen) {
|
|
6543
|
+
const elided = withoutInlineData(content, new CharBudget(maxLen));
|
|
6544
|
+
const rendered = typeof elided === "string" ? elided : toJson(elided);
|
|
6545
|
+
return sliceText(rendered, maxLen);
|
|
6546
|
+
}
|
|
6547
|
+
function fittingPrefixLen(itemLengths, maxLen) {
|
|
6548
|
+
let used = "[]".length;
|
|
6549
|
+
for (let count = 0; count < itemLengths.length; count++) {
|
|
6550
|
+
used += itemLengths[count] + (count > 0 ? JSON_ITEM_SEPARATOR.length : 0);
|
|
6551
|
+
if (used > maxLen) return count;
|
|
6552
|
+
}
|
|
6553
|
+
return itemLengths.length;
|
|
6554
|
+
}
|
|
6555
|
+
function encodeItemsWithin(items, maxLen) {
|
|
6556
|
+
const encoded = [];
|
|
6557
|
+
let used = "[]".length;
|
|
6558
|
+
for (const item of items) {
|
|
6559
|
+
const separatorLen = encoded.length > 0 ? JSON_ITEM_SEPARATOR.length : 0;
|
|
6560
|
+
const budget = new CharBudget(maxLen - used - separatorLen);
|
|
6561
|
+
const copy = withoutInlineData(item, budget);
|
|
6562
|
+
if (budget.remaining <= 0) break;
|
|
6563
|
+
const value = toJson(copy);
|
|
6564
|
+
used += value.length + separatorLen;
|
|
6565
|
+
if (used > maxLen) break;
|
|
6566
|
+
encoded.push(value);
|
|
6567
|
+
}
|
|
6568
|
+
return encoded;
|
|
6569
|
+
}
|
|
6570
|
+
function itemsEntry(items, role, maxLen) {
|
|
6571
|
+
const encoded = encodeItemsWithin(items, maxLen);
|
|
6572
|
+
const envelopeLen = JSON.stringify({ role, content: "" }).length;
|
|
6573
|
+
const escapedLengths = encoded.map((value) => JSON.stringify(value).length - '""'.length);
|
|
6574
|
+
const kept = encoded.slice(0, fittingPrefixLen(escapedLengths, maxLen - envelopeLen));
|
|
6575
|
+
if (items.length > 0 && kept.length === 0) return void 0;
|
|
6576
|
+
return JSON.stringify({ role, content: joinJsonArray(kept) });
|
|
6577
|
+
}
|
|
6578
|
+
function decisionQuestionsEntry(questions) {
|
|
6579
|
+
if (!Array.isArray(questions) || questions.length === 0) return void 0;
|
|
6580
|
+
const maxLen = Math.floor(attributeMaxSize() / DECISION_QUESTIONS_MAX_SHARE) - "[]".length;
|
|
6581
|
+
return itemsEntry(questions, DECISION_QUESTIONS_ROLE, maxLen);
|
|
6582
|
+
}
|
|
6583
|
+
var CharBudget = class {
|
|
6584
|
+
constructor(remaining) {
|
|
6585
|
+
this.remaining = remaining;
|
|
6586
|
+
}
|
|
6587
|
+
/** Return as much of `text` as the budget still allows, and charge it. */
|
|
6588
|
+
take(text) {
|
|
6589
|
+
const kept = sliceText(text, this.remaining);
|
|
6590
|
+
this.remaining -= kept.length;
|
|
6591
|
+
return kept;
|
|
6592
|
+
}
|
|
6593
|
+
};
|
|
6594
|
+
function dataUrlPlaceholder(value) {
|
|
6595
|
+
if (!value.startsWith("data:")) return void 0;
|
|
6596
|
+
const headerEnd = value.slice(0, MAX_DATA_URL_HEADER_LEN).indexOf(",");
|
|
6597
|
+
if (headerEnd === -1 || !value.slice(0, headerEnd).endsWith(";base64")) {
|
|
6598
|
+
return void 0;
|
|
6599
|
+
}
|
|
6600
|
+
return value.startsWith("data:image/") ? "[image]" : "[file]";
|
|
6601
|
+
}
|
|
6602
|
+
function withoutInlineData(value, budget, seen = /* @__PURE__ */ new WeakSet()) {
|
|
6603
|
+
if (typeof value === "string") {
|
|
6604
|
+
const placeholder = dataUrlPlaceholder(value);
|
|
6605
|
+
if (placeholder !== void 0) {
|
|
6606
|
+
if (budget) budget.remaining -= placeholder.length;
|
|
6607
|
+
return placeholder;
|
|
6608
|
+
}
|
|
6609
|
+
return budget ? budget.take(value) : value;
|
|
6610
|
+
}
|
|
6611
|
+
if (value === null || typeof value !== "object") return value;
|
|
6612
|
+
if (seen.has(value)) return "[Circular]";
|
|
6613
|
+
seen.add(value);
|
|
6614
|
+
let copy = value;
|
|
6615
|
+
if (Array.isArray(value)) {
|
|
6616
|
+
const items = [];
|
|
6617
|
+
for (const item of value) {
|
|
6618
|
+
if (budget && budget.remaining <= 0) break;
|
|
6619
|
+
items.push(withoutInlineData(item, budget, seen));
|
|
6620
|
+
}
|
|
6621
|
+
copy = items;
|
|
6622
|
+
} else if (isPlainObject(value)) {
|
|
6623
|
+
copy = Object.fromEntries(
|
|
6624
|
+
Object.entries(value).map(([key, item]) => [key, withoutInlineData(item, budget, seen)])
|
|
6625
|
+
);
|
|
6626
|
+
}
|
|
6627
|
+
seen.delete(value);
|
|
6628
|
+
return copy;
|
|
6629
|
+
}
|
|
6630
|
+
function isPlainObject(value) {
|
|
6631
|
+
const proto = Object.getPrototypeOf(value);
|
|
6632
|
+
return proto === Object.prototype || proto === null;
|
|
6633
|
+
}
|
|
6634
|
+
function setDecisionAnswerAttributes(span2, response) {
|
|
6635
|
+
const answers = response.answers;
|
|
6636
|
+
if (!Array.isArray(answers) || !isTraceContentEnabled()) return;
|
|
6637
|
+
try {
|
|
6638
|
+
const entry = itemsEntry(answers, DECISION_ANSWERS_ROLE, attributeMaxSize() - "[]".length);
|
|
6639
|
+
if (entry !== void 0) span2.setAttribute(OUTPUT_ATTRIBUTE, joinJsonArray([entry]));
|
|
6640
|
+
} catch (error) {
|
|
6641
|
+
NetraLogger.warn("Failed to record OpenAI decision answers:", error);
|
|
6642
|
+
}
|
|
6643
|
+
}
|
|
6644
|
+
|
|
6645
|
+
// src/instrumentation/google-genai/decision-utils.ts
|
|
6646
|
+
var DECISION_QUESTIONS_ROLE2 = "user";
|
|
6647
|
+
var DECISION_ANSWERS_ROLE2 = "assistant";
|
|
6648
|
+
var DECISION_QUESTIONS_MAX_SHARE2 = 2;
|
|
6649
|
+
var MODEL_RESOURCE_PREFIX = "models/";
|
|
6650
|
+
function decisionModelName(model) {
|
|
6651
|
+
if (typeof model !== "string" || !model) return void 0;
|
|
6652
|
+
return model.startsWith(MODEL_RESOURCE_PREFIX) ? model.slice(MODEL_RESOURCE_PREFIX.length) : model;
|
|
6653
|
+
}
|
|
6654
|
+
function decisionInputEntry2(block, maxContentLen) {
|
|
6655
|
+
if (typeof block === "string") {
|
|
6656
|
+
return block ? { role: "user", content: sliceText(block, maxContentLen) } : void 0;
|
|
6657
|
+
}
|
|
6658
|
+
if (!isDict(block)) return void 0;
|
|
6659
|
+
const blockType = typeof block.type === "string" && block.type ? block.type : "text";
|
|
6660
|
+
if (blockType === "text") {
|
|
6661
|
+
const text = block.text;
|
|
6662
|
+
return typeof text === "string" && text ? { role: "user", content: sliceText(text, maxContentLen) } : void 0;
|
|
6663
|
+
}
|
|
6664
|
+
const { data, ...media } = block;
|
|
6665
|
+
const recorded = data !== void 0 ? { ...media, data: `[${blockType}]` } : media;
|
|
6666
|
+
return { role: "user", content: asPromptContent(recorded, maxContentLen) };
|
|
6667
|
+
}
|
|
6668
|
+
function buildGeminiDecisionInput(input, questionsEntry) {
|
|
6669
|
+
const blocks = Array.isArray(input) ? input : input === void 0 || input === null ? [] : [input];
|
|
6670
|
+
const encodedEntries = [];
|
|
6671
|
+
let remaining = attributeMaxSize() - "[]".length;
|
|
6672
|
+
if (questionsEntry) remaining -= questionsEntry.length + JSON_ITEM_SEPARATOR.length;
|
|
6673
|
+
for (const block of blocks) {
|
|
6674
|
+
const budget = remaining - (encodedEntries.length > 0 ? JSON_ITEM_SEPARATOR.length : 0);
|
|
6675
|
+
if (budget <= 0) break;
|
|
6676
|
+
const entry = decisionInputEntry2(block, budget);
|
|
6677
|
+
if (!entry) continue;
|
|
6678
|
+
const encoded = encodeEntryWithin(entry, budget);
|
|
6679
|
+
if (encoded === void 0) break;
|
|
6680
|
+
encodedEntries.push(encoded);
|
|
6681
|
+
remaining = budget - encoded.length;
|
|
6682
|
+
}
|
|
6683
|
+
if (questionsEntry) encodedEntries.push(questionsEntry);
|
|
6684
|
+
return encodedEntries.length > 0 ? joinJsonArray(encodedEntries) : void 0;
|
|
6685
|
+
}
|
|
6686
|
+
function keyedItems(map) {
|
|
6687
|
+
return Object.entries(map).map(([id, value]) => isDict(value) ? { id, ...value } : { id, value });
|
|
6688
|
+
}
|
|
6689
|
+
function geminiDecisionQuestionsEntry(questions) {
|
|
6690
|
+
if (!isDict(questions) || Object.keys(questions).length === 0) return void 0;
|
|
6691
|
+
const maxLen = Math.floor(attributeMaxSize() / DECISION_QUESTIONS_MAX_SHARE2) - "[]".length;
|
|
6692
|
+
return itemsEntry(keyedItems(questions), DECISION_QUESTIONS_ROLE2, maxLen);
|
|
6693
|
+
}
|
|
6694
|
+
function setDecisionRequestAttributes2(span2, params) {
|
|
6695
|
+
if (!span2.isRecording()) return;
|
|
6696
|
+
span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "decision");
|
|
6697
|
+
span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
|
|
6698
|
+
const model = decisionModelName(params.model);
|
|
6699
|
+
if (model) {
|
|
6700
|
+
span2.setAttribute(SpanAttributes2.LLM_REQUEST_MODEL, model);
|
|
6701
|
+
span2.setAttribute(SpanAttributes2.LLM_RESPONSE_MODEL, model);
|
|
6702
|
+
}
|
|
6703
|
+
if (!isTraceContentEnabled()) return;
|
|
6704
|
+
let questionsEntry;
|
|
6705
|
+
try {
|
|
6706
|
+
questionsEntry = geminiDecisionQuestionsEntry(params.questions);
|
|
6707
|
+
} catch (error) {
|
|
6708
|
+
NetraLogger.warn("Failed to record Gemini decision questions:", error);
|
|
6709
|
+
}
|
|
6710
|
+
try {
|
|
6711
|
+
const inputJson = buildGeminiDecisionInput(params.input, questionsEntry);
|
|
6712
|
+
if (inputJson !== void 0) span2.setAttribute(INPUT_ATTRIBUTE, inputJson);
|
|
6713
|
+
} catch (error) {
|
|
6714
|
+
NetraLogger.warn("Failed to record Gemini decision input:", error);
|
|
6715
|
+
}
|
|
6716
|
+
}
|
|
6717
|
+
function tokenCount(usage, key) {
|
|
6718
|
+
const value = usage[key];
|
|
6719
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
6720
|
+
}
|
|
6721
|
+
function setDecisionResponseAttributes(span2, response) {
|
|
6722
|
+
if (!span2.isRecording() || !isDict(response)) return;
|
|
6723
|
+
try {
|
|
6724
|
+
const usage = response.usage;
|
|
6725
|
+
if (isDict(usage)) {
|
|
6726
|
+
const prompt = tokenCount(usage, "total_input_tokens");
|
|
6727
|
+
if (prompt !== void 0) span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, prompt);
|
|
6728
|
+
const output = [tokenCount(usage, "total_output_tokens"), tokenCount(usage, "total_thought_tokens")].filter(
|
|
6729
|
+
(n) => n !== void 0
|
|
6730
|
+
);
|
|
6731
|
+
if (output.length > 0) {
|
|
6732
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, output.reduce((a, b) => a + b, 0));
|
|
6733
|
+
}
|
|
6734
|
+
const total = tokenCount(usage, "total_tokens");
|
|
6735
|
+
if (total !== void 0) span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, total);
|
|
6736
|
+
const cached = tokenCount(usage, "total_cached_tokens");
|
|
6737
|
+
if (cached !== void 0) span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS, cached);
|
|
6738
|
+
}
|
|
6739
|
+
const feedback = response.prompt_feedback;
|
|
6740
|
+
if (isDict(feedback) && feedback.block_reason) {
|
|
6741
|
+
span2.setAttribute(SpanAttributes2.LLM_RESPONSE_FINISH_REASON, String(feedback.block_reason));
|
|
6742
|
+
}
|
|
6743
|
+
} catch (error) {
|
|
6744
|
+
NetraLogger.warn("Failed to record Gemini decision usage:", error);
|
|
6745
|
+
}
|
|
6746
|
+
const answers = response.answers;
|
|
6747
|
+
if (!isDict(answers) || Object.keys(answers).length === 0 || !isTraceContentEnabled()) return;
|
|
6748
|
+
try {
|
|
6749
|
+
const entry = itemsEntry(keyedItems(answers), DECISION_ANSWERS_ROLE2, attributeMaxSize() - "[]".length);
|
|
6750
|
+
if (entry !== void 0) span2.setAttribute(OUTPUT_ATTRIBUTE, joinJsonArray([entry]));
|
|
6751
|
+
} catch (error) {
|
|
6752
|
+
NetraLogger.warn("Failed to record Gemini decision answers:", error);
|
|
6753
|
+
}
|
|
6754
|
+
}
|
|
6755
|
+
|
|
6331
6756
|
// src/instrumentation/google-genai/wrappers.ts
|
|
6332
6757
|
var LOG_PREFIX2 = "netra.instrumentation.google_genai";
|
|
6333
6758
|
function buildParams(args, self) {
|
|
@@ -6496,11 +6921,72 @@ function streamWrapperFactory(tracer, spanName, requestType) {
|
|
|
6496
6921
|
var chatWrapper2 = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
|
|
6497
6922
|
var chatStreamWrapper2 = (tracer) => streamWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
|
|
6498
6923
|
var embeddingsWrapper = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.EMBEDDING, "embedding");
|
|
6924
|
+
var decisionsWrapper = (tracer) => function wrapper(original) {
|
|
6925
|
+
return function(...args) {
|
|
6926
|
+
if (shouldSuppressInstrumentation()) {
|
|
6927
|
+
return original.apply(this, args);
|
|
6928
|
+
}
|
|
6929
|
+
const params = typeof args[0] === "object" && args[0] !== null ? args[0] : {};
|
|
6930
|
+
const currentContext = context.active();
|
|
6931
|
+
return tracer.startActiveSpan(
|
|
6932
|
+
SPAN_NAMES2.DECISION,
|
|
6933
|
+
{ kind: SpanKind.CLIENT },
|
|
6934
|
+
(span2) => {
|
|
6935
|
+
try {
|
|
6936
|
+
try {
|
|
6937
|
+
setDecisionRequestAttributes2(span2, params);
|
|
6938
|
+
} catch (error) {
|
|
6939
|
+
NetraLogger.warn(`${LOG_PREFIX2}: failed to record decision request:`, error);
|
|
6940
|
+
}
|
|
6941
|
+
const startTime = Date.now();
|
|
6942
|
+
const spanContext = trace.setSpan(currentContext, span2);
|
|
6943
|
+
const suppressedCtx = createSuppressedContext(spanContext);
|
|
6944
|
+
const response = context.with(suppressedCtx, () => original.apply(this, args));
|
|
6945
|
+
return wrapResponse(
|
|
6946
|
+
response,
|
|
6947
|
+
{
|
|
6948
|
+
withContext: (fn) => context.with(spanContext, fn),
|
|
6949
|
+
onSuccess: (value) => {
|
|
6950
|
+
setDecisionResponseAttributes(span2, value);
|
|
6951
|
+
span2.setAttribute(SpanAttributes2.LLM_RESPONSE_DURATION, (Date.now() - startTime) / 1e3);
|
|
6952
|
+
},
|
|
6953
|
+
onError: (error) => {
|
|
6954
|
+
span2.setStatus({
|
|
6955
|
+
code: SpanStatusCode.ERROR,
|
|
6956
|
+
message: error instanceof Error ? error.message : String(error)
|
|
6957
|
+
});
|
|
6958
|
+
span2.recordException(error);
|
|
6959
|
+
},
|
|
6960
|
+
finalize: (status) => {
|
|
6961
|
+
if (status === "ok") {
|
|
6962
|
+
span2.setStatus({ code: SpanStatusCode.OK });
|
|
6963
|
+
}
|
|
6964
|
+
span2.end();
|
|
6965
|
+
}
|
|
6966
|
+
},
|
|
6967
|
+
{ preserveOriginal: response }
|
|
6968
|
+
);
|
|
6969
|
+
} catch (error) {
|
|
6970
|
+
span2.setStatus({
|
|
6971
|
+
code: SpanStatusCode.ERROR,
|
|
6972
|
+
message: error instanceof Error ? error.message : String(error)
|
|
6973
|
+
});
|
|
6974
|
+
span2.recordException(error);
|
|
6975
|
+
span2.end();
|
|
6976
|
+
throw error;
|
|
6977
|
+
}
|
|
6978
|
+
}
|
|
6979
|
+
);
|
|
6980
|
+
};
|
|
6981
|
+
};
|
|
6499
6982
|
|
|
6500
6983
|
// src/instrumentation/google-genai/index.ts
|
|
6984
|
+
var DECISIONS_PROPERTY = "decisions";
|
|
6501
6985
|
var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
|
|
6502
6986
|
constructor() {
|
|
6503
6987
|
super(...arguments);
|
|
6988
|
+
// Keyed by GoogleGenAI.prototype: the ESM and CJS builds each have their own.
|
|
6989
|
+
this.decisionsPatches = /* @__PURE__ */ new Map();
|
|
6504
6990
|
this.instrumentationName = "netra.instrumentation.google_genai";
|
|
6505
6991
|
this.instrumentationVersion = __version__2;
|
|
6506
6992
|
this.packageName = "@google/genai";
|
|
@@ -6509,7 +6995,7 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
|
|
|
6509
6995
|
extractClasses(mod) {
|
|
6510
6996
|
const root = mod.default ?? mod;
|
|
6511
6997
|
if (!root.Models) return null;
|
|
6512
|
-
return { Models: root.Models, Chat: root.Chat };
|
|
6998
|
+
return { Models: root.Models, Chat: root.Chat, GoogleGenAI: root.GoogleGenAI };
|
|
6513
6999
|
}
|
|
6514
7000
|
isSameClasses(a, b) {
|
|
6515
7001
|
return a.Models === b.Models;
|
|
@@ -6544,9 +7030,59 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
|
|
|
6544
7030
|
wrapped = true;
|
|
6545
7031
|
}
|
|
6546
7032
|
}
|
|
7033
|
+
if (this.patchDecisions(classes.GoogleGenAI?.prototype, tracer)) {
|
|
7034
|
+
wrapped = true;
|
|
7035
|
+
}
|
|
6547
7036
|
return wrapped;
|
|
6548
7037
|
}
|
|
7038
|
+
/**
|
|
7039
|
+
* Replace the `decisions` getter so the resource's `create` is wrapped on first access.
|
|
7040
|
+
*
|
|
7041
|
+
* @returns true when the getter was patched; false on releases without the Decisions API.
|
|
7042
|
+
*/
|
|
7043
|
+
patchDecisions(clientProto, tracer) {
|
|
7044
|
+
if (!clientProto || this.decisionsPatches.has(clientProto)) return false;
|
|
7045
|
+
const getter = Object.getOwnPropertyDescriptor(clientProto, DECISIONS_PROPERTY);
|
|
7046
|
+
if (!getter?.get || !getter.configurable) return false;
|
|
7047
|
+
const patch = { getter, wrappedPrototypes: /* @__PURE__ */ new Set() };
|
|
7048
|
+
const originalGet = getter.get;
|
|
7049
|
+
try {
|
|
7050
|
+
Object.defineProperty(clientProto, DECISIONS_PROPERTY, {
|
|
7051
|
+
configurable: true,
|
|
7052
|
+
enumerable: getter.enumerable,
|
|
7053
|
+
get() {
|
|
7054
|
+
const resource = originalGet.call(this);
|
|
7055
|
+
try {
|
|
7056
|
+
const resourceProto = resource ? Object.getPrototypeOf(resource) : void 0;
|
|
7057
|
+
if (resourceProto && typeof resourceProto.create === "function" && !resourceProto.create.__wrapped) {
|
|
7058
|
+
shimmer.wrap(resourceProto, "create", decisionsWrapper(tracer));
|
|
7059
|
+
patch.wrappedPrototypes.add(resourceProto);
|
|
7060
|
+
}
|
|
7061
|
+
} catch (error) {
|
|
7062
|
+
NetraLogger.error("Google GenAI: failed to instrument decisions.create", error);
|
|
7063
|
+
}
|
|
7064
|
+
return resource;
|
|
7065
|
+
}
|
|
7066
|
+
});
|
|
7067
|
+
} catch (error) {
|
|
7068
|
+
NetraLogger.error("Google GenAI: failed to patch the decisions getter", error);
|
|
7069
|
+
return false;
|
|
7070
|
+
}
|
|
7071
|
+
this.decisionsPatches.set(clientProto, patch);
|
|
7072
|
+
return true;
|
|
7073
|
+
}
|
|
7074
|
+
/** Restore the original `decisions` getter and unwrap every `create` it wrapped. */
|
|
7075
|
+
unpatchDecisions(clientProto) {
|
|
7076
|
+
const patch = clientProto ? this.decisionsPatches.get(clientProto) : void 0;
|
|
7077
|
+
if (!patch) return;
|
|
7078
|
+
Object.defineProperty(clientProto, DECISIONS_PROPERTY, patch.getter);
|
|
7079
|
+
for (const resourceProto of patch.wrappedPrototypes) {
|
|
7080
|
+
if (resourceProto.create?.__wrapped) shimmer.unwrap(resourceProto, "create");
|
|
7081
|
+
}
|
|
7082
|
+
this.decisionsPatches.delete(clientProto);
|
|
7083
|
+
}
|
|
6549
7084
|
removePatches(classes) {
|
|
7085
|
+
this.unpatchDecisions(classes.GoogleGenAI?.prototype);
|
|
6550
7086
|
const modelsProto = classes.Models?.prototype;
|
|
6551
7087
|
if (modelsProto) {
|
|
6552
7088
|
if (typeof modelsProto.generateContentInternal === "function")
|
|
@@ -6581,7 +7117,7 @@ function normalizeGenerativeAIRole(raw) {
|
|
|
6581
7117
|
const rawLower = raw.toLowerCase();
|
|
6582
7118
|
return rawLower === "model" ? "assistant" : rawLower;
|
|
6583
7119
|
}
|
|
6584
|
-
function
|
|
7120
|
+
function setRequestAttributes5(span2, kwargs, requestType, args) {
|
|
6585
7121
|
span2._netra_kwargs = kwargs;
|
|
6586
7122
|
if (!span2.isRecording()) {
|
|
6587
7123
|
return;
|
|
@@ -6799,7 +7335,7 @@ function _setPromptAttributes(span2, kwargs, args) {
|
|
|
6799
7335
|
}
|
|
6800
7336
|
}
|
|
6801
7337
|
}
|
|
6802
|
-
function
|
|
7338
|
+
function setResponseAttributes5(span2, response) {
|
|
6803
7339
|
if (!span2.isRecording()) {
|
|
6804
7340
|
return;
|
|
6805
7341
|
}
|
|
@@ -7010,7 +7546,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
|
|
|
7010
7546
|
(span2) => {
|
|
7011
7547
|
try {
|
|
7012
7548
|
try {
|
|
7013
|
-
|
|
7549
|
+
setRequestAttributes5(span2, kwargs, requestType, args[0]);
|
|
7014
7550
|
} catch (e) {
|
|
7015
7551
|
NetraLogger.error(`${LOG_PREFIX3}:`, e);
|
|
7016
7552
|
}
|
|
@@ -7023,7 +7559,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
|
|
|
7023
7559
|
try {
|
|
7024
7560
|
const endTime = Date.now();
|
|
7025
7561
|
const responseDict = modelAsDict(value);
|
|
7026
|
-
|
|
7562
|
+
setResponseAttributes5(span2, responseDict);
|
|
7027
7563
|
const duration = (endTime - startTime) / 1e3;
|
|
7028
7564
|
span2.setAttribute("llm.response.duration", duration);
|
|
7029
7565
|
if (requestType !== "embedding") {
|
|
@@ -7052,7 +7588,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
|
|
|
7052
7588
|
try {
|
|
7053
7589
|
const endTime = Date.now();
|
|
7054
7590
|
const responseDict = modelAsDict(response);
|
|
7055
|
-
|
|
7591
|
+
setResponseAttributes5(span2, responseDict);
|
|
7056
7592
|
span2.setAttribute(
|
|
7057
7593
|
"llm.response.duration",
|
|
7058
7594
|
(endTime - startTime) / 1e3
|
|
@@ -7098,7 +7634,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
|
|
|
7098
7634
|
const startTime = Date.now();
|
|
7099
7635
|
try {
|
|
7100
7636
|
try {
|
|
7101
|
-
|
|
7637
|
+
setRequestAttributes5(span2, kwargs, requestType, args[0]);
|
|
7102
7638
|
} catch (e) {
|
|
7103
7639
|
NetraLogger.error(`${LOG_PREFIX3}:`, e);
|
|
7104
7640
|
}
|
|
@@ -7116,7 +7652,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
|
|
|
7116
7652
|
try {
|
|
7117
7653
|
const endTime = Date.now();
|
|
7118
7654
|
const responseDict = modelAsDict(streamResult);
|
|
7119
|
-
|
|
7655
|
+
setResponseAttributes5(span2, responseDict);
|
|
7120
7656
|
const duration = (endTime - startTime) / 1e3;
|
|
7121
7657
|
span2.setAttribute("llm.response.duration", duration);
|
|
7122
7658
|
span2.setAttribute(
|
|
@@ -7145,14 +7681,14 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
|
|
|
7145
7681
|
try {
|
|
7146
7682
|
const finalResponse = await streamResult.response;
|
|
7147
7683
|
const responseDict = modelAsDict(finalResponse);
|
|
7148
|
-
|
|
7684
|
+
setResponseAttributes5(span2, responseDict);
|
|
7149
7685
|
} catch {
|
|
7150
7686
|
const responseDict = modelAsDict(streamResult);
|
|
7151
|
-
|
|
7687
|
+
setResponseAttributes5(span2, responseDict);
|
|
7152
7688
|
}
|
|
7153
7689
|
} else {
|
|
7154
7690
|
const responseDict = modelAsDict(streamResult);
|
|
7155
|
-
|
|
7691
|
+
setResponseAttributes5(span2, responseDict);
|
|
7156
7692
|
}
|
|
7157
7693
|
const duration = (endTime - startTime) / 1e3;
|
|
7158
7694
|
span2.setAttribute(
|
|
@@ -7326,14 +7862,14 @@ var googleGenerativeAIInstrumentor = new NetraGoogleGenerativeAIInstrumentor();
|
|
|
7326
7862
|
var __version__4 = "1.0.0";
|
|
7327
7863
|
|
|
7328
7864
|
// src/instrumentation/groq/utils.ts
|
|
7329
|
-
function
|
|
7865
|
+
function setRequestAttributes6(span2, kwargs, requestType) {
|
|
7330
7866
|
if (!span2.isRecording()) {
|
|
7331
7867
|
NetraLogger.log("Span is not recording");
|
|
7332
7868
|
return;
|
|
7333
7869
|
}
|
|
7334
7870
|
setRequestAttributes(span2, kwargs, requestType, "groq");
|
|
7335
7871
|
}
|
|
7336
|
-
function
|
|
7872
|
+
function setResponseAttributes6(span2, response) {
|
|
7337
7873
|
if (!span2.isRecording()) {
|
|
7338
7874
|
NetraLogger.log("Span is not recording");
|
|
7339
7875
|
return;
|
|
@@ -7344,6 +7880,14 @@ function setResponseAttributes5(span2, response) {
|
|
|
7344
7880
|
// src/instrumentation/groq/wrappers.ts
|
|
7345
7881
|
var CHAT_SPAN_NAME2 = "groq.chat";
|
|
7346
7882
|
var STREAM_ENABLED_REQUESTS = ["chat"];
|
|
7883
|
+
function recordSpanError(span2, error) {
|
|
7884
|
+
NetraLogger.error("netra.instrumentation.groq:", error);
|
|
7885
|
+
span2.setStatus({
|
|
7886
|
+
code: SpanStatusCode.ERROR,
|
|
7887
|
+
message: error instanceof Error ? error.message : String(error)
|
|
7888
|
+
});
|
|
7889
|
+
span2.recordException(error);
|
|
7890
|
+
}
|
|
7347
7891
|
function groqWrapper(tracer, spanName, requestType) {
|
|
7348
7892
|
return function wrapper(wrapped, instance, args, kwargs) {
|
|
7349
7893
|
if (shouldSuppressInstrumentation()) {
|
|
@@ -7362,25 +7906,17 @@ function groqWrapper(tracer, spanName, requestType) {
|
|
|
7362
7906
|
currentContext
|
|
7363
7907
|
);
|
|
7364
7908
|
try {
|
|
7365
|
-
|
|
7909
|
+
setRequestAttributes6(span2, kwargs, requestType);
|
|
7366
7910
|
const startTime = Date.now();
|
|
7367
7911
|
const response = wrapped.call(instance, ...args);
|
|
7368
|
-
if (isPromise(response)) {
|
|
7369
|
-
|
|
7370
|
-
|
|
7371
|
-
|
|
7372
|
-
|
|
7373
|
-
|
|
7374
|
-
|
|
7375
|
-
|
|
7376
|
-
code: SpanStatusCode.ERROR,
|
|
7377
|
-
message: error instanceof Error ? error.message : String(error)
|
|
7378
|
-
});
|
|
7379
|
-
span2.recordException(error);
|
|
7380
|
-
span2.end();
|
|
7381
|
-
throw error;
|
|
7382
|
-
}
|
|
7383
|
-
})();
|
|
7912
|
+
if (isPromise(response) || isAsyncIterable(response)) {
|
|
7913
|
+
const collector = new AsyncStreamCollector(span2, startTime, kwargs);
|
|
7914
|
+
return wrapResponse(response, {
|
|
7915
|
+
withContext: (fn) => fn(),
|
|
7916
|
+
onChunk: (chunk) => collector.processChunk(chunk),
|
|
7917
|
+
onError: (error) => recordSpanError(span2, error),
|
|
7918
|
+
finalize: (status) => collector.finish(status)
|
|
7919
|
+
}, { deriveAPIPromise: true });
|
|
7384
7920
|
} else {
|
|
7385
7921
|
return new StreamingWrapper(span2, response, startTime, kwargs);
|
|
7386
7922
|
}
|
|
@@ -7403,38 +7939,27 @@ function groqWrapper(tracer, spanName, requestType) {
|
|
|
7403
7939
|
},
|
|
7404
7940
|
(span2) => {
|
|
7405
7941
|
try {
|
|
7406
|
-
|
|
7942
|
+
setRequestAttributes6(span2, kwargs, requestType);
|
|
7407
7943
|
const startTime = Date.now();
|
|
7408
7944
|
const response = wrapped.call(instance, ...args);
|
|
7409
7945
|
if (isPromise(response)) {
|
|
7410
|
-
return (
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
const responseDict = modelAsDict(value);
|
|
7415
|
-
setResponseAttributes5(span2, responseDict);
|
|
7946
|
+
return wrapPromise(response, {
|
|
7947
|
+
withContext: (fn) => fn(),
|
|
7948
|
+
onSuccess: (value) => {
|
|
7949
|
+
setResponseAttributes6(span2, modelAsDict(value));
|
|
7416
7950
|
span2.setAttribute(
|
|
7417
7951
|
"llm.response.duration",
|
|
7418
|
-
(
|
|
7952
|
+
(Date.now() - startTime) / 1e3
|
|
7419
7953
|
);
|
|
7420
7954
|
span2.setStatus({ code: SpanStatusCode.OK });
|
|
7421
|
-
|
|
7422
|
-
|
|
7423
|
-
|
|
7424
|
-
|
|
7425
|
-
span2.setStatus({
|
|
7426
|
-
code: SpanStatusCode.ERROR,
|
|
7427
|
-
message: error instanceof Error ? error.message : String(error)
|
|
7428
|
-
});
|
|
7429
|
-
span2.recordException(error);
|
|
7430
|
-
span2.end();
|
|
7431
|
-
throw error;
|
|
7432
|
-
}
|
|
7433
|
-
})();
|
|
7955
|
+
},
|
|
7956
|
+
onError: (error) => recordSpanError(span2, error),
|
|
7957
|
+
finalize: () => span2.end()
|
|
7958
|
+
}, { deriveAPIPromise: true });
|
|
7434
7959
|
} else {
|
|
7435
7960
|
const endTime = Date.now();
|
|
7436
7961
|
const responseDict = modelAsDict(response);
|
|
7437
|
-
|
|
7962
|
+
setResponseAttributes6(span2, responseDict);
|
|
7438
7963
|
span2.setAttribute(
|
|
7439
7964
|
"llm.response.duration",
|
|
7440
7965
|
(endTime - startTime) / 1e3
|
|
@@ -7556,57 +8081,15 @@ var StreamingWrapper = class {
|
|
|
7556
8081
|
this.span.end();
|
|
7557
8082
|
}
|
|
7558
8083
|
};
|
|
7559
|
-
var
|
|
7560
|
-
constructor(span2,
|
|
7561
|
-
this.
|
|
8084
|
+
var AsyncStreamCollector = class {
|
|
8085
|
+
constructor(span2, startTime, requestKwargs) {
|
|
8086
|
+
this.span = span2;
|
|
8087
|
+
this.startTime = startTime;
|
|
8088
|
+
this.requestKwargs = requestKwargs;
|
|
7562
8089
|
this.completeResponse = {
|
|
7563
8090
|
choices: [],
|
|
7564
8091
|
model: ""
|
|
7565
8092
|
};
|
|
7566
|
-
defineHidden(this, "span", span2);
|
|
7567
|
-
defineHidden(this, "response", response);
|
|
7568
|
-
defineHidden(this, "startTime", startTime);
|
|
7569
|
-
defineHidden(this, "requestKwargs", requestKwargs);
|
|
7570
|
-
}
|
|
7571
|
-
toJSON() {
|
|
7572
|
-
return this.completeResponse;
|
|
7573
|
-
}
|
|
7574
|
-
[Symbol.asyncIterator]() {
|
|
7575
|
-
return this;
|
|
7576
|
-
}
|
|
7577
|
-
async next() {
|
|
7578
|
-
try {
|
|
7579
|
-
if (!this.iterator) {
|
|
7580
|
-
const isObject = this.response && typeof this.response === "object";
|
|
7581
|
-
if (!isObject) {
|
|
7582
|
-
throw new Error("Response is not an iterable");
|
|
7583
|
-
}
|
|
7584
|
-
if (Symbol.asyncIterator in this.response) {
|
|
7585
|
-
this.iterator = this.response[Symbol.asyncIterator]();
|
|
7586
|
-
} else if (Symbol.iterator in this.response) {
|
|
7587
|
-
const syncIterator = this.response[Symbol.iterator]();
|
|
7588
|
-
this.iterator = {
|
|
7589
|
-
async next() {
|
|
7590
|
-
return syncIterator.next();
|
|
7591
|
-
}
|
|
7592
|
-
};
|
|
7593
|
-
} else if (typeof this.response.next === "function") {
|
|
7594
|
-
this.iterator = this.response;
|
|
7595
|
-
} else {
|
|
7596
|
-
throw new Error("Response is not iterable");
|
|
7597
|
-
}
|
|
7598
|
-
}
|
|
7599
|
-
const result = await this.iterator.next();
|
|
7600
|
-
if (result.done) {
|
|
7601
|
-
this.finalizeSpan(SpanStatusCode.OK);
|
|
7602
|
-
return result;
|
|
7603
|
-
}
|
|
7604
|
-
this.processChunk(result.value);
|
|
7605
|
-
return result;
|
|
7606
|
-
} catch (error) {
|
|
7607
|
-
this.finalizeSpan(SpanStatusCode.ERROR);
|
|
7608
|
-
throw error;
|
|
7609
|
-
}
|
|
7610
8093
|
}
|
|
7611
8094
|
processChunk(chunk) {
|
|
7612
8095
|
const chunkDict = modelAsDict(chunk);
|
|
@@ -7663,12 +8146,12 @@ var AsyncStreamingWrapper = class {
|
|
|
7663
8146
|
);
|
|
7664
8147
|
}
|
|
7665
8148
|
}
|
|
7666
|
-
|
|
8149
|
+
finish(status) {
|
|
7667
8150
|
const endTime = Date.now();
|
|
7668
8151
|
const duration = (endTime - this.startTime) / 1e3;
|
|
7669
|
-
|
|
8152
|
+
setResponseAttributes6(this.span, this.completeResponse);
|
|
7670
8153
|
this.span.setAttribute("llm.response.duration", duration);
|
|
7671
|
-
this.span.setStatus({ code });
|
|
8154
|
+
if (status === "ok") this.span.setStatus({ code: SpanStatusCode.OK });
|
|
7672
8155
|
this.span.end();
|
|
7673
8156
|
}
|
|
7674
8157
|
};
|
|
@@ -7970,37 +8453,6 @@ function setLlmPrompts(span2, prompts) {
|
|
|
7970
8453
|
|
|
7971
8454
|
// src/instrumentation/langgraph/wrappers.ts
|
|
7972
8455
|
var LANGGRAPH_INSTRUMENTATION_ACTIVE = createContextKey("netra.langgraph.active");
|
|
7973
|
-
function getContextManager2() {
|
|
7974
|
-
try {
|
|
7975
|
-
if (context._getContextManager) {
|
|
7976
|
-
return context._getContextManager();
|
|
7977
|
-
}
|
|
7978
|
-
const globalSymbols = Object.getOwnPropertySymbols(global);
|
|
7979
|
-
const otelSymbol = globalSymbols.find(
|
|
7980
|
-
(s) => s.toString().includes("opentelemetry.js.api")
|
|
7981
|
-
);
|
|
7982
|
-
if (otelSymbol) {
|
|
7983
|
-
const globalState = global[otelSymbol];
|
|
7984
|
-
if (globalState?.contextManager) {
|
|
7985
|
-
return globalState.contextManager;
|
|
7986
|
-
}
|
|
7987
|
-
}
|
|
7988
|
-
return null;
|
|
7989
|
-
} catch {
|
|
7990
|
-
return null;
|
|
7991
|
-
}
|
|
7992
|
-
}
|
|
7993
|
-
function enterWithContext(newContext) {
|
|
7994
|
-
const contextManager = getContextManager2();
|
|
7995
|
-
if (!contextManager) return;
|
|
7996
|
-
if (typeof contextManager.enterWith === "function") {
|
|
7997
|
-
contextManager.enterWith(newContext);
|
|
7998
|
-
return;
|
|
7999
|
-
}
|
|
8000
|
-
if (contextManager._asyncLocalStorage && typeof contextManager._asyncLocalStorage.enterWith === "function") {
|
|
8001
|
-
contextManager._asyncLocalStorage.enterWith(newContext);
|
|
8002
|
-
}
|
|
8003
|
-
}
|
|
8004
8456
|
var NetraLanggraphCallbackHandler = null;
|
|
8005
8457
|
async function loadLanggraphCallbackHandler() {
|
|
8006
8458
|
if (NetraLanggraphCallbackHandler) return true;
|
|
@@ -8204,49 +8656,6 @@ function createCallbackHandlerClass(Base) {
|
|
|
8204
8656
|
}
|
|
8205
8657
|
};
|
|
8206
8658
|
}
|
|
8207
|
-
var LanggraphStreamingWrapper = class {
|
|
8208
|
-
constructor(rootSpan, rootContext) {
|
|
8209
|
-
this.output = {};
|
|
8210
|
-
defineHidden(this, "rootSpan", rootSpan);
|
|
8211
|
-
defineHidden(this, "rootContext", rootContext);
|
|
8212
|
-
}
|
|
8213
|
-
toJSON() {
|
|
8214
|
-
try {
|
|
8215
|
-
return this.output;
|
|
8216
|
-
} catch {
|
|
8217
|
-
return {};
|
|
8218
|
-
}
|
|
8219
|
-
}
|
|
8220
|
-
async startStream(originalFunc, instance, input, config, ...rest) {
|
|
8221
|
-
this.iterable = await originalFunc.call(instance, input, config, ...rest);
|
|
8222
|
-
return this;
|
|
8223
|
-
}
|
|
8224
|
-
async *[Symbol.asyncIterator]() {
|
|
8225
|
-
const spanContext = trace.setSpan(this.rootContext, this.rootSpan);
|
|
8226
|
-
try {
|
|
8227
|
-
const iterator = await this.iterable[Symbol.asyncIterator]();
|
|
8228
|
-
while (true) {
|
|
8229
|
-
let result;
|
|
8230
|
-
await context.with(spanContext, async () => {
|
|
8231
|
-
result = await iterator.next();
|
|
8232
|
-
});
|
|
8233
|
-
if (result.done) break;
|
|
8234
|
-
const value = result?.value ?? {};
|
|
8235
|
-
this.output = { ...this.output, ...value };
|
|
8236
|
-
yield result;
|
|
8237
|
-
}
|
|
8238
|
-
this.rootSpan.setAttribute(
|
|
8239
|
-
NetraLanggraphAttributes.entityOutput,
|
|
8240
|
-
JSON.stringify({ outputs: this.output })
|
|
8241
|
-
);
|
|
8242
|
-
} catch (error) {
|
|
8243
|
-
this.rootSpan.recordException(error);
|
|
8244
|
-
throw error;
|
|
8245
|
-
} finally {
|
|
8246
|
-
this.rootSpan.end();
|
|
8247
|
-
}
|
|
8248
|
-
}
|
|
8249
|
-
};
|
|
8250
8659
|
var LanggraphWrapper = class {
|
|
8251
8660
|
constructor(tracer) {
|
|
8252
8661
|
this.tracer = tracer;
|
|
@@ -8282,7 +8691,6 @@ var LanggraphWrapper = class {
|
|
|
8282
8691
|
NetraLogger.debug(`LangGraph span created. New TraceId: ${span2.spanContext().traceId}, SpanId: ${span2.spanContext().spanId}`);
|
|
8283
8692
|
const ctxWithSpan = trace.setSpan(context.active(), span2);
|
|
8284
8693
|
const ctxWithFlag = ctxWithSpan.setValue(LANGGRAPH_INSTRUMENTATION_ACTIVE, true);
|
|
8285
|
-
enterWithContext(ctxWithFlag);
|
|
8286
8694
|
return context.with(ctxWithFlag, async () => {
|
|
8287
8695
|
{
|
|
8288
8696
|
const innerSpan = trace.getSpan(context.active());
|
|
@@ -8322,22 +8730,39 @@ var LanggraphWrapper = class {
|
|
|
8322
8730
|
);
|
|
8323
8731
|
setGraphInputAttributes(span2, input);
|
|
8324
8732
|
const updatedConfig = this.getUpdatedConfig(config, span2);
|
|
8733
|
+
const ctxWithSpan = trace.setSpan(context.active(), span2);
|
|
8734
|
+
const ctxWithFlag = ctxWithSpan.setValue(LANGGRAPH_INSTRUMENTATION_ACTIVE, true);
|
|
8735
|
+
let stream;
|
|
8325
8736
|
try {
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
const streamingWrapper = new LanggraphStreamingWrapper(span2, ctxWithFlag);
|
|
8330
|
-
return streamingWrapper.startStream(
|
|
8331
|
-
originalFunc,
|
|
8332
|
-
instance,
|
|
8333
|
-
input,
|
|
8334
|
-
updatedConfig,
|
|
8335
|
-
...rest
|
|
8737
|
+
stream = await context.with(
|
|
8738
|
+
ctxWithFlag,
|
|
8739
|
+
() => originalFunc.call(instance, input, updatedConfig, ...rest)
|
|
8336
8740
|
);
|
|
8337
8741
|
} catch (error) {
|
|
8338
8742
|
span2.recordException(error);
|
|
8339
8743
|
span2.end();
|
|
8744
|
+
throw error;
|
|
8340
8745
|
}
|
|
8746
|
+
let output = {};
|
|
8747
|
+
return wrapAsyncIterable(stream, {
|
|
8748
|
+
withContext: (fn) => context.with(ctxWithFlag, fn),
|
|
8749
|
+
onChunk: (chunk) => {
|
|
8750
|
+
output = { ...output, ...chunk ?? {} };
|
|
8751
|
+
},
|
|
8752
|
+
onError: (error) => span2.recordException(error),
|
|
8753
|
+
finalize: (status) => {
|
|
8754
|
+
try {
|
|
8755
|
+
if (status === "ok") {
|
|
8756
|
+
span2.setAttribute(
|
|
8757
|
+
NetraLanggraphAttributes.entityOutput,
|
|
8758
|
+
JSON.stringify({ outputs: output })
|
|
8759
|
+
);
|
|
8760
|
+
}
|
|
8761
|
+
} finally {
|
|
8762
|
+
span2.end();
|
|
8763
|
+
}
|
|
8764
|
+
}
|
|
8765
|
+
});
|
|
8341
8766
|
}
|
|
8342
8767
|
};
|
|
8343
8768
|
|
|
@@ -8548,7 +8973,7 @@ var langgraphInstrumentor = new NetraLanggraphInstrumentor();
|
|
|
8548
8973
|
var __version__6 = "1.0.0";
|
|
8549
8974
|
|
|
8550
8975
|
// src/instrumentation/mistralai/utils.ts
|
|
8551
|
-
function
|
|
8976
|
+
function setRequestAttributes7(span2, kwargs, requestType) {
|
|
8552
8977
|
setRequestAttributes(span2, kwargs, requestType, "mistralai");
|
|
8553
8978
|
if (kwargs.agentId) {
|
|
8554
8979
|
span2.setAttribute("gen_ai.agent.id", String(kwargs.agentId));
|
|
@@ -8567,7 +8992,7 @@ function setRequestAttributes6(span2, kwargs, requestType) {
|
|
|
8567
8992
|
span2.setAttribute("llm.request.has_suffix", true);
|
|
8568
8993
|
}
|
|
8569
8994
|
}
|
|
8570
|
-
function
|
|
8995
|
+
function setResponseAttributes7(span2, response) {
|
|
8571
8996
|
setResponseAttributes(span2, response);
|
|
8572
8997
|
}
|
|
8573
8998
|
|
|
@@ -8579,6 +9004,14 @@ var AGENTS_SPAN_NAME = "mistralai.agents";
|
|
|
8579
9004
|
var CHAT_STREAM_SPAN_NAME = CHAT_SPAN_NAME3;
|
|
8580
9005
|
var FIM_STREAM_SPAN_NAME = FIM_SPAN_NAME;
|
|
8581
9006
|
var AGENTS_STREAM_SPAN_NAME = AGENTS_SPAN_NAME;
|
|
9007
|
+
function recordSpanError2(span2, error) {
|
|
9008
|
+
NetraLogger.error("netra.instrumentation.mistralai:", error);
|
|
9009
|
+
span2.setStatus({
|
|
9010
|
+
code: SpanStatusCode.ERROR,
|
|
9011
|
+
message: error instanceof Error ? error.message : String(error)
|
|
9012
|
+
});
|
|
9013
|
+
span2.recordException(error);
|
|
9014
|
+
}
|
|
8582
9015
|
function mistralWrapper(tracer, spanName, requestType) {
|
|
8583
9016
|
return function wrapper(wrapped, instance, args, kwargs) {
|
|
8584
9017
|
if (shouldSuppressInstrumentation()) {
|
|
@@ -8593,7 +9026,7 @@ function mistralWrapper(tracer, spanName, requestType) {
|
|
|
8593
9026
|
},
|
|
8594
9027
|
(span2) => {
|
|
8595
9028
|
try {
|
|
8596
|
-
|
|
9029
|
+
setRequestAttributes7(span2, kwargs, requestType);
|
|
8597
9030
|
const startTime = Date.now();
|
|
8598
9031
|
const response = wrapped.call(instance, ...args);
|
|
8599
9032
|
if (isPromise(response)) {
|
|
@@ -8601,7 +9034,7 @@ function mistralWrapper(tracer, spanName, requestType) {
|
|
|
8601
9034
|
try {
|
|
8602
9035
|
const value = await response;
|
|
8603
9036
|
const endTime2 = Date.now();
|
|
8604
|
-
|
|
9037
|
+
setResponseAttributes7(span2, modelAsDict(value));
|
|
8605
9038
|
span2.setAttribute(
|
|
8606
9039
|
"llm.response.duration",
|
|
8607
9040
|
(endTime2 - startTime) / 1e3
|
|
@@ -8622,7 +9055,7 @@ function mistralWrapper(tracer, spanName, requestType) {
|
|
|
8622
9055
|
})();
|
|
8623
9056
|
}
|
|
8624
9057
|
const endTime = Date.now();
|
|
8625
|
-
|
|
9058
|
+
setResponseAttributes7(span2, modelAsDict(response));
|
|
8626
9059
|
span2.setAttribute(
|
|
8627
9060
|
"llm.response.duration",
|
|
8628
9061
|
(endTime - startTime) / 1e3
|
|
@@ -8663,31 +9096,17 @@ function mistralStreamWrapper(tracer, spanName, requestType) {
|
|
|
8663
9096
|
currentContext
|
|
8664
9097
|
);
|
|
8665
9098
|
try {
|
|
8666
|
-
|
|
9099
|
+
setRequestAttributes7(span2, { ...kwargs, stream: true }, requestType);
|
|
8667
9100
|
const startTime = Date.now();
|
|
8668
9101
|
const response = wrapped.call(instance, ...args);
|
|
8669
|
-
if (isPromise(response)) {
|
|
8670
|
-
|
|
8671
|
-
|
|
8672
|
-
|
|
8673
|
-
|
|
8674
|
-
|
|
8675
|
-
|
|
8676
|
-
|
|
8677
|
-
} catch (error) {
|
|
8678
|
-
NetraLogger.error("netra.instrumentation.mistralai:", error);
|
|
8679
|
-
span2.setStatus({
|
|
8680
|
-
code: SpanStatusCode.ERROR,
|
|
8681
|
-
message: error instanceof Error ? error.message : String(error)
|
|
8682
|
-
});
|
|
8683
|
-
span2.recordException(error);
|
|
8684
|
-
span2.end();
|
|
8685
|
-
throw error;
|
|
8686
|
-
}
|
|
8687
|
-
})();
|
|
8688
|
-
}
|
|
8689
|
-
if (response && typeof response === "object" && Symbol.asyncIterator in response) {
|
|
8690
|
-
return new AsyncStreamingWrapper2(span2, response, startTime, kwargs);
|
|
9102
|
+
if (isPromise(response) || isAsyncIterable(response)) {
|
|
9103
|
+
const collector = new AsyncStreamCollector2(span2, startTime, kwargs);
|
|
9104
|
+
return wrapResponse(response, {
|
|
9105
|
+
withContext: (fn) => fn(),
|
|
9106
|
+
onChunk: (chunk) => collector.processChunk(chunk),
|
|
9107
|
+
onError: (error) => recordSpanError2(span2, error),
|
|
9108
|
+
finalize: (status) => collector.finish(status)
|
|
9109
|
+
});
|
|
8691
9110
|
}
|
|
8692
9111
|
return new StreamingWrapper2(span2, response, startTime, kwargs);
|
|
8693
9112
|
} catch (error) {
|
|
@@ -8837,7 +9256,7 @@ var StreamingWrapper2 = class {
|
|
|
8837
9256
|
finalizeSpan(error) {
|
|
8838
9257
|
const endTime = Date.now();
|
|
8839
9258
|
const duration = (endTime - this.startTime) / 1e3;
|
|
8840
|
-
|
|
9259
|
+
setResponseAttributes7(this.span, this.completeResponse);
|
|
8841
9260
|
this.span.setAttribute("llm.response.duration", duration);
|
|
8842
9261
|
if (error) {
|
|
8843
9262
|
this.span.setStatus({
|
|
@@ -8854,17 +9273,15 @@ var StreamingWrapper2 = class {
|
|
|
8854
9273
|
this.span.end();
|
|
8855
9274
|
}
|
|
8856
9275
|
};
|
|
8857
|
-
var
|
|
8858
|
-
constructor(span2,
|
|
8859
|
-
this.
|
|
8860
|
-
|
|
8861
|
-
|
|
8862
|
-
|
|
8863
|
-
|
|
8864
|
-
|
|
8865
|
-
|
|
8866
|
-
toJSON() {
|
|
8867
|
-
return this.completeResponse;
|
|
9276
|
+
var AsyncStreamCollector2 = class {
|
|
9277
|
+
constructor(span2, startTime, requestKwargs) {
|
|
9278
|
+
this.span = span2;
|
|
9279
|
+
this.startTime = startTime;
|
|
9280
|
+
this.requestKwargs = requestKwargs;
|
|
9281
|
+
this.completeResponse = {
|
|
9282
|
+
choices: [],
|
|
9283
|
+
model: ""
|
|
9284
|
+
};
|
|
8868
9285
|
}
|
|
8869
9286
|
isChat() {
|
|
8870
9287
|
return typeof this.requestKwargs === "object" && this.requestKwargs !== null && "messages" in this.requestKwargs;
|
|
@@ -8879,39 +9296,6 @@ var AsyncStreamingWrapper2 = class {
|
|
|
8879
9296
|
}
|
|
8880
9297
|
}
|
|
8881
9298
|
}
|
|
8882
|
-
[Symbol.asyncIterator]() {
|
|
8883
|
-
return this;
|
|
8884
|
-
}
|
|
8885
|
-
async next() {
|
|
8886
|
-
try {
|
|
8887
|
-
if (!this.iterator) {
|
|
8888
|
-
if (this.response && typeof this.response === "object" && Symbol.asyncIterator in this.response) {
|
|
8889
|
-
this.iterator = this.response[Symbol.asyncIterator]();
|
|
8890
|
-
} else if (this.response && typeof this.response === "object" && Symbol.iterator in this.response) {
|
|
8891
|
-
const syncIterator = this.response[Symbol.iterator]();
|
|
8892
|
-
this.iterator = {
|
|
8893
|
-
async next() {
|
|
8894
|
-
return syncIterator.next();
|
|
8895
|
-
}
|
|
8896
|
-
};
|
|
8897
|
-
} else if (this.response && typeof this.response === "object" && typeof this.response.next === "function") {
|
|
8898
|
-
this.iterator = this.response;
|
|
8899
|
-
} else {
|
|
8900
|
-
throw new Error("Response is not iterable");
|
|
8901
|
-
}
|
|
8902
|
-
}
|
|
8903
|
-
const result = await this.iterator.next();
|
|
8904
|
-
if (result.done) {
|
|
8905
|
-
this.finalizeSpan();
|
|
8906
|
-
return result;
|
|
8907
|
-
}
|
|
8908
|
-
this.processChunk(result.value);
|
|
8909
|
-
return result;
|
|
8910
|
-
} catch (error) {
|
|
8911
|
-
this.finalizeSpan(error);
|
|
8912
|
-
throw error;
|
|
8913
|
-
}
|
|
8914
|
-
}
|
|
8915
9299
|
processChunk(chunk) {
|
|
8916
9300
|
const chunkDict = modelAsDict(chunk);
|
|
8917
9301
|
const choices = this.completeResponse.choices;
|
|
@@ -8980,23 +9364,12 @@ var AsyncStreamingWrapper2 = class {
|
|
|
8980
9364
|
}
|
|
8981
9365
|
this.span.addEvent("llm.content.completion.chunk");
|
|
8982
9366
|
}
|
|
8983
|
-
|
|
9367
|
+
finish(status) {
|
|
8984
9368
|
const endTime = Date.now();
|
|
8985
9369
|
const duration = (endTime - this.startTime) / 1e3;
|
|
8986
|
-
|
|
9370
|
+
setResponseAttributes7(this.span, this.completeResponse);
|
|
8987
9371
|
this.span.setAttribute("llm.response.duration", duration);
|
|
8988
|
-
if (
|
|
8989
|
-
this.span.setStatus({
|
|
8990
|
-
code: SpanStatusCode.ERROR,
|
|
8991
|
-
message: error instanceof Error ? error.message : String(error)
|
|
8992
|
-
});
|
|
8993
|
-
try {
|
|
8994
|
-
this.span.recordException(error);
|
|
8995
|
-
} catch {
|
|
8996
|
-
}
|
|
8997
|
-
} else {
|
|
8998
|
-
this.span.setStatus({ code: SpanStatusCode.OK });
|
|
8999
|
-
}
|
|
9372
|
+
if (status === "ok") this.span.setStatus({ code: SpanStatusCode.OK });
|
|
9000
9373
|
this.span.end();
|
|
9001
9374
|
}
|
|
9002
9375
|
};
|
|
@@ -9416,42 +9789,34 @@ var mistralAIInstrumentor = new NetraMistralAIInstrumentor();
|
|
|
9416
9789
|
|
|
9417
9790
|
// src/instrumentation/openai/version.ts
|
|
9418
9791
|
var __version__7 = "1.0.0";
|
|
9419
|
-
|
|
9420
|
-
// src/instrumentation/openai/utils.ts
|
|
9421
|
-
function setRequestAttributes7(span2, kwargs, requestType) {
|
|
9422
|
-
if (!span2.isRecording()) return;
|
|
9423
|
-
setRequestAttributes(span2, kwargs, requestType, "openai");
|
|
9424
|
-
if (kwargs.dimensions !== void 0) {
|
|
9425
|
-
span2.setAttribute("gen_ai.request.dimensions", Number(kwargs.dimensions));
|
|
9426
|
-
}
|
|
9427
|
-
}
|
|
9428
|
-
function setResponseAttributes7(span2, response) {
|
|
9429
|
-
if (!span2.isRecording()) return;
|
|
9430
|
-
setResponseAttributes(span2, response);
|
|
9431
|
-
}
|
|
9432
|
-
|
|
9433
|
-
// src/instrumentation/openai/wrappers.ts
|
|
9434
9792
|
var SPAN_NAMES3 = {
|
|
9435
9793
|
chat: "openai.chat",
|
|
9436
9794
|
embedding: "openai.embedding",
|
|
9437
|
-
response: "openai.response"
|
|
9795
|
+
response: "openai.response",
|
|
9796
|
+
decision: "openai.decision"
|
|
9438
9797
|
};
|
|
9439
9798
|
var STREAMING_TYPES = /* @__PURE__ */ new Set(["chat", "response"]);
|
|
9440
|
-
function
|
|
9799
|
+
function recordSpanError3(span2, error) {
|
|
9441
9800
|
span2.setStatus({
|
|
9442
9801
|
code: SpanStatusCode.ERROR,
|
|
9443
9802
|
message: error instanceof Error ? error.message : String(error)
|
|
9444
9803
|
});
|
|
9445
9804
|
span2.recordException(error);
|
|
9805
|
+
}
|
|
9806
|
+
function handleSpanError(span2, error) {
|
|
9807
|
+
recordSpanError3(span2, error);
|
|
9446
9808
|
span2.end();
|
|
9447
9809
|
}
|
|
9448
9810
|
function setSpanRequestContext(span2, kwargs, requestType) {
|
|
9449
|
-
|
|
9811
|
+
setRequestAttributes4(span2, kwargs, requestType);
|
|
9450
9812
|
}
|
|
9451
|
-
function
|
|
9452
|
-
|
|
9813
|
+
function setSpanSuccess(span2, response, startTime) {
|
|
9814
|
+
setResponseAttributes4(span2, response);
|
|
9453
9815
|
span2.setAttribute("llm.response.duration", (Date.now() - startTime) / 1e3);
|
|
9454
9816
|
span2.setStatus({ code: SpanStatusCode.OK });
|
|
9817
|
+
}
|
|
9818
|
+
function finalizeSpanSuccess(span2, response, startTime) {
|
|
9819
|
+
setSpanSuccess(span2, response, startTime);
|
|
9455
9820
|
span2.end();
|
|
9456
9821
|
}
|
|
9457
9822
|
var BaseStreamHandler = class {
|
|
@@ -9572,68 +9937,36 @@ var StreamingWrapper3 = class extends BaseStreamHandler {
|
|
|
9572
9937
|
throw new Error("Response is not iterable");
|
|
9573
9938
|
}
|
|
9574
9939
|
};
|
|
9575
|
-
var
|
|
9576
|
-
|
|
9577
|
-
|
|
9578
|
-
this.iterator = null;
|
|
9579
|
-
defineHidden(this, "response", response);
|
|
9940
|
+
var AsyncStreamCollector3 = class extends BaseStreamHandler {
|
|
9941
|
+
collect(chunk) {
|
|
9942
|
+
this.processChunk(chunk);
|
|
9580
9943
|
}
|
|
9581
|
-
|
|
9582
|
-
|
|
9583
|
-
|
|
9584
|
-
|
|
9585
|
-
try {
|
|
9586
|
-
if (!this.iterator) {
|
|
9587
|
-
this.iterator = this.resolveIterator();
|
|
9588
|
-
}
|
|
9589
|
-
const result = await this.iterator.next();
|
|
9590
|
-
if (result.done) {
|
|
9591
|
-
this.finalizeSpan(SpanStatusCode.OK);
|
|
9592
|
-
} else {
|
|
9593
|
-
this.processChunk(result.value);
|
|
9594
|
-
}
|
|
9595
|
-
return result;
|
|
9596
|
-
} catch (error) {
|
|
9597
|
-
this.finalizeSpan(SpanStatusCode.ERROR);
|
|
9598
|
-
throw error;
|
|
9599
|
-
}
|
|
9600
|
-
}
|
|
9601
|
-
resolveIterator() {
|
|
9602
|
-
if (!this.response || typeof this.response !== "object") {
|
|
9603
|
-
throw new Error("Response is not iterable");
|
|
9604
|
-
}
|
|
9605
|
-
if (Symbol.asyncIterator in this.response) {
|
|
9606
|
-
return this.response[Symbol.asyncIterator]();
|
|
9607
|
-
}
|
|
9608
|
-
if (Symbol.iterator in this.response) {
|
|
9609
|
-
const syncIter = this.response[Symbol.iterator]();
|
|
9610
|
-
return {
|
|
9611
|
-
async next() {
|
|
9612
|
-
return syncIter.next();
|
|
9613
|
-
}
|
|
9614
|
-
};
|
|
9615
|
-
}
|
|
9616
|
-
if (typeof this.response.next === "function") {
|
|
9617
|
-
return this.response;
|
|
9944
|
+
finish(status) {
|
|
9945
|
+
if (status === "ok") {
|
|
9946
|
+
this.finalizeSpan(SpanStatusCode.OK);
|
|
9947
|
+
return;
|
|
9618
9948
|
}
|
|
9619
|
-
|
|
9949
|
+
this.span.setAttribute(
|
|
9950
|
+
"llm.response.duration",
|
|
9951
|
+
(Date.now() - this.startTime) / 1e3
|
|
9952
|
+
);
|
|
9953
|
+
this.span.end();
|
|
9620
9954
|
}
|
|
9621
9955
|
};
|
|
9622
9956
|
function executeStreaming(span2, ctx, kwargs, requestType, call) {
|
|
9623
9957
|
const startTime = Date.now();
|
|
9624
9958
|
try {
|
|
9625
9959
|
setSpanRequestContext(span2, kwargs, requestType);
|
|
9626
|
-
const
|
|
9627
|
-
|
|
9628
|
-
|
|
9629
|
-
|
|
9630
|
-
|
|
9631
|
-
|
|
9632
|
-
|
|
9633
|
-
|
|
9634
|
-
|
|
9635
|
-
|
|
9636
|
-
})();
|
|
9960
|
+
const spanContext = trace.setSpan(ctx, span2);
|
|
9961
|
+
const response = context.with(spanContext, call);
|
|
9962
|
+
if (isPromise(response) || isAsyncIterable(response)) {
|
|
9963
|
+
const collector = new AsyncStreamCollector3(span2, startTime, kwargs);
|
|
9964
|
+
return wrapResponse(response, {
|
|
9965
|
+
withContext: (fn) => context.with(spanContext, fn),
|
|
9966
|
+
onChunk: (chunk) => collector.collect(chunk),
|
|
9967
|
+
onError: (error) => recordSpanError3(span2, error),
|
|
9968
|
+
finalize: (status) => collector.finish(status)
|
|
9969
|
+
}, { deriveAPIPromise: true });
|
|
9637
9970
|
}
|
|
9638
9971
|
return new StreamingWrapper3(span2, response, startTime, kwargs);
|
|
9639
9972
|
} catch (error) {
|
|
@@ -9647,16 +9980,12 @@ function executeNonStreaming(span2, kwargs, requestType, call) {
|
|
|
9647
9980
|
setSpanRequestContext(span2, kwargs, requestType);
|
|
9648
9981
|
const result = call();
|
|
9649
9982
|
if (isPromise(result)) {
|
|
9650
|
-
return result
|
|
9651
|
-
(
|
|
9652
|
-
|
|
9653
|
-
|
|
9654
|
-
|
|
9655
|
-
|
|
9656
|
-
handleSpanError(span2, error);
|
|
9657
|
-
throw error;
|
|
9658
|
-
}
|
|
9659
|
-
);
|
|
9983
|
+
return wrapPromise(result, {
|
|
9984
|
+
withContext: (fn) => fn(),
|
|
9985
|
+
onSuccess: (value) => setSpanSuccess(span2, modelAsDict(value), startTime),
|
|
9986
|
+
onError: (error) => recordSpanError3(span2, error),
|
|
9987
|
+
finalize: () => span2.end()
|
|
9988
|
+
}, { deriveAPIPromise: true });
|
|
9660
9989
|
}
|
|
9661
9990
|
finalizeSpanSuccess(span2, modelAsDict(result), startTime);
|
|
9662
9991
|
return result;
|
|
@@ -9690,6 +10019,7 @@ function openAIWrapper(tracer, requestType) {
|
|
|
9690
10019
|
var chatWrapper6 = (tracer) => openAIWrapper(tracer, "chat");
|
|
9691
10020
|
var embeddingsWrapper4 = (tracer) => openAIWrapper(tracer, "embedding");
|
|
9692
10021
|
var responsesWrapper = (tracer) => openAIWrapper(tracer, "response");
|
|
10022
|
+
var decisionsWrapper2 = (tracer) => openAIWrapper(tracer, "decision");
|
|
9693
10023
|
|
|
9694
10024
|
// src/instrumentation/openai/index.ts
|
|
9695
10025
|
var INSTRUMENTATION_NAME5 = "netra.instrumentation.openai";
|
|
@@ -9731,6 +10061,14 @@ var PATCH_TARGETS = [
|
|
|
9731
10061
|
getPrototype: (O) => O.Responses?.prototype,
|
|
9732
10062
|
wrapperFactory: responsesWrapper,
|
|
9733
10063
|
optional: true
|
|
10064
|
+
},
|
|
10065
|
+
{
|
|
10066
|
+
// The Decisions API only exists in openai >= 7.30.0, so its absence on
|
|
10067
|
+
// older installs is expected and must not be reported as a failure.
|
|
10068
|
+
key: "decisions.create",
|
|
10069
|
+
getPrototype: (O) => O.Decisions?.prototype,
|
|
10070
|
+
wrapperFactory: decisionsWrapper2,
|
|
10071
|
+
optional: true
|
|
9734
10072
|
}
|
|
9735
10073
|
];
|
|
9736
10074
|
var _NetraOpenAIInstrumentor = class _NetraOpenAIInstrumentor {
|
|
@@ -11077,6 +11415,292 @@ var NetraTypeORMInstrumentor = class {
|
|
|
11077
11415
|
};
|
|
11078
11416
|
var typeORMInstrumentor = new NetraTypeORMInstrumentor();
|
|
11079
11417
|
|
|
11418
|
+
// src/instrumentation/typesafe/version.ts
|
|
11419
|
+
var __version__10 = "1.0.0";
|
|
11420
|
+
|
|
11421
|
+
// src/instrumentation/typesafe/utils.ts
|
|
11422
|
+
var GEN_AI_SYSTEM_TYPESAFE = "TypeSafe";
|
|
11423
|
+
var TYPESAFE_REQUEST_TYPE = "decision";
|
|
11424
|
+
var NETRA_SPAN_TYPE_ATTR2 = `${Config.LIBRARY_NAME}.span.type`;
|
|
11425
|
+
var ERROR_TYPE_ATTR = "error.type";
|
|
11426
|
+
var INPUT_ATTRIBUTE2 = "input";
|
|
11427
|
+
var OUTPUT_ATTRIBUTE2 = "output";
|
|
11428
|
+
var STATE_ROLE = "user";
|
|
11429
|
+
var QUESTIONS_ROLE = "user";
|
|
11430
|
+
var ANSWERS_ROLE = "assistant";
|
|
11431
|
+
var QUESTIONS_MAX_SHARE = 2;
|
|
11432
|
+
function mappingEntryWithin(role, mapping, maxLen) {
|
|
11433
|
+
let available = maxLen - JSON.stringify({ role, content: "{}" }).length;
|
|
11434
|
+
const kept = [];
|
|
11435
|
+
for (const [key, value] of Object.entries(mapping)) {
|
|
11436
|
+
const encoded = JSON.stringify(key) + ":" + toJson(value);
|
|
11437
|
+
const escapedLen = JSON.stringify(encoded).length - '""'.length;
|
|
11438
|
+
const cost = escapedLen + (kept.length > 0 ? JSON_ITEM_SEPARATOR.length : 0);
|
|
11439
|
+
if (cost > available) break;
|
|
11440
|
+
kept.push(encoded);
|
|
11441
|
+
available -= cost;
|
|
11442
|
+
}
|
|
11443
|
+
if (kept.length === 0) return void 0;
|
|
11444
|
+
return JSON.stringify({ role, content: "{" + kept.join(JSON_ITEM_SEPARATOR) + "}" });
|
|
11445
|
+
}
|
|
11446
|
+
function stateAsText(state) {
|
|
11447
|
+
if (typeof state === "string") return state;
|
|
11448
|
+
const toJSON = state?.toJSON;
|
|
11449
|
+
if (typeof toJSON === "function") {
|
|
11450
|
+
const serialised = toJSON.call(state);
|
|
11451
|
+
if (typeof serialised === "string") return serialised;
|
|
11452
|
+
}
|
|
11453
|
+
return toJson(state);
|
|
11454
|
+
}
|
|
11455
|
+
function extractRequest(args) {
|
|
11456
|
+
const request = args[0];
|
|
11457
|
+
return isDict(request) ? request : {};
|
|
11458
|
+
}
|
|
11459
|
+
function resolveRequestModel(instance, request) {
|
|
11460
|
+
if (request.model) return String(request.model);
|
|
11461
|
+
const defaultModel = instance?.defaultModel;
|
|
11462
|
+
return defaultModel ? String(defaultModel) : void 0;
|
|
11463
|
+
}
|
|
11464
|
+
function buildInput(state, questions) {
|
|
11465
|
+
const maxLen = attributeMaxSize();
|
|
11466
|
+
let remaining = maxLen - "[]".length;
|
|
11467
|
+
let questionsEntry;
|
|
11468
|
+
if (isDict(questions) && Object.keys(questions).length > 0) {
|
|
11469
|
+
questionsEntry = mappingEntryWithin(
|
|
11470
|
+
QUESTIONS_ROLE,
|
|
11471
|
+
questions,
|
|
11472
|
+
Math.floor(maxLen / QUESTIONS_MAX_SHARE) - "[]".length
|
|
11473
|
+
);
|
|
11474
|
+
if (questionsEntry) remaining -= questionsEntry.length + JSON_ITEM_SEPARATOR.length;
|
|
11475
|
+
}
|
|
11476
|
+
const entries2 = [];
|
|
11477
|
+
if (state != null && state !== "") {
|
|
11478
|
+
const text = stateAsText(state).slice(0, Math.max(remaining, 0));
|
|
11479
|
+
const stateEntry = encodeEntryWithin({ role: STATE_ROLE, content: text }, remaining);
|
|
11480
|
+
if (stateEntry) entries2.push(stateEntry);
|
|
11481
|
+
}
|
|
11482
|
+
if (questionsEntry) entries2.push(questionsEntry);
|
|
11483
|
+
return entries2.length > 0 ? joinJsonArray(entries2) : void 0;
|
|
11484
|
+
}
|
|
11485
|
+
function setRequestAttributes8(span2, instance, args) {
|
|
11486
|
+
if (!span2.isRecording()) return;
|
|
11487
|
+
const request = extractRequest(args);
|
|
11488
|
+
try {
|
|
11489
|
+
span2.setAttribute(NETRA_SPAN_TYPE_ATTR2, "GENERATION" /* GENERATION */);
|
|
11490
|
+
const model = resolveRequestModel(instance, request);
|
|
11491
|
+
if (model) span2.setAttribute(SpanAttributes2.LLM_REQUEST_MODEL, model);
|
|
11492
|
+
} catch (error) {
|
|
11493
|
+
NetraLogger.debug("Failed to set request attributes for TypeSafe span:", error);
|
|
11494
|
+
}
|
|
11495
|
+
if (!isTraceContentEnabled()) return;
|
|
11496
|
+
try {
|
|
11497
|
+
const inputJson = buildInput(request.state, request.questions);
|
|
11498
|
+
if (inputJson !== void 0) span2.setAttribute(INPUT_ATTRIBUTE2, inputJson);
|
|
11499
|
+
} catch (error) {
|
|
11500
|
+
NetraLogger.warn("Failed to record TypeSafe input:", error);
|
|
11501
|
+
}
|
|
11502
|
+
}
|
|
11503
|
+
function buildOutput(response) {
|
|
11504
|
+
let answers = response.answers;
|
|
11505
|
+
if (!isDict(answers)) {
|
|
11506
|
+
const { model: _model, usage: _usage, ...rest } = response;
|
|
11507
|
+
answers = rest;
|
|
11508
|
+
}
|
|
11509
|
+
const entry = mappingEntryWithin(
|
|
11510
|
+
ANSWERS_ROLE,
|
|
11511
|
+
answers,
|
|
11512
|
+
attributeMaxSize() - "[]".length
|
|
11513
|
+
);
|
|
11514
|
+
return entry ? joinJsonArray([entry]) : void 0;
|
|
11515
|
+
}
|
|
11516
|
+
function setResponseAttributes9(span2, response) {
|
|
11517
|
+
if (!span2.isRecording()) return;
|
|
11518
|
+
try {
|
|
11519
|
+
const responseDict = modelAsDict(response);
|
|
11520
|
+
if (responseDict.model) {
|
|
11521
|
+
span2.setAttribute(SpanAttributes2.LLM_RESPONSE_MODEL, String(responseDict.model));
|
|
11522
|
+
}
|
|
11523
|
+
const usage = responseDict.usage;
|
|
11524
|
+
if (isDict(usage)) {
|
|
11525
|
+
const inputTokens = usage.input_tokens;
|
|
11526
|
+
const outputTokens = usage.output_tokens;
|
|
11527
|
+
if (Number.isInteger(inputTokens)) {
|
|
11528
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, inputTokens);
|
|
11529
|
+
}
|
|
11530
|
+
if (Number.isInteger(outputTokens)) {
|
|
11531
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, outputTokens);
|
|
11532
|
+
}
|
|
11533
|
+
if (Number.isInteger(inputTokens) && Number.isInteger(outputTokens)) {
|
|
11534
|
+
span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, inputTokens + outputTokens);
|
|
11535
|
+
}
|
|
11536
|
+
}
|
|
11537
|
+
if (isTraceContentEnabled()) {
|
|
11538
|
+
const outputJson = buildOutput(responseDict);
|
|
11539
|
+
if (outputJson !== void 0) span2.setAttribute(OUTPUT_ATTRIBUTE2, outputJson);
|
|
11540
|
+
}
|
|
11541
|
+
} catch (error) {
|
|
11542
|
+
NetraLogger.warn("Failed to record TypeSafe output:", error);
|
|
11543
|
+
}
|
|
11544
|
+
}
|
|
11545
|
+
|
|
11546
|
+
// src/instrumentation/typesafe/wrappers.ts
|
|
11547
|
+
var SYSTEM_ONE_SPAN_NAME = "typesafe.system_one";
|
|
11548
|
+
var LLM_RESPONSE_DURATION = "llm.response.duration";
|
|
11549
|
+
var SPAN_OPTIONS = {
|
|
11550
|
+
kind: SpanKind.CLIENT,
|
|
11551
|
+
attributes: {
|
|
11552
|
+
[SpanAttributes2.LLM_SYSTEM]: GEN_AI_SYSTEM_TYPESAFE,
|
|
11553
|
+
[SpanAttributes2.LLM_REQUEST_TYPE]: TYPESAFE_REQUEST_TYPE
|
|
11554
|
+
}
|
|
11555
|
+
};
|
|
11556
|
+
function recordSuccess(span2, response, startTime) {
|
|
11557
|
+
span2.setAttribute(LLM_RESPONSE_DURATION, (Date.now() - startTime) / 1e3);
|
|
11558
|
+
setResponseAttributes9(span2, response);
|
|
11559
|
+
span2.setStatus({ code: SpanStatusCode.OK });
|
|
11560
|
+
}
|
|
11561
|
+
function recordFailure(span2, error) {
|
|
11562
|
+
const errorType = error?.constructor?.name;
|
|
11563
|
+
span2.setAttribute(
|
|
11564
|
+
ERROR_TYPE_ATTR,
|
|
11565
|
+
error instanceof Error && typeof errorType === "string" ? errorType : typeof error
|
|
11566
|
+
);
|
|
11567
|
+
span2.recordException(error instanceof Error ? error : String(error));
|
|
11568
|
+
span2.setStatus({
|
|
11569
|
+
code: SpanStatusCode.ERROR,
|
|
11570
|
+
message: error instanceof Error ? error.message : String(error)
|
|
11571
|
+
});
|
|
11572
|
+
}
|
|
11573
|
+
function systemOneWrapper(tracer) {
|
|
11574
|
+
return (wrapped, instance, args) => {
|
|
11575
|
+
if (shouldSuppressInstrumentation()) {
|
|
11576
|
+
return wrapped.call(instance, ...args);
|
|
11577
|
+
}
|
|
11578
|
+
return tracer.startActiveSpan(SYSTEM_ONE_SPAN_NAME, SPAN_OPTIONS, (span2) => {
|
|
11579
|
+
const startTime = Date.now();
|
|
11580
|
+
setRequestAttributes8(span2, instance, args);
|
|
11581
|
+
let result;
|
|
11582
|
+
try {
|
|
11583
|
+
result = wrapped.call(instance, ...args);
|
|
11584
|
+
} catch (error) {
|
|
11585
|
+
recordFailure(span2, error);
|
|
11586
|
+
span2.end();
|
|
11587
|
+
throw error;
|
|
11588
|
+
}
|
|
11589
|
+
if (!isPromise(result)) {
|
|
11590
|
+
recordSuccess(span2, result, startTime);
|
|
11591
|
+
span2.end();
|
|
11592
|
+
return result;
|
|
11593
|
+
}
|
|
11594
|
+
return wrapPromise(
|
|
11595
|
+
result,
|
|
11596
|
+
{
|
|
11597
|
+
withContext: (fn) => fn(),
|
|
11598
|
+
onSuccess: (value) => recordSuccess(span2, value, startTime),
|
|
11599
|
+
onError: (error) => recordFailure(span2, error),
|
|
11600
|
+
finalize: () => span2.end()
|
|
11601
|
+
},
|
|
11602
|
+
{ deriveAPIPromise: true }
|
|
11603
|
+
);
|
|
11604
|
+
});
|
|
11605
|
+
};
|
|
11606
|
+
}
|
|
11607
|
+
|
|
11608
|
+
// src/instrumentation/typesafe/index.ts
|
|
11609
|
+
var INSTRUMENTATION_NAME8 = "netra.instrumentation.typesafe";
|
|
11610
|
+
var SUPPORTED_VERSIONS2 = ["@typesafe-ai/sdk >= 0.7.0"];
|
|
11611
|
+
var MODULE_NAME2 = "@typesafe-ai/sdk";
|
|
11612
|
+
var METHOD = "systemOne";
|
|
11613
|
+
var typeSafeClientClasses = [];
|
|
11614
|
+
async function resolveTypeSafeClients() {
|
|
11615
|
+
if (typeSafeClientClasses.length > 0) return typeSafeClientClasses;
|
|
11616
|
+
try {
|
|
11617
|
+
const mod = await import('@typesafe-ai/sdk');
|
|
11618
|
+
if (mod?.TypeSafeClient) typeSafeClientClasses.push(mod.TypeSafeClient);
|
|
11619
|
+
} catch {
|
|
11620
|
+
NetraLogger.debug("TypeSafe SDK ESM module not available");
|
|
11621
|
+
}
|
|
11622
|
+
try {
|
|
11623
|
+
const req = createRequire(import.meta.url);
|
|
11624
|
+
const cjsClass = req(MODULE_NAME2)?.TypeSafeClient;
|
|
11625
|
+
if (cjsClass && !typeSafeClientClasses.includes(cjsClass)) {
|
|
11626
|
+
typeSafeClientClasses.push(cjsClass);
|
|
11627
|
+
}
|
|
11628
|
+
} catch {
|
|
11629
|
+
NetraLogger.debug("TypeSafe SDK CJS module not available");
|
|
11630
|
+
}
|
|
11631
|
+
return typeSafeClientClasses;
|
|
11632
|
+
}
|
|
11633
|
+
var _NetraTypeSafeInstrumentor = class _NetraTypeSafeInstrumentor {
|
|
11634
|
+
constructor() {
|
|
11635
|
+
this.tracer = null;
|
|
11636
|
+
this.originalMethods = /* @__PURE__ */ new Map();
|
|
11637
|
+
}
|
|
11638
|
+
instrumentationDependencies() {
|
|
11639
|
+
return [...SUPPORTED_VERSIONS2];
|
|
11640
|
+
}
|
|
11641
|
+
isInstrumented() {
|
|
11642
|
+
return _NetraTypeSafeInstrumentor._isInstrumented;
|
|
11643
|
+
}
|
|
11644
|
+
async instrument(options = {}) {
|
|
11645
|
+
if (this.isInstrumented()) {
|
|
11646
|
+
NetraLogger.warn("TypeSafe is already instrumented");
|
|
11647
|
+
return this;
|
|
11648
|
+
}
|
|
11649
|
+
try {
|
|
11650
|
+
const provider = options.tracerProvider;
|
|
11651
|
+
this.tracer = provider ? provider.getTracer(INSTRUMENTATION_NAME8, __version__10) : trace.getTracer(INSTRUMENTATION_NAME8, __version__10);
|
|
11652
|
+
} catch (error) {
|
|
11653
|
+
NetraLogger.error(`Failed to initialize tracer: ${error}`);
|
|
11654
|
+
return this;
|
|
11655
|
+
}
|
|
11656
|
+
const clientClasses = await resolveTypeSafeClients();
|
|
11657
|
+
if (clientClasses.length === 0) {
|
|
11658
|
+
NetraLogger.debug("TypeSafe SDK not installed; skipping instrumentation");
|
|
11659
|
+
return this;
|
|
11660
|
+
}
|
|
11661
|
+
clientClasses.forEach((clientClass) => this.patch(clientClass));
|
|
11662
|
+
_NetraTypeSafeInstrumentor._isInstrumented = true;
|
|
11663
|
+
return this;
|
|
11664
|
+
}
|
|
11665
|
+
async uninstrument() {
|
|
11666
|
+
if (!this.isInstrumented()) {
|
|
11667
|
+
NetraLogger.warn("TypeSafe is not instrumented");
|
|
11668
|
+
return;
|
|
11669
|
+
}
|
|
11670
|
+
for (const [proto, original] of this.originalMethods) {
|
|
11671
|
+
try {
|
|
11672
|
+
proto[METHOD] = original;
|
|
11673
|
+
} catch (error) {
|
|
11674
|
+
NetraLogger.error(`Failed to uninstrument TypeSafe ${METHOD}: ${error}`);
|
|
11675
|
+
}
|
|
11676
|
+
}
|
|
11677
|
+
this.originalMethods.clear();
|
|
11678
|
+
typeSafeClientClasses.length = 0;
|
|
11679
|
+
_NetraTypeSafeInstrumentor._isInstrumented = false;
|
|
11680
|
+
}
|
|
11681
|
+
patch(clientClass) {
|
|
11682
|
+
if (!this.tracer) return;
|
|
11683
|
+
const proto = clientClass?.prototype;
|
|
11684
|
+
const original = proto?.[METHOD];
|
|
11685
|
+
if (typeof original !== "function") {
|
|
11686
|
+
NetraLogger.error(`Failed to find TypeSafe method to patch: TypeSafeClient.${METHOD}`);
|
|
11687
|
+
return;
|
|
11688
|
+
}
|
|
11689
|
+
try {
|
|
11690
|
+
const wrapper = systemOneWrapper(this.tracer);
|
|
11691
|
+
this.originalMethods.set(proto, original);
|
|
11692
|
+
proto[METHOD] = function(...args) {
|
|
11693
|
+
return wrapper(original, this, args);
|
|
11694
|
+
};
|
|
11695
|
+
} catch (error) {
|
|
11696
|
+
NetraLogger.error(`Failed to instrument TypeSafe ${METHOD}: ${error}`);
|
|
11697
|
+
}
|
|
11698
|
+
}
|
|
11699
|
+
};
|
|
11700
|
+
_NetraTypeSafeInstrumentor._isInstrumented = false;
|
|
11701
|
+
var NetraTypeSafeInstrumentor = _NetraTypeSafeInstrumentor;
|
|
11702
|
+
var typeSafeInstrumentor = new NetraTypeSafeInstrumentor();
|
|
11703
|
+
|
|
11080
11704
|
// src/exporters/utils.ts
|
|
11081
11705
|
var trialBlockedAt = null;
|
|
11082
11706
|
var blockedTraceIds = /* @__PURE__ */ new Set();
|
|
@@ -11789,7 +12413,8 @@ function initInstrumentations(config, instruments, blockInstruments, rootInstrum
|
|
|
11789
12413
|
googleGenAI: false,
|
|
11790
12414
|
googleGenerativeAI: false,
|
|
11791
12415
|
anthropic: false,
|
|
11792
|
-
openAiAgents: false
|
|
12416
|
+
openAiAgents: false,
|
|
12417
|
+
typesafe: false
|
|
11793
12418
|
};
|
|
11794
12419
|
const resolved = enableAll ? new Set(Object.values(NetraInstruments).filter((v) => v !== "__all__" /* ALL */)) : instruments && instruments.size > 0 ? instruments : DEFAULT_INSTRUMENTS;
|
|
11795
12420
|
instrumentModules.google_vertexai = false;
|
|
@@ -11844,6 +12469,9 @@ function initInstrumentations(config, instruments, blockInstruments, rootInstrum
|
|
|
11844
12469
|
if (resolved.has("openai_agents" /* OPENAI_AGENTS */)) {
|
|
11845
12470
|
customInstrumentModules.openAiAgents = true;
|
|
11846
12471
|
}
|
|
12472
|
+
if (resolved.has("typesafe" /* TYPESAFE */)) {
|
|
12473
|
+
customInstrumentModules.typesafe = true;
|
|
12474
|
+
}
|
|
11847
12475
|
if (blockInstruments && blockInstruments.size > 0) {
|
|
11848
12476
|
const blockAll = blockInstruments.has("__all__" /* ALL */);
|
|
11849
12477
|
if (blockAll || blockInstruments.has("openai" /* OPENAI */)) customInstrumentModules.openai = false;
|
|
@@ -11854,6 +12482,7 @@ function initInstrumentations(config, instruments, blockInstruments, rootInstrum
|
|
|
11854
12482
|
if (blockAll || blockInstruments.has("google_generative_ai" /* GOOGLE_GENERATIVE_AI */)) customInstrumentModules.googleGenerativeAI = false;
|
|
11855
12483
|
if (blockAll || blockInstruments.has("anthropic" /* ANTHROPIC */)) customInstrumentModules.anthropic = false;
|
|
11856
12484
|
if (blockAll || blockInstruments.has("openai_agents" /* OPENAI_AGENTS */)) customInstrumentModules.openAiAgents = false;
|
|
12485
|
+
if (blockAll || blockInstruments.has("typesafe" /* TYPESAFE */)) customInstrumentModules.typesafe = false;
|
|
11857
12486
|
if (blockAll || blockInstruments.has("vertexai" /* VERTEX_AI */)) instrumentModules.google_vertexai = false;
|
|
11858
12487
|
if (blockAll || blockInstruments.has("langchain" /* LANGCHAIN */)) instrumentModules.langchain = false;
|
|
11859
12488
|
if (blockAll || blockInstruments.has("llama_index" /* LLAMA_INDEX */)) instrumentModules.llamaIndex = false;
|
|
@@ -11988,6 +12617,14 @@ async function initCustomInstrumentationsAsync(config, tracerProvider, customIns
|
|
|
11988
12617
|
NetraLogger.debug("Failed to initialize custom Anthropic instrumentation:", e);
|
|
11989
12618
|
}
|
|
11990
12619
|
}
|
|
12620
|
+
if (customInstrumentModules.typesafe) {
|
|
12621
|
+
try {
|
|
12622
|
+
await typeSafeInstrumentor.instrument({ tracerProvider });
|
|
12623
|
+
NetraLogger.debug("Custom TypeSafe instrumentation enabled");
|
|
12624
|
+
} catch (e) {
|
|
12625
|
+
NetraLogger.debug("Failed to initialize custom TypeSafe instrumentation:", e);
|
|
12626
|
+
}
|
|
12627
|
+
}
|
|
11991
12628
|
if (customInstrumentModules.openAiAgents && !blockInstruments?.has("openai_agents" /* OPENAI_AGENTS */)) {
|
|
11992
12629
|
try {
|
|
11993
12630
|
await openaiAgentsInstrumentor.instrument({ tracerProvider });
|
|
@@ -12180,6 +12817,14 @@ async function uninstrumentAll() {
|
|
|
12180
12817
|
} catch (e) {
|
|
12181
12818
|
NetraLogger.debug("Failed to uninstrument Groq:", e);
|
|
12182
12819
|
}
|
|
12820
|
+
try {
|
|
12821
|
+
if (typeSafeInstrumentor.isInstrumented()) {
|
|
12822
|
+
await typeSafeInstrumentor.uninstrument();
|
|
12823
|
+
NetraLogger.debug("Custom TypeSafe instrumentation disabled");
|
|
12824
|
+
}
|
|
12825
|
+
} catch (e) {
|
|
12826
|
+
NetraLogger.debug("Failed to uninstrument TypeSafe:", e);
|
|
12827
|
+
}
|
|
12183
12828
|
try {
|
|
12184
12829
|
if (anthropicInstrumentor.isInstrumented()) {
|
|
12185
12830
|
anthropicInstrumentor.uninstrument();
|
|
@@ -13393,7 +14038,7 @@ var Simulation = class {
|
|
|
13393
14038
|
}
|
|
13394
14039
|
}
|
|
13395
14040
|
};
|
|
13396
|
-
var
|
|
14041
|
+
var Tracer20 = class {
|
|
13397
14042
|
constructor(cfg, effectiveProvider) {
|
|
13398
14043
|
if (effectiveProvider && typeof effectiveProvider.getTracer === "function") {
|
|
13399
14044
|
this.tracer = effectiveProvider.getTracer(Config.LIBRARY_NAME, Config.LIBRARY_VERSION);
|
|
@@ -13611,7 +14256,7 @@ var _Netra = class _Netra {
|
|
|
13611
14256
|
config.blockInstruments,
|
|
13612
14257
|
config.rootInstruments
|
|
13613
14258
|
);
|
|
13614
|
-
const tracer = new
|
|
14259
|
+
const tracer = new Tracer20(cfg, effectiveProvider);
|
|
13615
14260
|
this._tracer = tracer.tracer;
|
|
13616
14261
|
try {
|
|
13617
14262
|
this.usage = new Usage(cfg);
|