braintrust 3.31.0 → 3.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -43
- package/dev/dist/index.d.mts +767 -0
- package/dev/dist/index.d.ts +767 -0
- package/dev/dist/index.js +3115 -908
- package/dev/dist/index.mjs +2466 -259
- package/dist/apply-auto-instrumentation.js +325 -221
- package/dist/apply-auto-instrumentation.mjs +110 -6
- package/dist/auto-instrumentations/bundler/esbuild.cjs +182 -7
- package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
- package/dist/auto-instrumentations/bundler/next.cjs +182 -7
- package/dist/auto-instrumentations/bundler/next.mjs +3 -3
- package/dist/auto-instrumentations/bundler/rollup.cjs +182 -7
- package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
- package/dist/auto-instrumentations/bundler/vite.cjs +182 -7
- package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
- package/dist/auto-instrumentations/bundler/webpack-loader.cjs +182 -7
- package/dist/auto-instrumentations/bundler/webpack.cjs +182 -7
- package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
- package/dist/auto-instrumentations/{chunk-U64OYU4Q.mjs → chunk-T2DMPWFI.mjs} +113 -6
- package/dist/auto-instrumentations/{chunk-LW4HDHXT.mjs → chunk-UHJ2DNYJ.mjs} +74 -2
- package/dist/auto-instrumentations/{chunk-OXINGIEZ.mjs → chunk-W5QNG3PV.mjs} +1 -1
- package/dist/auto-instrumentations/hook.mjs +209 -9
- package/dist/auto-instrumentations/index.cjs +115 -6
- package/dist/auto-instrumentations/index.d.mts +5 -1
- package/dist/auto-instrumentations/index.d.ts +5 -1
- package/dist/auto-instrumentations/index.mjs +5 -1
- package/dist/browser.d.mts +2324 -342
- package/dist/browser.d.ts +2324 -342
- package/dist/browser.js +3573 -626
- package/dist/browser.mjs +3573 -626
- package/dist/chunk-7P6ASYW6.mjs +9 -0
- package/dist/{chunk-V32LW47Z.js → chunk-AXJTOUOC.js} +3022 -1131
- package/dist/{chunk-4AQGZS6X.js → chunk-G3VHOHRC.js} +85 -11
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/{chunk-AJT4FR25.mjs → chunk-MZLBAFVJ.mjs} +2051 -160
- package/dist/{chunk-CE3BLB2L.mjs → chunk-TZVZN2JJ.mjs} +84 -10
- package/dist/cli.js +2614 -297
- package/dist/custom-views.d.mts +112 -0
- package/dist/custom-views.d.ts +112 -0
- package/dist/custom-views.js +13 -0
- package/dist/custom-views.mjs +13 -0
- package/dist/edge-light.d.mts +1 -1
- package/dist/edge-light.d.ts +1 -1
- package/dist/edge-light.js +3573 -626
- package/dist/edge-light.mjs +3573 -626
- package/dist/index.d.mts +2324 -342
- package/dist/index.d.ts +2324 -342
- package/dist/index.js +1959 -969
- package/dist/index.mjs +1450 -460
- package/dist/instrumentation/index.d.mts +439 -245
- package/dist/instrumentation/index.d.ts +439 -245
- package/dist/instrumentation/index.js +2550 -258
- package/dist/instrumentation/index.mjs +2550 -258
- package/dist/vitest-evals-reporter.js +17 -16
- package/dist/vitest-evals-reporter.mjs +3 -2
- package/dist/workerd.d.mts +1 -1
- package/dist/workerd.d.ts +1 -1
- package/dist/workerd.js +3573 -626
- package/dist/workerd.mjs +3573 -626
- package/package.json +10 -2
- package/util/dist/index.d.mts +326 -0
- package/util/dist/index.d.ts +326 -0
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
cursorSDKChannels,
|
|
13
13
|
debugLogger,
|
|
14
14
|
detectSpanOriginEnvironment,
|
|
15
|
+
elevenLabsChannels,
|
|
15
16
|
flueChannels,
|
|
16
17
|
genkitChannels,
|
|
17
18
|
genkitCoreChannels,
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
gitHubCopilotChannels,
|
|
23
24
|
googleADKChannels,
|
|
24
25
|
googleGenAIChannels,
|
|
26
|
+
googleGenerativeAIChannels,
|
|
25
27
|
groqChannels,
|
|
26
28
|
harnessAgentChannels,
|
|
27
29
|
huggingFaceChannels,
|
|
@@ -31,6 +33,7 @@ import {
|
|
|
31
33
|
isSupportedHuggingFaceTransformersTask,
|
|
32
34
|
isomorph_default,
|
|
33
35
|
langChainChannels,
|
|
36
|
+
langGraphSDKChannels,
|
|
34
37
|
langSmithChannels,
|
|
35
38
|
mergeSpanOriginContext,
|
|
36
39
|
mistralChannels,
|
|
@@ -52,7 +55,7 @@ import {
|
|
|
52
55
|
strandsAgentSDKChannels,
|
|
53
56
|
voyageAIChannels,
|
|
54
57
|
withSpanInstrumentationName
|
|
55
|
-
} from "./chunk-
|
|
58
|
+
} from "./chunk-TZVZN2JJ.mjs";
|
|
56
59
|
|
|
57
60
|
// src/id-gen.ts
|
|
58
61
|
import { v4 as uuidv4 } from "uuid";
|
|
@@ -2013,6 +2016,14 @@ var ChatCompletionContentPartImageWithTitle = z6.object({
|
|
|
2013
2016
|
ttl: z6.enum(["5m", "1h"]).optional()
|
|
2014
2017
|
}).optional()
|
|
2015
2018
|
});
|
|
2019
|
+
var ChatCompletionContentPartInputAudioWithTitle = z6.object({
|
|
2020
|
+
input_audio: z6.object({ data: z6.string(), format: z6.enum(["wav", "mp3"]) }),
|
|
2021
|
+
type: z6.literal("input_audio"),
|
|
2022
|
+
cache_control: z6.object({
|
|
2023
|
+
type: z6.literal("ephemeral"),
|
|
2024
|
+
ttl: z6.enum(["5m", "1h"]).optional()
|
|
2025
|
+
}).optional()
|
|
2026
|
+
});
|
|
2016
2027
|
var ChatCompletionContentPartFileFile = z6.object({ file_data: z6.string(), filename: z6.string(), file_id: z6.string() }).partial();
|
|
2017
2028
|
var ChatCompletionContentPartFileWithTitle = z6.object({
|
|
2018
2029
|
file: ChatCompletionContentPartFileFile,
|
|
@@ -2025,6 +2036,7 @@ var ChatCompletionContentPartFileWithTitle = z6.object({
|
|
|
2025
2036
|
var ChatCompletionContentPart = z6.union([
|
|
2026
2037
|
ChatCompletionContentPartTextWithTitle,
|
|
2027
2038
|
ChatCompletionContentPartImageWithTitle,
|
|
2039
|
+
ChatCompletionContentPartInputAudioWithTitle,
|
|
2028
2040
|
ChatCompletionContentPartFileWithTitle
|
|
2029
2041
|
]);
|
|
2030
2042
|
var ChatCompletionContentPartText = z6.object({
|
|
@@ -8576,6 +8588,38 @@ function getSpanParentObjectAndPropagatedState(options) {
|
|
|
8576
8588
|
function getSpanParentObject(options) {
|
|
8577
8589
|
return getSpanParentObjectAndPropagatedState(options).parentObject;
|
|
8578
8590
|
}
|
|
8591
|
+
function _internalExportParentSynchronously(parent) {
|
|
8592
|
+
if ("toStr" in parent) {
|
|
8593
|
+
return parent.toStr();
|
|
8594
|
+
}
|
|
8595
|
+
if ("getParentInfo" in parent) {
|
|
8596
|
+
const parentInfo = parent.getParentInfo();
|
|
8597
|
+
if (!parentInfo) {
|
|
8598
|
+
return void 0;
|
|
8599
|
+
}
|
|
8600
|
+
const objectId = parentInfo.objectId.getSync().value;
|
|
8601
|
+
if (!objectId && !parentInfo.computeObjectMetadataArgs) {
|
|
8602
|
+
return void 0;
|
|
8603
|
+
}
|
|
8604
|
+
return new SpanComponentsV4({
|
|
8605
|
+
object_type: parentInfo.objectType,
|
|
8606
|
+
...objectId ? { object_id: objectId } : {
|
|
8607
|
+
compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
|
|
8608
|
+
},
|
|
8609
|
+
row_id: parent.id,
|
|
8610
|
+
root_span_id: parent.rootSpanId,
|
|
8611
|
+
span_id: parent.spanId
|
|
8612
|
+
}).toStr();
|
|
8613
|
+
}
|
|
8614
|
+
const components = braintrustParentToComponents(parent._getOtelParent());
|
|
8615
|
+
if (!components) {
|
|
8616
|
+
return void 0;
|
|
8617
|
+
}
|
|
8618
|
+
return new SpanComponentsV4({
|
|
8619
|
+
object_type: components.objectType,
|
|
8620
|
+
...components.objectId ? { object_id: components.objectId } : { compute_object_metadata_args: components.computeArgs ?? {} }
|
|
8621
|
+
}).toStr();
|
|
8622
|
+
}
|
|
8579
8623
|
function currentBraintrustParent(state) {
|
|
8580
8624
|
const resolvedState = state ?? _globalState;
|
|
8581
8625
|
const experiment = currentExperiment({ state: resolvedState });
|
|
@@ -10187,10 +10231,16 @@ var SpanImpl = class _SpanImpl {
|
|
|
10187
10231
|
inject(carrier) {
|
|
10188
10232
|
const resolvedCarrier = carrier ?? {};
|
|
10189
10233
|
try {
|
|
10234
|
+
const braintrustParent = this._getOtelParent() ?? this._propagatedState?.braintrustParent;
|
|
10235
|
+
if (!braintrustParent) {
|
|
10236
|
+
debugLogger.forState(this._state).warn(
|
|
10237
|
+
"Injecting trace context without braintrust.parent because the span's destination is not available yet. The receiver will start a new local trace instead of continuing this one."
|
|
10238
|
+
);
|
|
10239
|
+
}
|
|
10190
10240
|
_injectIntoCarrier(resolvedCarrier, {
|
|
10191
10241
|
traceId: this._rootSpanId,
|
|
10192
10242
|
spanId: this._spanId,
|
|
10193
|
-
braintrustParent
|
|
10243
|
+
braintrustParent,
|
|
10194
10244
|
propagatedState: this._propagatedState
|
|
10195
10245
|
});
|
|
10196
10246
|
} catch (e) {
|
|
@@ -10743,6 +10793,16 @@ function renderMessageImpl(render, message, variables) {
|
|
|
10743
10793
|
}
|
|
10744
10794
|
}
|
|
10745
10795
|
];
|
|
10796
|
+
case "input_audio":
|
|
10797
|
+
return [
|
|
10798
|
+
{
|
|
10799
|
+
...c,
|
|
10800
|
+
input_audio: {
|
|
10801
|
+
...c.input_audio,
|
|
10802
|
+
data: render(c.input_audio.data)
|
|
10803
|
+
}
|
|
10804
|
+
}
|
|
10805
|
+
];
|
|
10746
10806
|
case "file":
|
|
10747
10807
|
return [
|
|
10748
10808
|
{
|
|
@@ -12914,27 +12974,8 @@ function continuationParentFromCreateSessionParams(params) {
|
|
|
12914
12974
|
}
|
|
12915
12975
|
return context.parent;
|
|
12916
12976
|
}
|
|
12917
|
-
function exportSpanSynchronously(span) {
|
|
12918
|
-
const parentInfo = span.getParentInfo();
|
|
12919
|
-
if (!parentInfo) {
|
|
12920
|
-
return void 0;
|
|
12921
|
-
}
|
|
12922
|
-
const objectId = parentInfo.objectId.getSync().value;
|
|
12923
|
-
if (!objectId && !parentInfo.computeObjectMetadataArgs) {
|
|
12924
|
-
return void 0;
|
|
12925
|
-
}
|
|
12926
|
-
return new SpanComponentsV4({
|
|
12927
|
-
object_type: parentInfo.objectType,
|
|
12928
|
-
...objectId ? { object_id: objectId } : {
|
|
12929
|
-
compute_object_metadata_args: parentInfo.computeObjectMetadataArgs ?? {}
|
|
12930
|
-
},
|
|
12931
|
-
row_id: span.id,
|
|
12932
|
-
root_span_id: span.rootSpanId,
|
|
12933
|
-
span_id: span.spanId
|
|
12934
|
-
}).toStr();
|
|
12935
|
-
}
|
|
12936
12977
|
function exportedParent(parent) {
|
|
12937
|
-
return typeof parent === "string" ? parent :
|
|
12978
|
+
return typeof parent === "string" ? parent : _internalExportParentSynchronously(parent);
|
|
12938
12979
|
}
|
|
12939
12980
|
function addSerializedContext(args) {
|
|
12940
12981
|
if (!isObject(args.continuation) || args.sessionId === void 0) {
|
|
@@ -15295,9 +15336,9 @@ function patchAISDKStreamingResult(args) {
|
|
|
15295
15336
|
}
|
|
15296
15337
|
finalize({ metrics, output });
|
|
15297
15338
|
} catch (error) {
|
|
15298
|
-
const
|
|
15339
|
+
const loggedError2 = toLoggedError(error);
|
|
15299
15340
|
try {
|
|
15300
|
-
span.log({ error:
|
|
15341
|
+
span.log({ error: loggedError2 });
|
|
15301
15342
|
} catch (loggingError) {
|
|
15302
15343
|
debugLogger.error(
|
|
15303
15344
|
"Error logging AI SDK streaming failure:",
|
|
@@ -15305,7 +15346,7 @@ function patchAISDKStreamingResult(args) {
|
|
|
15305
15346
|
);
|
|
15306
15347
|
}
|
|
15307
15348
|
finalize({
|
|
15308
|
-
error: error instanceof Error ? error : new Error(String(
|
|
15349
|
+
error: error instanceof Error ? error : new Error(String(loggedError2))
|
|
15309
15350
|
});
|
|
15310
15351
|
}
|
|
15311
15352
|
};
|
|
@@ -15418,9 +15459,9 @@ function patchAISDKStreamingResult(args) {
|
|
|
15418
15459
|
}
|
|
15419
15460
|
controller.enqueue(value);
|
|
15420
15461
|
} catch (error) {
|
|
15421
|
-
const
|
|
15462
|
+
const loggedError2 = toLoggedError(error);
|
|
15422
15463
|
try {
|
|
15423
|
-
span.log({ error:
|
|
15464
|
+
span.log({ error: loggedError2 });
|
|
15424
15465
|
} catch (loggingError) {
|
|
15425
15466
|
debugLogger.error(
|
|
15426
15467
|
"Error logging AI SDK base stream failure:",
|
|
@@ -15428,7 +15469,7 @@ function patchAISDKStreamingResult(args) {
|
|
|
15428
15469
|
);
|
|
15429
15470
|
}
|
|
15430
15471
|
finalize({
|
|
15431
|
-
error: error instanceof Error ? error : new Error(String(
|
|
15472
|
+
error: error instanceof Error ? error : new Error(String(loggedError2))
|
|
15432
15473
|
});
|
|
15433
15474
|
controller.error(error);
|
|
15434
15475
|
}
|
|
@@ -16828,16 +16869,16 @@ function braintrustAISDKTelemetry() {
|
|
|
16828
16869
|
if (!toolCallId || !state) {
|
|
16829
16870
|
return;
|
|
16830
16871
|
}
|
|
16831
|
-
const
|
|
16872
|
+
const toolOutput2 = event.toolOutput;
|
|
16832
16873
|
const workflowToolError = event.success === false && "error" in event ? event.error : void 0;
|
|
16833
|
-
if (
|
|
16834
|
-
const error =
|
|
16874
|
+
if (toolOutput2?.type === "tool-error" || workflowToolError !== void 0) {
|
|
16875
|
+
const error = toolOutput2?.error ?? workflowToolError;
|
|
16835
16876
|
state.span.log({
|
|
16836
16877
|
error: error instanceof Error ? error.message : String(error),
|
|
16837
16878
|
metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
|
|
16838
16879
|
});
|
|
16839
16880
|
} else {
|
|
16840
|
-
const output =
|
|
16881
|
+
const output = toolOutput2 && "output" in toolOutput2 ? toolOutput2.output : event.output;
|
|
16841
16882
|
state.span.log({
|
|
16842
16883
|
...shouldRecordOutputs(event) ? { output } : {},
|
|
16843
16884
|
metrics: typeof event.durationMs === "number" ? { duration_ms: event.durationMs } : {}
|
|
@@ -18699,6 +18740,23 @@ function processImagesInOutput(output) {
|
|
|
18699
18740
|
return output;
|
|
18700
18741
|
}
|
|
18701
18742
|
|
|
18743
|
+
// src/instrumentation/plugins/openai-manual-instrumentation-utils.ts
|
|
18744
|
+
async function deterministicDigest(namespace, ...parts) {
|
|
18745
|
+
const encoded = new TextEncoder().encode(
|
|
18746
|
+
[namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
|
|
18747
|
+
);
|
|
18748
|
+
return new Uint8Array(
|
|
18749
|
+
await globalThis.crypto.subtle.digest("SHA-256", encoded)
|
|
18750
|
+
);
|
|
18751
|
+
}
|
|
18752
|
+
function digestHex(bytes, length) {
|
|
18753
|
+
return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
18754
|
+
}
|
|
18755
|
+
function digestUuid(bytes) {
|
|
18756
|
+
const hex = digestHex(bytes, 16);
|
|
18757
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
18758
|
+
}
|
|
18759
|
+
|
|
18702
18760
|
// src/instrumentation/plugins/openai-batch-instrumentation.ts
|
|
18703
18761
|
var SUPPORTED_ENDPOINTS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/responses"]);
|
|
18704
18762
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
@@ -18739,21 +18797,6 @@ async function exportParent(parent) {
|
|
|
18739
18797
|
}
|
|
18740
18798
|
return void 0;
|
|
18741
18799
|
}
|
|
18742
|
-
async function deterministicDigest(namespace, ...parts) {
|
|
18743
|
-
const encoded = new TextEncoder().encode(
|
|
18744
|
-
[namespace, ...parts].map((part) => `${part.length}:${part}`).join("\0")
|
|
18745
|
-
);
|
|
18746
|
-
return new Uint8Array(
|
|
18747
|
-
await globalThis.crypto.subtle.digest("SHA-256", encoded)
|
|
18748
|
-
);
|
|
18749
|
-
}
|
|
18750
|
-
function digestHex(bytes, length) {
|
|
18751
|
-
return Array.from(bytes.slice(0, length)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
18752
|
-
}
|
|
18753
|
-
function digestUuid(bytes) {
|
|
18754
|
-
const hex = digestHex(bytes, 16);
|
|
18755
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
18756
|
-
}
|
|
18757
18800
|
async function batchSpanIds(inputFileId) {
|
|
18758
18801
|
const [row, span, root] = await Promise.all([
|
|
18759
18802
|
deterministicDigest("openai:batch:row", inputFileId),
|
|
@@ -19244,6 +19287,628 @@ var interceptOpenAIBatchTraceComplete = (target, thisArg, args) => Promise.resol
|
|
|
19244
19287
|
return result;
|
|
19245
19288
|
});
|
|
19246
19289
|
|
|
19290
|
+
// src/instrumentation/plugins/openai-agents-api-instrumentation.ts
|
|
19291
|
+
var TERMINAL_TURN_EVENTS = /* @__PURE__ */ new Set([
|
|
19292
|
+
"agent.session.turn.completed",
|
|
19293
|
+
"agent.session.turn.failed",
|
|
19294
|
+
"agent.session.turn.cancelled"
|
|
19295
|
+
]);
|
|
19296
|
+
var TURN_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
|
|
19297
|
+
"agent.session.turn.created",
|
|
19298
|
+
"agent.session.turn.in_progress",
|
|
19299
|
+
...TERMINAL_TURN_EVENTS
|
|
19300
|
+
]);
|
|
19301
|
+
var SESSION_EVENTS = /* @__PURE__ */ new Set([
|
|
19302
|
+
"agent.session.created",
|
|
19303
|
+
"agent.session.failed",
|
|
19304
|
+
"agent.session.idle",
|
|
19305
|
+
"agent.session.in_progress",
|
|
19306
|
+
"agent.session.requires_action"
|
|
19307
|
+
]);
|
|
19308
|
+
var SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
|
|
19309
|
+
"agent.session.subagent.active",
|
|
19310
|
+
"agent.session.subagent.closed",
|
|
19311
|
+
"agent.session.subagent.created"
|
|
19312
|
+
]);
|
|
19313
|
+
function read2(value, key) {
|
|
19314
|
+
if (!isObject(value)) {
|
|
19315
|
+
return void 0;
|
|
19316
|
+
}
|
|
19317
|
+
try {
|
|
19318
|
+
return Reflect.get(value, key);
|
|
19319
|
+
} catch {
|
|
19320
|
+
return void 0;
|
|
19321
|
+
}
|
|
19322
|
+
}
|
|
19323
|
+
function stringValue(value) {
|
|
19324
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
19325
|
+
}
|
|
19326
|
+
function recordValue(record, key) {
|
|
19327
|
+
return Object.hasOwn(record, key) ? record[key] : void 0;
|
|
19328
|
+
}
|
|
19329
|
+
function setRecordValue(record, key, value) {
|
|
19330
|
+
Object.defineProperty(record, key, {
|
|
19331
|
+
configurable: true,
|
|
19332
|
+
enumerable: true,
|
|
19333
|
+
value,
|
|
19334
|
+
writable: true
|
|
19335
|
+
});
|
|
19336
|
+
}
|
|
19337
|
+
function loggedError(value, fallback) {
|
|
19338
|
+
if (value instanceof Error) {
|
|
19339
|
+
return value;
|
|
19340
|
+
}
|
|
19341
|
+
const message = stringValue(read2(value, "message"));
|
|
19342
|
+
return new Error(message ?? (typeof value === "string" ? value : fallback));
|
|
19343
|
+
}
|
|
19344
|
+
function logInstrumentationError2(context, error) {
|
|
19345
|
+
debugLogger.debug(`OpenAI Agents API instrumentation ${context}:`, error);
|
|
19346
|
+
}
|
|
19347
|
+
async function childSpanIds2(rootKey, kind, providerId) {
|
|
19348
|
+
const [row, span] = await Promise.all([
|
|
19349
|
+
deterministicDigest("openai:agents:row", rootKey, kind, providerId),
|
|
19350
|
+
deterministicDigest("openai:agents:span", rootKey, kind, providerId)
|
|
19351
|
+
]);
|
|
19352
|
+
return { rowId: digestUuid(row), spanId: digestHex(span, 8) };
|
|
19353
|
+
}
|
|
19354
|
+
function traceMetadata(args) {
|
|
19355
|
+
const metadata = {};
|
|
19356
|
+
const suppliedMetadata = read2(args, "metadata");
|
|
19357
|
+
if (isObject(suppliedMetadata)) {
|
|
19358
|
+
try {
|
|
19359
|
+
for (const key of Object.keys(suppliedMetadata)) {
|
|
19360
|
+
metadata[key] = read2(suppliedMetadata, key);
|
|
19361
|
+
}
|
|
19362
|
+
} catch (error) {
|
|
19363
|
+
logInstrumentationError2("could not read supplied metadata", error);
|
|
19364
|
+
}
|
|
19365
|
+
}
|
|
19366
|
+
const agent = read2(args, "agent");
|
|
19367
|
+
const agentId = stringValue(read2(agent, "id")) ?? stringValue(read2(args, "agent_id"));
|
|
19368
|
+
const agentName = stringValue(read2(agent, "name"));
|
|
19369
|
+
const model = stringValue(read2(agent, "model"));
|
|
19370
|
+
return {
|
|
19371
|
+
...metadata,
|
|
19372
|
+
api: "agents",
|
|
19373
|
+
...agentId ? { agent_id: agentId } : {},
|
|
19374
|
+
...agentName ? { agent_name: agentName } : {},
|
|
19375
|
+
...model ? { model } : {},
|
|
19376
|
+
provider: "openai"
|
|
19377
|
+
};
|
|
19378
|
+
}
|
|
19379
|
+
function copyState(state) {
|
|
19380
|
+
return {
|
|
19381
|
+
...state,
|
|
19382
|
+
callItems: { ...state.callItems },
|
|
19383
|
+
eventIds: [...state.eventIds],
|
|
19384
|
+
openTools: { ...state.openTools },
|
|
19385
|
+
subagents: { ...state.subagents },
|
|
19386
|
+
turnSubagents: { ...state.turnSubagents }
|
|
19387
|
+
};
|
|
19388
|
+
}
|
|
19389
|
+
function startRootSpan(state) {
|
|
19390
|
+
const root = SpanComponentsV4.fromStr(state.root);
|
|
19391
|
+
const parent = SpanComponentsV4.fromStr(state.rootParent);
|
|
19392
|
+
const rowId = stringValue(root.data.row_id);
|
|
19393
|
+
const rootSpanId = stringValue(root.data.root_span_id);
|
|
19394
|
+
const spanId = stringValue(root.data.span_id);
|
|
19395
|
+
if (!rowId || !rootSpanId || !spanId) {
|
|
19396
|
+
throw new Error("OpenAI Agents trace root is invalid");
|
|
19397
|
+
}
|
|
19398
|
+
const hasParentSpan = Boolean(
|
|
19399
|
+
parent.data.row_id && parent.data.span_id && parent.data.root_span_id
|
|
19400
|
+
);
|
|
19401
|
+
return withCurrent(
|
|
19402
|
+
NOOP_SPAN,
|
|
19403
|
+
() => _internalStartSpanWithInitialMergeAndParentSpanIds(
|
|
19404
|
+
withSpanInstrumentationName(
|
|
19405
|
+
{
|
|
19406
|
+
name: "openai.agents.turn",
|
|
19407
|
+
type: "task" /* TASK */,
|
|
19408
|
+
parent: state.rootParent,
|
|
19409
|
+
...!hasParentSpan ? {
|
|
19410
|
+
parentSpanIds: {
|
|
19411
|
+
parentSpanIds: [],
|
|
19412
|
+
rootSpanId
|
|
19413
|
+
}
|
|
19414
|
+
} : {},
|
|
19415
|
+
spanId,
|
|
19416
|
+
startTime: state.startTime,
|
|
19417
|
+
event: { id: rowId }
|
|
19418
|
+
},
|
|
19419
|
+
INSTRUMENTATION_NAMES.OPENAI
|
|
19420
|
+
)
|
|
19421
|
+
)
|
|
19422
|
+
);
|
|
19423
|
+
}
|
|
19424
|
+
async function startSubagentSpan(state, subagentId, input, metadata, visiting = /* @__PURE__ */ new Set()) {
|
|
19425
|
+
const subagent = recordValue(state.subagents, subagentId);
|
|
19426
|
+
let parent = state.root;
|
|
19427
|
+
if (subagent?.parentAgentId && subagent.parentAgentId !== subagentId && recordValue(state.subagents, subagent.parentAgentId) && !visiting.has(subagent.parentAgentId)) {
|
|
19428
|
+
visiting.add(subagentId);
|
|
19429
|
+
parent = await (await startSubagentSpan(
|
|
19430
|
+
state,
|
|
19431
|
+
subagent.parentAgentId,
|
|
19432
|
+
void 0,
|
|
19433
|
+
void 0,
|
|
19434
|
+
visiting
|
|
19435
|
+
)).export();
|
|
19436
|
+
}
|
|
19437
|
+
const ids = await childSpanIds2(state.rootKey, "subagent", subagentId);
|
|
19438
|
+
return withCurrent(
|
|
19439
|
+
NOOP_SPAN,
|
|
19440
|
+
() => _internalStartSpanWithInitialMerge(
|
|
19441
|
+
withSpanInstrumentationName(
|
|
19442
|
+
{
|
|
19443
|
+
name: "openai.agents.subagent",
|
|
19444
|
+
type: "task" /* TASK */,
|
|
19445
|
+
parent,
|
|
19446
|
+
spanId: ids.spanId,
|
|
19447
|
+
startTime: subagent?.openedAt,
|
|
19448
|
+
event: {
|
|
19449
|
+
id: ids.rowId,
|
|
19450
|
+
...input !== void 0 ? { input } : {},
|
|
19451
|
+
metadata: {
|
|
19452
|
+
...metadata,
|
|
19453
|
+
agent_id: subagentId,
|
|
19454
|
+
...subagent?.parentAgentId ? { parent_agent_id: subagent.parentAgentId } : {},
|
|
19455
|
+
provider: "openai"
|
|
19456
|
+
}
|
|
19457
|
+
}
|
|
19458
|
+
},
|
|
19459
|
+
INSTRUMENTATION_NAMES.OPENAI
|
|
19460
|
+
)
|
|
19461
|
+
)
|
|
19462
|
+
);
|
|
19463
|
+
}
|
|
19464
|
+
async function parentForTurn(state, turnId) {
|
|
19465
|
+
const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
|
|
19466
|
+
if (!subagentId) {
|
|
19467
|
+
return state.root;
|
|
19468
|
+
}
|
|
19469
|
+
return await (await startSubagentSpan(state, subagentId)).export();
|
|
19470
|
+
}
|
|
19471
|
+
async function startToolSpan(state, tool, input) {
|
|
19472
|
+
const ids = await childSpanIds2(state.rootKey, "tool", tool.itemId);
|
|
19473
|
+
return withCurrent(
|
|
19474
|
+
NOOP_SPAN,
|
|
19475
|
+
async () => _internalStartSpanWithInitialMerge(
|
|
19476
|
+
withSpanInstrumentationName(
|
|
19477
|
+
{
|
|
19478
|
+
name: tool.name,
|
|
19479
|
+
type: "tool" /* TOOL */,
|
|
19480
|
+
parent: await parentForTurn(state, tool.turnId),
|
|
19481
|
+
spanId: ids.spanId,
|
|
19482
|
+
startTime: tool.startTime,
|
|
19483
|
+
event: {
|
|
19484
|
+
id: ids.rowId,
|
|
19485
|
+
...input !== void 0 ? { input } : {},
|
|
19486
|
+
metadata: {
|
|
19487
|
+
item_id: tool.itemId,
|
|
19488
|
+
provider: "openai",
|
|
19489
|
+
tool_type: tool.toolType,
|
|
19490
|
+
...tool.turnId ? { turn_id: tool.turnId } : {}
|
|
19491
|
+
}
|
|
19492
|
+
}
|
|
19493
|
+
},
|
|
19494
|
+
INSTRUMENTATION_NAMES.OPENAI
|
|
19495
|
+
)
|
|
19496
|
+
)
|
|
19497
|
+
);
|
|
19498
|
+
}
|
|
19499
|
+
function toolFromItem(item, observedAt) {
|
|
19500
|
+
const itemId = stringValue(read2(item, "id"));
|
|
19501
|
+
const toolType = stringValue(read2(item, "type"));
|
|
19502
|
+
if (!itemId || !toolType) {
|
|
19503
|
+
return void 0;
|
|
19504
|
+
}
|
|
19505
|
+
const turnId = stringValue(read2(item, "turn_id"));
|
|
19506
|
+
switch (toolType) {
|
|
19507
|
+
case "function_call":
|
|
19508
|
+
return {
|
|
19509
|
+
input: read2(item, "arguments"),
|
|
19510
|
+
tool: {
|
|
19511
|
+
itemId,
|
|
19512
|
+
name: stringValue(read2(item, "name")) ?? "Function call",
|
|
19513
|
+
startTime: observedAt,
|
|
19514
|
+
toolType,
|
|
19515
|
+
...turnId ? { turnId } : {}
|
|
19516
|
+
}
|
|
19517
|
+
};
|
|
19518
|
+
case "mcp_call": {
|
|
19519
|
+
const name = stringValue(read2(item, "name")) ?? "MCP call";
|
|
19520
|
+
const server = stringValue(read2(item, "server_label"));
|
|
19521
|
+
return {
|
|
19522
|
+
input: read2(item, "arguments"),
|
|
19523
|
+
tool: {
|
|
19524
|
+
itemId,
|
|
19525
|
+
name: server ? `${server}.${name}` : name,
|
|
19526
|
+
startTime: observedAt,
|
|
19527
|
+
toolType,
|
|
19528
|
+
...turnId ? { turnId } : {}
|
|
19529
|
+
}
|
|
19530
|
+
};
|
|
19531
|
+
}
|
|
19532
|
+
case "web_search_call":
|
|
19533
|
+
return {
|
|
19534
|
+
input: read2(item, "action"),
|
|
19535
|
+
tool: {
|
|
19536
|
+
itemId,
|
|
19537
|
+
name: "Web search",
|
|
19538
|
+
startTime: observedAt,
|
|
19539
|
+
toolType,
|
|
19540
|
+
...turnId ? { turnId } : {}
|
|
19541
|
+
}
|
|
19542
|
+
};
|
|
19543
|
+
case "command_execution":
|
|
19544
|
+
return {
|
|
19545
|
+
input: {
|
|
19546
|
+
command: read2(item, "command"),
|
|
19547
|
+
cwd: read2(item, "cwd")
|
|
19548
|
+
},
|
|
19549
|
+
tool: {
|
|
19550
|
+
itemId,
|
|
19551
|
+
name: "Command execution",
|
|
19552
|
+
startTime: observedAt,
|
|
19553
|
+
toolType,
|
|
19554
|
+
...turnId ? { turnId } : {}
|
|
19555
|
+
}
|
|
19556
|
+
};
|
|
19557
|
+
default:
|
|
19558
|
+
return void 0;
|
|
19559
|
+
}
|
|
19560
|
+
}
|
|
19561
|
+
function textFromContent(content) {
|
|
19562
|
+
if (!Array.isArray(content)) {
|
|
19563
|
+
return void 0;
|
|
19564
|
+
}
|
|
19565
|
+
const text = [];
|
|
19566
|
+
for (const part of content) {
|
|
19567
|
+
const partText = read2(part, "text");
|
|
19568
|
+
if (read2(part, "type") === "output_text" && typeof partText === "string") {
|
|
19569
|
+
text.push(partText);
|
|
19570
|
+
}
|
|
19571
|
+
}
|
|
19572
|
+
return text.length > 0 ? text.join("") : void 0;
|
|
19573
|
+
}
|
|
19574
|
+
function toolOutput(item, toolType) {
|
|
19575
|
+
switch (toolType) {
|
|
19576
|
+
case "function_call":
|
|
19577
|
+
return read2(item, "output");
|
|
19578
|
+
case "mcp_call":
|
|
19579
|
+
return read2(item, "output");
|
|
19580
|
+
case "web_search_call":
|
|
19581
|
+
return read2(item, "action");
|
|
19582
|
+
case "command_execution":
|
|
19583
|
+
return read2(item, "output");
|
|
19584
|
+
default:
|
|
19585
|
+
return void 0;
|
|
19586
|
+
}
|
|
19587
|
+
}
|
|
19588
|
+
function toolFailed(item, toolType) {
|
|
19589
|
+
const status = read2(item, "status");
|
|
19590
|
+
const explicitError = read2(item, "error");
|
|
19591
|
+
if (explicitError !== void 0 && explicitError !== null) {
|
|
19592
|
+
return loggedError(explicitError, `OpenAI ${toolType} failed`);
|
|
19593
|
+
}
|
|
19594
|
+
if (status === "failed" || status === "incomplete") {
|
|
19595
|
+
return new Error(`OpenAI ${toolType} ${status}`);
|
|
19596
|
+
}
|
|
19597
|
+
if (toolType === "command_execution" && typeof read2(item, "exit_code") === "number" && read2(item, "exit_code") !== 0) {
|
|
19598
|
+
return new Error(
|
|
19599
|
+
`OpenAI command exited with code ${read2(item, "exit_code")}`
|
|
19600
|
+
);
|
|
19601
|
+
}
|
|
19602
|
+
return void 0;
|
|
19603
|
+
}
|
|
19604
|
+
async function completeTool(state, tool, item, endTime) {
|
|
19605
|
+
const span = await startToolSpan(state, tool);
|
|
19606
|
+
const output = toolOutput(item, tool.toolType);
|
|
19607
|
+
const error = toolFailed(item, tool.toolType);
|
|
19608
|
+
span.log({
|
|
19609
|
+
...output !== void 0 ? { output } : {},
|
|
19610
|
+
...error ? { error } : {},
|
|
19611
|
+
metadata: {
|
|
19612
|
+
status: read2(item, "status"),
|
|
19613
|
+
...tool.toolType === "command_execution" ? { exit_code: read2(item, "exit_code") } : {}
|
|
19614
|
+
}
|
|
19615
|
+
});
|
|
19616
|
+
span.end({ endTime });
|
|
19617
|
+
Reflect.deleteProperty(state.openTools, tool.itemId);
|
|
19618
|
+
}
|
|
19619
|
+
async function captureMessage(state, item) {
|
|
19620
|
+
if (read2(item, "type") !== "message" || read2(item, "role") !== "assistant" || read2(item, "phase") !== "final_answer") {
|
|
19621
|
+
return;
|
|
19622
|
+
}
|
|
19623
|
+
const output = textFromContent(read2(item, "content"));
|
|
19624
|
+
if (output === void 0) {
|
|
19625
|
+
return;
|
|
19626
|
+
}
|
|
19627
|
+
const turnId = stringValue(read2(item, "turn_id"));
|
|
19628
|
+
const subagentId = turnId ? recordValue(state.turnSubagents, turnId) : void 0;
|
|
19629
|
+
if (subagentId) {
|
|
19630
|
+
(await startSubagentSpan(state, subagentId)).log({ output });
|
|
19631
|
+
} else {
|
|
19632
|
+
startRootSpan(state).log({ output });
|
|
19633
|
+
}
|
|
19634
|
+
}
|
|
19635
|
+
async function captureItem(state, item, isDone, observedAt) {
|
|
19636
|
+
await captureMessage(state, item);
|
|
19637
|
+
const itemType = stringValue(read2(item, "type"));
|
|
19638
|
+
if (itemType === "function_call_output") {
|
|
19639
|
+
const callId = stringValue(read2(item, "call_id"));
|
|
19640
|
+
const itemId = callId ? recordValue(state.callItems, callId) : void 0;
|
|
19641
|
+
const tool2 = itemId ? recordValue(state.openTools, itemId) : void 0;
|
|
19642
|
+
if (tool2) {
|
|
19643
|
+
await completeTool(state, tool2, item, observedAt);
|
|
19644
|
+
}
|
|
19645
|
+
return;
|
|
19646
|
+
}
|
|
19647
|
+
const descriptor = toolFromItem(item, observedAt);
|
|
19648
|
+
if (!descriptor) {
|
|
19649
|
+
return;
|
|
19650
|
+
}
|
|
19651
|
+
const existing = recordValue(state.openTools, descriptor.tool.itemId);
|
|
19652
|
+
const tool = existing ?? descriptor.tool;
|
|
19653
|
+
setRecordValue(state.openTools, tool.itemId, tool);
|
|
19654
|
+
if (itemType === "function_call") {
|
|
19655
|
+
const callId = stringValue(read2(item, "call_id"));
|
|
19656
|
+
if (callId) {
|
|
19657
|
+
setRecordValue(state.callItems, callId, tool.itemId);
|
|
19658
|
+
}
|
|
19659
|
+
}
|
|
19660
|
+
await startToolSpan(state, tool, descriptor.input);
|
|
19661
|
+
const status = read2(item, "status");
|
|
19662
|
+
const terminalFunctionCall = itemType === "function_call" && (status === "failed" || status === "incomplete");
|
|
19663
|
+
if (itemType !== "function_call" && (isDone || status !== "in_progress") || terminalFunctionCall) {
|
|
19664
|
+
await completeTool(state, tool, item, observedAt);
|
|
19665
|
+
}
|
|
19666
|
+
}
|
|
19667
|
+
function updateSessionMetadata(state, session) {
|
|
19668
|
+
const sessionId = stringValue(read2(session, "id"));
|
|
19669
|
+
const agent = read2(session, "agent");
|
|
19670
|
+
startRootSpan(state).log({
|
|
19671
|
+
metadata: {
|
|
19672
|
+
...sessionId ? { session_id: sessionId } : {},
|
|
19673
|
+
...stringValue(read2(agent, "id")) ? { agent_id: read2(agent, "id") } : {},
|
|
19674
|
+
...stringValue(read2(agent, "name")) ? { agent_name: read2(agent, "name") } : {},
|
|
19675
|
+
...stringValue(read2(agent, "model")) ? { model: read2(agent, "model") } : {}
|
|
19676
|
+
}
|
|
19677
|
+
});
|
|
19678
|
+
}
|
|
19679
|
+
async function captureSubagent(state, eventType, subagent, observedAt) {
|
|
19680
|
+
const subagentId = stringValue(read2(subagent, "id"));
|
|
19681
|
+
if (!subagentId) {
|
|
19682
|
+
return;
|
|
19683
|
+
}
|
|
19684
|
+
const existing = recordValue(state.subagents, subagentId);
|
|
19685
|
+
const observedOpenedAt = read2(subagent, "opened_at");
|
|
19686
|
+
const openedAt = typeof observedOpenedAt === "number" && Number.isFinite(observedOpenedAt) && observedOpenedAt >= 0 ? observedOpenedAt : existing?.openedAt ?? observedAt;
|
|
19687
|
+
const observedClosedAt = read2(subagent, "closed_at");
|
|
19688
|
+
const closedAt = typeof observedClosedAt === "number" && Number.isFinite(observedClosedAt) && observedClosedAt >= 0 ? observedClosedAt : existing?.closedAt;
|
|
19689
|
+
const parentAgentId = stringValue(read2(subagent, "parent_agent_id")) ?? existing?.parentAgentId;
|
|
19690
|
+
setRecordValue(state.subagents, subagentId, {
|
|
19691
|
+
...closedAt !== void 0 ? { closedAt } : {},
|
|
19692
|
+
openedAt,
|
|
19693
|
+
...parentAgentId ? { parentAgentId } : {}
|
|
19694
|
+
});
|
|
19695
|
+
const span = await startSubagentSpan(
|
|
19696
|
+
state,
|
|
19697
|
+
subagentId,
|
|
19698
|
+
read2(subagent, "instructions"),
|
|
19699
|
+
{
|
|
19700
|
+
...stringValue(read2(subagent, "name")) ? { agent_name: read2(subagent, "name") } : {},
|
|
19701
|
+
status: read2(subagent, "status")
|
|
19702
|
+
}
|
|
19703
|
+
);
|
|
19704
|
+
if (eventType === "agent.session.subagent.closed") {
|
|
19705
|
+
span.end({ endTime: closedAt ?? observedAt });
|
|
19706
|
+
}
|
|
19707
|
+
}
|
|
19708
|
+
async function closeTrace(state, endTime, error, usage) {
|
|
19709
|
+
if (state.ended) {
|
|
19710
|
+
return;
|
|
19711
|
+
}
|
|
19712
|
+
for (const tool of Object.values(state.openTools)) {
|
|
19713
|
+
const span = await startToolSpan(state, tool);
|
|
19714
|
+
span.log({
|
|
19715
|
+
error: error ?? new Error("OpenAI Agents turn ended before tool completion")
|
|
19716
|
+
});
|
|
19717
|
+
span.end({ endTime });
|
|
19718
|
+
}
|
|
19719
|
+
state.openTools = {};
|
|
19720
|
+
for (const subagentId of Object.keys(state.subagents)) {
|
|
19721
|
+
const subagent = state.subagents[subagentId];
|
|
19722
|
+
const span = await startSubagentSpan(state, subagentId);
|
|
19723
|
+
span.end({ endTime: subagent.closedAt ?? endTime });
|
|
19724
|
+
}
|
|
19725
|
+
const root = startRootSpan(state);
|
|
19726
|
+
root.log({
|
|
19727
|
+
...error ? { error } : {},
|
|
19728
|
+
metrics: parseMetricsFromUsage(usage)
|
|
19729
|
+
});
|
|
19730
|
+
root.end({ endTime });
|
|
19731
|
+
state.ended = true;
|
|
19732
|
+
}
|
|
19733
|
+
async function captureTurnLifecycle(state, event, eventType, observedAt) {
|
|
19734
|
+
const turn = read2(event, "turn");
|
|
19735
|
+
const turnId = stringValue(read2(event, "turn_id")) ?? stringValue(read2(turn, "id"));
|
|
19736
|
+
const subagentId = stringValue(read2(turn, "subagent_id"));
|
|
19737
|
+
if (turnId && subagentId) {
|
|
19738
|
+
setRecordValue(state.turnSubagents, turnId, subagentId);
|
|
19739
|
+
if (!recordValue(state.subagents, subagentId)) {
|
|
19740
|
+
const createdAt = read2(turn, "created_at");
|
|
19741
|
+
setRecordValue(state.subagents, subagentId, {
|
|
19742
|
+
openedAt: typeof createdAt === "number" && Number.isFinite(createdAt) && createdAt >= 0 ? createdAt : observedAt
|
|
19743
|
+
});
|
|
19744
|
+
}
|
|
19745
|
+
await startSubagentSpan(state, subagentId);
|
|
19746
|
+
}
|
|
19747
|
+
const sessionId = stringValue(read2(event, "session_id"));
|
|
19748
|
+
if (sessionId) {
|
|
19749
|
+
startRootSpan(state).log({ metadata: { session_id: sessionId } });
|
|
19750
|
+
}
|
|
19751
|
+
if (!TERMINAL_TURN_EVENTS.has(eventType) || subagentId) {
|
|
19752
|
+
if (subagentId && eventType === "agent.session.turn.failed") {
|
|
19753
|
+
(await startSubagentSpan(state, subagentId)).log({
|
|
19754
|
+
error: loggedError(read2(turn, "error"), "OpenAI subagent turn failed")
|
|
19755
|
+
});
|
|
19756
|
+
}
|
|
19757
|
+
return;
|
|
19758
|
+
}
|
|
19759
|
+
const completedAt = read2(turn, "completed_at");
|
|
19760
|
+
const endTime = typeof completedAt === "number" && Number.isFinite(completedAt) && completedAt >= 0 ? completedAt : observedAt;
|
|
19761
|
+
const usage = read2(event, "usage") ?? read2(turn, "usage");
|
|
19762
|
+
const error = eventType === "agent.session.turn.completed" ? void 0 : loggedError(
|
|
19763
|
+
read2(turn, "error"),
|
|
19764
|
+
eventType === "agent.session.turn.cancelled" ? "OpenAI Agents turn cancelled" : "OpenAI Agents turn failed"
|
|
19765
|
+
);
|
|
19766
|
+
await closeTrace(state, endTime, error, usage);
|
|
19767
|
+
}
|
|
19768
|
+
async function captureEvent(state, event) {
|
|
19769
|
+
if (state.ended) {
|
|
19770
|
+
return state;
|
|
19771
|
+
}
|
|
19772
|
+
const eventType = stringValue(read2(event, "type"));
|
|
19773
|
+
const eventId = stringValue(read2(event, "event_id"));
|
|
19774
|
+
if (!eventType || eventId && state.eventIds.includes(eventId)) {
|
|
19775
|
+
return state;
|
|
19776
|
+
}
|
|
19777
|
+
const next = copyState(state);
|
|
19778
|
+
const observedAt = getCurrentUnixTimestamp();
|
|
19779
|
+
let handled = false;
|
|
19780
|
+
if (SESSION_EVENTS.has(eventType)) {
|
|
19781
|
+
const session = read2(event, "session");
|
|
19782
|
+
if (session) {
|
|
19783
|
+
updateSessionMetadata(next, session);
|
|
19784
|
+
}
|
|
19785
|
+
handled = true;
|
|
19786
|
+
}
|
|
19787
|
+
if (eventType === "agent.session.turn.item.added") {
|
|
19788
|
+
await captureItem(next, read2(event, "item"), false, observedAt);
|
|
19789
|
+
handled = true;
|
|
19790
|
+
} else if (eventType === "agent.session.turn.item.done") {
|
|
19791
|
+
await captureItem(next, read2(event, "item"), true, observedAt);
|
|
19792
|
+
handled = true;
|
|
19793
|
+
} else if (TURN_LIFECYCLE_EVENTS.has(eventType)) {
|
|
19794
|
+
await captureTurnLifecycle(next, event, eventType, observedAt);
|
|
19795
|
+
handled = true;
|
|
19796
|
+
} else if (SUBAGENT_EVENTS.has(eventType)) {
|
|
19797
|
+
await captureSubagent(next, eventType, read2(event, "subagent"), observedAt);
|
|
19798
|
+
handled = true;
|
|
19799
|
+
} else if (eventType === "agent.session.turn.output_text.delta" && next.firstTokenAt === void 0 && stringValue(read2(event, "delta"))) {
|
|
19800
|
+
next.firstTokenAt = observedAt;
|
|
19801
|
+
startRootSpan(next).log({
|
|
19802
|
+
metrics: { time_to_first_token: observedAt - next.startTime }
|
|
19803
|
+
});
|
|
19804
|
+
handled = true;
|
|
19805
|
+
} else if (eventType === "agent.session.failed") {
|
|
19806
|
+
const session = read2(event, "session");
|
|
19807
|
+
const lastActiveAt = read2(session, "last_active_at");
|
|
19808
|
+
const endTime = typeof lastActiveAt === "number" && Number.isFinite(lastActiveAt) && lastActiveAt >= 0 ? lastActiveAt : observedAt;
|
|
19809
|
+
await closeTrace(
|
|
19810
|
+
next,
|
|
19811
|
+
endTime,
|
|
19812
|
+
loggedError(read2(session, "error"), "OpenAI Agents session failed"),
|
|
19813
|
+
read2(session, "usage")
|
|
19814
|
+
);
|
|
19815
|
+
handled = true;
|
|
19816
|
+
} else if (eventType === "error") {
|
|
19817
|
+
await closeTrace(
|
|
19818
|
+
next,
|
|
19819
|
+
observedAt,
|
|
19820
|
+
loggedError(read2(event, "error"), "OpenAI Agents session failed")
|
|
19821
|
+
);
|
|
19822
|
+
handled = true;
|
|
19823
|
+
}
|
|
19824
|
+
if (!handled) {
|
|
19825
|
+
return state;
|
|
19826
|
+
}
|
|
19827
|
+
if (eventId) {
|
|
19828
|
+
next.eventIds.push(eventId);
|
|
19829
|
+
}
|
|
19830
|
+
return next;
|
|
19831
|
+
}
|
|
19832
|
+
var interceptOpenAIAgentsTraceStart = async (target, thisArg, args) => {
|
|
19833
|
+
const fallback = await Reflect.apply(target, thisArg, args);
|
|
19834
|
+
try {
|
|
19835
|
+
const state = args[0].state;
|
|
19836
|
+
const parent = state.rootParent;
|
|
19837
|
+
const traceArgs = args[0].args;
|
|
19838
|
+
const parentComponents = SpanComponentsV4.fromStr(parent);
|
|
19839
|
+
const hasParentSpan = Boolean(
|
|
19840
|
+
parentComponents.data.row_id && parentComponents.data.span_id && parentComponents.data.root_span_id
|
|
19841
|
+
);
|
|
19842
|
+
const rootComponents = SpanComponentsV4.fromStr(state.root);
|
|
19843
|
+
const rowId = stringValue(rootComponents.data.row_id);
|
|
19844
|
+
const rootSpanId = stringValue(rootComponents.data.root_span_id);
|
|
19845
|
+
const spanId = stringValue(rootComponents.data.span_id);
|
|
19846
|
+
if (!rowId || !rootSpanId || !spanId) {
|
|
19847
|
+
throw new Error("OpenAI Agents trace root is invalid");
|
|
19848
|
+
}
|
|
19849
|
+
withCurrent(
|
|
19850
|
+
NOOP_SPAN,
|
|
19851
|
+
() => _internalStartSpanWithInitialMergeAndParentSpanIds(
|
|
19852
|
+
withSpanInstrumentationName(
|
|
19853
|
+
{
|
|
19854
|
+
name: "openai.agents.turn",
|
|
19855
|
+
type: "task" /* TASK */,
|
|
19856
|
+
parent,
|
|
19857
|
+
...!hasParentSpan ? {
|
|
19858
|
+
parentSpanIds: {
|
|
19859
|
+
parentSpanIds: [],
|
|
19860
|
+
rootSpanId
|
|
19861
|
+
}
|
|
19862
|
+
} : {},
|
|
19863
|
+
spanId,
|
|
19864
|
+
startTime: state.startTime,
|
|
19865
|
+
event: {
|
|
19866
|
+
id: rowId,
|
|
19867
|
+
input: read2(traceArgs, "input"),
|
|
19868
|
+
metadata: traceMetadata(traceArgs)
|
|
19869
|
+
}
|
|
19870
|
+
},
|
|
19871
|
+
INSTRUMENTATION_NAMES.OPENAI
|
|
19872
|
+
)
|
|
19873
|
+
)
|
|
19874
|
+
);
|
|
19875
|
+
return state;
|
|
19876
|
+
} catch (error) {
|
|
19877
|
+
logInstrumentationError2("could not start trace", error);
|
|
19878
|
+
return fallback;
|
|
19879
|
+
}
|
|
19880
|
+
};
|
|
19881
|
+
var interceptOpenAIAgentsTraceCapture = async (target, thisArg, args) => {
|
|
19882
|
+
const fallback = await Reflect.apply(target, thisArg, args);
|
|
19883
|
+
if (!args[0].state) {
|
|
19884
|
+
return fallback;
|
|
19885
|
+
}
|
|
19886
|
+
try {
|
|
19887
|
+
return await captureEvent(args[0].state, args[0].event);
|
|
19888
|
+
} catch (error) {
|
|
19889
|
+
logInstrumentationError2("could not capture event", error);
|
|
19890
|
+
return fallback;
|
|
19891
|
+
}
|
|
19892
|
+
};
|
|
19893
|
+
var interceptOpenAIAgentsTraceFail = async (target, thisArg, args) => {
|
|
19894
|
+
const fallback = await Reflect.apply(target, thisArg, args);
|
|
19895
|
+
if (!args[0].state) {
|
|
19896
|
+
return fallback;
|
|
19897
|
+
}
|
|
19898
|
+
try {
|
|
19899
|
+
const next = copyState(args[0].state);
|
|
19900
|
+
await closeTrace(
|
|
19901
|
+
next,
|
|
19902
|
+
getCurrentUnixTimestamp(),
|
|
19903
|
+
loggedError(args[0].error, "OpenAI Agents request failed")
|
|
19904
|
+
);
|
|
19905
|
+
return next;
|
|
19906
|
+
} catch (error) {
|
|
19907
|
+
logInstrumentationError2("could not fail trace", error);
|
|
19908
|
+
return fallback;
|
|
19909
|
+
}
|
|
19910
|
+
};
|
|
19911
|
+
|
|
19247
19912
|
// src/instrumentation/plugins/openai-plugin.ts
|
|
19248
19913
|
var OpenAIPlugin = class extends BasePlugin {
|
|
19249
19914
|
constructor() {
|
|
@@ -19251,6 +19916,13 @@ var OpenAIPlugin = class extends BasePlugin {
|
|
|
19251
19916
|
}
|
|
19252
19917
|
onEnable() {
|
|
19253
19918
|
this.unsubscribers.push(
|
|
19919
|
+
openAIChannels.agentsTraceStart.intercept(
|
|
19920
|
+
interceptOpenAIAgentsTraceStart
|
|
19921
|
+
),
|
|
19922
|
+
openAIChannels.agentsTraceCapture.intercept(
|
|
19923
|
+
interceptOpenAIAgentsTraceCapture
|
|
19924
|
+
),
|
|
19925
|
+
openAIChannels.agentsTraceFail.intercept(interceptOpenAIAgentsTraceFail),
|
|
19254
19926
|
openAIChannels.filesCreateTraced.intercept(
|
|
19255
19927
|
interceptOpenAIFilesCreateTraced
|
|
19256
19928
|
),
|
|
@@ -19795,7 +20467,7 @@ async function* patchCodexEventStream(events, state) {
|
|
|
19795
20467
|
try {
|
|
19796
20468
|
await handleCodexEvent(state, event);
|
|
19797
20469
|
} catch (error) {
|
|
19798
|
-
|
|
20470
|
+
logInstrumentationError3("OpenAI Codex stream event", error);
|
|
19799
20471
|
}
|
|
19800
20472
|
yield event;
|
|
19801
20473
|
}
|
|
@@ -20295,10 +20967,10 @@ function safeLog2(span, event) {
|
|
|
20295
20967
|
try {
|
|
20296
20968
|
span.log(event);
|
|
20297
20969
|
} catch (error) {
|
|
20298
|
-
|
|
20970
|
+
logInstrumentationError3("OpenAI Codex span log", error);
|
|
20299
20971
|
}
|
|
20300
20972
|
}
|
|
20301
|
-
function
|
|
20973
|
+
function logInstrumentationError3(context, error) {
|
|
20302
20974
|
debugLogger.error(`Error processing ${context}:`, error);
|
|
20303
20975
|
}
|
|
20304
20976
|
|
|
@@ -23478,7 +24150,7 @@ function wrapSendOptionsCallbacks(options, state) {
|
|
|
23478
24150
|
try {
|
|
23479
24151
|
await handleInteractionUpdate(state, args.update);
|
|
23480
24152
|
} catch (error) {
|
|
23481
|
-
|
|
24153
|
+
logInstrumentationError4("Cursor SDK onDelta", error);
|
|
23482
24154
|
}
|
|
23483
24155
|
if (originalOnDelta) {
|
|
23484
24156
|
return originalOnDelta(args);
|
|
@@ -23488,7 +24160,7 @@ function wrapSendOptionsCallbacks(options, state) {
|
|
|
23488
24160
|
try {
|
|
23489
24161
|
handleStepUpdate(state, args.step);
|
|
23490
24162
|
} catch (error) {
|
|
23491
|
-
|
|
24163
|
+
logInstrumentationError4("Cursor SDK onStep", error);
|
|
23492
24164
|
}
|
|
23493
24165
|
if (originalOnStep) {
|
|
23494
24166
|
return originalOnStep(args);
|
|
@@ -23570,7 +24242,7 @@ async function* patchCursorStream(stream, state) {
|
|
|
23570
24242
|
try {
|
|
23571
24243
|
await handleStreamMessage2(state, message);
|
|
23572
24244
|
} catch (error) {
|
|
23573
|
-
|
|
24245
|
+
logInstrumentationError4("Cursor SDK stream", error);
|
|
23574
24246
|
}
|
|
23575
24247
|
yield message;
|
|
23576
24248
|
}
|
|
@@ -23634,7 +24306,7 @@ async function handleToolUpdate(state, update) {
|
|
|
23634
24306
|
if (!state.activeToolSpans.has(callId)) {
|
|
23635
24307
|
state.activeToolSpans.set(
|
|
23636
24308
|
callId,
|
|
23637
|
-
await
|
|
24309
|
+
await startToolSpan2(state, {
|
|
23638
24310
|
args,
|
|
23639
24311
|
callId,
|
|
23640
24312
|
name,
|
|
@@ -23645,7 +24317,7 @@ async function handleToolUpdate(state, update) {
|
|
|
23645
24317
|
}
|
|
23646
24318
|
return;
|
|
23647
24319
|
}
|
|
23648
|
-
const toolState = state.activeToolSpans.get(callId) ?? await
|
|
24320
|
+
const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
|
|
23649
24321
|
args,
|
|
23650
24322
|
callId,
|
|
23651
24323
|
name,
|
|
@@ -23682,7 +24354,7 @@ async function handleStreamMessage2(state, message) {
|
|
|
23682
24354
|
} else if (block?.type === "tool_use" && block.id) {
|
|
23683
24355
|
state.activeToolSpans.set(
|
|
23684
24356
|
block.id,
|
|
23685
|
-
await
|
|
24357
|
+
await startToolSpan2(state, {
|
|
23686
24358
|
args: block.input,
|
|
23687
24359
|
callId: block.id,
|
|
23688
24360
|
name: block.name,
|
|
@@ -23717,7 +24389,7 @@ async function handleToolMessage(state, message) {
|
|
|
23717
24389
|
if (!state.activeToolSpans.has(callId)) {
|
|
23718
24390
|
state.activeToolSpans.set(
|
|
23719
24391
|
callId,
|
|
23720
|
-
await
|
|
24392
|
+
await startToolSpan2(state, {
|
|
23721
24393
|
args: message.args,
|
|
23722
24394
|
callId,
|
|
23723
24395
|
name: message.name,
|
|
@@ -23728,7 +24400,7 @@ async function handleToolMessage(state, message) {
|
|
|
23728
24400
|
}
|
|
23729
24401
|
return;
|
|
23730
24402
|
}
|
|
23731
|
-
const toolState = state.activeToolSpans.get(callId) ?? await
|
|
24403
|
+
const toolState = state.activeToolSpans.get(callId) ?? await startToolSpan2(state, {
|
|
23732
24404
|
args: message.args,
|
|
23733
24405
|
callId,
|
|
23734
24406
|
name: message.name,
|
|
@@ -23755,7 +24427,7 @@ async function handleConversation(state, turns) {
|
|
|
23755
24427
|
const command = turn.turn?.shellCommand?.command;
|
|
23756
24428
|
if (command) {
|
|
23757
24429
|
const callId = `shell:${state.activeToolSpans.size}:${command}`;
|
|
23758
|
-
const toolState = await
|
|
24430
|
+
const toolState = await startToolSpan2(state, {
|
|
23759
24431
|
args: turn.turn?.shellCommand,
|
|
23760
24432
|
callId,
|
|
23761
24433
|
name: "shell",
|
|
@@ -23779,7 +24451,7 @@ async function handleConversationStep(state, step) {
|
|
|
23779
24451
|
}
|
|
23780
24452
|
const toolCall = step.message;
|
|
23781
24453
|
const callId = typeof toolCall?.callId === "string" ? toolCall.callId : `conversation-tool:${state.activeToolSpans.size}`;
|
|
23782
|
-
const toolState = await
|
|
24454
|
+
const toolState = await startToolSpan2(state, {
|
|
23783
24455
|
args: extractToolArgs(toolCall),
|
|
23784
24456
|
callId,
|
|
23785
24457
|
name: extractToolName(toolCall),
|
|
@@ -23810,7 +24482,7 @@ function handleStepUpdate(state, step) {
|
|
|
23810
24482
|
state.stepText.push(step.message.text);
|
|
23811
24483
|
}
|
|
23812
24484
|
}
|
|
23813
|
-
async function
|
|
24485
|
+
async function startToolSpan2(state, args) {
|
|
23814
24486
|
const name = args.name || "unknown";
|
|
23815
24487
|
const metadata = {
|
|
23816
24488
|
"cursor_sdk.tool.status": args.status,
|
|
@@ -24097,10 +24769,10 @@ function safeLog3(span, event) {
|
|
|
24097
24769
|
try {
|
|
24098
24770
|
span.log(event);
|
|
24099
24771
|
} catch (error) {
|
|
24100
|
-
|
|
24772
|
+
logInstrumentationError4("Cursor SDK span log", error);
|
|
24101
24773
|
}
|
|
24102
24774
|
}
|
|
24103
|
-
function
|
|
24775
|
+
function logInstrumentationError4(context, error) {
|
|
24104
24776
|
debugLogger.error(`Error processing ${context}:`, error);
|
|
24105
24777
|
}
|
|
24106
24778
|
function cleanMetrics2(metrics) {
|
|
@@ -24562,6 +25234,328 @@ var OpenAIAgentsPlugin = class extends BasePlugin {
|
|
|
24562
25234
|
}
|
|
24563
25235
|
};
|
|
24564
25236
|
|
|
25237
|
+
// src/instrumentation/plugins/google-generative-ai-plugin.ts
|
|
25238
|
+
var GENERATION_CONFIG_KEYS = [
|
|
25239
|
+
"temperature",
|
|
25240
|
+
"topP",
|
|
25241
|
+
"topK",
|
|
25242
|
+
"candidateCount",
|
|
25243
|
+
"maxOutputTokens",
|
|
25244
|
+
"stopSequences",
|
|
25245
|
+
"responseMimeType",
|
|
25246
|
+
"responseSchema",
|
|
25247
|
+
"presencePenalty",
|
|
25248
|
+
"frequencyPenalty",
|
|
25249
|
+
"responseLogprobs",
|
|
25250
|
+
"logprobs",
|
|
25251
|
+
"thinkingConfig"
|
|
25252
|
+
];
|
|
25253
|
+
var GoogleGenerativeAIPlugin = class extends BasePlugin {
|
|
25254
|
+
onEnable() {
|
|
25255
|
+
this.unsubscribers.push(
|
|
25256
|
+
interceptCall(
|
|
25257
|
+
googleGenerativeAIChannels.generateContent,
|
|
25258
|
+
"generateContent"
|
|
25259
|
+
),
|
|
25260
|
+
interceptCall(
|
|
25261
|
+
googleGenerativeAIChannels.generateContentStream,
|
|
25262
|
+
"generateContentStream"
|
|
25263
|
+
),
|
|
25264
|
+
interceptCall(googleGenerativeAIChannels.sendMessage, "sendMessage"),
|
|
25265
|
+
interceptCall(
|
|
25266
|
+
googleGenerativeAIChannels.sendMessageStream,
|
|
25267
|
+
"sendMessageStream"
|
|
25268
|
+
),
|
|
25269
|
+
interceptCall(googleGenerativeAIChannels.embedContent, "embedContent"),
|
|
25270
|
+
interceptCall(
|
|
25271
|
+
googleGenerativeAIChannels.batchEmbedContents,
|
|
25272
|
+
"batchEmbedContents"
|
|
25273
|
+
)
|
|
25274
|
+
);
|
|
25275
|
+
}
|
|
25276
|
+
onDisable() {
|
|
25277
|
+
this.unsubscribers = unsubscribeAll(this.unsubscribers);
|
|
25278
|
+
}
|
|
25279
|
+
};
|
|
25280
|
+
function interceptCall(channel, operation) {
|
|
25281
|
+
return channel.intercept((target, thisArg, args) => {
|
|
25282
|
+
const invokeTarget = () => Reflect.apply(target, thisArg, args);
|
|
25283
|
+
if (isAutoInstrumentationSuppressed()) return invokeTarget();
|
|
25284
|
+
const self = thisArg;
|
|
25285
|
+
const chat = operation.startsWith("sendMessage");
|
|
25286
|
+
const embedding = operation === "embedContent" || operation === "batchEmbedContents";
|
|
25287
|
+
const start = getCurrentUnixTimestamp();
|
|
25288
|
+
let span;
|
|
25289
|
+
try {
|
|
25290
|
+
span = startSpan(
|
|
25291
|
+
withSpanInstrumentationName(
|
|
25292
|
+
{
|
|
25293
|
+
name: embedding ? operation === "embedContent" ? "embed_content" : "batch_embed_contents" : "generate_content",
|
|
25294
|
+
spanAttributes: { type: "llm" /* LLM */ },
|
|
25295
|
+
event: extractInput(self, args[0], operation)
|
|
25296
|
+
},
|
|
25297
|
+
INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI
|
|
25298
|
+
)
|
|
25299
|
+
);
|
|
25300
|
+
} catch (error) {
|
|
25301
|
+
debugLogger.error("Error starting Google Generative AI span:", error);
|
|
25302
|
+
return invokeTarget();
|
|
25303
|
+
}
|
|
25304
|
+
let ended = false;
|
|
25305
|
+
const finish = (log2) => {
|
|
25306
|
+
if (ended) return;
|
|
25307
|
+
ended = true;
|
|
25308
|
+
try {
|
|
25309
|
+
log2();
|
|
25310
|
+
} catch (error) {
|
|
25311
|
+
debugLogger.error("Error logging Google Generative AI span:", error);
|
|
25312
|
+
}
|
|
25313
|
+
try {
|
|
25314
|
+
span.end();
|
|
25315
|
+
} catch (error) {
|
|
25316
|
+
debugLogger.error("Error ending Google Generative AI span:", error);
|
|
25317
|
+
}
|
|
25318
|
+
};
|
|
25319
|
+
if (chat) {
|
|
25320
|
+
try {
|
|
25321
|
+
void self._sendPromise.then(
|
|
25322
|
+
() => {
|
|
25323
|
+
try {
|
|
25324
|
+
span.log(extractInput(self, args[0], operation));
|
|
25325
|
+
} catch (error) {
|
|
25326
|
+
debugLogger.error("Error capturing Google chat history:", error);
|
|
25327
|
+
}
|
|
25328
|
+
},
|
|
25329
|
+
() => {
|
|
25330
|
+
}
|
|
25331
|
+
);
|
|
25332
|
+
} catch (error) {
|
|
25333
|
+
debugLogger.error("Error observing Google chat history:", error);
|
|
25334
|
+
}
|
|
25335
|
+
}
|
|
25336
|
+
let result;
|
|
25337
|
+
try {
|
|
25338
|
+
result = withCurrent(
|
|
25339
|
+
span,
|
|
25340
|
+
() => runWithAutoInstrumentationSuppressed(invokeTarget)
|
|
25341
|
+
);
|
|
25342
|
+
} catch (error) {
|
|
25343
|
+
finish(() => span.log({ error }));
|
|
25344
|
+
throw error;
|
|
25345
|
+
}
|
|
25346
|
+
void Promise.resolve(result).then(
|
|
25347
|
+
(value) => {
|
|
25348
|
+
try {
|
|
25349
|
+
if ("stream" in value) {
|
|
25350
|
+
let firstToken = false;
|
|
25351
|
+
const partial = { candidates: [] };
|
|
25352
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
25353
|
+
patchStreamIfNeeded(value.stream, {
|
|
25354
|
+
aroundNext: (callback) => withCurrent(span, callback),
|
|
25355
|
+
onChunk: (chunk) => {
|
|
25356
|
+
for (const candidate of chunk.candidates ?? []) {
|
|
25357
|
+
const index = candidate.index ?? 0;
|
|
25358
|
+
const previous = candidates.get(index);
|
|
25359
|
+
const parts = [...previous?.content?.parts ?? []];
|
|
25360
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
25361
|
+
const last = parts[parts.length - 1];
|
|
25362
|
+
if (part.text !== void 0 && last?.text !== void 0) {
|
|
25363
|
+
parts[parts.length - 1] = {
|
|
25364
|
+
...last,
|
|
25365
|
+
text: last.text + part.text
|
|
25366
|
+
};
|
|
25367
|
+
} else parts.push(part);
|
|
25368
|
+
}
|
|
25369
|
+
candidates.set(index, {
|
|
25370
|
+
...previous,
|
|
25371
|
+
...candidate,
|
|
25372
|
+
content: {
|
|
25373
|
+
role: candidate.content?.role ?? previous?.content?.role ?? "model",
|
|
25374
|
+
parts
|
|
25375
|
+
}
|
|
25376
|
+
});
|
|
25377
|
+
}
|
|
25378
|
+
partial.candidates = Array.from(candidates.values());
|
|
25379
|
+
if (chunk.usageMetadata)
|
|
25380
|
+
partial.usageMetadata = chunk.usageMetadata;
|
|
25381
|
+
if (!firstToken && chunk.candidates?.some(
|
|
25382
|
+
(candidate) => candidate.content?.parts.some(
|
|
25383
|
+
(part) => part.text !== void 0 ? part.text.length > 0 : Object.keys(part).length > 0
|
|
25384
|
+
)
|
|
25385
|
+
)) {
|
|
25386
|
+
firstToken = true;
|
|
25387
|
+
span.log({
|
|
25388
|
+
metrics: {
|
|
25389
|
+
time_to_first_token: getCurrentUnixTimestamp() - start
|
|
25390
|
+
}
|
|
25391
|
+
});
|
|
25392
|
+
}
|
|
25393
|
+
},
|
|
25394
|
+
onComplete: () => {
|
|
25395
|
+
},
|
|
25396
|
+
onError: (error) => finish(() => {
|
|
25397
|
+
logResponse(span, partial);
|
|
25398
|
+
span.log({ error });
|
|
25399
|
+
}),
|
|
25400
|
+
onCancel: () => finish(() => logResponse(span, partial))
|
|
25401
|
+
});
|
|
25402
|
+
void value.response.then(
|
|
25403
|
+
(response) => finish(() => logResponse(span, response)),
|
|
25404
|
+
(error) => finish(() => {
|
|
25405
|
+
logResponse(span, partial);
|
|
25406
|
+
span.log({ error });
|
|
25407
|
+
})
|
|
25408
|
+
);
|
|
25409
|
+
} else if ("response" in value) {
|
|
25410
|
+
finish(() => logResponse(span, value.response));
|
|
25411
|
+
} else {
|
|
25412
|
+
const metrics = {};
|
|
25413
|
+
const promptTokens = value.usageMetadata?.promptTokenCount;
|
|
25414
|
+
if (typeof promptTokens === "number" && Number.isFinite(promptTokens) && promptTokens >= 0) {
|
|
25415
|
+
metrics.prompt_tokens = promptTokens;
|
|
25416
|
+
metrics.tokens = promptTokens;
|
|
25417
|
+
}
|
|
25418
|
+
for (const detail of value.usageMetadata?.promptTokenDetails ?? []) {
|
|
25419
|
+
if (detail.modality === "AUDIO" && typeof detail.tokenCount === "number" && Number.isFinite(detail.tokenCount) && detail.tokenCount >= 0) {
|
|
25420
|
+
metrics.prompt_audio_tokens = (metrics.prompt_audio_tokens ?? 0) + detail.tokenCount;
|
|
25421
|
+
}
|
|
25422
|
+
}
|
|
25423
|
+
finish(
|
|
25424
|
+
() => span.log({
|
|
25425
|
+
metrics,
|
|
25426
|
+
output: {
|
|
25427
|
+
count: value.embeddings?.length ?? (value.embedding ? 1 : 0)
|
|
25428
|
+
}
|
|
25429
|
+
})
|
|
25430
|
+
);
|
|
25431
|
+
}
|
|
25432
|
+
} catch (error) {
|
|
25433
|
+
debugLogger.error(
|
|
25434
|
+
"Error observing Google Generative AI result:",
|
|
25435
|
+
error
|
|
25436
|
+
);
|
|
25437
|
+
finish(() => {
|
|
25438
|
+
});
|
|
25439
|
+
}
|
|
25440
|
+
},
|
|
25441
|
+
(error) => finish(() => span.log({ error }))
|
|
25442
|
+
);
|
|
25443
|
+
return result;
|
|
25444
|
+
});
|
|
25445
|
+
}
|
|
25446
|
+
function normalizeContent(message) {
|
|
25447
|
+
const parts = (typeof message === "string" ? [message] : message).map(
|
|
25448
|
+
(part) => typeof part === "string" ? { text: part } : part
|
|
25449
|
+
);
|
|
25450
|
+
return {
|
|
25451
|
+
role: parts.some((part) => part.functionResponse) ? "function" : "user",
|
|
25452
|
+
parts
|
|
25453
|
+
};
|
|
25454
|
+
}
|
|
25455
|
+
function extractInput(self, request, operation) {
|
|
25456
|
+
const model = self.model.replace(/^models\//, "");
|
|
25457
|
+
if (operation === "embedContent" || operation === "batchEmbedContents") {
|
|
25458
|
+
const requests = operation === "batchEmbedContents" ? request.requests : [
|
|
25459
|
+
typeof request === "string" || Array.isArray(request) ? { content: normalizeContent(request) } : request
|
|
25460
|
+
];
|
|
25461
|
+
const dimensions = requests[0]?.outputDimensionality;
|
|
25462
|
+
return {
|
|
25463
|
+
input: {
|
|
25464
|
+
inputs: convertAttachments(requests).map((item) => ({
|
|
25465
|
+
content: item.content.parts.length === 1 && item.content.parts[0].text !== void 0 ? item.content.parts[0].text : item.content.parts.map((part) => {
|
|
25466
|
+
if (part.text !== void 0)
|
|
25467
|
+
return { type: "text", text: part.text };
|
|
25468
|
+
const mimeType = part.inlineData?.mimeType ?? part.fileData?.mimeType;
|
|
25469
|
+
const data = part.inlineData ? typeof part.inlineData.data === "string" ? `data:${mimeType};base64,${part.inlineData.data}` : part.inlineData.data : part.fileData?.fileUri;
|
|
25470
|
+
return mimeType?.startsWith("image/") ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { file_data: data } };
|
|
25471
|
+
})
|
|
25472
|
+
})),
|
|
25473
|
+
...dimensions !== void 0 && requests.every((item) => item.outputDimensionality === dimensions) ? { output_dimensions: dimensions } : {}
|
|
25474
|
+
},
|
|
25475
|
+
metadata: { model, provider: "google" }
|
|
25476
|
+
};
|
|
25477
|
+
}
|
|
25478
|
+
const chat = operation.startsWith("sendMessage");
|
|
25479
|
+
const config = chat ? self.params ?? {} : self;
|
|
25480
|
+
const params = typeof request === "string" || Array.isArray(request) ? { contents: [normalizeContent(request)] } : request;
|
|
25481
|
+
const system = params.systemInstruction ?? config.systemInstruction;
|
|
25482
|
+
const systemContent = typeof system === "string" ? { role: "system", parts: [{ text: system }] } : system && "parts" in system ? { ...system, role: "system" } : system ? { role: "system", parts: [system] } : void 0;
|
|
25483
|
+
const contents = [
|
|
25484
|
+
...systemContent ? [systemContent] : [],
|
|
25485
|
+
...chat ? self._history : [],
|
|
25486
|
+
...params.contents
|
|
25487
|
+
];
|
|
25488
|
+
const metadata = { model, provider: "google" };
|
|
25489
|
+
const generation = params.generationConfig ?? config.generationConfig;
|
|
25490
|
+
for (const key of GENERATION_CONFIG_KEYS) {
|
|
25491
|
+
if (generation && Object.hasOwn(generation, key))
|
|
25492
|
+
metadata[key] = generation[key];
|
|
25493
|
+
}
|
|
25494
|
+
for (const key of ["tools", "toolConfig", "safetySettings"]) {
|
|
25495
|
+
const value = params[key] ?? config[key];
|
|
25496
|
+
if (value !== void 0) metadata[key] = value;
|
|
25497
|
+
}
|
|
25498
|
+
const cached = params.cachedContent ?? config.cachedContent;
|
|
25499
|
+
if (cached)
|
|
25500
|
+
metadata.cachedContent = typeof cached === "string" ? cached : cached.name;
|
|
25501
|
+
return { input: convertAttachments({ model, contents }), metadata };
|
|
25502
|
+
}
|
|
25503
|
+
function convertAttachments(value) {
|
|
25504
|
+
const convert = (node) => {
|
|
25505
|
+
if (Array.isArray(node)) return node.map(convert);
|
|
25506
|
+
if (!isObject(node)) return node;
|
|
25507
|
+
if (isObject(node.inlineData)) {
|
|
25508
|
+
const { data, mimeType } = node.inlineData;
|
|
25509
|
+
const processed = processInputAttachments({
|
|
25510
|
+
type: "file",
|
|
25511
|
+
file: { file_data: `data:${mimeType};base64,${data}` }
|
|
25512
|
+
});
|
|
25513
|
+
if (typeof processed.file.file_data === "string")
|
|
25514
|
+
throw new Error("Unable to convert Google inline data");
|
|
25515
|
+
return {
|
|
25516
|
+
...node,
|
|
25517
|
+
inlineData: { ...node.inlineData, data: processed.file.file_data }
|
|
25518
|
+
};
|
|
25519
|
+
}
|
|
25520
|
+
return Object.fromEntries(
|
|
25521
|
+
Object.entries(node).map(([key, item]) => [key, convert(item)])
|
|
25522
|
+
);
|
|
25523
|
+
};
|
|
25524
|
+
try {
|
|
25525
|
+
return convert(value);
|
|
25526
|
+
} catch (error) {
|
|
25527
|
+
debugLogger.error(
|
|
25528
|
+
"Error converting Google Generative AI attachments:",
|
|
25529
|
+
error
|
|
25530
|
+
);
|
|
25531
|
+
return value;
|
|
25532
|
+
}
|
|
25533
|
+
}
|
|
25534
|
+
function logResponse(span, response) {
|
|
25535
|
+
const usage = response.usageMetadata;
|
|
25536
|
+
const metrics = {};
|
|
25537
|
+
if (usage) {
|
|
25538
|
+
if (usage.promptTokenCount !== void 0)
|
|
25539
|
+
metrics.prompt_tokens = usage.promptTokenCount;
|
|
25540
|
+
if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0)
|
|
25541
|
+
metrics.completion_tokens = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
|
|
25542
|
+
if (usage.totalTokenCount !== void 0)
|
|
25543
|
+
metrics.tokens = usage.totalTokenCount;
|
|
25544
|
+
if (usage.cachedContentTokenCount !== void 0)
|
|
25545
|
+
metrics.prompt_cached_tokens = usage.cachedContentTokenCount;
|
|
25546
|
+
if (usage.thoughtsTokenCount !== void 0)
|
|
25547
|
+
metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
|
|
25548
|
+
}
|
|
25549
|
+
span.log({
|
|
25550
|
+
output: convertAttachments({
|
|
25551
|
+
candidates: response.candidates,
|
|
25552
|
+
promptFeedback: response.promptFeedback
|
|
25553
|
+
}),
|
|
25554
|
+
metrics,
|
|
25555
|
+
...response.modelVersion ? { metadata: { model: response.modelVersion } } : {}
|
|
25556
|
+
});
|
|
25557
|
+
}
|
|
25558
|
+
|
|
24565
25559
|
// src/instrumentation/plugins/google-genai-plugin.ts
|
|
24566
25560
|
var GOOGLE_GENAI_INTERNAL_CONTEXT = {
|
|
24567
25561
|
caller_filename: "<node-internal>",
|
|
@@ -24702,13 +25696,45 @@ var GoogleGenAIPlugin = class extends BasePlugin {
|
|
|
24702
25696
|
subscribeToEmbedContentChannel() {
|
|
24703
25697
|
const tracingChannel = googleGenAIChannels.embedContent.tracingChannel();
|
|
24704
25698
|
const states = /* @__PURE__ */ new WeakMap();
|
|
25699
|
+
const embeddingSpans = /* @__PURE__ */ new WeakSet();
|
|
25700
|
+
this.unsubscribers.push(
|
|
25701
|
+
googleGenAIChannels.httpResponseJson.intercept(
|
|
25702
|
+
(target, thisArg, args) => {
|
|
25703
|
+
const span = currentSpan();
|
|
25704
|
+
const result = Reflect.apply(target, thisArg, args);
|
|
25705
|
+
if (embeddingSpans.has(span)) {
|
|
25706
|
+
void Promise.resolve(result).then(
|
|
25707
|
+
(response) => {
|
|
25708
|
+
try {
|
|
25709
|
+
const metrics = cleanMetrics3(
|
|
25710
|
+
extractEmbedContentMetrics(response)
|
|
25711
|
+
);
|
|
25712
|
+
if (embeddingSpans.has(span) && Object.keys(metrics).length > 0) {
|
|
25713
|
+
span.log({ metrics });
|
|
25714
|
+
}
|
|
25715
|
+
} catch (error) {
|
|
25716
|
+
debugLogger.error(
|
|
25717
|
+
"Error reading Google GenAI embedding usage:",
|
|
25718
|
+
error
|
|
25719
|
+
);
|
|
25720
|
+
}
|
|
25721
|
+
},
|
|
25722
|
+
() => {
|
|
25723
|
+
}
|
|
25724
|
+
// The embedding channel handles the original rejection.
|
|
25725
|
+
);
|
|
25726
|
+
}
|
|
25727
|
+
return result;
|
|
25728
|
+
}
|
|
25729
|
+
)
|
|
25730
|
+
);
|
|
24705
25731
|
const unbindCurrentSpanStore = bindCurrentSpanStoreToStart2(
|
|
24706
25732
|
tracingChannel,
|
|
24707
25733
|
states,
|
|
24708
25734
|
(event) => {
|
|
24709
25735
|
const params = event.arguments[0];
|
|
24710
25736
|
const input = serializeEmbedContentInput(params);
|
|
24711
|
-
const metadata =
|
|
25737
|
+
const metadata = { provider: "google", model: params.model };
|
|
24712
25738
|
const span = startSpan(
|
|
24713
25739
|
withSpanInstrumentationName(
|
|
24714
25740
|
{
|
|
@@ -24721,6 +25747,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
|
|
|
24721
25747
|
INSTRUMENTATION_NAMES.GOOGLE_GENAI
|
|
24722
25748
|
)
|
|
24723
25749
|
);
|
|
25750
|
+
embeddingSpans.add(span);
|
|
24724
25751
|
return {
|
|
24725
25752
|
span,
|
|
24726
25753
|
startTime: getCurrentUnixTimestamp()
|
|
@@ -24732,7 +25759,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
|
|
|
24732
25759
|
ensureSpanState(states, event, () => {
|
|
24733
25760
|
const params = event.arguments[0];
|
|
24734
25761
|
const input = serializeEmbedContentInput(params);
|
|
24735
|
-
const metadata =
|
|
25762
|
+
const metadata = { provider: "google", model: params.model };
|
|
24736
25763
|
const span = startSpan(
|
|
24737
25764
|
withSpanInstrumentationName(
|
|
24738
25765
|
{
|
|
@@ -24745,6 +25772,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
|
|
|
24745
25772
|
INSTRUMENTATION_NAMES.GOOGLE_GENAI
|
|
24746
25773
|
)
|
|
24747
25774
|
);
|
|
25775
|
+
embeddingSpans.add(span);
|
|
24748
25776
|
return {
|
|
24749
25777
|
span,
|
|
24750
25778
|
startTime: getCurrentUnixTimestamp()
|
|
@@ -24757,20 +25785,28 @@ var GoogleGenAIPlugin = class extends BasePlugin {
|
|
|
24757
25785
|
return;
|
|
24758
25786
|
}
|
|
24759
25787
|
try {
|
|
24760
|
-
const output = summarizeEmbedContentOutput(event.result);
|
|
24761
25788
|
spanState.span.log({
|
|
24762
|
-
|
|
25789
|
+
output: summarizeEmbedContentOutput(event.result),
|
|
24763
25790
|
metrics: cleanMetrics3(
|
|
24764
25791
|
extractEmbedContentMetrics(event.result, spanState.startTime)
|
|
24765
25792
|
)
|
|
24766
25793
|
});
|
|
24767
25794
|
} finally {
|
|
25795
|
+
embeddingSpans.delete(spanState.span);
|
|
24768
25796
|
spanState.span.end();
|
|
24769
25797
|
states.delete(event);
|
|
24770
25798
|
}
|
|
24771
25799
|
},
|
|
24772
25800
|
error: (event) => {
|
|
24773
|
-
|
|
25801
|
+
const spanState = states.get(event);
|
|
25802
|
+
if (!spanState) return;
|
|
25803
|
+
try {
|
|
25804
|
+
spanState.span.log({ error: event.error, output: { count: 0 } });
|
|
25805
|
+
} finally {
|
|
25806
|
+
embeddingSpans.delete(spanState.span);
|
|
25807
|
+
spanState.span.end();
|
|
25808
|
+
states.delete(event);
|
|
25809
|
+
}
|
|
24774
25810
|
}
|
|
24775
25811
|
};
|
|
24776
25812
|
tracingChannel.subscribe(handlers);
|
|
@@ -25005,15 +26041,53 @@ function serializeGenerateContentInput(params) {
|
|
|
25005
26041
|
return input;
|
|
25006
26042
|
}
|
|
25007
26043
|
function serializeEmbedContentInput(params) {
|
|
26044
|
+
let contents = Array.isArray(params.contents) ? params.contents : [params.contents];
|
|
26045
|
+
if (params.model.includes("gemini-embedding-2") && contents.length > 0 && contents.every(
|
|
26046
|
+
(content) => typeof content === "string" || !Array.isArray(content) && !("parts" in content)
|
|
26047
|
+
)) {
|
|
26048
|
+
contents = [contents];
|
|
26049
|
+
}
|
|
25008
26050
|
const input = {
|
|
25009
|
-
|
|
25010
|
-
|
|
26051
|
+
inputs: contents.map((content) => {
|
|
26052
|
+
const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content : "parts" in content ? content.parts : [content];
|
|
26053
|
+
const normalized = parts.flatMap((part) => {
|
|
26054
|
+
if (typeof part === "string") return [{ type: "text", text: part }];
|
|
26055
|
+
if (part.text !== void 0) return [{ type: "text", text: part.text }];
|
|
26056
|
+
const media = part.inlineData ?? part.fileData;
|
|
26057
|
+
if (!media) return [];
|
|
26058
|
+
const data = "data" in media ? `data:${media.mimeType};base64,${typeof media.data === "string" ? media.data : uint8ArrayToBase64(media.data)}` : media.fileUri;
|
|
26059
|
+
return media.mimeType?.startsWith("image/") ? [{ type: "image_url", image_url: { url: data } }] : [
|
|
26060
|
+
{
|
|
26061
|
+
type: "file",
|
|
26062
|
+
file: {
|
|
26063
|
+
file_data: data,
|
|
26064
|
+
..."displayName" in media && media.displayName ? { filename: media.displayName } : {}
|
|
26065
|
+
}
|
|
26066
|
+
}
|
|
26067
|
+
];
|
|
26068
|
+
});
|
|
26069
|
+
return {
|
|
26070
|
+
content: normalized.length === 1 && normalized[0].type === "text" ? normalized[0].text : normalized
|
|
26071
|
+
};
|
|
26072
|
+
}),
|
|
26073
|
+
...params.config?.outputDimensionality !== void 0 ? { output_dimensions: params.config.outputDimensionality } : {}
|
|
25011
26074
|
};
|
|
25012
|
-
|
|
25013
|
-
|
|
25014
|
-
|
|
26075
|
+
try {
|
|
26076
|
+
const processed = processInputAttachments(input);
|
|
26077
|
+
const hasInlineMedia = processed.inputs.some(
|
|
26078
|
+
({ content }) => Array.isArray(content) && content.some((part) => {
|
|
26079
|
+
const data = part.type === "image_url" ? part.image_url.url : part.type === "file" ? part.file.file_data : void 0;
|
|
26080
|
+
return typeof data === "string" && data.startsWith("data:");
|
|
26081
|
+
})
|
|
26082
|
+
);
|
|
26083
|
+
return hasInlineMedia ? input : processed;
|
|
26084
|
+
} catch (error) {
|
|
26085
|
+
debugLogger.error(
|
|
26086
|
+
"Error processing Google GenAI embedding attachments:",
|
|
26087
|
+
error
|
|
26088
|
+
);
|
|
26089
|
+
return input;
|
|
25015
26090
|
}
|
|
25016
|
-
return input;
|
|
25017
26091
|
}
|
|
25018
26092
|
function serializeInteractionInput(params) {
|
|
25019
26093
|
const input = {
|
|
@@ -25201,19 +26275,6 @@ function extractGenerateContentMetadata(params) {
|
|
|
25201
26275
|
}
|
|
25202
26276
|
return metadata;
|
|
25203
26277
|
}
|
|
25204
|
-
function extractEmbedContentMetadata(params) {
|
|
25205
|
-
const metadata = {};
|
|
25206
|
-
if (params.model) {
|
|
25207
|
-
metadata.model = params.model;
|
|
25208
|
-
}
|
|
25209
|
-
const config = params.config ? tryToDict(params.config) : null;
|
|
25210
|
-
if (config) {
|
|
25211
|
-
Object.keys(config).forEach((key) => {
|
|
25212
|
-
metadata[key] = config[key];
|
|
25213
|
-
});
|
|
25214
|
-
}
|
|
25215
|
-
return metadata;
|
|
25216
|
-
}
|
|
25217
26278
|
function extractGenerateContentMetrics(response, startTime) {
|
|
25218
26279
|
const metrics = {};
|
|
25219
26280
|
if (startTime !== void 0) {
|
|
@@ -25233,15 +26294,23 @@ function extractEmbedContentMetrics(response, startTime) {
|
|
|
25233
26294
|
const end = getCurrentUnixTimestamp();
|
|
25234
26295
|
metrics.start = startTime;
|
|
25235
26296
|
metrics.end = end;
|
|
25236
|
-
metrics.duration = end - startTime;
|
|
25237
|
-
}
|
|
25238
|
-
if (response?.usageMetadata) {
|
|
25239
|
-
populateUsageMetrics(metrics, response.usageMetadata);
|
|
25240
26297
|
}
|
|
25241
26298
|
const embeddingTokenCount = extractEmbedPromptTokenCount(response);
|
|
25242
26299
|
if (embeddingTokenCount !== void 0) {
|
|
25243
26300
|
metrics.prompt_tokens = embeddingTokenCount;
|
|
25244
|
-
|
|
26301
|
+
}
|
|
26302
|
+
const totalTokens = response?.usageMetadata?.totalTokenCount ?? embeddingTokenCount;
|
|
26303
|
+
if (totalTokens !== void 0) {
|
|
26304
|
+
metrics.tokens = totalTokens;
|
|
26305
|
+
}
|
|
26306
|
+
const audioTokens = (response?.usageMetadata?.promptTokenDetails ?? response?.usageMetadata?.promptTokensDetails)?.filter(
|
|
26307
|
+
(detail) => detail.modality === "AUDIO" && detail.tokenCount !== void 0
|
|
26308
|
+
);
|
|
26309
|
+
if (audioTokens?.length) {
|
|
26310
|
+
metrics.prompt_audio_tokens = audioTokens.reduce(
|
|
26311
|
+
(sum, detail) => sum + (detail.tokenCount ?? 0),
|
|
26312
|
+
0
|
|
26313
|
+
);
|
|
25245
26314
|
}
|
|
25246
26315
|
return metrics;
|
|
25247
26316
|
}
|
|
@@ -25280,41 +26349,25 @@ function extractEmbedPromptTokenCount(response) {
|
|
|
25280
26349
|
if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
|
|
25281
26350
|
return usagePromptTokens;
|
|
25282
26351
|
}
|
|
25283
|
-
const usageTotalTokens = response.usageMetadata?.totalTokenCount;
|
|
25284
|
-
if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
|
|
25285
|
-
return usageTotalTokens;
|
|
25286
|
-
}
|
|
25287
26352
|
const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
|
|
25288
26353
|
if (embeddings.length === 0) {
|
|
25289
26354
|
return void 0;
|
|
25290
26355
|
}
|
|
25291
26356
|
let total = 0;
|
|
25292
|
-
let sawAny = false;
|
|
25293
26357
|
for (const embedding of embeddings) {
|
|
25294
26358
|
const embeddingStats = tryToDict(tryToDict(embedding)?.statistics);
|
|
25295
26359
|
const tokenCount2 = embeddingStats?.tokenCount;
|
|
25296
26360
|
if (typeof tokenCount2 === "number" && Number.isFinite(tokenCount2)) {
|
|
25297
26361
|
total += tokenCount2;
|
|
25298
|
-
|
|
26362
|
+
} else {
|
|
26363
|
+
return void 0;
|
|
25299
26364
|
}
|
|
25300
26365
|
}
|
|
25301
|
-
return
|
|
26366
|
+
return total;
|
|
25302
26367
|
}
|
|
25303
26368
|
function summarizeEmbedContentOutput(response) {
|
|
25304
|
-
if (!response) {
|
|
25305
|
-
return void 0;
|
|
25306
|
-
}
|
|
25307
|
-
const embeddings = Array.isArray(response.embeddings) ? response.embeddings : response.embedding ? [response.embedding] : [];
|
|
25308
|
-
if (embeddings.length === 0) {
|
|
25309
|
-
return void 0;
|
|
25310
|
-
}
|
|
25311
|
-
const firstValues = embeddings[0]?.values;
|
|
25312
|
-
if (!Array.isArray(firstValues)) {
|
|
25313
|
-
return void 0;
|
|
25314
|
-
}
|
|
25315
26369
|
return {
|
|
25316
|
-
|
|
25317
|
-
embedding_length: firstValues.length
|
|
26370
|
+
count: Array.isArray(response?.embeddings) ? response.embeddings.length : response?.embedding ? 1 : 0
|
|
25318
26371
|
};
|
|
25319
26372
|
}
|
|
25320
26373
|
function populateUsageMetrics(metrics, usage) {
|
|
@@ -26113,7 +27166,7 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
|
|
|
26113
27166
|
getTask(event)
|
|
26114
27167
|
),
|
|
26115
27168
|
extractInput: (args, event) => ({
|
|
26116
|
-
input:
|
|
27169
|
+
input: extractInput2(
|
|
26117
27170
|
getTask(event),
|
|
26118
27171
|
args
|
|
26119
27172
|
),
|
|
@@ -26203,7 +27256,7 @@ function modelIdentifier(pipeline) {
|
|
|
26203
27256
|
}
|
|
26204
27257
|
return void 0;
|
|
26205
27258
|
}
|
|
26206
|
-
function
|
|
27259
|
+
function extractInput2(task, args) {
|
|
26207
27260
|
switch (task) {
|
|
26208
27261
|
case "feature-extraction":
|
|
26209
27262
|
return args[0];
|
|
@@ -28765,6 +29818,363 @@ function aggregateMistralStreamChunks(chunks) {
|
|
|
28765
29818
|
};
|
|
28766
29819
|
}
|
|
28767
29820
|
|
|
29821
|
+
// src/instrumentation/plugins/langgraph-sdk-plugin.ts
|
|
29822
|
+
var LangGraphSDKPlugin = class extends BasePlugin {
|
|
29823
|
+
onEnable() {
|
|
29824
|
+
this.unsubscribers.push(
|
|
29825
|
+
langGraphSDKChannels.wait.intercept(
|
|
29826
|
+
(target, self, args) => instrumentRun("wait", args, () => Reflect.apply(target, self, args))
|
|
29827
|
+
),
|
|
29828
|
+
langGraphSDKChannels.stream.intercept(
|
|
29829
|
+
(target, self, args) => instrumentRun("stream", args, () => Reflect.apply(target, self, args))
|
|
29830
|
+
)
|
|
29831
|
+
);
|
|
29832
|
+
}
|
|
29833
|
+
onDisable() {
|
|
29834
|
+
this.unsubscribers = unsubscribeAll(this.unsubscribers);
|
|
29835
|
+
}
|
|
29836
|
+
};
|
|
29837
|
+
function normalizeMessage(value) {
|
|
29838
|
+
if (!isObject(value)) return value;
|
|
29839
|
+
const role = value.role ?? (value.type === "human" ? "user" : value.type === "ai" || value.type === "AIMessageChunk" ? "assistant" : value.type === "system" || value.type === "tool" || value.type === "function" ? value.type : void 0);
|
|
29840
|
+
if (typeof role !== "string") return value;
|
|
29841
|
+
const message = {
|
|
29842
|
+
role,
|
|
29843
|
+
content: value.content ?? ""
|
|
29844
|
+
};
|
|
29845
|
+
for (const key of ["name", "tool_call_id", "refusal"]) {
|
|
29846
|
+
if (value[key] !== void 0) message[key] = value[key];
|
|
29847
|
+
}
|
|
29848
|
+
const additional = isObject(value.additional_kwargs) ? value.additional_kwargs : {};
|
|
29849
|
+
const toolCalls = Array.isArray(value.tool_calls) && value.tool_calls.length ? value.tool_calls : additional.tool_calls;
|
|
29850
|
+
if (Array.isArray(toolCalls) && toolCalls.length > 0) {
|
|
29851
|
+
message.tool_calls = toolCalls.map((call) => {
|
|
29852
|
+
if (!isObject(call)) return call;
|
|
29853
|
+
if (isObject(call.function)) return call;
|
|
29854
|
+
return {
|
|
29855
|
+
id: call.id,
|
|
29856
|
+
type: "function",
|
|
29857
|
+
function: {
|
|
29858
|
+
name: call.name,
|
|
29859
|
+
arguments: typeof call.args === "string" ? call.args : JSON.stringify(call.args ?? {})
|
|
29860
|
+
}
|
|
29861
|
+
};
|
|
29862
|
+
});
|
|
29863
|
+
}
|
|
29864
|
+
if (Array.isArray(value.invalid_tool_calls) && value.invalid_tool_calls.length > 0)
|
|
29865
|
+
message.invalid_tool_calls = value.invalid_tool_calls;
|
|
29866
|
+
if (message.refusal === void 0 && additional.refusal !== void 0)
|
|
29867
|
+
message.refusal = additional.refusal;
|
|
29868
|
+
return message;
|
|
29869
|
+
}
|
|
29870
|
+
function normalizeRunError(value) {
|
|
29871
|
+
let name;
|
|
29872
|
+
let message;
|
|
29873
|
+
if (value instanceof Error) {
|
|
29874
|
+
name = value.name;
|
|
29875
|
+
message = value.message;
|
|
29876
|
+
} else if (isObject(value) && typeof value.error === "string" && typeof value.message === "string") {
|
|
29877
|
+
name = value.error;
|
|
29878
|
+
message = value.message;
|
|
29879
|
+
} else {
|
|
29880
|
+
return value;
|
|
29881
|
+
}
|
|
29882
|
+
for (let depth = 0; depth < 3; depth++) {
|
|
29883
|
+
try {
|
|
29884
|
+
const nested = JSON.parse(
|
|
29885
|
+
message.startsWith(`${name}: `) ? message.slice(name.length + 2) : message
|
|
29886
|
+
);
|
|
29887
|
+
if (!isObject(nested) || typeof nested.error !== "string" || typeof nested.message !== "string")
|
|
29888
|
+
break;
|
|
29889
|
+
name = nested.error;
|
|
29890
|
+
message = nested.message;
|
|
29891
|
+
} catch {
|
|
29892
|
+
break;
|
|
29893
|
+
}
|
|
29894
|
+
}
|
|
29895
|
+
if (value instanceof Error && name === value.name && message === value.message)
|
|
29896
|
+
return value;
|
|
29897
|
+
return Object.assign(new Error(message), { name });
|
|
29898
|
+
}
|
|
29899
|
+
function normalizeState(value) {
|
|
29900
|
+
if (!isObject(value)) return value;
|
|
29901
|
+
return Object.fromEntries(
|
|
29902
|
+
Object.entries(value).map(([key, field]) => {
|
|
29903
|
+
if (key === "messages" && Array.isArray(field))
|
|
29904
|
+
return [key, field.map(normalizeMessage)];
|
|
29905
|
+
if (key === "__error__") {
|
|
29906
|
+
const error = normalizeRunError(field);
|
|
29907
|
+
if (error instanceof Error)
|
|
29908
|
+
return [key, { error: error.name, message: error.message }];
|
|
29909
|
+
}
|
|
29910
|
+
return [key, field];
|
|
29911
|
+
})
|
|
29912
|
+
);
|
|
29913
|
+
}
|
|
29914
|
+
function normalizeRunOutput(value, input) {
|
|
29915
|
+
if (!isObject(value)) return value;
|
|
29916
|
+
if (Array.isArray(value.messages)) {
|
|
29917
|
+
if (value.__interrupt__ !== void 0 || value.__error__ !== void 0)
|
|
29918
|
+
return void 0;
|
|
29919
|
+
const inputMessages = isObject(input) && Array.isArray(input.messages) ? input.messages : [];
|
|
29920
|
+
let inputPrefixLength = 0;
|
|
29921
|
+
while (inputPrefixLength < inputMessages.length) {
|
|
29922
|
+
const previous = inputMessages[inputPrefixLength];
|
|
29923
|
+
const message = value.messages[inputPrefixLength];
|
|
29924
|
+
if (isObject(previous) && isObject(message) && previous.id !== void 0 && message.id !== void 0 && previous.id !== message.id || JSON.stringify(normalizeMessage(previous)) !== JSON.stringify(normalizeMessage(message)))
|
|
29925
|
+
break;
|
|
29926
|
+
inputPrefixLength++;
|
|
29927
|
+
}
|
|
29928
|
+
for (let index = value.messages.length - 1; index >= inputPrefixLength; index--) {
|
|
29929
|
+
const message = value.messages[index];
|
|
29930
|
+
const normalized = normalizeMessage(message);
|
|
29931
|
+
if (!isObject(normalized)) continue;
|
|
29932
|
+
if (normalized.role === "user") return void 0;
|
|
29933
|
+
if (normalized.role !== "assistant") continue;
|
|
29934
|
+
if (inputMessages.some((previous) => {
|
|
29935
|
+
if (!isObject(previous) || !isObject(message)) return false;
|
|
29936
|
+
return previous.id !== void 0 && previous.id === message.id && JSON.stringify(normalizeMessage(previous)) === JSON.stringify(normalized);
|
|
29937
|
+
}))
|
|
29938
|
+
continue;
|
|
29939
|
+
return normalized;
|
|
29940
|
+
}
|
|
29941
|
+
return void 0;
|
|
29942
|
+
}
|
|
29943
|
+
const result = Object.fromEntries(
|
|
29944
|
+
Object.entries(value).filter(
|
|
29945
|
+
([key]) => key !== "__interrupt__" && key !== "__error__"
|
|
29946
|
+
)
|
|
29947
|
+
);
|
|
29948
|
+
return !Object.keys(result).length && (value.__interrupt__ !== void 0 || value.__error__ !== void 0) ? void 0 : result;
|
|
29949
|
+
}
|
|
29950
|
+
function instrumentRun(operation, [threadId, assistantId, options], invoke) {
|
|
29951
|
+
if (isAutoInstrumentationSuppressed()) return invoke();
|
|
29952
|
+
const start = getCurrentUnixTimestamp();
|
|
29953
|
+
let span;
|
|
29954
|
+
try {
|
|
29955
|
+
const metadata = {
|
|
29956
|
+
"langgraph.thread_id": threadId,
|
|
29957
|
+
"langgraph.assistant_id": assistantId
|
|
29958
|
+
};
|
|
29959
|
+
for (const key of [
|
|
29960
|
+
"streamMode",
|
|
29961
|
+
"streamSubgraphs",
|
|
29962
|
+
"interruptBefore",
|
|
29963
|
+
"interruptAfter",
|
|
29964
|
+
"multitaskStrategy",
|
|
29965
|
+
"durability"
|
|
29966
|
+
]) {
|
|
29967
|
+
if (options?.[key] !== void 0) metadata[key] = options[key];
|
|
29968
|
+
}
|
|
29969
|
+
span = startSpan(
|
|
29970
|
+
withSpanInstrumentationName(
|
|
29971
|
+
{
|
|
29972
|
+
name: `langgraph.runs.${operation}`,
|
|
29973
|
+
spanAttributes: { type: "task" /* TASK */ },
|
|
29974
|
+
event: {
|
|
29975
|
+
input: options?.command === void 0 ? normalizeState(options?.input) : {
|
|
29976
|
+
input: normalizeState(options.input),
|
|
29977
|
+
command: options.command
|
|
29978
|
+
},
|
|
29979
|
+
metadata
|
|
29980
|
+
}
|
|
29981
|
+
},
|
|
29982
|
+
INSTRUMENTATION_NAMES.LANGGRAPH_SDK
|
|
29983
|
+
)
|
|
29984
|
+
);
|
|
29985
|
+
} catch (error) {
|
|
29986
|
+
debugLogger.error("Error starting LangGraph SDK span:", error);
|
|
29987
|
+
return invoke();
|
|
29988
|
+
}
|
|
29989
|
+
let ended = false;
|
|
29990
|
+
let output;
|
|
29991
|
+
let streamError;
|
|
29992
|
+
let firstToken;
|
|
29993
|
+
const updates = [];
|
|
29994
|
+
const usageByMessage = /* @__PURE__ */ new Map();
|
|
29995
|
+
const captureUsage = (id, usage) => {
|
|
29996
|
+
if (!isObject(usage)) return;
|
|
29997
|
+
const metrics = {};
|
|
29998
|
+
for (const [source, destination] of [
|
|
29999
|
+
["input_tokens", "prompt_tokens"],
|
|
30000
|
+
["output_tokens", "completion_tokens"],
|
|
30001
|
+
["total_tokens", "tokens"]
|
|
30002
|
+
]) {
|
|
30003
|
+
const value = usage[source];
|
|
30004
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
30005
|
+
metrics[destination] = value;
|
|
30006
|
+
}
|
|
30007
|
+
if (metrics.tokens === void 0 && metrics.prompt_tokens !== void 0 && metrics.completion_tokens !== void 0)
|
|
30008
|
+
metrics.tokens = metrics.prompt_tokens + metrics.completion_tokens;
|
|
30009
|
+
usageByMessage.set(id, { ...usageByMessage.get(id), ...metrics });
|
|
30010
|
+
};
|
|
30011
|
+
const messages = /* @__PURE__ */ new Map();
|
|
30012
|
+
const messageSnapshots = /* @__PURE__ */ new Map();
|
|
30013
|
+
const finish = (error) => {
|
|
30014
|
+
if (ended) return;
|
|
30015
|
+
ended = true;
|
|
30016
|
+
try {
|
|
30017
|
+
const metrics = {};
|
|
30018
|
+
for (const usage of usageByMessage.values()) {
|
|
30019
|
+
for (const [key, value] of Object.entries(usage))
|
|
30020
|
+
metrics[key] = (metrics[key] ?? 0) + value;
|
|
30021
|
+
}
|
|
30022
|
+
if (firstToken !== void 0)
|
|
30023
|
+
metrics.time_to_first_token = firstToken - start;
|
|
30024
|
+
const finalMessages = [
|
|
30025
|
+
...new Map([...messages, ...messageSnapshots]).values()
|
|
30026
|
+
];
|
|
30027
|
+
let loggedOutput = normalizeRunOutput(output, options?.input);
|
|
30028
|
+
if (loggedOutput === void 0 && finalMessages.length)
|
|
30029
|
+
loggedOutput = normalizeRunOutput(
|
|
30030
|
+
{ messages: finalMessages },
|
|
30031
|
+
void 0
|
|
30032
|
+
);
|
|
30033
|
+
if (output === void 0 && !finalMessages.length && updates.length) {
|
|
30034
|
+
const results = updates.map((update) => normalizeRunOutput(update, options?.input)).filter((update) => update !== void 0);
|
|
30035
|
+
if (results.length) loggedOutput = { updates: results };
|
|
30036
|
+
}
|
|
30037
|
+
const interrupted = [output, ...updates].find(
|
|
30038
|
+
(state) => isObject(state) && state.__interrupt__ !== void 0
|
|
30039
|
+
);
|
|
30040
|
+
span.log({
|
|
30041
|
+
...loggedOutput !== void 0 ? { output: loggedOutput } : {},
|
|
30042
|
+
...isObject(interrupted) ? { metadata: { "langgraph.interrupts": interrupted.__interrupt__ } } : {},
|
|
30043
|
+
...error !== void 0 || streamError !== void 0 ? { error: normalizeRunError(error ?? streamError) } : {},
|
|
30044
|
+
metrics
|
|
30045
|
+
});
|
|
30046
|
+
} catch (error2) {
|
|
30047
|
+
debugLogger.error("Error logging LangGraph SDK span:", error2);
|
|
30048
|
+
}
|
|
30049
|
+
try {
|
|
30050
|
+
span.end();
|
|
30051
|
+
} catch (error2) {
|
|
30052
|
+
debugLogger.error("Error ending LangGraph SDK span:", error2);
|
|
30053
|
+
}
|
|
30054
|
+
};
|
|
30055
|
+
const observeMessages = (value, streaming) => {
|
|
30056
|
+
if (!isObject(value) || !Array.isArray(value.messages)) return;
|
|
30057
|
+
const inputMessages = isObject(options?.input) && Array.isArray(options.input.messages) ? options.input.messages : [];
|
|
30058
|
+
for (const message of value.messages) {
|
|
30059
|
+
if (!isObject(message) || message.type !== "ai" && message.role !== "assistant")
|
|
30060
|
+
continue;
|
|
30061
|
+
if (message.id !== void 0 && inputMessages.some(
|
|
30062
|
+
(input) => isObject(input) && input.id === message.id
|
|
30063
|
+
))
|
|
30064
|
+
continue;
|
|
30065
|
+
captureUsage(
|
|
30066
|
+
typeof message.id === "string" ? message.id : "message",
|
|
30067
|
+
message.usage_metadata
|
|
30068
|
+
);
|
|
30069
|
+
if (streaming && (typeof message.content === "string" ? message.content.length > 0 : Array.isArray(message.content) && message.content.some(
|
|
30070
|
+
(part) => isObject(part) && typeof part.text === "string" && part.text.length > 0
|
|
30071
|
+
)))
|
|
30072
|
+
firstToken ??= getCurrentUnixTimestamp();
|
|
30073
|
+
}
|
|
30074
|
+
};
|
|
30075
|
+
const onChunk = ({ event, data }) => {
|
|
30076
|
+
if (ended) return;
|
|
30077
|
+
if (event === "metadata" && isObject(data)) {
|
|
30078
|
+
if (typeof data.run_id === "string")
|
|
30079
|
+
span.log({ metadata: { "langgraph.run_id": data.run_id } });
|
|
30080
|
+
} else if (event === "error") {
|
|
30081
|
+
streamError = normalizeRunError(data);
|
|
30082
|
+
} else if (event === "values") {
|
|
30083
|
+
output = data;
|
|
30084
|
+
observeMessages(data, true);
|
|
30085
|
+
} else if (event === "updates") {
|
|
30086
|
+
if (isObject(data)) {
|
|
30087
|
+
const stateUpdates = [];
|
|
30088
|
+
for (const [node, update] of Object.entries(data)) {
|
|
30089
|
+
observeMessages(update, true);
|
|
30090
|
+
if (isObject(update) && Array.isArray(update.messages)) {
|
|
30091
|
+
for (const message of update.messages) {
|
|
30092
|
+
if (isObject(message))
|
|
30093
|
+
messageSnapshots.set(
|
|
30094
|
+
typeof message.id === "string" ? message.id : `update-${messageSnapshots.size}`,
|
|
30095
|
+
message
|
|
30096
|
+
);
|
|
30097
|
+
}
|
|
30098
|
+
const state = Object.fromEntries(
|
|
30099
|
+
Object.entries(update).filter(([key]) => key !== "messages")
|
|
30100
|
+
);
|
|
30101
|
+
if (Object.keys(state).length) stateUpdates.push([node, state]);
|
|
30102
|
+
} else {
|
|
30103
|
+
stateUpdates.push([node, update]);
|
|
30104
|
+
}
|
|
30105
|
+
}
|
|
30106
|
+
if (stateUpdates.length) updates.push(Object.fromEntries(stateUpdates));
|
|
30107
|
+
} else {
|
|
30108
|
+
updates.push(data);
|
|
30109
|
+
}
|
|
30110
|
+
} else if ((event === "messages" || event === "messages/partial" || event === "messages/complete") && Array.isArray(data)) {
|
|
30111
|
+
const parts = event === "messages" ? [data[0]] : data;
|
|
30112
|
+
for (const part of parts) {
|
|
30113
|
+
if (!isObject(part)) continue;
|
|
30114
|
+
const id = typeof part.id === "string" ? part.id : "message";
|
|
30115
|
+
captureUsage(id, part.usage_metadata);
|
|
30116
|
+
const previous = messages.get(id);
|
|
30117
|
+
messages.set(
|
|
30118
|
+
id,
|
|
30119
|
+
event === "messages" && previous && typeof part.content === "string" && typeof previous.content === "string" ? { ...part, content: previous.content + part.content } : part
|
|
30120
|
+
);
|
|
30121
|
+
if (typeof part.content === "string" && part.content.length > 0)
|
|
30122
|
+
firstToken ??= getCurrentUnixTimestamp();
|
|
30123
|
+
}
|
|
30124
|
+
}
|
|
30125
|
+
};
|
|
30126
|
+
let result;
|
|
30127
|
+
try {
|
|
30128
|
+
result = withCurrent(
|
|
30129
|
+
span,
|
|
30130
|
+
() => runWithAutoInstrumentationSuppressed(invoke)
|
|
30131
|
+
);
|
|
30132
|
+
} catch (error) {
|
|
30133
|
+
finish(error);
|
|
30134
|
+
throw error;
|
|
30135
|
+
}
|
|
30136
|
+
if (operation === "stream") {
|
|
30137
|
+
try {
|
|
30138
|
+
patchStreamIfNeeded(result, {
|
|
30139
|
+
shouldCollect: (chunk) => {
|
|
30140
|
+
try {
|
|
30141
|
+
onChunk(chunk);
|
|
30142
|
+
} catch (error) {
|
|
30143
|
+
debugLogger.error(
|
|
30144
|
+
"Error processing LangGraph stream event:",
|
|
30145
|
+
error
|
|
30146
|
+
);
|
|
30147
|
+
}
|
|
30148
|
+
return false;
|
|
30149
|
+
},
|
|
30150
|
+
aroundNext: (next) => withCurrent(span, () => runWithAutoInstrumentationSuppressed(next)),
|
|
30151
|
+
onComplete: () => finish(),
|
|
30152
|
+
onCancel: () => finish(),
|
|
30153
|
+
onError: (error) => finish(error)
|
|
30154
|
+
});
|
|
30155
|
+
} catch (error) {
|
|
30156
|
+
debugLogger.error("Error observing LangGraph stream:", error);
|
|
30157
|
+
finish();
|
|
30158
|
+
}
|
|
30159
|
+
} else {
|
|
30160
|
+
void Promise.resolve(result).then(
|
|
30161
|
+
(value) => {
|
|
30162
|
+
try {
|
|
30163
|
+
output = value;
|
|
30164
|
+
observeMessages(value, false);
|
|
30165
|
+
if (isObject(value) && isObject(value.__error__))
|
|
30166
|
+
streamError = normalizeRunError(value.__error__);
|
|
30167
|
+
finish();
|
|
30168
|
+
} catch (error) {
|
|
30169
|
+
finish(error);
|
|
30170
|
+
}
|
|
30171
|
+
},
|
|
30172
|
+
(error) => finish(error)
|
|
30173
|
+
);
|
|
30174
|
+
}
|
|
30175
|
+
return result;
|
|
30176
|
+
}
|
|
30177
|
+
|
|
28768
30178
|
// src/instrumentation/plugins/ollama-plugin.ts
|
|
28769
30179
|
var OllamaPlugin = class extends BasePlugin {
|
|
28770
30180
|
onEnable() {
|
|
@@ -28954,7 +30364,7 @@ function normalizeTextAndImages(content, images) {
|
|
|
28954
30364
|
...unrecognizedImages.length > 0 ? { unrecognizedImages } : {}
|
|
28955
30365
|
};
|
|
28956
30366
|
}
|
|
28957
|
-
function
|
|
30367
|
+
function normalizeMessage2(message, toolCallId, syntheticToolCallIdOffset = 0) {
|
|
28958
30368
|
if (typeof message.role !== "string") {
|
|
28959
30369
|
return void 0;
|
|
28960
30370
|
}
|
|
@@ -29000,7 +30410,7 @@ function normalizeMessages(messages) {
|
|
|
29000
30410
|
toolCallId = pendingToolCallIds.get(toolName)?.shift();
|
|
29001
30411
|
}
|
|
29002
30412
|
}
|
|
29003
|
-
const normalized =
|
|
30413
|
+
const normalized = normalizeMessage2(
|
|
29004
30414
|
ollamaMessage,
|
|
29005
30415
|
toolCallId,
|
|
29006
30416
|
syntheticToolCallIdOffset
|
|
@@ -29119,7 +30529,7 @@ function extractOllamaChatOutput(result, syntheticToolCallIdOffset = 0) {
|
|
|
29119
30529
|
if (!isObject(result) || !isObject(result.message)) {
|
|
29120
30530
|
return void 0;
|
|
29121
30531
|
}
|
|
29122
|
-
const message =
|
|
30532
|
+
const message = normalizeMessage2(
|
|
29123
30533
|
result.message,
|
|
29124
30534
|
void 0,
|
|
29125
30535
|
syntheticToolCallIdOffset
|
|
@@ -31710,14 +33120,14 @@ function extractActionSpanMetadata(args) {
|
|
|
31710
33120
|
const options = extractRunInNewSpanOptions(args);
|
|
31711
33121
|
const labels = isObject(options?.labels) ? options.labels : void 0;
|
|
31712
33122
|
const metadata = isObject(options?.metadata) ? options.metadata : void 0;
|
|
31713
|
-
const actionType =
|
|
31714
|
-
const name =
|
|
33123
|
+
const actionType = stringValue2(labels?.["genkit:metadata:subtype"]);
|
|
33124
|
+
const name = stringValue2(metadata?.name);
|
|
31715
33125
|
if (!actionType || !name) {
|
|
31716
33126
|
return void 0;
|
|
31717
33127
|
}
|
|
31718
33128
|
return {
|
|
31719
33129
|
actionType,
|
|
31720
|
-
key:
|
|
33130
|
+
key: stringValue2(labels?.["genkit:key"]),
|
|
31721
33131
|
name
|
|
31722
33132
|
};
|
|
31723
33133
|
}
|
|
@@ -31827,7 +33237,7 @@ function pickNumberMetrics(values) {
|
|
|
31827
33237
|
})
|
|
31828
33238
|
);
|
|
31829
33239
|
}
|
|
31830
|
-
function
|
|
33240
|
+
function stringValue2(value) {
|
|
31831
33241
|
return typeof value === "string" ? value : void 0;
|
|
31832
33242
|
}
|
|
31833
33243
|
|
|
@@ -32530,10 +33940,10 @@ var LangSmithPlugin = class extends BasePlugin {
|
|
|
32530
33940
|
const creates = ownValue(batch, "runCreates");
|
|
32531
33941
|
if (Array.isArray(creates)) {
|
|
32532
33942
|
const parentFirst = [...creates].sort((left, right) => {
|
|
32533
|
-
const leftId =
|
|
32534
|
-
const rightId =
|
|
32535
|
-
const leftParent =
|
|
32536
|
-
const rightParent =
|
|
33943
|
+
const leftId = stringValue3(ownValue(left, "id"));
|
|
33944
|
+
const rightId = stringValue3(ownValue(right, "id"));
|
|
33945
|
+
const leftParent = stringValue3(ownValue(left, "parent_run_id"));
|
|
33946
|
+
const rightParent = stringValue3(ownValue(right, "parent_run_id"));
|
|
32537
33947
|
if (leftParent && leftParent === rightId) {
|
|
32538
33948
|
return 1;
|
|
32539
33949
|
}
|
|
@@ -32552,13 +33962,13 @@ var LangSmithPlugin = class extends BasePlugin {
|
|
|
32552
33962
|
if (Array.isArray(updates)) {
|
|
32553
33963
|
for (const run of updates) {
|
|
32554
33964
|
this.containLifecycleFailure("batchIngestRuns update", () => {
|
|
32555
|
-
this.processUpdate(
|
|
33965
|
+
this.processUpdate(stringValue3(ownValue(run, "id")) ?? "", run);
|
|
32556
33966
|
});
|
|
32557
33967
|
}
|
|
32558
33968
|
}
|
|
32559
33969
|
}
|
|
32560
33970
|
processCreate(run) {
|
|
32561
|
-
const id =
|
|
33971
|
+
const id = stringValue3(ownValue(run, "id"));
|
|
32562
33972
|
if (!id || this.completedRuns.get(id)) {
|
|
32563
33973
|
return;
|
|
32564
33974
|
}
|
|
@@ -32591,7 +34001,7 @@ var LangSmithPlugin = class extends BasePlugin {
|
|
|
32591
34001
|
this.endIfComplete(id, activeRun, run);
|
|
32592
34002
|
}
|
|
32593
34003
|
processUpdate(explicitId, run) {
|
|
32594
|
-
const id =
|
|
34004
|
+
const id = stringValue3(explicitId) ?? stringValue3(ownValue(run, "id"));
|
|
32595
34005
|
if (!id || this.completedRuns.get(id)) {
|
|
32596
34006
|
return;
|
|
32597
34007
|
}
|
|
@@ -32614,13 +34024,13 @@ var LangSmithPlugin = class extends BasePlugin {
|
|
|
32614
34024
|
this.endIfComplete(id, active, active.run);
|
|
32615
34025
|
}
|
|
32616
34026
|
startRunSpan(id, run) {
|
|
32617
|
-
const traceId =
|
|
32618
|
-
const parentId =
|
|
34027
|
+
const traceId = stringValue3(ownValue(run, "trace_id")) ?? id;
|
|
34028
|
+
const parentId = stringValue3(ownValue(run, "parent_run_id")) ?? stringValue3(ownValue(ownValue(run, "parent_run"), "id"));
|
|
32619
34029
|
const startTime = timestampSeconds(ownValue(run, "start_time"));
|
|
32620
34030
|
return startSpan(
|
|
32621
34031
|
withSpanInstrumentationName(
|
|
32622
34032
|
{
|
|
32623
|
-
name:
|
|
34033
|
+
name: stringValue3(ownValue(run, "name")) ?? "LangSmith run",
|
|
32624
34034
|
spanId: id,
|
|
32625
34035
|
parentSpanIds: {
|
|
32626
34036
|
parentSpanIds: parentId ? [parentId] : [],
|
|
@@ -32712,7 +34122,7 @@ function mergeRuns(previous, current) {
|
|
|
32712
34122
|
function isRecord2(value) {
|
|
32713
34123
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32714
34124
|
}
|
|
32715
|
-
function
|
|
34125
|
+
function stringValue3(value) {
|
|
32716
34126
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
32717
34127
|
}
|
|
32718
34128
|
function timestampSeconds(value) {
|
|
@@ -32730,7 +34140,7 @@ function timestampSeconds(value) {
|
|
|
32730
34140
|
return void 0;
|
|
32731
34141
|
}
|
|
32732
34142
|
function dottedOrderDepth(run) {
|
|
32733
|
-
const dottedOrder =
|
|
34143
|
+
const dottedOrder = stringValue3(ownValue(run, "dotted_order"));
|
|
32734
34144
|
return dottedOrder ? dottedOrder.split(".").length : Number.MAX_SAFE_INTEGER;
|
|
32735
34145
|
}
|
|
32736
34146
|
function mapRunType(runType) {
|
|
@@ -32923,7 +34333,7 @@ var PiCodingAgentPlugin = class extends BasePlugin {
|
|
|
32923
34333
|
}
|
|
32924
34334
|
);
|
|
32925
34335
|
} catch (error) {
|
|
32926
|
-
|
|
34336
|
+
logInstrumentationError5("Pi Coding Agent prompt start", error);
|
|
32927
34337
|
}
|
|
32928
34338
|
if (!state) {
|
|
32929
34339
|
return runWithAutoInstrumentationSuppressed(invokeTarget);
|
|
@@ -33056,12 +34466,12 @@ function installPiAgentInstrumentation(agent) {
|
|
|
33056
34466
|
() => handlePiAgentEvent(state, event)
|
|
33057
34467
|
);
|
|
33058
34468
|
} catch (error) {
|
|
33059
|
-
|
|
34469
|
+
logInstrumentationError5("Pi Coding Agent event", error);
|
|
33060
34470
|
}
|
|
33061
34471
|
});
|
|
33062
34472
|
piAgentEventSubscriptions.add(agent);
|
|
33063
34473
|
} catch (error) {
|
|
33064
|
-
|
|
34474
|
+
logInstrumentationError5("Pi Coding Agent event subscription", error);
|
|
33065
34475
|
}
|
|
33066
34476
|
}
|
|
33067
34477
|
function makeInstrumentedStreamFunction(agent, originalStreamFunction, property) {
|
|
@@ -33111,7 +34521,7 @@ function wrapPiToolExecutors(tools) {
|
|
|
33111
34521
|
});
|
|
33112
34522
|
tool.execute = wrappedExecute;
|
|
33113
34523
|
} catch (error) {
|
|
33114
|
-
|
|
34524
|
+
logInstrumentationError5("Pi Coding Agent tool wrapping", error);
|
|
33115
34525
|
}
|
|
33116
34526
|
}
|
|
33117
34527
|
}
|
|
@@ -33190,7 +34600,7 @@ function patchAssistantMessageStream(stream, promptState, llmState) {
|
|
|
33190
34600
|
try {
|
|
33191
34601
|
await iterator.return();
|
|
33192
34602
|
} catch (cleanupError) {
|
|
33193
|
-
|
|
34603
|
+
logInstrumentationError5(
|
|
33194
34604
|
"Pi Coding Agent stream cleanup",
|
|
33195
34605
|
cleanupError
|
|
33196
34606
|
);
|
|
@@ -33355,7 +34765,7 @@ function finishPiPromptRun(state, error) {
|
|
|
33355
34765
|
try {
|
|
33356
34766
|
state.span.end();
|
|
33357
34767
|
} catch (endError) {
|
|
33358
|
-
|
|
34768
|
+
logInstrumentationError5("Pi Coding Agent prompt end", endError);
|
|
33359
34769
|
}
|
|
33360
34770
|
}
|
|
33361
34771
|
}
|
|
@@ -33687,10 +35097,10 @@ function safeLog4(span, event) {
|
|
|
33687
35097
|
try {
|
|
33688
35098
|
span.log(event);
|
|
33689
35099
|
} catch (error) {
|
|
33690
|
-
|
|
35100
|
+
logInstrumentationError5("Pi Coding Agent span log", error);
|
|
33691
35101
|
}
|
|
33692
35102
|
}
|
|
33693
|
-
function
|
|
35103
|
+
function logInstrumentationError5(context, error) {
|
|
33694
35104
|
debugLogger.debug(`${context}:`, error);
|
|
33695
35105
|
}
|
|
33696
35106
|
|
|
@@ -33908,7 +35318,7 @@ function handleAgentStreamEvent(state, event) {
|
|
|
33908
35318
|
finalizeModelSpan(state, event);
|
|
33909
35319
|
break;
|
|
33910
35320
|
case "beforeToolCallEvent":
|
|
33911
|
-
|
|
35321
|
+
startToolSpan3(state, event);
|
|
33912
35322
|
break;
|
|
33913
35323
|
case "afterToolCallEvent":
|
|
33914
35324
|
finalizeToolSpan(state, event);
|
|
@@ -33933,7 +35343,7 @@ function handleAgentStreamEvent(state, event) {
|
|
|
33933
35343
|
break;
|
|
33934
35344
|
}
|
|
33935
35345
|
} catch (error) {
|
|
33936
|
-
|
|
35346
|
+
logInstrumentationError6("Strands Agent SDK event", error);
|
|
33937
35347
|
}
|
|
33938
35348
|
}
|
|
33939
35349
|
function handleMultiAgentStreamEvent(state, event, activeChildParents) {
|
|
@@ -33969,7 +35379,7 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
|
|
|
33969
35379
|
break;
|
|
33970
35380
|
}
|
|
33971
35381
|
} catch (error) {
|
|
33972
|
-
|
|
35382
|
+
logInstrumentationError6("Strands Agent SDK multi-agent event", error);
|
|
33973
35383
|
}
|
|
33974
35384
|
}
|
|
33975
35385
|
function buildModelSpanInput(event, attachmentCache) {
|
|
@@ -34048,7 +35458,7 @@ function finalizeModelSpan(state, event) {
|
|
|
34048
35458
|
});
|
|
34049
35459
|
modelState.span.end();
|
|
34050
35460
|
}
|
|
34051
|
-
function
|
|
35461
|
+
function startToolSpan3(state, event) {
|
|
34052
35462
|
const toolUse = event.toolUse;
|
|
34053
35463
|
const key = toolKey2(toolUse);
|
|
34054
35464
|
if (state.activeTools.has(key)) {
|
|
@@ -34328,7 +35738,7 @@ function getModelConfig(model) {
|
|
|
34328
35738
|
try {
|
|
34329
35739
|
return model.getConfig();
|
|
34330
35740
|
} catch (error) {
|
|
34331
|
-
|
|
35741
|
+
logInstrumentationError6("Strands Agent SDK model config", error);
|
|
34332
35742
|
return void 0;
|
|
34333
35743
|
}
|
|
34334
35744
|
}
|
|
@@ -34411,7 +35821,7 @@ function processStrandsInputAttachments(input, cache = createStrandsAttachmentCa
|
|
|
34411
35821
|
try {
|
|
34412
35822
|
return processStrandsInputNode(input, cache);
|
|
34413
35823
|
} catch (error) {
|
|
34414
|
-
|
|
35824
|
+
logInstrumentationError6("Strands Agent SDK input attachments", error);
|
|
34415
35825
|
return input;
|
|
34416
35826
|
}
|
|
34417
35827
|
}
|
|
@@ -34631,13 +36041,465 @@ function safeLog5(span, event) {
|
|
|
34631
36041
|
try {
|
|
34632
36042
|
span.log(event);
|
|
34633
36043
|
} catch (error) {
|
|
34634
|
-
|
|
36044
|
+
logInstrumentationError6("Strands Agent SDK span log", error);
|
|
34635
36045
|
}
|
|
34636
36046
|
}
|
|
34637
|
-
function
|
|
36047
|
+
function logInstrumentationError6(context, error) {
|
|
34638
36048
|
debugLogger.debug(`${context}:`, error);
|
|
34639
36049
|
}
|
|
34640
36050
|
|
|
36051
|
+
// src/instrumentation/plugins/elevenlabs-plugin.ts
|
|
36052
|
+
var ElevenLabsPlugin = class extends BasePlugin {
|
|
36053
|
+
onEnable() {
|
|
36054
|
+
for (const method of [
|
|
36055
|
+
"convert",
|
|
36056
|
+
"stream",
|
|
36057
|
+
"convertWithTimestamps",
|
|
36058
|
+
"streamWithTimestamps"
|
|
36059
|
+
]) {
|
|
36060
|
+
this.unsubscribers.push(
|
|
36061
|
+
interceptCall2(
|
|
36062
|
+
elevenLabsChannels[method],
|
|
36063
|
+
`elevenlabs.textToSpeech.${method}`,
|
|
36064
|
+
([voice, request]) => ({
|
|
36065
|
+
input: {
|
|
36066
|
+
operation: "speech",
|
|
36067
|
+
prompt: request.text,
|
|
36068
|
+
parameters: {
|
|
36069
|
+
voice,
|
|
36070
|
+
format: request.outputFormat,
|
|
36071
|
+
language: request.languageCode,
|
|
36072
|
+
speed: request.voiceSettings?.speed
|
|
36073
|
+
}
|
|
36074
|
+
},
|
|
36075
|
+
metadata: {
|
|
36076
|
+
provider: "elevenlabs",
|
|
36077
|
+
model: request.modelId ?? "eleven_multilingual_v2"
|
|
36078
|
+
}
|
|
36079
|
+
}),
|
|
36080
|
+
(value, args, span, finish, headers, started) => captureSpeech(
|
|
36081
|
+
value,
|
|
36082
|
+
args[1],
|
|
36083
|
+
method,
|
|
36084
|
+
span,
|
|
36085
|
+
finish,
|
|
36086
|
+
started,
|
|
36087
|
+
headers
|
|
36088
|
+
)
|
|
36089
|
+
)
|
|
36090
|
+
);
|
|
36091
|
+
}
|
|
36092
|
+
this.unsubscribers.push(
|
|
36093
|
+
interceptCall2(
|
|
36094
|
+
elevenLabsChannels.transcribe,
|
|
36095
|
+
"elevenlabs.speechToText.convert",
|
|
36096
|
+
([request]) => {
|
|
36097
|
+
if (request.webhook) return void 0;
|
|
36098
|
+
const file = request.file;
|
|
36099
|
+
const filename = typeof File !== "undefined" && file instanceof File ? file.name : "audio";
|
|
36100
|
+
const contentType = file instanceof Blob ? file.type || "application/octet-stream" : "application/octet-stream";
|
|
36101
|
+
const blob = file instanceof Blob ? file : file instanceof Uint8Array ? new Blob([new Uint8Array(file)], { type: contentType }) : file instanceof ArrayBuffer ? new Blob([file.slice(0)], { type: contentType }) : void 0;
|
|
36102
|
+
const fileData = blob ? new Attachment({ data: blob, filename, contentType }) : request.cloudStorageUrl;
|
|
36103
|
+
return {
|
|
36104
|
+
input: {
|
|
36105
|
+
operation: "transcribe",
|
|
36106
|
+
content: fileData ? [{ type: "file", file: { filename, file_data: fileData } }] : [],
|
|
36107
|
+
parameters: {
|
|
36108
|
+
language: request.languageCode,
|
|
36109
|
+
timestamp_granularities: request.timestampsGranularity
|
|
36110
|
+
}
|
|
36111
|
+
},
|
|
36112
|
+
metadata: { provider: "elevenlabs", model: request.modelId }
|
|
36113
|
+
};
|
|
36114
|
+
},
|
|
36115
|
+
(value, _args, span, finish) => {
|
|
36116
|
+
const result = value;
|
|
36117
|
+
const transcripts = result.transcripts ?? [result];
|
|
36118
|
+
span.log({
|
|
36119
|
+
output: {
|
|
36120
|
+
content: transcripts.flatMap(
|
|
36121
|
+
(transcript) => typeof transcript.text === "string" ? [{ type: "text", text: transcript.text }] : []
|
|
36122
|
+
),
|
|
36123
|
+
annotations: {
|
|
36124
|
+
language: result.languageCode,
|
|
36125
|
+
words: result.words ?? (result.transcripts ? result.transcripts.flatMap(
|
|
36126
|
+
(transcript) => transcript.words ?? []
|
|
36127
|
+
) : void 0)
|
|
36128
|
+
}
|
|
36129
|
+
}
|
|
36130
|
+
});
|
|
36131
|
+
finish();
|
|
36132
|
+
},
|
|
36133
|
+
([request], span) => {
|
|
36134
|
+
const file = request.file;
|
|
36135
|
+
if (!isAsyncIterable(file)) return;
|
|
36136
|
+
const chunks = [];
|
|
36137
|
+
const filename = isObject(file) && typeof file.path === "string" ? file.path.split(/[\\/]/).pop() || "audio" : "audio";
|
|
36138
|
+
observeAudioStream(
|
|
36139
|
+
file,
|
|
36140
|
+
(chunk) => chunks.push(new Uint8Array(chunk)),
|
|
36141
|
+
() => {
|
|
36142
|
+
const contentType = "application/octet-stream";
|
|
36143
|
+
const data = new Blob(chunks, {
|
|
36144
|
+
type: contentType
|
|
36145
|
+
});
|
|
36146
|
+
chunks.length = 0;
|
|
36147
|
+
span.log({
|
|
36148
|
+
input: {
|
|
36149
|
+
content: [
|
|
36150
|
+
{
|
|
36151
|
+
type: "file",
|
|
36152
|
+
file: {
|
|
36153
|
+
filename,
|
|
36154
|
+
file_data: new Attachment({
|
|
36155
|
+
data,
|
|
36156
|
+
filename,
|
|
36157
|
+
contentType
|
|
36158
|
+
})
|
|
36159
|
+
}
|
|
36160
|
+
}
|
|
36161
|
+
]
|
|
36162
|
+
}
|
|
36163
|
+
});
|
|
36164
|
+
},
|
|
36165
|
+
() => {
|
|
36166
|
+
chunks.length = 0;
|
|
36167
|
+
},
|
|
36168
|
+
span
|
|
36169
|
+
);
|
|
36170
|
+
}
|
|
36171
|
+
)
|
|
36172
|
+
);
|
|
36173
|
+
}
|
|
36174
|
+
onDisable() {
|
|
36175
|
+
this.unsubscribers = unsubscribeAll(this.unsubscribers);
|
|
36176
|
+
}
|
|
36177
|
+
};
|
|
36178
|
+
function interceptCall2(channel, name, input, output, beforeInvoke) {
|
|
36179
|
+
return channel.intercept((target, self, args) => {
|
|
36180
|
+
const invoke = () => Reflect.apply(target, self, args);
|
|
36181
|
+
if (isAutoInstrumentationSuppressed()) return invoke();
|
|
36182
|
+
const started = Date.now() / 1e3;
|
|
36183
|
+
let span;
|
|
36184
|
+
try {
|
|
36185
|
+
const event = input(args);
|
|
36186
|
+
if (event !== void 0)
|
|
36187
|
+
span = startSpan(
|
|
36188
|
+
withSpanInstrumentationName(
|
|
36189
|
+
{
|
|
36190
|
+
name,
|
|
36191
|
+
spanAttributes: { type: "llm" /* LLM */ },
|
|
36192
|
+
event
|
|
36193
|
+
},
|
|
36194
|
+
INSTRUMENTATION_NAMES.ELEVENLABS
|
|
36195
|
+
)
|
|
36196
|
+
);
|
|
36197
|
+
} catch (error) {
|
|
36198
|
+
debugLogger.error("Error starting ElevenLabs span", error);
|
|
36199
|
+
return invoke();
|
|
36200
|
+
}
|
|
36201
|
+
if (!span) return invoke();
|
|
36202
|
+
const activeSpan = span;
|
|
36203
|
+
let ended = false;
|
|
36204
|
+
const finish = (error) => {
|
|
36205
|
+
if (ended) return;
|
|
36206
|
+
ended = true;
|
|
36207
|
+
try {
|
|
36208
|
+
if (error !== void 0) activeSpan.log({ error });
|
|
36209
|
+
activeSpan.end();
|
|
36210
|
+
} catch (loggingError) {
|
|
36211
|
+
debugLogger.error("Error ending ElevenLabs span", loggingError);
|
|
36212
|
+
}
|
|
36213
|
+
};
|
|
36214
|
+
try {
|
|
36215
|
+
beforeInvoke?.(args, span);
|
|
36216
|
+
} catch (error) {
|
|
36217
|
+
debugLogger.error("Error observing ElevenLabs input", error);
|
|
36218
|
+
}
|
|
36219
|
+
let result;
|
|
36220
|
+
try {
|
|
36221
|
+
result = withCurrent(
|
|
36222
|
+
span,
|
|
36223
|
+
() => runWithAutoInstrumentationSuppressed(invoke)
|
|
36224
|
+
);
|
|
36225
|
+
} catch (error) {
|
|
36226
|
+
finish(error);
|
|
36227
|
+
throw error;
|
|
36228
|
+
}
|
|
36229
|
+
const capture = (value, headers) => {
|
|
36230
|
+
try {
|
|
36231
|
+
output(value, args, span, finish, headers, started);
|
|
36232
|
+
} catch (error) {
|
|
36233
|
+
debugLogger.error("Error capturing ElevenLabs output", error);
|
|
36234
|
+
finish();
|
|
36235
|
+
}
|
|
36236
|
+
};
|
|
36237
|
+
try {
|
|
36238
|
+
if (isObject(result) && typeof result.withRawResponse === "function") {
|
|
36239
|
+
void result.withRawResponse().then(
|
|
36240
|
+
({
|
|
36241
|
+
data,
|
|
36242
|
+
rawResponse
|
|
36243
|
+
}) => capture(data, rawResponse?.headers),
|
|
36244
|
+
finish
|
|
36245
|
+
);
|
|
36246
|
+
} else {
|
|
36247
|
+
void Promise.resolve(result).then((value) => capture(value), finish);
|
|
36248
|
+
}
|
|
36249
|
+
} catch (error) {
|
|
36250
|
+
debugLogger.error("Error observing ElevenLabs result", error);
|
|
36251
|
+
finish();
|
|
36252
|
+
}
|
|
36253
|
+
return result;
|
|
36254
|
+
});
|
|
36255
|
+
}
|
|
36256
|
+
function captureSpeech(value, request, method, span, finish, started, headers) {
|
|
36257
|
+
const format = request.outputFormat ?? "mp3_44100_128";
|
|
36258
|
+
const formatType = format.startsWith("mp3_") ? "audio/mpeg" : format.startsWith("pcm_") ? "audio/pcm" : format.startsWith("opus_") ? "audio/ogg" : format.startsWith("ulaw_") ? "audio/basic" : format.startsWith("alaw_") ? "audio/x-alaw" : void 0;
|
|
36259
|
+
const headerType = headers?.get("content-type")?.split(";")[0];
|
|
36260
|
+
const contentType = headerType?.startsWith("audio/") ? headerType : formatType;
|
|
36261
|
+
const disposition = headers?.get("content-disposition");
|
|
36262
|
+
const headerFilename = disposition?.match(
|
|
36263
|
+
/filename="([^"]+)"|filename=([^;]+)/i
|
|
36264
|
+
);
|
|
36265
|
+
const filename = headerFilename?.[1] ?? headerFilename?.[2]?.trim() ?? `speech.${contentType ? getExtensionFromMediaType(contentType) : "bin"}`;
|
|
36266
|
+
const chunks = [];
|
|
36267
|
+
const alignments = [];
|
|
36268
|
+
let bytes = 0;
|
|
36269
|
+
let first = true;
|
|
36270
|
+
let stopped = false;
|
|
36271
|
+
const observe = (chunk) => {
|
|
36272
|
+
if (stopped || chunk.byteLength === 0) return;
|
|
36273
|
+
if (first && method.startsWith("stream")) {
|
|
36274
|
+
span.log({
|
|
36275
|
+
metrics: { time_to_first_token: Date.now() / 1e3 - started }
|
|
36276
|
+
});
|
|
36277
|
+
}
|
|
36278
|
+
first = false;
|
|
36279
|
+
chunks.push(new Uint8Array(chunk));
|
|
36280
|
+
bytes += chunk.byteLength;
|
|
36281
|
+
};
|
|
36282
|
+
const complete = () => {
|
|
36283
|
+
if (stopped) return;
|
|
36284
|
+
stopped = true;
|
|
36285
|
+
try {
|
|
36286
|
+
const content = [];
|
|
36287
|
+
if (contentType && bytes) {
|
|
36288
|
+
const data = new Uint8Array(bytes);
|
|
36289
|
+
let offset = 0;
|
|
36290
|
+
for (const chunk of chunks) {
|
|
36291
|
+
data.set(chunk, offset);
|
|
36292
|
+
offset += chunk.length;
|
|
36293
|
+
}
|
|
36294
|
+
content.push({
|
|
36295
|
+
type: "file",
|
|
36296
|
+
file: {
|
|
36297
|
+
filename,
|
|
36298
|
+
byte_size: bytes,
|
|
36299
|
+
file_data: new Attachment({
|
|
36300
|
+
data: new Blob([data], { type: contentType }),
|
|
36301
|
+
filename,
|
|
36302
|
+
contentType
|
|
36303
|
+
})
|
|
36304
|
+
}
|
|
36305
|
+
});
|
|
36306
|
+
}
|
|
36307
|
+
span.log({
|
|
36308
|
+
output: {
|
|
36309
|
+
content,
|
|
36310
|
+
...alignments.length ? { annotations: alignments } : {}
|
|
36311
|
+
}
|
|
36312
|
+
});
|
|
36313
|
+
} finally {
|
|
36314
|
+
chunks.length = 0;
|
|
36315
|
+
finish();
|
|
36316
|
+
}
|
|
36317
|
+
};
|
|
36318
|
+
const cancel = (error) => {
|
|
36319
|
+
stopped = true;
|
|
36320
|
+
chunks.length = 0;
|
|
36321
|
+
finish(error);
|
|
36322
|
+
};
|
|
36323
|
+
const timestampChunk = (chunk) => {
|
|
36324
|
+
const binary = atob(chunk.audioBase64);
|
|
36325
|
+
observe(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
|
|
36326
|
+
if (chunk.alignment || chunk.normalizedAlignment)
|
|
36327
|
+
alignments.push({
|
|
36328
|
+
alignment: chunk.alignment,
|
|
36329
|
+
normalized_alignment: chunk.normalizedAlignment
|
|
36330
|
+
});
|
|
36331
|
+
};
|
|
36332
|
+
if (method === "convertWithTimestamps") {
|
|
36333
|
+
timestampChunk(value);
|
|
36334
|
+
complete();
|
|
36335
|
+
} else if (method === "streamWithTimestamps") {
|
|
36336
|
+
patchStreamIfNeeded(value, {
|
|
36337
|
+
shouldCollect: (chunk) => {
|
|
36338
|
+
try {
|
|
36339
|
+
timestampChunk(chunk);
|
|
36340
|
+
} catch (error) {
|
|
36341
|
+
debugLogger.error("Error collecting ElevenLabs timestamps", error);
|
|
36342
|
+
cancel();
|
|
36343
|
+
}
|
|
36344
|
+
return false;
|
|
36345
|
+
},
|
|
36346
|
+
onComplete: complete,
|
|
36347
|
+
onCancel: () => cancel(),
|
|
36348
|
+
onError: cancel,
|
|
36349
|
+
aroundNext: (next) => withCurrent(span, next)
|
|
36350
|
+
});
|
|
36351
|
+
} else {
|
|
36352
|
+
observeAudioStream(value, observe, complete, cancel, span);
|
|
36353
|
+
}
|
|
36354
|
+
}
|
|
36355
|
+
function observeAudioStream(value, observe, complete, cancel, span) {
|
|
36356
|
+
let ended = false;
|
|
36357
|
+
const safeObserve = (chunk) => {
|
|
36358
|
+
if (ended) return;
|
|
36359
|
+
try {
|
|
36360
|
+
observe(chunk);
|
|
36361
|
+
} catch (error) {
|
|
36362
|
+
debugLogger.error("Error collecting ElevenLabs audio", error);
|
|
36363
|
+
end(false);
|
|
36364
|
+
}
|
|
36365
|
+
};
|
|
36366
|
+
const end = (success, error) => {
|
|
36367
|
+
if (ended) return;
|
|
36368
|
+
ended = true;
|
|
36369
|
+
try {
|
|
36370
|
+
if (success) complete();
|
|
36371
|
+
else cancel(error);
|
|
36372
|
+
} catch (loggingError) {
|
|
36373
|
+
debugLogger.error("Error logging ElevenLabs audio", loggingError);
|
|
36374
|
+
cancel();
|
|
36375
|
+
}
|
|
36376
|
+
};
|
|
36377
|
+
if (!isObject(value) || !Object.isExtensible(value)) {
|
|
36378
|
+
end(false);
|
|
36379
|
+
return;
|
|
36380
|
+
}
|
|
36381
|
+
if (typeof value.read === "function" && typeof value.on === "function") {
|
|
36382
|
+
value.on("end", () => end(true));
|
|
36383
|
+
value.on("close", () => end(false));
|
|
36384
|
+
const emit = value.emit;
|
|
36385
|
+
if (typeof emit === "function")
|
|
36386
|
+
value.emit = function(event, ...args) {
|
|
36387
|
+
if (event === "data" && args[0] instanceof Uint8Array)
|
|
36388
|
+
safeObserve(args[0]);
|
|
36389
|
+
if (event === "error") end(false, args[0]);
|
|
36390
|
+
return Reflect.apply(emit, this, [event, ...args]);
|
|
36391
|
+
};
|
|
36392
|
+
return;
|
|
36393
|
+
}
|
|
36394
|
+
if (typeof value.getReader === "function") {
|
|
36395
|
+
const webStream = value;
|
|
36396
|
+
const pipeTo = webStream.pipeTo;
|
|
36397
|
+
const pipeThrough = webStream.pipeThrough;
|
|
36398
|
+
webStream.pipeTo = function(destination, options) {
|
|
36399
|
+
if (!isObject(destination) || this.locked || destination.locked)
|
|
36400
|
+
return pipeTo.call(this, destination, options);
|
|
36401
|
+
const tap = new TransformStream({
|
|
36402
|
+
transform(chunk, controller) {
|
|
36403
|
+
safeObserve(chunk);
|
|
36404
|
+
controller.enqueue(chunk);
|
|
36405
|
+
},
|
|
36406
|
+
flush() {
|
|
36407
|
+
end(true);
|
|
36408
|
+
}
|
|
36409
|
+
});
|
|
36410
|
+
const observed = pipeThrough.call(
|
|
36411
|
+
this,
|
|
36412
|
+
tap,
|
|
36413
|
+
options
|
|
36414
|
+
);
|
|
36415
|
+
return observed.pipeTo(destination, options).catch((error) => {
|
|
36416
|
+
end(false, error);
|
|
36417
|
+
throw error;
|
|
36418
|
+
});
|
|
36419
|
+
};
|
|
36420
|
+
webStream.pipeThrough = function(transform, options) {
|
|
36421
|
+
if (this.locked || transform.writable.locked || transform.readable.locked)
|
|
36422
|
+
return pipeThrough.call(this, transform, options);
|
|
36423
|
+
const result = webStream.pipeTo.call(this, transform.writable, options);
|
|
36424
|
+
void result.catch(() => {
|
|
36425
|
+
});
|
|
36426
|
+
return transform.readable;
|
|
36427
|
+
};
|
|
36428
|
+
const getReader = value.getReader;
|
|
36429
|
+
value.getReader = function(...args) {
|
|
36430
|
+
const reader = Reflect.apply(getReader, this, args);
|
|
36431
|
+
const read3 = reader.read;
|
|
36432
|
+
reader.read = function(...readArgs) {
|
|
36433
|
+
return Promise.resolve(
|
|
36434
|
+
withCurrent(span, () => Reflect.apply(read3, this, readArgs))
|
|
36435
|
+
).then(
|
|
36436
|
+
(result) => {
|
|
36437
|
+
if (result.value) safeObserve(result.value);
|
|
36438
|
+
if (result.done) end(true);
|
|
36439
|
+
return result;
|
|
36440
|
+
},
|
|
36441
|
+
(error) => {
|
|
36442
|
+
end(false, error);
|
|
36443
|
+
throw error;
|
|
36444
|
+
}
|
|
36445
|
+
);
|
|
36446
|
+
};
|
|
36447
|
+
const readerCancel = reader.cancel;
|
|
36448
|
+
reader.cancel = function(...cancelArgs) {
|
|
36449
|
+
const result = Reflect.apply(readerCancel, this, cancelArgs);
|
|
36450
|
+
end(false);
|
|
36451
|
+
return result;
|
|
36452
|
+
};
|
|
36453
|
+
return reader;
|
|
36454
|
+
};
|
|
36455
|
+
const streamCancel = value.cancel;
|
|
36456
|
+
if (typeof streamCancel === "function")
|
|
36457
|
+
value.cancel = function(...args) {
|
|
36458
|
+
const result = Reflect.apply(streamCancel, this, args);
|
|
36459
|
+
void Promise.resolve(result).then(
|
|
36460
|
+
() => end(false),
|
|
36461
|
+
() => {
|
|
36462
|
+
}
|
|
36463
|
+
);
|
|
36464
|
+
return result;
|
|
36465
|
+
};
|
|
36466
|
+
}
|
|
36467
|
+
if (typeof value.getReader === "function" && typeof value.values === "function") {
|
|
36468
|
+
const values = value.values;
|
|
36469
|
+
const iterate = function(...args) {
|
|
36470
|
+
const iterator = Reflect.apply(values, this, args);
|
|
36471
|
+
patchStreamIfNeeded(iterator, {
|
|
36472
|
+
shouldCollect(chunk) {
|
|
36473
|
+
safeObserve(chunk);
|
|
36474
|
+
return false;
|
|
36475
|
+
},
|
|
36476
|
+
onComplete: () => end(true),
|
|
36477
|
+
onCancel: () => end(false),
|
|
36478
|
+
onError: (error) => end(false, error),
|
|
36479
|
+
aroundNext: (next) => withCurrent(span, next)
|
|
36480
|
+
});
|
|
36481
|
+
return iterator;
|
|
36482
|
+
};
|
|
36483
|
+
value.values = iterate;
|
|
36484
|
+
Object.defineProperty(value, Symbol.asyncIterator, {
|
|
36485
|
+
configurable: true,
|
|
36486
|
+
writable: true,
|
|
36487
|
+
value: iterate
|
|
36488
|
+
});
|
|
36489
|
+
} else if (isAsyncIterable(value)) {
|
|
36490
|
+
patchStreamIfNeeded(value, {
|
|
36491
|
+
shouldCollect: (chunk) => {
|
|
36492
|
+
safeObserve(chunk);
|
|
36493
|
+
return false;
|
|
36494
|
+
},
|
|
36495
|
+
onComplete: () => end(true),
|
|
36496
|
+
onCancel: () => end(false),
|
|
36497
|
+
onError: (error) => end(false, error),
|
|
36498
|
+
aroundNext: (next) => withCurrent(span, next)
|
|
36499
|
+
});
|
|
36500
|
+
} else if (typeof value.getReader !== "function") end(false);
|
|
36501
|
+
}
|
|
36502
|
+
|
|
34641
36503
|
// src/instrumentation/plugins/voyageai-plugin.ts
|
|
34642
36504
|
var RERANK_METADATA_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
34643
36505
|
"model",
|
|
@@ -34681,7 +36543,7 @@ var VoyageAIPlugin = class extends BasePlugin {
|
|
|
34681
36543
|
this.unsubscribers = unsubscribeAll(this.unsubscribers);
|
|
34682
36544
|
}
|
|
34683
36545
|
};
|
|
34684
|
-
function interceptVoyageAICall(channel, name,
|
|
36546
|
+
function interceptVoyageAICall(channel, name, extractInput3, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
|
|
34685
36547
|
return channel.intercept((target, thisArg, args) => {
|
|
34686
36548
|
const invokeTarget = () => Reflect.apply(target, thisArg, args);
|
|
34687
36549
|
if (isAutoInstrumentationSuppressed()) {
|
|
@@ -34689,7 +36551,7 @@ function interceptVoyageAICall(channel, name, extractInput2, extractOutput2, ext
|
|
|
34689
36551
|
}
|
|
34690
36552
|
let span;
|
|
34691
36553
|
try {
|
|
34692
|
-
const { input, metadata } =
|
|
36554
|
+
const { input, metadata } = extractInput3(args);
|
|
34693
36555
|
span = startSpan(
|
|
34694
36556
|
withSpanInstrumentationName(
|
|
34695
36557
|
{
|
|
@@ -35046,14 +36908,14 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
|
|
|
35046
36908
|
const result = event.arguments[0];
|
|
35047
36909
|
state = agent ? this.findResponseState(
|
|
35048
36910
|
agent,
|
|
35049
|
-
|
|
36911
|
+
stringValue4(ownValue2(result, "requestId"))
|
|
35050
36912
|
) : void 0;
|
|
35051
36913
|
if (!state) {
|
|
35052
36914
|
return;
|
|
35053
36915
|
}
|
|
35054
36916
|
state.responseObserved = true;
|
|
35055
36917
|
const output = serializeMessage(ownValue2(result, "message"));
|
|
35056
|
-
const status =
|
|
36918
|
+
const status = stringValue4(ownValue2(result, "status"));
|
|
35057
36919
|
const error = ownValue2(result, "error");
|
|
35058
36920
|
const input = ownValue2(result, "continuation") === true ? state.input : serializeMessages(readProperty(agent, "messages"))?.filter(
|
|
35059
36921
|
(message) => typeof output?.id !== "string" || message.id !== output.id
|
|
@@ -35100,7 +36962,7 @@ var CloudflareAIChatPlugin = class extends BasePlugin {
|
|
|
35100
36962
|
}
|
|
35101
36963
|
try {
|
|
35102
36964
|
const agent = asObject(event.self);
|
|
35103
|
-
const requestId =
|
|
36965
|
+
const requestId = stringValue4(event.arguments[0]);
|
|
35104
36966
|
const key = requestId ?? /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn");
|
|
35105
36967
|
const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
|
|
35106
36968
|
const existing = activeForAgent?.get(key);
|
|
@@ -35269,7 +37131,7 @@ function ownValue2(value, key) {
|
|
|
35269
37131
|
const descriptor = Object.getOwnPropertyDescriptor(object, key);
|
|
35270
37132
|
return descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
35271
37133
|
}
|
|
35272
|
-
function
|
|
37134
|
+
function stringValue4(value) {
|
|
35273
37135
|
return typeof value === "string" ? value : void 0;
|
|
35274
37136
|
}
|
|
35275
37137
|
function serializeMessages(value) {
|
|
@@ -35375,7 +37237,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
|
|
|
35375
37237
|
);
|
|
35376
37238
|
spans.set(event, span);
|
|
35377
37239
|
} catch (error) {
|
|
35378
|
-
|
|
37240
|
+
logInstrumentationError7("start", error);
|
|
35379
37241
|
}
|
|
35380
37242
|
},
|
|
35381
37243
|
asyncEnd: (event) => {
|
|
@@ -35395,7 +37257,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
|
|
|
35395
37257
|
}
|
|
35396
37258
|
}
|
|
35397
37259
|
} catch (error) {
|
|
35398
|
-
|
|
37260
|
+
logInstrumentationError7("completion", error);
|
|
35399
37261
|
} finally {
|
|
35400
37262
|
safelyEndSpan(span);
|
|
35401
37263
|
}
|
|
@@ -35409,7 +37271,7 @@ var CloudflareAgentsPlugin = class extends BasePlugin {
|
|
|
35409
37271
|
try {
|
|
35410
37272
|
span.log({ error: event.error });
|
|
35411
37273
|
} catch (error) {
|
|
35412
|
-
|
|
37274
|
+
logInstrumentationError7("rejection", error);
|
|
35413
37275
|
} finally {
|
|
35414
37276
|
safelyEndSpan(span);
|
|
35415
37277
|
}
|
|
@@ -35439,10 +37301,10 @@ function safelyEndSpan(span) {
|
|
|
35439
37301
|
try {
|
|
35440
37302
|
span.end();
|
|
35441
37303
|
} catch (error) {
|
|
35442
|
-
|
|
37304
|
+
logInstrumentationError7("span end", error);
|
|
35443
37305
|
}
|
|
35444
37306
|
}
|
|
35445
|
-
function
|
|
37307
|
+
function logInstrumentationError7(operation, error) {
|
|
35446
37308
|
debugLogger.error(
|
|
35447
37309
|
`Failed to process Cloudflare Agents ${operation} instrumentation:`,
|
|
35448
37310
|
error
|
|
@@ -35460,12 +37322,14 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35460
37322
|
cloudflareThinkPlugin = null;
|
|
35461
37323
|
cursorSDKPlugin = null;
|
|
35462
37324
|
openAIAgentsPlugin = null;
|
|
37325
|
+
googleGenerativeAIPlugin = null;
|
|
35463
37326
|
googleGenAIPlugin = null;
|
|
35464
37327
|
huggingFacePlugin = null;
|
|
35465
37328
|
huggingFaceTransformersPlugin = null;
|
|
35466
37329
|
openRouterPlugin = null;
|
|
35467
37330
|
openRouterAgentPlugin = null;
|
|
35468
37331
|
mistralPlugin = null;
|
|
37332
|
+
langGraphSDKPlugin = null;
|
|
35469
37333
|
ollamaPlugin = null;
|
|
35470
37334
|
googleADKPlugin = null;
|
|
35471
37335
|
coherePlugin = null;
|
|
@@ -35478,6 +37342,7 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35478
37342
|
langSmithPlugin = null;
|
|
35479
37343
|
piCodingAgentPlugin = null;
|
|
35480
37344
|
strandsAgentSDKPlugin = null;
|
|
37345
|
+
elevenLabsPlugin = null;
|
|
35481
37346
|
voyageAIPlugin = null;
|
|
35482
37347
|
cloudflareAIChatPlugin = null;
|
|
35483
37348
|
cloudflareAgentsPlugin = null;
|
|
@@ -35519,6 +37384,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35519
37384
|
this.openAIAgentsPlugin = new OpenAIAgentsPlugin();
|
|
35520
37385
|
this.openAIAgentsPlugin.enable();
|
|
35521
37386
|
}
|
|
37387
|
+
if (integrations.googleGenerativeAI !== false) {
|
|
37388
|
+
this.googleGenerativeAIPlugin = new GoogleGenerativeAIPlugin();
|
|
37389
|
+
this.googleGenerativeAIPlugin.enable();
|
|
37390
|
+
}
|
|
35522
37391
|
if (integrations.googleGenAI !== false && integrations.google !== false) {
|
|
35523
37392
|
this.googleGenAIPlugin = new GoogleGenAIPlugin();
|
|
35524
37393
|
this.googleGenAIPlugin.enable();
|
|
@@ -35541,6 +37410,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35541
37410
|
this.mistralPlugin = new MistralPlugin();
|
|
35542
37411
|
this.mistralPlugin.enable();
|
|
35543
37412
|
}
|
|
37413
|
+
if (integrations.langgraphSDK !== false) {
|
|
37414
|
+
this.langGraphSDKPlugin = new LangGraphSDKPlugin();
|
|
37415
|
+
this.langGraphSDKPlugin.enable();
|
|
37416
|
+
}
|
|
35544
37417
|
if (integrations.ollama !== false) {
|
|
35545
37418
|
this.ollamaPlugin = new OllamaPlugin();
|
|
35546
37419
|
this.ollamaPlugin.enable();
|
|
@@ -35553,6 +37426,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35553
37426
|
this.coherePlugin = new CoherePlugin();
|
|
35554
37427
|
this.coherePlugin.enable();
|
|
35555
37428
|
}
|
|
37429
|
+
if (integrations.elevenlabs !== false) {
|
|
37430
|
+
this.elevenLabsPlugin = new ElevenLabsPlugin();
|
|
37431
|
+
this.elevenLabsPlugin.enable();
|
|
37432
|
+
}
|
|
35556
37433
|
if (integrations.voyageai !== false) {
|
|
35557
37434
|
this.voyageAIPlugin = new VoyageAIPlugin();
|
|
35558
37435
|
this.voyageAIPlugin.enable();
|
|
@@ -35637,6 +37514,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35637
37514
|
this.openAIAgentsPlugin.disable();
|
|
35638
37515
|
this.openAIAgentsPlugin = null;
|
|
35639
37516
|
}
|
|
37517
|
+
if (this.googleGenerativeAIPlugin) {
|
|
37518
|
+
this.googleGenerativeAIPlugin.disable();
|
|
37519
|
+
this.googleGenerativeAIPlugin = null;
|
|
37520
|
+
}
|
|
35640
37521
|
if (this.googleGenAIPlugin) {
|
|
35641
37522
|
this.googleGenAIPlugin.disable();
|
|
35642
37523
|
this.googleGenAIPlugin = null;
|
|
@@ -35661,6 +37542,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35661
37542
|
this.mistralPlugin.disable();
|
|
35662
37543
|
this.mistralPlugin = null;
|
|
35663
37544
|
}
|
|
37545
|
+
if (this.langGraphSDKPlugin) {
|
|
37546
|
+
this.langGraphSDKPlugin.disable();
|
|
37547
|
+
this.langGraphSDKPlugin = null;
|
|
37548
|
+
}
|
|
35664
37549
|
if (this.ollamaPlugin) {
|
|
35665
37550
|
this.ollamaPlugin.disable();
|
|
35666
37551
|
this.ollamaPlugin = null;
|
|
@@ -35673,6 +37558,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
35673
37558
|
this.coherePlugin.disable();
|
|
35674
37559
|
this.coherePlugin = null;
|
|
35675
37560
|
}
|
|
37561
|
+
if (this.elevenLabsPlugin) {
|
|
37562
|
+
this.elevenLabsPlugin.disable();
|
|
37563
|
+
this.elevenLabsPlugin = null;
|
|
37564
|
+
}
|
|
35676
37565
|
if (this.voyageAIPlugin) {
|
|
35677
37566
|
this.voyageAIPlugin.disable();
|
|
35678
37567
|
this.voyageAIPlugin = null;
|
|
@@ -36503,6 +38392,7 @@ export {
|
|
|
36503
38392
|
IDGenerator,
|
|
36504
38393
|
UUIDGenerator,
|
|
36505
38394
|
OTELIDGenerator,
|
|
38395
|
+
resolveUseLegacyUuidIds,
|
|
36506
38396
|
getIdGenerator,
|
|
36507
38397
|
TRACEPARENT_HEADER,
|
|
36508
38398
|
TRACESTATE_HEADER,
|
|
@@ -36591,6 +38481,7 @@ export {
|
|
|
36591
38481
|
currentLogger,
|
|
36592
38482
|
currentSpan,
|
|
36593
38483
|
getSpanParentObject,
|
|
38484
|
+
_internalExportParentSynchronously,
|
|
36594
38485
|
injectTraceContext,
|
|
36595
38486
|
extractTraceContextFromHeaders,
|
|
36596
38487
|
logError,
|