@arizeai/openinference-instrumentation-beeai 1.0.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.
Files changed (158) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +80 -0
  3. package/dist/esm/config.d.ts +39 -0
  4. package/dist/esm/config.d.ts.map +1 -0
  5. package/dist/esm/config.js +39 -0
  6. package/dist/esm/config.js.map +1 -0
  7. package/dist/esm/helpers/buildTraceTree.d.ts +21 -0
  8. package/dist/esm/helpers/buildTraceTree.d.ts.map +1 -0
  9. package/dist/esm/helpers/buildTraceTree.js +71 -0
  10. package/dist/esm/helpers/buildTraceTree.js.map +1 -0
  11. package/dist/esm/helpers/create-span.d.ts +32 -0
  12. package/dist/esm/helpers/create-span.d.ts.map +1 -0
  13. package/dist/esm/helpers/create-span.js +42 -0
  14. package/dist/esm/helpers/create-span.js.map +1 -0
  15. package/dist/esm/helpers/getErrorSafe.d.ts +17 -0
  16. package/dist/esm/helpers/getErrorSafe.d.ts.map +1 -0
  17. package/dist/esm/helpers/getErrorSafe.js +24 -0
  18. package/dist/esm/helpers/getErrorSafe.js.map +1 -0
  19. package/dist/esm/helpers/getSerializedObjectSafe.d.ts +18 -0
  20. package/dist/esm/helpers/getSerializedObjectSafe.d.ts.map +1 -0
  21. package/dist/esm/helpers/getSerializedObjectSafe.js +217 -0
  22. package/dist/esm/helpers/getSerializedObjectSafe.js.map +1 -0
  23. package/dist/esm/helpers/idNameManager.d.ts +31 -0
  24. package/dist/esm/helpers/idNameManager.d.ts.map +1 -0
  25. package/dist/esm/helpers/idNameManager.js +50 -0
  26. package/dist/esm/helpers/idNameManager.js.map +1 -0
  27. package/dist/esm/helpers/traceSerializer.d.ts +19 -0
  28. package/dist/esm/helpers/traceSerializer.d.ts.map +1 -0
  29. package/dist/esm/helpers/traceSerializer.js +35 -0
  30. package/dist/esm/helpers/traceSerializer.js.map +1 -0
  31. package/dist/esm/index.d.ts +2 -0
  32. package/dist/esm/index.d.ts.map +1 -0
  33. package/dist/esm/index.js +2 -0
  34. package/dist/esm/index.js.map +1 -0
  35. package/dist/esm/instrumentation.d.ts +34 -0
  36. package/dist/esm/instrumentation.d.ts.map +1 -0
  37. package/dist/esm/instrumentation.js +71 -0
  38. package/dist/esm/instrumentation.js.map +1 -0
  39. package/dist/esm/middleware.d.ts +27 -0
  40. package/dist/esm/middleware.d.ts.map +1 -0
  41. package/dist/esm/middleware.js +247 -0
  42. package/dist/esm/middleware.js.map +1 -0
  43. package/dist/esm/package.json +1 -0
  44. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  45. package/dist/esm/types.d.ts +36 -0
  46. package/dist/esm/types.d.ts.map +1 -0
  47. package/dist/esm/types.js +17 -0
  48. package/dist/esm/types.js.map +1 -0
  49. package/dist/esnext/config.d.ts +39 -0
  50. package/dist/esnext/config.d.ts.map +1 -0
  51. package/dist/esnext/config.js +39 -0
  52. package/dist/esnext/config.js.map +1 -0
  53. package/dist/esnext/helpers/buildTraceTree.d.ts +21 -0
  54. package/dist/esnext/helpers/buildTraceTree.d.ts.map +1 -0
  55. package/dist/esnext/helpers/buildTraceTree.js +57 -0
  56. package/dist/esnext/helpers/buildTraceTree.js.map +1 -0
  57. package/dist/esnext/helpers/create-span.d.ts +32 -0
  58. package/dist/esnext/helpers/create-span.d.ts.map +1 -0
  59. package/dist/esnext/helpers/create-span.js +37 -0
  60. package/dist/esnext/helpers/create-span.js.map +1 -0
  61. package/dist/esnext/helpers/getErrorSafe.d.ts +17 -0
  62. package/dist/esnext/helpers/getErrorSafe.d.ts.map +1 -0
  63. package/dist/esnext/helpers/getErrorSafe.js +24 -0
  64. package/dist/esnext/helpers/getErrorSafe.js.map +1 -0
  65. package/dist/esnext/helpers/getSerializedObjectSafe.d.ts +18 -0
  66. package/dist/esnext/helpers/getSerializedObjectSafe.d.ts.map +1 -0
  67. package/dist/esnext/helpers/getSerializedObjectSafe.js +165 -0
  68. package/dist/esnext/helpers/getSerializedObjectSafe.js.map +1 -0
  69. package/dist/esnext/helpers/idNameManager.d.ts +31 -0
  70. package/dist/esnext/helpers/idNameManager.d.ts.map +1 -0
  71. package/dist/esnext/helpers/idNameManager.js +50 -0
  72. package/dist/esnext/helpers/idNameManager.js.map +1 -0
  73. package/dist/esnext/helpers/traceSerializer.d.ts +19 -0
  74. package/dist/esnext/helpers/traceSerializer.d.ts.map +1 -0
  75. package/dist/esnext/helpers/traceSerializer.js +35 -0
  76. package/dist/esnext/helpers/traceSerializer.js.map +1 -0
  77. package/dist/esnext/index.d.ts +2 -0
  78. package/dist/esnext/index.d.ts.map +1 -0
  79. package/dist/esnext/index.js +2 -0
  80. package/dist/esnext/index.js.map +1 -0
  81. package/dist/esnext/instrumentation.d.ts +34 -0
  82. package/dist/esnext/instrumentation.d.ts.map +1 -0
  83. package/dist/esnext/instrumentation.js +71 -0
  84. package/dist/esnext/instrumentation.js.map +1 -0
  85. package/dist/esnext/middleware.d.ts +27 -0
  86. package/dist/esnext/middleware.d.ts.map +1 -0
  87. package/dist/esnext/middleware.js +241 -0
  88. package/dist/esnext/middleware.js.map +1 -0
  89. package/dist/esnext/tsconfig.esnext.tsbuildinfo +1 -0
  90. package/dist/esnext/types.d.ts +36 -0
  91. package/dist/esnext/types.d.ts.map +1 -0
  92. package/dist/esnext/types.js +17 -0
  93. package/dist/esnext/types.js.map +1 -0
  94. package/dist/examples/bee.d.ts +2 -0
  95. package/dist/examples/bee.d.ts.map +1 -0
  96. package/dist/examples/bee.js +35 -0
  97. package/dist/examples/bee.js.map +1 -0
  98. package/dist/examples/instrumentation.d.ts +2 -0
  99. package/dist/examples/instrumentation.d.ts.map +1 -0
  100. package/dist/examples/instrumentation.js +54 -0
  101. package/dist/examples/instrumentation.js.map +1 -0
  102. package/dist/src/config.d.ts +39 -0
  103. package/dist/src/config.d.ts.map +1 -0
  104. package/dist/src/config.js +42 -0
  105. package/dist/src/config.js.map +1 -0
  106. package/dist/src/helpers/buildTraceTree.d.ts +21 -0
  107. package/dist/src/helpers/buildTraceTree.d.ts.map +1 -0
  108. package/dist/src/helpers/buildTraceTree.js +60 -0
  109. package/dist/src/helpers/buildTraceTree.js.map +1 -0
  110. package/dist/src/helpers/create-span.d.ts +32 -0
  111. package/dist/src/helpers/create-span.d.ts.map +1 -0
  112. package/dist/src/helpers/create-span.js +40 -0
  113. package/dist/src/helpers/create-span.js.map +1 -0
  114. package/dist/src/helpers/getErrorSafe.d.ts +17 -0
  115. package/dist/src/helpers/getErrorSafe.d.ts.map +1 -0
  116. package/dist/src/helpers/getErrorSafe.js +27 -0
  117. package/dist/src/helpers/getErrorSafe.js.map +1 -0
  118. package/dist/src/helpers/getSerializedObjectSafe.d.ts +18 -0
  119. package/dist/src/helpers/getSerializedObjectSafe.d.ts.map +1 -0
  120. package/dist/src/helpers/getSerializedObjectSafe.js +168 -0
  121. package/dist/src/helpers/getSerializedObjectSafe.js.map +1 -0
  122. package/dist/src/helpers/idNameManager.d.ts +31 -0
  123. package/dist/src/helpers/idNameManager.d.ts.map +1 -0
  124. package/dist/src/helpers/idNameManager.js +54 -0
  125. package/dist/src/helpers/idNameManager.js.map +1 -0
  126. package/dist/src/helpers/traceSerializer.d.ts +19 -0
  127. package/dist/src/helpers/traceSerializer.d.ts.map +1 -0
  128. package/dist/src/helpers/traceSerializer.js +38 -0
  129. package/dist/src/helpers/traceSerializer.js.map +1 -0
  130. package/dist/src/index.d.ts +2 -0
  131. package/dist/src/index.d.ts.map +1 -0
  132. package/dist/src/index.js +18 -0
  133. package/dist/src/index.js.map +1 -0
  134. package/dist/src/instrumentation.d.ts +34 -0
  135. package/dist/src/instrumentation.d.ts.map +1 -0
  136. package/dist/src/instrumentation.js +76 -0
  137. package/dist/src/instrumentation.js.map +1 -0
  138. package/dist/src/middleware.d.ts +27 -0
  139. package/dist/src/middleware.d.ts.map +1 -0
  140. package/dist/src/middleware.js +254 -0
  141. package/dist/src/middleware.js.map +1 -0
  142. package/dist/src/types.d.ts +36 -0
  143. package/dist/src/types.d.ts.map +1 -0
  144. package/dist/src/types.js +18 -0
  145. package/dist/src/types.js.map +1 -0
  146. package/dist/tsconfig.tsbuildinfo +1 -0
  147. package/package.json +64 -0
  148. package/src/config.ts +48 -0
  149. package/src/helpers/buildTraceTree.ts +118 -0
  150. package/src/helpers/create-span.ts +66 -0
  151. package/src/helpers/getErrorSafe.ts +26 -0
  152. package/src/helpers/getSerializedObjectSafe.ts +325 -0
  153. package/src/helpers/idNameManager.ts +53 -0
  154. package/src/helpers/traceSerializer.ts +46 -0
  155. package/src/index.ts +1 -0
  156. package/src/instrumentation.ts +123 -0
  157. package/src/middleware.ts +318 -0
  158. package/src/types.ts +38 -0
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Copyright 2025 IBM Corp.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const DEFAULT_IGNORE_KEYS = [
18
+ "emitter",
19
+ "logger",
20
+ "tokens",
21
+ "createdBy",
22
+ "client",
23
+ ];
24
+
25
+ export function traceSerializer({
26
+ ignored_keys = [],
27
+ }: {
28
+ ignored_keys?: string[];
29
+ }) {
30
+ const mergedIgnoreKeys = new Set([...DEFAULT_IGNORE_KEYS, ...ignored_keys]);
31
+
32
+ return (body: object) =>
33
+ JSON.stringify(
34
+ body,
35
+ (() => {
36
+ return (key, value) => {
37
+ // Ignore specific keys, all owned entities and keys starting with underscore
38
+ if (mergedIgnoreKeys.has(key) || key.startsWith("_")) {
39
+ return;
40
+ }
41
+
42
+ return value;
43
+ };
44
+ })(),
45
+ );
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./instrumentation";
@@ -0,0 +1,123 @@
1
+ import {
2
+ InstrumentationBase,
3
+ InstrumentationNodeModuleDefinition,
4
+ InstrumentationConfig,
5
+ } from "@opentelemetry/instrumentation";
6
+ import { diag } from "@opentelemetry/api";
7
+ import { Version } from "beeai-framework";
8
+ import * as bee from "beeai-framework";
9
+
10
+ import { OITracer, TraceConfigOptions } from "@arizeai/openinference-core";
11
+ import { createTelemetryMiddleware } from "./middleware";
12
+
13
+ const MODULE_NAME = "beeai-framework";
14
+
15
+ /**
16
+ * Flag to check if the openai module has been patched
17
+ * Note: This is a fallback in case the module is made immutable (e.x. Deno, webpack, etc.)
18
+ */
19
+ let _isOpenInferencePatched = false;
20
+
21
+ /**
22
+ * function to check if instrumentation is enabled / disabled
23
+ */
24
+ export function isPatched() {
25
+ return _isOpenInferencePatched;
26
+ }
27
+
28
+ export class BeeAIInstrumentation extends InstrumentationBase {
29
+ private oiTracer: OITracer;
30
+
31
+ constructor({
32
+ instrumentationConfig,
33
+ traceConfig,
34
+ }: {
35
+ /**
36
+ * The config for the instrumentation
37
+ * @see {@link InstrumentationConfig}
38
+ */
39
+ instrumentationConfig?: InstrumentationConfig;
40
+ /**
41
+ * The OpenInference trace configuration. Can be used to mask or redact sensitive information on spans.
42
+ * @see {@link TraceConfigOptions}
43
+ */
44
+ traceConfig?: TraceConfigOptions;
45
+ } = {}) {
46
+ super(
47
+ "@arizeai/openinference-instrumentation-beeai",
48
+ Version,
49
+ Object.assign({}, instrumentationConfig),
50
+ );
51
+ this.oiTracer = new OITracer({ tracer: this.tracer, traceConfig });
52
+ }
53
+
54
+ protected init() {
55
+ const module = new InstrumentationNodeModuleDefinition(
56
+ MODULE_NAME,
57
+ ["0.*"],
58
+ this.patch.bind(this),
59
+ this.unpatch.bind(this),
60
+ );
61
+
62
+ return module;
63
+ }
64
+
65
+ /**
66
+ * Manually instruments the BeeAI module. This is needed when the module is not loaded via require (commonjs)
67
+ * @param {openai} module
68
+ */
69
+ manuallyInstrument(module: typeof bee) {
70
+ diag.debug(`[BeeaiInstrumentation] Manually instrumenting ${MODULE_NAME}`);
71
+ this.patch(module);
72
+ }
73
+
74
+ private patch(module: typeof bee & { openInferencePatched?: boolean }) {
75
+ if (!module?.BaseAgent) {
76
+ diag.warn(
77
+ "[BeeaiInstrumentation] BaseAgent not found, skipping instrumentation.",
78
+ );
79
+ return module;
80
+ }
81
+
82
+ if (module?.openInferencePatched || _isOpenInferencePatched) {
83
+ return module;
84
+ }
85
+
86
+ diag.info("[BeeaiInstrumentation] Patching BaseAgent.run");
87
+
88
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
89
+ const instrumentation: BeeAIInstrumentation = this;
90
+
91
+ this._wrap(module.BaseAgent.prototype, "run", (original) => {
92
+ return function wrappedRun(this: unknown, ...args) {
93
+ const returned = original.apply(this, args);
94
+ returned.middleware(
95
+ createTelemetryMiddleware(instrumentation.oiTracer),
96
+ );
97
+
98
+ return returned;
99
+ };
100
+ });
101
+
102
+ return module;
103
+ }
104
+
105
+ /**
106
+ * Un-patches the OpenAI module's chat completions API
107
+ */
108
+ private unpatch(
109
+ moduleExports: typeof bee & { openInferencePatched?: boolean },
110
+ moduleVersion?: string,
111
+ ) {
112
+ diag.debug(`Removing patch for ${MODULE_NAME}@${moduleVersion}`);
113
+ this._unwrap(moduleExports.BaseAgent.prototype, "run");
114
+
115
+ _isOpenInferencePatched = false;
116
+ try {
117
+ // This can fail if the module is made immutable via the runtime or bundler
118
+ moduleExports.openInferencePatched = false;
119
+ } catch (e) {
120
+ diag.warn(`Failed to unset ${MODULE_NAME} patched flag on the module`, e);
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Copyright 2025 IBM Corp.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { OITracer } from "@arizeai/openinference-core";
18
+ import { getSerializedObjectSafe } from "./helpers/getSerializedObjectSafe";
19
+ import { createSpan } from "./helpers/create-span";
20
+ import { IdNameManager } from "./helpers/idNameManager";
21
+ import { getErrorSafe } from "./helpers/getErrorSafe";
22
+ import { findLast, isEmpty } from "remeda";
23
+ import type { BeeCallbacks } from "beeai-framework/agents/bee/types";
24
+ import type { InferCallbackValue } from "beeai-framework/emitter/types";
25
+ import { FrameworkError } from "beeai-framework/errors";
26
+ import { Version } from "beeai-framework/version";
27
+ import { Role } from "beeai-framework/backend/message";
28
+ import type { GetRunContext, RunInstance } from "beeai-framework/context";
29
+ import { traceSerializer } from "./helpers/traceSerializer";
30
+ import {
31
+ errorLLMEventName,
32
+ finishLLMEventName,
33
+ INSTRUMENTATION_IGNORED_KEYS,
34
+ newTokenLLMEventName,
35
+ partialUpdateEventName,
36
+ successLLMEventName,
37
+ } from "./config";
38
+ import { createFullPath } from "beeai-framework/emitter/utils";
39
+ import type { BeeAgent } from "beeai-framework/agents/bee/agent";
40
+ import { BaseAgent } from "beeai-framework/agents/base";
41
+ import { diag } from "@opentelemetry/api";
42
+ import { FrameworkSpan, GeneratedResponse } from "./types";
43
+ import { buildTraceTree } from "./helpers/buildTraceTree";
44
+ import { SemanticConventions } from "@arizeai/openinference-semantic-conventions";
45
+
46
+ export const activeTracesMap = new Map<string, string>();
47
+
48
+ /**
49
+ * First we collect, filter and transform events from the beeai emitter to our internal framework spans in the `emitter.match("*.*"` block
50
+ * Some special data are collected in other `emitter.match` blocks like (history, response, rawPromt)
51
+ *
52
+ * Then we create the open telemetry spans when all data are collected. We are retroactively deleting some unnecessary internal spans
53
+ * see "emitter.match((event) => event.path === `${basePath}.run.${finishEventName}`" section
54
+ */
55
+ export function createTelemetryMiddleware(tracer: OITracer) {
56
+ return (context: GetRunContext<RunInstance, unknown>) => {
57
+ if (!context.emitter?.trace?.id) {
58
+ throw new FrameworkError(`Fatal error. Missing traceId`, [], { context });
59
+ }
60
+
61
+ const traceId = context.emitter?.trace?.id;
62
+ if (activeTracesMap.has(traceId)) {
63
+ return;
64
+ }
65
+ activeTracesMap.set(traceId, context.instance.constructor.name);
66
+
67
+ diag.debug("createTelemetryMiddleware", {
68
+ source: context.instance.constructor.name,
69
+ traceId: traceId,
70
+ });
71
+ const { emitter, runParams, instance } = context;
72
+ const basePath = createFullPath(emitter.namespace, "");
73
+
74
+ let prompt: string | undefined | null = null;
75
+ if (instance instanceof BaseAgent) {
76
+ prompt = (runParams as Parameters<BeeAgent["run"]>)[0].prompt;
77
+ }
78
+
79
+ const spansMap = new Map<string, FrameworkSpan>();
80
+ const parentIdsMap = new Map<string, number>();
81
+ const spansToDeleteMap = new Map<string, undefined>();
82
+
83
+ let generatedMessage: GeneratedResponse | undefined = undefined;
84
+ let history: GeneratedResponse[] | undefined = undefined;
85
+ const groupIterations: string[] = [];
86
+
87
+ const idNameManager = new IdNameManager();
88
+
89
+ const eventsIterationsMap = new Map<string, Map<string, string>>();
90
+
91
+ const startTimeDate = new Date().getTime();
92
+ const startTimePerf = performance.now();
93
+ function convertDateToPerformance(date: Date) {
94
+ return date.getTime() - startTimeDate + startTimePerf;
95
+ }
96
+
97
+ const serializer = traceSerializer({
98
+ ignored_keys: INSTRUMENTATION_IGNORED_KEYS,
99
+ });
100
+
101
+ function cleanSpanSources({ spanId }: { spanId: string }) {
102
+ const parentId = spansMap.get(spanId)?.parent_id;
103
+ if (!parentId) {
104
+ return;
105
+ }
106
+
107
+ const spanCount = parentIdsMap.get(parentId);
108
+ if (!spanCount) {
109
+ return;
110
+ }
111
+
112
+ if (spanCount > 1) {
113
+ // increase the span count for the parentId
114
+ parentIdsMap.set(parentId, spanCount - 1);
115
+ } else if (spanCount === 1) {
116
+ parentIdsMap.delete(parentId);
117
+ // check the `spansToDelete` if the span should be deleted when it has no children's
118
+ if (spansToDeleteMap.has(parentId)) {
119
+ spansMap.delete(parentId);
120
+ spansToDeleteMap.delete(parentId);
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Create OpenTelemetry spans from collected data
127
+ */
128
+ emitter.match(
129
+ (event) => event.path === `${basePath}.run.${finishLLMEventName}`,
130
+ async (_, meta) => {
131
+ try {
132
+ diag.debug("run finish event", { path: meta.path, traceId: traceId });
133
+
134
+ if (!prompt && instance instanceof BaseAgent) {
135
+ prompt = findLast(
136
+ instance.memory.messages,
137
+ (message) => message.role === Role.USER,
138
+ )?.text;
139
+
140
+ if (!prompt) {
141
+ throw new FrameworkError(
142
+ "The prompt must be defined for the Agent's run",
143
+ [],
144
+ {
145
+ context,
146
+ },
147
+ );
148
+ }
149
+ }
150
+
151
+ // create tracer spans from collected data
152
+ buildTraceTree({
153
+ tracer,
154
+ data: {
155
+ prompt: prompt,
156
+ history,
157
+ generatedMessage,
158
+ spans: JSON.parse(serializer(Array.from(spansMap.values()))),
159
+ traceId,
160
+ version: Version,
161
+ runErrorSpanKey: `${basePath}.run.${errorLLMEventName}`,
162
+ startTime: startTimePerf,
163
+ endTime: performance.now(),
164
+ source: activeTracesMap.get(traceId)!,
165
+ },
166
+ });
167
+ } catch (e) {
168
+ diag.warn("Instrumentation error", e);
169
+ } finally {
170
+ activeTracesMap.delete(traceId);
171
+ }
172
+ },
173
+ );
174
+
175
+ /**
176
+ * This block collects all "not run category" events with their data and prepares spans for the OpenTelemetry.
177
+ * The huge number of `newToken` events are skipped and only the last one for each parent event is saved because of `generated_token_count` information
178
+ * The framework event tree structure is different from the open-telemetry tree structure and must be transformed from groupId and parentGroupId pattern via idNameManager
179
+ * The artificial "iteration" main tree level is computed from the `meta.groupId`
180
+ */
181
+ emitter.match("*.*", (data, meta) => {
182
+ // allow `run.error` event due to the runtime error information
183
+ if (
184
+ meta.path.includes(".run.") &&
185
+ meta.path !== `${basePath}.run.${errorLLMEventName}`
186
+ ) {
187
+ return;
188
+ }
189
+ // skip all new token events
190
+ if (meta.name === newTokenLLMEventName) {
191
+ return;
192
+ }
193
+ if (!meta.trace?.runId) {
194
+ throw new FrameworkError(
195
+ `Fatal error. Missing runId for event: ${meta.path}`,
196
+ [],
197
+ {
198
+ context,
199
+ },
200
+ );
201
+ }
202
+
203
+ /**
204
+ * create groupId span level (id does not exist)
205
+ * I use only the top-level groups like iterations other nested groups like tokens would introduce unuseful complexity
206
+ */
207
+ if (
208
+ meta.groupId &&
209
+ !meta.trace.parentRunId &&
210
+ !groupIterations.includes(meta.groupId)
211
+ ) {
212
+ spansMap.set(
213
+ meta.groupId,
214
+ createSpan({
215
+ id: meta.groupId,
216
+ name: meta.groupId,
217
+ target: "groupId",
218
+ data: {
219
+ [SemanticConventions.OPENINFERENCE_SPAN_KIND]: "Chain",
220
+ },
221
+ startedAt: convertDateToPerformance(meta.createdAt),
222
+ }),
223
+ );
224
+ groupIterations.push(meta.groupId);
225
+ }
226
+
227
+ const { spanId, parentSpanId } = idNameManager.getIds({
228
+ path: meta.path,
229
+ id: meta.id,
230
+ runId: meta.trace.runId,
231
+ parentRunId: meta.trace.parentRunId,
232
+ groupId: meta.groupId,
233
+ });
234
+
235
+ const serializedData = getSerializedObjectSafe(data, meta);
236
+
237
+ // skip partialUpdate events with no data
238
+ if (meta.name === partialUpdateEventName && isEmpty(serializedData)) {
239
+ return;
240
+ }
241
+
242
+ const span = createSpan({
243
+ id: spanId,
244
+ name: meta.name,
245
+ target: meta.path,
246
+ ...(parentSpanId && { parent: { id: parentSpanId } }),
247
+ ctx: meta.context,
248
+ data: serializedData,
249
+ error: getErrorSafe(data),
250
+ startedAt: convertDateToPerformance(meta.createdAt),
251
+ });
252
+
253
+ const lastIteration = groupIterations[groupIterations.length - 1];
254
+
255
+ // delete the `partialUpdate` event if does not have nested spans
256
+ const lastIterationEventSpanId = eventsIterationsMap
257
+ .get(lastIteration)
258
+ ?.get(meta.name);
259
+ if (
260
+ lastIterationEventSpanId &&
261
+ partialUpdateEventName === meta.name &&
262
+ spansMap.has(lastIterationEventSpanId)
263
+ ) {
264
+ const { context } = spansMap.get(lastIterationEventSpanId)!;
265
+ if (parentIdsMap.has(context.span_id)) {
266
+ spansToDeleteMap.set(lastIterationEventSpanId, undefined);
267
+ } else {
268
+ // delete span
269
+ cleanSpanSources({ spanId: lastIterationEventSpanId });
270
+ spansMap.delete(lastIterationEventSpanId);
271
+ }
272
+ }
273
+
274
+ // create new span
275
+ spansMap.set(span.context.span_id, span);
276
+ // update number of nested spans for parent_id if exists
277
+ if (span.parent_id) {
278
+ parentIdsMap.set(
279
+ span.parent_id,
280
+ (parentIdsMap.get(span.parent_id) || 0) + 1,
281
+ );
282
+ }
283
+
284
+ // save the last event for each iteration
285
+ if (groupIterations.length > 0) {
286
+ if (eventsIterationsMap.has(lastIteration)) {
287
+ eventsIterationsMap
288
+ .get(lastIteration)!
289
+ .set(meta.name, span.context.span_id);
290
+ } else {
291
+ eventsIterationsMap.set(
292
+ lastIteration,
293
+ new Map().set(meta.name, span.context.span_id),
294
+ );
295
+ }
296
+ }
297
+ });
298
+
299
+ // The generated response and message history are collected from the `success` agent's event
300
+ emitter.match(
301
+ (event) =>
302
+ event.name === successLLMEventName &&
303
+ event.creator instanceof BaseAgent,
304
+ (data: InferCallbackValue<BeeCallbacks["success"]>) => {
305
+ const { data: dataObject, memory } = data;
306
+
307
+ generatedMessage = {
308
+ role: dataObject.role,
309
+ text: dataObject.text,
310
+ };
311
+ history = memory.messages.map((msg) => ({
312
+ text: msg.text,
313
+ role: msg.role,
314
+ }));
315
+ },
316
+ );
317
+ };
318
+ }
package/src/types.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Copyright 2025 IBM Corp.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { Attributes, SpanStatus, TimeInput } from "@opentelemetry/api";
18
+
19
+ export interface FrameworkSpan {
20
+ attributes: {
21
+ metadata?: Attributes | null;
22
+ data?: Attributes | null;
23
+ target: string;
24
+ };
25
+ context: {
26
+ span_id: string;
27
+ };
28
+ end_time: TimeInput;
29
+ name: string;
30
+ parent_id?: string;
31
+ start_time: TimeInput;
32
+ status: SpanStatus;
33
+ }
34
+
35
+ export interface GeneratedResponse {
36
+ text: string;
37
+ role: string;
38
+ }