neatlogs 1.1.2 → 1.1.5
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/browser.cjs +11 -11
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +15 -15
- package/dist/browser.mjs +11 -11
- package/dist/browser.mjs.map +1 -1
- package/dist/google-genai.cjs +640 -0
- package/dist/google-genai.cjs.map +1 -0
- package/dist/google-genai.d.ts +42 -0
- package/dist/google-genai.mjs +622 -0
- package/dist/google-genai.mjs.map +1 -0
- package/dist/index.cjs +746 -346
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +745 -348
- package/dist/index.mjs.map +1 -1
- package/dist/opencode-plugin.cjs +1 -1
- package/dist/opencode-plugin.cjs.map +1 -1
- package/dist/opencode-plugin.mjs +1 -1
- package/dist/opencode-plugin.mjs.map +1 -1
- package/package.json +12 -1
package/dist/index.cjs
CHANGED
|
@@ -66,7 +66,8 @@ __export(index_exports, {
|
|
|
66
66
|
trace: () => trace2,
|
|
67
67
|
traceToolAnthropic: () => traceTool2,
|
|
68
68
|
traceToolAzureOpenAI: () => traceTool3,
|
|
69
|
-
traceToolBedrock: () =>
|
|
69
|
+
traceToolBedrock: () => traceTool6,
|
|
70
|
+
traceToolGoogleGenAI: () => traceTool5,
|
|
70
71
|
traceToolOpenAI: () => traceTool,
|
|
71
72
|
traceToolVertexAI: () => traceTool4,
|
|
72
73
|
updatePrompt: () => updatePrompt,
|
|
@@ -76,6 +77,8 @@ __export(index_exports, {
|
|
|
76
77
|
wrapBedrock: () => wrapBedrock,
|
|
77
78
|
wrapCallModel: () => wrapCallModel,
|
|
78
79
|
wrapClaudeAgentSDK: () => wrapClaudeAgentSDK,
|
|
80
|
+
wrapGoogleGenAI: () => wrapGoogleGenAI,
|
|
81
|
+
wrapGoogleGenAIChat: () => wrapGoogleGenAIChat,
|
|
79
82
|
wrapMastra: () => wrapMastra,
|
|
80
83
|
wrapOpenAI: () => wrapOpenAI,
|
|
81
84
|
wrapOpenRouterAgent: () => wrapOpenRouterAgent,
|
|
@@ -2217,9 +2220,84 @@ function applyMask(spanData, globalMask) {
|
|
|
2217
2220
|
}
|
|
2218
2221
|
}
|
|
2219
2222
|
|
|
2220
|
-
// src/
|
|
2223
|
+
// src/core/identity.ts
|
|
2221
2224
|
var import_node_async_hooks = require("async_hooks");
|
|
2222
|
-
var
|
|
2225
|
+
var _GLOBAL_KEY = /* @__PURE__ */ Symbol.for("neatlogs.identity.storage");
|
|
2226
|
+
var _g = globalThis;
|
|
2227
|
+
var _storage = _g[_GLOBAL_KEY] ?? (_g[_GLOBAL_KEY] = new import_node_async_hooks.AsyncLocalStorage());
|
|
2228
|
+
function currentSessionId() {
|
|
2229
|
+
return _storage.getStore()?.sessionId;
|
|
2230
|
+
}
|
|
2231
|
+
function currentEndUserId() {
|
|
2232
|
+
return _storage.getStore()?.endUserId;
|
|
2233
|
+
}
|
|
2234
|
+
function currentEndUserMetadata() {
|
|
2235
|
+
return _storage.getStore()?.endUserMetadata;
|
|
2236
|
+
}
|
|
2237
|
+
function identify(opts, fn) {
|
|
2238
|
+
const prev = _storage.getStore();
|
|
2239
|
+
const next = { ...prev ?? {} };
|
|
2240
|
+
if (opts.sessionId !== void 0) next.sessionId = opts.sessionId;
|
|
2241
|
+
if (opts.endUserId !== void 0) next.endUserId = opts.endUserId;
|
|
2242
|
+
if (opts.endUserMetadata !== void 0) next.endUserMetadata = opts.endUserMetadata;
|
|
2243
|
+
return _storage.run(next, fn);
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
// src/core/session.ts
|
|
2247
|
+
var logger4 = getLogger();
|
|
2248
|
+
var SESSION_ID_KEY = "neatlogs.session.id";
|
|
2249
|
+
function applySessionAttributes(span2, sessionId, isRoot = true) {
|
|
2250
|
+
const resolved = isRoot ? sessionId ?? currentSessionId() : sessionId;
|
|
2251
|
+
if (!resolved) return;
|
|
2252
|
+
if (!isRoot) {
|
|
2253
|
+
logger4.debug(
|
|
2254
|
+
"[session] Ignoring sessionId on a non-root span \u2014 declare it on the trace root (top-level trace()/span()) or identify()."
|
|
2255
|
+
);
|
|
2256
|
+
return;
|
|
2257
|
+
}
|
|
2258
|
+
span2.setAttribute(SESSION_ID_KEY, String(resolved));
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
// src/core/end-user.ts
|
|
2262
|
+
var import_api = require("@opentelemetry/api");
|
|
2263
|
+
var logger5 = getLogger();
|
|
2264
|
+
var END_USER_ID_KEY = "neatlogs.end_user.id";
|
|
2265
|
+
var END_USER_METADATA_KEY = "neatlogs.end_user.metadata";
|
|
2266
|
+
function normalizeEndUserMetadata(metadata) {
|
|
2267
|
+
if (metadata === void 0 || metadata === null) return void 0;
|
|
2268
|
+
if (typeof metadata === "string") return metadata || void 0;
|
|
2269
|
+
try {
|
|
2270
|
+
return JSON.stringify(metadata);
|
|
2271
|
+
} catch {
|
|
2272
|
+
return JSON.stringify(String(metadata));
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
function isRootSpan() {
|
|
2276
|
+
const current = import_api.trace.getSpan(import_api.context.active());
|
|
2277
|
+
return !(current && current.isRecording());
|
|
2278
|
+
}
|
|
2279
|
+
function applyEndUserAttributes(span2, endUserId, endUserMetadata, isRoot = true) {
|
|
2280
|
+
const resolvedId = isRoot ? endUserId ?? currentEndUserId() : endUserId;
|
|
2281
|
+
const resolvedMeta = isRoot ? endUserMetadata ?? currentEndUserMetadata() : endUserMetadata;
|
|
2282
|
+
if (!resolvedId && !resolvedMeta) return;
|
|
2283
|
+
if (!isRoot) {
|
|
2284
|
+
logger5.debug(
|
|
2285
|
+
"[end_user] Ignoring endUserId/endUserMetadata on a non-root span \u2014 declare it on the trace root (top-level trace()/span()) or identify()."
|
|
2286
|
+
);
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
if (resolvedId) {
|
|
2290
|
+
span2.setAttribute(END_USER_ID_KEY, String(resolvedId));
|
|
2291
|
+
}
|
|
2292
|
+
const metaJson = normalizeEndUserMetadata(resolvedMeta);
|
|
2293
|
+
if (metaJson) {
|
|
2294
|
+
span2.setAttribute(END_USER_METADATA_KEY, metaJson);
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
|
|
2298
|
+
// src/prompt/template.ts
|
|
2299
|
+
var import_node_async_hooks2 = require("async_hooks");
|
|
2300
|
+
var _promptStorage = new import_node_async_hooks2.AsyncLocalStorage();
|
|
2223
2301
|
var PromptContext = class {
|
|
2224
2302
|
/**
|
|
2225
2303
|
* Store system prompt template and variables in context.
|
|
@@ -2246,7 +2324,7 @@ var PromptContext = class {
|
|
|
2246
2324
|
_promptStorage.enterWith(void 0);
|
|
2247
2325
|
}
|
|
2248
2326
|
};
|
|
2249
|
-
var _userPromptStorage = new
|
|
2327
|
+
var _userPromptStorage = new import_node_async_hooks2.AsyncLocalStorage();
|
|
2250
2328
|
var UserPromptContext = class {
|
|
2251
2329
|
/**
|
|
2252
2330
|
* Store user prompt template and variables in context.
|
|
@@ -2372,83 +2450,6 @@ var UserPromptTemplate = class extends BasePromptTemplate {
|
|
|
2372
2450
|
// src/core/context.ts
|
|
2373
2451
|
var import_api3 = require("@opentelemetry/api");
|
|
2374
2452
|
|
|
2375
|
-
// src/core/end-user.ts
|
|
2376
|
-
var import_api = require("@opentelemetry/api");
|
|
2377
|
-
|
|
2378
|
-
// src/core/identity.ts
|
|
2379
|
-
var import_node_async_hooks2 = require("async_hooks");
|
|
2380
|
-
var _GLOBAL_KEY = /* @__PURE__ */ Symbol.for("neatlogs.identity.storage");
|
|
2381
|
-
var _g = globalThis;
|
|
2382
|
-
var _storage = _g[_GLOBAL_KEY] ?? (_g[_GLOBAL_KEY] = new import_node_async_hooks2.AsyncLocalStorage());
|
|
2383
|
-
function currentSessionId() {
|
|
2384
|
-
return _storage.getStore()?.sessionId;
|
|
2385
|
-
}
|
|
2386
|
-
function currentEndUserId() {
|
|
2387
|
-
return _storage.getStore()?.endUserId;
|
|
2388
|
-
}
|
|
2389
|
-
function currentEndUserMetadata() {
|
|
2390
|
-
return _storage.getStore()?.endUserMetadata;
|
|
2391
|
-
}
|
|
2392
|
-
function identify(opts, fn) {
|
|
2393
|
-
const prev = _storage.getStore();
|
|
2394
|
-
const next = { ...prev ?? {} };
|
|
2395
|
-
if (opts.sessionId !== void 0) next.sessionId = opts.sessionId;
|
|
2396
|
-
if (opts.endUserId !== void 0) next.endUserId = opts.endUserId;
|
|
2397
|
-
if (opts.endUserMetadata !== void 0) next.endUserMetadata = opts.endUserMetadata;
|
|
2398
|
-
return _storage.run(next, fn);
|
|
2399
|
-
}
|
|
2400
|
-
|
|
2401
|
-
// src/core/end-user.ts
|
|
2402
|
-
var logger4 = getLogger();
|
|
2403
|
-
var END_USER_ID_KEY = "neatlogs.end_user.id";
|
|
2404
|
-
var END_USER_METADATA_KEY = "neatlogs.end_user.metadata";
|
|
2405
|
-
function normalizeEndUserMetadata(metadata) {
|
|
2406
|
-
if (metadata === void 0 || metadata === null) return void 0;
|
|
2407
|
-
if (typeof metadata === "string") return metadata || void 0;
|
|
2408
|
-
try {
|
|
2409
|
-
return JSON.stringify(metadata);
|
|
2410
|
-
} catch {
|
|
2411
|
-
return JSON.stringify(String(metadata));
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2414
|
-
function isRootSpan() {
|
|
2415
|
-
const current = import_api.trace.getSpan(import_api.context.active());
|
|
2416
|
-
return !(current && current.isRecording());
|
|
2417
|
-
}
|
|
2418
|
-
function applyEndUserAttributes(span2, endUserId, endUserMetadata, isRoot = true) {
|
|
2419
|
-
const resolvedId = isRoot ? endUserId ?? currentEndUserId() : endUserId;
|
|
2420
|
-
const resolvedMeta = isRoot ? endUserMetadata ?? currentEndUserMetadata() : endUserMetadata;
|
|
2421
|
-
if (!resolvedId && !resolvedMeta) return;
|
|
2422
|
-
if (!isRoot) {
|
|
2423
|
-
logger4.debug(
|
|
2424
|
-
"[end_user] Ignoring endUserId/endUserMetadata on a non-root span \u2014 declare it on the trace root (top-level trace()/span()) or identify()."
|
|
2425
|
-
);
|
|
2426
|
-
return;
|
|
2427
|
-
}
|
|
2428
|
-
if (resolvedId) {
|
|
2429
|
-
span2.setAttribute(END_USER_ID_KEY, String(resolvedId));
|
|
2430
|
-
}
|
|
2431
|
-
const metaJson = normalizeEndUserMetadata(resolvedMeta);
|
|
2432
|
-
if (metaJson) {
|
|
2433
|
-
span2.setAttribute(END_USER_METADATA_KEY, metaJson);
|
|
2434
|
-
}
|
|
2435
|
-
}
|
|
2436
|
-
|
|
2437
|
-
// src/core/session.ts
|
|
2438
|
-
var logger5 = getLogger();
|
|
2439
|
-
var SESSION_ID_KEY = "neatlogs.session.id";
|
|
2440
|
-
function applySessionAttributes(span2, sessionId, isRoot = true) {
|
|
2441
|
-
const resolved = isRoot ? sessionId ?? currentSessionId() : sessionId;
|
|
2442
|
-
if (!resolved) return;
|
|
2443
|
-
if (!isRoot) {
|
|
2444
|
-
logger5.debug(
|
|
2445
|
-
"[session] Ignoring sessionId on a non-root span \u2014 declare it on the trace root (top-level trace()/span()) or identify()."
|
|
2446
|
-
);
|
|
2447
|
-
return;
|
|
2448
|
-
}
|
|
2449
|
-
span2.setAttribute(SESSION_ID_KEY, String(resolved));
|
|
2450
|
-
}
|
|
2451
|
-
|
|
2452
2453
|
// src/decorators/base.ts
|
|
2453
2454
|
var import_api2 = require("@opentelemetry/api");
|
|
2454
2455
|
var logger6 = getLogger();
|
|
@@ -4426,6 +4427,10 @@ var NeatlogsSpanProcessor = class {
|
|
|
4426
4427
|
onStart(span2, parentContext) {
|
|
4427
4428
|
const startTime = import_node_perf_hooks.performance.now();
|
|
4428
4429
|
try {
|
|
4430
|
+
if (!span2.parentSpanId) {
|
|
4431
|
+
applySessionAttributes(span2, void 0, true);
|
|
4432
|
+
applyEndUserAttributes(span2, void 0, void 0, true);
|
|
4433
|
+
}
|
|
4429
4434
|
const attrs = span2.attributes ?? {};
|
|
4430
4435
|
const spanKind = attrs["openinference.span.kind"];
|
|
4431
4436
|
const spanName = typeof span2.name === "string" ? span2.name : "";
|
|
@@ -5818,7 +5823,7 @@ async function removeTag(name, tag) {
|
|
|
5818
5823
|
}
|
|
5819
5824
|
|
|
5820
5825
|
// src/version.ts
|
|
5821
|
-
var __version__ = "1.1.
|
|
5826
|
+
var __version__ = "1.1.5";
|
|
5822
5827
|
|
|
5823
5828
|
// src/init.ts
|
|
5824
5829
|
var logger13 = getLogger();
|
|
@@ -7879,10 +7884,14 @@ function recordError4(span2, err) {
|
|
|
7879
7884
|
span2.end();
|
|
7880
7885
|
}
|
|
7881
7886
|
|
|
7882
|
-
// src/
|
|
7887
|
+
// src/google-genai.ts
|
|
7883
7888
|
var import_api15 = require("@opentelemetry/api");
|
|
7884
|
-
var TRACER_NAME7 = "neatlogs.
|
|
7885
|
-
var PROVIDER3 = "
|
|
7889
|
+
var TRACER_NAME7 = "neatlogs.google_genai";
|
|
7890
|
+
var PROVIDER3 = "google";
|
|
7891
|
+
var SYSTEM3 = "google_genai";
|
|
7892
|
+
function wrapGoogleGenAI(client) {
|
|
7893
|
+
return wrapNamespace5(client, []);
|
|
7894
|
+
}
|
|
7886
7895
|
function traceTool5(name, fn) {
|
|
7887
7896
|
return async function tracedTool(args) {
|
|
7888
7897
|
const tracer = getProviderTracer(TRACER_NAME7);
|
|
@@ -7912,65 +7921,78 @@ function traceTool5(name, fn) {
|
|
|
7912
7921
|
);
|
|
7913
7922
|
};
|
|
7914
7923
|
}
|
|
7915
|
-
function
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
|
|
7924
|
+
function wrapNamespace5(target, path3) {
|
|
7925
|
+
return new Proxy(target, {
|
|
7926
|
+
get(obj, prop, receiver) {
|
|
7927
|
+
const value = Reflect.get(obj, prop, receiver);
|
|
7928
|
+
if (typeof prop === "symbol" || String(prop).startsWith("_")) return value;
|
|
7929
|
+
const currentPath = [...path3, String(prop)];
|
|
7930
|
+
const pathStr = currentPath.join(".");
|
|
7931
|
+
if (pathStr === "models.generateContent" && typeof value === "function") {
|
|
7932
|
+
return tracedGenerateContent2(value.bind(obj), false);
|
|
7933
|
+
}
|
|
7934
|
+
if (pathStr === "models.generateContentStream" && typeof value === "function") {
|
|
7935
|
+
return tracedGenerateContent2(value.bind(obj), true);
|
|
7936
|
+
}
|
|
7937
|
+
if (pathStr === "models.embedContent" && typeof value === "function") {
|
|
7938
|
+
return tracedEmbedContent2(value.bind(obj));
|
|
7939
|
+
}
|
|
7940
|
+
if (pathStr === "models.countTokens" && typeof value === "function") {
|
|
7941
|
+
return tracedCountTokens2(value.bind(obj));
|
|
7942
|
+
}
|
|
7943
|
+
if (value && typeof value === "object" && !Array.isArray(value) && isNamespace5(currentPath)) {
|
|
7944
|
+
return wrapNamespace5(value, currentPath);
|
|
7945
|
+
}
|
|
7946
|
+
return value;
|
|
7934
7947
|
}
|
|
7935
|
-
|
|
7936
|
-
};
|
|
7937
|
-
c._neatlogsBedrockPatched = true;
|
|
7938
|
-
return client;
|
|
7948
|
+
});
|
|
7939
7949
|
}
|
|
7940
|
-
function
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7950
|
+
function isNamespace5(path3) {
|
|
7951
|
+
if (path3.length > 2) return false;
|
|
7952
|
+
return ["models", "chats"].includes(path3[path3.length - 1]);
|
|
7953
|
+
}
|
|
7954
|
+
function wrapGoogleGenAIChat(chat) {
|
|
7955
|
+
const c = chat;
|
|
7956
|
+
if (!c || c._neatlogsGoogleGenAIPatched) return chat;
|
|
7957
|
+
if (typeof c.sendMessage === "function") {
|
|
7958
|
+
const orig = c.sendMessage.bind(c);
|
|
7959
|
+
c.sendMessage = (params, ...rest) => tracedChatSend2(orig, c, params, rest, false);
|
|
7944
7960
|
}
|
|
7945
|
-
|
|
7946
|
-
|
|
7961
|
+
if (typeof c.sendMessageStream === "function") {
|
|
7962
|
+
const orig = c.sendMessageStream.bind(c);
|
|
7963
|
+
c.sendMessageStream = (params, ...rest) => tracedChatSend2(orig, c, params, rest, true);
|
|
7964
|
+
}
|
|
7965
|
+
try {
|
|
7966
|
+
Object.defineProperty(c, "_neatlogsGoogleGenAIPatched", { value: true, enumerable: false, configurable: true });
|
|
7967
|
+
} catch {
|
|
7968
|
+
c._neatlogsGoogleGenAIPatched = true;
|
|
7969
|
+
}
|
|
7970
|
+
return chat;
|
|
7947
7971
|
}
|
|
7948
|
-
function
|
|
7949
|
-
|
|
7972
|
+
function tracedChatSend2(original, chat, params, rest, isStream) {
|
|
7973
|
+
const tracer = getProviderTracer(TRACER_NAME7);
|
|
7974
|
+
const model = chat?.model ?? chat?.modelVersion ?? "";
|
|
7975
|
+
const span2 = tracer.startSpan("google_genai.chat.send_message", {
|
|
7950
7976
|
attributes: {
|
|
7951
7977
|
"neatlogs.span.kind": "LLM",
|
|
7952
7978
|
"neatlogs.llm.provider": PROVIDER3,
|
|
7953
|
-
"neatlogs.llm.system":
|
|
7954
|
-
"neatlogs.llm.model_name":
|
|
7979
|
+
"neatlogs.llm.system": SYSTEM3,
|
|
7980
|
+
"neatlogs.llm.model_name": model,
|
|
7955
7981
|
"neatlogs.llm.is_streaming": isStream
|
|
7956
7982
|
}
|
|
7957
7983
|
}, import_api15.context.active());
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
|
|
7962
|
-
|
|
7963
|
-
isStream
|
|
7984
|
+
const message = params?.message ?? params;
|
|
7985
|
+
span2.setAttribute("neatlogs.llm.input_messages.0.role", "user");
|
|
7986
|
+
span2.setAttribute(
|
|
7987
|
+
"neatlogs.llm.input_messages.0.content",
|
|
7988
|
+
typeof message === "string" ? message : safeStringify7(message)
|
|
7964
7989
|
);
|
|
7965
|
-
setConverseInput(span2, input);
|
|
7966
7990
|
const ctx = import_api15.trace.setSpan(import_api15.context.active(), span2);
|
|
7967
|
-
const
|
|
7968
|
-
return
|
|
7991
|
+
const result = import_api15.context.with(ctx, () => original(params, ...rest));
|
|
7992
|
+
return Promise.resolve(result).then(
|
|
7969
7993
|
(response) => {
|
|
7970
|
-
if (isStream)
|
|
7971
|
-
|
|
7972
|
-
}
|
|
7973
|
-
finalizeConverse(span2, response);
|
|
7994
|
+
if (isStream) return wrapStream2(response, span2);
|
|
7995
|
+
finalizeResponse2(span2, response);
|
|
7974
7996
|
return response;
|
|
7975
7997
|
},
|
|
7976
7998
|
(err) => {
|
|
@@ -7979,43 +8001,418 @@ function tracedConverse(originalSend, command, input, rest, isStream) {
|
|
|
7979
8001
|
}
|
|
7980
8002
|
);
|
|
7981
8003
|
}
|
|
7982
|
-
function
|
|
7983
|
-
|
|
7984
|
-
|
|
7985
|
-
const
|
|
7986
|
-
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
7990
|
-
|
|
7991
|
-
|
|
7992
|
-
|
|
7993
|
-
|
|
7994
|
-
|
|
7995
|
-
|
|
7996
|
-
|
|
7997
|
-
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8004
|
+
function tracedEmbedContent2(original) {
|
|
8005
|
+
return function(opts, ...rest) {
|
|
8006
|
+
const tracer = getProviderTracer(TRACER_NAME7);
|
|
8007
|
+
const span2 = tracer.startSpan("google_genai.models.embed_content", {
|
|
8008
|
+
attributes: {
|
|
8009
|
+
"neatlogs.span.kind": "EMBEDDING",
|
|
8010
|
+
"neatlogs.llm.provider": PROVIDER3,
|
|
8011
|
+
"neatlogs.embedding.model_name": opts?.model ?? "",
|
|
8012
|
+
"neatlogs.embedding.text": safeStringify7(opts?.contents ?? "")
|
|
8013
|
+
}
|
|
8014
|
+
}, import_api15.context.active());
|
|
8015
|
+
const ctx = import_api15.trace.setSpan(import_api15.context.active(), span2);
|
|
8016
|
+
const result = import_api15.context.with(ctx, () => original(opts, ...rest));
|
|
8017
|
+
return Promise.resolve(result).then(
|
|
8018
|
+
(response) => {
|
|
8019
|
+
const embeddings = response?.embeddings;
|
|
8020
|
+
if (Array.isArray(embeddings)) {
|
|
8021
|
+
span2.setAttribute("neatlogs.embedding.count", embeddings.length);
|
|
8022
|
+
const vals = embeddings[0]?.values;
|
|
8023
|
+
if (Array.isArray(vals)) span2.setAttribute("neatlogs.embedding.dimensions", vals.length);
|
|
8024
|
+
}
|
|
8025
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.OK });
|
|
8026
|
+
span2.end();
|
|
8027
|
+
return response;
|
|
8028
|
+
},
|
|
8029
|
+
(err) => {
|
|
8030
|
+
recordError5(span2, err);
|
|
8031
|
+
throw err;
|
|
8032
|
+
}
|
|
8033
|
+
);
|
|
8034
|
+
};
|
|
8035
|
+
}
|
|
8036
|
+
function tracedCountTokens2(original) {
|
|
8037
|
+
return function(opts, ...rest) {
|
|
8038
|
+
const tracer = getProviderTracer(TRACER_NAME7);
|
|
8039
|
+
const span2 = tracer.startSpan("google_genai.models.count_tokens", {
|
|
8040
|
+
attributes: {
|
|
8041
|
+
"neatlogs.span.kind": "LLM",
|
|
8042
|
+
"neatlogs.llm.provider": PROVIDER3,
|
|
8043
|
+
"neatlogs.llm.task": "count_tokens",
|
|
8044
|
+
"neatlogs.llm.model_name": opts?.model ?? ""
|
|
8045
|
+
}
|
|
8046
|
+
}, import_api15.context.active());
|
|
8047
|
+
const ctx = import_api15.trace.setSpan(import_api15.context.active(), span2);
|
|
8048
|
+
const result = import_api15.context.with(ctx, () => original(opts, ...rest));
|
|
8049
|
+
return Promise.resolve(result).then(
|
|
8050
|
+
(response) => {
|
|
8051
|
+
if (response?.totalTokens != null) span2.setAttribute("neatlogs.llm.token_count.prompt", response.totalTokens);
|
|
8052
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.OK });
|
|
8053
|
+
span2.end();
|
|
8054
|
+
return response;
|
|
8055
|
+
},
|
|
8056
|
+
(err) => {
|
|
8057
|
+
recordError5(span2, err);
|
|
8058
|
+
throw err;
|
|
8059
|
+
}
|
|
8060
|
+
);
|
|
8061
|
+
};
|
|
8062
|
+
}
|
|
8063
|
+
function tracedGenerateContent2(original, isStream) {
|
|
8064
|
+
return function(opts, ...rest) {
|
|
8065
|
+
const tracer = getProviderTracer(TRACER_NAME7);
|
|
8066
|
+
const model = opts?.model ?? "";
|
|
8067
|
+
const span2 = tracer.startSpan("google_genai.models.generate_content", {
|
|
8068
|
+
attributes: {
|
|
8069
|
+
"neatlogs.span.kind": "LLM",
|
|
8070
|
+
"neatlogs.llm.provider": PROVIDER3,
|
|
8071
|
+
"neatlogs.llm.system": SYSTEM3,
|
|
8072
|
+
"neatlogs.llm.model_name": model,
|
|
8073
|
+
"neatlogs.llm.is_streaming": isStream
|
|
8074
|
+
}
|
|
8075
|
+
}, import_api15.context.active());
|
|
8076
|
+
setInputAttributes2(span2, opts);
|
|
8077
|
+
const ctx = import_api15.trace.setSpan(import_api15.context.active(), span2);
|
|
8078
|
+
const result = import_api15.context.with(ctx, () => original(opts, ...rest));
|
|
8079
|
+
return Promise.resolve(result).then(
|
|
8080
|
+
(response) => {
|
|
8081
|
+
if (isStream) {
|
|
8082
|
+
return wrapStream2(response, span2);
|
|
8083
|
+
}
|
|
8084
|
+
finalizeResponse2(span2, response);
|
|
8085
|
+
return response;
|
|
8086
|
+
},
|
|
8087
|
+
(err) => {
|
|
8088
|
+
recordError5(span2, err);
|
|
8089
|
+
throw err;
|
|
8090
|
+
}
|
|
8091
|
+
);
|
|
8092
|
+
};
|
|
8093
|
+
}
|
|
8094
|
+
function setInputAttributes2(span2, opts) {
|
|
8095
|
+
let idx = 0;
|
|
8096
|
+
const config = opts?.config;
|
|
8097
|
+
const systemInstruction = config?.systemInstruction ?? config?.system_instruction;
|
|
8098
|
+
if (systemInstruction) {
|
|
8099
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "system");
|
|
8100
|
+
span2.setAttribute(
|
|
8101
|
+
`neatlogs.llm.input_messages.${idx}.content`,
|
|
8102
|
+
typeof systemInstruction === "string" ? systemInstruction : safeStringify7(systemInstruction)
|
|
8103
|
+
);
|
|
8104
|
+
idx++;
|
|
8105
|
+
}
|
|
8106
|
+
const contents = opts?.contents;
|
|
8107
|
+
if (typeof contents === "string") {
|
|
8108
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "user");
|
|
8109
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, contents);
|
|
8110
|
+
} else if (Array.isArray(contents)) {
|
|
8111
|
+
for (const item of contents) {
|
|
8112
|
+
if (typeof item === "string") {
|
|
8113
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "user");
|
|
8114
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, item);
|
|
8115
|
+
idx++;
|
|
8116
|
+
} else if (item && typeof item === "object") {
|
|
8117
|
+
const role = item.role ?? "user";
|
|
8118
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, role);
|
|
8119
|
+
const parts = item.parts ?? [];
|
|
8120
|
+
const textParts = [];
|
|
8121
|
+
for (const part of parts) {
|
|
8122
|
+
if (typeof part === "string") textParts.push(part);
|
|
8123
|
+
else if (part?.text) textParts.push(part.text);
|
|
8124
|
+
}
|
|
8125
|
+
span2.setAttribute(
|
|
8126
|
+
`neatlogs.llm.input_messages.${idx}.content`,
|
|
8127
|
+
textParts.length ? textParts.join("\n") : safeStringify7(parts)
|
|
8128
|
+
);
|
|
8129
|
+
idx++;
|
|
8130
|
+
}
|
|
8131
|
+
}
|
|
8132
|
+
} else if (contents) {
|
|
8133
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "user");
|
|
8134
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, safeStringify7(contents));
|
|
8135
|
+
}
|
|
8136
|
+
const tools = config?.tools;
|
|
8137
|
+
if (Array.isArray(tools)) {
|
|
8138
|
+
let t = 0;
|
|
8139
|
+
for (const tool of tools) {
|
|
8140
|
+
const decls = tool?.functionDeclarations ?? tool?.function_declarations ?? [];
|
|
8141
|
+
for (const fn of decls) {
|
|
8142
|
+
span2.setAttribute(`neatlogs.llm.tools.${t}.name`, fn?.name ?? "");
|
|
8143
|
+
if (fn?.description) span2.setAttribute(`neatlogs.llm.tools.${t}.description`, fn.description);
|
|
8144
|
+
if (fn?.parameters) span2.setAttribute(`neatlogs.llm.tools.${t}.input_schema`, safeStringify7(fn.parameters));
|
|
8145
|
+
t++;
|
|
8146
|
+
}
|
|
8147
|
+
}
|
|
8148
|
+
}
|
|
8149
|
+
if (config) {
|
|
8150
|
+
if (config.temperature != null) span2.setAttribute("neatlogs.llm.temperature", config.temperature);
|
|
8151
|
+
if (config.topP != null) span2.setAttribute("neatlogs.llm.top_p", config.topP);
|
|
8152
|
+
if (config.topK != null) span2.setAttribute("neatlogs.llm.top_k", config.topK);
|
|
8153
|
+
const maxTokens = config.maxOutputTokens ?? config.max_output_tokens;
|
|
8154
|
+
if (maxTokens != null) span2.setAttribute("neatlogs.llm.max_tokens", maxTokens);
|
|
8155
|
+
const params = {};
|
|
8156
|
+
if (config.temperature != null) params.temperature = config.temperature;
|
|
8157
|
+
if (config.topP != null) params.top_p = config.topP;
|
|
8158
|
+
if (config.topK != null) params.top_k = config.topK;
|
|
8159
|
+
if (maxTokens != null) params.max_tokens = maxTokens;
|
|
8160
|
+
if (config.frequencyPenalty != null) params.frequency_penalty = config.frequencyPenalty;
|
|
8161
|
+
if (config.presencePenalty != null) params.presence_penalty = config.presencePenalty;
|
|
8162
|
+
if (Object.keys(params).length > 0) {
|
|
8163
|
+
span2.setAttribute("neatlogs.llm.invocation_parameters", JSON.stringify(params));
|
|
8164
|
+
}
|
|
8165
|
+
}
|
|
8166
|
+
}
|
|
8167
|
+
function wrapStream2(stream, span2) {
|
|
8168
|
+
const chunks = [];
|
|
8169
|
+
const originalAsyncIterator = stream?.[Symbol.asyncIterator]?.bind(stream);
|
|
8170
|
+
if (!originalAsyncIterator) {
|
|
8171
|
+
finalizeStreamChunks4(span2, chunks);
|
|
8172
|
+
return stream;
|
|
8173
|
+
}
|
|
8174
|
+
const wrapped = Object.create(Object.getPrototypeOf(stream));
|
|
8175
|
+
Object.assign(wrapped, stream);
|
|
8176
|
+
wrapped[Symbol.asyncIterator] = function() {
|
|
8177
|
+
const iterator = originalAsyncIterator();
|
|
8178
|
+
return {
|
|
8179
|
+
async next() {
|
|
8180
|
+
try {
|
|
8181
|
+
const result = await iterator.next();
|
|
8182
|
+
if (result.done) {
|
|
8183
|
+
finalizeStreamChunks4(span2, chunks);
|
|
8184
|
+
return result;
|
|
8185
|
+
}
|
|
8186
|
+
chunks.push(result.value);
|
|
8187
|
+
return result;
|
|
8188
|
+
} catch (err) {
|
|
8189
|
+
recordError5(span2, err);
|
|
8190
|
+
throw err;
|
|
8191
|
+
}
|
|
8192
|
+
},
|
|
8193
|
+
async return(value) {
|
|
8194
|
+
finalizeStreamChunks4(span2, chunks);
|
|
8195
|
+
return iterator.return?.(value) ?? { done: true, value: void 0 };
|
|
8196
|
+
},
|
|
8197
|
+
async throw(err) {
|
|
8198
|
+
recordError5(span2, err);
|
|
8199
|
+
return iterator.throw?.(err) ?? { done: true, value: void 0 };
|
|
8200
|
+
}
|
|
8201
|
+
};
|
|
8202
|
+
};
|
|
8203
|
+
return wrapped;
|
|
8204
|
+
}
|
|
8205
|
+
function finalizeStreamChunks4(span2, chunks) {
|
|
8206
|
+
const textParts = [];
|
|
8207
|
+
let finishReason = "";
|
|
8208
|
+
let usage = null;
|
|
8209
|
+
for (const chunk of chunks) {
|
|
8210
|
+
for (const candidate of chunk?.candidates ?? []) {
|
|
8211
|
+
for (const part of candidate?.content?.parts ?? []) {
|
|
8212
|
+
if (part?.text && !part?.thought) textParts.push(part.text);
|
|
8213
|
+
}
|
|
8214
|
+
if (candidate?.finishReason) finishReason = candidate.finishReason;
|
|
8215
|
+
}
|
|
8216
|
+
if (chunk?.usageMetadata) usage = chunk.usageMetadata;
|
|
8217
|
+
}
|
|
8218
|
+
const fullText = textParts.join("");
|
|
8219
|
+
if (fullText) {
|
|
8220
|
+
span2.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
|
|
8221
|
+
span2.setAttribute("neatlogs.llm.output_messages.0.content", fullText);
|
|
8222
|
+
}
|
|
8223
|
+
if (finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(finishReason));
|
|
8224
|
+
setUsage2(span2, usage);
|
|
8225
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.OK });
|
|
8226
|
+
span2.end();
|
|
8227
|
+
}
|
|
8228
|
+
function finalizeResponse2(span2, response) {
|
|
8229
|
+
const textParts = [];
|
|
8230
|
+
let toolIdx = 0;
|
|
8231
|
+
for (const candidate of response?.candidates ?? []) {
|
|
8232
|
+
for (const part of candidate?.content?.parts ?? []) {
|
|
8233
|
+
if (part?.text && !part?.thought) {
|
|
8234
|
+
textParts.push(part.text);
|
|
8235
|
+
} else if (part?.thought && part?.text) {
|
|
8236
|
+
span2.setAttribute("neatlogs.llm.output_messages.0.thinking", part.text);
|
|
8237
|
+
} else if (part?.functionCall) {
|
|
8238
|
+
const fc = part.functionCall;
|
|
8239
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.name`, fc?.name ?? "");
|
|
8240
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.arguments`, safeStringify7(fc?.args ?? {}));
|
|
8241
|
+
toolIdx++;
|
|
8242
|
+
}
|
|
8243
|
+
}
|
|
8244
|
+
if (candidate?.finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(candidate.finishReason));
|
|
8245
|
+
}
|
|
8246
|
+
if (textParts.length) {
|
|
8247
|
+
span2.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
|
|
8248
|
+
span2.setAttribute("neatlogs.llm.output_messages.0.content", textParts.join(""));
|
|
8249
|
+
}
|
|
8250
|
+
setUsage2(span2, response?.usageMetadata);
|
|
8251
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.OK });
|
|
8252
|
+
span2.end();
|
|
8253
|
+
}
|
|
8254
|
+
function setUsage2(span2, usage) {
|
|
8255
|
+
if (!usage) return;
|
|
8256
|
+
if (usage.promptTokenCount != null) span2.setAttribute("neatlogs.llm.token_count.prompt", usage.promptTokenCount);
|
|
8257
|
+
if (usage.candidatesTokenCount != null) span2.setAttribute("neatlogs.llm.token_count.completion", usage.candidatesTokenCount);
|
|
8258
|
+
if (usage.totalTokenCount != null) span2.setAttribute("neatlogs.llm.token_count.total", usage.totalTokenCount);
|
|
8259
|
+
if (usage.cachedContentTokenCount != null) span2.setAttribute("neatlogs.llm.token_count.cache_read", usage.cachedContentTokenCount);
|
|
8260
|
+
if (usage.thoughtsTokenCount != null) span2.setAttribute("neatlogs.llm.token_count.reasoning", usage.thoughtsTokenCount);
|
|
8261
|
+
}
|
|
8262
|
+
function safeStringify7(value) {
|
|
8263
|
+
try {
|
|
8264
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8265
|
+
} catch {
|
|
8266
|
+
return "";
|
|
8267
|
+
}
|
|
8268
|
+
}
|
|
8269
|
+
function recordError5(span2, err) {
|
|
8270
|
+
if (err instanceof Error) {
|
|
8271
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.ERROR, message: err.message });
|
|
8272
|
+
span2.recordException(err);
|
|
8273
|
+
} else {
|
|
8274
|
+
span2.setStatus({ code: import_api15.SpanStatusCode.ERROR, message: String(err) });
|
|
8275
|
+
}
|
|
8276
|
+
span2.end();
|
|
8277
|
+
}
|
|
8278
|
+
|
|
8279
|
+
// src/bedrock.ts
|
|
8280
|
+
var import_api16 = require("@opentelemetry/api");
|
|
8281
|
+
var TRACER_NAME8 = "neatlogs.bedrock";
|
|
8282
|
+
var PROVIDER4 = "bedrock";
|
|
8283
|
+
function traceTool6(name, fn) {
|
|
8284
|
+
return async function tracedTool(args) {
|
|
8285
|
+
const tracer = getProviderTracer(TRACER_NAME8);
|
|
8286
|
+
return tracer.startActiveSpan(
|
|
8287
|
+
`tool.${name}`,
|
|
8288
|
+
{
|
|
8289
|
+
attributes: {
|
|
8290
|
+
"neatlogs.span.kind": "TOOL",
|
|
8291
|
+
"neatlogs.tool.name": name,
|
|
8292
|
+
"input.value": safeStringify8(args)
|
|
8293
|
+
}
|
|
8294
|
+
},
|
|
8295
|
+
import_api16.context.active(),
|
|
8296
|
+
async (span2) => {
|
|
8297
|
+
try {
|
|
8298
|
+
const result = await fn(args);
|
|
8299
|
+
span2.setAttribute("output.value", safeStringify8(result));
|
|
8300
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8301
|
+
return result;
|
|
8302
|
+
} catch (err) {
|
|
8303
|
+
recordError6(span2, err);
|
|
8304
|
+
throw err;
|
|
8305
|
+
} finally {
|
|
8306
|
+
span2.end();
|
|
8307
|
+
}
|
|
8308
|
+
}
|
|
8309
|
+
);
|
|
8310
|
+
};
|
|
8311
|
+
}
|
|
8312
|
+
function wrapBedrock(client) {
|
|
8313
|
+
const c = client;
|
|
8314
|
+
if (c._neatlogsBedrockPatched) return client;
|
|
8315
|
+
if (typeof c.send !== "function") return client;
|
|
8316
|
+
const originalSend = c.send.bind(c);
|
|
8317
|
+
c.send = function(command, ...rest) {
|
|
8318
|
+
const name = command?.constructor?.name ?? "";
|
|
8319
|
+
const input = command?.input ?? {};
|
|
8320
|
+
if (name === "ConverseCommand") {
|
|
8321
|
+
return tracedConverse(originalSend, command, input, rest, false);
|
|
8322
|
+
}
|
|
8323
|
+
if (name === "ConverseStreamCommand") {
|
|
8324
|
+
return tracedConverse(originalSend, command, input, rest, true);
|
|
8325
|
+
}
|
|
8326
|
+
if (name === "InvokeModelCommand") {
|
|
8327
|
+
return tracedInvokeModel(originalSend, command, input, rest, false);
|
|
8328
|
+
}
|
|
8329
|
+
if (name === "InvokeModelWithResponseStreamCommand") {
|
|
8330
|
+
return tracedInvokeModel(originalSend, command, input, rest, true);
|
|
8331
|
+
}
|
|
8332
|
+
return originalSend(command, ...rest);
|
|
8333
|
+
};
|
|
8334
|
+
c._neatlogsBedrockPatched = true;
|
|
8335
|
+
return client;
|
|
8336
|
+
}
|
|
8337
|
+
function vendorFromModel(modelId) {
|
|
8338
|
+
let tail = String(modelId ?? "").split("/").pop() ?? "";
|
|
8339
|
+
for (const prefix of ["us.", "eu.", "apac.", "us-gov."]) {
|
|
8340
|
+
if (tail.startsWith(prefix)) tail = tail.slice(prefix.length);
|
|
8341
|
+
}
|
|
8342
|
+
const vendor = tail.includes(".") ? tail.split(".")[0] : "";
|
|
8343
|
+
return vendor || "bedrock";
|
|
8344
|
+
}
|
|
8345
|
+
function startSpan(name, modelId, isStream) {
|
|
8346
|
+
return getProviderTracer(TRACER_NAME8).startSpan(name, {
|
|
8347
|
+
attributes: {
|
|
8348
|
+
"neatlogs.span.kind": "LLM",
|
|
8349
|
+
"neatlogs.llm.provider": PROVIDER4,
|
|
8350
|
+
"neatlogs.llm.system": vendorFromModel(modelId),
|
|
8351
|
+
"neatlogs.llm.model_name": String(modelId ?? ""),
|
|
8352
|
+
"neatlogs.llm.is_streaming": isStream
|
|
8353
|
+
}
|
|
8354
|
+
}, import_api16.context.active());
|
|
8355
|
+
}
|
|
8356
|
+
function tracedConverse(originalSend, command, input, rest, isStream) {
|
|
8357
|
+
const span2 = startSpan(
|
|
8358
|
+
isStream ? "bedrock.converse_stream" : "bedrock.converse",
|
|
8359
|
+
input?.modelId,
|
|
8360
|
+
isStream
|
|
8361
|
+
);
|
|
8362
|
+
setConverseInput(span2, input);
|
|
8363
|
+
const ctx = import_api16.trace.setSpan(import_api16.context.active(), span2);
|
|
8364
|
+
const promise = import_api16.context.with(ctx, () => originalSend(command, ...rest));
|
|
8365
|
+
return promise.then(
|
|
8366
|
+
(response) => {
|
|
8367
|
+
if (isStream) {
|
|
8368
|
+
return wrapConverseStream(response, span2);
|
|
8369
|
+
}
|
|
8370
|
+
finalizeConverse(span2, response);
|
|
8371
|
+
return response;
|
|
8372
|
+
},
|
|
8373
|
+
(err) => {
|
|
8374
|
+
recordError6(span2, err);
|
|
8375
|
+
throw err;
|
|
8376
|
+
}
|
|
8377
|
+
);
|
|
8378
|
+
}
|
|
8379
|
+
function setConverseInput(span2, input) {
|
|
8380
|
+
let idx = 0;
|
|
8381
|
+
if (Array.isArray(input?.system)) {
|
|
8382
|
+
const text = input.system.map((b) => b?.text ?? "").join(" ").trim();
|
|
8383
|
+
if (text) {
|
|
8384
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "system");
|
|
8385
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, text);
|
|
8386
|
+
idx++;
|
|
8387
|
+
}
|
|
8388
|
+
}
|
|
8389
|
+
for (const msg of input?.messages ?? []) {
|
|
8390
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, msg?.role ?? "user");
|
|
8391
|
+
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, converseBlocksToText(msg?.content));
|
|
8392
|
+
idx++;
|
|
8393
|
+
}
|
|
8394
|
+
const cfg = input?.inferenceConfig ?? {};
|
|
8395
|
+
if (cfg.temperature != null) span2.setAttribute("neatlogs.llm.temperature", cfg.temperature);
|
|
8396
|
+
if (cfg.topP != null) span2.setAttribute("neatlogs.llm.top_p", cfg.topP);
|
|
8397
|
+
if (cfg.maxTokens != null) span2.setAttribute("neatlogs.llm.max_tokens", cfg.maxTokens);
|
|
8001
8398
|
const tools = input?.toolConfig?.tools ?? [];
|
|
8002
8399
|
for (let i = 0; i < tools.length; i++) {
|
|
8003
8400
|
const spec = tools[i]?.toolSpec ?? {};
|
|
8004
8401
|
if (spec.name) span2.setAttribute(`neatlogs.llm.tools.${i}.name`, spec.name);
|
|
8005
8402
|
if (spec.description) span2.setAttribute(`neatlogs.llm.tools.${i}.description`, spec.description);
|
|
8006
|
-
if (spec.inputSchema) span2.setAttribute(`neatlogs.llm.tools.${i}.input_schema`,
|
|
8403
|
+
if (spec.inputSchema) span2.setAttribute(`neatlogs.llm.tools.${i}.input_schema`, safeStringify8(spec.inputSchema));
|
|
8007
8404
|
}
|
|
8008
8405
|
}
|
|
8009
8406
|
function converseBlocksToText(content) {
|
|
8010
8407
|
if (typeof content === "string") return content;
|
|
8011
|
-
if (!Array.isArray(content)) return
|
|
8408
|
+
if (!Array.isArray(content)) return safeStringify8(content);
|
|
8012
8409
|
const parts = [];
|
|
8013
8410
|
for (const block of content) {
|
|
8014
8411
|
if (block && typeof block === "object") {
|
|
8015
8412
|
if ("text" in block) parts.push(String(block.text));
|
|
8016
|
-
else if ("toolResult" in block) parts.push(
|
|
8017
|
-
else if ("toolUse" in block) parts.push(
|
|
8018
|
-
else parts.push(
|
|
8413
|
+
else if ("toolResult" in block) parts.push(safeStringify8(block.toolResult));
|
|
8414
|
+
else if ("toolUse" in block) parts.push(safeStringify8(block.toolUse));
|
|
8415
|
+
else parts.push(safeStringify8(block));
|
|
8019
8416
|
} else {
|
|
8020
8417
|
parts.push(String(block));
|
|
8021
8418
|
}
|
|
@@ -8034,7 +8431,7 @@ function finalizeConverse(span2, response) {
|
|
|
8034
8431
|
const tu = block.toolUse;
|
|
8035
8432
|
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.id`, String(tu?.toolUseId ?? ""));
|
|
8036
8433
|
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.name`, String(tu?.name ?? ""));
|
|
8037
|
-
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.arguments`,
|
|
8434
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.arguments`, safeStringify8(tu?.input ?? {}));
|
|
8038
8435
|
toolIdx++;
|
|
8039
8436
|
}
|
|
8040
8437
|
}
|
|
@@ -8044,7 +8441,7 @@ function finalizeConverse(span2, response) {
|
|
|
8044
8441
|
}
|
|
8045
8442
|
if (response?.stopReason) span2.setAttribute("neatlogs.llm.finish_reason", String(response.stopReason));
|
|
8046
8443
|
setConverseUsage(span2, response?.usage);
|
|
8047
|
-
span2.setStatus({ code:
|
|
8444
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8048
8445
|
span2.end();
|
|
8049
8446
|
}
|
|
8050
8447
|
function setConverseUsage(span2, usage) {
|
|
@@ -8058,7 +8455,7 @@ function setConverseUsage(span2, usage) {
|
|
|
8058
8455
|
function wrapConverseStream(response, span2) {
|
|
8059
8456
|
const stream = response?.stream;
|
|
8060
8457
|
if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
|
|
8061
|
-
span2.setStatus({ code:
|
|
8458
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8062
8459
|
span2.end();
|
|
8063
8460
|
return response;
|
|
8064
8461
|
}
|
|
@@ -8097,7 +8494,7 @@ function wrapConverseStream(response, span2) {
|
|
|
8097
8494
|
if (ev?.metadata?.usage) usage = ev.metadata.usage;
|
|
8098
8495
|
return result;
|
|
8099
8496
|
} catch (err) {
|
|
8100
|
-
|
|
8497
|
+
recordError6(span2, err);
|
|
8101
8498
|
throw err;
|
|
8102
8499
|
}
|
|
8103
8500
|
},
|
|
@@ -8126,7 +8523,7 @@ function finalizeConverseStream(span2, textParts, toolCalls, finishReason, usage
|
|
|
8126
8523
|
}
|
|
8127
8524
|
if (finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(finishReason));
|
|
8128
8525
|
setConverseUsage(span2, usage);
|
|
8129
|
-
span2.setStatus({ code:
|
|
8526
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8130
8527
|
span2.end();
|
|
8131
8528
|
}
|
|
8132
8529
|
function isEmbeddingModel(modelId) {
|
|
@@ -8138,16 +8535,16 @@ function tracedInvokeModel(originalSend, command, input, rest, isStream) {
|
|
|
8138
8535
|
const bodyIn = decodeBody(input?.body);
|
|
8139
8536
|
let span2;
|
|
8140
8537
|
if (isEmbedding) {
|
|
8141
|
-
span2 = getProviderTracer(
|
|
8538
|
+
span2 = getProviderTracer(TRACER_NAME8).startSpan("bedrock.invoke_model", {
|
|
8142
8539
|
attributes: {
|
|
8143
8540
|
"neatlogs.span.kind": "EMBEDDING",
|
|
8144
|
-
"neatlogs.llm.provider":
|
|
8541
|
+
"neatlogs.llm.provider": PROVIDER4,
|
|
8145
8542
|
"neatlogs.embedding.model_name": String(input?.modelId ?? "")
|
|
8146
8543
|
}
|
|
8147
|
-
},
|
|
8544
|
+
}, import_api16.context.active());
|
|
8148
8545
|
const text = bodyIn?.inputText ?? bodyIn?.texts ?? bodyIn?.input_text;
|
|
8149
8546
|
if (text) {
|
|
8150
|
-
span2.setAttribute("neatlogs.embedding.text", typeof text === "string" ? text :
|
|
8547
|
+
span2.setAttribute("neatlogs.embedding.text", typeof text === "string" ? text : safeStringify8(text));
|
|
8151
8548
|
}
|
|
8152
8549
|
} else {
|
|
8153
8550
|
span2 = startSpan(
|
|
@@ -8157,8 +8554,8 @@ function tracedInvokeModel(originalSend, command, input, rest, isStream) {
|
|
|
8157
8554
|
);
|
|
8158
8555
|
setInvokeInput(span2, vendor, bodyIn);
|
|
8159
8556
|
}
|
|
8160
|
-
const ctx =
|
|
8161
|
-
const promise =
|
|
8557
|
+
const ctx = import_api16.trace.setSpan(import_api16.context.active(), span2);
|
|
8558
|
+
const promise = import_api16.context.with(ctx, () => originalSend(command, ...rest));
|
|
8162
8559
|
return promise.then(
|
|
8163
8560
|
(response) => {
|
|
8164
8561
|
if (isStream) {
|
|
@@ -8171,13 +8568,13 @@ function tracedInvokeModel(originalSend, command, input, rest, isStream) {
|
|
|
8171
8568
|
finalizeInvoke(span2, vendor, decodeBody(response?.body));
|
|
8172
8569
|
}
|
|
8173
8570
|
} catch {
|
|
8174
|
-
span2.setStatus({ code:
|
|
8571
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8175
8572
|
span2.end();
|
|
8176
8573
|
}
|
|
8177
8574
|
return response;
|
|
8178
8575
|
},
|
|
8179
8576
|
(err) => {
|
|
8180
|
-
|
|
8577
|
+
recordError6(span2, err);
|
|
8181
8578
|
throw err;
|
|
8182
8579
|
}
|
|
8183
8580
|
);
|
|
@@ -8196,7 +8593,7 @@ function finalizeInvokeEmbedding(span2, body) {
|
|
|
8196
8593
|
span2.setAttribute("neatlogs.llm.token_count.prompt", body.inputTextTokenCount);
|
|
8197
8594
|
span2.setAttribute("neatlogs.embedding.token_count", body.inputTextTokenCount);
|
|
8198
8595
|
}
|
|
8199
|
-
span2.setStatus({ code:
|
|
8596
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8200
8597
|
span2.end();
|
|
8201
8598
|
}
|
|
8202
8599
|
function decodeBody(body) {
|
|
@@ -8218,7 +8615,7 @@ function setInvokeInput(span2, vendor, body) {
|
|
|
8218
8615
|
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "system");
|
|
8219
8616
|
span2.setAttribute(
|
|
8220
8617
|
`neatlogs.llm.input_messages.${idx}.content`,
|
|
8221
|
-
typeof body.system === "string" ? body.system :
|
|
8618
|
+
typeof body.system === "string" ? body.system : safeStringify8(body.system)
|
|
8222
8619
|
);
|
|
8223
8620
|
idx++;
|
|
8224
8621
|
}
|
|
@@ -8227,7 +8624,7 @@ function setInvokeInput(span2, vendor, body) {
|
|
|
8227
8624
|
span2.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, msg?.role ?? "user");
|
|
8228
8625
|
span2.setAttribute(
|
|
8229
8626
|
`neatlogs.llm.input_messages.${idx}.content`,
|
|
8230
|
-
typeof msg?.content === "string" ? msg.content :
|
|
8627
|
+
typeof msg?.content === "string" ? msg.content : safeStringify8(msg?.content)
|
|
8231
8628
|
);
|
|
8232
8629
|
idx++;
|
|
8233
8630
|
}
|
|
@@ -8262,7 +8659,7 @@ function finalizeInvoke(span2, vendor, body) {
|
|
|
8262
8659
|
if (b?.type === "tool_use") {
|
|
8263
8660
|
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.id`, String(b.id ?? ""));
|
|
8264
8661
|
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.name`, String(b.name ?? ""));
|
|
8265
|
-
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.arguments`,
|
|
8662
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${toolIdx}.arguments`, safeStringify8(b.input ?? {}));
|
|
8266
8663
|
toolIdx++;
|
|
8267
8664
|
}
|
|
8268
8665
|
}
|
|
@@ -8304,13 +8701,13 @@ function finalizeInvoke(span2, vendor, body) {
|
|
|
8304
8701
|
span2.setAttribute("neatlogs.llm.token_count.total", promptTokens + completionTokens);
|
|
8305
8702
|
}
|
|
8306
8703
|
if (finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(finishReason));
|
|
8307
|
-
span2.setStatus({ code:
|
|
8704
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8308
8705
|
span2.end();
|
|
8309
8706
|
}
|
|
8310
8707
|
function wrapInvokeStream(response, span2, vendor) {
|
|
8311
8708
|
const body = response?.body;
|
|
8312
8709
|
if (!body || typeof body[Symbol.asyncIterator] !== "function") {
|
|
8313
|
-
span2.setStatus({ code:
|
|
8710
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8314
8711
|
span2.end();
|
|
8315
8712
|
return response;
|
|
8316
8713
|
}
|
|
@@ -8328,7 +8725,7 @@ function wrapInvokeStream(response, span2, vendor) {
|
|
|
8328
8725
|
if (promptTokens != null) span2.setAttribute("neatlogs.llm.token_count.prompt", promptTokens);
|
|
8329
8726
|
if (completionTokens != null) span2.setAttribute("neatlogs.llm.token_count.completion", completionTokens);
|
|
8330
8727
|
if (finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(finishReason));
|
|
8331
|
-
span2.setStatus({ code:
|
|
8728
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.OK });
|
|
8332
8729
|
span2.end();
|
|
8333
8730
|
};
|
|
8334
8731
|
const wrappedBody = {
|
|
@@ -8358,7 +8755,7 @@ function wrapInvokeStream(response, span2, vendor) {
|
|
|
8358
8755
|
}
|
|
8359
8756
|
return result;
|
|
8360
8757
|
} catch (err) {
|
|
8361
|
-
|
|
8758
|
+
recordError6(span2, err);
|
|
8362
8759
|
throw err;
|
|
8363
8760
|
}
|
|
8364
8761
|
},
|
|
@@ -8372,26 +8769,26 @@ function wrapInvokeStream(response, span2, vendor) {
|
|
|
8372
8769
|
response.body = wrappedBody;
|
|
8373
8770
|
return response;
|
|
8374
8771
|
}
|
|
8375
|
-
function
|
|
8772
|
+
function safeStringify8(value) {
|
|
8376
8773
|
try {
|
|
8377
8774
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8378
8775
|
} catch {
|
|
8379
8776
|
return "";
|
|
8380
8777
|
}
|
|
8381
8778
|
}
|
|
8382
|
-
function
|
|
8779
|
+
function recordError6(span2, err) {
|
|
8383
8780
|
if (err instanceof Error) {
|
|
8384
|
-
span2.setStatus({ code:
|
|
8781
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.ERROR, message: err.message });
|
|
8385
8782
|
span2.recordException(err);
|
|
8386
8783
|
} else {
|
|
8387
|
-
span2.setStatus({ code:
|
|
8784
|
+
span2.setStatus({ code: import_api16.SpanStatusCode.ERROR, message: String(err) });
|
|
8388
8785
|
}
|
|
8389
8786
|
span2.end();
|
|
8390
8787
|
}
|
|
8391
8788
|
|
|
8392
8789
|
// src/langchain.ts
|
|
8393
|
-
var
|
|
8394
|
-
var
|
|
8790
|
+
var import_api17 = require("@opentelemetry/api");
|
|
8791
|
+
var TRACER_NAME9 = "neatlogs.langchain";
|
|
8395
8792
|
function langchainHandler(opts) {
|
|
8396
8793
|
return new NeatlogsCallbackHandler(opts);
|
|
8397
8794
|
}
|
|
@@ -8415,10 +8812,10 @@ var NeatlogsCallbackHandler = class {
|
|
|
8415
8812
|
_startCtx(parentRunId, runId, kind) {
|
|
8416
8813
|
const parentSpan = parentRunId ? this._spans.get(parentRunId) : void 0;
|
|
8417
8814
|
if (parentSpan) {
|
|
8418
|
-
return
|
|
8815
|
+
return import_api17.trace.setSpan(import_api17.context.active(), parentSpan);
|
|
8419
8816
|
}
|
|
8420
|
-
const tracer =
|
|
8421
|
-
const { root, ctx } = maybeOpenAutoRoot(tracer, kind,
|
|
8817
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8818
|
+
const { root, ctx } = maybeOpenAutoRoot(tracer, kind, import_api17.context.active());
|
|
8422
8819
|
if (root) this._autoRoots.set(runId, root);
|
|
8423
8820
|
return ctx;
|
|
8424
8821
|
}
|
|
@@ -8431,7 +8828,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8431
8828
|
}
|
|
8432
8829
|
// --- Chain/Graph callbacks ---
|
|
8433
8830
|
async handleChainStart(serialized, inputs, runId, parentRunId, tags, metadata) {
|
|
8434
|
-
const tracer =
|
|
8831
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8435
8832
|
const name = serialized?.name ?? serialized?.id?.at(-1) ?? "chain";
|
|
8436
8833
|
const parentCtx = this._startCtx(parentRunId, runId, "chain");
|
|
8437
8834
|
const attrs = {
|
|
@@ -8439,7 +8836,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8439
8836
|
"neatlogs.chain.name": name
|
|
8440
8837
|
};
|
|
8441
8838
|
if (this._workflowName) attrs["neatlogs.workflow.name"] = this._workflowName;
|
|
8442
|
-
if (inputs) attrs["input.value"] =
|
|
8839
|
+
if (inputs) attrs["input.value"] = safeStringify9(inputs);
|
|
8443
8840
|
if (tags?.length) attrs["neatlogs.tags"] = tags.join(",");
|
|
8444
8841
|
const span2 = tracer.startSpan(`langchain.chain.${name}`, { attributes: attrs }, parentCtx);
|
|
8445
8842
|
this._spans.set(runId, span2);
|
|
@@ -8447,8 +8844,8 @@ var NeatlogsCallbackHandler = class {
|
|
|
8447
8844
|
async handleChainEnd(outputs, runId) {
|
|
8448
8845
|
const span2 = this._spans.get(runId);
|
|
8449
8846
|
if (!span2) return;
|
|
8450
|
-
if (outputs) span2.setAttribute("output.value",
|
|
8451
|
-
span2.setStatus({ code:
|
|
8847
|
+
if (outputs) span2.setAttribute("output.value", safeStringify9(outputs));
|
|
8848
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.OK });
|
|
8452
8849
|
span2.end();
|
|
8453
8850
|
this._spans.delete(runId);
|
|
8454
8851
|
this._endAutoRoot(runId);
|
|
@@ -8456,7 +8853,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8456
8853
|
async handleChainError(error, runId) {
|
|
8457
8854
|
const span2 = this._spans.get(runId);
|
|
8458
8855
|
if (!span2) return;
|
|
8459
|
-
span2.setStatus({ code:
|
|
8856
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.ERROR, message: error.message });
|
|
8460
8857
|
span2.recordException(error);
|
|
8461
8858
|
span2.end();
|
|
8462
8859
|
this._spans.delete(runId);
|
|
@@ -8464,7 +8861,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8464
8861
|
}
|
|
8465
8862
|
// --- LLM callbacks ---
|
|
8466
8863
|
async handleLLMStart(serialized, prompts, runId, parentRunId, extraParams) {
|
|
8467
|
-
const tracer =
|
|
8864
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8468
8865
|
const model = serialized?.kwargs?.model_name ?? serialized?.kwargs?.model ?? serialized?.name ?? "";
|
|
8469
8866
|
const parentCtx = this._startCtx(parentRunId, runId, "llm");
|
|
8470
8867
|
const attrs = {
|
|
@@ -8486,7 +8883,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8486
8883
|
this._spans.set(runId, span2);
|
|
8487
8884
|
}
|
|
8488
8885
|
async handleChatModelStart(serialized, messages, runId, parentRunId, extraParams) {
|
|
8489
|
-
const tracer =
|
|
8886
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8490
8887
|
const model = serialized?.kwargs?.model_name ?? serialized?.kwargs?.model ?? serialized?.name ?? "";
|
|
8491
8888
|
const parentCtx = this._startCtx(parentRunId, runId, "llm");
|
|
8492
8889
|
const attrs = {
|
|
@@ -8498,7 +8895,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8498
8895
|
for (let i = 0; i < flatMessages.length; i++) {
|
|
8499
8896
|
const msg = flatMessages[i];
|
|
8500
8897
|
const role = msg?.role ?? msg?._getType?.() ?? msg?.constructor?.name ?? "unknown";
|
|
8501
|
-
const content = typeof msg?.content === "string" ? msg.content :
|
|
8898
|
+
const content = typeof msg?.content === "string" ? msg.content : safeStringify9(msg?.content);
|
|
8502
8899
|
attrs[`neatlogs.llm.input_messages.${i}.role`] = mapRole(role);
|
|
8503
8900
|
attrs[`neatlogs.llm.input_messages.${i}.content`] = content;
|
|
8504
8901
|
}
|
|
@@ -8529,7 +8926,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8529
8926
|
const tc = toolCalls[k];
|
|
8530
8927
|
span2.setAttribute(`neatlogs.llm.tool_calls.${k}.id`, tc.id ?? "");
|
|
8531
8928
|
span2.setAttribute(`neatlogs.llm.tool_calls.${k}.name`, tc.name ?? tc.function?.name ?? "");
|
|
8532
|
-
span2.setAttribute(`neatlogs.llm.tool_calls.${k}.arguments`, tc.args ?
|
|
8929
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${k}.arguments`, tc.args ? safeStringify9(tc.args) : tc.function?.arguments ?? "");
|
|
8533
8930
|
}
|
|
8534
8931
|
}
|
|
8535
8932
|
}
|
|
@@ -8546,7 +8943,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8546
8943
|
span2.setAttribute("neatlogs.llm.token_count.total", usage.totalTokens ?? usage.total_tokens);
|
|
8547
8944
|
}
|
|
8548
8945
|
}
|
|
8549
|
-
span2.setStatus({ code:
|
|
8946
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.OK });
|
|
8550
8947
|
span2.end();
|
|
8551
8948
|
this._spans.delete(runId);
|
|
8552
8949
|
this._endAutoRoot(runId);
|
|
@@ -8556,7 +8953,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8556
8953
|
async handleLLMError(error, runId) {
|
|
8557
8954
|
const span2 = this._spans.get(runId);
|
|
8558
8955
|
if (!span2) return;
|
|
8559
|
-
span2.setStatus({ code:
|
|
8956
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.ERROR, message: error.message });
|
|
8560
8957
|
span2.recordException(error);
|
|
8561
8958
|
span2.end();
|
|
8562
8959
|
this._spans.delete(runId);
|
|
@@ -8564,7 +8961,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8564
8961
|
}
|
|
8565
8962
|
// --- Tool callbacks ---
|
|
8566
8963
|
async handleToolStart(serialized, input, runId, parentRunId, _tags, _metadata, runName, toolCallId) {
|
|
8567
|
-
const tracer =
|
|
8964
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8568
8965
|
const name = serialized?.name || runName || (Array.isArray(serialized?.id) ? serialized.id[serialized.id.length - 1] : void 0) || "tool";
|
|
8569
8966
|
const parentCtx = this._startCtx(parentRunId, runId, "tool");
|
|
8570
8967
|
const attrs = {
|
|
@@ -8580,7 +8977,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8580
8977
|
const span2 = this._spans.get(runId);
|
|
8581
8978
|
if (!span2) return;
|
|
8582
8979
|
span2.setAttribute("output.value", String(output));
|
|
8583
|
-
span2.setStatus({ code:
|
|
8980
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.OK });
|
|
8584
8981
|
span2.end();
|
|
8585
8982
|
this._spans.delete(runId);
|
|
8586
8983
|
this._endAutoRoot(runId);
|
|
@@ -8588,7 +8985,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8588
8985
|
async handleToolError(error, runId) {
|
|
8589
8986
|
const span2 = this._spans.get(runId);
|
|
8590
8987
|
if (!span2) return;
|
|
8591
|
-
span2.setStatus({ code:
|
|
8988
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.ERROR, message: error.message });
|
|
8592
8989
|
span2.recordException(error);
|
|
8593
8990
|
span2.end();
|
|
8594
8991
|
this._spans.delete(runId);
|
|
@@ -8596,7 +8993,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8596
8993
|
}
|
|
8597
8994
|
// --- Retriever callbacks ---
|
|
8598
8995
|
async handleRetrieverStart(serialized, query, runId, parentRunId) {
|
|
8599
|
-
const tracer =
|
|
8996
|
+
const tracer = import_api17.trace.getTracer(TRACER_NAME9);
|
|
8600
8997
|
const name = serialized?.name ?? "retriever";
|
|
8601
8998
|
const parentCtx = this._startCtx(parentRunId, runId, "retriever");
|
|
8602
8999
|
const attrs = {
|
|
@@ -8619,7 +9016,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8619
9016
|
}
|
|
8620
9017
|
}
|
|
8621
9018
|
}
|
|
8622
|
-
span2.setStatus({ code:
|
|
9019
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.OK });
|
|
8623
9020
|
span2.end();
|
|
8624
9021
|
this._spans.delete(runId);
|
|
8625
9022
|
this._endAutoRoot(runId);
|
|
@@ -8627,7 +9024,7 @@ var NeatlogsCallbackHandler = class {
|
|
|
8627
9024
|
async handleRetrieverError(error, runId) {
|
|
8628
9025
|
const span2 = this._spans.get(runId);
|
|
8629
9026
|
if (!span2) return;
|
|
8630
|
-
span2.setStatus({ code:
|
|
9027
|
+
span2.setStatus({ code: import_api17.SpanStatusCode.ERROR, message: error.message });
|
|
8631
9028
|
span2.recordException(error);
|
|
8632
9029
|
span2.end();
|
|
8633
9030
|
this._spans.delete(runId);
|
|
@@ -8652,7 +9049,7 @@ function mapRole(role) {
|
|
|
8652
9049
|
if (r === "tool" || r === "toolmessage") return "tool";
|
|
8653
9050
|
return role;
|
|
8654
9051
|
}
|
|
8655
|
-
function
|
|
9052
|
+
function safeStringify9(value) {
|
|
8656
9053
|
try {
|
|
8657
9054
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8658
9055
|
} catch {
|
|
@@ -8728,7 +9125,7 @@ function setOutput(span2, isTool, out) {
|
|
|
8728
9125
|
} else {
|
|
8729
9126
|
span2.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
|
|
8730
9127
|
span2.setAttribute("neatlogs.llm.output_messages.0.content", out);
|
|
8731
|
-
span2.setAttribute("neatlogs.llm.output",
|
|
9128
|
+
span2.setAttribute("neatlogs.llm.output", safeStringify10({ role: "assistant", content: out }));
|
|
8732
9129
|
}
|
|
8733
9130
|
}
|
|
8734
9131
|
function appendInputMessage(span2, role, content) {
|
|
@@ -8739,7 +9136,7 @@ function appendInputMessage(span2, role, content) {
|
|
|
8739
9136
|
const existing = span2.__neatlogs_in_msgs ?? [];
|
|
8740
9137
|
existing.push({ role, content });
|
|
8741
9138
|
span2.__neatlogs_in_msgs = existing;
|
|
8742
|
-
const blob =
|
|
9139
|
+
const blob = safeStringify10({ messages: existing });
|
|
8743
9140
|
span2.setAttribute("input.value", blob);
|
|
8744
9141
|
span2.setAttribute("neatlogs.llm.input", blob);
|
|
8745
9142
|
}
|
|
@@ -8782,15 +9179,15 @@ function flattenBlocks(val) {
|
|
|
8782
9179
|
const o = item;
|
|
8783
9180
|
if (typeof o.text === "string") out.push(o.text);
|
|
8784
9181
|
else if (typeof o.content === "string") out.push(o.content);
|
|
8785
|
-
else if (o.toolUse) out.push(`${o.toolUse.name ?? "tool"}(${
|
|
9182
|
+
else if (o.toolUse) out.push(`${o.toolUse.name ?? "tool"}(${safeStringify10(o.toolUse.input ?? {})})`);
|
|
8786
9183
|
else if (o.toolResult) out.push(flattenBlocks(o.toolResult.content ?? o.toolResult));
|
|
8787
9184
|
else if (Array.isArray(o.parts)) out.push(flattenBlocks(o.parts));
|
|
8788
9185
|
else if (Array.isArray(o.content)) out.push(flattenBlocks(o.content));
|
|
8789
|
-
else out.push(
|
|
9186
|
+
else out.push(safeStringify10(o));
|
|
8790
9187
|
}
|
|
8791
9188
|
return out.filter(Boolean).join("\n");
|
|
8792
9189
|
}
|
|
8793
|
-
function
|
|
9190
|
+
function safeStringify10(value) {
|
|
8794
9191
|
if (typeof value === "string") return value;
|
|
8795
9192
|
try {
|
|
8796
9193
|
return JSON.stringify(value) ?? "";
|
|
@@ -8800,8 +9197,8 @@ function safeStringify9(value) {
|
|
|
8800
9197
|
}
|
|
8801
9198
|
|
|
8802
9199
|
// src/openai-agents.ts
|
|
8803
|
-
var
|
|
8804
|
-
var
|
|
9200
|
+
var import_api18 = require("@opentelemetry/api");
|
|
9201
|
+
var TRACER_NAME10 = "neatlogs.openai_agents";
|
|
8805
9202
|
function openaiAgentsProcessor() {
|
|
8806
9203
|
return new NeatlogsTraceProcessor();
|
|
8807
9204
|
}
|
|
@@ -8810,13 +9207,13 @@ var NeatlogsTraceProcessor = class {
|
|
|
8810
9207
|
_startTimes = /* @__PURE__ */ new Map();
|
|
8811
9208
|
// The @openai/agents SDK passes a Trace object: { traceId, name, groupId, metadata }.
|
|
8812
9209
|
onTraceStart(traceData) {
|
|
8813
|
-
const tracer =
|
|
9210
|
+
const tracer = import_api18.trace.getTracer(TRACER_NAME10);
|
|
8814
9211
|
const attrs = { "neatlogs.span.kind": "WORKFLOW" };
|
|
8815
9212
|
const workflowName = traceData?.name ?? traceData?.workflow_name;
|
|
8816
9213
|
if (workflowName) attrs["neatlogs.workflow.name"] = workflowName;
|
|
8817
9214
|
const traceId = traceData?.traceId ?? traceData?.trace_id;
|
|
8818
9215
|
if (traceId) attrs["neatlogs.agent.trace_id"] = String(traceId);
|
|
8819
|
-
const span2 = tracer.startSpan("openai_agents.trace", { attributes: attrs },
|
|
9216
|
+
const span2 = tracer.startSpan("openai_agents.trace", { attributes: attrs }, import_api18.context.active());
|
|
8820
9217
|
const key = String(traceId ?? `trace_${Date.now()}`);
|
|
8821
9218
|
this._spans.set(key, span2);
|
|
8822
9219
|
this._startTimes.set(key, Date.now());
|
|
@@ -8829,7 +9226,7 @@ var NeatlogsTraceProcessor = class {
|
|
|
8829
9226
|
if (startTime) {
|
|
8830
9227
|
span2.setAttribute("neatlogs.metrics.duration_ms", Date.now() - startTime);
|
|
8831
9228
|
}
|
|
8832
|
-
span2.setStatus({ code:
|
|
9229
|
+
span2.setStatus({ code: import_api18.SpanStatusCode.OK });
|
|
8833
9230
|
span2.end();
|
|
8834
9231
|
this._spans.delete(key);
|
|
8835
9232
|
this._startTimes.delete(key);
|
|
@@ -8837,13 +9234,13 @@ var NeatlogsTraceProcessor = class {
|
|
|
8837
9234
|
// The SDK passes a Span object: { type, spanId, traceId, parentId?, spanData: {...} }.
|
|
8838
9235
|
// The meaningful payload (type, name, input, output, usage, ...) lives in `spanData`.
|
|
8839
9236
|
onSpanStart(span2) {
|
|
8840
|
-
const tracer =
|
|
9237
|
+
const tracer = import_api18.trace.getTracer(TRACER_NAME10);
|
|
8841
9238
|
const data = span2?.spanData ?? span2 ?? {};
|
|
8842
9239
|
const spanType = data?.type ?? data?.span_type ?? span2?.type ?? "";
|
|
8843
9240
|
const spanId = String(span2?.spanId ?? span2?.span_id ?? data?.span_id ?? `span_${Date.now()}`);
|
|
8844
9241
|
const parentKey = String(span2?.parentId ?? span2?.traceId ?? span2?.trace_id ?? "");
|
|
8845
9242
|
const parentSpan = this._spans.get(parentKey);
|
|
8846
|
-
const parentCtx = parentSpan ?
|
|
9243
|
+
const parentCtx = parentSpan ? import_api18.trace.setSpan(import_api18.context.active(), parentSpan) : import_api18.context.active();
|
|
8847
9244
|
let otelSpan;
|
|
8848
9245
|
if (spanType === "agent" || spanType === "agent_run") {
|
|
8849
9246
|
const agentName = data?.name ?? data?.agent_name ?? "agent";
|
|
@@ -8869,7 +9266,7 @@ var NeatlogsTraceProcessor = class {
|
|
|
8869
9266
|
const role = typeof msg === "object" ? msg.role ?? "" : "";
|
|
8870
9267
|
const content = typeof msg === "object" ? msg.content ?? "" : String(msg);
|
|
8871
9268
|
if (role) attrs[`neatlogs.llm.input_messages.${i}.role`] = role;
|
|
8872
|
-
if (content) attrs[`neatlogs.llm.input_messages.${i}.content`] = typeof content === "string" ? content :
|
|
9269
|
+
if (content) attrs[`neatlogs.llm.input_messages.${i}.content`] = typeof content === "string" ? content : safeStringify11(content);
|
|
8873
9270
|
}
|
|
8874
9271
|
}
|
|
8875
9272
|
otelSpan = tracer.startSpan("openai_agents.generation", { attributes: attrs }, parentCtx);
|
|
@@ -8881,7 +9278,7 @@ var NeatlogsTraceProcessor = class {
|
|
|
8881
9278
|
};
|
|
8882
9279
|
const toolInput = data?.input ?? data?.arguments;
|
|
8883
9280
|
if (toolInput !== void 0) {
|
|
8884
|
-
attrs["input.value"] = typeof toolInput === "string" ? toolInput :
|
|
9281
|
+
attrs["input.value"] = typeof toolInput === "string" ? toolInput : safeStringify11(toolInput);
|
|
8885
9282
|
}
|
|
8886
9283
|
otelSpan = tracer.startSpan(`openai_agents.tool.${toolName}`, { attributes: attrs }, parentCtx);
|
|
8887
9284
|
} else if (spanType === "handoff") {
|
|
@@ -8918,13 +9315,13 @@ var NeatlogsTraceProcessor = class {
|
|
|
8918
9315
|
for (let i = 0; i < toolCalls.length; i++) {
|
|
8919
9316
|
const tc = toolCalls[i];
|
|
8920
9317
|
otelSpan.setAttribute(`neatlogs.llm.tool_calls.${i}.name`, tc.name ?? "");
|
|
8921
|
-
otelSpan.setAttribute(`neatlogs.llm.tool_calls.${i}.arguments`, typeof tc.arguments === "string" ? tc.arguments :
|
|
9318
|
+
otelSpan.setAttribute(`neatlogs.llm.tool_calls.${i}.arguments`, typeof tc.arguments === "string" ? tc.arguments : safeStringify11(tc.arguments ?? {}));
|
|
8922
9319
|
if (tc.callId ?? tc.id) otelSpan.setAttribute(`neatlogs.llm.tool_calls.${i}.id`, tc.callId ?? tc.id);
|
|
8923
9320
|
}
|
|
8924
9321
|
} else if (outputItems?.content) {
|
|
8925
9322
|
otelSpan.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
|
|
8926
9323
|
const c = outputItems.content;
|
|
8927
|
-
otelSpan.setAttribute("neatlogs.llm.output_messages.0.content", typeof c === "string" ? c :
|
|
9324
|
+
otelSpan.setAttribute("neatlogs.llm.output_messages.0.content", typeof c === "string" ? c : safeStringify11(c));
|
|
8928
9325
|
}
|
|
8929
9326
|
const usage = data?.usage ?? resp?.usage;
|
|
8930
9327
|
if (usage) {
|
|
@@ -8941,24 +9338,24 @@ var NeatlogsTraceProcessor = class {
|
|
|
8941
9338
|
} else if (spanType === "function" || spanType === "tool" || spanType === "tool_call") {
|
|
8942
9339
|
const output = data?.output ?? data?.result;
|
|
8943
9340
|
if (output != null) {
|
|
8944
|
-
otelSpan.setAttribute("output.value", typeof output === "string" ? output :
|
|
9341
|
+
otelSpan.setAttribute("output.value", typeof output === "string" ? output : safeStringify11(output));
|
|
8945
9342
|
}
|
|
8946
9343
|
} else if (spanType === "agent" || spanType === "agent_run") {
|
|
8947
9344
|
const output = data?.output;
|
|
8948
9345
|
if (output != null) {
|
|
8949
|
-
otelSpan.setAttribute("output.value", typeof output === "string" ? output :
|
|
9346
|
+
otelSpan.setAttribute("output.value", typeof output === "string" ? output : safeStringify11(output));
|
|
8950
9347
|
}
|
|
8951
9348
|
}
|
|
8952
9349
|
const error = data?.error ?? span2?.error;
|
|
8953
9350
|
if (error) {
|
|
8954
9351
|
if (error instanceof Error) {
|
|
8955
|
-
otelSpan.setStatus({ code:
|
|
9352
|
+
otelSpan.setStatus({ code: import_api18.SpanStatusCode.ERROR, message: error.message });
|
|
8956
9353
|
otelSpan.recordException(error);
|
|
8957
9354
|
} else {
|
|
8958
|
-
otelSpan.setStatus({ code:
|
|
9355
|
+
otelSpan.setStatus({ code: import_api18.SpanStatusCode.ERROR, message: String(error) });
|
|
8959
9356
|
}
|
|
8960
9357
|
} else {
|
|
8961
|
-
otelSpan.setStatus({ code:
|
|
9358
|
+
otelSpan.setStatus({ code: import_api18.SpanStatusCode.OK });
|
|
8962
9359
|
}
|
|
8963
9360
|
if (startTime) {
|
|
8964
9361
|
otelSpan.setAttribute("neatlogs.llm.metrics.duration_ms", Date.now() - startTime);
|
|
@@ -8969,7 +9366,7 @@ var NeatlogsTraceProcessor = class {
|
|
|
8969
9366
|
}
|
|
8970
9367
|
shutdown() {
|
|
8971
9368
|
for (const [, span2] of this._spans) {
|
|
8972
|
-
span2.setStatus({ code:
|
|
9369
|
+
span2.setStatus({ code: import_api18.SpanStatusCode.ERROR, message: "Processor shutdown before span completed" });
|
|
8973
9370
|
span2.end();
|
|
8974
9371
|
}
|
|
8975
9372
|
this._spans.clear();
|
|
@@ -8978,7 +9375,7 @@ var NeatlogsTraceProcessor = class {
|
|
|
8978
9375
|
forceFlush() {
|
|
8979
9376
|
}
|
|
8980
9377
|
};
|
|
8981
|
-
function
|
|
9378
|
+
function safeStringify11(value) {
|
|
8982
9379
|
try {
|
|
8983
9380
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8984
9381
|
} catch {
|
|
@@ -8987,8 +9384,8 @@ function safeStringify10(value) {
|
|
|
8987
9384
|
}
|
|
8988
9385
|
|
|
8989
9386
|
// src/mastra-wrap.ts
|
|
8990
|
-
var
|
|
8991
|
-
var
|
|
9387
|
+
var import_api19 = require("@opentelemetry/api");
|
|
9388
|
+
var TRACER_NAME11 = "neatlogs.mastra";
|
|
8992
9389
|
var PATCH_FLAG2 = "_neatlogs_patched";
|
|
8993
9390
|
function wrapMastra(entity) {
|
|
8994
9391
|
if (!entity || entity[PATCH_FLAG2]) return entity;
|
|
@@ -9054,14 +9451,14 @@ function patchAgentMethod(agent, method, streaming) {
|
|
|
9054
9451
|
}
|
|
9055
9452
|
if (streaming) attrs["neatlogs.llm.is_streaming"] = true;
|
|
9056
9453
|
if (streaming) {
|
|
9057
|
-
const tracer =
|
|
9058
|
-
const span2 = tracer.startSpan(`mastra.agent.${agentName}`, { attributes: attrs },
|
|
9059
|
-
const ctx =
|
|
9454
|
+
const tracer = import_api19.trace.getTracer(TRACER_NAME11);
|
|
9455
|
+
const span2 = tracer.startSpan(`mastra.agent.${agentName}`, { attributes: attrs }, import_api19.context.active());
|
|
9456
|
+
const ctx = import_api19.trace.setSpan(import_api19.context.active(), span2);
|
|
9060
9457
|
try {
|
|
9061
|
-
const result = await
|
|
9458
|
+
const result = await import_api19.context.with(ctx, () => orig(input, opts));
|
|
9062
9459
|
return wrapStreamingOutput(result, span2, ctx);
|
|
9063
9460
|
} catch (err) {
|
|
9064
|
-
|
|
9461
|
+
recordError7(span2, err);
|
|
9065
9462
|
span2.end();
|
|
9066
9463
|
throw err;
|
|
9067
9464
|
}
|
|
@@ -9104,7 +9501,7 @@ function patchModelInPlace(model) {
|
|
|
9104
9501
|
if (provider) attrs["neatlogs.llm.provider"] = provider;
|
|
9105
9502
|
if (isStream) attrs["neatlogs.llm.is_streaming"] = true;
|
|
9106
9503
|
const promptInput = callOpts?.prompt ?? callOpts?.messages;
|
|
9107
|
-
if (promptInput !== void 0) attrs["input.value"] =
|
|
9504
|
+
if (promptInput !== void 0) attrs["input.value"] = safeStringify12(promptInput);
|
|
9108
9505
|
captureInvocationParams(attrs, callOpts);
|
|
9109
9506
|
return withActiveSpan(`mastra.llm.${modelId || "model"}.${fn}`, attrs, async (span2) => {
|
|
9110
9507
|
const result = await orig(callOpts);
|
|
@@ -9138,12 +9535,12 @@ function patchToolExecute(tool, key) {
|
|
|
9138
9535
|
const attrs = {
|
|
9139
9536
|
"neatlogs.span.kind": "TOOL",
|
|
9140
9537
|
"neatlogs.tool.name": toolName,
|
|
9141
|
-
"input.value":
|
|
9538
|
+
"input.value": safeStringify12(params)
|
|
9142
9539
|
};
|
|
9143
9540
|
if (tool.description) attrs["neatlogs.tool.description"] = String(tool.description);
|
|
9144
9541
|
return withActiveSpan(`mastra.tool.${toolName}`, attrs, async (span2) => {
|
|
9145
9542
|
const result = await orig(params, options);
|
|
9146
|
-
span2.setAttribute("output.value",
|
|
9543
|
+
span2.setAttribute("output.value", safeStringify12(result));
|
|
9147
9544
|
return result;
|
|
9148
9545
|
});
|
|
9149
9546
|
};
|
|
@@ -9169,13 +9566,13 @@ function patchRunMethod(run, method, workflowName) {
|
|
|
9169
9566
|
"neatlogs.workflow.name": workflowName
|
|
9170
9567
|
};
|
|
9171
9568
|
if (startOpts?.inputData !== void 0) {
|
|
9172
|
-
attrs["input.value"] =
|
|
9569
|
+
attrs["input.value"] = safeStringify12(startOpts.inputData);
|
|
9173
9570
|
}
|
|
9174
9571
|
return withActiveSpan(`mastra.workflow.${workflowName}`, attrs, async (span2) => {
|
|
9175
9572
|
const result = await orig(startOpts);
|
|
9176
|
-
if (result?.status) span2.setAttribute("neatlogs.metadata",
|
|
9573
|
+
if (result?.status) span2.setAttribute("neatlogs.metadata", safeStringify12({ status: result.status }));
|
|
9177
9574
|
if (result?.result !== void 0) {
|
|
9178
|
-
span2.setAttribute("output.value",
|
|
9575
|
+
span2.setAttribute("output.value", safeStringify12(result.result));
|
|
9179
9576
|
}
|
|
9180
9577
|
return result;
|
|
9181
9578
|
});
|
|
@@ -9196,14 +9593,14 @@ function patchVectorOp(vector, op, kind) {
|
|
|
9196
9593
|
"neatlogs.span.kind": kind,
|
|
9197
9594
|
"neatlogs.db.system": dbName,
|
|
9198
9595
|
"neatlogs.db.operation": op,
|
|
9199
|
-
"input.value":
|
|
9596
|
+
"input.value": safeStringify12(params)
|
|
9200
9597
|
};
|
|
9201
9598
|
const indexName = params?.indexName;
|
|
9202
9599
|
if (indexName) attrs["neatlogs.vectordb.index_name"] = String(indexName);
|
|
9203
9600
|
if (kind === "RETRIEVER" && params?.topK != null) attrs["neatlogs.retriever.top_k"] = params.topK;
|
|
9204
9601
|
return withActiveSpan(`mastra.vector.${op}`, attrs, async (span2) => {
|
|
9205
9602
|
const result = await orig(params);
|
|
9206
|
-
span2.setAttribute("output.value",
|
|
9603
|
+
span2.setAttribute("output.value", safeStringify12(result));
|
|
9207
9604
|
return result;
|
|
9208
9605
|
});
|
|
9209
9606
|
};
|
|
@@ -9217,11 +9614,11 @@ function patchMemory(memory) {
|
|
|
9217
9614
|
const attrs = {
|
|
9218
9615
|
"neatlogs.span.kind": "CHAIN",
|
|
9219
9616
|
"neatlogs.db.operation": op,
|
|
9220
|
-
"input.value":
|
|
9617
|
+
"input.value": safeStringify12(args?.[0])
|
|
9221
9618
|
};
|
|
9222
9619
|
return withActiveSpan(`mastra.memory.${op}`, attrs, async (span2) => {
|
|
9223
9620
|
const result = await orig(...args);
|
|
9224
|
-
span2.setAttribute("output.value",
|
|
9621
|
+
span2.setAttribute("output.value", safeStringify12(result));
|
|
9225
9622
|
return result;
|
|
9226
9623
|
});
|
|
9227
9624
|
};
|
|
@@ -9262,7 +9659,7 @@ function wrapRootMastra(mastra) {
|
|
|
9262
9659
|
}
|
|
9263
9660
|
function wrapStreamingOutput(output, span2, ctx) {
|
|
9264
9661
|
if (!output) {
|
|
9265
|
-
span2.setStatus({ code:
|
|
9662
|
+
span2.setStatus({ code: import_api19.SpanStatusCode.OK });
|
|
9266
9663
|
span2.end();
|
|
9267
9664
|
return output;
|
|
9268
9665
|
}
|
|
@@ -9270,8 +9667,8 @@ function wrapStreamingOutput(output, span2, ctx) {
|
|
|
9270
9667
|
const endOnce = (err) => {
|
|
9271
9668
|
if (ended) return;
|
|
9272
9669
|
ended = true;
|
|
9273
|
-
if (err)
|
|
9274
|
-
else span2.setStatus({ code:
|
|
9670
|
+
if (err) recordError7(span2, err);
|
|
9671
|
+
else span2.setStatus({ code: import_api19.SpanStatusCode.OK });
|
|
9275
9672
|
span2.end();
|
|
9276
9673
|
};
|
|
9277
9674
|
if (output.text && typeof output.text.then === "function") {
|
|
@@ -9362,7 +9759,7 @@ function rebindStreamContext(output, ctx) {
|
|
|
9362
9759
|
const origIterator = value[Symbol.asyncIterator].bind(value);
|
|
9363
9760
|
return {
|
|
9364
9761
|
[Symbol.asyncIterator]() {
|
|
9365
|
-
return
|
|
9762
|
+
return import_api19.context.with(ctx, () => origIterator());
|
|
9366
9763
|
}
|
|
9367
9764
|
};
|
|
9368
9765
|
}
|
|
@@ -9404,7 +9801,7 @@ function finalizeModelResult(span2, result) {
|
|
|
9404
9801
|
const tc = toolCalls[i];
|
|
9405
9802
|
setToolCall(span2, i, tc.toolName, tc.input ?? tc.args, tc.toolCallId);
|
|
9406
9803
|
}
|
|
9407
|
-
span2.setAttribute("output.value",
|
|
9804
|
+
span2.setAttribute("output.value", safeStringify12(result.content));
|
|
9408
9805
|
}
|
|
9409
9806
|
if (result.usage) recordUsage(span2, result.usage);
|
|
9410
9807
|
span2.setAttribute("neatlogs.llm.stop_reason", normalizeFinishReason(result.finishReason));
|
|
@@ -9412,7 +9809,7 @@ function finalizeModelResult(span2, result) {
|
|
|
9412
9809
|
function normalizeFinishReason(fr) {
|
|
9413
9810
|
if (fr == null) return "";
|
|
9414
9811
|
if (typeof fr === "string") return fr;
|
|
9415
|
-
return String(fr.unified ?? fr.reason ?? fr.type ??
|
|
9812
|
+
return String(fr.unified ?? fr.reason ?? fr.type ?? safeStringify12(fr));
|
|
9416
9813
|
}
|
|
9417
9814
|
function tokenValue(v) {
|
|
9418
9815
|
if (v == null) return void 0;
|
|
@@ -9441,22 +9838,22 @@ function captureInvocationParams(attrs, callOpts) {
|
|
|
9441
9838
|
}
|
|
9442
9839
|
}
|
|
9443
9840
|
if (Array.isArray(callOpts.stopSequences) && callOpts.stopSequences.length) {
|
|
9444
|
-
attrs["neatlogs.llm.stop_sequences"] =
|
|
9841
|
+
attrs["neatlogs.llm.stop_sequences"] = safeStringify12(callOpts.stopSequences);
|
|
9445
9842
|
invocation.stopSequences = callOpts.stopSequences;
|
|
9446
9843
|
}
|
|
9447
9844
|
if (Array.isArray(callOpts.tools)) {
|
|
9448
9845
|
for (let i = 0; i < callOpts.tools.length; i++) {
|
|
9449
|
-
attrs[`neatlogs.llm.tools.${i}`] =
|
|
9846
|
+
attrs[`neatlogs.llm.tools.${i}`] = safeStringify12(callOpts.tools[i]);
|
|
9450
9847
|
}
|
|
9451
9848
|
invocation.toolChoice = callOpts.toolChoice;
|
|
9452
9849
|
}
|
|
9453
9850
|
if (Object.keys(invocation).length) {
|
|
9454
|
-
attrs["neatlogs.llm.invocation_parameters"] =
|
|
9851
|
+
attrs["neatlogs.llm.invocation_parameters"] = safeStringify12(invocation);
|
|
9455
9852
|
}
|
|
9456
9853
|
}
|
|
9457
9854
|
function setToolCall(span2, i, name, args, id) {
|
|
9458
9855
|
span2.setAttribute(`neatlogs.llm.tool_calls.${i}.name`, name ?? "");
|
|
9459
|
-
span2.setAttribute(`neatlogs.llm.tool_calls.${i}.arguments`,
|
|
9856
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${i}.arguments`, safeStringify12(args ?? {}));
|
|
9460
9857
|
if (id) span2.setAttribute(`neatlogs.llm.tool_calls.${i}.id`, id);
|
|
9461
9858
|
}
|
|
9462
9859
|
function recordUsage(span2, usage) {
|
|
@@ -9472,16 +9869,16 @@ function recordUsage(span2, usage) {
|
|
|
9472
9869
|
}
|
|
9473
9870
|
}
|
|
9474
9871
|
function withActiveSpan(name, attrs, fn) {
|
|
9475
|
-
const tracer =
|
|
9476
|
-
const span2 = tracer.startSpan(name, { attributes: attrs },
|
|
9477
|
-
const ctx =
|
|
9478
|
-
return
|
|
9872
|
+
const tracer = import_api19.trace.getTracer(TRACER_NAME11);
|
|
9873
|
+
const span2 = tracer.startSpan(name, { attributes: attrs }, import_api19.context.active());
|
|
9874
|
+
const ctx = import_api19.trace.setSpan(import_api19.context.active(), span2);
|
|
9875
|
+
return import_api19.context.with(ctx, async () => {
|
|
9479
9876
|
try {
|
|
9480
9877
|
const result = await fn(span2);
|
|
9481
|
-
span2.setStatus({ code:
|
|
9878
|
+
span2.setStatus({ code: import_api19.SpanStatusCode.OK });
|
|
9482
9879
|
return result;
|
|
9483
9880
|
} catch (err) {
|
|
9484
|
-
|
|
9881
|
+
recordError7(span2, err);
|
|
9485
9882
|
throw err;
|
|
9486
9883
|
} finally {
|
|
9487
9884
|
span2.end();
|
|
@@ -9501,9 +9898,9 @@ function extractModelId(model) {
|
|
|
9501
9898
|
return model.modelId ?? model.name ?? "";
|
|
9502
9899
|
}
|
|
9503
9900
|
function toInputValue(input) {
|
|
9504
|
-
return typeof input === "string" ? input :
|
|
9901
|
+
return typeof input === "string" ? input : safeStringify12(input);
|
|
9505
9902
|
}
|
|
9506
|
-
function
|
|
9903
|
+
function safeStringify12(value) {
|
|
9507
9904
|
if (typeof value === "string") return value;
|
|
9508
9905
|
try {
|
|
9509
9906
|
return JSON.stringify(value) ?? "";
|
|
@@ -9511,25 +9908,25 @@ function safeStringify11(value) {
|
|
|
9511
9908
|
return "";
|
|
9512
9909
|
}
|
|
9513
9910
|
}
|
|
9514
|
-
function
|
|
9911
|
+
function recordError7(span2, err) {
|
|
9515
9912
|
if (err instanceof Error) {
|
|
9516
|
-
span2.setStatus({ code:
|
|
9913
|
+
span2.setStatus({ code: import_api19.SpanStatusCode.ERROR, message: err.message });
|
|
9517
9914
|
span2.recordException(err);
|
|
9518
9915
|
} else {
|
|
9519
|
-
span2.setStatus({ code:
|
|
9916
|
+
span2.setStatus({ code: import_api19.SpanStatusCode.ERROR, message: String(err) });
|
|
9520
9917
|
}
|
|
9521
9918
|
}
|
|
9522
9919
|
|
|
9523
9920
|
// src/pi-agent.ts
|
|
9524
|
-
var
|
|
9525
|
-
var
|
|
9921
|
+
var import_api20 = require("@opentelemetry/api");
|
|
9922
|
+
var TRACER_NAME12 = "neatlogs.pi-agent";
|
|
9526
9923
|
var PATCH_FLAG3 = "_neatlogs_patched";
|
|
9527
9924
|
function piAgentHooks(agent) {
|
|
9528
9925
|
if (!agent || agent[PATCH_FLAG3]) return agent;
|
|
9529
9926
|
const a = agent;
|
|
9530
9927
|
if (typeof a.subscribe !== "function") return agent;
|
|
9531
9928
|
const state = { toolSpans: /* @__PURE__ */ new Map(), inputMessages: [] };
|
|
9532
|
-
const tracer =
|
|
9929
|
+
const tracer = import_api20.trace.getTracer(TRACER_NAME12);
|
|
9533
9930
|
a.subscribe((event) => {
|
|
9534
9931
|
try {
|
|
9535
9932
|
handleEvent(tracer, state, event);
|
|
@@ -9545,10 +9942,10 @@ function handleEvent(tracer, state, event) {
|
|
|
9545
9942
|
const span2 = tracer.startSpan(
|
|
9546
9943
|
"pi_agent.run",
|
|
9547
9944
|
{ attributes: { "neatlogs.span.kind": "AGENT" } },
|
|
9548
|
-
|
|
9945
|
+
import_api20.context.active()
|
|
9549
9946
|
);
|
|
9550
9947
|
state.agentSpan = span2;
|
|
9551
|
-
state.agentCtx =
|
|
9948
|
+
state.agentCtx = import_api20.trace.setSpan(import_api20.context.active(), span2);
|
|
9552
9949
|
state.inputMessages = [];
|
|
9553
9950
|
break;
|
|
9554
9951
|
}
|
|
@@ -9567,14 +9964,14 @@ function handleEvent(tracer, state, event) {
|
|
|
9567
9964
|
break;
|
|
9568
9965
|
}
|
|
9569
9966
|
case "tool_execution_start": {
|
|
9570
|
-
const parent = state.agentCtx ??
|
|
9967
|
+
const parent = state.agentCtx ?? import_api20.context.active();
|
|
9571
9968
|
const span2 = tracer.startSpan(
|
|
9572
9969
|
`pi_agent.tool.${event.toolName ?? "tool"}`,
|
|
9573
9970
|
{
|
|
9574
9971
|
attributes: {
|
|
9575
9972
|
"neatlogs.span.kind": "TOOL",
|
|
9576
9973
|
...event.toolName ? { "neatlogs.tool.name": String(event.toolName) } : {},
|
|
9577
|
-
...event.args !== void 0 ? { "input.value":
|
|
9974
|
+
...event.args !== void 0 ? { "input.value": safeStringify13(event.args) } : {}
|
|
9578
9975
|
}
|
|
9579
9976
|
},
|
|
9580
9977
|
parent
|
|
@@ -9586,13 +9983,13 @@ function handleEvent(tracer, state, event) {
|
|
|
9586
9983
|
const span2 = event.toolCallId ? state.toolSpans.get(event.toolCallId) : void 0;
|
|
9587
9984
|
if (!span2) return;
|
|
9588
9985
|
if (event.result !== void 0) {
|
|
9589
|
-
span2.setAttribute("output.value",
|
|
9986
|
+
span2.setAttribute("output.value", safeStringify13(event.result));
|
|
9590
9987
|
}
|
|
9591
9988
|
if (event.isError) {
|
|
9592
|
-
span2.setStatus({ code:
|
|
9989
|
+
span2.setStatus({ code: import_api20.SpanStatusCode.ERROR });
|
|
9593
9990
|
span2.setAttribute("neatlogs.tool.is_error", true);
|
|
9594
9991
|
} else {
|
|
9595
|
-
span2.setStatus({ code:
|
|
9992
|
+
span2.setStatus({ code: import_api20.SpanStatusCode.OK });
|
|
9596
9993
|
}
|
|
9597
9994
|
span2.end();
|
|
9598
9995
|
if (event.toolCallId) state.toolSpans.delete(event.toolCallId);
|
|
@@ -9611,7 +10008,7 @@ function handleEvent(tracer, state, event) {
|
|
|
9611
10008
|
if (firstUser) state.agentSpan.setAttribute("input.value", firstUser.content);
|
|
9612
10009
|
const finalText = lastAssistantText(event.messages);
|
|
9613
10010
|
if (finalText) state.agentSpan.setAttribute("output.value", finalText);
|
|
9614
|
-
state.agentSpan.setStatus({ code:
|
|
10011
|
+
state.agentSpan.setStatus({ code: import_api20.SpanStatusCode.OK });
|
|
9615
10012
|
state.agentSpan.end();
|
|
9616
10013
|
state.agentSpan = void 0;
|
|
9617
10014
|
state.agentCtx = void 0;
|
|
@@ -9633,11 +10030,11 @@ function emitLlmSpan(tracer, state, msg) {
|
|
|
9633
10030
|
attrs[`neatlogs.llm.input_messages.${i}.role`] = m.role;
|
|
9634
10031
|
attrs[`neatlogs.llm.input_messages.${i}.content`] = m.content;
|
|
9635
10032
|
});
|
|
9636
|
-
attrs["neatlogs.llm.input"] =
|
|
9637
|
-
attrs["input.value"] =
|
|
10033
|
+
attrs["neatlogs.llm.input"] = safeStringify13({ messages: inMsgs });
|
|
10034
|
+
attrs["input.value"] = safeStringify13({ messages: inMsgs });
|
|
9638
10035
|
}
|
|
9639
10036
|
const { text, toolCalls } = splitAssistantContent(msg.content);
|
|
9640
|
-
const outText = text || toolCalls.map((tc) => `${tc.name}(${
|
|
10037
|
+
const outText = text || toolCalls.map((tc) => `${tc.name}(${safeStringify13(tc.arguments)})`).join("\n");
|
|
9641
10038
|
if (outText || toolCalls.length) {
|
|
9642
10039
|
attrs["neatlogs.llm.output_messages.0.role"] = "assistant";
|
|
9643
10040
|
attrs["neatlogs.llm.output_messages.0.content"] = outText || "";
|
|
@@ -9647,11 +10044,11 @@ function emitLlmSpan(tracer, state, msg) {
|
|
|
9647
10044
|
toolCalls.forEach((tc, j) => {
|
|
9648
10045
|
if (tc.name) attrs[`neatlogs.llm.tool_calls.${j}.name`] = tc.name;
|
|
9649
10046
|
if (tc.arguments !== void 0)
|
|
9650
|
-
attrs[`neatlogs.llm.tool_calls.${j}.arguments`] =
|
|
10047
|
+
attrs[`neatlogs.llm.tool_calls.${j}.arguments`] = safeStringify13(tc.arguments);
|
|
9651
10048
|
if (tc.id) attrs[`neatlogs.llm.tool_calls.${j}.id`] = String(tc.id);
|
|
9652
10049
|
});
|
|
9653
10050
|
}
|
|
9654
|
-
attrs["neatlogs.llm.output"] =
|
|
10051
|
+
attrs["neatlogs.llm.output"] = safeStringify13(outBlob);
|
|
9655
10052
|
attrs["output.value"] = outText || "";
|
|
9656
10053
|
}
|
|
9657
10054
|
const usage = msg.usage;
|
|
@@ -9663,13 +10060,13 @@ function emitLlmSpan(tracer, state, msg) {
|
|
|
9663
10060
|
if (usage.cacheRead) attrs["neatlogs.llm.token_count.cache_read"] = usage.cacheRead;
|
|
9664
10061
|
if (usage.cacheWrite) attrs["neatlogs.llm.token_count.cache_write"] = usage.cacheWrite;
|
|
9665
10062
|
}
|
|
9666
|
-
const parent = state.agentCtx ??
|
|
10063
|
+
const parent = state.agentCtx ?? import_api20.context.active();
|
|
9667
10064
|
const span2 = tracer.startSpan(
|
|
9668
10065
|
`pi_agent.llm.${msg.model || "model"}`,
|
|
9669
10066
|
{ attributes: attrs },
|
|
9670
10067
|
parent
|
|
9671
10068
|
);
|
|
9672
|
-
span2.setStatus({ code:
|
|
10069
|
+
span2.setStatus({ code: import_api20.SpanStatusCode.OK });
|
|
9673
10070
|
span2.end();
|
|
9674
10071
|
}
|
|
9675
10072
|
function splitAssistantContent(content) {
|
|
@@ -9697,7 +10094,7 @@ function messageText(msg) {
|
|
|
9697
10094
|
if (typeof block === "string") parts.push(block);
|
|
9698
10095
|
else if (block && typeof block === "object") {
|
|
9699
10096
|
if (typeof block.text === "string") parts.push(block.text);
|
|
9700
|
-
else if (block.type === "toolCall") parts.push(`${block.name ?? "tool"}(${
|
|
10097
|
+
else if (block.type === "toolCall") parts.push(`${block.name ?? "tool"}(${safeStringify13(block.arguments)})`);
|
|
9701
10098
|
}
|
|
9702
10099
|
}
|
|
9703
10100
|
return parts.join("");
|
|
@@ -9720,7 +10117,7 @@ function markPatched2(e) {
|
|
|
9720
10117
|
e[PATCH_FLAG3] = true;
|
|
9721
10118
|
}
|
|
9722
10119
|
}
|
|
9723
|
-
function
|
|
10120
|
+
function safeStringify13(value) {
|
|
9724
10121
|
if (typeof value === "string") return value;
|
|
9725
10122
|
try {
|
|
9726
10123
|
return JSON.stringify(value) ?? "";
|
|
@@ -9730,8 +10127,8 @@ function safeStringify12(value) {
|
|
|
9730
10127
|
}
|
|
9731
10128
|
|
|
9732
10129
|
// src/claude-agent-sdk.ts
|
|
9733
|
-
var
|
|
9734
|
-
var
|
|
10130
|
+
var import_api21 = require("@opentelemetry/api");
|
|
10131
|
+
var TRACER_NAME13 = "neatlogs.claude_agent_sdk";
|
|
9735
10132
|
var ROOT_SCOPE = "__root__";
|
|
9736
10133
|
function wrapClaudeAgentSDK(sdk, options = {}) {
|
|
9737
10134
|
if (!sdk || typeof sdk.query !== "function") return sdk;
|
|
@@ -9751,13 +10148,13 @@ function wrapClaudeAgentSDK(sdk, options = {}) {
|
|
|
9751
10148
|
}
|
|
9752
10149
|
function wrapQuery(original, options) {
|
|
9753
10150
|
return function(params, ...rest) {
|
|
9754
|
-
const tracer =
|
|
10151
|
+
const tracer = import_api21.trace.getTracer(TRACER_NAME13);
|
|
9755
10152
|
const workflowName = options.workflowName ?? "claude_agent.query";
|
|
9756
10153
|
const promptRef = { text: "" };
|
|
9757
10154
|
const agentSpan = tracer.startSpan(
|
|
9758
10155
|
"claude_agent.query",
|
|
9759
10156
|
{ attributes: { "neatlogs.span.kind": "AGENT", "neatlogs.workflow.name": workflowName } },
|
|
9760
|
-
|
|
10157
|
+
import_api21.context.active()
|
|
9761
10158
|
);
|
|
9762
10159
|
const promptText = extractPromptText(params?.prompt);
|
|
9763
10160
|
if (promptText) {
|
|
@@ -9766,8 +10163,8 @@ function wrapQuery(original, options) {
|
|
|
9766
10163
|
} else if (params && isAsyncIterable(params.prompt)) {
|
|
9767
10164
|
params = { ...params, prompt: tapPromptStream(params.prompt, promptRef) };
|
|
9768
10165
|
}
|
|
9769
|
-
const agentCtx =
|
|
9770
|
-
const queryObj =
|
|
10166
|
+
const agentCtx = import_api21.trace.setSpan(import_api21.context.active(), agentSpan);
|
|
10167
|
+
const queryObj = import_api21.context.with(agentCtx, () => original(params, ...rest));
|
|
9771
10168
|
return instrumentQueryIterable(queryObj, agentSpan, agentCtx, tracer, promptRef);
|
|
9772
10169
|
};
|
|
9773
10170
|
}
|
|
@@ -9786,7 +10183,7 @@ async function* tapPromptStream(prompt, ref) {
|
|
|
9786
10183
|
function instrumentQueryIterable(queryObj, agentSpan, agentCtx, tracer, promptRef) {
|
|
9787
10184
|
const originalAsyncIterator = queryObj?.[Symbol.asyncIterator]?.bind(queryObj);
|
|
9788
10185
|
if (!originalAsyncIterator) {
|
|
9789
|
-
agentSpan.setStatus({ code:
|
|
10186
|
+
agentSpan.setStatus({ code: import_api21.SpanStatusCode.OK });
|
|
9790
10187
|
agentSpan.end();
|
|
9791
10188
|
return queryObj;
|
|
9792
10189
|
}
|
|
@@ -9821,9 +10218,9 @@ function instrumentQueryIterable(queryObj, agentSpan, agentCtx, tracer, promptRe
|
|
|
9821
10218
|
}
|
|
9822
10219
|
if (rootScope.finalText) agentSpan.setAttribute("output.value", rootScope.finalText);
|
|
9823
10220
|
if (status === "error") {
|
|
9824
|
-
|
|
10221
|
+
recordError8(agentSpan, err);
|
|
9825
10222
|
} else {
|
|
9826
|
-
agentSpan.setStatus({ code:
|
|
10223
|
+
agentSpan.setStatus({ code: import_api21.SpanStatusCode.OK });
|
|
9827
10224
|
agentSpan.end();
|
|
9828
10225
|
}
|
|
9829
10226
|
};
|
|
@@ -9834,7 +10231,7 @@ function instrumentQueryIterable(queryObj, agentSpan, agentCtx, tracer, promptRe
|
|
|
9834
10231
|
return {
|
|
9835
10232
|
async next() {
|
|
9836
10233
|
try {
|
|
9837
|
-
const result = await
|
|
10234
|
+
const result = await import_api21.context.with(agentCtx, () => iterator.next());
|
|
9838
10235
|
if (result.done) {
|
|
9839
10236
|
finalizeAgent("ok");
|
|
9840
10237
|
return result;
|
|
@@ -9865,7 +10262,7 @@ function instrumentQueryIterable(queryObj, agentSpan, agentCtx, tracer, promptRe
|
|
|
9865
10262
|
function closeScope(scope, status) {
|
|
9866
10263
|
try {
|
|
9867
10264
|
if (scope.finalText) scope.span.setAttribute("output.value", scope.finalText);
|
|
9868
|
-
scope.span.setStatus({ code: status === "ok" ?
|
|
10265
|
+
scope.span.setStatus({ code: status === "ok" ? import_api21.SpanStatusCode.OK : import_api21.SpanStatusCode.ERROR });
|
|
9869
10266
|
scope.span.end();
|
|
9870
10267
|
} catch {
|
|
9871
10268
|
}
|
|
@@ -9880,7 +10277,7 @@ function getScope(tracer, state, msg) {
|
|
|
9880
10277
|
flushAssistantTurn(tracer, root, state);
|
|
9881
10278
|
}
|
|
9882
10279
|
const parentToolSpan = state.toolSpans.get(parentId);
|
|
9883
|
-
const parentCtx = parentToolSpan ?
|
|
10280
|
+
const parentCtx = parentToolSpan ? import_api21.trace.setSpan(import_api21.context.active(), parentToolSpan) : state.scopes.get(ROOT_SCOPE).ctx;
|
|
9884
10281
|
const subType = msg?.subagent_type ? String(msg.subagent_type) : "subagent";
|
|
9885
10282
|
const attrs = {
|
|
9886
10283
|
"neatlogs.span.kind": "AGENT",
|
|
@@ -9890,7 +10287,7 @@ function getScope(tracer, state, msg) {
|
|
|
9890
10287
|
const span2 = tracer.startSpan(`claude_agent.subagent.${subType}`, { attributes: attrs }, parentCtx);
|
|
9891
10288
|
const scope = {
|
|
9892
10289
|
span: span2,
|
|
9893
|
-
ctx:
|
|
10290
|
+
ctx: import_api21.trace.setSpan(import_api21.context.active(), span2),
|
|
9894
10291
|
inputMessages: msg?.task_description ? [{ role: "user", content: String(msg.task_description) }] : [],
|
|
9895
10292
|
assistantBuffer: null,
|
|
9896
10293
|
finalText: "",
|
|
@@ -9945,7 +10342,7 @@ function handleMessage(tracer, state, msg, finalizeAgent) {
|
|
|
9945
10342
|
rootScope.span.setAttribute("neatlogs.conversation.id", String(msg.session_id));
|
|
9946
10343
|
}
|
|
9947
10344
|
const usage = msg.usage;
|
|
9948
|
-
if (usage)
|
|
10345
|
+
if (usage) setUsage3(rootScope.span, usage);
|
|
9949
10346
|
if (msg.total_cost_usd != null) rootScope.span.setAttribute("neatlogs.agent.cost_usd", msg.total_cost_usd);
|
|
9950
10347
|
if (msg.num_turns != null) rootScope.span.setAttribute("neatlogs.agent.num_turns", msg.num_turns);
|
|
9951
10348
|
if (msg.is_error) rootScope.span.setAttribute("neatlogs.agent.is_error", true);
|
|
@@ -9994,10 +10391,10 @@ function flushAssistantTurn(tracer, scope, state) {
|
|
|
9994
10391
|
attrs[`neatlogs.llm.input_messages.${i}.content`] = m.content;
|
|
9995
10392
|
});
|
|
9996
10393
|
if (scope.inputMessages.length) {
|
|
9997
|
-
attrs["input.value"] =
|
|
10394
|
+
attrs["input.value"] = safeStringify14({ messages: scope.inputMessages });
|
|
9998
10395
|
}
|
|
9999
10396
|
const outText = buf.textParts.join("");
|
|
10000
|
-
const outValue = outText || buf.toolCalls.map((tc) => `${tc.name}(${
|
|
10397
|
+
const outValue = outText || buf.toolCalls.map((tc) => `${tc.name}(${safeStringify14(tc.input ?? {})})`).join("\n");
|
|
10001
10398
|
if (outValue) {
|
|
10002
10399
|
attrs["neatlogs.llm.output_messages.0.role"] = "assistant";
|
|
10003
10400
|
attrs["neatlogs.llm.output_messages.0.content"] = outValue;
|
|
@@ -10009,17 +10406,17 @@ function flushAssistantTurn(tracer, scope, state) {
|
|
|
10009
10406
|
buf.toolCalls.forEach((tc, j) => {
|
|
10010
10407
|
attrs[`neatlogs.llm.tool_calls.${j}.id`] = tc.id;
|
|
10011
10408
|
attrs[`neatlogs.llm.tool_calls.${j}.name`] = tc.name;
|
|
10012
|
-
attrs[`neatlogs.llm.tool_calls.${j}.arguments`] =
|
|
10409
|
+
attrs[`neatlogs.llm.tool_calls.${j}.arguments`] = safeStringify14(tc.input ?? {});
|
|
10013
10410
|
});
|
|
10014
10411
|
if (buf.stopReason) attrs["neatlogs.llm.finish_reason"] = String(buf.stopReason);
|
|
10015
10412
|
const span2 = tracer.startSpan(`claude_agent.llm.${model || "model"}`, { attributes: attrs }, scope.ctx);
|
|
10016
|
-
if (buf.usage)
|
|
10017
|
-
span2.setStatus({ code:
|
|
10413
|
+
if (buf.usage) setUsage3(span2, buf.usage);
|
|
10414
|
+
span2.setStatus({ code: import_api21.SpanStatusCode.OK });
|
|
10018
10415
|
span2.end();
|
|
10019
10416
|
if (outText) scope.finalText = outText;
|
|
10020
10417
|
const turnParts = [];
|
|
10021
10418
|
if (outText) turnParts.push(outText);
|
|
10022
|
-
for (const tc of buf.toolCalls) turnParts.push(`[tool_call ${tc.name} ${
|
|
10419
|
+
for (const tc of buf.toolCalls) turnParts.push(`[tool_call ${tc.name} ${safeStringify14(tc.input ?? {})}]`);
|
|
10023
10420
|
if (turnParts.length) scope.inputMessages.push({ role: "assistant", content: turnParts.join("\n") });
|
|
10024
10421
|
for (const tc of buf.toolCalls) {
|
|
10025
10422
|
const toolSpan = tracer.startSpan(
|
|
@@ -10029,7 +10426,7 @@ function flushAssistantTurn(tracer, scope, state) {
|
|
|
10029
10426
|
"neatlogs.span.kind": "TOOL",
|
|
10030
10427
|
"neatlogs.tool.name": String(tc.name ?? ""),
|
|
10031
10428
|
...tc.id ? { "neatlogs.tool_call.id": String(tc.id) } : {},
|
|
10032
|
-
"input.value":
|
|
10429
|
+
"input.value": safeStringify14(tc.input ?? {})
|
|
10033
10430
|
}
|
|
10034
10431
|
},
|
|
10035
10432
|
scope.ctx
|
|
@@ -10043,16 +10440,16 @@ function closeToolSpansFromUser(state, scope, msg) {
|
|
|
10043
10440
|
if (block?.type !== "tool_result") continue;
|
|
10044
10441
|
const id = block.tool_use_id ?? "";
|
|
10045
10442
|
const out = block.content;
|
|
10046
|
-
const outText = typeof out === "string" ? out :
|
|
10443
|
+
const outText = typeof out === "string" ? out : safeStringify14(out);
|
|
10047
10444
|
if (outText) scope.inputMessages.push({ role: "tool", content: outText });
|
|
10048
10445
|
const span2 = state.toolSpans.get(id);
|
|
10049
10446
|
if (!span2) continue;
|
|
10050
10447
|
span2.setAttribute("output.value", outText);
|
|
10051
10448
|
if (block.is_error) {
|
|
10052
|
-
span2.setStatus({ code:
|
|
10449
|
+
span2.setStatus({ code: import_api21.SpanStatusCode.ERROR });
|
|
10053
10450
|
span2.setAttribute("neatlogs.tool.is_error", true);
|
|
10054
10451
|
} else {
|
|
10055
|
-
span2.setStatus({ code:
|
|
10452
|
+
span2.setStatus({ code: import_api21.SpanStatusCode.OK });
|
|
10056
10453
|
}
|
|
10057
10454
|
span2.end();
|
|
10058
10455
|
state.toolSpans.delete(id);
|
|
@@ -10071,7 +10468,7 @@ function userMessageText(msg) {
|
|
|
10071
10468
|
}
|
|
10072
10469
|
return parts.join("\n");
|
|
10073
10470
|
}
|
|
10074
|
-
function
|
|
10471
|
+
function setUsage3(span2, usage) {
|
|
10075
10472
|
if (!usage) return;
|
|
10076
10473
|
if (usage.input_tokens != null) span2.setAttribute("neatlogs.llm.token_count.prompt", usage.input_tokens);
|
|
10077
10474
|
if (usage.output_tokens != null) span2.setAttribute("neatlogs.llm.token_count.completion", usage.output_tokens);
|
|
@@ -10089,7 +10486,7 @@ function extractPromptText(prompt) {
|
|
|
10089
10486
|
if (typeof prompt === "string") return prompt;
|
|
10090
10487
|
return "";
|
|
10091
10488
|
}
|
|
10092
|
-
function
|
|
10489
|
+
function safeStringify14(value) {
|
|
10093
10490
|
if (typeof value === "string") return value;
|
|
10094
10491
|
try {
|
|
10095
10492
|
return JSON.stringify(value) ?? "";
|
|
@@ -10097,20 +10494,20 @@ function safeStringify13(value) {
|
|
|
10097
10494
|
return "";
|
|
10098
10495
|
}
|
|
10099
10496
|
}
|
|
10100
|
-
function
|
|
10497
|
+
function recordError8(span2, err) {
|
|
10101
10498
|
if (err instanceof Error) {
|
|
10102
|
-
span2.setStatus({ code:
|
|
10499
|
+
span2.setStatus({ code: import_api21.SpanStatusCode.ERROR, message: err.message });
|
|
10103
10500
|
span2.recordException(err);
|
|
10104
10501
|
} else {
|
|
10105
|
-
span2.setStatus({ code:
|
|
10502
|
+
span2.setStatus({ code: import_api21.SpanStatusCode.ERROR, message: String(err) });
|
|
10106
10503
|
}
|
|
10107
10504
|
span2.end();
|
|
10108
10505
|
}
|
|
10109
10506
|
|
|
10110
10507
|
// src/openrouter-agent.ts
|
|
10111
|
-
var
|
|
10112
|
-
var
|
|
10113
|
-
var
|
|
10508
|
+
var import_api22 = require("@opentelemetry/api");
|
|
10509
|
+
var TRACER_NAME14 = "neatlogs.openrouter_agent";
|
|
10510
|
+
var PROVIDER5 = "openrouter";
|
|
10114
10511
|
function wrapOpenRouterAgent(client) {
|
|
10115
10512
|
const c = client;
|
|
10116
10513
|
if (!c || c._neatlogsWrapped) return client;
|
|
@@ -10127,30 +10524,30 @@ function wrapOpenRouterAgent(client) {
|
|
|
10127
10524
|
function wrapCallModel(callModel) {
|
|
10128
10525
|
return function(clientArg, opts, ...rest) {
|
|
10129
10526
|
const span2 = startLlmSpan(opts);
|
|
10130
|
-
const ctx =
|
|
10131
|
-
const result =
|
|
10527
|
+
const ctx = import_api22.trace.setSpan(import_api22.context.active(), span2);
|
|
10528
|
+
const result = import_api22.context.with(ctx, () => callModel.call(this, clientArg, opts, ...rest));
|
|
10132
10529
|
return instrumentModelResult(result, span2);
|
|
10133
10530
|
};
|
|
10134
10531
|
}
|
|
10135
10532
|
function tracedCallModel(original) {
|
|
10136
10533
|
return function(opts, ...rest) {
|
|
10137
10534
|
const span2 = startLlmSpan(opts);
|
|
10138
|
-
const ctx =
|
|
10139
|
-
const result =
|
|
10535
|
+
const ctx = import_api22.trace.setSpan(import_api22.context.active(), span2);
|
|
10536
|
+
const result = import_api22.context.with(ctx, () => original(opts, ...rest));
|
|
10140
10537
|
return instrumentModelResult(result, span2);
|
|
10141
10538
|
};
|
|
10142
10539
|
}
|
|
10143
10540
|
function startLlmSpan(opts) {
|
|
10144
|
-
const tracer = getProviderTracer(
|
|
10541
|
+
const tracer = getProviderTracer(TRACER_NAME14);
|
|
10145
10542
|
const model = opts?.model ?? "";
|
|
10146
10543
|
const span2 = tracer.startSpan("openrouter.call_model", {
|
|
10147
10544
|
attributes: {
|
|
10148
10545
|
"neatlogs.span.kind": "LLM",
|
|
10149
|
-
"neatlogs.llm.provider":
|
|
10150
|
-
"neatlogs.llm.system":
|
|
10546
|
+
"neatlogs.llm.provider": PROVIDER5,
|
|
10547
|
+
"neatlogs.llm.system": PROVIDER5,
|
|
10151
10548
|
"neatlogs.llm.model_name": model
|
|
10152
10549
|
}
|
|
10153
|
-
},
|
|
10550
|
+
}, import_api22.context.active());
|
|
10154
10551
|
const messages = Array.isArray(opts?.messages) ? opts.messages : Array.isArray(opts?.input) ? opts.input : [];
|
|
10155
10552
|
if (messages.length) {
|
|
10156
10553
|
messages.forEach((msg, i) => {
|
|
@@ -10158,10 +10555,10 @@ function startLlmSpan(opts) {
|
|
|
10158
10555
|
const content = msg?.content;
|
|
10159
10556
|
span2.setAttribute(
|
|
10160
10557
|
`neatlogs.llm.input_messages.${i}.content`,
|
|
10161
|
-
typeof content === "string" ? content :
|
|
10558
|
+
typeof content === "string" ? content : safeStringify15(content)
|
|
10162
10559
|
);
|
|
10163
10560
|
});
|
|
10164
|
-
span2.setAttribute("input.value",
|
|
10561
|
+
span2.setAttribute("input.value", safeStringify15({ messages }));
|
|
10165
10562
|
} else if (typeof opts?.input === "string") {
|
|
10166
10563
|
span2.setAttribute("neatlogs.llm.input_messages.0.role", "user");
|
|
10167
10564
|
span2.setAttribute("neatlogs.llm.input_messages.0.content", opts.input);
|
|
@@ -10202,7 +10599,7 @@ function startLlmSpan(opts) {
|
|
|
10202
10599
|
}
|
|
10203
10600
|
function instrumentModelResult(result, span2) {
|
|
10204
10601
|
if (!result || typeof result !== "object" && typeof result !== "function") {
|
|
10205
|
-
span2.setStatus({ code:
|
|
10602
|
+
span2.setStatus({ code: import_api22.SpanStatusCode.OK });
|
|
10206
10603
|
span2.end();
|
|
10207
10604
|
return result;
|
|
10208
10605
|
}
|
|
@@ -10213,14 +10610,14 @@ function instrumentModelResult(result, span2) {
|
|
|
10213
10610
|
try {
|
|
10214
10611
|
finalizeLlm(span2, resolved);
|
|
10215
10612
|
} catch {
|
|
10216
|
-
span2.setStatus({ code:
|
|
10613
|
+
span2.setStatus({ code: import_api22.SpanStatusCode.OK });
|
|
10217
10614
|
span2.end();
|
|
10218
10615
|
}
|
|
10219
10616
|
};
|
|
10220
10617
|
const finalizeError = (err) => {
|
|
10221
10618
|
if (finalized) return;
|
|
10222
10619
|
finalized = true;
|
|
10223
|
-
|
|
10620
|
+
recordError9(span2, err);
|
|
10224
10621
|
};
|
|
10225
10622
|
return new Proxy(result, {
|
|
10226
10623
|
get(obj, prop, receiver) {
|
|
@@ -10306,7 +10703,7 @@ function finalizeLlm(span2, result) {
|
|
|
10306
10703
|
span2.setAttribute(`neatlogs.llm.tool_calls.${j}.id`, tc?.id ?? "");
|
|
10307
10704
|
span2.setAttribute(`neatlogs.llm.tool_calls.${j}.name`, tc?.function?.name ?? tc?.name ?? "");
|
|
10308
10705
|
const args = tc?.function?.arguments ?? tc?.arguments;
|
|
10309
|
-
span2.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, typeof args === "string" ? args :
|
|
10706
|
+
span2.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, typeof args === "string" ? args : safeStringify15(args ?? {}));
|
|
10310
10707
|
});
|
|
10311
10708
|
}
|
|
10312
10709
|
const model = result?.model ?? result?.response?.model;
|
|
@@ -10316,7 +10713,7 @@ function finalizeLlm(span2, result) {
|
|
|
10316
10713
|
const finishReason = result?.finishReason ?? result?.finish_reason ?? result?.choices?.[0]?.finish_reason;
|
|
10317
10714
|
if (finishReason) span2.setAttribute("neatlogs.llm.finish_reason", String(finishReason));
|
|
10318
10715
|
setOpenResponsesUsage(span2, result);
|
|
10319
|
-
span2.setStatus({ code:
|
|
10716
|
+
span2.setStatus({ code: import_api22.SpanStatusCode.OK });
|
|
10320
10717
|
span2.end();
|
|
10321
10718
|
}
|
|
10322
10719
|
function extractOpenResponsesText(result) {
|
|
@@ -10332,7 +10729,7 @@ function extractOpenResponsesText(result) {
|
|
|
10332
10729
|
}
|
|
10333
10730
|
return parts.length ? parts.join("") : void 0;
|
|
10334
10731
|
}
|
|
10335
|
-
function
|
|
10732
|
+
function safeStringify15(value) {
|
|
10336
10733
|
if (typeof value === "string") return value;
|
|
10337
10734
|
try {
|
|
10338
10735
|
return JSON.stringify(value) ?? "";
|
|
@@ -10340,12 +10737,12 @@ function safeStringify14(value) {
|
|
|
10340
10737
|
return "";
|
|
10341
10738
|
}
|
|
10342
10739
|
}
|
|
10343
|
-
function
|
|
10740
|
+
function recordError9(span2, err) {
|
|
10344
10741
|
if (err instanceof Error) {
|
|
10345
|
-
span2.setStatus({ code:
|
|
10742
|
+
span2.setStatus({ code: import_api22.SpanStatusCode.ERROR, message: err.message });
|
|
10346
10743
|
span2.recordException(err);
|
|
10347
10744
|
} else {
|
|
10348
|
-
span2.setStatus({ code:
|
|
10745
|
+
span2.setStatus({ code: import_api22.SpanStatusCode.ERROR, message: String(err) });
|
|
10349
10746
|
}
|
|
10350
10747
|
span2.end();
|
|
10351
10748
|
}
|
|
@@ -10502,7 +10899,7 @@ var protoRoot = import_protobufjs.default.Root.fromJSON(OTLP_PROTO_JSON);
|
|
|
10502
10899
|
var ExportTraceServiceRequest = protoRoot.lookupType(
|
|
10503
10900
|
"opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest"
|
|
10504
10901
|
);
|
|
10505
|
-
var
|
|
10902
|
+
var SpanStatusCode17 = { UNSET: 0, OK: 1, ERROR: 2 };
|
|
10506
10903
|
function randomBytes(length) {
|
|
10507
10904
|
const out = new Uint8Array(length);
|
|
10508
10905
|
const crypto = globalThis.crypto;
|
|
@@ -10709,7 +11106,7 @@ var NeatlogsOpencodePlugin = async (_ctx) => {
|
|
|
10709
11106
|
startTimeUnixNano: st.rootSpan.startNano,
|
|
10710
11107
|
endTimeUnixNano: nowNanoString(),
|
|
10711
11108
|
attributes: attrs,
|
|
10712
|
-
status: { code:
|
|
11109
|
+
status: { code: SpanStatusCode17.OK }
|
|
10713
11110
|
});
|
|
10714
11111
|
const m = nowNanoString();
|
|
10715
11112
|
shipper.enqueue({
|
|
@@ -10796,18 +11193,18 @@ var NeatlogsOpencodePlugin = async (_ctx) => {
|
|
|
10796
11193
|
{ key: "neatlogs.conversation.id", value: { stringValue: sessionID } }
|
|
10797
11194
|
];
|
|
10798
11195
|
if (start.args !== void 0) {
|
|
10799
|
-
setIO(attrs, "TOOL",
|
|
10800
|
-
push(attrs, attrStr("neatlogs.tool.input",
|
|
11196
|
+
setIO(attrs, "TOOL", safeStringify16(start.args), void 0);
|
|
11197
|
+
push(attrs, attrStr("neatlogs.tool.input", safeStringify16(start.args)));
|
|
10801
11198
|
}
|
|
10802
11199
|
if (result?.title) push(attrs, attrStr("neatlogs.tool.title", String(result.title)));
|
|
10803
11200
|
const out = result?.output ?? result?.result;
|
|
10804
11201
|
if (out !== void 0) {
|
|
10805
|
-
const o = typeof out === "string" ? out :
|
|
11202
|
+
const o = typeof out === "string" ? out : safeStringify16(out);
|
|
10806
11203
|
setIO(attrs, "TOOL", void 0, o);
|
|
10807
11204
|
push(attrs, attrStr("neatlogs.tool.output", o));
|
|
10808
11205
|
}
|
|
10809
11206
|
if (result?.metadata !== void 0) {
|
|
10810
|
-
push(attrs, attrStr("neatlogs.tool.metadata",
|
|
11207
|
+
push(attrs, attrStr("neatlogs.tool.metadata", safeStringify16(result.metadata)));
|
|
10811
11208
|
}
|
|
10812
11209
|
shipper.enqueue({
|
|
10813
11210
|
traceId: st.traceId,
|
|
@@ -10818,7 +11215,7 @@ var NeatlogsOpencodePlugin = async (_ctx) => {
|
|
|
10818
11215
|
startTimeUnixNano: start.startNano,
|
|
10819
11216
|
endTimeUnixNano: nowNanoString(),
|
|
10820
11217
|
attributes: attrs,
|
|
10821
|
-
status: { code:
|
|
11218
|
+
status: { code: SpanStatusCode17.OK }
|
|
10822
11219
|
});
|
|
10823
11220
|
} catch {
|
|
10824
11221
|
}
|
|
@@ -10905,10 +11302,10 @@ function emitLlmSpan2(shipper, st, info, sessionID) {
|
|
|
10905
11302
|
if (toolCalls.length) {
|
|
10906
11303
|
toolCalls.forEach((tc, j) => {
|
|
10907
11304
|
push(attrs, attrStr(`neatlogs.llm.tool_calls.${j}.name`, tc.name));
|
|
10908
|
-
push(attrs, attrStr(`neatlogs.llm.tool_calls.${j}.arguments`,
|
|
11305
|
+
push(attrs, attrStr(`neatlogs.llm.tool_calls.${j}.arguments`, safeStringify16(tc.input ?? {})));
|
|
10909
11306
|
});
|
|
10910
11307
|
if (!outText) {
|
|
10911
|
-
const rendered = toolCalls.map((tc) => `\u2192 ${tc.name}(${
|
|
11308
|
+
const rendered = toolCalls.map((tc) => `\u2192 ${tc.name}(${safeStringify16(tc.input ?? {})})`).join("\n");
|
|
10912
11309
|
push(attrs, attrStr("neatlogs.llm.output_messages.0.role", "assistant"));
|
|
10913
11310
|
push(attrs, attrStr("neatlogs.llm.output_messages.0.content", rendered));
|
|
10914
11311
|
setIO(attrs, "LLM", void 0, rendered);
|
|
@@ -10937,7 +11334,7 @@ function emitLlmSpan2(shipper, st, info, sessionID) {
|
|
|
10937
11334
|
startTimeUnixNano: startNano,
|
|
10938
11335
|
endTimeUnixNano: nowNanoString(),
|
|
10939
11336
|
attributes: attrs,
|
|
10940
|
-
status: { code:
|
|
11337
|
+
status: { code: SpanStatusCode17.OK }
|
|
10941
11338
|
});
|
|
10942
11339
|
if (info?.id) {
|
|
10943
11340
|
st.outputParts.delete(String(info.id));
|
|
@@ -10973,7 +11370,7 @@ function messageText2(info) {
|
|
|
10973
11370
|
}
|
|
10974
11371
|
return out.join("");
|
|
10975
11372
|
}
|
|
10976
|
-
function
|
|
11373
|
+
function safeStringify16(value) {
|
|
10977
11374
|
if (typeof value === "string") return value;
|
|
10978
11375
|
try {
|
|
10979
11376
|
return JSON.stringify(value) ?? "";
|
|
@@ -11070,6 +11467,7 @@ function bindTemplates(llm, systemTpl, userTpl, compiledVars) {
|
|
|
11070
11467
|
traceToolAnthropic,
|
|
11071
11468
|
traceToolAzureOpenAI,
|
|
11072
11469
|
traceToolBedrock,
|
|
11470
|
+
traceToolGoogleGenAI,
|
|
11073
11471
|
traceToolOpenAI,
|
|
11074
11472
|
traceToolVertexAI,
|
|
11075
11473
|
updatePrompt,
|
|
@@ -11079,6 +11477,8 @@ function bindTemplates(llm, systemTpl, userTpl, compiledVars) {
|
|
|
11079
11477
|
wrapBedrock,
|
|
11080
11478
|
wrapCallModel,
|
|
11081
11479
|
wrapClaudeAgentSDK,
|
|
11480
|
+
wrapGoogleGenAI,
|
|
11481
|
+
wrapGoogleGenAIChat,
|
|
11082
11482
|
wrapMastra,
|
|
11083
11483
|
wrapOpenAI,
|
|
11084
11484
|
wrapOpenRouterAgent,
|