@traceloop/instrumentation-bedrock 0.3.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/LICENSE +201 -0
- package/README.md +55 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +34 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/instrumentation.d.ts +20 -0
- package/dist/src/instrumentation.js +274 -0
- package/dist/src/instrumentation.js.map +1 -0
- package/dist/src/types.d.ts +9 -0
- package/dist/src/types.js +3 -0
- package/dist/src/types.js.map +1 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# OpenTelemetry VertexAI instrumentation for Node.js
|
|
2
|
+
|
|
3
|
+
[![NPM Published Version][npm-img]][npm-url]
|
|
4
|
+
[![Apache License][license-image]][license-image]
|
|
5
|
+
|
|
6
|
+
This module provides automatic instrumentation for [`AWS Bedrock Runtime Client SDK`](https://www.npmjs.com/package/@aws-sdk/client-bedrock-runtime?activeTab=readme) module, which may be loaded using the [`@opentelemetry/sdk-trace-node`](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node) package and is included in the [`@traceloop/node-server-sdk`](https://www.npmjs.com/package/@traceloop/node-server-sdk) bundle.
|
|
7
|
+
|
|
8
|
+
If total installation size is not constrained, it is recommended to use the [`@traceloop/node-server-sdk`](https://www.npmjs.com/package/@traceloop/node-server-sdk) bundle for the most seamless instrumentation experience.
|
|
9
|
+
|
|
10
|
+
Compatible with OpenTelemetry JS API and SDK `1.0+`.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install --save @traceloop/instrumentation-bedrock
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Supported Versions
|
|
19
|
+
|
|
20
|
+
- `>=3.499.0`
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
To load a specific plugin, specify it in the registerInstrumentations's configuration:
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
|
|
28
|
+
const {
|
|
29
|
+
BedrockInstrumentation,
|
|
30
|
+
} = require("@traceloop/instrumentation-bedrock");
|
|
31
|
+
const { registerInstrumentations } = require("@opentelemetry/instrumentation");
|
|
32
|
+
|
|
33
|
+
const provider = new NodeTracerProvider();
|
|
34
|
+
provider.register();
|
|
35
|
+
|
|
36
|
+
registerInstrumentations({
|
|
37
|
+
instrumentations: [new BedrockInstrumentation()],
|
|
38
|
+
});
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Useful links
|
|
42
|
+
|
|
43
|
+
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
|
|
44
|
+
- For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
|
|
45
|
+
- For help or feedback on this project, join us on [Slack][slack-url]
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
Apache 2.0 - See [LICENSE][license-url] for more information.
|
|
50
|
+
|
|
51
|
+
[slack-url]: https://traceloop.com/slack
|
|
52
|
+
[license-url]: https://github.com/traceloop/openllmetry-js/blob/main/LICENSE
|
|
53
|
+
[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
|
|
54
|
+
[npm-url]: https://www.npmjs.com/package/@traceloop/instrumentation-openai
|
|
55
|
+
[npm-img]: https://badge.fury.io/js/%40traceloop%2Finstrumentation-openai.svg
|
|
@@ -0,0 +1,34 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { InstrumentationBase, InstrumentationModuleDefinition } from "@opentelemetry/instrumentation";
|
|
2
|
+
import { BedrockInstrumentationConfig } from "./types";
|
|
3
|
+
import * as bedrock from "@aws-sdk/client-bedrock-runtime";
|
|
4
|
+
export declare class BedrockInstrumentation extends InstrumentationBase<any> {
|
|
5
|
+
protected _config: BedrockInstrumentationConfig;
|
|
6
|
+
constructor(config?: BedrockInstrumentationConfig);
|
|
7
|
+
setConfig(config?: BedrockInstrumentationConfig): void;
|
|
8
|
+
protected init(): InstrumentationModuleDefinition<any>;
|
|
9
|
+
manuallyInstrument(module: typeof bedrock): void;
|
|
10
|
+
private wrap;
|
|
11
|
+
private unwrap;
|
|
12
|
+
private wrapperMethod;
|
|
13
|
+
private _wrapPromise;
|
|
14
|
+
private _startSpan;
|
|
15
|
+
private _endSpan;
|
|
16
|
+
private _setRequestAttributes;
|
|
17
|
+
private _setResponseAttributes;
|
|
18
|
+
private _shouldSendPrompts;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=instrumentation.d.ts.map
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
3
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
4
|
+
var m = o[Symbol.asyncIterator], i;
|
|
5
|
+
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);
|
|
6
|
+
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); }); }; }
|
|
7
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
8
|
+
};
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.BedrockInstrumentation = void 0;
|
|
11
|
+
/*
|
|
12
|
+
* Copyright Traceloop
|
|
13
|
+
*
|
|
14
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
15
|
+
* you may not use this file except in compliance with the License.
|
|
16
|
+
* You may obtain a copy of the License at
|
|
17
|
+
*
|
|
18
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
19
|
+
*
|
|
20
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
21
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
22
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
23
|
+
* See the License for the specific language governing permissions and
|
|
24
|
+
* limitations under the License.
|
|
25
|
+
*/
|
|
26
|
+
const api_1 = require("@opentelemetry/api");
|
|
27
|
+
const instrumentation_1 = require("@opentelemetry/instrumentation");
|
|
28
|
+
const ai_semantic_conventions_1 = require("@traceloop/ai-semantic-conventions");
|
|
29
|
+
class BedrockInstrumentation extends instrumentation_1.InstrumentationBase {
|
|
30
|
+
constructor(config = {}) {
|
|
31
|
+
super("@traceloop/instrumentation-bedrock", "0.3.0", config);
|
|
32
|
+
}
|
|
33
|
+
setConfig(config = {}) {
|
|
34
|
+
super.setConfig(config);
|
|
35
|
+
}
|
|
36
|
+
init() {
|
|
37
|
+
const module = new instrumentation_1.InstrumentationNodeModuleDefinition("@aws-sdk/client-bedrock-runtime", [">=3.499.0"], this.wrap.bind(this), this.unwrap.bind(this));
|
|
38
|
+
return module;
|
|
39
|
+
}
|
|
40
|
+
manuallyInstrument(module) {
|
|
41
|
+
this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
|
|
42
|
+
}
|
|
43
|
+
wrap(module) {
|
|
44
|
+
this._wrap(module.BedrockRuntimeClient.prototype, "send", this.wrapperMethod());
|
|
45
|
+
return module;
|
|
46
|
+
}
|
|
47
|
+
unwrap(module) {
|
|
48
|
+
this._unwrap(module.BedrockRuntimeClient.prototype, "send");
|
|
49
|
+
}
|
|
50
|
+
wrapperMethod() {
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
52
|
+
const plugin = this;
|
|
53
|
+
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
54
|
+
return (original) => {
|
|
55
|
+
return function method(...args) {
|
|
56
|
+
const span = plugin._startSpan({
|
|
57
|
+
params: args[0],
|
|
58
|
+
});
|
|
59
|
+
const execContext = api_1.trace.setSpan(api_1.context.active(), span);
|
|
60
|
+
const execPromise = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
|
|
61
|
+
return api_1.context.with(execContext, () => {
|
|
62
|
+
return original.apply(this, args);
|
|
63
|
+
});
|
|
64
|
+
}, () => { });
|
|
65
|
+
const wrappedPromise = plugin._wrapPromise(span, execPromise);
|
|
66
|
+
return api_1.context.bind(execContext, wrappedPromise);
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
_wrapPromise(span, promise) {
|
|
71
|
+
return promise
|
|
72
|
+
.then(async (result) => {
|
|
73
|
+
await this._endSpan({
|
|
74
|
+
span,
|
|
75
|
+
result: result,
|
|
76
|
+
});
|
|
77
|
+
return new Promise((resolve) => resolve(result));
|
|
78
|
+
})
|
|
79
|
+
.catch((error) => {
|
|
80
|
+
return new Promise((_, reject) => {
|
|
81
|
+
span.setStatus({
|
|
82
|
+
code: api_1.SpanStatusCode.ERROR,
|
|
83
|
+
message: error.message,
|
|
84
|
+
});
|
|
85
|
+
span.recordException(error);
|
|
86
|
+
span.end();
|
|
87
|
+
reject(error);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
_startSpan({ params, }) {
|
|
92
|
+
const [vendor, model] = params.input.modelId
|
|
93
|
+
? params.input.modelId.split(".")
|
|
94
|
+
: ["", ""];
|
|
95
|
+
let attributes = {
|
|
96
|
+
[ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR]: vendor,
|
|
97
|
+
[ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_MODEL]: model,
|
|
98
|
+
[ai_semantic_conventions_1.SpanAttributes.LLM_RESPONSE_MODEL]: model,
|
|
99
|
+
[ai_semantic_conventions_1.SpanAttributes.LLM_REQUEST_TYPE]: ai_semantic_conventions_1.LLMRequestTypeValues.COMPLETION,
|
|
100
|
+
};
|
|
101
|
+
if (typeof params.input.body === "string") {
|
|
102
|
+
const requestBody = JSON.parse(params.input.body);
|
|
103
|
+
attributes = Object.assign(Object.assign({}, attributes), this._setRequestAttributes(vendor, requestBody));
|
|
104
|
+
}
|
|
105
|
+
return this.tracer.startSpan(`bedrock.completion`, {
|
|
106
|
+
kind: api_1.SpanKind.CLIENT,
|
|
107
|
+
attributes,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async _endSpan({ span, result, }) {
|
|
111
|
+
var _a, e_1, _b, _c;
|
|
112
|
+
var _d;
|
|
113
|
+
if ("body" in result) {
|
|
114
|
+
const attributes = "attributes" in span ? span["attributes"] : {};
|
|
115
|
+
if (ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR in attributes) {
|
|
116
|
+
if (!(result.body instanceof Object.getPrototypeOf(Uint8Array))) {
|
|
117
|
+
const rawRes = result.body;
|
|
118
|
+
let streamedContent = "";
|
|
119
|
+
try {
|
|
120
|
+
for (var _e = true, rawRes_1 = __asyncValues(rawRes), rawRes_1_1; rawRes_1_1 = await rawRes_1.next(), _a = rawRes_1_1.done, !_a; _e = true) {
|
|
121
|
+
_c = rawRes_1_1.value;
|
|
122
|
+
_e = false;
|
|
123
|
+
const value = _c;
|
|
124
|
+
// Convert it to a JSON String
|
|
125
|
+
const jsonString = new TextDecoder().decode((_d = value.chunk) === null || _d === void 0 ? void 0 : _d.bytes);
|
|
126
|
+
// Parse the JSON string
|
|
127
|
+
const parsedResponse = JSON.parse(jsonString);
|
|
128
|
+
if ("amazon-bedrock-invocationMetrics" in parsedResponse) {
|
|
129
|
+
span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_PROMPT_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"]);
|
|
130
|
+
span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
|
|
131
|
+
span.setAttribute(ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_TOTAL_TOKENS, parsedResponse["amazon-bedrock-invocationMetrics"]["inputTokenCount"] +
|
|
132
|
+
parsedResponse["amazon-bedrock-invocationMetrics"]["outputTokenCount"]);
|
|
133
|
+
}
|
|
134
|
+
let responseAttributes = this._setResponseAttributes(attributes[ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR], parsedResponse, true);
|
|
135
|
+
// ! NOTE: This make sure the content always have all streamed chunks
|
|
136
|
+
if (this._shouldSendPrompts()) {
|
|
137
|
+
// Update local value with attribute value that was set by _setResponseAttributes
|
|
138
|
+
streamedContent +=
|
|
139
|
+
responseAttributes[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`];
|
|
140
|
+
// re-assign the new value to responseAttributes
|
|
141
|
+
responseAttributes = Object.assign(Object.assign({}, responseAttributes), { [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: streamedContent });
|
|
142
|
+
}
|
|
143
|
+
span.setAttributes(responseAttributes);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
147
|
+
finally {
|
|
148
|
+
try {
|
|
149
|
+
if (!_e && !_a && (_b = rawRes_1.return)) await _b.call(rawRes_1);
|
|
150
|
+
}
|
|
151
|
+
finally { if (e_1) throw e_1.error; }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else if (result.body instanceof Object.getPrototypeOf(Uint8Array)) {
|
|
155
|
+
// Convert it to a JSON String
|
|
156
|
+
const jsonString = new TextDecoder().decode(result.body);
|
|
157
|
+
// Parse the JSON string
|
|
158
|
+
const parsedResponse = JSON.parse(jsonString);
|
|
159
|
+
const responseAttributes = this._setResponseAttributes(attributes[ai_semantic_conventions_1.SpanAttributes.LLM_VENDOR], parsedResponse);
|
|
160
|
+
span.setAttributes(responseAttributes);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
span.setStatus({ code: api_1.SpanStatusCode.OK });
|
|
165
|
+
span.end();
|
|
166
|
+
}
|
|
167
|
+
_setRequestAttributes(vendor, requestBody) {
|
|
168
|
+
switch (vendor) {
|
|
169
|
+
case "ai21": {
|
|
170
|
+
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()
|
|
171
|
+
? {
|
|
172
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
|
|
173
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
|
|
174
|
+
}
|
|
175
|
+
: {}));
|
|
176
|
+
}
|
|
177
|
+
case "amazon": {
|
|
178
|
+
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()
|
|
179
|
+
? {
|
|
180
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
|
|
181
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["inputText"],
|
|
182
|
+
}
|
|
183
|
+
: {}));
|
|
184
|
+
}
|
|
185
|
+
case "anthropic": {
|
|
186
|
+
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()
|
|
187
|
+
? {
|
|
188
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
|
|
189
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"]
|
|
190
|
+
// The format is removing when we are setting span attribute
|
|
191
|
+
.replace("\n\nHuman:", "")
|
|
192
|
+
.replace("\n\nAssistant:", ""),
|
|
193
|
+
}
|
|
194
|
+
: {}));
|
|
195
|
+
}
|
|
196
|
+
case "cohere": {
|
|
197
|
+
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()
|
|
198
|
+
? {
|
|
199
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
|
|
200
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
|
|
201
|
+
}
|
|
202
|
+
: {}));
|
|
203
|
+
}
|
|
204
|
+
case "meta": {
|
|
205
|
+
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()
|
|
206
|
+
? {
|
|
207
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.role`]: "user",
|
|
208
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_PROMPTS}.0.content`]: requestBody["prompt"],
|
|
209
|
+
}
|
|
210
|
+
: {}));
|
|
211
|
+
}
|
|
212
|
+
default:
|
|
213
|
+
return {};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
_setResponseAttributes(vendor, response, isStream = false) {
|
|
217
|
+
switch (vendor) {
|
|
218
|
+
case "ai21": {
|
|
219
|
+
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()
|
|
220
|
+
? {
|
|
221
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completions"][0]["data"]["text"],
|
|
222
|
+
}
|
|
223
|
+
: {}));
|
|
224
|
+
}
|
|
225
|
+
case "amazon": {
|
|
226
|
+
return Object.assign({ [`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`]: isStream
|
|
227
|
+
? response["completionReason"]
|
|
228
|
+
: 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
|
|
229
|
+
? response["totalOutputTextTokenCount"]
|
|
230
|
+
: response["results"][0]["tokenCount"], [ai_semantic_conventions_1.SpanAttributes.LLM_USAGE_TOTAL_TOKENS]: isStream
|
|
231
|
+
? response["inputTextTokenCount"] +
|
|
232
|
+
response["totalOutputTextTokenCount"]
|
|
233
|
+
: response["inputTextTokenCount"] +
|
|
234
|
+
response["results"][0]["tokenCount"] }, (this._shouldSendPrompts()
|
|
235
|
+
? {
|
|
236
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: isStream
|
|
237
|
+
? response["outputText"]
|
|
238
|
+
: response["results"][0]["outputText"],
|
|
239
|
+
}
|
|
240
|
+
: {}));
|
|
241
|
+
}
|
|
242
|
+
case "anthropic": {
|
|
243
|
+
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()
|
|
244
|
+
? {
|
|
245
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["completion"],
|
|
246
|
+
}
|
|
247
|
+
: {}));
|
|
248
|
+
}
|
|
249
|
+
case "cohere": {
|
|
250
|
+
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()
|
|
251
|
+
? {
|
|
252
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generations"][0]["text"],
|
|
253
|
+
}
|
|
254
|
+
: {}));
|
|
255
|
+
}
|
|
256
|
+
case "meta": {
|
|
257
|
+
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()
|
|
258
|
+
? {
|
|
259
|
+
[`${ai_semantic_conventions_1.SpanAttributes.LLM_COMPLETIONS}.0.content`]: response["generation"],
|
|
260
|
+
}
|
|
261
|
+
: {}));
|
|
262
|
+
}
|
|
263
|
+
default:
|
|
264
|
+
return {};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
_shouldSendPrompts() {
|
|
268
|
+
return this._config.traceContent !== undefined
|
|
269
|
+
? this._config.traceContent
|
|
270
|
+
: true;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
exports.BedrockInstrumentation = BedrockInstrumentation;
|
|
274
|
+
//# sourceMappingURL=instrumentation.js.map
|
|
@@ -0,0 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QACxB,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS;YAC5C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY;YAC3B,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;CACF;AAraD,wDAqaC","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 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 () => {},\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: boolean = 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 return this._config.traceContent !== undefined\n ? this._config.traceContent\n : true;\n }\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { InstrumentationConfig } from "@opentelemetry/instrumentation";
|
|
2
|
+
export interface BedrockInstrumentationConfig extends InstrumentationConfig {
|
|
3
|
+
/**
|
|
4
|
+
* Whether to log prompts, completions and embeddings on traces.
|
|
5
|
+
* @default true
|
|
6
|
+
*/
|
|
7
|
+
traceContent?: boolean;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@traceloop/instrumentation-bedrock",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Amazon Bedrock Instrumentation",
|
|
5
|
+
"main": "dist/src/index.js",
|
|
6
|
+
"types": "dist/src/index.d.ts",
|
|
7
|
+
"repository": "traceloop/openllmetry-js",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc --build tsconfig.json",
|
|
10
|
+
"lint": "eslint . --ext .ts",
|
|
11
|
+
"lint:fix": "eslint . --ext .ts --fix",
|
|
12
|
+
"test": "ts-mocha -p tsconfig.json 'tests/**/*.test.ts' --timeout 20000"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"opentelemetry",
|
|
16
|
+
"nodejs",
|
|
17
|
+
"tracing",
|
|
18
|
+
"attributes",
|
|
19
|
+
"semantic conventions"
|
|
20
|
+
],
|
|
21
|
+
"author": "Swaroop<maddisaiswaroop@gmail.com>",
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=14"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist/src/**/*.js",
|
|
28
|
+
"dist/src/**/*.js.map",
|
|
29
|
+
"dist/src/**/*.d.ts",
|
|
30
|
+
"doc",
|
|
31
|
+
"LICENSE",
|
|
32
|
+
"README.md",
|
|
33
|
+
"package.json"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@opentelemetry/core": "^1.8.0",
|
|
40
|
+
"@opentelemetry/instrumentation": "^0.44.0",
|
|
41
|
+
"@opentelemetry/semantic-conventions": "^1.0.0",
|
|
42
|
+
"@traceloop/ai-semantic-conventions": "^0.3.0"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@aws-sdk/client-bedrock-runtime": "^3.499.0"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/traceloop/openllmetry-js/tree/main/packages/instrumentation-openai",
|
|
48
|
+
"gitHead": "1adfc77ff6dc9d55d053fdf89ef449497aff9bac"
|
|
49
|
+
}
|