@elizaos/plugin-openai 2.0.0-alpha.9 → 2.0.3-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +221 -0
- package/auto-enable.ts +17 -0
- package/package.json +70 -17
- package/dist/browser/index.browser.js +0 -3
- package/dist/browser/index.browser.js.map +0 -24
- package/dist/browser/index.d.ts +0 -2
- package/dist/build.d.ts +0 -13
- package/dist/build.d.ts.map +0 -1
- package/dist/cjs/index.d.ts +0 -2
- package/dist/cjs/index.node.cjs +0 -1315
- package/dist/cjs/index.node.js.map +0 -24
- package/dist/generated/specs/specs.d.ts +0 -55
- package/dist/generated/specs/specs.d.ts.map +0 -1
- package/dist/index.browser.d.ts +0 -3
- package/dist/index.browser.d.ts.map +0 -1
- package/dist/index.d.ts +0 -4
- package/dist/index.d.ts.map +0 -1
- package/dist/index.node.d.ts +0 -3
- package/dist/index.node.d.ts.map +0 -1
- package/dist/init.d.ts +0 -4
- package/dist/init.d.ts.map +0 -1
- package/dist/models/audio.d.ts +0 -9
- package/dist/models/audio.d.ts.map +0 -1
- package/dist/models/embedding.d.ts +0 -3
- package/dist/models/embedding.d.ts.map +0 -1
- package/dist/models/image.d.ts +0 -5
- package/dist/models/image.d.ts.map +0 -1
- package/dist/models/index.d.ts +0 -8
- package/dist/models/index.d.ts.map +0 -1
- package/dist/models/object.d.ts +0 -4
- package/dist/models/object.d.ts.map +0 -1
- package/dist/models/research.d.ts +0 -34
- package/dist/models/research.d.ts.map +0 -1
- package/dist/models/text.d.ts +0 -28
- package/dist/models/text.d.ts.map +0 -1
- package/dist/models/tokenizer.d.ts +0 -4
- package/dist/models/tokenizer.d.ts.map +0 -1
- package/dist/node/index.d.ts +0 -2
- package/dist/node/index.node.js +0 -1286
- package/dist/node/index.node.js.map +0 -24
- package/dist/providers/index.d.ts +0 -2
- package/dist/providers/index.d.ts.map +0 -1
- package/dist/providers/openai.d.ts +0 -4
- package/dist/providers/openai.d.ts.map +0 -1
- package/dist/types/index.d.ts +0 -345
- package/dist/types/index.d.ts.map +0 -1
- package/dist/utils/audio.d.ts +0 -6
- package/dist/utils/audio.d.ts.map +0 -1
- package/dist/utils/config.d.ts +0 -27
- package/dist/utils/config.d.ts.map +0 -1
- package/dist/utils/events.d.ts +0 -21
- package/dist/utils/events.d.ts.map +0 -1
- package/dist/utils/index.d.ts +0 -6
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/json.d.ts +0 -10
- package/dist/utils/json.d.ts.map +0 -1
- package/dist/utils/tokenization.d.ts +0 -6
- package/dist/utils/tokenization.d.ts.map +0 -1
package/dist/node/index.node.js
DELETED
|
@@ -1,1286 +0,0 @@
|
|
|
1
|
-
// index.ts
|
|
2
|
-
import { logger as logger11, ModelType as ModelType7 } from "@elizaos/core";
|
|
3
|
-
|
|
4
|
-
// init.ts
|
|
5
|
-
import { logger as logger2 } from "@elizaos/core";
|
|
6
|
-
|
|
7
|
-
// utils/config.ts
|
|
8
|
-
import { logger } from "@elizaos/core";
|
|
9
|
-
function getEnvValue(key) {
|
|
10
|
-
if (typeof process === "undefined" || !process.env) {
|
|
11
|
-
return;
|
|
12
|
-
}
|
|
13
|
-
const value = process.env[key];
|
|
14
|
-
return value === undefined ? undefined : String(value);
|
|
15
|
-
}
|
|
16
|
-
function getSetting(runtime, key, defaultValue) {
|
|
17
|
-
const value = runtime.getSetting(key);
|
|
18
|
-
if (value !== undefined && value !== null) {
|
|
19
|
-
return String(value);
|
|
20
|
-
}
|
|
21
|
-
return getEnvValue(key) ?? defaultValue;
|
|
22
|
-
}
|
|
23
|
-
function getNumericSetting(runtime, key, defaultValue) {
|
|
24
|
-
const value = getSetting(runtime, key);
|
|
25
|
-
if (value === undefined) {
|
|
26
|
-
return defaultValue;
|
|
27
|
-
}
|
|
28
|
-
const parsed = Number.parseInt(value, 10);
|
|
29
|
-
if (!Number.isFinite(parsed)) {
|
|
30
|
-
throw new Error(`Setting '${key}' must be a valid integer, got: ${value}`);
|
|
31
|
-
}
|
|
32
|
-
return parsed;
|
|
33
|
-
}
|
|
34
|
-
function getBooleanSetting(runtime, key, defaultValue) {
|
|
35
|
-
const value = getSetting(runtime, key);
|
|
36
|
-
if (value === undefined) {
|
|
37
|
-
return defaultValue;
|
|
38
|
-
}
|
|
39
|
-
const normalized = value.toLowerCase();
|
|
40
|
-
return normalized === "true" || normalized === "1" || normalized === "yes";
|
|
41
|
-
}
|
|
42
|
-
function isBrowser() {
|
|
43
|
-
return typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
|
|
44
|
-
}
|
|
45
|
-
function isProxyMode(runtime) {
|
|
46
|
-
return isBrowser() && !!getSetting(runtime, "OPENAI_BROWSER_BASE_URL");
|
|
47
|
-
}
|
|
48
|
-
function getApiKey(runtime) {
|
|
49
|
-
return getSetting(runtime, "OPENAI_API_KEY");
|
|
50
|
-
}
|
|
51
|
-
function getEmbeddingApiKey(runtime) {
|
|
52
|
-
const embeddingApiKey = getSetting(runtime, "OPENAI_EMBEDDING_API_KEY");
|
|
53
|
-
if (embeddingApiKey) {
|
|
54
|
-
logger.debug("[OpenAI] Using specific embedding API key");
|
|
55
|
-
return embeddingApiKey;
|
|
56
|
-
}
|
|
57
|
-
logger.debug("[OpenAI] Falling back to general API key for embeddings");
|
|
58
|
-
return getApiKey(runtime);
|
|
59
|
-
}
|
|
60
|
-
function getAuthHeader(runtime, forEmbedding = false) {
|
|
61
|
-
if (isBrowser() && !getBooleanSetting(runtime, "OPENAI_ALLOW_BROWSER_API_KEY", false)) {
|
|
62
|
-
return {};
|
|
63
|
-
}
|
|
64
|
-
const key = forEmbedding ? getEmbeddingApiKey(runtime) : getApiKey(runtime);
|
|
65
|
-
return key ? { Authorization: `Bearer ${key}` } : {};
|
|
66
|
-
}
|
|
67
|
-
function getBaseURL(runtime) {
|
|
68
|
-
const browserURL = getSetting(runtime, "OPENAI_BROWSER_BASE_URL");
|
|
69
|
-
const baseURL = isBrowser() && browserURL ? browserURL : getSetting(runtime, "OPENAI_BASE_URL") ?? "https://api.openai.com/v1";
|
|
70
|
-
logger.debug(`[OpenAI] Base URL: ${baseURL}`);
|
|
71
|
-
return baseURL;
|
|
72
|
-
}
|
|
73
|
-
function getEmbeddingBaseURL(runtime) {
|
|
74
|
-
const embeddingURL = isBrowser() ? getSetting(runtime, "OPENAI_BROWSER_EMBEDDING_URL") ?? getSetting(runtime, "OPENAI_BROWSER_BASE_URL") : getSetting(runtime, "OPENAI_EMBEDDING_URL");
|
|
75
|
-
if (embeddingURL) {
|
|
76
|
-
logger.debug(`[OpenAI] Using embedding base URL: ${embeddingURL}`);
|
|
77
|
-
return embeddingURL;
|
|
78
|
-
}
|
|
79
|
-
logger.debug("[OpenAI] Falling back to general base URL for embeddings");
|
|
80
|
-
return getBaseURL(runtime);
|
|
81
|
-
}
|
|
82
|
-
function getSmallModel(runtime) {
|
|
83
|
-
return getSetting(runtime, "OPENAI_SMALL_MODEL") ?? getSetting(runtime, "SMALL_MODEL") ?? "gpt-5-mini";
|
|
84
|
-
}
|
|
85
|
-
function getLargeModel(runtime) {
|
|
86
|
-
return getSetting(runtime, "OPENAI_LARGE_MODEL") ?? getSetting(runtime, "LARGE_MODEL") ?? "gpt-5";
|
|
87
|
-
}
|
|
88
|
-
function getEmbeddingModel(runtime) {
|
|
89
|
-
return getSetting(runtime, "OPENAI_EMBEDDING_MODEL") ?? "text-embedding-3-small";
|
|
90
|
-
}
|
|
91
|
-
function getImageDescriptionModel(runtime) {
|
|
92
|
-
return getSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MODEL") ?? "gpt-5-mini";
|
|
93
|
-
}
|
|
94
|
-
function getTranscriptionModel(runtime) {
|
|
95
|
-
return getSetting(runtime, "OPENAI_TRANSCRIPTION_MODEL") ?? "gpt-5-mini-transcribe";
|
|
96
|
-
}
|
|
97
|
-
function getTTSModel(runtime) {
|
|
98
|
-
return getSetting(runtime, "OPENAI_TTS_MODEL") ?? "tts-1";
|
|
99
|
-
}
|
|
100
|
-
function getTTSVoice(runtime) {
|
|
101
|
-
return getSetting(runtime, "OPENAI_TTS_VOICE") ?? "nova";
|
|
102
|
-
}
|
|
103
|
-
function getTTSInstructions(runtime) {
|
|
104
|
-
return getSetting(runtime, "OPENAI_TTS_INSTRUCTIONS") ?? "";
|
|
105
|
-
}
|
|
106
|
-
function getImageModel(runtime) {
|
|
107
|
-
return getSetting(runtime, "OPENAI_IMAGE_MODEL") ?? "dall-e-3";
|
|
108
|
-
}
|
|
109
|
-
function getExperimentalTelemetry(runtime) {
|
|
110
|
-
return getBooleanSetting(runtime, "OPENAI_EXPERIMENTAL_TELEMETRY", false);
|
|
111
|
-
}
|
|
112
|
-
function getEmbeddingDimensions(runtime) {
|
|
113
|
-
return getNumericSetting(runtime, "OPENAI_EMBEDDING_DIMENSIONS", 1536);
|
|
114
|
-
}
|
|
115
|
-
function getImageDescriptionMaxTokens(runtime) {
|
|
116
|
-
return getNumericSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS", 8192);
|
|
117
|
-
}
|
|
118
|
-
function getResearchModel(runtime) {
|
|
119
|
-
return getSetting(runtime, "OPENAI_RESEARCH_MODEL") ?? "o3-deep-research";
|
|
120
|
-
}
|
|
121
|
-
function getResearchTimeout(runtime) {
|
|
122
|
-
return getNumericSetting(runtime, "OPENAI_RESEARCH_TIMEOUT", 3600000);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// init.ts
|
|
126
|
-
globalThis.AI_SDK_LOG_WARNINGS ??= false;
|
|
127
|
-
function initializeOpenAI(_config, runtime) {
|
|
128
|
-
validateOpenAIConfiguration(runtime);
|
|
129
|
-
}
|
|
130
|
-
async function validateOpenAIConfiguration(runtime) {
|
|
131
|
-
if (isBrowser()) {
|
|
132
|
-
logger2.debug("[OpenAI] Skipping API validation in browser environment");
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
const apiKey = getApiKey(runtime);
|
|
136
|
-
if (!apiKey) {
|
|
137
|
-
logger2.warn("[OpenAI] OPENAI_API_KEY is not configured. " + "OpenAI functionality will fail until a valid API key is provided.");
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
try {
|
|
141
|
-
const baseURL = getBaseURL(runtime);
|
|
142
|
-
const response = await fetch(`${baseURL}/models`, {
|
|
143
|
-
headers: getAuthHeader(runtime)
|
|
144
|
-
});
|
|
145
|
-
if (!response.ok) {
|
|
146
|
-
logger2.warn(`[OpenAI] API key validation failed: ${response.status} ${response.statusText}. ` + "Please verify your OPENAI_API_KEY is correct.");
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
} catch (error) {
|
|
150
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
151
|
-
logger2.warn(`[OpenAI] API validation error: ${message}. OpenAI functionality may be limited.`);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// models/audio.ts
|
|
156
|
-
import { logger as logger4 } from "@elizaos/core";
|
|
157
|
-
|
|
158
|
-
// utils/audio.ts
|
|
159
|
-
import { logger as logger3 } from "@elizaos/core";
|
|
160
|
-
var MAGIC_BYTES = {
|
|
161
|
-
WAV: {
|
|
162
|
-
HEADER: [82, 73, 70, 70],
|
|
163
|
-
IDENTIFIER: [87, 65, 86, 69]
|
|
164
|
-
},
|
|
165
|
-
MP3_ID3: [73, 68, 51],
|
|
166
|
-
OGG: [79, 103, 103, 83],
|
|
167
|
-
FLAC: [102, 76, 97, 67],
|
|
168
|
-
FTYP: [102, 116, 121, 112],
|
|
169
|
-
WEBM_EBML: [26, 69, 223, 163]
|
|
170
|
-
};
|
|
171
|
-
var MIN_DETECTION_BUFFER_SIZE = 12;
|
|
172
|
-
function matchBytes(buffer, offset, expected) {
|
|
173
|
-
for (let i = 0;i < expected.length; i++) {
|
|
174
|
-
const expectedByte = expected[i];
|
|
175
|
-
if (expectedByte === undefined || buffer[offset + i] !== expectedByte) {
|
|
176
|
-
return false;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
return true;
|
|
180
|
-
}
|
|
181
|
-
function detectAudioMimeType(buffer) {
|
|
182
|
-
if (buffer.length < MIN_DETECTION_BUFFER_SIZE) {
|
|
183
|
-
return "application/octet-stream";
|
|
184
|
-
}
|
|
185
|
-
if (matchBytes(buffer, 0, MAGIC_BYTES.WAV.HEADER) && matchBytes(buffer, 8, MAGIC_BYTES.WAV.IDENTIFIER)) {
|
|
186
|
-
return "audio/wav";
|
|
187
|
-
}
|
|
188
|
-
const firstByte = buffer[0];
|
|
189
|
-
const secondByte = buffer[1];
|
|
190
|
-
if (matchBytes(buffer, 0, MAGIC_BYTES.MP3_ID3) || firstByte === 255 && secondByte !== undefined && (secondByte & 224) === 224) {
|
|
191
|
-
return "audio/mpeg";
|
|
192
|
-
}
|
|
193
|
-
if (matchBytes(buffer, 0, MAGIC_BYTES.OGG)) {
|
|
194
|
-
return "audio/ogg";
|
|
195
|
-
}
|
|
196
|
-
if (matchBytes(buffer, 0, MAGIC_BYTES.FLAC)) {
|
|
197
|
-
return "audio/flac";
|
|
198
|
-
}
|
|
199
|
-
if (matchBytes(buffer, 4, MAGIC_BYTES.FTYP)) {
|
|
200
|
-
return "audio/mp4";
|
|
201
|
-
}
|
|
202
|
-
if (matchBytes(buffer, 0, MAGIC_BYTES.WEBM_EBML)) {
|
|
203
|
-
return "audio/webm";
|
|
204
|
-
}
|
|
205
|
-
logger3.warn("Could not detect audio format from buffer, using generic binary type");
|
|
206
|
-
return "application/octet-stream";
|
|
207
|
-
}
|
|
208
|
-
function getExtensionForMimeType(mimeType) {
|
|
209
|
-
switch (mimeType) {
|
|
210
|
-
case "audio/wav":
|
|
211
|
-
return "wav";
|
|
212
|
-
case "audio/mpeg":
|
|
213
|
-
return "mp3";
|
|
214
|
-
case "audio/ogg":
|
|
215
|
-
return "ogg";
|
|
216
|
-
case "audio/flac":
|
|
217
|
-
return "flac";
|
|
218
|
-
case "audio/mp4":
|
|
219
|
-
return "m4a";
|
|
220
|
-
case "audio/webm":
|
|
221
|
-
return "webm";
|
|
222
|
-
case "application/octet-stream":
|
|
223
|
-
return "bin";
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
function getFilenameForMimeType(mimeType) {
|
|
227
|
-
const ext = getExtensionForMimeType(mimeType);
|
|
228
|
-
return `recording.${ext}`;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// models/audio.ts
|
|
232
|
-
function isBlobOrFile(value) {
|
|
233
|
-
return value instanceof Blob || value instanceof File;
|
|
234
|
-
}
|
|
235
|
-
function isBuffer(value) {
|
|
236
|
-
return Buffer.isBuffer(value);
|
|
237
|
-
}
|
|
238
|
-
function isLocalTranscriptionParams(value) {
|
|
239
|
-
return typeof value === "object" && value !== null && "audio" in value && (isBlobOrFile(value.audio) || isBuffer(value.audio));
|
|
240
|
-
}
|
|
241
|
-
function isCoreTranscriptionParams(value) {
|
|
242
|
-
return typeof value === "object" && value !== null && "audioUrl" in value && typeof value.audioUrl === "string";
|
|
243
|
-
}
|
|
244
|
-
async function fetchAudioFromUrl(url) {
|
|
245
|
-
const response = await fetch(url);
|
|
246
|
-
if (!response.ok) {
|
|
247
|
-
throw new Error(`Failed to fetch audio from URL: ${response.status}`);
|
|
248
|
-
}
|
|
249
|
-
return response.blob();
|
|
250
|
-
}
|
|
251
|
-
async function handleTranscription(runtime, input) {
|
|
252
|
-
let modelName = getTranscriptionModel(runtime);
|
|
253
|
-
let blob;
|
|
254
|
-
let extraParams = {};
|
|
255
|
-
if (typeof input === "string") {
|
|
256
|
-
logger4.debug(`[OpenAI] Fetching audio from URL: ${input}`);
|
|
257
|
-
blob = await fetchAudioFromUrl(input);
|
|
258
|
-
} else if (isBlobOrFile(input)) {
|
|
259
|
-
blob = input;
|
|
260
|
-
} else if (isBuffer(input)) {
|
|
261
|
-
const mimeType2 = detectAudioMimeType(input);
|
|
262
|
-
logger4.debug(`[OpenAI] Auto-detected audio MIME type: ${mimeType2}`);
|
|
263
|
-
blob = new Blob([new Uint8Array(input)], { type: mimeType2 });
|
|
264
|
-
} else if (isLocalTranscriptionParams(input)) {
|
|
265
|
-
extraParams = input;
|
|
266
|
-
if (input.model) {
|
|
267
|
-
modelName = input.model;
|
|
268
|
-
}
|
|
269
|
-
if (isBuffer(input.audio)) {
|
|
270
|
-
const mimeType2 = input.mimeType ?? detectAudioMimeType(input.audio);
|
|
271
|
-
logger4.debug(`[OpenAI] Using MIME type: ${mimeType2}`);
|
|
272
|
-
blob = new Blob([new Uint8Array(input.audio)], { type: mimeType2 });
|
|
273
|
-
} else {
|
|
274
|
-
blob = input.audio;
|
|
275
|
-
}
|
|
276
|
-
} else if (isCoreTranscriptionParams(input)) {
|
|
277
|
-
logger4.debug(`[OpenAI] Fetching audio from URL: ${input.audioUrl}`);
|
|
278
|
-
blob = await fetchAudioFromUrl(input.audioUrl);
|
|
279
|
-
extraParams = { prompt: input.prompt };
|
|
280
|
-
} else {
|
|
281
|
-
throw new Error("TRANSCRIPTION expects Blob, File, Buffer, URL string, or TranscriptionParams object");
|
|
282
|
-
}
|
|
283
|
-
logger4.debug(`[OpenAI] Using TRANSCRIPTION model: ${modelName}`);
|
|
284
|
-
const mimeType = blob.type || "audio/webm";
|
|
285
|
-
const filename = blob.name || getFilenameForMimeType(mimeType.startsWith("audio/") ? mimeType : "audio/webm");
|
|
286
|
-
const formData = new FormData;
|
|
287
|
-
formData.append("file", blob, filename);
|
|
288
|
-
formData.append("model", modelName);
|
|
289
|
-
if (extraParams.language) {
|
|
290
|
-
formData.append("language", extraParams.language);
|
|
291
|
-
}
|
|
292
|
-
if (extraParams.responseFormat) {
|
|
293
|
-
formData.append("response_format", extraParams.responseFormat);
|
|
294
|
-
}
|
|
295
|
-
if (extraParams.prompt) {
|
|
296
|
-
formData.append("prompt", extraParams.prompt);
|
|
297
|
-
}
|
|
298
|
-
if (extraParams.temperature !== undefined) {
|
|
299
|
-
formData.append("temperature", String(extraParams.temperature));
|
|
300
|
-
}
|
|
301
|
-
if (extraParams.timestampGranularities) {
|
|
302
|
-
for (const granularity of extraParams.timestampGranularities) {
|
|
303
|
-
formData.append("timestamp_granularities[]", granularity);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
const baseURL = getBaseURL(runtime);
|
|
307
|
-
const response = await fetch(`${baseURL}/audio/transcriptions`, {
|
|
308
|
-
method: "POST",
|
|
309
|
-
headers: getAuthHeader(runtime),
|
|
310
|
-
body: formData
|
|
311
|
-
});
|
|
312
|
-
if (!response.ok) {
|
|
313
|
-
const errorText = await response.text().catch(() => "Unknown error");
|
|
314
|
-
throw new Error(`OpenAI transcription failed: ${response.status} ${response.statusText} - ${errorText}`);
|
|
315
|
-
}
|
|
316
|
-
const data = await response.json();
|
|
317
|
-
return data.text;
|
|
318
|
-
}
|
|
319
|
-
async function handleTextToSpeech(runtime, input) {
|
|
320
|
-
let text;
|
|
321
|
-
let voice;
|
|
322
|
-
let format = "mp3";
|
|
323
|
-
let model;
|
|
324
|
-
let instructions;
|
|
325
|
-
if (typeof input === "string") {
|
|
326
|
-
text = input;
|
|
327
|
-
voice = undefined;
|
|
328
|
-
} else {
|
|
329
|
-
text = input.text;
|
|
330
|
-
voice = input.voice;
|
|
331
|
-
if ("format" in input && input.format) {
|
|
332
|
-
format = input.format;
|
|
333
|
-
}
|
|
334
|
-
if ("model" in input && input.model) {
|
|
335
|
-
model = input.model;
|
|
336
|
-
}
|
|
337
|
-
if ("instructions" in input && input.instructions) {
|
|
338
|
-
instructions = input.instructions;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
model = model ?? getTTSModel(runtime);
|
|
342
|
-
voice = voice ?? getTTSVoice(runtime);
|
|
343
|
-
instructions = instructions ?? getTTSInstructions(runtime);
|
|
344
|
-
logger4.debug(`[OpenAI] Using TEXT_TO_SPEECH model: ${model}`);
|
|
345
|
-
if (!text || text.trim().length === 0) {
|
|
346
|
-
throw new Error("TEXT_TO_SPEECH requires non-empty text");
|
|
347
|
-
}
|
|
348
|
-
if (text.length > 4096) {
|
|
349
|
-
throw new Error("TEXT_TO_SPEECH text exceeds 4096 character limit");
|
|
350
|
-
}
|
|
351
|
-
const validVoices = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];
|
|
352
|
-
if (voice && !validVoices.includes(voice)) {
|
|
353
|
-
throw new Error(`Invalid voice: ${voice}. Must be one of: ${validVoices.join(", ")}`);
|
|
354
|
-
}
|
|
355
|
-
const baseURL = getBaseURL(runtime);
|
|
356
|
-
const requestBody = {
|
|
357
|
-
model,
|
|
358
|
-
voice,
|
|
359
|
-
input: text,
|
|
360
|
-
response_format: format
|
|
361
|
-
};
|
|
362
|
-
if (instructions && instructions.length > 0) {
|
|
363
|
-
requestBody.instructions = instructions;
|
|
364
|
-
}
|
|
365
|
-
const response = await fetch(`${baseURL}/audio/speech`, {
|
|
366
|
-
method: "POST",
|
|
367
|
-
headers: {
|
|
368
|
-
...getAuthHeader(runtime),
|
|
369
|
-
"Content-Type": "application/json",
|
|
370
|
-
...format === "mp3" ? { Accept: "audio/mpeg" } : {}
|
|
371
|
-
},
|
|
372
|
-
body: JSON.stringify(requestBody)
|
|
373
|
-
});
|
|
374
|
-
if (!response.ok) {
|
|
375
|
-
const errorText = await response.text().catch(() => "Unknown error");
|
|
376
|
-
throw new Error(`OpenAI TTS failed: ${response.status} ${response.statusText} - ${errorText}`);
|
|
377
|
-
}
|
|
378
|
-
return response.arrayBuffer();
|
|
379
|
-
}
|
|
380
|
-
// models/embedding.ts
|
|
381
|
-
import { logger as logger5, ModelType, VECTOR_DIMS } from "@elizaos/core";
|
|
382
|
-
|
|
383
|
-
// utils/events.ts
|
|
384
|
-
import { EventType } from "@elizaos/core";
|
|
385
|
-
var MAX_PROMPT_LENGTH = 200;
|
|
386
|
-
function truncatePrompt(prompt) {
|
|
387
|
-
if (prompt.length <= MAX_PROMPT_LENGTH) {
|
|
388
|
-
return prompt;
|
|
389
|
-
}
|
|
390
|
-
return `${prompt.slice(0, MAX_PROMPT_LENGTH)}…`;
|
|
391
|
-
}
|
|
392
|
-
function normalizeUsage(usage) {
|
|
393
|
-
if ("promptTokens" in usage) {
|
|
394
|
-
const promptTokensDetails = "promptTokensDetails" in usage ? usage.promptTokensDetails : undefined;
|
|
395
|
-
const cachedPromptTokens = usage.cachedPromptTokens ?? promptTokensDetails?.cachedTokens;
|
|
396
|
-
return {
|
|
397
|
-
promptTokens: usage.promptTokens ?? 0,
|
|
398
|
-
completionTokens: usage.completionTokens ?? 0,
|
|
399
|
-
totalTokens: usage.totalTokens ?? (usage.promptTokens ?? 0) + (usage.completionTokens ?? 0),
|
|
400
|
-
cachedPromptTokens
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
if ("inputTokens" in usage || "outputTokens" in usage) {
|
|
404
|
-
const input = usage.inputTokens ?? 0;
|
|
405
|
-
const output = usage.outputTokens ?? 0;
|
|
406
|
-
const total = usage.totalTokens ?? input + output;
|
|
407
|
-
return {
|
|
408
|
-
promptTokens: input,
|
|
409
|
-
completionTokens: output,
|
|
410
|
-
totalTokens: total,
|
|
411
|
-
cachedPromptTokens: usage.cachedInputTokens
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
return {
|
|
415
|
-
promptTokens: 0,
|
|
416
|
-
completionTokens: 0,
|
|
417
|
-
totalTokens: 0
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
function emitModelUsageEvent(runtime, type, prompt, usage) {
|
|
421
|
-
const normalized = normalizeUsage(usage);
|
|
422
|
-
const payload = {
|
|
423
|
-
runtime,
|
|
424
|
-
source: "openai",
|
|
425
|
-
provider: "openai",
|
|
426
|
-
type,
|
|
427
|
-
prompt: truncatePrompt(prompt),
|
|
428
|
-
tokens: {
|
|
429
|
-
prompt: normalized.promptTokens,
|
|
430
|
-
completion: normalized.completionTokens,
|
|
431
|
-
total: normalized.totalTokens,
|
|
432
|
-
...normalized.cachedPromptTokens !== undefined ? { cached: normalized.cachedPromptTokens } : {}
|
|
433
|
-
}
|
|
434
|
-
};
|
|
435
|
-
runtime.emitEvent(EventType.MODEL_USED, payload);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
// models/embedding.ts
|
|
439
|
-
var MAX_EMBEDDING_TOKENS = 8000;
|
|
440
|
-
function validateDimension(dimension) {
|
|
441
|
-
const validDimensions = Object.values(VECTOR_DIMS);
|
|
442
|
-
if (!validDimensions.includes(dimension)) {
|
|
443
|
-
throw new Error(`Invalid embedding dimension: ${dimension}. Must be one of: ${validDimensions.join(", ")}`);
|
|
444
|
-
}
|
|
445
|
-
return dimension;
|
|
446
|
-
}
|
|
447
|
-
function extractText(params) {
|
|
448
|
-
if (params === null) {
|
|
449
|
-
return null;
|
|
450
|
-
}
|
|
451
|
-
if (typeof params === "string") {
|
|
452
|
-
return params;
|
|
453
|
-
}
|
|
454
|
-
if (typeof params === "object" && typeof params.text === "string") {
|
|
455
|
-
return params.text;
|
|
456
|
-
}
|
|
457
|
-
throw new Error("Invalid embedding params: expected string, { text: string }, or null");
|
|
458
|
-
}
|
|
459
|
-
async function handleTextEmbedding(runtime, params) {
|
|
460
|
-
const embeddingModel = getEmbeddingModel(runtime);
|
|
461
|
-
const embeddingDimension = validateDimension(getEmbeddingDimensions(runtime));
|
|
462
|
-
const text = extractText(params);
|
|
463
|
-
if (text === null) {
|
|
464
|
-
logger5.debug("[OpenAI] Creating test embedding for initialization");
|
|
465
|
-
const testVector = new Array(embeddingDimension).fill(0);
|
|
466
|
-
testVector[0] = 0.1;
|
|
467
|
-
return testVector;
|
|
468
|
-
}
|
|
469
|
-
let trimmedText = text.trim();
|
|
470
|
-
if (trimmedText.length === 0) {
|
|
471
|
-
throw new Error("Cannot generate embedding for empty text");
|
|
472
|
-
}
|
|
473
|
-
const maxChars = MAX_EMBEDDING_TOKENS * 4;
|
|
474
|
-
if (trimmedText.length > maxChars) {
|
|
475
|
-
logger5.warn(`[OpenAI] Embedding input too long (~${Math.ceil(trimmedText.length / 4)} tokens), truncating to ~${MAX_EMBEDDING_TOKENS} tokens`);
|
|
476
|
-
trimmedText = trimmedText.slice(0, maxChars);
|
|
477
|
-
}
|
|
478
|
-
const baseURL = getEmbeddingBaseURL(runtime);
|
|
479
|
-
const url = `${baseURL}/embeddings`;
|
|
480
|
-
logger5.debug(`[OpenAI] Generating embedding with model: ${embeddingModel}`);
|
|
481
|
-
const response = await fetch(url, {
|
|
482
|
-
method: "POST",
|
|
483
|
-
headers: {
|
|
484
|
-
...getAuthHeader(runtime, true),
|
|
485
|
-
"Content-Type": "application/json"
|
|
486
|
-
},
|
|
487
|
-
body: JSON.stringify({
|
|
488
|
-
model: embeddingModel,
|
|
489
|
-
input: trimmedText
|
|
490
|
-
})
|
|
491
|
-
});
|
|
492
|
-
if (!response.ok) {
|
|
493
|
-
const errorText = await response.text().catch(() => "Unknown error");
|
|
494
|
-
throw new Error(`OpenAI embedding API error: ${response.status} ${response.statusText} - ${errorText}`);
|
|
495
|
-
}
|
|
496
|
-
const data = await response.json();
|
|
497
|
-
const firstResult = data?.data?.[0];
|
|
498
|
-
if (!firstResult || !firstResult.embedding) {
|
|
499
|
-
throw new Error("OpenAI API returned invalid embedding response structure");
|
|
500
|
-
}
|
|
501
|
-
const embedding = firstResult.embedding;
|
|
502
|
-
if (embedding.length !== embeddingDimension) {
|
|
503
|
-
throw new Error(`Embedding dimension mismatch: got ${embedding.length}, expected ${embeddingDimension}. ` + `Check OPENAI_EMBEDDING_DIMENSIONS setting.`);
|
|
504
|
-
}
|
|
505
|
-
if (data.usage) {
|
|
506
|
-
emitModelUsageEvent(runtime, ModelType.TEXT_EMBEDDING, trimmedText, {
|
|
507
|
-
promptTokens: data.usage.prompt_tokens,
|
|
508
|
-
completionTokens: 0,
|
|
509
|
-
totalTokens: data.usage.total_tokens
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
logger5.debug(`[OpenAI] Generated embedding with ${embedding.length} dimensions`);
|
|
513
|
-
return embedding;
|
|
514
|
-
}
|
|
515
|
-
// models/image.ts
|
|
516
|
-
import { logger as logger6, ModelType as ModelType2 } from "@elizaos/core";
|
|
517
|
-
var DEFAULT_IMAGE_DESCRIPTION_PROMPT = "Please analyze this image and provide a title and detailed description.";
|
|
518
|
-
async function handleImageGeneration(runtime, params) {
|
|
519
|
-
const modelName = getImageModel(runtime);
|
|
520
|
-
const count = params.count ?? 1;
|
|
521
|
-
const size = params.size ?? "1024x1024";
|
|
522
|
-
const extendedParams = params;
|
|
523
|
-
logger6.debug(`[OpenAI] Using IMAGE model: ${modelName}`);
|
|
524
|
-
if (!params.prompt || params.prompt.trim().length === 0) {
|
|
525
|
-
throw new Error("IMAGE generation requires a non-empty prompt");
|
|
526
|
-
}
|
|
527
|
-
if (count < 1 || count > 10) {
|
|
528
|
-
throw new Error("IMAGE count must be between 1 and 10");
|
|
529
|
-
}
|
|
530
|
-
const baseURL = getBaseURL(runtime);
|
|
531
|
-
const requestBody = {
|
|
532
|
-
model: modelName,
|
|
533
|
-
prompt: params.prompt,
|
|
534
|
-
n: count,
|
|
535
|
-
size
|
|
536
|
-
};
|
|
537
|
-
if (extendedParams.quality) {
|
|
538
|
-
requestBody.quality = extendedParams.quality;
|
|
539
|
-
}
|
|
540
|
-
if (extendedParams.style) {
|
|
541
|
-
requestBody.style = extendedParams.style;
|
|
542
|
-
}
|
|
543
|
-
const response = await fetch(`${baseURL}/images/generations`, {
|
|
544
|
-
method: "POST",
|
|
545
|
-
headers: {
|
|
546
|
-
...getAuthHeader(runtime),
|
|
547
|
-
"Content-Type": "application/json"
|
|
548
|
-
},
|
|
549
|
-
body: JSON.stringify(requestBody)
|
|
550
|
-
});
|
|
551
|
-
if (!response.ok) {
|
|
552
|
-
const errorText = await response.text().catch(() => "Unknown error");
|
|
553
|
-
throw new Error(`OpenAI image generation failed: ${response.status} ${response.statusText} - ${errorText}`);
|
|
554
|
-
}
|
|
555
|
-
const data = await response.json();
|
|
556
|
-
if (!data.data || data.data.length === 0) {
|
|
557
|
-
throw new Error("OpenAI API returned no images");
|
|
558
|
-
}
|
|
559
|
-
return data.data.map((item) => ({
|
|
560
|
-
url: item.url,
|
|
561
|
-
revisedPrompt: item.revised_prompt
|
|
562
|
-
}));
|
|
563
|
-
}
|
|
564
|
-
function parseTitleFromResponse(content) {
|
|
565
|
-
const titleMatch = content.match(/title[:\s]+(.+?)(?:\n|$)/i);
|
|
566
|
-
return titleMatch?.[1]?.trim() ?? "Image Analysis";
|
|
567
|
-
}
|
|
568
|
-
function parseDescriptionFromResponse(content) {
|
|
569
|
-
return content.replace(/title[:\s]+(.+?)(?:\n|$)/i, "").trim();
|
|
570
|
-
}
|
|
571
|
-
async function handleImageDescription(runtime, params) {
|
|
572
|
-
const modelName = getImageDescriptionModel(runtime);
|
|
573
|
-
const maxTokens = getImageDescriptionMaxTokens(runtime);
|
|
574
|
-
logger6.debug(`[OpenAI] Using IMAGE_DESCRIPTION model: ${modelName}`);
|
|
575
|
-
let imageUrl;
|
|
576
|
-
let promptText;
|
|
577
|
-
if (typeof params === "string") {
|
|
578
|
-
imageUrl = params;
|
|
579
|
-
promptText = DEFAULT_IMAGE_DESCRIPTION_PROMPT;
|
|
580
|
-
} else {
|
|
581
|
-
imageUrl = params.imageUrl;
|
|
582
|
-
promptText = params.prompt ?? DEFAULT_IMAGE_DESCRIPTION_PROMPT;
|
|
583
|
-
}
|
|
584
|
-
if (!imageUrl || imageUrl.trim().length === 0) {
|
|
585
|
-
throw new Error("IMAGE_DESCRIPTION requires a valid image URL");
|
|
586
|
-
}
|
|
587
|
-
const baseURL = getBaseURL(runtime);
|
|
588
|
-
const requestBody = {
|
|
589
|
-
model: modelName,
|
|
590
|
-
messages: [
|
|
591
|
-
{
|
|
592
|
-
role: "user",
|
|
593
|
-
content: [
|
|
594
|
-
{ type: "text", text: promptText },
|
|
595
|
-
{ type: "image_url", image_url: { url: imageUrl } }
|
|
596
|
-
]
|
|
597
|
-
}
|
|
598
|
-
],
|
|
599
|
-
max_tokens: maxTokens
|
|
600
|
-
};
|
|
601
|
-
const response = await fetch(`${baseURL}/chat/completions`, {
|
|
602
|
-
method: "POST",
|
|
603
|
-
headers: {
|
|
604
|
-
...getAuthHeader(runtime),
|
|
605
|
-
"Content-Type": "application/json"
|
|
606
|
-
},
|
|
607
|
-
body: JSON.stringify(requestBody)
|
|
608
|
-
});
|
|
609
|
-
if (!response.ok) {
|
|
610
|
-
const errorText = await response.text().catch(() => "Unknown error");
|
|
611
|
-
throw new Error(`OpenAI image description failed: ${response.status} ${response.statusText} - ${errorText}`);
|
|
612
|
-
}
|
|
613
|
-
const data = await response.json();
|
|
614
|
-
if (data.usage) {
|
|
615
|
-
emitModelUsageEvent(runtime, ModelType2.IMAGE_DESCRIPTION, typeof params === "string" ? params : params.prompt ?? "", {
|
|
616
|
-
promptTokens: data.usage.prompt_tokens,
|
|
617
|
-
completionTokens: data.usage.completion_tokens,
|
|
618
|
-
totalTokens: data.usage.total_tokens
|
|
619
|
-
});
|
|
620
|
-
}
|
|
621
|
-
const firstChoice = data.choices?.[0];
|
|
622
|
-
const content = firstChoice?.message?.content;
|
|
623
|
-
if (!content) {
|
|
624
|
-
throw new Error("OpenAI API returned empty image description");
|
|
625
|
-
}
|
|
626
|
-
return {
|
|
627
|
-
title: parseTitleFromResponse(content),
|
|
628
|
-
description: parseDescriptionFromResponse(content)
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
// models/object.ts
|
|
632
|
-
import { logger as logger8, ModelType as ModelType3 } from "@elizaos/core";
|
|
633
|
-
import { generateObject } from "ai";
|
|
634
|
-
|
|
635
|
-
// providers/openai.ts
|
|
636
|
-
import { createOpenAI } from "@ai-sdk/openai";
|
|
637
|
-
var PROXY_API_KEY = "sk-proxy";
|
|
638
|
-
function createOpenAIClient(runtime) {
|
|
639
|
-
const baseURL = getBaseURL(runtime);
|
|
640
|
-
const apiKey = getApiKey(runtime);
|
|
641
|
-
if (!apiKey && isProxyMode(runtime)) {
|
|
642
|
-
return createOpenAI({
|
|
643
|
-
apiKey: PROXY_API_KEY,
|
|
644
|
-
baseURL
|
|
645
|
-
});
|
|
646
|
-
}
|
|
647
|
-
if (!apiKey) {
|
|
648
|
-
throw new Error("OPENAI_API_KEY is required. Set it in your environment variables or runtime settings.");
|
|
649
|
-
}
|
|
650
|
-
return createOpenAI({
|
|
651
|
-
apiKey,
|
|
652
|
-
baseURL
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
// utils/json.ts
|
|
656
|
-
import { logger as logger7 } from "@elizaos/core";
|
|
657
|
-
import { JSONParseError } from "ai";
|
|
658
|
-
var JSON_CLEANUP_PATTERNS = {
|
|
659
|
-
MARKDOWN_JSON: /```json\n|\n```|```/g,
|
|
660
|
-
WHITESPACE: /^\s+|\s+$/g
|
|
661
|
-
};
|
|
662
|
-
function getJsonRepairFunction() {
|
|
663
|
-
return async ({ text, error }) => {
|
|
664
|
-
if (!(error instanceof JSONParseError)) {
|
|
665
|
-
return null;
|
|
666
|
-
}
|
|
667
|
-
try {
|
|
668
|
-
const cleanedText = text.replace(JSON_CLEANUP_PATTERNS.MARKDOWN_JSON, "");
|
|
669
|
-
JSON.parse(cleanedText);
|
|
670
|
-
logger7.debug("[JSON Repair] Successfully repaired JSON by removing markdown wrappers");
|
|
671
|
-
return cleanedText;
|
|
672
|
-
} catch {
|
|
673
|
-
logger7.warn("[JSON Repair] Unable to repair JSON text");
|
|
674
|
-
return null;
|
|
675
|
-
}
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
// models/object.ts
|
|
680
|
-
async function generateObjectByModelType(runtime, params, modelType, getModelFn) {
|
|
681
|
-
const openai = createOpenAIClient(runtime);
|
|
682
|
-
const modelName = getModelFn(runtime);
|
|
683
|
-
logger8.debug(`[OpenAI] Using ${modelType} model: ${modelName}`);
|
|
684
|
-
if (!params.prompt || params.prompt.trim().length === 0) {
|
|
685
|
-
throw new Error("Object generation requires a non-empty prompt");
|
|
686
|
-
}
|
|
687
|
-
if (params.schema) {
|
|
688
|
-
logger8.debug("[OpenAI] Schema provided but using no-schema mode. " + "Structure is determined by prompt instructions.");
|
|
689
|
-
}
|
|
690
|
-
const model = openai.chat(modelName);
|
|
691
|
-
const { object, usage } = await generateObject({
|
|
692
|
-
model,
|
|
693
|
-
output: "no-schema",
|
|
694
|
-
prompt: params.prompt,
|
|
695
|
-
experimental_repairText: getJsonRepairFunction()
|
|
696
|
-
});
|
|
697
|
-
if (usage) {
|
|
698
|
-
emitModelUsageEvent(runtime, modelType, params.prompt, usage);
|
|
699
|
-
}
|
|
700
|
-
if (typeof object !== "object" || object === null) {
|
|
701
|
-
throw new Error(`Object generation returned ${typeof object}, expected object`);
|
|
702
|
-
}
|
|
703
|
-
return object;
|
|
704
|
-
}
|
|
705
|
-
async function handleObjectSmall(runtime, params) {
|
|
706
|
-
return generateObjectByModelType(runtime, params, ModelType3.OBJECT_SMALL, getSmallModel);
|
|
707
|
-
}
|
|
708
|
-
async function handleObjectLarge(runtime, params) {
|
|
709
|
-
return generateObjectByModelType(runtime, params, ModelType3.OBJECT_LARGE, getLargeModel);
|
|
710
|
-
}
|
|
711
|
-
// models/research.ts
|
|
712
|
-
import { logger as logger9 } from "@elizaos/core";
|
|
713
|
-
function convertToolToApi(tool) {
|
|
714
|
-
switch (tool.type) {
|
|
715
|
-
case "web_search_preview":
|
|
716
|
-
return { type: "web_search_preview" };
|
|
717
|
-
case "file_search":
|
|
718
|
-
return {
|
|
719
|
-
type: "file_search",
|
|
720
|
-
vector_store_ids: tool.vectorStoreIds
|
|
721
|
-
};
|
|
722
|
-
case "code_interpreter":
|
|
723
|
-
return {
|
|
724
|
-
type: "code_interpreter",
|
|
725
|
-
container: tool.container ?? { type: "auto" }
|
|
726
|
-
};
|
|
727
|
-
case "mcp":
|
|
728
|
-
return {
|
|
729
|
-
type: "mcp",
|
|
730
|
-
server_label: tool.serverLabel,
|
|
731
|
-
server_url: tool.serverUrl,
|
|
732
|
-
require_approval: tool.requireApproval ?? "never"
|
|
733
|
-
};
|
|
734
|
-
default:
|
|
735
|
-
throw new Error(`Unknown research tool type: ${tool.type}`);
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
function convertOutputItem(item) {
|
|
739
|
-
switch (item.type) {
|
|
740
|
-
case "web_search_call":
|
|
741
|
-
return {
|
|
742
|
-
id: item.id ?? "",
|
|
743
|
-
type: "web_search_call",
|
|
744
|
-
status: item.status ?? "completed",
|
|
745
|
-
action: {
|
|
746
|
-
type: item.action?.type ?? "search",
|
|
747
|
-
query: item.action?.query,
|
|
748
|
-
url: item.action?.url
|
|
749
|
-
}
|
|
750
|
-
};
|
|
751
|
-
case "file_search_call":
|
|
752
|
-
return {
|
|
753
|
-
id: item.id ?? "",
|
|
754
|
-
type: "file_search_call",
|
|
755
|
-
status: item.status ?? "completed",
|
|
756
|
-
query: item.query ?? "",
|
|
757
|
-
results: item.results?.map((r) => ({
|
|
758
|
-
fileId: r.file_id,
|
|
759
|
-
fileName: r.file_name,
|
|
760
|
-
score: r.score
|
|
761
|
-
}))
|
|
762
|
-
};
|
|
763
|
-
case "code_interpreter_call":
|
|
764
|
-
return {
|
|
765
|
-
id: item.id ?? "",
|
|
766
|
-
type: "code_interpreter_call",
|
|
767
|
-
status: item.status ?? "completed",
|
|
768
|
-
code: item.code ?? "",
|
|
769
|
-
output: item.output
|
|
770
|
-
};
|
|
771
|
-
case "mcp_tool_call":
|
|
772
|
-
return {
|
|
773
|
-
id: item.id ?? "",
|
|
774
|
-
type: "mcp_tool_call",
|
|
775
|
-
status: item.status ?? "completed",
|
|
776
|
-
serverLabel: item.server_label ?? "",
|
|
777
|
-
toolName: item.tool_name ?? "",
|
|
778
|
-
arguments: item.arguments ?? {},
|
|
779
|
-
result: item.result
|
|
780
|
-
};
|
|
781
|
-
case "message":
|
|
782
|
-
return {
|
|
783
|
-
type: "message",
|
|
784
|
-
content: item.content?.map((c) => ({
|
|
785
|
-
type: "output_text",
|
|
786
|
-
text: c.text,
|
|
787
|
-
annotations: c.annotations?.map((a) => ({
|
|
788
|
-
url: a.url,
|
|
789
|
-
title: a.title,
|
|
790
|
-
startIndex: a.start_index,
|
|
791
|
-
endIndex: a.end_index
|
|
792
|
-
})) ?? []
|
|
793
|
-
})) ?? []
|
|
794
|
-
};
|
|
795
|
-
default:
|
|
796
|
-
return null;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
function extractTextAndAnnotations(response) {
|
|
800
|
-
if (response.output_text) {
|
|
801
|
-
const annotations2 = [];
|
|
802
|
-
if (response.output) {
|
|
803
|
-
for (const item of response.output) {
|
|
804
|
-
if (item.type === "message" && item.content) {
|
|
805
|
-
for (const content of item.content) {
|
|
806
|
-
if (content.annotations) {
|
|
807
|
-
for (const ann of content.annotations) {
|
|
808
|
-
annotations2.push({
|
|
809
|
-
url: ann.url,
|
|
810
|
-
title: ann.title,
|
|
811
|
-
startIndex: ann.start_index,
|
|
812
|
-
endIndex: ann.end_index
|
|
813
|
-
});
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
return { text: response.output_text, annotations: annotations2 };
|
|
821
|
-
}
|
|
822
|
-
let text = "";
|
|
823
|
-
const annotations = [];
|
|
824
|
-
if (response.output) {
|
|
825
|
-
for (const item of response.output) {
|
|
826
|
-
if (item.type === "message" && item.content) {
|
|
827
|
-
for (const content of item.content) {
|
|
828
|
-
text += content.text;
|
|
829
|
-
if (content.annotations) {
|
|
830
|
-
for (const ann of content.annotations) {
|
|
831
|
-
annotations.push({
|
|
832
|
-
url: ann.url,
|
|
833
|
-
title: ann.title,
|
|
834
|
-
startIndex: ann.start_index,
|
|
835
|
-
endIndex: ann.end_index
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
return { text, annotations };
|
|
844
|
-
}
|
|
845
|
-
async function handleResearch(runtime, params) {
|
|
846
|
-
const apiKey = getApiKey(runtime);
|
|
847
|
-
if (!apiKey) {
|
|
848
|
-
throw new Error("OPENAI_API_KEY is required for deep research. Set it in your environment variables or runtime settings.");
|
|
849
|
-
}
|
|
850
|
-
const baseURL = getBaseURL(runtime);
|
|
851
|
-
const modelName = params.model ?? getResearchModel(runtime);
|
|
852
|
-
const timeout = getResearchTimeout(runtime);
|
|
853
|
-
logger9.debug(`[OpenAI] Starting deep research with model: ${modelName}`);
|
|
854
|
-
logger9.debug(`[OpenAI] Research input: ${params.input.substring(0, 100)}...`);
|
|
855
|
-
const dataSourceTools = params.tools?.filter((t) => t.type === "web_search_preview" || t.type === "file_search" || t.type === "mcp");
|
|
856
|
-
if (!dataSourceTools || dataSourceTools.length === 0) {
|
|
857
|
-
logger9.debug("[OpenAI] No data source tools specified, defaulting to web_search_preview");
|
|
858
|
-
params.tools = [{ type: "web_search_preview" }, ...params.tools ?? []];
|
|
859
|
-
}
|
|
860
|
-
const requestBody = {
|
|
861
|
-
model: modelName,
|
|
862
|
-
input: params.input
|
|
863
|
-
};
|
|
864
|
-
if (params.instructions) {
|
|
865
|
-
requestBody.instructions = params.instructions;
|
|
866
|
-
}
|
|
867
|
-
if (params.background !== undefined) {
|
|
868
|
-
requestBody.background = params.background;
|
|
869
|
-
}
|
|
870
|
-
if (params.tools && params.tools.length > 0) {
|
|
871
|
-
requestBody.tools = params.tools.map(convertToolToApi);
|
|
872
|
-
}
|
|
873
|
-
if (params.maxToolCalls !== undefined) {
|
|
874
|
-
requestBody.max_tool_calls = params.maxToolCalls;
|
|
875
|
-
}
|
|
876
|
-
if (params.reasoningSummary) {
|
|
877
|
-
requestBody.reasoning = { summary: params.reasoningSummary };
|
|
878
|
-
}
|
|
879
|
-
logger9.debug(`[OpenAI] Research request body: ${JSON.stringify(requestBody, null, 2)}`);
|
|
880
|
-
const response = await fetch(`${baseURL}/responses`, {
|
|
881
|
-
method: "POST",
|
|
882
|
-
headers: {
|
|
883
|
-
Authorization: `Bearer ${apiKey}`,
|
|
884
|
-
"Content-Type": "application/json"
|
|
885
|
-
},
|
|
886
|
-
body: JSON.stringify(requestBody),
|
|
887
|
-
signal: AbortSignal.timeout(timeout)
|
|
888
|
-
});
|
|
889
|
-
if (!response.ok) {
|
|
890
|
-
const errorText = await response.text();
|
|
891
|
-
logger9.error(`[OpenAI] Research request failed: ${response.status} ${errorText}`);
|
|
892
|
-
throw new Error(`Deep research request failed: ${response.status} ${response.statusText}`);
|
|
893
|
-
}
|
|
894
|
-
const data = await response.json();
|
|
895
|
-
if (data.error) {
|
|
896
|
-
logger9.error(`[OpenAI] Research API error: ${data.error.message}`);
|
|
897
|
-
throw new Error(`Deep research error: ${data.error.message}`);
|
|
898
|
-
}
|
|
899
|
-
logger9.debug(`[OpenAI] Research response received. Status: ${data.status ?? "completed"}`);
|
|
900
|
-
const { text, annotations } = extractTextAndAnnotations(data);
|
|
901
|
-
const outputItems = [];
|
|
902
|
-
if (data.output) {
|
|
903
|
-
for (const item of data.output) {
|
|
904
|
-
const converted = convertOutputItem(item);
|
|
905
|
-
if (converted) {
|
|
906
|
-
outputItems.push(converted);
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
const result = {
|
|
911
|
-
id: data.id,
|
|
912
|
-
text,
|
|
913
|
-
annotations,
|
|
914
|
-
outputItems,
|
|
915
|
-
status: data.status
|
|
916
|
-
};
|
|
917
|
-
logger9.info(`[OpenAI] Research completed. Text length: ${text.length}, Annotations: ${annotations.length}, Output items: ${outputItems.length}`);
|
|
918
|
-
return result;
|
|
919
|
-
}
|
|
920
|
-
// models/text.ts
|
|
921
|
-
import { logger as logger10, ModelType as ModelType4 } from "@elizaos/core";
|
|
922
|
-
import { generateText, streamText } from "ai";
|
|
923
|
-
function convertUsage(usage) {
|
|
924
|
-
if (!usage) {
|
|
925
|
-
return;
|
|
926
|
-
}
|
|
927
|
-
const promptTokens = usage.inputTokens ?? 0;
|
|
928
|
-
const completionTokens = usage.outputTokens ?? 0;
|
|
929
|
-
const usageWithCache = usage;
|
|
930
|
-
return {
|
|
931
|
-
promptTokens,
|
|
932
|
-
completionTokens,
|
|
933
|
-
totalTokens: promptTokens + completionTokens,
|
|
934
|
-
cachedPromptTokens: usageWithCache.cachedInputTokens
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
function resolvePromptCacheOptions(params) {
|
|
938
|
-
const withOpenAIOptions = params;
|
|
939
|
-
return {
|
|
940
|
-
promptCacheKey: withOpenAIOptions.providerOptions?.openai?.promptCacheKey,
|
|
941
|
-
promptCacheRetention: withOpenAIOptions.providerOptions?.openai?.promptCacheRetention
|
|
942
|
-
};
|
|
943
|
-
}
|
|
944
|
-
async function generateTextByModelType(runtime, params, modelType, getModelFn) {
|
|
945
|
-
const openai = createOpenAIClient(runtime);
|
|
946
|
-
const modelName = getModelFn(runtime);
|
|
947
|
-
logger10.debug(`[OpenAI] Using ${modelType} model: ${modelName}`);
|
|
948
|
-
const promptCacheOptions = resolvePromptCacheOptions(params);
|
|
949
|
-
const systemPrompt = runtime.character.system ?? undefined;
|
|
950
|
-
const model = openai.chat(modelName);
|
|
951
|
-
const generateParams = {
|
|
952
|
-
model,
|
|
953
|
-
prompt: params.prompt,
|
|
954
|
-
system: systemPrompt,
|
|
955
|
-
maxOutputTokens: params.maxTokens ?? 8192,
|
|
956
|
-
experimental_telemetry: { isEnabled: getExperimentalTelemetry(runtime) },
|
|
957
|
-
...promptCacheOptions.promptCacheKey || promptCacheOptions.promptCacheRetention ? {
|
|
958
|
-
providerOptions: {
|
|
959
|
-
openai: {
|
|
960
|
-
...promptCacheOptions.promptCacheKey ? { promptCacheKey: promptCacheOptions.promptCacheKey } : {},
|
|
961
|
-
...promptCacheOptions.promptCacheRetention ? { promptCacheRetention: promptCacheOptions.promptCacheRetention } : {}
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
} : {}
|
|
965
|
-
};
|
|
966
|
-
if (params.stream) {
|
|
967
|
-
const result = streamText(generateParams);
|
|
968
|
-
return {
|
|
969
|
-
textStream: result.textStream,
|
|
970
|
-
text: Promise.resolve(result.text),
|
|
971
|
-
usage: Promise.resolve(result.usage).then(convertUsage),
|
|
972
|
-
finishReason: Promise.resolve(result.finishReason).then((r) => r)
|
|
973
|
-
};
|
|
974
|
-
}
|
|
975
|
-
const { text, usage } = await generateText(generateParams);
|
|
976
|
-
if (usage) {
|
|
977
|
-
emitModelUsageEvent(runtime, modelType, params.prompt, usage);
|
|
978
|
-
}
|
|
979
|
-
return text;
|
|
980
|
-
}
|
|
981
|
-
async function handleTextSmall(runtime, params) {
|
|
982
|
-
return generateTextByModelType(runtime, params, ModelType4.TEXT_SMALL, getSmallModel);
|
|
983
|
-
}
|
|
984
|
-
async function handleTextLarge(runtime, params) {
|
|
985
|
-
return generateTextByModelType(runtime, params, ModelType4.TEXT_LARGE, getLargeModel);
|
|
986
|
-
}
|
|
987
|
-
// models/tokenizer.ts
|
|
988
|
-
import { ModelType as ModelType6 } from "@elizaos/core";
|
|
989
|
-
|
|
990
|
-
// utils/tokenization.ts
|
|
991
|
-
import { ModelType as ModelType5 } from "@elizaos/core";
|
|
992
|
-
import {
|
|
993
|
-
encodingForModel,
|
|
994
|
-
getEncoding
|
|
995
|
-
} from "js-tiktoken";
|
|
996
|
-
function resolveTokenizerEncoding(modelName) {
|
|
997
|
-
const normalized = modelName.toLowerCase();
|
|
998
|
-
const fallbackEncoding = normalized.includes("4o") ? "o200k_base" : "cl100k_base";
|
|
999
|
-
try {
|
|
1000
|
-
return encodingForModel(modelName);
|
|
1001
|
-
} catch {
|
|
1002
|
-
return getEncoding(fallbackEncoding);
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
function getModelName(runtime, modelType) {
|
|
1006
|
-
if (modelType === ModelType5.TEXT_SMALL) {
|
|
1007
|
-
return getSmallModel(runtime);
|
|
1008
|
-
}
|
|
1009
|
-
return getLargeModel(runtime);
|
|
1010
|
-
}
|
|
1011
|
-
function tokenizeText(runtime, modelType, text) {
|
|
1012
|
-
const modelName = getModelName(runtime, modelType);
|
|
1013
|
-
const encoder = resolveTokenizerEncoding(modelName);
|
|
1014
|
-
return encoder.encode(text);
|
|
1015
|
-
}
|
|
1016
|
-
function detokenizeText(runtime, modelType, tokens) {
|
|
1017
|
-
const modelName = getModelName(runtime, modelType);
|
|
1018
|
-
const encoder = resolveTokenizerEncoding(modelName);
|
|
1019
|
-
return encoder.decode(tokens);
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
// models/tokenizer.ts
|
|
1023
|
-
async function handleTokenizerEncode(runtime, params) {
|
|
1024
|
-
if (!params.prompt) {
|
|
1025
|
-
throw new Error("Tokenization requires a non-empty prompt");
|
|
1026
|
-
}
|
|
1027
|
-
const modelType = params.modelType ?? ModelType6.TEXT_LARGE;
|
|
1028
|
-
return tokenizeText(runtime, modelType, params.prompt);
|
|
1029
|
-
}
|
|
1030
|
-
async function handleTokenizerDecode(runtime, params) {
|
|
1031
|
-
if (!params.tokens || !Array.isArray(params.tokens)) {
|
|
1032
|
-
throw new Error("Detokenization requires a valid tokens array");
|
|
1033
|
-
}
|
|
1034
|
-
if (params.tokens.length === 0) {
|
|
1035
|
-
return "";
|
|
1036
|
-
}
|
|
1037
|
-
for (let i = 0;i < params.tokens.length; i++) {
|
|
1038
|
-
const token = params.tokens[i];
|
|
1039
|
-
if (typeof token !== "number" || !Number.isFinite(token)) {
|
|
1040
|
-
throw new Error(`Invalid token at index ${i}: expected number`);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
const modelType = params.modelType ?? ModelType6.TEXT_LARGE;
|
|
1044
|
-
return detokenizeText(runtime, modelType, params.tokens);
|
|
1045
|
-
}
|
|
1046
|
-
// index.ts
|
|
1047
|
-
function getProcessEnv() {
|
|
1048
|
-
if (typeof process === "undefined") {
|
|
1049
|
-
return {};
|
|
1050
|
-
}
|
|
1051
|
-
return process.env;
|
|
1052
|
-
}
|
|
1053
|
-
var env = getProcessEnv();
|
|
1054
|
-
var openaiPlugin = {
|
|
1055
|
-
name: "openai",
|
|
1056
|
-
description: "OpenAI API integration for text, image, audio, and embedding models",
|
|
1057
|
-
config: {
|
|
1058
|
-
OPENAI_API_KEY: env.OPENAI_API_KEY ?? null,
|
|
1059
|
-
OPENAI_BASE_URL: env.OPENAI_BASE_URL ?? null,
|
|
1060
|
-
OPENAI_SMALL_MODEL: env.OPENAI_SMALL_MODEL ?? null,
|
|
1061
|
-
OPENAI_LARGE_MODEL: env.OPENAI_LARGE_MODEL ?? null,
|
|
1062
|
-
SMALL_MODEL: env.SMALL_MODEL ?? null,
|
|
1063
|
-
LARGE_MODEL: env.LARGE_MODEL ?? null,
|
|
1064
|
-
OPENAI_EMBEDDING_MODEL: env.OPENAI_EMBEDDING_MODEL ?? null,
|
|
1065
|
-
OPENAI_EMBEDDING_API_KEY: env.OPENAI_EMBEDDING_API_KEY ?? null,
|
|
1066
|
-
OPENAI_EMBEDDING_URL: env.OPENAI_EMBEDDING_URL ?? null,
|
|
1067
|
-
OPENAI_EMBEDDING_DIMENSIONS: env.OPENAI_EMBEDDING_DIMENSIONS ?? null,
|
|
1068
|
-
OPENAI_IMAGE_DESCRIPTION_MODEL: env.OPENAI_IMAGE_DESCRIPTION_MODEL ?? null,
|
|
1069
|
-
OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS: env.OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS ?? null,
|
|
1070
|
-
OPENAI_EXPERIMENTAL_TELEMETRY: env.OPENAI_EXPERIMENTAL_TELEMETRY ?? null,
|
|
1071
|
-
OPENAI_RESEARCH_MODEL: env.OPENAI_RESEARCH_MODEL ?? null,
|
|
1072
|
-
OPENAI_RESEARCH_TIMEOUT: env.OPENAI_RESEARCH_TIMEOUT ?? null
|
|
1073
|
-
},
|
|
1074
|
-
async init(config, runtime) {
|
|
1075
|
-
initializeOpenAI(config, runtime);
|
|
1076
|
-
},
|
|
1077
|
-
models: {
|
|
1078
|
-
[ModelType7.TEXT_EMBEDDING]: async (runtime, params) => {
|
|
1079
|
-
return handleTextEmbedding(runtime, params);
|
|
1080
|
-
},
|
|
1081
|
-
[ModelType7.TEXT_TOKENIZER_ENCODE]: async (runtime, params) => {
|
|
1082
|
-
return handleTokenizerEncode(runtime, params);
|
|
1083
|
-
},
|
|
1084
|
-
[ModelType7.TEXT_TOKENIZER_DECODE]: async (runtime, params) => {
|
|
1085
|
-
return handleTokenizerDecode(runtime, params);
|
|
1086
|
-
},
|
|
1087
|
-
[ModelType7.TEXT_SMALL]: async (runtime, params) => {
|
|
1088
|
-
return handleTextSmall(runtime, params);
|
|
1089
|
-
},
|
|
1090
|
-
[ModelType7.TEXT_LARGE]: async (runtime, params) => {
|
|
1091
|
-
return handleTextLarge(runtime, params);
|
|
1092
|
-
},
|
|
1093
|
-
[ModelType7.IMAGE]: async (runtime, params) => {
|
|
1094
|
-
return handleImageGeneration(runtime, params);
|
|
1095
|
-
},
|
|
1096
|
-
[ModelType7.IMAGE_DESCRIPTION]: async (runtime, params) => {
|
|
1097
|
-
return handleImageDescription(runtime, params);
|
|
1098
|
-
},
|
|
1099
|
-
[ModelType7.TRANSCRIPTION]: async (runtime, input) => {
|
|
1100
|
-
return handleTranscription(runtime, input);
|
|
1101
|
-
},
|
|
1102
|
-
[ModelType7.TEXT_TO_SPEECH]: async (runtime, input) => {
|
|
1103
|
-
return handleTextToSpeech(runtime, input);
|
|
1104
|
-
},
|
|
1105
|
-
[ModelType7.OBJECT_SMALL]: async (runtime, params) => {
|
|
1106
|
-
return handleObjectSmall(runtime, params);
|
|
1107
|
-
},
|
|
1108
|
-
[ModelType7.OBJECT_LARGE]: async (runtime, params) => {
|
|
1109
|
-
return handleObjectLarge(runtime, params);
|
|
1110
|
-
},
|
|
1111
|
-
[ModelType7.RESEARCH]: async (runtime, params) => {
|
|
1112
|
-
return handleResearch(runtime, params);
|
|
1113
|
-
}
|
|
1114
|
-
},
|
|
1115
|
-
tests: [
|
|
1116
|
-
{
|
|
1117
|
-
name: "openai_plugin_tests",
|
|
1118
|
-
tests: [
|
|
1119
|
-
{
|
|
1120
|
-
name: "openai_test_api_connectivity",
|
|
1121
|
-
fn: async (runtime) => {
|
|
1122
|
-
const baseURL = getBaseURL(runtime);
|
|
1123
|
-
const response = await fetch(`${baseURL}/models`, {
|
|
1124
|
-
headers: getAuthHeader(runtime)
|
|
1125
|
-
});
|
|
1126
|
-
if (!response.ok) {
|
|
1127
|
-
throw new Error(`API connectivity test failed: ${response.status} ${response.statusText}`);
|
|
1128
|
-
}
|
|
1129
|
-
const data = await response.json();
|
|
1130
|
-
logger11.info(`[OpenAI Test] API connected. ${data.data?.length ?? 0} models available.`);
|
|
1131
|
-
}
|
|
1132
|
-
},
|
|
1133
|
-
{
|
|
1134
|
-
name: "openai_test_text_embedding",
|
|
1135
|
-
fn: async (runtime) => {
|
|
1136
|
-
const embedding = await runtime.useModel(ModelType7.TEXT_EMBEDDING, {
|
|
1137
|
-
text: "Hello, world!"
|
|
1138
|
-
});
|
|
1139
|
-
if (!Array.isArray(embedding) || embedding.length === 0) {
|
|
1140
|
-
throw new Error("Embedding should return a non-empty array");
|
|
1141
|
-
}
|
|
1142
|
-
logger11.info(`[OpenAI Test] Generated embedding with ${embedding.length} dimensions`);
|
|
1143
|
-
}
|
|
1144
|
-
},
|
|
1145
|
-
{
|
|
1146
|
-
name: "openai_test_text_small",
|
|
1147
|
-
fn: async (runtime) => {
|
|
1148
|
-
const text = await runtime.useModel(ModelType7.TEXT_SMALL, {
|
|
1149
|
-
prompt: "Say hello in exactly 5 words."
|
|
1150
|
-
});
|
|
1151
|
-
if (typeof text !== "string" || text.length === 0) {
|
|
1152
|
-
throw new Error("TEXT_SMALL should return non-empty string");
|
|
1153
|
-
}
|
|
1154
|
-
logger11.info(`[OpenAI Test] TEXT_SMALL generated: "${text.substring(0, 50)}..."`);
|
|
1155
|
-
}
|
|
1156
|
-
},
|
|
1157
|
-
{
|
|
1158
|
-
name: "openai_test_text_large",
|
|
1159
|
-
fn: async (runtime) => {
|
|
1160
|
-
const text = await runtime.useModel(ModelType7.TEXT_LARGE, {
|
|
1161
|
-
prompt: "Explain quantum computing in 2 sentences."
|
|
1162
|
-
});
|
|
1163
|
-
if (typeof text !== "string" || text.length === 0) {
|
|
1164
|
-
throw new Error("TEXT_LARGE should return non-empty string");
|
|
1165
|
-
}
|
|
1166
|
-
logger11.info(`[OpenAI Test] TEXT_LARGE generated: "${text.substring(0, 50)}..."`);
|
|
1167
|
-
}
|
|
1168
|
-
},
|
|
1169
|
-
{
|
|
1170
|
-
name: "openai_test_tokenizer_roundtrip",
|
|
1171
|
-
fn: async (runtime) => {
|
|
1172
|
-
const originalText = "Hello, tokenizer test!";
|
|
1173
|
-
const tokens = await runtime.useModel(ModelType7.TEXT_TOKENIZER_ENCODE, {
|
|
1174
|
-
prompt: originalText,
|
|
1175
|
-
modelType: ModelType7.TEXT_SMALL
|
|
1176
|
-
});
|
|
1177
|
-
if (!Array.isArray(tokens) || tokens.length === 0) {
|
|
1178
|
-
throw new Error("Tokenization should return non-empty token array");
|
|
1179
|
-
}
|
|
1180
|
-
const decodedText = await runtime.useModel(ModelType7.TEXT_TOKENIZER_DECODE, {
|
|
1181
|
-
tokens,
|
|
1182
|
-
modelType: ModelType7.TEXT_SMALL
|
|
1183
|
-
});
|
|
1184
|
-
if (decodedText !== originalText) {
|
|
1185
|
-
throw new Error(`Tokenizer roundtrip failed: expected "${originalText}", got "${decodedText}"`);
|
|
1186
|
-
}
|
|
1187
|
-
logger11.info(`[OpenAI Test] Tokenizer roundtrip successful (${tokens.length} tokens)`);
|
|
1188
|
-
}
|
|
1189
|
-
},
|
|
1190
|
-
{
|
|
1191
|
-
name: "openai_test_streaming",
|
|
1192
|
-
fn: async (runtime) => {
|
|
1193
|
-
const chunks = [];
|
|
1194
|
-
const result = await runtime.useModel(ModelType7.TEXT_LARGE, {
|
|
1195
|
-
prompt: "Count from 1 to 5, one number per line.",
|
|
1196
|
-
stream: true,
|
|
1197
|
-
onStreamChunk: (chunk) => {
|
|
1198
|
-
chunks.push(chunk);
|
|
1199
|
-
}
|
|
1200
|
-
});
|
|
1201
|
-
if (typeof result !== "string" || result.length === 0) {
|
|
1202
|
-
throw new Error("Streaming should return non-empty result");
|
|
1203
|
-
}
|
|
1204
|
-
if (chunks.length === 0) {
|
|
1205
|
-
throw new Error("No streaming chunks received");
|
|
1206
|
-
}
|
|
1207
|
-
logger11.info(`[OpenAI Test] Streaming test: ${chunks.length} chunks received`);
|
|
1208
|
-
}
|
|
1209
|
-
},
|
|
1210
|
-
{
|
|
1211
|
-
name: "openai_test_image_description",
|
|
1212
|
-
fn: async (runtime) => {
|
|
1213
|
-
const testImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Camponotus_flavomarginatus_ant.jpg/440px-Camponotus_flavomarginatus_ant.jpg";
|
|
1214
|
-
const result = await runtime.useModel(ModelType7.IMAGE_DESCRIPTION, testImageUrl);
|
|
1215
|
-
if (!result || typeof result !== "object" || !("title" in result) || !("description" in result)) {
|
|
1216
|
-
throw new Error("Image description should return { title, description }");
|
|
1217
|
-
}
|
|
1218
|
-
logger11.info(`[OpenAI Test] Image described: "${result.title}"`);
|
|
1219
|
-
}
|
|
1220
|
-
},
|
|
1221
|
-
{
|
|
1222
|
-
name: "openai_test_transcription",
|
|
1223
|
-
fn: async (runtime) => {
|
|
1224
|
-
const audioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/25/En-Open_Source.ogg";
|
|
1225
|
-
const response = await fetch(audioUrl);
|
|
1226
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
1227
|
-
const audioBuffer = Buffer.from(new Uint8Array(arrayBuffer));
|
|
1228
|
-
const transcription = await runtime.useModel(ModelType7.TRANSCRIPTION, audioBuffer);
|
|
1229
|
-
if (typeof transcription !== "string") {
|
|
1230
|
-
throw new Error("Transcription should return a string");
|
|
1231
|
-
}
|
|
1232
|
-
logger11.info(`[OpenAI Test] Transcription: "${transcription.substring(0, 50)}..."`);
|
|
1233
|
-
}
|
|
1234
|
-
},
|
|
1235
|
-
{
|
|
1236
|
-
name: "openai_test_text_to_speech",
|
|
1237
|
-
fn: async (runtime) => {
|
|
1238
|
-
const audioData = await runtime.useModel(ModelType7.TEXT_TO_SPEECH, {
|
|
1239
|
-
text: "Hello, this is a text-to-speech test."
|
|
1240
|
-
});
|
|
1241
|
-
if (!(audioData instanceof ArrayBuffer) || audioData.byteLength === 0) {
|
|
1242
|
-
throw new Error("TTS should return non-empty ArrayBuffer");
|
|
1243
|
-
}
|
|
1244
|
-
logger11.info(`[OpenAI Test] TTS generated ${audioData.byteLength} bytes of audio`);
|
|
1245
|
-
}
|
|
1246
|
-
},
|
|
1247
|
-
{
|
|
1248
|
-
name: "openai_test_object_generation",
|
|
1249
|
-
fn: async (runtime) => {
|
|
1250
|
-
const result = await runtime.useModel(ModelType7.OBJECT_SMALL, {
|
|
1251
|
-
prompt: "Return a JSON object with exactly these fields: name (string), age (number), active (boolean)"
|
|
1252
|
-
});
|
|
1253
|
-
if (!result || typeof result !== "object") {
|
|
1254
|
-
throw new Error("Object generation should return an object");
|
|
1255
|
-
}
|
|
1256
|
-
logger11.info(`[OpenAI Test] Object generated: ${JSON.stringify(result).substring(0, 100)}`);
|
|
1257
|
-
}
|
|
1258
|
-
},
|
|
1259
|
-
{
|
|
1260
|
-
name: "openai_test_research",
|
|
1261
|
-
fn: async (runtime) => {
|
|
1262
|
-
const result = await runtime.useModel(ModelType7.RESEARCH, {
|
|
1263
|
-
input: "What is the current date and time?",
|
|
1264
|
-
tools: [{ type: "web_search_preview" }],
|
|
1265
|
-
maxToolCalls: 3
|
|
1266
|
-
});
|
|
1267
|
-
if (!result || typeof result !== "object" || !("text" in result)) {
|
|
1268
|
-
throw new Error("Research should return an object with text property");
|
|
1269
|
-
}
|
|
1270
|
-
if (typeof result.text !== "string" || result.text.length === 0) {
|
|
1271
|
-
throw new Error("Research result text should be a non-empty string");
|
|
1272
|
-
}
|
|
1273
|
-
logger11.info(`[OpenAI Test] Research completed. Text length: ${result.text.length}, Annotations: ${result.annotations?.length ?? 0}`);
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1276
|
-
]
|
|
1277
|
-
}
|
|
1278
|
-
]
|
|
1279
|
-
};
|
|
1280
|
-
var typescript_default = openaiPlugin;
|
|
1281
|
-
export {
|
|
1282
|
-
openaiPlugin,
|
|
1283
|
-
typescript_default as default
|
|
1284
|
-
};
|
|
1285
|
-
|
|
1286
|
-
//# debugId=A63C30D83B0EE8CA64756E2164756E21
|