@elizaos/plugin-groq 1.0.0-beta.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
- # OpenAI Plugin
1
+ # Groq Plugin
2
2
 
3
- This plugin provides integration with OpenAI's models through the ElizaOS platform.
3
+ This plugin provides integration with Groq Cloud through the ElizaOS platform.
4
4
 
5
5
  ## Usage
6
6
 
7
7
  Add the plugin to your character configuration:
8
8
 
9
9
  ```json
10
- "plugins": ["@elizaos/plugin-openai"]
10
+ "plugins": ["@elizaos-plugins/plugin-groq"]
11
11
  ```
12
12
 
13
13
  ## Configuration
@@ -16,70 +16,129 @@ The plugin requires these environment variables (can be set in .env file or char
16
16
 
17
17
  ```json
18
18
  "settings": {
19
- "OPENAI_API_KEY": "your_openai_api_key",
20
- "OPENAI_BASE_URL": "optional_custom_endpoint",
21
- "OPENAI_SMALL_MODEL": "gpt-4o-mini",
22
- "OPENAI_LARGE_MODEL": "gpt-4o"
19
+ "GROQ_API_KEY": "your_groq_api_key",
20
+ "GROQ_BASE_URL": "optional_custom_endpoint",
21
+ "GROQ_SMALL_MODEL": "llama-3.1-8b-instant",
22
+ "GROQ_LARGE_MODEL": "qwen-qwq-32b"
23
23
  }
24
24
  ```
25
25
 
26
26
  Or in `.env` file:
27
27
 
28
28
  ```
29
- OPENAI_API_KEY=your_openai_api_key
29
+ GROQ_API_KEY=your_groq_api_key
30
30
  # Optional overrides:
31
- OPENAI_BASE_URL=optional_custom_endpoint
32
- OPENAI_SMALL_MODEL=gpt-4o-mini
33
- OPENAI_LARGE_MODEL=gpt-4o
31
+ GROQ_BASE_URL=optional_custom_endpoint
32
+ GROQ_SMALL_MODEL=llama-3.1-8b-instant
33
+ GROQ_LARGE_MODEL=qwen-qwq-32b
34
34
  ```
35
35
 
36
36
  ### Configuration Options
37
37
 
38
- - `OPENAI_API_KEY` (required): Your OpenAI API credentials
39
- - `OPENAI_BASE_URL`: Custom API endpoint (default: https://api.openai.com/v1)
40
- - `OPENAI_SMALL_MODEL`: Defaults to GPT-4o Mini ("gpt-4o-mini")
41
- - `OPENAI_LARGE_MODEL`: Defaults to GPT-4o ("gpt-4o")
38
+ - `GROQ_API_KEY` (required): Your Groq API credentials.
39
+ - `GROQ_BASE_URL`: Custom API endpoint (default: https://api.groq.com/openai/v1).
40
+ - `GROQ_SMALL_MODEL`: Defaults to Llama 3.1 8B Instant ("llama-3.1-8b-instant").
41
+ - `GROQ_LARGE_MODEL`: Defaults to Qwen QWQ 32B ("qwen-qwq-32b").
42
42
 
43
43
  The plugin provides these model classes:
44
44
 
45
- - `TEXT_SMALL`: Optimized for fast, cost-effective responses
46
- - `TEXT_LARGE`: For complex tasks requiring deeper reasoning
47
- - `TEXT_EMBEDDING`: Text embedding model (text-embedding-3-small)
48
- - `IMAGE`: DALL-E image generation
49
- - `IMAGE_DESCRIPTION`: GPT-4o image analysis
50
- - `TRANSCRIPTION`: Whisper audio transcription
51
- - `TEXT_TOKENIZER_ENCODE`: Text tokenization
52
- - `TEXT_TOKENIZER_DECODE`: Token decoding
45
+ - `TEXT_SMALL`: Optimized for fast, cost-effective responses (uses `GROQ_SMALL_MODEL`).
46
+ - `TEXT_LARGE`: For complex tasks requiring deeper reasoning (uses `GROQ_LARGE_MODEL`).
47
+ - `IMAGE`: Image generation.
48
+ - `TRANSCRIPTION`: Whisper audio transcription.
49
+ - `TEXT_TOKENIZER_ENCODE`: Text tokenization.
50
+ - `TEXT_TOKENIZER_DECODE`: Token decoding.
51
+ - `OBJECT_SMALL`: For generating structured JSON objects with the small model.
52
+ - `OBJECT_LARGE`: For generating structured JSON objects with the large model.
53
53
 
54
54
  ## Additional Features
55
55
 
56
+ ### Text Generation (Small Model)
57
+
58
+ ```javascript
59
+ const response = await runtime.useModel(ModelType.TEXT_SMALL, {
60
+ prompt: 'Explain quantum computing in simple terms.',
61
+ // Optional parameters:
62
+ // stopSequences: ["stop phrase"],
63
+ // maxTokens: 200,
64
+ // temperature: 0.7,
65
+ // frequencyPenalty: 0.7,
66
+ // presencePenalty: 0.7,
67
+ });
68
+ console.log(response);
69
+ ```
70
+
71
+ ### Text Generation (Large Model)
72
+
73
+ ```javascript
74
+ const response = await runtime.useModel(ModelType.TEXT_LARGE, {
75
+ prompt: 'Write a comprehensive guide on sustainable gardening.',
76
+ // Optional parameters:
77
+ // stopSequences: ["stop phrase"],
78
+ // maxTokens: 1000,
79
+ // temperature: 0.8,
80
+ // frequencyPenalty: 0.5,
81
+ // presencePenalty: 0.5,
82
+ });
83
+ console.log(response);
84
+ ```
85
+
56
86
  ### Image Generation
57
87
 
58
- ```js
59
- await runtime.useModel(ModelType.IMAGE, {
60
- prompt: 'A sunset over mountains',
88
+ ```javascript
89
+ const images = await runtime.useModel(ModelType.IMAGE, {
90
+ prompt: 'A futuristic cityscape at sunset',
61
91
  n: 1, // number of images
62
92
  size: '1024x1024', // image resolution
63
93
  });
94
+ console.log(images[0].url); // Example: Accessing the URL of the first image
64
95
  ```
65
96
 
66
97
  ### Audio Transcription
67
98
 
68
- ```js
99
+ ```javascript
100
+ // Assuming 'audioBuffer' is a Buffer containing the audio data (e.g., from a file)
69
101
  const transcription = await runtime.useModel(ModelType.TRANSCRIPTION, audioBuffer);
102
+ console.log(transcription);
103
+ ```
104
+
105
+ ### Text Tokenization (Encode)
106
+
107
+ ```javascript
108
+ const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, {
109
+ prompt: 'Hello, world!',
110
+ modelType: ModelType.TEXT_SMALL, // Or ModelType.TEXT_LARGE
111
+ });
112
+ console.log(tokens);
113
+ ```
114
+
115
+ ### Text Tokenization (Decode)
116
+
117
+ ```javascript
118
+ // Assuming 'tokens' is an array of numbers obtained from encoding
119
+ const text = await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, {
120
+ tokens: [15339, 29871, 29991], // Example tokens for "Hello, world!" with some models
121
+ modelType: ModelType.TEXT_SMALL, // Or ModelType.TEXT_LARGE
122
+ });
123
+ console.log(text);
70
124
  ```
71
125
 
72
- ### Image Analysis
126
+ ### Object Generation (Small Model)
73
127
 
74
- ```js
75
- const { title, description } = await runtime.useModel(
76
- ModelType.IMAGE_DESCRIPTION,
77
- 'https://example.com/image.jpg'
78
- );
128
+ ```javascript
129
+ const userProfile = await runtime.useModel(ModelType.OBJECT_SMALL, {
130
+ prompt: 'Generate a JSON object for a user with name "Alex", age 30, and hobbies ["reading", "hiking"].',
131
+ temperature: 0.5,
132
+ });
133
+ console.log(userProfile);
79
134
  ```
80
135
 
81
- ### Text Embeddings
136
+ ### Object Generation (Large Model)
82
137
 
83
- ```js
84
- const embedding = await runtime.useModel(ModelType.TEXT_EMBEDDING, 'text to embed');
138
+ ```javascript
139
+ const complexData = await runtime.useModel(ModelType.OBJECT_LARGE, {
140
+ prompt: 'Generate a detailed JSON object for a product listing: name "Laptop Pro", category "Electronics", price 1200, features ["16GB RAM", "512GB SSD", "15-inch Display"], and availability "in stock".',
141
+ temperature: 0.7,
142
+ });
143
+ console.log(complexData);
85
144
  ```
@@ -0,0 +1,5 @@
1
+ import { Plugin } from '@elizaos/core';
2
+
3
+ declare const groqPlugin: Plugin;
4
+
5
+ export { groqPlugin as default, groqPlugin };
package/dist/index.js CHANGED
@@ -2,59 +2,512 @@
2
2
  import { createGroq } from "@ai-sdk/groq";
3
3
  import {
4
4
  ModelType,
5
+ ServiceType,
5
6
  logger
6
7
  } from "@elizaos/core";
7
8
  import { generateObject, generateText } from "ai";
8
9
  import { encodingForModel } from "js-tiktoken";
9
- function getCloudflareGatewayBaseURL(runtime, provider) {
10
+
11
+ // node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
12
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
13
+
14
+ // node_modules/@opentelemetry/api/build/esm/version.js
15
+ var VERSION = "1.9.0";
16
+
17
+ // node_modules/@opentelemetry/api/build/esm/internal/semver.js
18
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
19
+ function _makeCompatibilityCheck(ownVersion) {
20
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
21
+ var rejectedVersions = /* @__PURE__ */ new Set();
22
+ var myVersionMatch = ownVersion.match(re);
23
+ if (!myVersionMatch) {
24
+ return function() {
25
+ return false;
26
+ };
27
+ }
28
+ var ownVersionParsed = {
29
+ major: +myVersionMatch[1],
30
+ minor: +myVersionMatch[2],
31
+ patch: +myVersionMatch[3],
32
+ prerelease: myVersionMatch[4]
33
+ };
34
+ if (ownVersionParsed.prerelease != null) {
35
+ return function isExactmatch(globalVersion) {
36
+ return globalVersion === ownVersion;
37
+ };
38
+ }
39
+ function _reject(v) {
40
+ rejectedVersions.add(v);
41
+ return false;
42
+ }
43
+ function _accept(v) {
44
+ acceptedVersions.add(v);
45
+ return true;
46
+ }
47
+ return function isCompatible2(globalVersion) {
48
+ if (acceptedVersions.has(globalVersion)) {
49
+ return true;
50
+ }
51
+ if (rejectedVersions.has(globalVersion)) {
52
+ return false;
53
+ }
54
+ var globalVersionMatch = globalVersion.match(re);
55
+ if (!globalVersionMatch) {
56
+ return _reject(globalVersion);
57
+ }
58
+ var globalVersionParsed = {
59
+ major: +globalVersionMatch[1],
60
+ minor: +globalVersionMatch[2],
61
+ patch: +globalVersionMatch[3],
62
+ prerelease: globalVersionMatch[4]
63
+ };
64
+ if (globalVersionParsed.prerelease != null) {
65
+ return _reject(globalVersion);
66
+ }
67
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
68
+ return _reject(globalVersion);
69
+ }
70
+ if (ownVersionParsed.major === 0) {
71
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
72
+ return _accept(globalVersion);
73
+ }
74
+ return _reject(globalVersion);
75
+ }
76
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
77
+ return _accept(globalVersion);
78
+ }
79
+ return _reject(globalVersion);
80
+ };
81
+ }
82
+ var isCompatible = _makeCompatibilityCheck(VERSION);
83
+
84
+ // node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
85
+ var major = VERSION.split(".")[0];
86
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
87
+ var _global = _globalThis;
88
+ function registerGlobal(type, instance, diag, allowOverride) {
89
+ var _a;
90
+ if (allowOverride === void 0) {
91
+ allowOverride = false;
92
+ }
93
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
94
+ version: VERSION
95
+ };
96
+ if (!allowOverride && api[type]) {
97
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
98
+ diag.error(err.stack || err.message);
99
+ return false;
100
+ }
101
+ if (api.version !== VERSION) {
102
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
103
+ diag.error(err.stack || err.message);
104
+ return false;
105
+ }
106
+ api[type] = instance;
107
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
108
+ return true;
109
+ }
110
+ function getGlobal(type) {
111
+ var _a, _b;
112
+ var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
113
+ if (!globalVersion || !isCompatible(globalVersion)) {
114
+ return;
115
+ }
116
+ return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
117
+ }
118
+ function unregisterGlobal(type, diag) {
119
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
120
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
121
+ if (api) {
122
+ delete api[type];
123
+ }
124
+ }
125
+
126
+ // node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
127
+ var __read = function(o, n) {
128
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
129
+ if (!m) return o;
130
+ var i = m.call(o), r, ar = [], e;
10
131
  try {
11
- const isCloudflareEnabled = runtime.getSetting("CLOUDFLARE_GW_ENABLED") === "true";
12
- const cloudflareAccountId = runtime.getSetting("CLOUDFLARE_AI_ACCOUNT_ID");
13
- const cloudflareGatewayId = runtime.getSetting("CLOUDFLARE_AI_GATEWAY_ID");
14
- const defaultUrl = "https://api.groq.com/openai/v1";
15
- logger.debug("Cloudflare Gateway Configuration:", {
16
- isEnabled: isCloudflareEnabled,
17
- hasAccountId: !!cloudflareAccountId,
18
- hasGatewayId: !!cloudflareGatewayId,
19
- provider
20
- });
21
- if (!isCloudflareEnabled) {
22
- logger.debug("Cloudflare Gateway is not enabled");
23
- return defaultUrl;
132
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
133
+ } catch (error) {
134
+ e = { error };
135
+ } finally {
136
+ try {
137
+ if (r && !r.done && (m = i["return"])) m.call(i);
138
+ } finally {
139
+ if (e) throw e.error;
140
+ }
141
+ }
142
+ return ar;
143
+ };
144
+ var __spreadArray = function(to, from, pack) {
145
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
146
+ if (ar || !(i in from)) {
147
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
148
+ ar[i] = from[i];
24
149
  }
25
- if (!cloudflareAccountId) {
26
- logger.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_ACCOUNT_ID is not set");
27
- return defaultUrl;
150
+ }
151
+ return to.concat(ar || Array.prototype.slice.call(from));
152
+ };
153
+ var DiagComponentLogger = (
154
+ /** @class */
155
+ function() {
156
+ function DiagComponentLogger2(props) {
157
+ this._namespace = props.namespace || "DiagComponentLogger";
28
158
  }
29
- if (!cloudflareGatewayId) {
30
- logger.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_GATEWAY_ID is not set");
31
- return defaultUrl;
159
+ DiagComponentLogger2.prototype.debug = function() {
160
+ var args = [];
161
+ for (var _i = 0; _i < arguments.length; _i++) {
162
+ args[_i] = arguments[_i];
163
+ }
164
+ return logProxy("debug", this._namespace, args);
165
+ };
166
+ DiagComponentLogger2.prototype.error = function() {
167
+ var args = [];
168
+ for (var _i = 0; _i < arguments.length; _i++) {
169
+ args[_i] = arguments[_i];
170
+ }
171
+ return logProxy("error", this._namespace, args);
172
+ };
173
+ DiagComponentLogger2.prototype.info = function() {
174
+ var args = [];
175
+ for (var _i = 0; _i < arguments.length; _i++) {
176
+ args[_i] = arguments[_i];
177
+ }
178
+ return logProxy("info", this._namespace, args);
179
+ };
180
+ DiagComponentLogger2.prototype.warn = function() {
181
+ var args = [];
182
+ for (var _i = 0; _i < arguments.length; _i++) {
183
+ args[_i] = arguments[_i];
184
+ }
185
+ return logProxy("warn", this._namespace, args);
186
+ };
187
+ DiagComponentLogger2.prototype.verbose = function() {
188
+ var args = [];
189
+ for (var _i = 0; _i < arguments.length; _i++) {
190
+ args[_i] = arguments[_i];
191
+ }
192
+ return logProxy("verbose", this._namespace, args);
193
+ };
194
+ return DiagComponentLogger2;
195
+ }()
196
+ );
197
+ function logProxy(funcName, namespace, args) {
198
+ var logger2 = getGlobal("diag");
199
+ if (!logger2) {
200
+ return;
201
+ }
202
+ args.unshift(namespace);
203
+ return logger2[funcName].apply(logger2, __spreadArray([], __read(args), false));
204
+ }
205
+
206
+ // node_modules/@opentelemetry/api/build/esm/diag/types.js
207
+ var DiagLogLevel;
208
+ (function(DiagLogLevel2) {
209
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
210
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
211
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
212
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
213
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
214
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
215
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
216
+ })(DiagLogLevel || (DiagLogLevel = {}));
217
+
218
+ // node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
219
+ function createLogLevelDiagLogger(maxLevel, logger2) {
220
+ if (maxLevel < DiagLogLevel.NONE) {
221
+ maxLevel = DiagLogLevel.NONE;
222
+ } else if (maxLevel > DiagLogLevel.ALL) {
223
+ maxLevel = DiagLogLevel.ALL;
224
+ }
225
+ logger2 = logger2 || {};
226
+ function _filterFunc(funcName, theLevel) {
227
+ var theFunc = logger2[funcName];
228
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
229
+ return theFunc.bind(logger2);
32
230
  }
33
- const baseURL = `https://gateway.ai.cloudflare.com/v1/${cloudflareAccountId}/${cloudflareGatewayId}/${provider.toLowerCase()}`;
34
- logger.info("Using Cloudflare Gateway:", {
35
- provider,
36
- baseURL,
37
- accountId: cloudflareAccountId,
38
- gatewayId: cloudflareGatewayId
39
- });
40
- return baseURL;
231
+ return function() {
232
+ };
233
+ }
234
+ return {
235
+ error: _filterFunc("error", DiagLogLevel.ERROR),
236
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
237
+ info: _filterFunc("info", DiagLogLevel.INFO),
238
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
239
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
240
+ };
241
+ }
242
+
243
+ // node_modules/@opentelemetry/api/build/esm/api/diag.js
244
+ var __read2 = function(o, n) {
245
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
246
+ if (!m) return o;
247
+ var i = m.call(o), r, ar = [], e;
248
+ try {
249
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
250
+ } catch (error) {
251
+ e = { error };
252
+ } finally {
253
+ try {
254
+ if (r && !r.done && (m = i["return"])) m.call(i);
255
+ } finally {
256
+ if (e) throw e.error;
257
+ }
258
+ }
259
+ return ar;
260
+ };
261
+ var __spreadArray2 = function(to, from, pack) {
262
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
263
+ if (ar || !(i in from)) {
264
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
265
+ ar[i] = from[i];
266
+ }
267
+ }
268
+ return to.concat(ar || Array.prototype.slice.call(from));
269
+ };
270
+ var API_NAME = "diag";
271
+ var DiagAPI = (
272
+ /** @class */
273
+ function() {
274
+ function DiagAPI2() {
275
+ function _logProxy(funcName) {
276
+ return function() {
277
+ var args = [];
278
+ for (var _i = 0; _i < arguments.length; _i++) {
279
+ args[_i] = arguments[_i];
280
+ }
281
+ var logger2 = getGlobal("diag");
282
+ if (!logger2)
283
+ return;
284
+ return logger2[funcName].apply(logger2, __spreadArray2([], __read2(args), false));
285
+ };
286
+ }
287
+ var self = this;
288
+ var setLogger = function(logger2, optionsOrLogLevel) {
289
+ var _a, _b, _c;
290
+ if (optionsOrLogLevel === void 0) {
291
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
292
+ }
293
+ if (logger2 === self) {
294
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
295
+ self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
296
+ return false;
297
+ }
298
+ if (typeof optionsOrLogLevel === "number") {
299
+ optionsOrLogLevel = {
300
+ logLevel: optionsOrLogLevel
301
+ };
302
+ }
303
+ var oldLogger = getGlobal("diag");
304
+ var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger2);
305
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
306
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
307
+ oldLogger.warn("Current logger will be overwritten from " + stack);
308
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
309
+ }
310
+ return registerGlobal("diag", newLogger, self, true);
311
+ };
312
+ self.setLogger = setLogger;
313
+ self.disable = function() {
314
+ unregisterGlobal(API_NAME, self);
315
+ };
316
+ self.createComponentLogger = function(options) {
317
+ return new DiagComponentLogger(options);
318
+ };
319
+ self.verbose = _logProxy("verbose");
320
+ self.debug = _logProxy("debug");
321
+ self.info = _logProxy("info");
322
+ self.warn = _logProxy("warn");
323
+ self.error = _logProxy("error");
324
+ }
325
+ DiagAPI2.instance = function() {
326
+ if (!this._instance) {
327
+ this._instance = new DiagAPI2();
328
+ }
329
+ return this._instance;
330
+ };
331
+ return DiagAPI2;
332
+ }()
333
+ );
334
+
335
+ // node_modules/@opentelemetry/api/build/esm/context/context.js
336
+ var BaseContext = (
337
+ /** @class */
338
+ /* @__PURE__ */ function() {
339
+ function BaseContext2(parentContext) {
340
+ var self = this;
341
+ self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
342
+ self.getValue = function(key) {
343
+ return self._currentContext.get(key);
344
+ };
345
+ self.setValue = function(key, value) {
346
+ var context2 = new BaseContext2(self._currentContext);
347
+ context2._currentContext.set(key, value);
348
+ return context2;
349
+ };
350
+ self.deleteValue = function(key) {
351
+ var context2 = new BaseContext2(self._currentContext);
352
+ context2._currentContext.delete(key);
353
+ return context2;
354
+ };
355
+ }
356
+ return BaseContext2;
357
+ }()
358
+ );
359
+ var ROOT_CONTEXT = new BaseContext();
360
+
361
+ // node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
362
+ var __read3 = function(o, n) {
363
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
364
+ if (!m) return o;
365
+ var i = m.call(o), r, ar = [], e;
366
+ try {
367
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
368
+ } catch (error) {
369
+ e = { error };
370
+ } finally {
371
+ try {
372
+ if (r && !r.done && (m = i["return"])) m.call(i);
373
+ } finally {
374
+ if (e) throw e.error;
375
+ }
376
+ }
377
+ return ar;
378
+ };
379
+ var __spreadArray3 = function(to, from, pack) {
380
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
381
+ if (ar || !(i in from)) {
382
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
383
+ ar[i] = from[i];
384
+ }
385
+ }
386
+ return to.concat(ar || Array.prototype.slice.call(from));
387
+ };
388
+ var NoopContextManager = (
389
+ /** @class */
390
+ function() {
391
+ function NoopContextManager2() {
392
+ }
393
+ NoopContextManager2.prototype.active = function() {
394
+ return ROOT_CONTEXT;
395
+ };
396
+ NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
397
+ var args = [];
398
+ for (var _i = 3; _i < arguments.length; _i++) {
399
+ args[_i - 3] = arguments[_i];
400
+ }
401
+ return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
402
+ };
403
+ NoopContextManager2.prototype.bind = function(_context, target) {
404
+ return target;
405
+ };
406
+ NoopContextManager2.prototype.enable = function() {
407
+ return this;
408
+ };
409
+ NoopContextManager2.prototype.disable = function() {
410
+ return this;
411
+ };
412
+ return NoopContextManager2;
413
+ }()
414
+ );
415
+
416
+ // node_modules/@opentelemetry/api/build/esm/api/context.js
417
+ var __read4 = function(o, n) {
418
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
419
+ if (!m) return o;
420
+ var i = m.call(o), r, ar = [], e;
421
+ try {
422
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
41
423
  } catch (error) {
42
- logger.error("Error in getCloudflareGatewayBaseURL:", error);
43
- return "https://api.groq.com/openai/v1";
424
+ e = { error };
425
+ } finally {
426
+ try {
427
+ if (r && !r.done && (m = i["return"])) m.call(i);
428
+ } finally {
429
+ if (e) throw e.error;
430
+ }
44
431
  }
432
+ return ar;
433
+ };
434
+ var __spreadArray4 = function(to, from, pack) {
435
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
436
+ if (ar || !(i in from)) {
437
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
438
+ ar[i] = from[i];
439
+ }
440
+ }
441
+ return to.concat(ar || Array.prototype.slice.call(from));
442
+ };
443
+ var API_NAME2 = "context";
444
+ var NOOP_CONTEXT_MANAGER = new NoopContextManager();
445
+ var ContextAPI = (
446
+ /** @class */
447
+ function() {
448
+ function ContextAPI2() {
449
+ }
450
+ ContextAPI2.getInstance = function() {
451
+ if (!this._instance) {
452
+ this._instance = new ContextAPI2();
453
+ }
454
+ return this._instance;
455
+ };
456
+ ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
457
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
458
+ };
459
+ ContextAPI2.prototype.active = function() {
460
+ return this._getContextManager().active();
461
+ };
462
+ ContextAPI2.prototype.with = function(context2, fn, thisArg) {
463
+ var _a;
464
+ var args = [];
465
+ for (var _i = 3; _i < arguments.length; _i++) {
466
+ args[_i - 3] = arguments[_i];
467
+ }
468
+ return (_a = this._getContextManager()).with.apply(_a, __spreadArray4([context2, fn, thisArg], __read4(args), false));
469
+ };
470
+ ContextAPI2.prototype.bind = function(context2, target) {
471
+ return this._getContextManager().bind(context2, target);
472
+ };
473
+ ContextAPI2.prototype._getContextManager = function() {
474
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
475
+ };
476
+ ContextAPI2.prototype.disable = function() {
477
+ this._getContextManager().disable();
478
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
479
+ };
480
+ return ContextAPI2;
481
+ }()
482
+ );
483
+
484
+ // node_modules/@opentelemetry/api/build/esm/trace/status.js
485
+ var SpanStatusCode;
486
+ (function(SpanStatusCode2) {
487
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
488
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
489
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
490
+ })(SpanStatusCode || (SpanStatusCode = {}));
491
+
492
+ // node_modules/@opentelemetry/api/build/esm/context-api.js
493
+ var context = ContextAPI.getInstance();
494
+
495
+ // src/index.ts
496
+ function getBaseURL(runtime) {
497
+ return runtime.getSetting("GROQ_BASE_URL") || "https://api.groq.com/openai/v1";
45
498
  }
46
- function findModelName(model) {
499
+ function findModelName(runtime, model) {
47
500
  try {
48
- const name = model === ModelType.TEXT_SMALL ? process.env.SMALL_GROQ_MODEL ?? "llama-3.1-8b-instant" : process.env.LARGE_GROQ_MODEL ?? "llama-3.2-90b-vision-preview";
501
+ const name = model === ModelType.TEXT_SMALL ? runtime.getSetting("GROQ_SMALL_MODEL") ?? "llama-3.1-8b-instant" : runtime.getSetting("GROQ_LARGE_MODEL") ?? "qwen-qwq-32b";
49
502
  return name;
50
503
  } catch (error) {
51
504
  logger.error("Error in findModelName:", error);
52
505
  return "llama-3.1-8b-instant";
53
506
  }
54
507
  }
55
- async function tokenizeText(model, prompt) {
508
+ async function tokenizeText(runtime, model, prompt) {
56
509
  try {
57
- const encoding = encodingForModel(findModelName(model));
510
+ const encoding = encodingForModel(findModelName(runtime, model));
58
511
  const tokens = encoding.encode(prompt);
59
512
  return tokens;
60
513
  } catch (error) {
@@ -62,9 +515,9 @@ async function tokenizeText(model, prompt) {
62
515
  return [];
63
516
  }
64
517
  }
65
- async function detokenizeText(model, tokens) {
518
+ async function detokenizeText(runtime, model, tokens) {
66
519
  try {
67
- const modelName = findModelName(model);
520
+ const modelName = findModelName(runtime, model);
68
521
  const encoding = encodingForModel(modelName);
69
522
  return encoding.decode(tokens);
70
523
  } catch (error) {
@@ -93,6 +546,60 @@ async function handleRateLimitError(error, retryFn) {
93
546
  throw retryError;
94
547
  }
95
548
  }
549
+ function getTracer(runtime) {
550
+ const availableServices = Array.from(runtime.getAllServices().keys());
551
+ logger.debug(`[getTracer] Available services: ${JSON.stringify(availableServices)}`);
552
+ logger.debug(`[getTracer] Attempting to get service with key: ${ServiceType.INSTRUMENTATION}`);
553
+ const instrumentationService = runtime.getService(
554
+ ServiceType.INSTRUMENTATION
555
+ );
556
+ if (!instrumentationService) {
557
+ logger.warn(`[getTracer] Service ${ServiceType.INSTRUMENTATION} not found in runtime.`);
558
+ return null;
559
+ }
560
+ if (!instrumentationService.isEnabled()) {
561
+ logger.debug("[getTracer] Instrumentation service found but is disabled.");
562
+ return null;
563
+ }
564
+ logger.debug("[getTracer] Successfully retrieved enabled instrumentation service.");
565
+ return instrumentationService.getTracer("eliza.llm.openai");
566
+ }
567
+ async function startLlmSpan(runtime, spanName, attributes, fn) {
568
+ const tracer = getTracer(runtime);
569
+ if (!tracer) {
570
+ const dummySpan = {
571
+ setAttribute: () => {
572
+ },
573
+ setAttributes: () => {
574
+ },
575
+ addEvent: () => {
576
+ },
577
+ recordException: () => {
578
+ },
579
+ setStatus: () => {
580
+ },
581
+ end: () => {
582
+ },
583
+ spanContext: () => ({ traceId: "", spanId: "", traceFlags: 0 })
584
+ };
585
+ return fn(dummySpan);
586
+ }
587
+ const activeContext = context.active();
588
+ return tracer.startActiveSpan(spanName, { attributes }, activeContext, async (span) => {
589
+ try {
590
+ const result = await fn(span);
591
+ span.setStatus({ code: SpanStatusCode.OK });
592
+ span.end();
593
+ return result;
594
+ } catch (error) {
595
+ const message = error instanceof Error ? error.message : String(error);
596
+ span.recordException(error);
597
+ span.setStatus({ code: SpanStatusCode.ERROR, message });
598
+ span.end();
599
+ throw error;
600
+ }
601
+ });
602
+ }
96
603
  async function generateGroqText(groq, model, params) {
97
604
  try {
98
605
  const { text: groqResponse } = await generateText({
@@ -144,39 +651,23 @@ async function generateGroqObject(groq, model, params) {
144
651
  var groqPlugin = {
145
652
  name: "groq",
146
653
  description: "Groq plugin",
147
- config: {
148
- GROQ_API_KEY: process.env.GROQ_API_KEY,
149
- SMALL_GROQ_MODEL: process.env.SMALL_GROQ_MODEL,
150
- MEDIUM_GROQ_MODEL: process.env.MEDIUM_GROQ_MODEL,
151
- LARGE_GROQ_MODEL: process.env.LARGE_GROQ_MODEL
152
- },
153
- async init(config) {
154
- if (!process.env.GROQ_API_KEY) {
654
+ async init(config, runtime) {
655
+ if (!runtime.getSetting("GROQ_API_KEY")) {
155
656
  throw Error("Missing GROQ_API_KEY in environment variables");
156
657
  }
157
658
  },
158
659
  models: {
159
- [ModelType.TEXT_EMBEDDING]: async (runtime, params) => {
160
- try {
161
- const testVector = Array(1536).fill(0);
162
- testVector[0] = 0.1;
163
- return testVector;
164
- } catch (error) {
165
- logger.error("Error in TEXT_EMBEDDING model:", error);
166
- return Array(1536).fill(0);
167
- }
168
- },
169
- [ModelType.TEXT_TOKENIZER_ENCODE]: async (_runtime, { prompt, modelType = ModelType.TEXT_LARGE }) => {
660
+ [ModelType.TEXT_TOKENIZER_ENCODE]: async (runtime, { prompt, modelType = ModelType.TEXT_LARGE }) => {
170
661
  try {
171
- return await tokenizeText(modelType ?? ModelType.TEXT_LARGE, prompt);
662
+ return await tokenizeText(runtime, modelType ?? ModelType.TEXT_LARGE, prompt);
172
663
  } catch (error) {
173
664
  logger.error("Error in TEXT_TOKENIZER_ENCODE model:", error);
174
665
  return [];
175
666
  }
176
667
  },
177
- [ModelType.TEXT_TOKENIZER_DECODE]: async (_runtime, { tokens, modelType = ModelType.TEXT_LARGE }) => {
668
+ [ModelType.TEXT_TOKENIZER_DECODE]: async (runtime, { tokens, modelType = ModelType.TEXT_LARGE }) => {
178
669
  try {
179
- return await detokenizeText(modelType ?? ModelType.TEXT_LARGE, tokens);
670
+ return await detokenizeText(runtime, modelType ?? ModelType.TEXT_LARGE, tokens);
180
671
  } catch (error) {
181
672
  logger.error("Error in TEXT_TOKENIZER_DECODE model:", error);
182
673
  return "";
@@ -188,7 +679,7 @@ var groqPlugin = {
188
679
  const frequency_penalty = 0.7;
189
680
  const presence_penalty = 0.7;
190
681
  const max_response_length = 8e3;
191
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
682
+ const baseURL = getBaseURL(runtime);
192
683
  const groq = createGroq({
193
684
  apiKey: runtime.getSetting("GROQ_API_KEY"),
194
685
  fetch: runtime.fetch,
@@ -220,8 +711,8 @@ var groqPlugin = {
220
711
  presencePenalty = 0.7
221
712
  }) => {
222
713
  try {
223
- const model = runtime.getSetting("GROQ_LARGE_MODEL") ?? runtime.getSetting("LARGE_MODEL") ?? "llama-3.2-90b";
224
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
714
+ const model = runtime.getSetting("GROQ_LARGE_MODEL") ?? runtime.getSetting("LARGE_MODEL") ?? "qwen-qwq-32b";
715
+ const baseURL = getBaseURL(runtime);
225
716
  const groq = createGroq({
226
717
  apiKey: runtime.getSetting("GROQ_API_KEY"),
227
718
  fetch: runtime.fetch,
@@ -243,7 +734,7 @@ var groqPlugin = {
243
734
  },
244
735
  [ModelType.IMAGE]: async (runtime, params) => {
245
736
  try {
246
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
737
+ const baseURL = getBaseURL(runtime);
247
738
  const response = await fetch(`${baseURL}/images/generations`, {
248
739
  method: "POST",
249
740
  headers: {
@@ -270,12 +761,11 @@ var groqPlugin = {
270
761
  },
271
762
  [ModelType.TRANSCRIPTION]: async (runtime, audioBuffer) => {
272
763
  try {
273
- logger.log("audioBuffer", audioBuffer);
274
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
764
+ const baseURL = getBaseURL(runtime);
275
765
  const formData = new FormData();
276
- const enhancedFormData = formData;
277
- enhancedFormData.append("file", new Blob([audioBuffer], { type: "audio/mp3" }));
278
- enhancedFormData.append("model", "whisper-1");
766
+ const file = new File([audioBuffer], "audio.mp3", { type: "audio/mp3" });
767
+ formData.append("file", file);
768
+ formData.append("model", "distil-whisper-large-v3-en");
279
769
  const response = await fetch(`${baseURL}/audio/transcriptions`, {
280
770
  method: "POST",
281
771
  headers: {
@@ -283,7 +773,6 @@ var groqPlugin = {
283
773
  },
284
774
  body: formData
285
775
  });
286
- logger.log("response", response);
287
776
  if (!response.ok) {
288
777
  logger.error(`Failed to transcribe audio: ${response.statusText}`);
289
778
  return "Error transcribing audio. Please try again later.";
@@ -295,9 +784,56 @@ var groqPlugin = {
295
784
  return "Error transcribing audio. Please try again later.";
296
785
  }
297
786
  },
787
+ // you can include elevenlabs before this plugin to prefer elevenlabs voice
788
+ // The model playai-tts requires terms acceptance. Please have the org admin accept the terms at https://console.groq.com/playground?model=playai-tts"
789
+ [ModelType.TEXT_TO_SPEECH]: async (runtime, text) => {
790
+ const ttsModelName = runtime.getSetting("GROQ_TTS_MODEL") || "playai-tts";
791
+ const voice = runtime.getSetting("GROQ_TTS_VOICE") || "Chip-PlayAI";
792
+ const attributes = {
793
+ "llm.vendor": "Groq",
794
+ "llm.request.type": "tts",
795
+ "llm.request.model": ttsModelName,
796
+ "input.text.length": text.length
797
+ };
798
+ return startLlmSpan(runtime, "LLM.tts", attributes, async (span) => {
799
+ logger.log(`[Groq] Using TEXT_TO_SPEECH model: ${ttsModelName}`);
800
+ span.addEvent("llm.prompt", { "prompt.content": text });
801
+ try {
802
+ const baseURL = getBaseURL(runtime);
803
+ const res = await fetch(`${baseURL}/audio/speech`, {
804
+ method: "POST",
805
+ headers: {
806
+ Authorization: `Bearer ${runtime.getSetting("GROQ_API_KEY")}`,
807
+ "Content-Type": "application/json"
808
+ },
809
+ body: JSON.stringify({
810
+ model: ttsModelName,
811
+ voice,
812
+ input: text
813
+ //...(instructions && { instructions }),
814
+ })
815
+ });
816
+ if (!res.ok) {
817
+ const err = await res.text();
818
+ throw new Error(`Groq TTS error ${res.status}: ${err}`);
819
+ }
820
+ const speechStream = res.body;
821
+ span.addEvent("llm.response.success", {
822
+ info: "Speech stream generated"
823
+ });
824
+ return speechStream;
825
+ } catch (error) {
826
+ const message = error instanceof Error ? error.message : String(error);
827
+ const exception = error instanceof Error ? error : new Error(message);
828
+ span.recordException(exception);
829
+ span.setStatus({ code: SpanStatusCode.ERROR, message });
830
+ throw error;
831
+ }
832
+ });
833
+ },
298
834
  [ModelType.OBJECT_SMALL]: async (runtime, params) => {
299
835
  try {
300
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
836
+ const baseURL = getBaseURL(runtime);
301
837
  const groq = createGroq({
302
838
  apiKey: runtime.getSetting("GROQ_API_KEY"),
303
839
  baseURL
@@ -314,12 +850,12 @@ var groqPlugin = {
314
850
  },
315
851
  [ModelType.OBJECT_LARGE]: async (runtime, params) => {
316
852
  try {
317
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq");
853
+ const baseURL = getBaseURL(runtime);
318
854
  const groq = createGroq({
319
855
  apiKey: runtime.getSetting("GROQ_API_KEY"),
320
856
  baseURL
321
857
  });
322
- const model = runtime.getSetting("GROQ_LARGE_MODEL") ?? runtime.getSetting("LARGE_MODEL") ?? "llama-3.2-90b-vision-preview";
858
+ const model = runtime.getSetting("GROQ_LARGE_MODEL") ?? runtime.getSetting("LARGE_MODEL") ?? "qwen-qwq-32b";
323
859
  if (params.schema) {
324
860
  logger.info("Using OBJECT_LARGE without schema validation");
325
861
  }
@@ -338,7 +874,7 @@ var groqPlugin = {
338
874
  name: "groq_test_url_and_api_key_validation",
339
875
  fn: async (runtime) => {
340
876
  try {
341
- const baseURL = getCloudflareGatewayBaseURL(runtime, "groq") ?? "https://api.groq.com/openai/v1";
877
+ const baseURL = getBaseURL(runtime) ?? "https://api.groq.com/openai/v1";
342
878
  const response = await fetch(`${baseURL}/models`, {
343
879
  headers: {
344
880
  Authorization: `Bearer ${runtime.getSetting("GROQ_API_KEY")}`
@@ -355,19 +891,6 @@ var groqPlugin = {
355
891
  }
356
892
  }
357
893
  },
358
- {
359
- name: "groq_test_text_embedding",
360
- fn: async (runtime) => {
361
- try {
362
- const embedding = await runtime.useModel(ModelType.TEXT_EMBEDDING, {
363
- text: "Hello, world!"
364
- });
365
- logger.log("embedding", embedding);
366
- } catch (error) {
367
- logger.error("Error in test_text_embedding:", error);
368
- }
369
- }
370
- },
371
894
  {
372
895
  name: "groq_test_text_large",
373
896
  fn: async (runtime) => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createGroq } from '@ai-sdk/groq';\nimport type {\n ImageDescriptionParams,\n ModelTypeName,\n ObjectGenerationParams,\n Plugin,\n TextEmbeddingParams,\n} from '@elizaos/core';\nimport {\n type DetokenizeTextParams,\n type GenerateTextParams,\n ModelType,\n type TokenizeTextParams,\n logger,\n} from '@elizaos/core';\nimport { generateObject, generateText } from 'ai';\nimport { type TiktokenModel, encodingForModel } from 'js-tiktoken';\nimport { z } from 'zod';\n\n/**\n * Runtime interface for the Groq plugin\n */\ninterface Runtime {\n getSetting(key: string): string | undefined;\n character: {\n system?: string;\n };\n fetch?: typeof fetch;\n}\n\n/**\n * Gets the Cloudflare Gateway base URL for a specific provider if enabled\n * @param runtime The runtime environment\n * @param provider The model provider name\n * @returns The Cloudflare Gateway base URL if enabled, undefined otherwise\n */\nfunction getCloudflareGatewayBaseURL(runtime: Runtime, provider: string): string | undefined {\n try {\n const isCloudflareEnabled = runtime.getSetting('CLOUDFLARE_GW_ENABLED') === 'true';\n const cloudflareAccountId = runtime.getSetting('CLOUDFLARE_AI_ACCOUNT_ID');\n const cloudflareGatewayId = runtime.getSetting('CLOUDFLARE_AI_GATEWAY_ID');\n\n const defaultUrl = 'https://api.groq.com/openai/v1';\n logger.debug('Cloudflare Gateway Configuration:', {\n isEnabled: isCloudflareEnabled,\n hasAccountId: !!cloudflareAccountId,\n hasGatewayId: !!cloudflareGatewayId,\n provider: provider,\n });\n\n if (!isCloudflareEnabled) {\n logger.debug('Cloudflare Gateway is not enabled');\n return defaultUrl;\n }\n\n if (!cloudflareAccountId) {\n logger.warn('Cloudflare Gateway is enabled but CLOUDFLARE_AI_ACCOUNT_ID is not set');\n return defaultUrl;\n }\n\n if (!cloudflareGatewayId) {\n logger.warn('Cloudflare Gateway is enabled but CLOUDFLARE_AI_GATEWAY_ID is not set');\n return defaultUrl;\n }\n\n const baseURL = `https://gateway.ai.cloudflare.com/v1/${cloudflareAccountId}/${cloudflareGatewayId}/${provider.toLowerCase()}`;\n logger.info('Using Cloudflare Gateway:', {\n provider,\n baseURL,\n accountId: cloudflareAccountId,\n gatewayId: cloudflareGatewayId,\n });\n\n return baseURL;\n } catch (error) {\n logger.error('Error in getCloudflareGatewayBaseURL:', error);\n return 'https://api.groq.com/openai/v1';\n }\n}\n\nfunction findModelName(model: ModelTypeName): TiktokenModel {\n try {\n const name =\n model === ModelType.TEXT_SMALL\n ? (process.env.SMALL_GROQ_MODEL ?? 'llama-3.1-8b-instant')\n : (process.env.LARGE_GROQ_MODEL ?? 'llama-3.2-90b-vision-preview');\n return name as TiktokenModel;\n } catch (error) {\n logger.error('Error in findModelName:', error);\n return 'llama-3.1-8b-instant' as TiktokenModel;\n }\n}\n\nasync function tokenizeText(model: ModelTypeName, prompt: string) {\n try {\n const encoding = encodingForModel(findModelName(model));\n const tokens = encoding.encode(prompt);\n return tokens;\n } catch (error) {\n logger.error('Error in tokenizeText:', error);\n return [];\n }\n}\n\n/**\n * Detokenize a sequence of tokens back into text using the specified model.\n *\n * @param {ModelTypeName} model - The type of model to use for detokenization.\n * @param {number[]} tokens - The sequence of tokens to detokenize.\n * @returns {string} The detokenized text.\n */\nasync function detokenizeText(model: ModelTypeName, tokens: number[]) {\n try {\n const modelName = findModelName(model);\n const encoding = encodingForModel(modelName);\n return encoding.decode(tokens);\n } catch (error) {\n logger.error('Error in detokenizeText:', error);\n return '';\n }\n}\n\n/**\n * Handles rate limit errors, waits for the appropriate delay, and retries the operation\n * @param error The error object from the failed request\n * @param retryFn The function to retry after waiting\n * @returns Result from the retry function\n */\nasync function handleRateLimitError(error: Error, retryFn: () => Promise<unknown>) {\n try {\n if (error.message.includes('Rate limit reached')) {\n logger.warn('Groq rate limit reached', { error: error.message });\n\n // Extract retry delay from error message if possible\n let retryDelay = 10000; // Default to 10 seconds\n const delayMatch = error.message.match(/try again in (\\d+\\.?\\d*)s/i);\n if (delayMatch?.[1]) {\n // Convert to milliseconds and add a small buffer\n retryDelay = Math.ceil(Number.parseFloat(delayMatch[1]) * 1000) + 1000;\n }\n\n logger.info(`Will retry after ${retryDelay}ms delay`);\n\n // Wait for the suggested delay plus a small buffer\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n\n // Retry the request\n logger.info('Retrying request after rate limit delay');\n return await retryFn();\n }\n\n // For other errors, log and rethrow\n logger.error('Error with Groq API:', error);\n throw error;\n } catch (retryError) {\n logger.error('Error during retry handling:', retryError);\n throw retryError;\n }\n}\n\n/**\n * Generate text using Groq API with retry handling for rate limits\n */\nasync function generateGroqText(\n groq: ReturnType<typeof createGroq>,\n model: string,\n params: {\n prompt: string;\n system?: string;\n temperature: number;\n maxTokens: number;\n frequencyPenalty: number;\n presencePenalty: number;\n stopSequences: string[];\n }\n) {\n try {\n const { text: groqResponse } = await generateText({\n model: groq.languageModel(model),\n prompt: params.prompt,\n system: params.system,\n temperature: params.temperature,\n maxTokens: params.maxTokens,\n frequencyPenalty: params.frequencyPenalty,\n presencePenalty: params.presencePenalty,\n stopSequences: params.stopSequences,\n });\n return groqResponse;\n } catch (error: unknown) {\n try {\n return await handleRateLimitError(error as Error, async () => {\n const { text: groqRetryResponse } = await generateText({\n model: groq.languageModel(model),\n prompt: params.prompt,\n system: params.system,\n temperature: params.temperature,\n maxTokens: params.maxTokens,\n frequencyPenalty: params.frequencyPenalty,\n presencePenalty: params.presencePenalty,\n stopSequences: params.stopSequences,\n });\n return groqRetryResponse;\n });\n } catch (retryError) {\n logger.error('Final error in generateGroqText:', retryError);\n return 'Error generating text. Please try again later.';\n }\n }\n}\n\n/**\n * Generate object using Groq API with consistent error handling\n */\nasync function generateGroqObject(\n groq: ReturnType<typeof createGroq>,\n model: string,\n params: ObjectGenerationParams\n) {\n try {\n const { object } = await generateObject({\n model: groq.languageModel(model),\n output: 'no-schema',\n prompt: params.prompt,\n temperature: params.temperature,\n });\n return object;\n } catch (error: unknown) {\n logger.error('Error generating object:', error);\n return {};\n }\n}\n\nexport const groqPlugin: Plugin = {\n name: 'groq',\n description: 'Groq plugin',\n config: {\n GROQ_API_KEY: process.env.GROQ_API_KEY,\n SMALL_GROQ_MODEL: process.env.SMALL_GROQ_MODEL,\n MEDIUM_GROQ_MODEL: process.env.MEDIUM_GROQ_MODEL,\n LARGE_GROQ_MODEL: process.env.LARGE_GROQ_MODEL,\n },\n async init(config: Record<string, string>) {\n if (!process.env.GROQ_API_KEY) {\n throw Error('Missing GROQ_API_KEY in environment variables');\n }\n },\n models: {\n [ModelType.TEXT_EMBEDDING]: async (\n runtime,\n params: TextEmbeddingParams | string | null\n ): Promise<number[]> => {\n try {\n const testVector = Array(1536).fill(0);\n testVector[0] = 0.1;\n return testVector;\n } catch (error) {\n logger.error('Error in TEXT_EMBEDDING model:', error);\n // Return a fallback vector rather than crashing\n return Array(1536).fill(0);\n }\n },\n [ModelType.TEXT_TOKENIZER_ENCODE]: async (\n _runtime,\n { prompt, modelType = ModelType.TEXT_LARGE }: TokenizeTextParams\n ) => {\n try {\n return await tokenizeText(modelType ?? ModelType.TEXT_LARGE, prompt);\n } catch (error) {\n logger.error('Error in TEXT_TOKENIZER_ENCODE model:', error);\n // Return empty array instead of crashing\n return [];\n }\n },\n [ModelType.TEXT_TOKENIZER_DECODE]: async (\n _runtime,\n { tokens, modelType = ModelType.TEXT_LARGE }: DetokenizeTextParams\n ) => {\n try {\n return await detokenizeText(modelType ?? ModelType.TEXT_LARGE, tokens);\n } catch (error) {\n logger.error('Error in TEXT_TOKENIZER_DECODE model:', error);\n // Return empty string instead of crashing\n return '';\n }\n },\n [ModelType.TEXT_SMALL]: async (runtime, { prompt, stopSequences = [] }: GenerateTextParams) => {\n try {\n const temperature = 0.7;\n const frequency_penalty = 0.7;\n const presence_penalty = 0.7;\n const max_response_length = 8000;\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n fetch: runtime.fetch,\n baseURL,\n });\n\n const model =\n runtime.getSetting('GROQ_SMALL_MODEL') ??\n runtime.getSetting('SMALL_MODEL') ??\n 'llama-3.1-8b-instant';\n\n logger.log('generating text');\n logger.log(prompt);\n\n return await generateGroqText(groq, model, {\n prompt,\n system: runtime.character.system ?? undefined,\n temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences,\n });\n } catch (error) {\n logger.error('Error in TEXT_SMALL model:', error);\n return 'Error generating text. Please try again later.';\n }\n },\n [ModelType.TEXT_LARGE]: async (\n runtime,\n {\n prompt,\n stopSequences = [],\n maxTokens = 8192,\n temperature = 0.7,\n frequencyPenalty = 0.7,\n presencePenalty = 0.7,\n }: GenerateTextParams\n ) => {\n try {\n const model =\n runtime.getSetting('GROQ_LARGE_MODEL') ??\n runtime.getSetting('LARGE_MODEL') ??\n 'llama-3.2-90b';\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n fetch: runtime.fetch,\n baseURL,\n });\n\n return await generateGroqText(groq, model, {\n prompt,\n system: runtime.character.system ?? undefined,\n temperature,\n maxTokens,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n });\n } catch (error) {\n logger.error('Error in TEXT_LARGE model:', error);\n return 'Error generating text. Please try again later.';\n }\n },\n [ModelType.IMAGE]: async (\n runtime,\n params: {\n prompt: string;\n n?: number;\n size?: string;\n }\n ) => {\n try {\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n const response = await fetch(`${baseURL}/images/generations`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n prompt: params.prompt,\n n: params.n || 1,\n size: params.size || '1024x1024',\n }),\n });\n if (!response.ok) {\n logger.error(`Failed to generate image: ${response.statusText}`);\n return [{ url: '' }];\n }\n const data = await response.json();\n const typedData = data as { data: { url: string }[] };\n return typedData.data;\n } catch (error) {\n logger.error('Error in IMAGE model:', error);\n return [{ url: '' }];\n }\n },\n [ModelType.TRANSCRIPTION]: async (runtime, audioBuffer: Buffer) => {\n try {\n logger.log('audioBuffer', audioBuffer);\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n\n // Create a FormData instance\n const formData = new FormData();\n\n // Create a proper interface for FormData to avoid type errors\n interface EnhancedFormData extends FormData {\n append(name: string, value: string | Blob, fileName?: string): void;\n }\n\n // Cast to our enhanced interface\n const enhancedFormData = formData as EnhancedFormData;\n enhancedFormData.append('file', new Blob([audioBuffer], { type: 'audio/mp3' }));\n enhancedFormData.append('model', 'whisper-1');\n\n const response = await fetch(`${baseURL}/audio/transcriptions`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n },\n body: formData,\n });\n\n logger.log('response', response);\n if (!response.ok) {\n logger.error(`Failed to transcribe audio: ${response.statusText}`);\n return 'Error transcribing audio. Please try again later.';\n }\n const data = (await response.json()) as { text: string };\n return data.text;\n } catch (error) {\n logger.error('Error in TRANSCRIPTION model:', error);\n return 'Error transcribing audio. Please try again later.';\n }\n },\n [ModelType.OBJECT_SMALL]: async (runtime, params: ObjectGenerationParams) => {\n try {\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n baseURL,\n });\n const model =\n runtime.getSetting('GROQ_SMALL_MODEL') ??\n runtime.getSetting('SMALL_MODEL') ??\n 'llama-3.1-8b-instant';\n\n if (params.schema) {\n logger.info('Using OBJECT_SMALL without schema validation');\n }\n\n return await generateGroqObject(groq, model, params);\n } catch (error) {\n logger.error('Error in OBJECT_SMALL model:', error);\n // Return empty object instead of crashing\n return {};\n }\n },\n [ModelType.OBJECT_LARGE]: async (runtime, params: ObjectGenerationParams) => {\n try {\n const baseURL = getCloudflareGatewayBaseURL(runtime, 'groq');\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n baseURL,\n });\n const model =\n runtime.getSetting('GROQ_LARGE_MODEL') ??\n runtime.getSetting('LARGE_MODEL') ??\n 'llama-3.2-90b-vision-preview';\n\n if (params.schema) {\n logger.info('Using OBJECT_LARGE without schema validation');\n }\n\n return await generateGroqObject(groq, model, params);\n } catch (error) {\n logger.error('Error in OBJECT_LARGE model:', error);\n // Return empty object instead of crashing\n return {};\n }\n },\n },\n tests: [\n {\n name: 'groq_plugin_tests',\n tests: [\n {\n name: 'groq_test_url_and_api_key_validation',\n fn: async (runtime) => {\n try {\n const baseURL =\n getCloudflareGatewayBaseURL(runtime, 'groq') ?? 'https://api.groq.com/openai/v1';\n const response = await fetch(`${baseURL}/models`, {\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n },\n });\n const data = await response.json();\n logger.log('Models Available:', (data as { data: unknown[] })?.data?.length);\n if (!response.ok) {\n logger.error(`Failed to validate Groq API key: ${response.statusText}`);\n return;\n }\n } catch (error) {\n logger.error('Error in groq_test_url_and_api_key_validation:', error);\n }\n },\n },\n {\n name: 'groq_test_text_embedding',\n fn: async (runtime) => {\n try {\n const embedding = await runtime.useModel(ModelType.TEXT_EMBEDDING, {\n text: 'Hello, world!',\n });\n logger.log('embedding', embedding);\n } catch (error) {\n logger.error('Error in test_text_embedding:', error);\n }\n },\n },\n {\n name: 'groq_test_text_large',\n fn: async (runtime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n logger.error('Failed to generate text');\n return;\n }\n logger.log('generated with test_text_large:', text);\n } catch (error) {\n logger.error('Error in test_text_large:', error);\n }\n },\n },\n {\n name: 'groq_test_text_small',\n fn: async (runtime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n logger.error('Failed to generate text');\n return;\n }\n logger.log('generated with test_text_small:', text);\n } catch (error) {\n logger.error('Error in test_text_small:', error);\n }\n },\n },\n {\n name: 'groq_test_image_generation',\n fn: async (runtime) => {\n try {\n logger.log('groq_test_image_generation');\n const image = await runtime.useModel(ModelType.IMAGE, {\n prompt: 'A beautiful sunset over a calm ocean',\n n: 1,\n size: '1024x1024',\n });\n logger.log('generated with test_image_generation:', image);\n } catch (error) {\n logger.error('Error in test_image_generation:', error);\n }\n },\n },\n {\n name: 'groq_test_transcription',\n fn: async (runtime) => {\n try {\n logger.log('groq_test_transcription');\n const response = await fetch(\n 'https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg'\n );\n if (!response.ok) {\n logger.error(`Failed to fetch audio sample: ${response.statusText}`);\n return;\n }\n const arrayBuffer = await response.arrayBuffer();\n const transcription = await runtime.useModel(\n ModelType.TRANSCRIPTION,\n Buffer.from(new Uint8Array(arrayBuffer))\n );\n logger.log('generated with test_transcription:', transcription);\n } catch (error) {\n logger.error('Error in test_transcription:', error);\n }\n },\n },\n {\n name: 'groq_test_text_tokenizer_encode',\n fn: async (runtime) => {\n try {\n const prompt = 'Hello tokenizer encode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n if (!Array.isArray(tokens) || tokens.length === 0) {\n logger.error('Failed to tokenize text: expected non-empty array of tokens');\n return;\n }\n logger.log('Tokenized output:', tokens);\n } catch (error) {\n logger.error('Error in test_text_tokenizer_encode:', error);\n }\n },\n },\n {\n name: 'groq_test_text_tokenizer_decode',\n fn: async (runtime) => {\n try {\n const prompt = 'Hello tokenizer decode!';\n // Encode the string into tokens first\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n // Now decode tokens back into text\n const decodedText = await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, {\n tokens,\n });\n if (decodedText !== prompt) {\n logger.error(\n `Decoded text does not match original. Expected \"${prompt}\", got \"${decodedText}\"`\n );\n return;\n }\n logger.log('Decoded text:', decodedText);\n } catch (error) {\n logger.error('Error in test_text_tokenizer_decode:', error);\n }\n },\n },\n {\n name: 'groq_test_object_small',\n fn: async (runtime) => {\n try {\n const object = await runtime.useModel(ModelType.OBJECT_SMALL, {\n prompt:\n 'Generate a JSON object representing a user profile with name, age, and hobbies',\n temperature: 0.7,\n });\n logger.log('Generated object:', object);\n } catch (error) {\n logger.error('Error in test_object_small:', error);\n }\n },\n },\n {\n name: 'groq_test_object_large',\n fn: async (runtime) => {\n try {\n const object = await runtime.useModel(ModelType.OBJECT_LARGE, {\n prompt:\n 'Generate a detailed JSON object representing a restaurant with name, cuisine type, menu items with prices, and customer reviews',\n temperature: 0.7,\n });\n logger.log('Generated object:', object);\n } catch (error) {\n logger.error('Error in test_object_large:', error);\n }\n },\n },\n ],\n },\n ],\n};\nexport default groqPlugin;\n"],"mappings":";AAAA,SAAS,kBAAkB;AAQ3B;AAAA,EAGE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,gBAAgB,oBAAoB;AAC7C,SAA6B,wBAAwB;AAoBrD,SAAS,4BAA4B,SAAkB,UAAsC;AAC3F,MAAI;AACF,UAAM,sBAAsB,QAAQ,WAAW,uBAAuB,MAAM;AAC5E,UAAM,sBAAsB,QAAQ,WAAW,0BAA0B;AACzE,UAAM,sBAAsB,QAAQ,WAAW,0BAA0B;AAEzE,UAAM,aAAa;AACnB,WAAO,MAAM,qCAAqC;AAAA,MAChD,WAAW;AAAA,MACX,cAAc,CAAC,CAAC;AAAA,MAChB,cAAc,CAAC,CAAC;AAAA,MAChB;AAAA,IACF,CAAC;AAED,QAAI,CAAC,qBAAqB;AACxB,aAAO,MAAM,mCAAmC;AAChD,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,qBAAqB;AACxB,aAAO,KAAK,uEAAuE;AACnF,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,qBAAqB;AACxB,aAAO,KAAK,uEAAuE;AACnF,aAAO;AAAA,IACT;AAEA,UAAM,UAAU,wCAAwC,mBAAmB,IAAI,mBAAmB,IAAI,SAAS,YAAY,CAAC;AAC5H,WAAO,KAAK,6BAA6B;AAAA,MACvC;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,WAAW;AAAA,IACb,CAA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ACN,IAAI,OAAO,YAAY;AACrB,gBAAI;AACF,oBAAM,SAAS,MAAM,QAAQ,SAAS,UAAU,cAAc;AAAA,gBAC5D,QACE;AAAA,gBACF,aAAa;AAAA,cACf,CAAC;AACD,qBAAO,IAAI,qBAAqB,MAAM;AAAA,YACxC,SAAS,OAAO;AACd,qBAAO,MAAM,+BAA+B,KAAK;AAAA,YACnD;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../node_modules/@opentelemetry/api/src/platform/node/globalThis.ts","../node_modules/@opentelemetry/api/src/version.ts","../node_modules/@opentelemetry/api/src/internal/semver.ts","../node_modules/@opentelemetry/api/src/internal/global-utils.ts","../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../node_modules/@opentelemetry/api/src/diag/types.ts","../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../node_modules/@opentelemetry/api/src/api/diag.ts","../node_modules/@opentelemetry/api/src/context/context.ts","../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts","../node_modules/@opentelemetry/api/src/api/context.ts","../node_modules/@opentelemetry/api/src/trace/status.ts","../node_modules/@opentelemetry/api/src/context-api.ts"],"sourcesContent":["import { createGroq } from '@ai-sdk/groq';\nimport type { IAgentRuntime, ModelTypeName, ObjectGenerationParams, Plugin } from '@elizaos/core';\nimport {\n type DetokenizeTextParams,\n type GenerateTextParams,\n ModelType,\n ServiceType,\n type TokenizeTextParams,\n type InstrumentationService,\n logger,\n} from '@elizaos/core';\nimport { generateObject, generateText } from 'ai';\nimport { type TiktokenModel, encodingForModel } from 'js-tiktoken';\nimport { context, SpanStatusCode, type Span } from '@opentelemetry/api';\n\n/**\n * Retrieves the Groq API base URL, using runtime settings or environment variables if available.\n *\n * @returns The resolved Groq API base URL.\n */\nfunction getBaseURL(runtime: any): string {\n return runtime.getSetting('GROQ_BASE_URL') || 'https://api.groq.com/openai/v1';\n}\n\n/**\n * Returns the appropriate Groq model name string for the specified model type.\n *\n * If environment variables for model names are set, they are used; otherwise, defaults are returned.\n *\n * @param model - The model type for which to retrieve the model name.\n * @returns The model name string corresponding to the given {@link model}.\n *\n * @remark If an error occurs, returns the default model name 'llama-3.1-8b-instant'.\n */\nfunction findModelName(runtime: IAgentRuntime, model: ModelTypeName): TiktokenModel {\n try {\n const name =\n model === ModelType.TEXT_SMALL\n ? (runtime.getSetting('GROQ_SMALL_MODEL') ?? 'llama-3.1-8b-instant')\n : (runtime.getSetting('GROQ_LARGE_MODEL') ?? 'qwen-qwq-32b');\n return name as TiktokenModel;\n } catch (error) {\n logger.error('Error in findModelName:', error);\n return 'llama-3.1-8b-instant' as TiktokenModel;\n }\n}\n\nasync function tokenizeText(runtime: IAgentRuntime, model: ModelTypeName, prompt: string) {\n try {\n const encoding = encodingForModel(findModelName(runtime, model));\n const tokens = encoding.encode(prompt);\n return tokens;\n } catch (error) {\n logger.error('Error in tokenizeText:', error);\n return [];\n }\n}\n\n/**\n * Detokenize a sequence of tokens back into text using the specified model.\n *\n * @param {ModelTypeName} model - The type of model to use for detokenization.\n * @param {number[]} tokens - The sequence of tokens to detokenize.\n * @returns {string} The detokenized text.\n */\nasync function detokenizeText(runtime: IAgentRuntime, model: ModelTypeName, tokens: number[]) {\n try {\n const modelName = findModelName(runtime, model);\n const encoding = encodingForModel(modelName);\n return encoding.decode(tokens);\n } catch (error) {\n logger.error('Error in detokenizeText:', error);\n return '';\n }\n}\n\n/**\n * Handles rate limit errors, waits for the appropriate delay, and retries the operation\n * @param error The error object from the failed request\n * @param retryFn The function to retry after waiting\n * @returns Result from the retry function\n */\nasync function handleRateLimitError(error: Error, retryFn: () => Promise<unknown>) {\n try {\n if (error.message.includes('Rate limit reached')) {\n logger.warn('Groq rate limit reached', { error: error.message });\n\n // Extract retry delay from error message if possible\n let retryDelay = 10000; // Default to 10 seconds\n const delayMatch = error.message.match(/try again in (\\d+\\.?\\d*)s/i);\n if (delayMatch?.[1]) {\n // Convert to milliseconds and add a small buffer\n retryDelay = Math.ceil(Number.parseFloat(delayMatch[1]) * 1000) + 1000;\n }\n\n logger.info(`Will retry after ${retryDelay}ms delay`);\n\n // Wait for the suggested delay plus a small buffer\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n\n // Retry the request\n logger.info('Retrying request after rate limit delay');\n return await retryFn();\n }\n\n // For other errors, log and rethrow\n logger.error('Error with Groq API:', error);\n throw error;\n } catch (retryError) {\n logger.error('Error during retry handling:', retryError);\n throw retryError;\n }\n}\n\n/**\n * Helper function to get tracer if instrumentation is enabled\n */\nfunction getTracer(runtime: IAgentRuntime) {\n const availableServices = Array.from(runtime.getAllServices().keys());\n logger.debug(`[getTracer] Available services: ${JSON.stringify(availableServices)}`);\n logger.debug(`[getTracer] Attempting to get service with key: ${ServiceType.INSTRUMENTATION}`);\n\n const instrumentationService = runtime.getService<InstrumentationService>(\n ServiceType.INSTRUMENTATION\n );\n\n if (!instrumentationService) {\n logger.warn(`[getTracer] Service ${ServiceType.INSTRUMENTATION} not found in runtime.`);\n return null;\n }\n\n if (!instrumentationService.isEnabled()) {\n logger.debug('[getTracer] Instrumentation service found but is disabled.');\n return null;\n }\n\n logger.debug('[getTracer] Successfully retrieved enabled instrumentation service.');\n return instrumentationService.getTracer('eliza.llm.openai');\n}\n\n/**\n * Helper function to start an LLM span\n */\nasync function startLlmSpan<T>(\n runtime: IAgentRuntime,\n spanName: string,\n attributes: Record<string, string | number | boolean | undefined>,\n fn: (span: Span) => Promise<T>\n): Promise<T> {\n const tracer = getTracer(runtime);\n if (!tracer) {\n const dummySpan = {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n recordException: () => {},\n setStatus: () => {},\n end: () => {},\n spanContext: () => ({ traceId: '', spanId: '', traceFlags: 0 }),\n } as unknown as Span;\n return fn(dummySpan);\n }\n\n // Get active context to ensure proper nesting\n const activeContext = context.active();\n\n return tracer.startActiveSpan(spanName, { attributes }, activeContext, async (span: Span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.end();\n throw error;\n }\n });\n}\n\n\n/**\n * Generate text using Groq API with retry handling for rate limits\n */\nasync function generateGroqText(\n groq: ReturnType<typeof createGroq>,\n model: string,\n params: {\n prompt: string;\n system?: string;\n temperature: number;\n maxTokens: number;\n frequencyPenalty: number;\n presencePenalty: number;\n stopSequences: string[];\n }\n) {\n try {\n const { text: groqResponse } = await generateText({\n model: groq.languageModel(model),\n prompt: params.prompt,\n system: params.system,\n temperature: params.temperature,\n maxTokens: params.maxTokens,\n frequencyPenalty: params.frequencyPenalty,\n presencePenalty: params.presencePenalty,\n stopSequences: params.stopSequences,\n });\n return groqResponse;\n } catch (error: unknown) {\n try {\n return await handleRateLimitError(error as Error, async () => {\n const { text: groqRetryResponse } = await generateText({\n model: groq.languageModel(model),\n prompt: params.prompt,\n system: params.system,\n temperature: params.temperature,\n maxTokens: params.maxTokens,\n frequencyPenalty: params.frequencyPenalty,\n presencePenalty: params.presencePenalty,\n stopSequences: params.stopSequences,\n });\n return groqRetryResponse;\n });\n } catch (retryError) {\n logger.error('Final error in generateGroqText:', retryError);\n return 'Error generating text. Please try again later.';\n }\n }\n}\n\n/**\n * Generate object using Groq API with consistent error handling\n */\nasync function generateGroqObject(\n groq: ReturnType<typeof createGroq>,\n model: string,\n params: ObjectGenerationParams\n) {\n try {\n const { object } = await generateObject({\n model: groq.languageModel(model),\n output: 'no-schema',\n prompt: params.prompt,\n temperature: params.temperature,\n });\n return object;\n } catch (error: unknown) {\n logger.error('Error generating object:', error);\n return {};\n }\n}\n\nexport const groqPlugin: Plugin = {\n name: 'groq',\n description: 'Groq plugin',\n async init(config: Record<string, string>, runtime: IAgentRuntime) {\n if (!runtime.getSetting('GROQ_API_KEY')) {\n throw Error('Missing GROQ_API_KEY in environment variables');\n }\n },\n models: {\n [ModelType.TEXT_TOKENIZER_ENCODE]: async (\n runtime,\n { prompt, modelType = ModelType.TEXT_LARGE }: TokenizeTextParams\n ) => {\n try {\n return await tokenizeText(runtime, modelType ?? ModelType.TEXT_LARGE, prompt);\n } catch (error) {\n logger.error('Error in TEXT_TOKENIZER_ENCODE model:', error);\n // Return empty array instead of crashing\n return [];\n }\n },\n [ModelType.TEXT_TOKENIZER_DECODE]: async (\n runtime,\n { tokens, modelType = ModelType.TEXT_LARGE }: DetokenizeTextParams\n ) => {\n try {\n return await detokenizeText(runtime, modelType ?? ModelType.TEXT_LARGE, tokens);\n } catch (error) {\n logger.error('Error in TEXT_TOKENIZER_DECODE model:', error);\n // Return empty string instead of crashing\n return '';\n }\n },\n [ModelType.TEXT_SMALL]: async (runtime, { prompt, stopSequences = [] }: GenerateTextParams) => {\n try {\n const temperature = 0.7;\n const frequency_penalty = 0.7;\n const presence_penalty = 0.7;\n const max_response_length = 8000;\n const baseURL = getBaseURL(runtime);\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n fetch: runtime.fetch,\n baseURL,\n });\n\n const model =\n runtime.getSetting('GROQ_SMALL_MODEL') ??\n runtime.getSetting('SMALL_MODEL') ??\n 'llama-3.1-8b-instant';\n\n logger.log('generating text');\n logger.log(prompt);\n\n return await generateGroqText(groq, model, {\n prompt,\n system: runtime.character.system ?? undefined,\n temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences,\n });\n } catch (error) {\n logger.error('Error in TEXT_SMALL model:', error);\n return 'Error generating text. Please try again later.';\n }\n },\n [ModelType.TEXT_LARGE]: async (\n runtime,\n {\n prompt,\n stopSequences = [],\n maxTokens = 8192,\n temperature = 0.7,\n frequencyPenalty = 0.7,\n presencePenalty = 0.7,\n }: GenerateTextParams\n ) => {\n try {\n const model =\n runtime.getSetting('GROQ_LARGE_MODEL') ??\n runtime.getSetting('LARGE_MODEL') ??\n 'qwen-qwq-32b';\n const baseURL = getBaseURL(runtime);\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n fetch: runtime.fetch,\n baseURL,\n });\n\n return await generateGroqText(groq, model, {\n prompt,\n system: runtime.character.system ?? undefined,\n temperature,\n maxTokens,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n });\n } catch (error) {\n logger.error('Error in TEXT_LARGE model:', error);\n return 'Error generating text. Please try again later.';\n }\n },\n [ModelType.IMAGE]: async (\n runtime,\n params: {\n prompt: string;\n n?: number;\n size?: string;\n }\n ) => {\n try {\n const baseURL = getBaseURL(runtime);\n const response = await fetch(`${baseURL}/images/generations`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n prompt: params.prompt,\n n: params.n || 1,\n size: params.size || '1024x1024',\n }),\n });\n if (!response.ok) {\n logger.error(`Failed to generate image: ${response.statusText}`);\n return [{ url: '' }];\n }\n const data = await response.json();\n const typedData = data as { data: { url: string }[] };\n return typedData.data;\n } catch (error) {\n logger.error('Error in IMAGE model:', error);\n return [{ url: '' }];\n }\n },\n [ModelType.TRANSCRIPTION]: async (runtime, audioBuffer: Buffer) => {\n try {\n const baseURL = getBaseURL(runtime);\n\n // Create a FormData instance\n const formData = new FormData();\n const file = new File([audioBuffer], 'audio.mp3', { type: 'audio/mp3' });\n formData.append('file', file);\n formData.append('model', 'distil-whisper-large-v3-en');\n\n const response = await fetch(`${baseURL}/audio/transcriptions`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n },\n body: formData,\n });\n\n if (!response.ok) {\n logger.error(`Failed to transcribe audio: ${response.statusText}`);\n return 'Error transcribing audio. Please try again later.';\n }\n const data = (await response.json()) as { text: string };\n return data.text;\n } catch (error) {\n //console.error('groq audio', error)\n logger.error('Error in TRANSCRIPTION model:', error);\n return 'Error transcribing audio. Please try again later.';\n }\n },\n // you can include elevenlabs before this plugin to prefer elevenlabs voice\n // The model playai-tts requires terms acceptance. Please have the org admin accept the terms at https://console.groq.com/playground?model=playai-tts\"\n [ModelType.TEXT_TO_SPEECH]: async (runtime: IAgentRuntime, text: string) => {\n const ttsModelName = runtime.getSetting('GROQ_TTS_MODEL') || 'playai-tts';\n const voice = runtime.getSetting('GROQ_TTS_VOICE') || 'Chip-PlayAI';\n const attributes = {\n 'llm.vendor': 'Groq',\n 'llm.request.type': 'tts',\n 'llm.request.model': ttsModelName,\n 'input.text.length': text.length,\n };\n return startLlmSpan(runtime, 'LLM.tts', attributes, async (span) => {\n logger.log(`[Groq] Using TEXT_TO_SPEECH model: ${ttsModelName}`);\n span.addEvent('llm.prompt', { 'prompt.content': text });\n try {\n const baseURL = getBaseURL(runtime);\n const res = await fetch(`${baseURL}/audio/speech`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: ttsModelName,\n voice,\n input: text,\n //...(instructions && { instructions }),\n }),\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Groq TTS error ${res.status}: ${err}`);\n }\n\n const speechStream = res.body;\n //const speechStream = await fetchTextToSpeech(runtime, text);\n span.addEvent('llm.response.success', {\n info: 'Speech stream generated',\n });\n return speechStream;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\n });\n },\n [ModelType.OBJECT_SMALL]: async (runtime, params: ObjectGenerationParams) => {\n try {\n const baseURL = getBaseURL(runtime);\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n baseURL,\n });\n const model =\n runtime.getSetting('GROQ_SMALL_MODEL') ??\n runtime.getSetting('SMALL_MODEL') ??\n 'llama-3.1-8b-instant';\n\n if (params.schema) {\n logger.info('Using OBJECT_SMALL without schema validation');\n }\n\n return await generateGroqObject(groq, model, params);\n } catch (error) {\n logger.error('Error in OBJECT_SMALL model:', error);\n // Return empty object instead of crashing\n return {};\n }\n },\n [ModelType.OBJECT_LARGE]: async (runtime, params: ObjectGenerationParams) => {\n try {\n const baseURL = getBaseURL(runtime);\n const groq = createGroq({\n apiKey: runtime.getSetting('GROQ_API_KEY'),\n baseURL,\n });\n const model =\n runtime.getSetting('GROQ_LARGE_MODEL') ??\n runtime.getSetting('LARGE_MODEL') ??\n 'qwen-qwq-32b';\n\n if (params.schema) {\n logger.info('Using OBJECT_LARGE without schema validation');\n }\n\n return await generateGroqObject(groq, model, params);\n } catch (error) {\n logger.error('Error in OBJECT_LARGE model:', error);\n // Return empty object instead of crashing\n return {};\n }\n },\n },\n tests: [\n {\n name: 'groq_plugin_tests',\n tests: [\n {\n name: 'groq_test_url_and_api_key_validation',\n fn: async (runtime) => {\n try {\n const baseURL = getBaseURL(runtime) ?? 'https://api.groq.com/openai/v1';\n const response = await fetch(`${baseURL}/models`, {\n headers: {\n Authorization: `Bearer ${runtime.getSetting('GROQ_API_KEY')}`,\n },\n });\n const data = await response.json();\n logger.log('Models Available:', (data as { data: unknown[] })?.data?.length);\n if (!response.ok) {\n logger.error(`Failed to validate Groq API key: ${response.statusText}`);\n return;\n }\n } catch (error) {\n logger.error('Error in groq_test_url_and_api_key_validation:', error);\n }\n },\n },\n {\n name: 'groq_test_text_large',\n fn: async (runtime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n logger.error('Failed to generate text');\n return;\n }\n logger.log('generated with test_text_large:', text);\n } catch (error) {\n logger.error('Error in test_text_large:', error);\n }\n },\n },\n {\n name: 'groq_test_text_small',\n fn: async (runtime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n logger.error('Failed to generate text');\n return;\n }\n logger.log('generated with test_text_small:', text);\n } catch (error) {\n logger.error('Error in test_text_small:', error);\n }\n },\n },\n {\n name: 'groq_test_image_generation',\n fn: async (runtime) => {\n try {\n logger.log('groq_test_image_generation');\n const image = await runtime.useModel(ModelType.IMAGE, {\n prompt: 'A beautiful sunset over a calm ocean',\n n: 1,\n size: '1024x1024',\n });\n logger.log('generated with test_image_generation:', image);\n } catch (error) {\n logger.error('Error in test_image_generation:', error);\n }\n },\n },\n {\n name: 'groq_test_transcription',\n fn: async (runtime) => {\n try {\n logger.log('groq_test_transcription');\n const response = await fetch(\n 'https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg'\n );\n if (!response.ok) {\n logger.error(`Failed to fetch audio sample: ${response.statusText}`);\n return;\n }\n const arrayBuffer = await response.arrayBuffer();\n const transcription = await runtime.useModel(\n ModelType.TRANSCRIPTION,\n Buffer.from(new Uint8Array(arrayBuffer))\n );\n logger.log('generated with test_transcription:', transcription);\n } catch (error) {\n logger.error('Error in test_transcription:', error);\n }\n },\n },\n {\n name: 'groq_test_text_tokenizer_encode',\n fn: async (runtime) => {\n try {\n const prompt = 'Hello tokenizer encode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n if (!Array.isArray(tokens) || tokens.length === 0) {\n logger.error('Failed to tokenize text: expected non-empty array of tokens');\n return;\n }\n logger.log('Tokenized output:', tokens);\n } catch (error) {\n logger.error('Error in test_text_tokenizer_encode:', error);\n }\n },\n },\n {\n name: 'groq_test_text_tokenizer_decode',\n fn: async (runtime) => {\n try {\n const prompt = 'Hello tokenizer decode!';\n // Encode the string into tokens first\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n // Now decode tokens back into text\n const decodedText = await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, {\n tokens,\n });\n if (decodedText !== prompt) {\n logger.error(\n `Decoded text does not match original. Expected \"${prompt}\", got \"${decodedText}\"`\n );\n return;\n }\n logger.log('Decoded text:', decodedText);\n } catch (error) {\n logger.error('Error in test_text_tokenizer_decode:', error);\n }\n },\n },\n {\n name: 'groq_test_object_small',\n fn: async (runtime) => {\n try {\n const object = await runtime.useModel(ModelType.OBJECT_SMALL, {\n prompt:\n 'Generate a JSON object representing a user profile with name, age, and hobbies',\n temperature: 0.7,\n });\n logger.log('Generated object:', object);\n } catch (error) {\n logger.error('Error in test_object_small:', error);\n }\n },\n },\n {\n name: 'groq_test_object_large',\n fn: async (runtime) => {\n try {\n const object = await runtime.useModel(ModelType.OBJECT_LARGE, {\n prompt:\n 'Generate a detailed JSON object representing a restaurant with name, cuisine type, menu items with prices, and customer reviews',\n temperature: 0.7,\n });\n logger.log('Generated object:', object);\n } catch (error) {\n logger.error('Error in test_object_large:', error);\n }\n },\n },\n ],\n },\n ],\n};\nexport default groqPlugin;\n","/*\n * Copyright The OpenTelemetry Authors\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\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n","/*\n * Copyright The OpenTelemetry Authors\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 type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map<symbol, unknown>;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map<symbol, unknown>) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return fn.call(thisArg, ...args);\n }\n\n bind<T>(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\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\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind<T>(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\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 */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n","/*\n * Copyright The OpenTelemetry Authors\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\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B;AAAA,EAGE;AAAA,EACA;AAAA,EAGA;AAAA,OACK;AACP,SAAS,gBAAgB,oBAAoB;AAC7C,SAA6B,wBAAwB;;;ACM9C,IAAM,cAAc,OAAO,eAAe,WAAW,aAAa;;;ACDlE,IAAM,UAAU;;;ACCvB,IAAM,KAAK;AAkBL,SAAU,wBACd,YAAkB;AAElB,MAAM,mBAAmB,oBAAI,IAAY,CAAC,UAAU,CAAC;AACrD,MAAM,mBAAmB,oBAAI,IAAG;AAEhC,MAAM,iBAAiB,WAAW,MAAM,EAAE;AAC1C,MAAI,CAAC,gBAAgB;AAEnB,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;AAEf,oBAAM,SAAS,MAAM,QAAQ,SAAS,UAAU,uBAAuB,EAAE,OAAO,CAAC;AAEjF,oBAAM,cAAc,MAAM,QAAQ,SAAS,UAAU,uBAAuB;AAAA,gBAC1E;AAAA,cACF,CAAC;AACD,kBAAI,gBAAgB,QAAQ;AAC1B,uBAAO;AAAA,kBACL,mDAAmD,MAAM,WAAW,WAAW;AAAA,gBACjF;AACA;AAAA,cACF;AACA,qBAAO,IAAI,iBAAiB,WAAW;AAAA,YACzC,SAAS,OAAO;AACd,qBAAO,MAAM,wCAAwC,KAAK;AAAA,YAC5D;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,IAAI,OAAO,YAAY;AACrB,gBAAI;AACF,oBAAM,SAAS,MAAM,QAAQ,SAAS,UAAU,cAAc;AAAA,gBAC5D,QACE;AAAA,gBACF,aAAa;AAAA,cACf,CAAC;AACD,qBAAO,IAAI,qBAAqB,MAAM;AAAA,YACxC,SAAS,OAAO;AACd,qBAAO,MAAM,+BAA+B,KAAK;AAAA,YACnD;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,IAAI,OAAO,YAAY;AACrB,gBAAI;AACF,oBAAM,SAAS,MAAM,QAAQ,SAAS,UAAU,cAAc;AAAA,gBAC5D,QACE;AAAA,gBACF,aAAa;AAAA,cACf,CAAC;AACD,qBAAO,IAAI,qBAAqB,MAAM;AAAA,YACxC,SAAS,OAAO;AACd,qBAAO,MAAM,+BAA+B,KAAK;AAAA,YACnD;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;","names":["isCompatible","DiagComponentLogger","logger","DiagLogLevel","logger","DiagAPI","logger","__spreadArray","__read","BaseContext","context","NoopContextManager","__spreadArray","__read","API_NAME","ContextAPI","context","__spreadArray","__read","SpanStatusCode"]}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@elizaos/plugin-groq",
3
- "version": "1.0.0-beta.8",
3
+ "version": "1.0.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/elizaos-plugins/plugin-groq"
10
+ "url": "git+https://github.com/elizaos-plugins/plugin-groq.git"
11
11
  },
12
12
  "exports": {
13
13
  "./package.json": "./package.json",
@@ -22,10 +22,10 @@
22
22
  "dist"
23
23
  ],
24
24
  "dependencies": {
25
- "@ai-sdk/groq": "^1.1.9",
26
- "@ai-sdk/ui-utils": "1.1.9",
27
- "@elizaos/core": "1.0.0-beta.8",
28
- "ai": "^4.1.25",
25
+ "@ai-sdk/groq": "^1.2.9",
26
+ "@ai-sdk/ui-utils": "^1.2.11",
27
+ "@elizaos/core": "^1.0.0",
28
+ "ai": "^4.3.15",
29
29
  "js-tiktoken": "^1.0.18",
30
30
  "tsup": "8.4.0"
31
31
  },
@@ -35,7 +35,8 @@
35
35
  "lint": "prettier --write ./src",
36
36
  "clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
37
37
  "format": "prettier --write ./src",
38
- "format:check": "prettier --check ./src"
38
+ "format:check": "prettier --check ./src",
39
+ "test": "npx elizaos test"
39
40
  },
40
41
  "publishConfig": {
41
42
  "access": "public"
@@ -49,8 +50,9 @@
49
50
  }
50
51
  }
51
52
  },
52
- "gitHead": "a84e25ee21e33387a1303e62a2f95dc670ffddd4",
53
+ "gitHead": "646c632924826e2b75c2304a75ee56959fe4a460",
53
54
  "devDependencies": {
54
- "prettier": "3.5.3"
55
+ "prettier": "3.5.3",
56
+ "typescript": "^5.8.2"
55
57
  }
56
58
  }