@elizaos/plugin-openai 1.0.11 → 1.5.11
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 +45 -8
- package/dist/browser/index.browser.js +3 -0
- package/dist/browser/index.browser.js.map +10 -0
- package/dist/browser/index.d.ts +2 -0
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.node.cjs +751 -0
- package/dist/cjs/index.node.js.map +10 -0
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.d.ts +3 -5
- package/dist/index.node.d.ts +2 -0
- package/dist/node/index.d.ts +2 -0
- package/dist/{index.js → node/index.node.js} +59 -104
- package/dist/node/index.node.js.map +10 -0
- package/package.json +54 -23
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __moduleCache = /* @__PURE__ */ new WeakMap;
|
|
6
|
+
var __toCommonJS = (from) => {
|
|
7
|
+
var entry = __moduleCache.get(from), desc;
|
|
8
|
+
if (entry)
|
|
9
|
+
return entry;
|
|
10
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function")
|
|
12
|
+
__getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
|
|
13
|
+
get: () => from[key],
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
}));
|
|
16
|
+
__moduleCache.set(from, entry);
|
|
17
|
+
return entry;
|
|
18
|
+
};
|
|
19
|
+
var __export = (target, all) => {
|
|
20
|
+
for (var name in all)
|
|
21
|
+
__defProp(target, name, {
|
|
22
|
+
get: all[name],
|
|
23
|
+
enumerable: true,
|
|
24
|
+
configurable: true,
|
|
25
|
+
set: (newValue) => all[name] = () => newValue
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// src/index.node.ts
|
|
30
|
+
var exports_index_node = {};
|
|
31
|
+
__export(exports_index_node, {
|
|
32
|
+
openaiPlugin: () => openaiPlugin,
|
|
33
|
+
default: () => src_default
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(exports_index_node);
|
|
36
|
+
|
|
37
|
+
// src/index.ts
|
|
38
|
+
var import_openai = require("@ai-sdk/openai");
|
|
39
|
+
var import_core = require("@elizaos/core");
|
|
40
|
+
var import_ai = require("ai");
|
|
41
|
+
var import_js_tiktoken = require("js-tiktoken");
|
|
42
|
+
function getSetting(runtime, key, defaultValue) {
|
|
43
|
+
return runtime.getSetting(key) ?? process.env[key] ?? defaultValue;
|
|
44
|
+
}
|
|
45
|
+
function isBrowser() {
|
|
46
|
+
return typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
|
|
47
|
+
}
|
|
48
|
+
function getAuthHeader(runtime, forEmbedding = false) {
|
|
49
|
+
if (isBrowser())
|
|
50
|
+
return {};
|
|
51
|
+
const key = forEmbedding ? getEmbeddingApiKey(runtime) : getApiKey(runtime);
|
|
52
|
+
return key ? { Authorization: `Bearer ${key}` } : {};
|
|
53
|
+
}
|
|
54
|
+
function getBaseURL(runtime) {
|
|
55
|
+
const browserURL = getSetting(runtime, "OPENAI_BROWSER_BASE_URL");
|
|
56
|
+
const baseURL = isBrowser() && browserURL ? browserURL : getSetting(runtime, "OPENAI_BASE_URL", "https://api.openai.com/v1");
|
|
57
|
+
import_core.logger.debug(`[OpenAI] Default base URL: ${baseURL}`);
|
|
58
|
+
return baseURL;
|
|
59
|
+
}
|
|
60
|
+
function getEmbeddingBaseURL(runtime) {
|
|
61
|
+
const embeddingURL = isBrowser() ? getSetting(runtime, "OPENAI_BROWSER_EMBEDDING_URL") || getSetting(runtime, "OPENAI_BROWSER_BASE_URL") : getSetting(runtime, "OPENAI_EMBEDDING_URL");
|
|
62
|
+
if (embeddingURL) {
|
|
63
|
+
import_core.logger.debug(`[OpenAI] Using specific embedding base URL: ${embeddingURL}`);
|
|
64
|
+
return embeddingURL;
|
|
65
|
+
}
|
|
66
|
+
import_core.logger.debug("[OpenAI] Falling back to general base URL for embeddings.");
|
|
67
|
+
return getBaseURL(runtime);
|
|
68
|
+
}
|
|
69
|
+
function getApiKey(runtime) {
|
|
70
|
+
return getSetting(runtime, "OPENAI_API_KEY");
|
|
71
|
+
}
|
|
72
|
+
function getEmbeddingApiKey(runtime) {
|
|
73
|
+
const embeddingApiKey = getSetting(runtime, "OPENAI_EMBEDDING_API_KEY");
|
|
74
|
+
if (embeddingApiKey) {
|
|
75
|
+
import_core.logger.debug("[OpenAI] Using specific embedding API key (present)");
|
|
76
|
+
return embeddingApiKey;
|
|
77
|
+
}
|
|
78
|
+
import_core.logger.debug("[OpenAI] Falling back to general API key for embeddings.");
|
|
79
|
+
return getApiKey(runtime);
|
|
80
|
+
}
|
|
81
|
+
function getSmallModel(runtime) {
|
|
82
|
+
return getSetting(runtime, "OPENAI_SMALL_MODEL") ?? getSetting(runtime, "SMALL_MODEL", "gpt-5-nano");
|
|
83
|
+
}
|
|
84
|
+
function getLargeModel(runtime) {
|
|
85
|
+
return getSetting(runtime, "OPENAI_LARGE_MODEL") ?? getSetting(runtime, "LARGE_MODEL", "gpt-5-mini");
|
|
86
|
+
}
|
|
87
|
+
function getImageDescriptionModel(runtime) {
|
|
88
|
+
return getSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MODEL", "gpt-5-nano") ?? "gpt-5-nano";
|
|
89
|
+
}
|
|
90
|
+
function getExperimentalTelemetry(runtime) {
|
|
91
|
+
const setting = getSetting(runtime, "OPENAI_EXPERIMENTAL_TELEMETRY", "false");
|
|
92
|
+
const normalizedSetting = String(setting).toLowerCase();
|
|
93
|
+
const result = normalizedSetting === "true";
|
|
94
|
+
import_core.logger.debug(`[OpenAI] Experimental telemetry in function: "${setting}" (type: ${typeof setting}, normalized: "${normalizedSetting}", result: ${result})`);
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
function createOpenAIClient(runtime) {
|
|
98
|
+
return import_openai.createOpenAI({
|
|
99
|
+
apiKey: getApiKey(runtime),
|
|
100
|
+
baseURL: getBaseURL(runtime)
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async function tokenizeText(model, prompt) {
|
|
104
|
+
const modelName = model === import_core.ModelType.TEXT_SMALL ? process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? "gpt-5-nano" : process.env.LARGE_MODEL ?? "gpt-5-mini";
|
|
105
|
+
const tokens = import_js_tiktoken.encodingForModel(modelName).encode(prompt);
|
|
106
|
+
return tokens;
|
|
107
|
+
}
|
|
108
|
+
async function detokenizeText(model, tokens) {
|
|
109
|
+
const modelName = model === import_core.ModelType.TEXT_SMALL ? process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? "gpt-5-nano" : process.env.OPENAI_LARGE_MODEL ?? process.env.LARGE_MODEL ?? "gpt-5-mini";
|
|
110
|
+
return import_js_tiktoken.encodingForModel(modelName).decode(tokens);
|
|
111
|
+
}
|
|
112
|
+
async function generateObjectByModelType(runtime, params, modelType, getModelFn) {
|
|
113
|
+
const openai = createOpenAIClient(runtime);
|
|
114
|
+
const modelName = getModelFn(runtime);
|
|
115
|
+
import_core.logger.log(`[OpenAI] Using ${modelType} model: ${modelName}`);
|
|
116
|
+
const temperature = params.temperature ?? 0;
|
|
117
|
+
const schemaPresent = !!params.schema;
|
|
118
|
+
if (schemaPresent) {
|
|
119
|
+
import_core.logger.info(`Using ${modelType} without schema validation (schema provided but output=no-schema)`);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const { object, usage } = await import_ai.generateObject({
|
|
123
|
+
model: openai.languageModel(modelName),
|
|
124
|
+
output: "no-schema",
|
|
125
|
+
prompt: params.prompt,
|
|
126
|
+
temperature,
|
|
127
|
+
experimental_repairText: getJsonRepairFunction()
|
|
128
|
+
});
|
|
129
|
+
if (usage) {
|
|
130
|
+
emitModelUsageEvent(runtime, modelType, params.prompt, usage);
|
|
131
|
+
}
|
|
132
|
+
return object;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error instanceof import_ai.JSONParseError) {
|
|
135
|
+
import_core.logger.error(`[generateObject] Failed to parse JSON: ${error.message}`);
|
|
136
|
+
const repairFunction = getJsonRepairFunction();
|
|
137
|
+
const repairedJsonString = await repairFunction({
|
|
138
|
+
text: error.text,
|
|
139
|
+
error
|
|
140
|
+
});
|
|
141
|
+
if (repairedJsonString) {
|
|
142
|
+
try {
|
|
143
|
+
const repairedObject = JSON.parse(repairedJsonString);
|
|
144
|
+
import_core.logger.info("[generateObject] Successfully repaired JSON.");
|
|
145
|
+
return repairedObject;
|
|
146
|
+
} catch (repairParseError) {
|
|
147
|
+
const message = repairParseError instanceof Error ? repairParseError.message : String(repairParseError);
|
|
148
|
+
import_core.logger.error(`[generateObject] Failed to parse repaired JSON: ${message}`);
|
|
149
|
+
throw repairParseError;
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
import_core.logger.error("[generateObject] JSON repair failed.");
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
157
|
+
import_core.logger.error(`[generateObject] Unknown error: ${message}`);
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function getJsonRepairFunction() {
|
|
163
|
+
return async ({ text, error }) => {
|
|
164
|
+
try {
|
|
165
|
+
if (error instanceof import_ai.JSONParseError) {
|
|
166
|
+
const cleanedText = text.replace(/```json\n|\n```|```/g, "");
|
|
167
|
+
JSON.parse(cleanedText);
|
|
168
|
+
return cleanedText;
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
} catch (jsonError) {
|
|
172
|
+
const message = jsonError instanceof Error ? jsonError.message : String(jsonError);
|
|
173
|
+
import_core.logger.warn(`Failed to repair JSON text: ${message}`);
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function emitModelUsageEvent(runtime, type, prompt, usage) {
|
|
179
|
+
runtime.emitEvent(import_core.EventType.MODEL_USED, {
|
|
180
|
+
provider: "openai",
|
|
181
|
+
type,
|
|
182
|
+
prompt,
|
|
183
|
+
tokens: {
|
|
184
|
+
prompt: usage.inputTokens,
|
|
185
|
+
completion: usage.outputTokens,
|
|
186
|
+
total: usage.totalTokens
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
async function fetchTextToSpeech(runtime, text) {
|
|
191
|
+
const model = getSetting(runtime, "OPENAI_TTS_MODEL", "gpt-4o-mini-tts");
|
|
192
|
+
const voice = getSetting(runtime, "OPENAI_TTS_VOICE", "nova");
|
|
193
|
+
const instructions = getSetting(runtime, "OPENAI_TTS_INSTRUCTIONS", "");
|
|
194
|
+
const baseURL = getBaseURL(runtime);
|
|
195
|
+
try {
|
|
196
|
+
const res = await fetch(`${baseURL}/audio/speech`, {
|
|
197
|
+
method: "POST",
|
|
198
|
+
headers: {
|
|
199
|
+
...getAuthHeader(runtime),
|
|
200
|
+
"Content-Type": "application/json"
|
|
201
|
+
},
|
|
202
|
+
body: JSON.stringify({
|
|
203
|
+
model,
|
|
204
|
+
voice,
|
|
205
|
+
input: text,
|
|
206
|
+
...instructions && { instructions }
|
|
207
|
+
})
|
|
208
|
+
});
|
|
209
|
+
if (!res.ok) {
|
|
210
|
+
const err = await res.text();
|
|
211
|
+
throw new Error(`OpenAI TTS error ${res.status}: ${err}`);
|
|
212
|
+
}
|
|
213
|
+
return res.body;
|
|
214
|
+
} catch (err) {
|
|
215
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
216
|
+
throw new Error(`Failed to fetch speech from OpenAI TTS: ${message}`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
var openaiPlugin = {
|
|
220
|
+
name: "openai",
|
|
221
|
+
description: "OpenAI plugin",
|
|
222
|
+
config: {
|
|
223
|
+
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
|
|
224
|
+
OPENAI_BASE_URL: process.env.OPENAI_BASE_URL,
|
|
225
|
+
OPENAI_SMALL_MODEL: process.env.OPENAI_SMALL_MODEL,
|
|
226
|
+
OPENAI_LARGE_MODEL: process.env.OPENAI_LARGE_MODEL,
|
|
227
|
+
SMALL_MODEL: process.env.SMALL_MODEL,
|
|
228
|
+
LARGE_MODEL: process.env.LARGE_MODEL,
|
|
229
|
+
OPENAI_EMBEDDING_MODEL: process.env.OPENAI_EMBEDDING_MODEL,
|
|
230
|
+
OPENAI_EMBEDDING_API_KEY: process.env.OPENAI_EMBEDDING_API_KEY,
|
|
231
|
+
OPENAI_EMBEDDING_URL: process.env.OPENAI_EMBEDDING_URL,
|
|
232
|
+
OPENAI_EMBEDDING_DIMENSIONS: process.env.OPENAI_EMBEDDING_DIMENSIONS,
|
|
233
|
+
OPENAI_IMAGE_DESCRIPTION_MODEL: process.env.OPENAI_IMAGE_DESCRIPTION_MODEL,
|
|
234
|
+
OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS: process.env.OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS,
|
|
235
|
+
OPENAI_EXPERIMENTAL_TELEMETRY: process.env.OPENAI_EXPERIMENTAL_TELEMETRY
|
|
236
|
+
},
|
|
237
|
+
async init(_config, runtime) {
|
|
238
|
+
new Promise(async (resolve) => {
|
|
239
|
+
resolve();
|
|
240
|
+
try {
|
|
241
|
+
if (!getApiKey(runtime) && !isBrowser()) {
|
|
242
|
+
import_core.logger.warn("OPENAI_API_KEY is not set in environment - OpenAI functionality will be limited");
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const baseURL = getBaseURL(runtime);
|
|
247
|
+
const response = await fetch(`${baseURL}/models`, {
|
|
248
|
+
headers: { ...getAuthHeader(runtime) }
|
|
249
|
+
});
|
|
250
|
+
if (!response.ok) {
|
|
251
|
+
import_core.logger.warn(`OpenAI API key validation failed: ${response.statusText}`);
|
|
252
|
+
import_core.logger.warn("OpenAI functionality will be limited until a valid API key is provided");
|
|
253
|
+
} else {
|
|
254
|
+
import_core.logger.log("OpenAI API key validated successfully");
|
|
255
|
+
}
|
|
256
|
+
} catch (fetchError) {
|
|
257
|
+
const message = fetchError instanceof Error ? fetchError.message : String(fetchError);
|
|
258
|
+
import_core.logger.warn(`Error validating OpenAI API key: ${message}`);
|
|
259
|
+
import_core.logger.warn("OpenAI functionality will be limited until a valid API key is provided");
|
|
260
|
+
}
|
|
261
|
+
} catch (error) {
|
|
262
|
+
const message = error?.errors?.map((e) => e.message).join(", ") || (error instanceof Error ? error.message : String(error));
|
|
263
|
+
import_core.logger.warn(`OpenAI plugin configuration issue: ${message} - You need to configure the OPENAI_API_KEY in your environment variables`);
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
},
|
|
267
|
+
models: {
|
|
268
|
+
[import_core.ModelType.TEXT_EMBEDDING]: async (runtime, params) => {
|
|
269
|
+
const embeddingModelName = getSetting(runtime, "OPENAI_EMBEDDING_MODEL", "text-embedding-3-small");
|
|
270
|
+
const embeddingDimension = Number.parseInt(getSetting(runtime, "OPENAI_EMBEDDING_DIMENSIONS", "1536") || "1536", 10);
|
|
271
|
+
if (!Object.values(import_core.VECTOR_DIMS).includes(embeddingDimension)) {
|
|
272
|
+
const errorMsg = `Invalid embedding dimension: ${embeddingDimension}. Must be one of: ${Object.values(import_core.VECTOR_DIMS).join(", ")}`;
|
|
273
|
+
import_core.logger.error(errorMsg);
|
|
274
|
+
throw new Error(errorMsg);
|
|
275
|
+
}
|
|
276
|
+
if (params === null) {
|
|
277
|
+
import_core.logger.debug("Creating test embedding for initialization");
|
|
278
|
+
const testVector = Array(embeddingDimension).fill(0);
|
|
279
|
+
testVector[0] = 0.1;
|
|
280
|
+
return testVector;
|
|
281
|
+
}
|
|
282
|
+
let text;
|
|
283
|
+
if (typeof params === "string") {
|
|
284
|
+
text = params;
|
|
285
|
+
} else if (typeof params === "object" && params.text) {
|
|
286
|
+
text = params.text;
|
|
287
|
+
} else {
|
|
288
|
+
import_core.logger.warn("Invalid input format for embedding");
|
|
289
|
+
const fallbackVector = Array(embeddingDimension).fill(0);
|
|
290
|
+
fallbackVector[0] = 0.2;
|
|
291
|
+
return fallbackVector;
|
|
292
|
+
}
|
|
293
|
+
if (!text.trim()) {
|
|
294
|
+
import_core.logger.warn("Empty text for embedding");
|
|
295
|
+
const emptyVector = Array(embeddingDimension).fill(0);
|
|
296
|
+
emptyVector[0] = 0.3;
|
|
297
|
+
return emptyVector;
|
|
298
|
+
}
|
|
299
|
+
const embeddingBaseURL = getEmbeddingBaseURL(runtime);
|
|
300
|
+
try {
|
|
301
|
+
const response = await fetch(`${embeddingBaseURL}/embeddings`, {
|
|
302
|
+
method: "POST",
|
|
303
|
+
headers: {
|
|
304
|
+
...getAuthHeader(runtime, true),
|
|
305
|
+
"Content-Type": "application/json"
|
|
306
|
+
},
|
|
307
|
+
body: JSON.stringify({
|
|
308
|
+
model: embeddingModelName,
|
|
309
|
+
input: text
|
|
310
|
+
})
|
|
311
|
+
});
|
|
312
|
+
const responseClone = response.clone();
|
|
313
|
+
const rawResponseBody = await responseClone.text();
|
|
314
|
+
if (!response.ok) {
|
|
315
|
+
import_core.logger.error(`OpenAI API error: ${response.status} - ${response.statusText}`);
|
|
316
|
+
const errorVector = Array(embeddingDimension).fill(0);
|
|
317
|
+
errorVector[0] = 0.4;
|
|
318
|
+
return errorVector;
|
|
319
|
+
}
|
|
320
|
+
const data = await response.json();
|
|
321
|
+
if (!data?.data?.[0]?.embedding) {
|
|
322
|
+
import_core.logger.error("API returned invalid structure");
|
|
323
|
+
const errorVector = Array(embeddingDimension).fill(0);
|
|
324
|
+
errorVector[0] = 0.5;
|
|
325
|
+
return errorVector;
|
|
326
|
+
}
|
|
327
|
+
const embedding = data.data[0].embedding;
|
|
328
|
+
if (data.usage) {
|
|
329
|
+
const usage = {
|
|
330
|
+
inputTokens: data.usage.prompt_tokens,
|
|
331
|
+
outputTokens: 0,
|
|
332
|
+
totalTokens: data.usage.total_tokens
|
|
333
|
+
};
|
|
334
|
+
emitModelUsageEvent(runtime, import_core.ModelType.TEXT_EMBEDDING, text, usage);
|
|
335
|
+
}
|
|
336
|
+
import_core.logger.log(`Got valid embedding with length ${embedding.length}`);
|
|
337
|
+
return embedding;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
340
|
+
import_core.logger.error(`Error generating embedding: ${message}`);
|
|
341
|
+
const errorVector = Array(embeddingDimension).fill(0);
|
|
342
|
+
errorVector[0] = 0.6;
|
|
343
|
+
return errorVector;
|
|
344
|
+
}
|
|
345
|
+
},
|
|
346
|
+
[import_core.ModelType.TEXT_TOKENIZER_ENCODE]: async (_runtime, { prompt, modelType = import_core.ModelType.TEXT_LARGE }) => {
|
|
347
|
+
return await tokenizeText(modelType ?? import_core.ModelType.TEXT_LARGE, prompt);
|
|
348
|
+
},
|
|
349
|
+
[import_core.ModelType.TEXT_TOKENIZER_DECODE]: async (_runtime, { tokens, modelType = import_core.ModelType.TEXT_LARGE }) => {
|
|
350
|
+
return await detokenizeText(modelType ?? import_core.ModelType.TEXT_LARGE, tokens);
|
|
351
|
+
},
|
|
352
|
+
[import_core.ModelType.TEXT_SMALL]: async (runtime, {
|
|
353
|
+
prompt,
|
|
354
|
+
stopSequences = [],
|
|
355
|
+
maxTokens = 8192,
|
|
356
|
+
temperature = 0.7,
|
|
357
|
+
frequencyPenalty = 0.7,
|
|
358
|
+
presencePenalty = 0.7
|
|
359
|
+
}) => {
|
|
360
|
+
const openai = createOpenAIClient(runtime);
|
|
361
|
+
const modelName = getSmallModel(runtime);
|
|
362
|
+
const experimentalTelemetry = getExperimentalTelemetry(runtime);
|
|
363
|
+
import_core.logger.log(`[OpenAI] Using TEXT_SMALL model: ${modelName}`);
|
|
364
|
+
import_core.logger.log(prompt);
|
|
365
|
+
const { text: openaiResponse, usage } = await import_ai.generateText({
|
|
366
|
+
model: openai.languageModel(modelName),
|
|
367
|
+
prompt,
|
|
368
|
+
system: runtime.character.system ?? undefined,
|
|
369
|
+
temperature,
|
|
370
|
+
maxOutputTokens: maxTokens,
|
|
371
|
+
frequencyPenalty,
|
|
372
|
+
presencePenalty,
|
|
373
|
+
stopSequences,
|
|
374
|
+
experimental_telemetry: {
|
|
375
|
+
isEnabled: experimentalTelemetry
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
if (usage) {
|
|
379
|
+
emitModelUsageEvent(runtime, import_core.ModelType.TEXT_SMALL, prompt, usage);
|
|
380
|
+
}
|
|
381
|
+
return openaiResponse;
|
|
382
|
+
},
|
|
383
|
+
[import_core.ModelType.TEXT_LARGE]: async (runtime, {
|
|
384
|
+
prompt,
|
|
385
|
+
stopSequences = [],
|
|
386
|
+
maxTokens = 8192,
|
|
387
|
+
temperature = 0.7,
|
|
388
|
+
frequencyPenalty = 0.7,
|
|
389
|
+
presencePenalty = 0.7
|
|
390
|
+
}) => {
|
|
391
|
+
const openai = createOpenAIClient(runtime);
|
|
392
|
+
const modelName = getLargeModel(runtime);
|
|
393
|
+
const experimentalTelemetry = getExperimentalTelemetry(runtime);
|
|
394
|
+
import_core.logger.log(`[OpenAI] Using TEXT_LARGE model: ${modelName}`);
|
|
395
|
+
import_core.logger.log(prompt);
|
|
396
|
+
const { text: openaiResponse, usage } = await import_ai.generateText({
|
|
397
|
+
model: openai.languageModel(modelName),
|
|
398
|
+
prompt,
|
|
399
|
+
system: runtime.character.system ?? undefined,
|
|
400
|
+
temperature,
|
|
401
|
+
maxOutputTokens: maxTokens,
|
|
402
|
+
frequencyPenalty,
|
|
403
|
+
presencePenalty,
|
|
404
|
+
stopSequences,
|
|
405
|
+
experimental_telemetry: {
|
|
406
|
+
isEnabled: experimentalTelemetry
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
if (usage) {
|
|
410
|
+
emitModelUsageEvent(runtime, import_core.ModelType.TEXT_LARGE, prompt, usage);
|
|
411
|
+
}
|
|
412
|
+
return openaiResponse;
|
|
413
|
+
},
|
|
414
|
+
[import_core.ModelType.IMAGE]: async (runtime, params) => {
|
|
415
|
+
const n = params.n || 1;
|
|
416
|
+
const size = params.size || "1024x1024";
|
|
417
|
+
const prompt = params.prompt;
|
|
418
|
+
const modelName = "dall-e-3";
|
|
419
|
+
import_core.logger.log(`[OpenAI] Using IMAGE model: ${modelName}`);
|
|
420
|
+
const baseURL = getBaseURL(runtime);
|
|
421
|
+
try {
|
|
422
|
+
const response = await fetch(`${baseURL}/images/generations`, {
|
|
423
|
+
method: "POST",
|
|
424
|
+
headers: {
|
|
425
|
+
...getAuthHeader(runtime),
|
|
426
|
+
"Content-Type": "application/json"
|
|
427
|
+
},
|
|
428
|
+
body: JSON.stringify({
|
|
429
|
+
prompt,
|
|
430
|
+
n,
|
|
431
|
+
size
|
|
432
|
+
})
|
|
433
|
+
});
|
|
434
|
+
const responseClone = response.clone();
|
|
435
|
+
const rawResponseBody = await responseClone.text();
|
|
436
|
+
if (!response.ok) {
|
|
437
|
+
throw new Error(`Failed to generate image: ${response.statusText}`);
|
|
438
|
+
}
|
|
439
|
+
const data = await response.json();
|
|
440
|
+
const typedData = data;
|
|
441
|
+
return typedData.data;
|
|
442
|
+
} catch (error) {
|
|
443
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
[import_core.ModelType.IMAGE_DESCRIPTION]: async (runtime, params) => {
|
|
448
|
+
let imageUrl;
|
|
449
|
+
let promptText;
|
|
450
|
+
const modelName = getImageDescriptionModel(runtime);
|
|
451
|
+
import_core.logger.log(`[OpenAI] Using IMAGE_DESCRIPTION model: ${modelName}`);
|
|
452
|
+
const maxTokens = Number.parseInt(getSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS", "8192") || "8192", 10);
|
|
453
|
+
if (typeof params === "string") {
|
|
454
|
+
imageUrl = params;
|
|
455
|
+
promptText = "Please analyze this image and provide a title and detailed description.";
|
|
456
|
+
} else {
|
|
457
|
+
imageUrl = params.imageUrl;
|
|
458
|
+
promptText = params.prompt || "Please analyze this image and provide a title and detailed description.";
|
|
459
|
+
}
|
|
460
|
+
const messages = [
|
|
461
|
+
{
|
|
462
|
+
role: "user",
|
|
463
|
+
content: [
|
|
464
|
+
{ type: "text", text: promptText },
|
|
465
|
+
{ type: "image_url", image_url: { url: imageUrl } }
|
|
466
|
+
]
|
|
467
|
+
}
|
|
468
|
+
];
|
|
469
|
+
const baseURL = getBaseURL(runtime);
|
|
470
|
+
try {
|
|
471
|
+
const requestBody = {
|
|
472
|
+
model: modelName,
|
|
473
|
+
messages,
|
|
474
|
+
max_tokens: maxTokens
|
|
475
|
+
};
|
|
476
|
+
const response = await fetch(`${baseURL}/chat/completions`, {
|
|
477
|
+
method: "POST",
|
|
478
|
+
headers: {
|
|
479
|
+
"Content-Type": "application/json",
|
|
480
|
+
...getAuthHeader(runtime)
|
|
481
|
+
},
|
|
482
|
+
body: JSON.stringify(requestBody)
|
|
483
|
+
});
|
|
484
|
+
const responseClone = response.clone();
|
|
485
|
+
const rawResponseBody = await responseClone.text();
|
|
486
|
+
if (!response.ok) {
|
|
487
|
+
throw new Error(`OpenAI API error: ${response.status}`);
|
|
488
|
+
}
|
|
489
|
+
const result = await response.json();
|
|
490
|
+
const typedResult = result;
|
|
491
|
+
const content = typedResult.choices?.[0]?.message?.content;
|
|
492
|
+
if (typedResult.usage) {
|
|
493
|
+
emitModelUsageEvent(runtime, import_core.ModelType.IMAGE_DESCRIPTION, typeof params === "string" ? params : params.prompt || "", {
|
|
494
|
+
inputTokens: typedResult.usage.prompt_tokens,
|
|
495
|
+
outputTokens: typedResult.usage.completion_tokens,
|
|
496
|
+
totalTokens: typedResult.usage.total_tokens
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
if (!content) {
|
|
500
|
+
return {
|
|
501
|
+
title: "Failed to analyze image",
|
|
502
|
+
description: "No response from API"
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
const isCustomPrompt = typeof params === "object" && params.prompt && params.prompt !== "Please analyze this image and provide a title and detailed description.";
|
|
506
|
+
if (isCustomPrompt) {
|
|
507
|
+
return content;
|
|
508
|
+
}
|
|
509
|
+
const titleMatch = content.match(/title[:\s]+(.+?)(?:\n|$)/i);
|
|
510
|
+
const title = titleMatch?.[1]?.trim() || "Image Analysis";
|
|
511
|
+
const description = content.replace(/title[:\s]+(.+?)(?:\n|$)/i, "").trim();
|
|
512
|
+
const processedResult = { title, description };
|
|
513
|
+
return processedResult;
|
|
514
|
+
} catch (error) {
|
|
515
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
516
|
+
import_core.logger.error(`Error analyzing image: ${message}`);
|
|
517
|
+
return {
|
|
518
|
+
title: "Failed to analyze image",
|
|
519
|
+
description: `Error: ${message}`
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
[import_core.ModelType.TRANSCRIPTION]: async (runtime, audioBuffer) => {
|
|
524
|
+
import_core.logger.debug({ size: audioBuffer?.length ?? 0 }, "audioBuffer received");
|
|
525
|
+
const modelName = "whisper-1";
|
|
526
|
+
import_core.logger.log(`[OpenAI] Using TRANSCRIPTION model: ${modelName}`);
|
|
527
|
+
const baseURL = getBaseURL(runtime);
|
|
528
|
+
if (!audioBuffer || audioBuffer.length === 0) {
|
|
529
|
+
throw new Error("Audio buffer is empty or invalid for transcription");
|
|
530
|
+
}
|
|
531
|
+
const formData = new FormData;
|
|
532
|
+
const arrayBuffer = audioBuffer.buffer;
|
|
533
|
+
const start = audioBuffer.byteOffset || 0;
|
|
534
|
+
const end = start + (audioBuffer.byteLength || 0);
|
|
535
|
+
const safeArrayBuffer = arrayBuffer.slice(start, end);
|
|
536
|
+
formData.append("file", new Blob([safeArrayBuffer], { type: "audio/mpeg" }), "recording.mp3");
|
|
537
|
+
formData.append("model", "whisper-1");
|
|
538
|
+
try {
|
|
539
|
+
const response = await fetch(`${baseURL}/audio/transcriptions`, {
|
|
540
|
+
method: "POST",
|
|
541
|
+
headers: {
|
|
542
|
+
...getAuthHeader(runtime)
|
|
543
|
+
},
|
|
544
|
+
body: formData
|
|
545
|
+
});
|
|
546
|
+
const responseClone = response.clone();
|
|
547
|
+
const rawResponseBody = await responseClone.text();
|
|
548
|
+
import_core.logger.log({ response }, "response");
|
|
549
|
+
if (!response.ok) {
|
|
550
|
+
throw new Error(`Failed to transcribe audio: ${response.statusText}`);
|
|
551
|
+
}
|
|
552
|
+
const data = await response.json();
|
|
553
|
+
const processedText = data.text;
|
|
554
|
+
return processedText;
|
|
555
|
+
} catch (error) {
|
|
556
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
557
|
+
throw error;
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
[import_core.ModelType.TEXT_TO_SPEECH]: async (runtime, text) => {
|
|
561
|
+
const ttsModelName = getSetting(runtime, "OPENAI_TTS_MODEL", "gpt-4o-mini-tts");
|
|
562
|
+
import_core.logger.log(`[OpenAI] Using TEXT_TO_SPEECH model: ${ttsModelName}`);
|
|
563
|
+
try {
|
|
564
|
+
const speechStream = await fetchTextToSpeech(runtime, text);
|
|
565
|
+
return speechStream;
|
|
566
|
+
} catch (error) {
|
|
567
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
568
|
+
throw error;
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
[import_core.ModelType.OBJECT_SMALL]: async (runtime, params) => {
|
|
572
|
+
return generateObjectByModelType(runtime, params, import_core.ModelType.OBJECT_SMALL, getSmallModel);
|
|
573
|
+
},
|
|
574
|
+
[import_core.ModelType.OBJECT_LARGE]: async (runtime, params) => {
|
|
575
|
+
return generateObjectByModelType(runtime, params, import_core.ModelType.OBJECT_LARGE, getLargeModel);
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
tests: [
|
|
579
|
+
{
|
|
580
|
+
name: "openai_plugin_tests",
|
|
581
|
+
tests: [
|
|
582
|
+
{
|
|
583
|
+
name: "openai_test_url_and_api_key_validation",
|
|
584
|
+
fn: async (runtime) => {
|
|
585
|
+
const baseURL = getBaseURL(runtime);
|
|
586
|
+
const response = await fetch(`${baseURL}/models`, {
|
|
587
|
+
headers: {
|
|
588
|
+
Authorization: `Bearer ${getApiKey(runtime)}`
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
const data = await response.json();
|
|
592
|
+
import_core.logger.log({ data: data?.data?.length ?? "N/A" }, "Models Available");
|
|
593
|
+
if (!response.ok) {
|
|
594
|
+
throw new Error(`Failed to validate OpenAI API key: ${response.statusText}`);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
},
|
|
598
|
+
{
|
|
599
|
+
name: "openai_test_text_embedding",
|
|
600
|
+
fn: async (runtime) => {
|
|
601
|
+
try {
|
|
602
|
+
const embedding = await runtime.useModel(import_core.ModelType.TEXT_EMBEDDING, {
|
|
603
|
+
text: "Hello, world!"
|
|
604
|
+
});
|
|
605
|
+
import_core.logger.log({ embedding }, "embedding");
|
|
606
|
+
} catch (error) {
|
|
607
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
608
|
+
import_core.logger.error(`Error in test_text_embedding: ${message}`);
|
|
609
|
+
throw error;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
},
|
|
613
|
+
{
|
|
614
|
+
name: "openai_test_text_large",
|
|
615
|
+
fn: async (runtime) => {
|
|
616
|
+
try {
|
|
617
|
+
const text = await runtime.useModel(import_core.ModelType.TEXT_LARGE, {
|
|
618
|
+
prompt: "What is the nature of reality in 10 words?"
|
|
619
|
+
});
|
|
620
|
+
if (text.length === 0) {
|
|
621
|
+
throw new Error("Failed to generate text");
|
|
622
|
+
}
|
|
623
|
+
import_core.logger.log({ text }, "generated with test_text_large");
|
|
624
|
+
} catch (error) {
|
|
625
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
626
|
+
import_core.logger.error(`Error in test_text_large: ${message}`);
|
|
627
|
+
throw error;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
},
|
|
631
|
+
{
|
|
632
|
+
name: "openai_test_text_small",
|
|
633
|
+
fn: async (runtime) => {
|
|
634
|
+
try {
|
|
635
|
+
const text = await runtime.useModel(import_core.ModelType.TEXT_SMALL, {
|
|
636
|
+
prompt: "What is the nature of reality in 10 words?"
|
|
637
|
+
});
|
|
638
|
+
if (text.length === 0) {
|
|
639
|
+
throw new Error("Failed to generate text");
|
|
640
|
+
}
|
|
641
|
+
import_core.logger.log({ text }, "generated with test_text_small");
|
|
642
|
+
} catch (error) {
|
|
643
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
644
|
+
import_core.logger.error(`Error in test_text_small: ${message}`);
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
},
|
|
649
|
+
{
|
|
650
|
+
name: "openai_test_image_generation",
|
|
651
|
+
fn: async (runtime) => {
|
|
652
|
+
import_core.logger.log("openai_test_image_generation");
|
|
653
|
+
try {
|
|
654
|
+
const image = await runtime.useModel(import_core.ModelType.IMAGE, {
|
|
655
|
+
prompt: "A beautiful sunset over a calm ocean",
|
|
656
|
+
n: 1,
|
|
657
|
+
size: "1024x1024"
|
|
658
|
+
});
|
|
659
|
+
import_core.logger.log({ image }, "generated with test_image_generation");
|
|
660
|
+
} catch (error) {
|
|
661
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
662
|
+
import_core.logger.error(`Error in test_image_generation: ${message}`);
|
|
663
|
+
throw error;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
{
|
|
668
|
+
name: "image-description",
|
|
669
|
+
fn: async (runtime) => {
|
|
670
|
+
try {
|
|
671
|
+
import_core.logger.log("openai_test_image_description");
|
|
672
|
+
try {
|
|
673
|
+
const result = await runtime.useModel(import_core.ModelType.IMAGE_DESCRIPTION, "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg/537px-Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg");
|
|
674
|
+
if (result && typeof result === "object" && "title" in result && "description" in result) {
|
|
675
|
+
import_core.logger.log({ result }, "Image description");
|
|
676
|
+
} else {
|
|
677
|
+
import_core.logger.error("Invalid image description result format:", result);
|
|
678
|
+
}
|
|
679
|
+
} catch (e) {
|
|
680
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
681
|
+
import_core.logger.error(`Error in image description test: ${message}`);
|
|
682
|
+
}
|
|
683
|
+
} catch (e) {
|
|
684
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
685
|
+
import_core.logger.error(`Error in openai_test_image_description: ${message}`);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
{
|
|
690
|
+
name: "openai_test_transcription",
|
|
691
|
+
fn: async (runtime) => {
|
|
692
|
+
import_core.logger.log("openai_test_transcription");
|
|
693
|
+
try {
|
|
694
|
+
const response = await fetch("https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg");
|
|
695
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
696
|
+
const transcription = await runtime.useModel(import_core.ModelType.TRANSCRIPTION, Buffer.from(new Uint8Array(arrayBuffer)));
|
|
697
|
+
import_core.logger.log({ transcription }, "generated with test_transcription");
|
|
698
|
+
} catch (error) {
|
|
699
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
700
|
+
import_core.logger.error(`Error in test_transcription: ${message}`);
|
|
701
|
+
throw error;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
},
|
|
705
|
+
{
|
|
706
|
+
name: "openai_test_text_tokenizer_encode",
|
|
707
|
+
fn: async (runtime) => {
|
|
708
|
+
const prompt = "Hello tokenizer encode!";
|
|
709
|
+
const tokens = await runtime.useModel(import_core.ModelType.TEXT_TOKENIZER_ENCODE, { prompt });
|
|
710
|
+
if (!Array.isArray(tokens) || tokens.length === 0) {
|
|
711
|
+
throw new Error("Failed to tokenize text: expected non-empty array of tokens");
|
|
712
|
+
}
|
|
713
|
+
import_core.logger.log({ tokens }, "Tokenized output");
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
name: "openai_test_text_tokenizer_decode",
|
|
718
|
+
fn: async (runtime) => {
|
|
719
|
+
const prompt = "Hello tokenizer decode!";
|
|
720
|
+
const tokens = await runtime.useModel(import_core.ModelType.TEXT_TOKENIZER_ENCODE, { prompt });
|
|
721
|
+
const decodedText = await runtime.useModel(import_core.ModelType.TEXT_TOKENIZER_DECODE, { tokens });
|
|
722
|
+
if (decodedText !== prompt) {
|
|
723
|
+
throw new Error(`Decoded text does not match original. Expected "${prompt}", got "${decodedText}"`);
|
|
724
|
+
}
|
|
725
|
+
import_core.logger.log({ decodedText }, "Decoded text");
|
|
726
|
+
}
|
|
727
|
+
},
|
|
728
|
+
{
|
|
729
|
+
name: "openai_test_text_to_speech",
|
|
730
|
+
fn: async (runtime) => {
|
|
731
|
+
try {
|
|
732
|
+
const text = "Hello, this is a test for text-to-speech.";
|
|
733
|
+
const response = await fetchTextToSpeech(runtime, text);
|
|
734
|
+
if (!response) {
|
|
735
|
+
throw new Error("Failed to generate speech");
|
|
736
|
+
}
|
|
737
|
+
import_core.logger.log("Generated speech successfully");
|
|
738
|
+
} catch (error) {
|
|
739
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
740
|
+
import_core.logger.error(`Error in openai_test_text_to_speech: ${message}`);
|
|
741
|
+
throw error;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
]
|
|
746
|
+
}
|
|
747
|
+
]
|
|
748
|
+
};
|
|
749
|
+
var src_default = openaiPlugin;
|
|
750
|
+
|
|
751
|
+
//# debugId=3AA0E1EB713F16F564756E2164756E21
|