@traceloop/instrumentation-bedrock 0.5.21 → 0.5.24

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.
@@ -0,0 +1,29 @@
1
+ import { InstrumentationConfig, InstrumentationBase, InstrumentationModuleDefinition } from '@opentelemetry/instrumentation';
2
+ import * as bedrock from '@aws-sdk/client-bedrock-runtime';
3
+
4
+ interface BedrockInstrumentationConfig extends InstrumentationConfig {
5
+ /**
6
+ * Whether to log prompts, completions and embeddings on traces.
7
+ * @default true
8
+ */
9
+ traceContent?: boolean;
10
+ }
11
+
12
+ declare class BedrockInstrumentation extends InstrumentationBase<any> {
13
+ protected _config: BedrockInstrumentationConfig;
14
+ constructor(config?: BedrockInstrumentationConfig);
15
+ setConfig(config?: BedrockInstrumentationConfig): void;
16
+ protected init(): InstrumentationModuleDefinition<any>;
17
+ manuallyInstrument(module: typeof bedrock): void;
18
+ private wrap;
19
+ private unwrap;
20
+ private wrapperMethod;
21
+ private _wrapPromise;
22
+ private _startSpan;
23
+ private _endSpan;
24
+ private _setRequestAttributes;
25
+ private _setResponseAttributes;
26
+ private _shouldSendPrompts;
27
+ }
28
+
29
+ export { BedrockInstrumentation, type BedrockInstrumentationConfig };
package/dist/index.js ADDED
@@ -0,0 +1,271 @@
1
+ 'use strict';
2
+
3
+ var tslib = require('tslib');
4
+ var api = require('@opentelemetry/api');
5
+ var instrumentation = require('@opentelemetry/instrumentation');
6
+ var aiSemanticConventions = require('@traceloop/ai-semantic-conventions');
7
+
8
+ var version = "0.5.23";
9
+
10
+ class BedrockInstrumentation extends instrumentation.InstrumentationBase {
11
+ constructor(config = {}) {
12
+ super("@traceloop/instrumentation-bedrock", version, config);
13
+ }
14
+ setConfig(config = {}) {
15
+ super.setConfig(config);
16
+ }
17
+ init() {
18
+ const module = new instrumentation.InstrumentationNodeModuleDefinition("@aws-sdk/client-bedrock-runtime", [">=3.499.0"], this.wrap.bind(this), this.unwrap.bind(this));
19
+ return module;
20
+ }
21
+ manuallyInstrument(module) {
22
+ this._diag.debug(`Patching @aws-sdk/client-bedrock-runtime manually`);
23
+ this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
24
+ }
25
+ wrap(module, moduleVersion) {
26
+ this._diag.debug(`Patching @aws-sdk/client-bedrock-runtime@${moduleVersion}`);
27
+ this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
28
+ return module;
29
+ }
30
+ unwrap(module, moduleVersion) {
31
+ this._diag.debug(`Unpatching @aws-sdk/client-bedrock-runtime@${moduleVersion}`);
32
+ this._unwrap(module.BedrockRuntimeClient.prototype, "send");
33
+ }
34
+ wrapperMethod() {
35
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
36
+ const plugin = this;
37
+ // eslint-disable-next-line @typescript-eslint/ban-types
38
+ return (original) => {
39
+ return function method(...args) {
40
+ const span = plugin._startSpan({
41
+ params: args[0],
42
+ });
43
+ const execContext = api.trace.setSpan(api.context.active(), span);
44
+ const execPromise = instrumentation.safeExecuteInTheMiddle(() => {
45
+ return api.context.with(execContext, () => {
46
+ return original.apply(this, args);
47
+ });
48
+ }, (e) => {
49
+ if (e) {
50
+ plugin._diag.error(`Error in bedrock instrumentation`, e);
51
+ }
52
+ });
53
+ const wrappedPromise = plugin._wrapPromise(span, execPromise);
54
+ return api.context.bind(execContext, wrappedPromise);
55
+ };
56
+ };
57
+ }
58
+ _wrapPromise(span, promise) {
59
+ return promise
60
+ .then((result) => tslib.__awaiter(this, void 0, void 0, function* () {
61
+ yield this._endSpan({
62
+ span,
63
+ result: result,
64
+ });
65
+ return new Promise((resolve) => resolve(result));
66
+ }))
67
+ .catch((error) => {
68
+ return new Promise((_, reject) => {
69
+ span.setStatus({
70
+ code: api.SpanStatusCode.ERROR,
71
+ message: error.message,
72
+ });
73
+ span.recordException(error);
74
+ span.end();
75
+ reject(error);
76
+ });
77
+ });
78
+ }
79
+ _startSpan({ params, }) {
80
+ const [vendor, model] = params.input.modelId
81
+ ? params.input.modelId.split(".")
82
+ : ["", ""];
83
+ let attributes = {
84
+ [aiSemanticConventions.SpanAttributes.LLM_VENDOR]: vendor,
85
+ [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MODEL]: model,
86
+ [aiSemanticConventions.SpanAttributes.LLM_RESPONSE_MODEL]: model,
87
+ [aiSemanticConventions.SpanAttributes.LLM_REQUEST_TYPE]: aiSemanticConventions.LLMRequestTypeValues.COMPLETION,
88
+ };
89
+ if (typeof params.input.body === "string") {
90
+ const requestBody = JSON.parse(params.input.body);
91
+ attributes = Object.assign(Object.assign({}, attributes), this._setRequestAttributes(vendor, requestBody));
92
+ }
93
+ return this.tracer.startSpan(`bedrock.completion`, {
94
+ kind: api.SpanKind.CLIENT,
95
+ attributes,
96
+ });
97
+ }
98
+ _endSpan({ span, result, }) {
99
+ var _a, e_1, _b, _c;
100
+ var _d;
101
+ return tslib.__awaiter(this, void 0, void 0, function* () {
102
+ if ("body" in result) {
103
+ const attributes = "attributes" in span ? span["attributes"] : {};
104
+ if (aiSemanticConventions.SpanAttributes.LLM_VENDOR in attributes) {
105
+ if (!(result.body instanceof Object.getPrototypeOf(Uint8Array))) {
106
+ const rawRes = result.body;
107
+ let streamedContent = "";
108
+ try {
109
+ for (var _e = true, rawRes_1 = tslib.__asyncValues(rawRes), rawRes_1_1; rawRes_1_1 = yield rawRes_1.next(), _a = rawRes_1_1.done, !_a; _e = true) {
110
+ _c = rawRes_1_1.value;
111
+ _e = false;
112
+ const value = _c;
113
+ // Convert it to a JSON String
114
+ const jsonString = new TextDecoder().decode((_d = value.chunk) === null || _d === void 0 ? void 0 : _d.bytes);
115
+ // Parse the JSON string
116
+ const parsedResponse = JSON.parse(jsonString);
117
+ if ("amazon-bedrock-invocationMetrics" in parsedResponse) {
118
+ span.setAttribute(aiSemanticConventions.SpanAttributes.LLM_USAGE_PROMPT_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"]);
119
+ span.setAttribute(aiSemanticConventions.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
120
+ span.setAttribute(aiSemanticConventions.SpanAttributes.LLM_USAGE_TOTAL_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"] +
121
+ parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
122
+ }
123
+ let responseAttributes = this._setResponseAttributes(attributes[aiSemanticConventions.SpanAttributes.LLM_VENDOR], parsedResponse, true);
124
+ // ! NOTE: This make sure the content always have all streamed chunks
125
+ if (this._shouldSendPrompts()) {
126
+ // Update local value with attribute value that was set by _setResponseAttributes
127
+ streamedContent +=
128
+ responseAttributes[`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`];
129
+ // re-assign the new value to responseAttributes
130
+ responseAttributes = Object.assign(Object.assign({}, responseAttributes), { [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: streamedContent });
131
+ }
132
+ span.setAttributes(responseAttributes);
133
+ }
134
+ }
135
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
136
+ finally {
137
+ try {
138
+ if (!_e && !_a && (_b = rawRes_1.return)) yield _b.call(rawRes_1);
139
+ }
140
+ finally { if (e_1) throw e_1.error; }
141
+ }
142
+ }
143
+ else if (result.body instanceof Object.getPrototypeOf(Uint8Array)) {
144
+ // Convert it to a JSON String
145
+ const jsonString = new TextDecoder().decode(result.body);
146
+ // Parse the JSON string
147
+ const parsedResponse = JSON.parse(jsonString);
148
+ const responseAttributes = this._setResponseAttributes(attributes[aiSemanticConventions.SpanAttributes.LLM_VENDOR], parsedResponse);
149
+ span.setAttributes(responseAttributes);
150
+ }
151
+ }
152
+ }
153
+ span.setStatus({ code: api.SpanStatusCode.OK });
154
+ span.end();
155
+ });
156
+ }
157
+ _setRequestAttributes(vendor, requestBody) {
158
+ switch (vendor) {
159
+ case "ai21": {
160
+ return Object.assign({ [aiSemanticConventions.SpanAttributes.LLM_TOP_P]: requestBody["topP"], [aiSemanticConventions.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["maxTokens"], [aiSemanticConventions.SpanAttributes.LLM_PRESENCE_PENALTY]: requestBody["presencePenalty"]["scale"], [aiSemanticConventions.SpanAttributes.LLM_FREQUENCY_PENALTY]: requestBody["frequencyPenalty"]["scale"] }, (this._shouldSendPrompts()
161
+ ? {
162
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
163
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
164
+ }
165
+ : {}));
166
+ }
167
+ case "amazon": {
168
+ return Object.assign({ [aiSemanticConventions.SpanAttributes.LLM_TOP_P]: requestBody["textGenerationConfig"]["topP"], [aiSemanticConventions.SpanAttributes.LLM_TEMPERATURE]: requestBody["textGenerationConfig"]["temperature"], [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["textGenerationConfig"]["maxTokenCount"] }, (this._shouldSendPrompts()
169
+ ? {
170
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
171
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["inputText"],
172
+ }
173
+ : {}));
174
+ }
175
+ case "anthropic": {
176
+ return Object.assign({ [aiSemanticConventions.SpanAttributes.LLM_TOP_P]: requestBody["top_p"], [aiSemanticConventions.SpanAttributes.LLM_TOP_K]: requestBody["top_k"], [aiSemanticConventions.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_tokens_to_sample"] }, (this._shouldSendPrompts()
177
+ ? {
178
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
179
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"]
180
+ // The format is removing when we are setting span attribute
181
+ .replace("\n\nHuman:", "")
182
+ .replace("\n\nAssistant:", ""),
183
+ }
184
+ : {}));
185
+ }
186
+ case "cohere": {
187
+ return Object.assign({ [aiSemanticConventions.SpanAttributes.LLM_TOP_P]: requestBody["p"], [aiSemanticConventions.SpanAttributes.LLM_TOP_K]: requestBody["k"], [aiSemanticConventions.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_tokens"] }, (this._shouldSendPrompts()
188
+ ? {
189
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
190
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
191
+ }
192
+ : {}));
193
+ }
194
+ case "meta": {
195
+ return Object.assign({ [aiSemanticConventions.SpanAttributes.LLM_TOP_P]: requestBody["top_p"], [aiSemanticConventions.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_gen_len"] }, (this._shouldSendPrompts()
196
+ ? {
197
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
198
+ [`${aiSemanticConventions.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
199
+ }
200
+ : {}));
201
+ }
202
+ default:
203
+ return {};
204
+ }
205
+ }
206
+ _setResponseAttributes(vendor, response, isStream = false) {
207
+ switch (vendor) {
208
+ case "ai21": {
209
+ return Object.assign({ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["completions"][0]["finishReason"]["reason"], [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
210
+ ? {
211
+ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completions"][0]["data"]["text"],
212
+ }
213
+ : {}));
214
+ }
215
+ case "amazon": {
216
+ return Object.assign({ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: isStream
217
+ ? response["completionReason"]
218
+ : response["results"][0]["completionReason"], [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant", [aiSemanticConventions.SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: response["inputTextTokenCount"], [aiSemanticConventions.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: isStream
219
+ ? response["totalOutputTextTokenCount"]
220
+ : response["results"][0]["tokenCount"], [aiSemanticConventions.SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: isStream
221
+ ? response["inputTextTokenCount"] +
222
+ response["totalOutputTextTokenCount"]
223
+ : response["inputTextTokenCount"] +
224
+ response["results"][0]["tokenCount"] }, (this._shouldSendPrompts()
225
+ ? {
226
+ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: isStream
227
+ ? response["outputText"]
228
+ : response["results"][0]["outputText"],
229
+ }
230
+ : {}));
231
+ }
232
+ case "anthropic": {
233
+ return Object.assign({ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["stop_reason"], [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
234
+ ? {
235
+ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completion"],
236
+ }
237
+ : {}));
238
+ }
239
+ case "cohere": {
240
+ return Object.assign({ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["generations"][0]["finish_reason"], [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
241
+ ? {
242
+ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generations"][0]["text"],
243
+ }
244
+ : {}));
245
+ }
246
+ case "meta": {
247
+ return Object.assign({ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["stop_reason"], [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant", [aiSemanticConventions.SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: response["prompt_token_count"], [aiSemanticConventions.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: response["generation_token_count"], [aiSemanticConventions.SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: response["prompt_token_count"] + response["generation_token_count"] }, (this._shouldSendPrompts()
248
+ ? {
249
+ [`${aiSemanticConventions.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generation"],
250
+ }
251
+ : {}));
252
+ }
253
+ default:
254
+ return {};
255
+ }
256
+ }
257
+ _shouldSendPrompts() {
258
+ const contextShouldSendPrompts = api.context
259
+ .active()
260
+ .getValue(aiSemanticConventions.CONTEXT_KEY_ALLOW_TRACE_CONTENT);
261
+ if (contextShouldSendPrompts !== undefined) {
262
+ return contextShouldSendPrompts;
263
+ }
264
+ return this._config.traceContent !== undefined
265
+ ? this._config.traceContent
266
+ : true;
267
+ }
268
+ }
269
+
270
+ exports.BedrockInstrumentation = BedrockInstrumentation;
271
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright Traceloop\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Span,\n Attributes,\n SpanKind,\n SpanStatusCode,\n context,\n trace,\n} from \"@opentelemetry/api\";\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from \"@opentelemetry/instrumentation\";\nimport { BedrockInstrumentationConfig } from \"./types\";\nimport type * as bedrock from \"@aws-sdk/client-bedrock-runtime\";\nimport {\n CONTEXT_KEY_ALLOW_TRACE_CONTENT,\n LLMRequestTypeValues,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { version } from \"../package.json\";\n\nexport class BedrockInstrumentation extends InstrumentationBase<any> {\n protected declare _config: BedrockInstrumentationConfig;\n\n constructor(config: BedrockInstrumentationConfig = {}) {\n super(\"@traceloop/instrumentation-bedrock\", version, config);\n }\n\n public override setConfig(config: BedrockInstrumentationConfig = {}) {\n super.setConfig(config);\n }\n\n protected init(): InstrumentationModuleDefinition<any> {\n const module = new InstrumentationNodeModuleDefinition<any>(\n \"@aws-sdk/client-bedrock-runtime\",\n [\">=3.499.0\"],\n this.wrap.bind(this),\n this.unwrap.bind(this),\n );\n\n return module;\n }\n\n public manuallyInstrument(module: typeof bedrock) {\n this._diag.debug(`Patching @aws-sdk/client-bedrock-runtime manually`);\n\n this._wrap(\n module.BedrockRuntimeClient.prototype,\n \"send\",\n this.wrapperMethod(),\n );\n }\n\n private wrap(module: typeof bedrock, moduleVersion?: string) {\n this._diag.debug(\n `Patching @aws-sdk/client-bedrock-runtime@${moduleVersion}`,\n );\n\n this._wrap(\n module.BedrockRuntimeClient.prototype,\n \"send\",\n this.wrapperMethod(),\n );\n\n return module;\n }\n\n private unwrap(module: typeof bedrock, moduleVersion?: string) {\n this._diag.debug(\n `Unpatching @aws-sdk/client-bedrock-runtime@${moduleVersion}`,\n );\n\n this._unwrap(module.BedrockRuntimeClient.prototype, \"send\");\n }\n\n private wrapperMethod() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const plugin = this;\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (original: Function) => {\n return function method(this: any, ...args: any) {\n const span = plugin._startSpan({\n params: args[0],\n });\n const execContext = trace.setSpan(context.active(), span);\n const execPromise = safeExecuteInTheMiddle(\n () => {\n return context.with(execContext, () => {\n return original.apply(this, args);\n });\n },\n (e) => {\n if (e) {\n plugin._diag.error(`Error in bedrock instrumentation`, e);\n }\n },\n );\n const wrappedPromise = plugin._wrapPromise(span, execPromise);\n return context.bind(execContext, wrappedPromise);\n };\n };\n }\n private _wrapPromise<T>(span: Span, promise: Promise<T>): Promise<T> {\n return promise\n .then(async (result) => {\n await this._endSpan({\n span,\n result: result as\n | bedrock.InvokeModelCommandOutput\n | bedrock.InvokeModelWithResponseStreamCommandOutput,\n });\n\n return new Promise<T>((resolve) => resolve(result));\n })\n .catch((error: Error) => {\n return new Promise<T>((_, reject) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n\n reject(error);\n });\n });\n }\n\n private _startSpan({\n params,\n }: {\n params: Parameters<bedrock.BedrockRuntimeClient[\"send\"]>[0];\n }): Span {\n const [vendor, model] = params.input.modelId\n ? params.input.modelId.split(\".\")\n : [\"\", \"\"];\n\n let attributes: Attributes = {\n [SpanAttributes.LLM_VENDOR]: vendor,\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n [SpanAttributes.LLM_RESPONSE_MODEL]: model,\n [SpanAttributes.LLM_REQUEST_TYPE]: LLMRequestTypeValues.COMPLETION,\n };\n\n if (typeof params.input.body === \"string\") {\n const requestBody = JSON.parse(params.input.body);\n\n attributes = {\n ...attributes,\n ...this._setRequestAttributes(vendor, requestBody),\n };\n }\n\n return this.tracer.startSpan(`bedrock.completion`, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n private async _endSpan({\n span,\n result,\n }: {\n span: Span;\n result:\n | bedrock.InvokeModelCommandOutput\n | bedrock.InvokeModelWithResponseStreamCommandOutput;\n }) {\n if (\"body\" in result) {\n const attributes =\n \"attributes\" in span ? (span[\"attributes\"] as Record<string, any>) : {};\n\n if (SpanAttributes.LLM_VENDOR in attributes) {\n if (!(result.body instanceof Object.getPrototypeOf(Uint8Array))) {\n const rawRes = result.body as AsyncIterable<bedrock.ResponseStream>;\n\n let streamedContent = \"\";\n for await (const value of rawRes) {\n // Convert it to a JSON String\n const jsonString = new TextDecoder().decode(value.chunk?.bytes);\n // Parse the JSON string\n const parsedResponse = JSON.parse(jsonString);\n\n if (\"amazon-bedrock-invocationMetrics\" in parsedResponse) {\n span.setAttribute(\n SpanAttributes.LLM_USAGE_PROMPT_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"inputTokenCount\"\n ],\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_COMPLETION_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"outputTokenCount\"\n ],\n );\n\n span.setAttribute(\n SpanAttributes.LLM_USAGE_TOTAL_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"inputTokenCount\"\n ] +\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"outputTokenCount\"\n ],\n );\n }\n\n let responseAttributes = this._setResponseAttributes(\n attributes[SpanAttributes.LLM_VENDOR],\n parsedResponse,\n true,\n );\n\n // ! NOTE: This make sure the content always have all streamed chunks\n if (this._shouldSendPrompts()) {\n // Update local value with attribute value that was set by _setResponseAttributes\n streamedContent +=\n responseAttributes[\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`\n ];\n // re-assign the new value to responseAttributes\n responseAttributes = {\n ...responseAttributes,\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n streamedContent,\n };\n }\n\n span.setAttributes(responseAttributes);\n }\n } else if (result.body instanceof Object.getPrototypeOf(Uint8Array)) {\n // Convert it to a JSON String\n const jsonString = new TextDecoder().decode(\n result.body as Uint8Array,\n );\n // Parse the JSON string\n const parsedResponse = JSON.parse(jsonString);\n\n const responseAttributes = this._setResponseAttributes(\n attributes[SpanAttributes.LLM_VENDOR],\n parsedResponse,\n );\n\n span.setAttributes(responseAttributes);\n }\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n }\n\n private _setRequestAttributes(\n vendor: string,\n requestBody: Record<string, any>,\n ) {\n switch (vendor) {\n case \"ai21\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"topP\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"maxTokens\"],\n [SpanAttributes.LLM_PRESENCE_PENALTY]:\n requestBody[\"presencePenalty\"][\"scale\"],\n [SpanAttributes.LLM_FREQUENCY_PENALTY]:\n requestBody[\"frequencyPenalty\"][\"scale\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n case \"amazon\": {\n return {\n [SpanAttributes.LLM_TOP_P]:\n requestBody[\"textGenerationConfig\"][\"topP\"],\n [SpanAttributes.LLM_TEMPERATURE]:\n requestBody[\"textGenerationConfig\"][\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]:\n requestBody[\"textGenerationConfig\"][\"maxTokenCount\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"inputText\"],\n }\n : {}),\n };\n }\n case \"anthropic\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"top_p\"],\n [SpanAttributes.LLM_TOP_K]: requestBody[\"top_k\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]:\n requestBody[\"max_tokens_to_sample\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody[\n \"prompt\"\n ]\n // The format is removing when we are setting span attribute\n .replace(\"\\n\\nHuman:\", \"\")\n .replace(\"\\n\\nAssistant:\", \"\"),\n }\n : {}),\n };\n }\n case \"cohere\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"p\"],\n [SpanAttributes.LLM_TOP_K]: requestBody[\"k\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"max_tokens\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n case \"meta\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"top_p\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"max_gen_len\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n default:\n return {};\n }\n }\n\n private _setResponseAttributes(\n vendor: string,\n response: Record<string, any>,\n isStream = false,\n ) {\n switch (vendor) {\n case \"ai21\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"completions\"][0][\"finishReason\"][\"reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"completions\"][0][\"data\"][\"text\"],\n }\n : {}),\n };\n }\n case \"amazon\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: isStream\n ? response[\"completionReason\"]\n : response[\"results\"][0][\"completionReason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]:\n response[\"inputTextTokenCount\"],\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: isStream\n ? response[\"totalOutputTextTokenCount\"]\n : response[\"results\"][0][\"tokenCount\"],\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: isStream\n ? response[\"inputTextTokenCount\"] +\n response[\"totalOutputTextTokenCount\"]\n : response[\"inputTextTokenCount\"] +\n response[\"results\"][0][\"tokenCount\"],\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]: isStream\n ? response[\"outputText\"]\n : response[\"results\"][0][\"outputText\"],\n }\n : {}),\n };\n }\n case \"anthropic\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"stop_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"completion\"],\n }\n : {}),\n };\n }\n case \"cohere\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"generations\"][0][\"finish_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"generations\"][0][\"text\"],\n }\n : {}),\n };\n }\n case \"meta\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"stop_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]:\n response[\"prompt_token_count\"],\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]:\n response[\"generation_token_count\"],\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]:\n response[\"prompt_token_count\"] + response[\"generation_token_count\"],\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"generation\"],\n }\n : {}),\n };\n }\n default:\n return {};\n }\n }\n\n private _shouldSendPrompts() {\n const contextShouldSendPrompts = context\n .active()\n .getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);\n\n if (contextShouldSendPrompts !== undefined) {\n return contextShouldSendPrompts;\n }\n\n return this._config.traceContent !== undefined\n ? this._config.traceContent\n : true;\n }\n}\n"],"names":["InstrumentationBase","InstrumentationNodeModuleDefinition","trace","context","safeExecuteInTheMiddle","__awaiter","SpanStatusCode","SpanAttributes","LLMRequestTypeValues","SpanKind","__asyncValues","CONTEXT_KEY_ALLOW_TRACE_CONTENT"],"mappings":";;;;;;;;;AAsCM,MAAO,sBAAuB,SAAQA,mCAAwB,CAAA;AAGlE,IAAA,WAAA,CAAY,SAAuC,EAAE,EAAA;AACnD,QAAA,KAAK,CAAC,oCAAoC,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;KAC9D;IAEe,SAAS,CAAC,SAAuC,EAAE,EAAA;AACjE,QAAA,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;KACzB;IAES,IAAI,GAAA;AACZ,QAAA,MAAM,MAAM,GAAG,IAAIC,mDAAmC,CACpD,iCAAiC,EACjC,CAAC,WAAW,CAAC,EACb,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EACpB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CACvB,CAAC;AAEF,QAAA,OAAO,MAAM,CAAC;KACf;AAEM,IAAA,kBAAkB,CAAC,MAAsB,EAAA;AAC9C,QAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,C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AAC,YAAY,CAAC;AACzB,qBAAA;sBACD,EAAE,EACN,CAAA;aACH;AACD,YAAA;AACE,gBAAA,OAAO,EAAE,CAAC;SACb;KACF;IAEO,kBAAkB,GAAA;QACxB,MAAM,wBAAwB,GAAGJ,WAAO;AACrC,aAAA,MAAM,EAAE;aACR,QAAQ,CAACQ,qDAA+B,CAAC,CAAC;AAE7C,QAAA,IAAI,wBAAwB,KAAK,SAAS,EAAE;AAC1C,YAAA,OAAO,wBAAwB,CAAC;SACjC;AAED,QAAA,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS;AAC5C,cAAE,IAAI,CAAC,OAAO,CAAC,YAAY;cACzB,IAAI,CAAC;KACV;AACF;;;;"}
@@ -1,6 +1,6 @@
1
1
  import { InstrumentationBase, InstrumentationModuleDefinition } from "@opentelemetry/instrumentation";
2
2
  import { BedrockInstrumentationConfig } from "./types";
3
- import * as bedrock from "@aws-sdk/client-bedrock-runtime";
3
+ import type * as bedrock from "@aws-sdk/client-bedrock-runtime";
4
4
  export declare class BedrockInstrumentation extends InstrumentationBase<any> {
5
5
  protected _config: BedrockInstrumentationConfig;
6
6
  constructor(config?: BedrockInstrumentationConfig);
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ai21.test.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=amazon.test.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=anthropic.test.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cohere.test.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=meta.test.d.ts.map
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@traceloop/instrumentation-bedrock",
3
- "version": "0.5.21",
3
+ "version": "0.5.24",
4
4
  "description": "Amazon Bedrock Instrumentation",
5
- "main": "dist/src/index.js",
6
- "types": "dist/src/index.d.ts",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
7
8
  "repository": "traceloop/openllmetry-js",
8
9
  "scripts": {
9
- "build": "tsc --build tsconfig.json",
10
+ "build": "rollup -c",
10
11
  "lint": "eslint . --ext .ts",
11
12
  "lint:fix": "eslint . --ext .ts --fix",
12
13
  "test": "ts-mocha -p tsconfig.json 'tests/**/*.test.ts' --timeout 20000"
@@ -24,9 +25,9 @@
24
25
  "node": ">=14"
25
26
  },
26
27
  "files": [
27
- "dist/src/**/*.js",
28
- "dist/src/**/*.js.map",
29
- "dist/src/**/*.d.ts",
28
+ "dist/**/*.js",
29
+ "dist/**/*.js.map",
30
+ "dist/**/*.d.ts",
30
31
  "doc",
31
32
  "LICENSE",
32
33
  "README.md",
@@ -48,5 +49,5 @@
48
49
  "@pollyjs/persister-fs": "^6.0.6"
49
50
  },
50
51
  "homepage": "https://github.com/traceloop/openllmetry-js/tree/main/packages/instrumentation-openai",
51
- "gitHead": "f2708ee34a64d85c7826cd135b3dedac4b26c38c"
52
+ "gitHead": "0225fcda81fc0d1673052470e26b4b5e75116032"
52
53
  }
package/dist/src/index.js DELETED
@@ -1,34 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright Traceloop
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
- };
31
- Object.defineProperty(exports, "__esModule", { value: true });
32
- __exportStar(require("./instrumentation"), exports);
33
- __exportStar(require("./types"), exports);
34
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,oDAAkC;AAClC,0CAAwB","sourcesContent":["/*\n * Copyright Traceloop\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from \"./instrumentation\";\nexport * from \"./types\";\n"]}
@@ -1,293 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __asyncValues = (this && this.__asyncValues) || function (o) {
12
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
- var m = o[Symbol.asyncIterator], i;
14
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
- };
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.BedrockInstrumentation = void 0;
20
- /*
21
- * Copyright Traceloop
22
- *
23
- * Licensed under the Apache License, Version 2.0 (the "License");
24
- * you may not use this file except in compliance with the License.
25
- * You may obtain a copy of the License at
26
- *
27
- * https://www.apache.org/licenses/LICENSE-2.0
28
- *
29
- * Unless required by applicable law or agreed to in writing, software
30
- * distributed under the License is distributed on an "AS IS" BASIS,
31
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
- * See the License for the specific language governing permissions and
33
- * limitations under the License.
34
- */
35
- const api_1 = require("@opentelemetry/api");
36
- const instrumentation_1 = require("@opentelemetry/instrumentation");
37
- const ai_semantic_conventions_1 = require("@traceloop/ai-semantic-conventions");
38
- class BedrockInstrumentation extends instrumentation_1.InstrumentationBase {
39
- constructor(config = {}) {
40
- super("@traceloop/instrumentation-bedrock", "0.3.0", config);
41
- }
42
- setConfig(config = {}) {
43
- super.setConfig(config);
44
- }
45
- init() {
46
- const module = new instrumentation_1.InstrumentationNodeModuleDefinition("@aws-sdk/client-bedrock-runtime", [">=3.499.0"], this.wrap.bind(this), this.unwrap.bind(this));
47
- return module;
48
- }
49
- manuallyInstrument(module) {
50
- this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
51
- }
52
- wrap(module) {
53
- this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
54
- return module;
55
- }
56
- unwrap(module) {
57
- this._unwrap(module.BedrockRuntimeClient.prototype, "send");
58
- }
59
- wrapperMethod() {
60
- // eslint-disable-next-line @typescript-eslint/no-this-alias
61
- const plugin = this;
62
- // eslint-disable-next-line @typescript-eslint/ban-types
63
- return (original) => {
64
- return function method(...args) {
65
- const span = plugin._startSpan({
66
- params: args[0],
67
- });
68
- const execContext = api_1.trace.setSpan(api_1.context.active(), span);
69
- const execPromise = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
70
- return api_1.context.with(execContext, () => {
71
- return original.apply(this, args);
72
- });
73
- },
74
- // eslint-disable-next-line @typescript-eslint/no-empty-function
75
- () => { });
76
- const wrappedPromise = plugin._wrapPromise(span, execPromise);
77
- return api_1.context.bind(execContext, wrappedPromise);
78
- };
79
- };
80
- }
81
- _wrapPromise(span, promise) {
82
- return promise
83
- .then((result) => __awaiter(this, void 0, void 0, function* () {
84
- yield this._endSpan({
85
- span,
86
- result: result,
87
- });
88
- return new Promise((resolve) => resolve(result));
89
- }))
90
- .catch((error) => {
91
- return new Promise((_, reject) => {
92
- span.setStatus({
93
- code: api_1.SpanStatusCode.ERROR,
94
- message: error.message,
95
- });
96
- span.recordException(error);
97
- span.end();
98
- reject(error);
99
- });
100
- });
101
- }
102
- _startSpan({ params, }) {
103
- const [vendor, model] = params.input.modelId
104
- ? params.input.modelId.split(".")
105
- : ["", ""];
106
- let attributes = {
107
- [ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR]: vendor,
108
- [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MODEL]: model,
109
- [ai_semantic_conventions_1.SpanAttributes.LLM_RESPONSE_MODEL]: model,
110
- [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_TYPE]: ai_semantic_conventions_1.LLMRequestTypeValues.COMPLETION,
111
- };
112
- if (typeof params.input.body === "string") {
113
- const requestBody = JSON.parse(params.input.body);
114
- attributes = Object.assign(Object.assign({}, attributes), this._setRequestAttributes(vendor, requestBody));
115
- }
116
- return this.tracer.startSpan(`bedrock.completion`, {
117
- kind: api_1.SpanKind.CLIENT,
118
- attributes,
119
- });
120
- }
121
- _endSpan({ span, result, }) {
122
- var _a, e_1, _b, _c;
123
- var _d;
124
- return __awaiter(this, void 0, void 0, function* () {
125
- if ("body" in result) {
126
- const attributes = "attributes" in span ? span["attributes"] : {};
127
- if (ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR in attributes) {
128
- if (!(result.body instanceof Object.getPrototypeOf(Uint8Array))) {
129
- const rawRes = result.body;
130
- let streamedContent = "";
131
- try {
132
- for (var _e = true, rawRes_1 = __asyncValues(rawRes), rawRes_1_1; rawRes_1_1 = yield rawRes_1.next(), _a = rawRes_1_1.done, !_a; _e = true) {
133
- _c = rawRes_1_1.value;
134
- _e = false;
135
- const value = _c;
136
- // Convert it to a JSON String
137
- const jsonString = new TextDecoder().decode((_d = value.chunk) === null || _d === void 0 ? void 0 : _d.bytes);
138
- // Parse the JSON string
139
- const parsedResponse = JSON.parse(jsonString);
140
- if ("amazon-bedrock-invocationMetrics" in parsedResponse) {
141
- span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_PROMPT_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"]);
142
- span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
143
- span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_TOTAL_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"] +
144
- parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
145
- }
146
- let responseAttributes = this._setResponseAttributes(attributes[ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR], parsedResponse, true);
147
- // ! NOTE: This make sure the content always have all streamed chunks
148
- if (this._shouldSendPrompts()) {
149
- // Update local value with attribute value that was set by _setResponseAttributes
150
- streamedContent +=
151
- responseAttributes[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`];
152
- // re-assign the new value to responseAttributes
153
- responseAttributes = Object.assign(Object.assign({}, responseAttributes), { [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: streamedContent });
154
- }
155
- span.setAttributes(responseAttributes);
156
- }
157
- }
158
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
159
- finally {
160
- try {
161
- if (!_e && !_a && (_b = rawRes_1.return)) yield _b.call(rawRes_1);
162
- }
163
- finally { if (e_1) throw e_1.error; }
164
- }
165
- }
166
- else if (result.body instanceof Object.getPrototypeOf(Uint8Array)) {
167
- // Convert it to a JSON String
168
- const jsonString = new TextDecoder().decode(result.body);
169
- // Parse the JSON string
170
- const parsedResponse = JSON.parse(jsonString);
171
- const responseAttributes = this._setResponseAttributes(attributes[ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR], parsedResponse);
172
- span.setAttributes(responseAttributes);
173
- }
174
- }
175
- }
176
- span.setStatus({ code: api_1.SpanStatusCode.OK });
177
- span.end();
178
- });
179
- }
180
- _setRequestAttributes(vendor, requestBody) {
181
- switch (vendor) {
182
- case "ai21": {
183
- return Object.assign({ [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_P]: requestBody["topP"], [ai_semantic_conventions_1.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["maxTokens"], [ai_semantic_conventions_1.SpanAttributes.LLM_PRESENCE_PENALTY]: requestBody["presencePenalty"]["scale"], [ai_semantic_conventions_1.SpanAttributes.LLM_FREQUENCY_PENALTY]: requestBody["frequencyPenalty"]["scale"] }, (this._shouldSendPrompts()
184
- ? {
185
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
186
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
187
- }
188
- : {}));
189
- }
190
- case "amazon": {
191
- return Object.assign({ [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_P]: requestBody["textGenerationConfig"]["topP"], [ai_semantic_conventions_1.SpanAttributes.LLM_TEMPERATURE]: requestBody["textGenerationConfig"]["temperature"], [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["textGenerationConfig"]["maxTokenCount"] }, (this._shouldSendPrompts()
192
- ? {
193
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
194
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["inputText"],
195
- }
196
- : {}));
197
- }
198
- case "anthropic": {
199
- return Object.assign({ [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_P]: requestBody["top_p"], [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_K]: requestBody["top_k"], [ai_semantic_conventions_1.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_tokens_to_sample"] }, (this._shouldSendPrompts()
200
- ? {
201
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
202
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"]
203
- // The format is removing when we are setting span attribute
204
- .replace("\n\nHuman:", "")
205
- .replace("\n\nAssistant:", ""),
206
- }
207
- : {}));
208
- }
209
- case "cohere": {
210
- return Object.assign({ [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_P]: requestBody["p"], [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_K]: requestBody["k"], [ai_semantic_conventions_1.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_tokens"] }, (this._shouldSendPrompts()
211
- ? {
212
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
213
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
214
- }
215
- : {}));
216
- }
217
- case "meta": {
218
- return Object.assign({ [ai_semantic_conventions_1.SpanAttributes.LLM_TOP_P]: requestBody["top_p"], [ai_semantic_conventions_1.SpanAttributes.LLM_TEMPERATURE]: requestBody["temperature"], [ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody["max_gen_len"] }, (this._shouldSendPrompts()
219
- ? {
220
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
221
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
222
- }
223
- : {}));
224
- }
225
- default:
226
- return {};
227
- }
228
- }
229
- _setResponseAttributes(vendor, response, isStream = false) {
230
- switch (vendor) {
231
- case "ai21": {
232
- return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["completions"][0]["finishReason"]["reason"], [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
233
- ? {
234
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completions"][0]["data"]["text"],
235
- }
236
- : {}));
237
- }
238
- case "amazon": {
239
- return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: isStream
240
- ? response["completionReason"]
241
- : response["results"][0]["completionReason"], [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant", [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: response["inputTextTokenCount"], [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: isStream
242
- ? response["totalOutputTextTokenCount"]
243
- : response["results"][0]["tokenCount"], [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: isStream
244
- ? response["inputTextTokenCount"] +
245
- response["totalOutputTextTokenCount"]
246
- : response["inputTextTokenCount"] +
247
- response["results"][0]["tokenCount"] }, (this._shouldSendPrompts()
248
- ? {
249
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: isStream
250
- ? response["outputText"]
251
- : response["results"][0]["outputText"],
252
- }
253
- : {}));
254
- }
255
- case "anthropic": {
256
- return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["stop_reason"], [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
257
- ? {
258
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completion"],
259
- }
260
- : {}));
261
- }
262
- case "cohere": {
263
- return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["generations"][0]["finish_reason"], [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant" }, (this._shouldSendPrompts()
264
- ? {
265
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generations"][0]["text"],
266
- }
267
- : {}));
268
- }
269
- case "meta": {
270
- return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: response["stop_reason"], [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.role`]: "assistant", [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_PROMPT_TOKENS]: response["prompt_token_count"], [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: response["generation_token_count"], [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: response["prompt_token_count"] + response["generation_token_count"] }, (this._shouldSendPrompts()
271
- ? {
272
- [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generation"],
273
- }
274
- : {}));
275
- }
276
- default:
277
- return {};
278
- }
279
- }
280
- _shouldSendPrompts() {
281
- const contextShouldSendPrompts = api_1.context
282
- .active()
283
- .getValue(ai_semantic_conventions_1.CONTEXT_KEY_ALLOW_TRACE_CONTENT);
284
- if (contextShouldSendPrompts !== undefined) {
285
- return contextShouldSendPrompts;
286
- }
287
- return this._config.traceContent !== undefined
288
- ? this._config.traceContent
289
- : true;
290
- }
291
- }
292
- exports.BedrockInstrumentation = BedrockInstrumentation;
293
- //# sourceMappingURL=instrumentation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAO4B;AAC5B,oEAKwC;AAGxC,gFAI4C;AAE5C,MAAa,sBAAuB,SAAQ,qCAAwB;IAGlE,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,oCAAoC,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAC/D,CAAC;IAEe,SAAS,CAAC,SAAuC,EAAE;QACjE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAES,IAAI;QACZ,MAAM,MAAM,GAAG,IAAI,qDAAmC,CACpD,iCAAiC,EACjC,CAAC,WAAW,CAAC,EACb,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EACpB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CACvB,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC;IAEM,kBAAkB,CAAC,MAAsB;QAC9C,IAAI,CAAC,KAAK,CACR,MAAM,CAAC,oBAAoB,CAAC,SAAS,EACrC,MAAM,EACN,IAAI,CAAC,aAAa,EAAE,CACr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CAAC,oBAAoB,CAAC,EAChC,CAAC,wCAAc,CAAC,2BAA2B,CAAC,EAC1C,QAAQ,CAAC,wBAAwB,CAAC,EACpC,CAAC,wCAAc,CAAC,sBAAsB,CAAC,EACrC,QAAQ,CAAC,oBAAoB,CAAC,GAAG,QAAQ,CAAC,wBAAwB,CAAC,IAClE,CAAC,IAAI,CAAC,kBAAkB,EAAE;oBAC3B,CAAC,CAAC;wBACE,CAAC,GAAG,wCAAc,CAAC,eAAe,YAAY,CAAC,EAC7C,QAAQ,CAAC,YAAY,CAAC;qBACzB;oBACH,CAAC,CAAC,EAAE,CAAC,EACP;YACJ,CAAC;YACD;gBACE,OAAO,EAAE,CAAC;QACd,CAAC;IACH,CAAC;IAEO,kBAAkB;QACxB,MAAM,wBAAwB,GAAG,aAAO;aACrC,MAAM,EAAE;aACR,QAAQ,CAAC,yDAA+B,CAAC,CAAC;QAE7C,IAAI,wBAAwB,KAAK,SAAS,EAAE,CAAC;YAC3C,OAAO,wBAAwB,CAAC;QAClC,CAAC;QAED,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS;YAC5C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY;YAC3B,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;CACF;AA9aD,wDA8aC","sourcesContent":["/*\n * Copyright Traceloop\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Span,\n Attributes,\n SpanKind,\n SpanStatusCode,\n context,\n trace,\n} from \"@opentelemetry/api\";\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from \"@opentelemetry/instrumentation\";\nimport { BedrockInstrumentationConfig } from \"./types\";\nimport * as bedrock from \"@aws-sdk/client-bedrock-runtime\";\nimport {\n CONTEXT_KEY_ALLOW_TRACE_CONTENT,\n LLMRequestTypeValues,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\n\nexport class BedrockInstrumentation extends InstrumentationBase<any> {\n protected override _config!: BedrockInstrumentationConfig;\n\n constructor(config: BedrockInstrumentationConfig = {}) {\n super(\"@traceloop/instrumentation-bedrock\", \"0.3.0\", config);\n }\n\n public override setConfig(config: BedrockInstrumentationConfig = {}) {\n super.setConfig(config);\n }\n\n protected init(): InstrumentationModuleDefinition<any> {\n const module = new InstrumentationNodeModuleDefinition<any>(\n \"@aws-sdk/client-bedrock-runtime\",\n [\">=3.499.0\"],\n this.wrap.bind(this),\n this.unwrap.bind(this),\n );\n\n return module;\n }\n\n public manuallyInstrument(module: typeof bedrock) {\n this._wrap(\n module.BedrockRuntimeClient.prototype,\n \"send\",\n this.wrapperMethod(),\n );\n }\n\n private wrap(module: typeof bedrock) {\n this._wrap(\n module.BedrockRuntimeClient.prototype,\n \"send\",\n this.wrapperMethod(),\n );\n\n return module;\n }\n\n private unwrap(module: typeof bedrock) {\n this._unwrap(module.BedrockRuntimeClient.prototype, \"send\");\n }\n\n private wrapperMethod() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const plugin = this;\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (original: Function) => {\n return function method(this: any, ...args: any) {\n const span = plugin._startSpan({\n params: args[0],\n });\n const execContext = trace.setSpan(context.active(), span);\n const execPromise = safeExecuteInTheMiddle(\n () => {\n return context.with(execContext, () => {\n return original.apply(this, args);\n });\n },\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n () => {},\n );\n const wrappedPromise = plugin._wrapPromise(span, execPromise);\n return context.bind(execContext, wrappedPromise);\n };\n };\n }\n private _wrapPromise<T>(span: Span, promise: Promise<T>): Promise<T> {\n return promise\n .then(async (result) => {\n await this._endSpan({\n span,\n result: result as\n | bedrock.InvokeModelCommandOutput\n | bedrock.InvokeModelWithResponseStreamCommandOutput,\n });\n\n return new Promise<T>((resolve) => resolve(result));\n })\n .catch((error: Error) => {\n return new Promise<T>((_, reject) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n\n reject(error);\n });\n });\n }\n\n private _startSpan({\n params,\n }: {\n params: Parameters<bedrock.BedrockRuntimeClient[\"send\"]>[0];\n }): Span {\n const [vendor, model] = params.input.modelId\n ? params.input.modelId.split(\".\")\n : [\"\", \"\"];\n\n let attributes: Attributes = {\n [SpanAttributes.LLM_VENDOR]: vendor,\n [SpanAttributes.LLM_REQUEST_MODEL]: model,\n [SpanAttributes.LLM_RESPONSE_MODEL]: model,\n [SpanAttributes.LLM_REQUEST_TYPE]: LLMRequestTypeValues.COMPLETION,\n };\n\n if (typeof params.input.body === \"string\") {\n const requestBody = JSON.parse(params.input.body);\n\n attributes = {\n ...attributes,\n ...this._setRequestAttributes(vendor, requestBody),\n };\n }\n\n return this.tracer.startSpan(`bedrock.completion`, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n private async _endSpan({\n span,\n result,\n }: {\n span: Span;\n result:\n | bedrock.InvokeModelCommandOutput\n | bedrock.InvokeModelWithResponseStreamCommandOutput;\n }) {\n if (\"body\" in result) {\n const attributes =\n \"attributes\" in span ? (span[\"attributes\"] as Record<string, any>) : {};\n\n if (SpanAttributes.LLM_VENDOR in attributes) {\n if (!(result.body instanceof Object.getPrototypeOf(Uint8Array))) {\n const rawRes = result.body as AsyncIterable<bedrock.ResponseStream>;\n\n let streamedContent = \"\";\n for await (const value of rawRes) {\n // Convert it to a JSON String\n const jsonString = new TextDecoder().decode(value.chunk?.bytes);\n // Parse the JSON string\n const parsedResponse = JSON.parse(jsonString);\n\n if (\"amazon-bedrock-invocationMetrics\" in parsedResponse) {\n span.setAttribute(\n SpanAttributes.LLM_USAGE_PROMPT_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"inputTokenCount\"\n ],\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_COMPLETION_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"outputTokenCount\"\n ],\n );\n\n span.setAttribute(\n SpanAttributes.LLM_USAGE_TOTAL_TOKENS,\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"inputTokenCount\"\n ] +\n parsedResponse[\"amazon-bedrock-invocationMetrics\"][\n \"outputTokenCount\"\n ],\n );\n }\n\n let responseAttributes = this._setResponseAttributes(\n attributes[SpanAttributes.LLM_VENDOR],\n parsedResponse,\n true,\n );\n\n // ! NOTE: This make sure the content always have all streamed chunks\n if (this._shouldSendPrompts()) {\n // Update local value with attribute value that was set by _setResponseAttributes\n streamedContent +=\n responseAttributes[\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`\n ];\n // re-assign the new value to responseAttributes\n responseAttributes = {\n ...responseAttributes,\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n streamedContent,\n };\n }\n\n span.setAttributes(responseAttributes);\n }\n } else if (result.body instanceof Object.getPrototypeOf(Uint8Array)) {\n // Convert it to a JSON String\n const jsonString = new TextDecoder().decode(\n result.body as Uint8Array,\n );\n // Parse the JSON string\n const parsedResponse = JSON.parse(jsonString);\n\n const responseAttributes = this._setResponseAttributes(\n attributes[SpanAttributes.LLM_VENDOR],\n parsedResponse,\n );\n\n span.setAttributes(responseAttributes);\n }\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n }\n\n private _setRequestAttributes(\n vendor: string,\n requestBody: Record<string, any>,\n ) {\n switch (vendor) {\n case \"ai21\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"topP\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"maxTokens\"],\n [SpanAttributes.LLM_PRESENCE_PENALTY]:\n requestBody[\"presencePenalty\"][\"scale\"],\n [SpanAttributes.LLM_FREQUENCY_PENALTY]:\n requestBody[\"frequencyPenalty\"][\"scale\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n case \"amazon\": {\n return {\n [SpanAttributes.LLM_TOP_P]:\n requestBody[\"textGenerationConfig\"][\"topP\"],\n [SpanAttributes.LLM_TEMPERATURE]:\n requestBody[\"textGenerationConfig\"][\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]:\n requestBody[\"textGenerationConfig\"][\"maxTokenCount\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"inputText\"],\n }\n : {}),\n };\n }\n case \"anthropic\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"top_p\"],\n [SpanAttributes.LLM_TOP_K]: requestBody[\"top_k\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]:\n requestBody[\"max_tokens_to_sample\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody[\n \"prompt\"\n ]\n // The format is removing when we are setting span attribute\n .replace(\"\\n\\nHuman:\", \"\")\n .replace(\"\\n\\nAssistant:\", \"\"),\n }\n : {}),\n };\n }\n case \"cohere\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"p\"],\n [SpanAttributes.LLM_TOP_K]: requestBody[\"k\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"max_tokens\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n case \"meta\": {\n return {\n [SpanAttributes.LLM_TOP_P]: requestBody[\"top_p\"],\n [SpanAttributes.LLM_TEMPERATURE]: requestBody[\"temperature\"],\n [SpanAttributes.LLM_REQUEST_MAX_TOKENS]: requestBody[\"max_gen_len\"],\n\n // Prompt & Role\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_PROMPTS}.0.role`]: \"user\",\n [`${SpanAttributes.LLM_PROMPTS}.0.content`]:\n requestBody[\"prompt\"],\n }\n : {}),\n };\n }\n default:\n return {};\n }\n }\n\n private _setResponseAttributes(\n vendor: string,\n response: Record<string, any>,\n isStream = false,\n ) {\n switch (vendor) {\n case \"ai21\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"completions\"][0][\"finishReason\"][\"reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"completions\"][0][\"data\"][\"text\"],\n }\n : {}),\n };\n }\n case \"amazon\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: isStream\n ? response[\"completionReason\"]\n : response[\"results\"][0][\"completionReason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]:\n response[\"inputTextTokenCount\"],\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]: isStream\n ? response[\"totalOutputTextTokenCount\"]\n : response[\"results\"][0][\"tokenCount\"],\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: isStream\n ? response[\"inputTextTokenCount\"] +\n response[\"totalOutputTextTokenCount\"]\n : response[\"inputTextTokenCount\"] +\n response[\"results\"][0][\"tokenCount\"],\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]: isStream\n ? response[\"outputText\"]\n : response[\"results\"][0][\"outputText\"],\n }\n : {}),\n };\n }\n case \"anthropic\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"stop_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"completion\"],\n }\n : {}),\n };\n }\n case \"cohere\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"generations\"][0][\"finish_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"generations\"][0][\"text\"],\n }\n : {}),\n };\n }\n case \"meta\": {\n return {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]:\n response[\"stop_reason\"],\n [`${SpanAttributes.LLM_COMPLETIONS}.0.role`]: \"assistant\",\n [SpanAttributes.LLM_USAGE_PROMPT_TOKENS]:\n response[\"prompt_token_count\"],\n [SpanAttributes.LLM_USAGE_COMPLETION_TOKENS]:\n response[\"generation_token_count\"],\n [SpanAttributes.LLM_USAGE_TOTAL_TOKENS]:\n response[\"prompt_token_count\"] + response[\"generation_token_count\"],\n ...(this._shouldSendPrompts()\n ? {\n [`${SpanAttributes.LLM_COMPLETIONS}.0.content`]:\n response[\"generation\"],\n }\n : {}),\n };\n }\n default:\n return {};\n }\n }\n\n private _shouldSendPrompts() {\n const contextShouldSendPrompts = context\n .active()\n .getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);\n\n if (contextShouldSendPrompts !== undefined) {\n return contextShouldSendPrompts;\n }\n\n return this._config.traceContent !== undefined\n ? this._config.traceContent\n : true;\n }\n}\n"]}
package/dist/src/types.js DELETED
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import { InstrumentationConfig } from \"@opentelemetry/instrumentation\";\n\nexport interface BedrockInstrumentationConfig extends InstrumentationConfig {\n /**\n * Whether to log prompts, completions and embeddings on traces.\n * @default true\n */\n traceContent?: boolean;\n}\n"]}