@elizaos/plugin-openai 2.0.0-beta.1 → 2.0.11-beta.7

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.
Files changed (58) hide show
  1. package/README.md +175 -117
  2. package/auto-enable.ts +2 -2
  3. package/package.json +45 -7
  4. package/dist/browser/index.browser.js +0 -3
  5. package/dist/browser/index.browser.js.map +0 -23
  6. package/dist/browser/index.d.ts +0 -2
  7. package/dist/build.d.ts +0 -13
  8. package/dist/build.d.ts.map +0 -1
  9. package/dist/cjs/index.d.ts +0 -2
  10. package/dist/cjs/index.node.cjs +0 -1748
  11. package/dist/cjs/index.node.js.map +0 -25
  12. package/dist/generated/specs/specs.d.ts +0 -55
  13. package/dist/generated/specs/specs.d.ts.map +0 -1
  14. package/dist/index.browser.d.ts +0 -4
  15. package/dist/index.browser.d.ts.map +0 -1
  16. package/dist/index.d.ts +0 -4
  17. package/dist/index.d.ts.map +0 -1
  18. package/dist/index.node.d.ts +0 -4
  19. package/dist/index.node.d.ts.map +0 -1
  20. package/dist/init.d.ts +0 -4
  21. package/dist/init.d.ts.map +0 -1
  22. package/dist/models/audio.d.ts +0 -9
  23. package/dist/models/audio.d.ts.map +0 -1
  24. package/dist/models/embedding.d.ts +0 -3
  25. package/dist/models/embedding.d.ts.map +0 -1
  26. package/dist/models/image.d.ts +0 -5
  27. package/dist/models/image.d.ts.map +0 -1
  28. package/dist/models/index.d.ts +0 -7
  29. package/dist/models/index.d.ts.map +0 -1
  30. package/dist/models/object.d.ts +0 -4
  31. package/dist/models/object.d.ts.map +0 -1
  32. package/dist/models/research.d.ts +0 -34
  33. package/dist/models/research.d.ts.map +0 -1
  34. package/dist/models/text.d.ts +0 -33
  35. package/dist/models/text.d.ts.map +0 -1
  36. package/dist/models/tokenizer.d.ts +0 -4
  37. package/dist/models/tokenizer.d.ts.map +0 -1
  38. package/dist/node/index.d.ts +0 -2
  39. package/dist/node/index.node.js +0 -1881
  40. package/dist/node/index.node.js.map +0 -23
  41. package/dist/providers/index.d.ts +0 -2
  42. package/dist/providers/index.d.ts.map +0 -1
  43. package/dist/providers/openai.d.ts +0 -4
  44. package/dist/providers/openai.d.ts.map +0 -1
  45. package/dist/types/index.d.ts +0 -363
  46. package/dist/types/index.d.ts.map +0 -1
  47. package/dist/utils/audio.d.ts +0 -6
  48. package/dist/utils/audio.d.ts.map +0 -1
  49. package/dist/utils/config.d.ts +0 -38
  50. package/dist/utils/config.d.ts.map +0 -1
  51. package/dist/utils/events.d.ts +0 -21
  52. package/dist/utils/events.d.ts.map +0 -1
  53. package/dist/utils/index.d.ts +0 -6
  54. package/dist/utils/index.d.ts.map +0 -1
  55. package/dist/utils/json.d.ts +0 -10
  56. package/dist/utils/json.d.ts.map +0 -1
  57. package/dist/utils/tokenization.d.ts +0 -6
  58. package/dist/utils/tokenization.d.ts.map +0 -1
@@ -1,1881 +0,0 @@
1
- // index.ts
2
- import { logger as logger9, ModelType as ModelType6 } 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 isCerebrasMode(runtime) {
49
- const explicitProvider = getSetting(runtime, "MILADY_PROVIDER");
50
- if (explicitProvider && explicitProvider.toLowerCase() === "cerebras") {
51
- return true;
52
- }
53
- const baseURL = getSetting(runtime, "OPENAI_BASE_URL");
54
- if (baseURL && /(^|\.)cerebras\.ai(\/|$)/i.test(baseURL)) {
55
- return true;
56
- }
57
- return false;
58
- }
59
- function getApiKey(runtime) {
60
- if (isCerebrasMode(runtime)) {
61
- const cerebrasKey = getSetting(runtime, "CEREBRAS_API_KEY");
62
- if (cerebrasKey) {
63
- return cerebrasKey;
64
- }
65
- }
66
- return getSetting(runtime, "OPENAI_API_KEY");
67
- }
68
- function getEmbeddingApiKey(runtime) {
69
- const embeddingApiKey = getSetting(runtime, "OPENAI_EMBEDDING_API_KEY");
70
- if (embeddingApiKey) {
71
- logger.debug("[OpenAI] Using specific embedding API key");
72
- return embeddingApiKey;
73
- }
74
- logger.debug("[OpenAI] Falling back to general API key for embeddings");
75
- return getApiKey(runtime);
76
- }
77
- function getAuthHeader(runtime, forEmbedding = false) {
78
- if (isBrowser() && !getBooleanSetting(runtime, "OPENAI_ALLOW_BROWSER_API_KEY", false)) {
79
- return {};
80
- }
81
- const key = forEmbedding ? getEmbeddingApiKey(runtime) : getApiKey(runtime);
82
- return key ? { Authorization: `Bearer ${key}` } : {};
83
- }
84
- function getBaseURL(runtime) {
85
- const browserURL = getSetting(runtime, "OPENAI_BROWSER_BASE_URL");
86
- const baseURL = isBrowser() && browserURL ? browserURL : getSetting(runtime, "OPENAI_BASE_URL") ?? "https://api.openai.com/v1";
87
- logger.debug(`[OpenAI] Base URL: ${baseURL}`);
88
- return baseURL;
89
- }
90
- function getEmbeddingBaseURL(runtime) {
91
- const embeddingURL = isBrowser() ? getSetting(runtime, "OPENAI_BROWSER_EMBEDDING_URL") ?? getSetting(runtime, "OPENAI_BROWSER_BASE_URL") : getSetting(runtime, "OPENAI_EMBEDDING_URL");
92
- if (embeddingURL) {
93
- logger.debug(`[OpenAI] Using embedding base URL: ${embeddingURL}`);
94
- return embeddingURL;
95
- }
96
- logger.debug("[OpenAI] Falling back to general base URL for embeddings");
97
- return getBaseURL(runtime);
98
- }
99
- function getSmallModel(runtime) {
100
- return getSetting(runtime, "OPENAI_SMALL_MODEL") ?? getSetting(runtime, "SMALL_MODEL") ?? "gpt-5.4-mini";
101
- }
102
- function getNanoModel(runtime) {
103
- return getSetting(runtime, "OPENAI_NANO_MODEL") ?? getSetting(runtime, "NANO_MODEL") ?? getSmallModel(runtime);
104
- }
105
- function getMediumModel(runtime) {
106
- return getSetting(runtime, "OPENAI_MEDIUM_MODEL") ?? getSetting(runtime, "MEDIUM_MODEL") ?? getSmallModel(runtime);
107
- }
108
- function getLargeModel(runtime) {
109
- return getSetting(runtime, "OPENAI_LARGE_MODEL") ?? getSetting(runtime, "LARGE_MODEL") ?? "gpt-5";
110
- }
111
- function getMegaModel(runtime) {
112
- return getSetting(runtime, "OPENAI_MEGA_MODEL") ?? getSetting(runtime, "MEGA_MODEL") ?? getLargeModel(runtime);
113
- }
114
- function getResponseHandlerModel(runtime) {
115
- return getSetting(runtime, "OPENAI_RESPONSE_HANDLER_MODEL") ?? getSetting(runtime, "OPENAI_SHOULD_RESPOND_MODEL") ?? getSetting(runtime, "RESPONSE_HANDLER_MODEL") ?? getSetting(runtime, "SHOULD_RESPOND_MODEL") ?? getSmallModel(runtime);
116
- }
117
- function getActionPlannerModel(runtime) {
118
- return getSetting(runtime, "OPENAI_ACTION_PLANNER_MODEL") ?? getSetting(runtime, "OPENAI_PLANNER_MODEL") ?? getSetting(runtime, "ACTION_PLANNER_MODEL") ?? getSetting(runtime, "PLANNER_MODEL") ?? getMediumModel(runtime);
119
- }
120
- function getEmbeddingModel(runtime) {
121
- return getSetting(runtime, "OPENAI_EMBEDDING_MODEL") ?? "text-embedding-3-small";
122
- }
123
- function getImageDescriptionModel(runtime) {
124
- return getSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MODEL") ?? "gpt-5-mini";
125
- }
126
- function getTranscriptionModel(runtime) {
127
- return getSetting(runtime, "OPENAI_TRANSCRIPTION_MODEL") ?? "gpt-5-mini-transcribe";
128
- }
129
- function getTTSModel(runtime) {
130
- return getSetting(runtime, "OPENAI_TTS_MODEL") ?? "tts-1";
131
- }
132
- function getTTSVoice(runtime) {
133
- return getSetting(runtime, "OPENAI_TTS_VOICE") ?? "nova";
134
- }
135
- function getTTSInstructions(runtime) {
136
- return getSetting(runtime, "OPENAI_TTS_INSTRUCTIONS") ?? "";
137
- }
138
- function getImageModel(runtime) {
139
- return getSetting(runtime, "OPENAI_IMAGE_MODEL") ?? "dall-e-3";
140
- }
141
- function getExperimentalTelemetry(runtime) {
142
- return getBooleanSetting(runtime, "OPENAI_EXPERIMENTAL_TELEMETRY", false);
143
- }
144
- function getEmbeddingDimensions(runtime) {
145
- return getNumericSetting(runtime, "OPENAI_EMBEDDING_DIMENSIONS", 1536);
146
- }
147
- function getImageDescriptionMaxTokens(runtime) {
148
- return getNumericSetting(runtime, "OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS", 8192);
149
- }
150
- function getResearchModel(runtime) {
151
- return getSetting(runtime, "OPENAI_RESEARCH_MODEL") ?? "o3-deep-research";
152
- }
153
- function getResearchTimeout(runtime) {
154
- return getNumericSetting(runtime, "OPENAI_RESEARCH_TIMEOUT", 3600000);
155
- }
156
-
157
- // init.ts
158
- globalThis.AI_SDK_LOG_WARNINGS ??= false;
159
- function initializeOpenAI(_config, runtime) {
160
- validateOpenAIConfiguration(runtime);
161
- }
162
- async function validateOpenAIConfiguration(runtime) {
163
- if (isBrowser()) {
164
- logger2.debug("[OpenAI] Skipping API validation in browser environment");
165
- return;
166
- }
167
- const apiKey = getApiKey(runtime);
168
- if (!apiKey) {
169
- logger2.warn("[OpenAI] OPENAI_API_KEY is not configured. " + "OpenAI functionality will fail until a valid API key is provided.");
170
- return;
171
- }
172
- try {
173
- const baseURL = getBaseURL(runtime);
174
- const response = await fetch(`${baseURL}/models`, {
175
- headers: getAuthHeader(runtime)
176
- });
177
- if (!response.ok) {
178
- logger2.warn(`[OpenAI] API key validation failed: ${response.status} ${response.statusText}. ` + "Please verify your OPENAI_API_KEY is correct.");
179
- return;
180
- }
181
- } catch (error) {
182
- const message = error instanceof Error ? error.message : String(error);
183
- logger2.warn(`[OpenAI] API validation error: ${message}. OpenAI functionality may be limited.`);
184
- }
185
- }
186
-
187
- // models/audio.ts
188
- import { logger as logger4, recordLlmCall } from "@elizaos/core";
189
-
190
- // utils/audio.ts
191
- import { logger as logger3 } from "@elizaos/core";
192
- var MAGIC_BYTES = {
193
- WAV: {
194
- HEADER: [82, 73, 70, 70],
195
- IDENTIFIER: [87, 65, 86, 69]
196
- },
197
- MP3_ID3: [73, 68, 51],
198
- OGG: [79, 103, 103, 83],
199
- FLAC: [102, 76, 97, 67],
200
- FTYP: [102, 116, 121, 112],
201
- WEBM_EBML: [26, 69, 223, 163]
202
- };
203
- var MIN_DETECTION_BUFFER_SIZE = 12;
204
- function matchBytes(buffer, offset, expected) {
205
- for (let i = 0;i < expected.length; i++) {
206
- const expectedByte = expected[i];
207
- if (expectedByte === undefined || buffer[offset + i] !== expectedByte) {
208
- return false;
209
- }
210
- }
211
- return true;
212
- }
213
- function detectAudioMimeType(buffer) {
214
- if (buffer.length < MIN_DETECTION_BUFFER_SIZE) {
215
- return "application/octet-stream";
216
- }
217
- if (matchBytes(buffer, 0, MAGIC_BYTES.WAV.HEADER) && matchBytes(buffer, 8, MAGIC_BYTES.WAV.IDENTIFIER)) {
218
- return "audio/wav";
219
- }
220
- const firstByte = buffer[0];
221
- const secondByte = buffer[1];
222
- if (matchBytes(buffer, 0, MAGIC_BYTES.MP3_ID3) || firstByte === 255 && secondByte !== undefined && (secondByte & 224) === 224) {
223
- return "audio/mpeg";
224
- }
225
- if (matchBytes(buffer, 0, MAGIC_BYTES.OGG)) {
226
- return "audio/ogg";
227
- }
228
- if (matchBytes(buffer, 0, MAGIC_BYTES.FLAC)) {
229
- return "audio/flac";
230
- }
231
- if (matchBytes(buffer, 4, MAGIC_BYTES.FTYP)) {
232
- return "audio/mp4";
233
- }
234
- if (matchBytes(buffer, 0, MAGIC_BYTES.WEBM_EBML)) {
235
- return "audio/webm";
236
- }
237
- logger3.warn("Could not detect audio format from buffer, using generic binary type");
238
- return "application/octet-stream";
239
- }
240
- function getExtensionForMimeType(mimeType) {
241
- switch (mimeType) {
242
- case "audio/wav":
243
- return "wav";
244
- case "audio/mpeg":
245
- return "mp3";
246
- case "audio/ogg":
247
- return "ogg";
248
- case "audio/flac":
249
- return "flac";
250
- case "audio/mp4":
251
- return "m4a";
252
- case "audio/webm":
253
- return "webm";
254
- case "application/octet-stream":
255
- return "bin";
256
- }
257
- }
258
- function getFilenameForMimeType(mimeType) {
259
- const ext = getExtensionForMimeType(mimeType);
260
- return `recording.${ext}`;
261
- }
262
-
263
- // models/audio.ts
264
- function isBlobOrFile(value) {
265
- return value instanceof Blob || value instanceof File;
266
- }
267
- function isBuffer(value) {
268
- return Buffer.isBuffer(value);
269
- }
270
- function isLocalTranscriptionParams(value) {
271
- return typeof value === "object" && value !== null && "audio" in value && (isBlobOrFile(value.audio) || isBuffer(value.audio));
272
- }
273
- function isCoreTranscriptionParams(value) {
274
- return typeof value === "object" && value !== null && "audioUrl" in value && typeof value.audioUrl === "string";
275
- }
276
- async function fetchAudioFromUrl(url) {
277
- const response = await fetch(url);
278
- if (!response.ok) {
279
- throw new Error(`Failed to fetch audio from URL: ${response.status}`);
280
- }
281
- return response.blob();
282
- }
283
- async function handleTranscription(runtime, input) {
284
- let modelName = getTranscriptionModel(runtime);
285
- let blob;
286
- let extraParams = {};
287
- if (typeof input === "string") {
288
- logger4.debug(`[OpenAI] Fetching audio from URL: ${input}`);
289
- blob = await fetchAudioFromUrl(input);
290
- } else if (isBlobOrFile(input)) {
291
- blob = input;
292
- } else if (isBuffer(input)) {
293
- const mimeType2 = detectAudioMimeType(input);
294
- logger4.debug(`[OpenAI] Auto-detected audio MIME type: ${mimeType2}`);
295
- blob = new Blob([new Uint8Array(input)], { type: mimeType2 });
296
- } else if (isLocalTranscriptionParams(input)) {
297
- extraParams = input;
298
- if (input.model) {
299
- modelName = input.model;
300
- }
301
- if (isBuffer(input.audio)) {
302
- const mimeType2 = input.mimeType ?? detectAudioMimeType(input.audio);
303
- logger4.debug(`[OpenAI] Using MIME type: ${mimeType2}`);
304
- blob = new Blob([new Uint8Array(input.audio)], { type: mimeType2 });
305
- } else {
306
- blob = input.audio;
307
- }
308
- } else if (isCoreTranscriptionParams(input)) {
309
- logger4.debug(`[OpenAI] Fetching audio from URL: ${input.audioUrl}`);
310
- blob = await fetchAudioFromUrl(input.audioUrl);
311
- extraParams = { prompt: input.prompt };
312
- } else {
313
- throw new Error("TRANSCRIPTION expects Blob, File, Buffer, URL string, or TranscriptionParams object");
314
- }
315
- logger4.debug(`[OpenAI] Using TRANSCRIPTION model: ${modelName}`);
316
- const mimeType = blob.type || "audio/webm";
317
- const filename = blob.name || getFilenameForMimeType(mimeType.startsWith("audio/") ? mimeType : "audio/webm");
318
- const formData = new FormData;
319
- formData.append("file", blob, filename);
320
- formData.append("model", modelName);
321
- if (extraParams.language) {
322
- formData.append("language", extraParams.language);
323
- }
324
- if (extraParams.responseFormat) {
325
- formData.append("response_format", extraParams.responseFormat);
326
- }
327
- if (extraParams.prompt) {
328
- formData.append("prompt", extraParams.prompt);
329
- }
330
- if (extraParams.temperature !== undefined) {
331
- formData.append("temperature", String(extraParams.temperature));
332
- }
333
- if (extraParams.timestampGranularities) {
334
- for (const granularity of extraParams.timestampGranularities) {
335
- formData.append("timestamp_granularities[]", granularity);
336
- }
337
- }
338
- const baseURL = getBaseURL(runtime);
339
- const details = {
340
- model: modelName,
341
- systemPrompt: extraParams.prompt ?? "",
342
- userPrompt: [
343
- `audio transcription request: filename=${filename}`,
344
- `mimeType=${mimeType}`,
345
- extraParams.language ? `language=${extraParams.language}` : "",
346
- extraParams.responseFormat ? `responseFormat=${extraParams.responseFormat}` : ""
347
- ].filter(Boolean).join(" "),
348
- temperature: extraParams.temperature ?? 0,
349
- maxTokens: 0,
350
- purpose: "external_llm",
351
- actionType: "openai.audio.transcriptions.create"
352
- };
353
- const data = await recordLlmCall(runtime, details, async () => {
354
- const response = await fetch(`${baseURL}/audio/transcriptions`, {
355
- method: "POST",
356
- headers: getAuthHeader(runtime),
357
- body: formData
358
- });
359
- if (!response.ok) {
360
- const errorText = await response.text().catch(() => "Unknown error");
361
- throw new Error(`OpenAI transcription failed: ${response.status} ${response.statusText} - ${errorText}`);
362
- }
363
- const result = await response.json();
364
- details.response = result.text;
365
- return result;
366
- });
367
- return data.text;
368
- }
369
- async function handleTextToSpeech(runtime, input) {
370
- let text;
371
- let voice;
372
- let format = "mp3";
373
- let model;
374
- let instructions;
375
- if (typeof input === "string") {
376
- text = input;
377
- voice = undefined;
378
- } else {
379
- text = input.text;
380
- voice = input.voice;
381
- if ("format" in input && input.format) {
382
- format = input.format;
383
- }
384
- if ("model" in input && input.model) {
385
- model = input.model;
386
- }
387
- if ("instructions" in input && input.instructions) {
388
- instructions = input.instructions;
389
- }
390
- }
391
- model = model ?? getTTSModel(runtime);
392
- voice = voice ?? getTTSVoice(runtime);
393
- instructions = instructions ?? getTTSInstructions(runtime);
394
- logger4.debug(`[OpenAI] Using TEXT_TO_SPEECH model: ${model}`);
395
- if (!text || text.trim().length === 0) {
396
- throw new Error("TEXT_TO_SPEECH requires non-empty text");
397
- }
398
- if (text.length > 4096) {
399
- throw new Error("TEXT_TO_SPEECH text exceeds 4096 character limit");
400
- }
401
- const validVoices = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];
402
- if (voice && !validVoices.includes(voice)) {
403
- throw new Error(`Invalid voice: ${voice}. Must be one of: ${validVoices.join(", ")}`);
404
- }
405
- const baseURL = getBaseURL(runtime);
406
- const requestBody = {
407
- model,
408
- voice,
409
- input: text,
410
- response_format: format
411
- };
412
- if (instructions && instructions.length > 0) {
413
- requestBody.instructions = instructions;
414
- }
415
- const details = {
416
- model,
417
- systemPrompt: instructions ?? "",
418
- userPrompt: text,
419
- temperature: 0,
420
- maxTokens: 0,
421
- purpose: "external_llm",
422
- actionType: "openai.audio.speech.create"
423
- };
424
- return recordLlmCall(runtime, details, async () => {
425
- const response = await fetch(`${baseURL}/audio/speech`, {
426
- method: "POST",
427
- headers: {
428
- ...getAuthHeader(runtime),
429
- "Content-Type": "application/json",
430
- ...format === "mp3" ? { Accept: "audio/mpeg" } : {}
431
- },
432
- body: JSON.stringify(requestBody)
433
- });
434
- if (!response.ok) {
435
- const errorText = await response.text().catch(() => "Unknown error");
436
- throw new Error(`OpenAI TTS failed: ${response.status} ${response.statusText} - ${errorText}`);
437
- }
438
- const audioBuffer = await response.arrayBuffer();
439
- details.response = `[audio bytes=${audioBuffer.byteLength} format=${format}]`;
440
- return audioBuffer;
441
- });
442
- }
443
- // models/embedding.ts
444
- import { logger as logger5, ModelType, VECTOR_DIMS } from "@elizaos/core";
445
-
446
- // utils/events.ts
447
- import { EventType } from "@elizaos/core";
448
- var MAX_PROMPT_LENGTH = 200;
449
- function truncatePrompt(prompt) {
450
- if (prompt.length <= MAX_PROMPT_LENGTH) {
451
- return prompt;
452
- }
453
- return `${prompt.slice(0, MAX_PROMPT_LENGTH)}…`;
454
- }
455
- function normalizeUsage(usage) {
456
- if ("promptTokens" in usage) {
457
- const promptTokensDetails = "promptTokensDetails" in usage ? usage.promptTokensDetails : undefined;
458
- const cachedPromptTokens = usage.cachedPromptTokens ?? promptTokensDetails?.cachedTokens;
459
- return {
460
- promptTokens: usage.promptTokens ?? 0,
461
- completionTokens: usage.completionTokens ?? 0,
462
- totalTokens: usage.totalTokens ?? (usage.promptTokens ?? 0) + (usage.completionTokens ?? 0),
463
- cachedPromptTokens
464
- };
465
- }
466
- if ("inputTokens" in usage || "outputTokens" in usage) {
467
- const input = usage.inputTokens ?? 0;
468
- const output = usage.outputTokens ?? 0;
469
- const total = usage.totalTokens ?? input + output;
470
- return {
471
- promptTokens: input,
472
- completionTokens: output,
473
- totalTokens: total,
474
- cachedPromptTokens: usage.cachedInputTokens
475
- };
476
- }
477
- return {
478
- promptTokens: 0,
479
- completionTokens: 0,
480
- totalTokens: 0
481
- };
482
- }
483
- function emitModelUsageEvent(runtime, type, prompt, usage) {
484
- const normalized = normalizeUsage(usage);
485
- const payload = {
486
- runtime,
487
- source: "openai",
488
- provider: "openai",
489
- type,
490
- prompt: truncatePrompt(prompt),
491
- tokens: {
492
- prompt: normalized.promptTokens,
493
- completion: normalized.completionTokens,
494
- total: normalized.totalTokens,
495
- ...normalized.cachedPromptTokens !== undefined ? { cached: normalized.cachedPromptTokens } : {}
496
- }
497
- };
498
- runtime.emitEvent(EventType.MODEL_USED, payload);
499
- }
500
-
501
- // models/embedding.ts
502
- function validateDimension(dimension) {
503
- const validDimensions = Object.values(VECTOR_DIMS);
504
- if (!validDimensions.includes(dimension)) {
505
- throw new Error(`Invalid embedding dimension: ${dimension}. Must be one of: ${validDimensions.join(", ")}`);
506
- }
507
- return dimension;
508
- }
509
- function extractText(params) {
510
- if (params === null) {
511
- return null;
512
- }
513
- if (typeof params === "string") {
514
- return params;
515
- }
516
- if (typeof params === "object" && typeof params.text === "string") {
517
- return params.text;
518
- }
519
- throw new Error("Invalid embedding params: expected string, { text: string }, or null");
520
- }
521
- function hasExplicitEmbeddingEndpoint(runtime) {
522
- const key = isBrowser() ? "OPENAI_BROWSER_EMBEDDING_URL" : "OPENAI_EMBEDDING_URL";
523
- const value = getSetting(runtime, key);
524
- return typeof value === "string" && value.trim().length > 0;
525
- }
526
- function shouldUseLocalEmbeddingFallback(runtime) {
527
- return isCerebrasMode(runtime) && !hasExplicitEmbeddingEndpoint(runtime);
528
- }
529
- function hashFeature(feature) {
530
- let hash = 2166136261;
531
- for (let i = 0;i < feature.length; i += 1) {
532
- hash ^= feature.charCodeAt(i);
533
- hash = Math.imul(hash, 16777619);
534
- }
535
- return hash >>> 0;
536
- }
537
- function createDeterministicEmbedding(text, dimension) {
538
- const vector = new Array(dimension).fill(0);
539
- const normalized = text.toLowerCase();
540
- const tokens = normalized.match(/[a-z0-9]+(?:[_-][a-z0-9]+)*/g) ?? [normalized];
541
- const addFeature = (feature, weight) => {
542
- const hash = hashFeature(feature);
543
- const idx = hash % dimension;
544
- const sign = (hash & 1) === 0 ? 1 : -1;
545
- vector[idx] += sign * weight;
546
- const secondHash = hashFeature(`b:${feature}`);
547
- const secondIdx = secondHash % dimension;
548
- const secondSign = (secondHash & 1) === 0 ? 1 : -1;
549
- vector[secondIdx] += secondSign * weight * 0.5;
550
- };
551
- tokens.forEach((token, index) => {
552
- addFeature(token, 1);
553
- if (index > 0) {
554
- addFeature(`${tokens[index - 1]} ${token}`, 0.35);
555
- }
556
- });
557
- addFeature(normalized.slice(0, 512), 0.15);
558
- const norm = Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
559
- if (norm === 0) {
560
- vector[0] = 1;
561
- return vector;
562
- }
563
- return vector.map((value) => value / norm);
564
- }
565
- async function handleTextEmbedding(runtime, params) {
566
- const embeddingModel = getEmbeddingModel(runtime);
567
- const embeddingDimension = validateDimension(getEmbeddingDimensions(runtime));
568
- const text = extractText(params);
569
- if (text === null) {
570
- logger5.debug("[OpenAI] Creating test embedding for initialization");
571
- const testVector = new Array(embeddingDimension).fill(0);
572
- testVector[0] = 0.1;
573
- return testVector;
574
- }
575
- let trimmedText = text.trim();
576
- if (trimmedText.length === 0) {
577
- throw new Error("Cannot generate embedding for empty text");
578
- }
579
- const maxChars = 8000 * 4;
580
- if (trimmedText.length > maxChars) {
581
- logger5.warn(`[OpenAI] Embedding input too long (~${Math.ceil(trimmedText.length / 4)} tokens), truncating to ~8000 tokens`);
582
- trimmedText = trimmedText.slice(0, maxChars);
583
- }
584
- if (shouldUseLocalEmbeddingFallback(runtime)) {
585
- logger5.debug("[OpenAI] Using deterministic local embedding fallback for Cerebras mode");
586
- return createDeterministicEmbedding(trimmedText, embeddingDimension);
587
- }
588
- const baseURL = getEmbeddingBaseURL(runtime);
589
- const url = `${baseURL}/embeddings`;
590
- logger5.debug(`[OpenAI] Generating embedding with model: ${embeddingModel}`);
591
- const response = await fetch(url, {
592
- method: "POST",
593
- headers: {
594
- ...getAuthHeader(runtime, true),
595
- "Content-Type": "application/json"
596
- },
597
- body: JSON.stringify({
598
- model: embeddingModel,
599
- input: trimmedText
600
- })
601
- });
602
- if (!response.ok) {
603
- const errorText = await response.text().catch(() => "Unknown error");
604
- throw new Error(`OpenAI embedding API error: ${response.status} ${response.statusText} - ${errorText}`);
605
- }
606
- const data = await response.json();
607
- const firstResult = data?.data?.[0];
608
- if (!firstResult?.embedding) {
609
- throw new Error("OpenAI API returned invalid embedding response structure");
610
- }
611
- const embedding = firstResult.embedding;
612
- if (embedding.length !== embeddingDimension) {
613
- throw new Error(`Embedding dimension mismatch: got ${embedding.length}, expected ${embeddingDimension}. ` + `Check OPENAI_EMBEDDING_DIMENSIONS setting.`);
614
- }
615
- if (data.usage) {
616
- emitModelUsageEvent(runtime, ModelType.TEXT_EMBEDDING, trimmedText, {
617
- promptTokens: data.usage.prompt_tokens,
618
- completionTokens: 0,
619
- totalTokens: data.usage.total_tokens
620
- });
621
- }
622
- logger5.debug(`[OpenAI] Generated embedding with ${embedding.length} dimensions`);
623
- return embedding;
624
- }
625
- // models/image.ts
626
- import { logger as logger6, ModelType as ModelType2, recordLlmCall as recordLlmCall2 } from "@elizaos/core";
627
- var DEFAULT_IMAGE_DESCRIPTION_PROMPT = "Please analyze this image and provide a title and detailed description.";
628
- async function handleImageGeneration(runtime, params) {
629
- const modelName = getImageModel(runtime);
630
- const count = params.count ?? 1;
631
- const size = params.size ?? "1024x1024";
632
- const extendedParams = params;
633
- logger6.debug(`[OpenAI] Using IMAGE model: ${modelName}`);
634
- if (params.prompt.trim().length === 0) {
635
- throw new Error("IMAGE generation requires a non-empty prompt");
636
- }
637
- if (count < 1 || count > 10) {
638
- throw new Error("IMAGE count must be between 1 and 10");
639
- }
640
- const baseURL = getBaseURL(runtime);
641
- const requestBody = {
642
- model: modelName,
643
- prompt: params.prompt,
644
- n: count,
645
- size
646
- };
647
- if (extendedParams.quality) {
648
- requestBody.quality = extendedParams.quality;
649
- }
650
- if (extendedParams.style) {
651
- requestBody.style = extendedParams.style;
652
- }
653
- const details = {
654
- model: modelName,
655
- systemPrompt: "",
656
- userPrompt: params.prompt,
657
- temperature: 0,
658
- maxTokens: 0,
659
- purpose: "external_llm",
660
- actionType: "openai.images.generate"
661
- };
662
- const data = await recordLlmCall2(runtime, details, async () => {
663
- const response = await fetch(`${baseURL}/images/generations`, {
664
- method: "POST",
665
- headers: {
666
- ...getAuthHeader(runtime),
667
- "Content-Type": "application/json"
668
- },
669
- body: JSON.stringify(requestBody)
670
- });
671
- if (!response.ok) {
672
- const errorText = await response.text().catch(() => "Unknown error");
673
- throw new Error(`OpenAI image generation failed: ${response.status} ${response.statusText} - ${errorText}`);
674
- }
675
- const responseData = await response.json();
676
- details.response = JSON.stringify(responseData.data);
677
- return responseData;
678
- });
679
- if (data.data.length === 0) {
680
- throw new Error("OpenAI API returned no images");
681
- }
682
- return data.data.map((item) => ({
683
- url: item.url,
684
- revisedPrompt: item.revised_prompt
685
- }));
686
- }
687
- function parseTitleFromResponse(content) {
688
- const titleMatch = content.match(/title[:\s]+(.+?)(?:\n|$)/i);
689
- return titleMatch?.[1]?.trim() ?? "Image Analysis";
690
- }
691
- function parseDescriptionFromResponse(content) {
692
- return content.replace(/title[:\s]+(.+?)(?:\n|$)/i, "").trim();
693
- }
694
- async function handleImageDescription(runtime, params) {
695
- const modelName = getImageDescriptionModel(runtime);
696
- const maxTokens = getImageDescriptionMaxTokens(runtime);
697
- logger6.debug(`[OpenAI] Using IMAGE_DESCRIPTION model: ${modelName}`);
698
- let imageUrl;
699
- let promptText;
700
- if (typeof params === "string") {
701
- imageUrl = params;
702
- promptText = DEFAULT_IMAGE_DESCRIPTION_PROMPT;
703
- } else {
704
- imageUrl = params.imageUrl;
705
- promptText = params.prompt ?? DEFAULT_IMAGE_DESCRIPTION_PROMPT;
706
- }
707
- if (!imageUrl || imageUrl.trim().length === 0) {
708
- throw new Error("IMAGE_DESCRIPTION requires a valid image URL");
709
- }
710
- const baseURL = getBaseURL(runtime);
711
- const requestBody = {
712
- model: modelName,
713
- messages: [
714
- {
715
- role: "user",
716
- content: [
717
- { type: "text", text: promptText },
718
- { type: "image_url", image_url: { url: imageUrl } }
719
- ]
720
- }
721
- ],
722
- max_tokens: maxTokens
723
- };
724
- const details = {
725
- model: modelName,
726
- systemPrompt: "",
727
- userPrompt: promptText,
728
- temperature: 0,
729
- maxTokens,
730
- purpose: "external_llm",
731
- actionType: "openai.chat.completions.create"
732
- };
733
- const data = await recordLlmCall2(runtime, details, async () => {
734
- const response = await fetch(`${baseURL}/chat/completions`, {
735
- method: "POST",
736
- headers: {
737
- ...getAuthHeader(runtime),
738
- "Content-Type": "application/json"
739
- },
740
- body: JSON.stringify(requestBody)
741
- });
742
- if (!response.ok) {
743
- const errorText = await response.text().catch(() => "Unknown error");
744
- throw new Error(`OpenAI image description failed: ${response.status} ${response.statusText} - ${errorText}`);
745
- }
746
- const responseData = await response.json();
747
- details.response = responseData.choices?.[0]?.message?.content ?? "";
748
- if (responseData.usage) {
749
- details.promptTokens = responseData.usage.prompt_tokens;
750
- details.completionTokens = responseData.usage.completion_tokens;
751
- }
752
- return responseData;
753
- });
754
- if (data.usage) {
755
- emitModelUsageEvent(runtime, ModelType2.IMAGE_DESCRIPTION, typeof params === "string" ? params : params.prompt ?? "", {
756
- promptTokens: data.usage.prompt_tokens,
757
- completionTokens: data.usage.completion_tokens,
758
- totalTokens: data.usage.total_tokens
759
- });
760
- }
761
- const firstChoice = data.choices?.[0];
762
- const content = firstChoice?.message?.content;
763
- if (!content) {
764
- throw new Error("OpenAI API returned empty image description");
765
- }
766
- return {
767
- title: parseTitleFromResponse(content),
768
- description: parseDescriptionFromResponse(content)
769
- };
770
- }
771
- // models/research.ts
772
- import { logger as logger7, recordLlmCall as recordLlmCall3 } from "@elizaos/core";
773
- function convertToolToApi(tool) {
774
- switch (tool.type) {
775
- case "web_search_preview":
776
- return { type: "web_search_preview" };
777
- case "file_search":
778
- return {
779
- type: "file_search",
780
- vector_store_ids: tool.vectorStoreIds
781
- };
782
- case "code_interpreter":
783
- return {
784
- type: "code_interpreter",
785
- container: tool.container ?? { type: "auto" }
786
- };
787
- case "mcp":
788
- return {
789
- type: "mcp",
790
- server_label: tool.serverLabel,
791
- server_url: tool.serverUrl,
792
- require_approval: tool.requireApproval ?? "never"
793
- };
794
- default:
795
- throw new Error(`Unknown research tool type: ${tool.type}`);
796
- }
797
- }
798
- function convertOutputItem(item) {
799
- switch (item.type) {
800
- case "web_search_call":
801
- return {
802
- id: item.id ?? "",
803
- type: "web_search_call",
804
- status: item.status ?? "completed",
805
- action: {
806
- type: item.action?.type ?? "search",
807
- query: item.action?.query,
808
- url: item.action?.url
809
- }
810
- };
811
- case "file_search_call":
812
- return {
813
- id: item.id ?? "",
814
- type: "file_search_call",
815
- status: item.status ?? "completed",
816
- query: item.query ?? "",
817
- results: item.results?.map((r) => ({
818
- fileId: r.file_id,
819
- fileName: r.file_name,
820
- score: r.score
821
- }))
822
- };
823
- case "code_interpreter_call":
824
- return {
825
- id: item.id ?? "",
826
- type: "code_interpreter_call",
827
- status: item.status ?? "completed",
828
- code: item.code ?? "",
829
- output: item.output
830
- };
831
- case "mcp_tool_call":
832
- return {
833
- id: item.id ?? "",
834
- type: "mcp_tool_call",
835
- status: item.status ?? "completed",
836
- serverLabel: item.server_label ?? "",
837
- toolName: item.tool_name ?? "",
838
- arguments: item.arguments ?? {},
839
- result: item.result
840
- };
841
- case "message":
842
- return {
843
- type: "message",
844
- content: item.content?.map((c) => ({
845
- type: "output_text",
846
- text: c.text,
847
- annotations: c.annotations?.map((a) => ({
848
- url: a.url,
849
- title: a.title,
850
- startIndex: a.start_index,
851
- endIndex: a.end_index
852
- })) ?? []
853
- })) ?? []
854
- };
855
- default:
856
- return null;
857
- }
858
- }
859
- function extractTextAndAnnotations(response) {
860
- if (response.output_text) {
861
- const annotations2 = [];
862
- if (response.output) {
863
- for (const item of response.output) {
864
- if (item.type === "message" && item.content) {
865
- for (const content of item.content) {
866
- if (content.annotations) {
867
- for (const ann of content.annotations) {
868
- annotations2.push({
869
- url: ann.url,
870
- title: ann.title,
871
- startIndex: ann.start_index,
872
- endIndex: ann.end_index
873
- });
874
- }
875
- }
876
- }
877
- }
878
- }
879
- }
880
- return { text: response.output_text, annotations: annotations2 };
881
- }
882
- let text = "";
883
- const annotations = [];
884
- if (response.output) {
885
- for (const item of response.output) {
886
- if (item.type === "message" && item.content) {
887
- for (const content of item.content) {
888
- text += content.text;
889
- if (content.annotations) {
890
- for (const ann of content.annotations) {
891
- annotations.push({
892
- url: ann.url,
893
- title: ann.title,
894
- startIndex: ann.start_index,
895
- endIndex: ann.end_index
896
- });
897
- }
898
- }
899
- }
900
- }
901
- }
902
- }
903
- return { text, annotations };
904
- }
905
- async function handleResearch(runtime, params) {
906
- const apiKey = getApiKey(runtime);
907
- if (!apiKey) {
908
- throw new Error("OPENAI_API_KEY is required for deep research. Set it in your environment variables or runtime settings.");
909
- }
910
- const baseURL = getBaseURL(runtime);
911
- const modelName = params.model ?? getResearchModel(runtime);
912
- const timeout = getResearchTimeout(runtime);
913
- logger7.debug(`[OpenAI] Starting deep research with model: ${modelName}`);
914
- logger7.debug(`[OpenAI] Research input: ${params.input.substring(0, 100)}...`);
915
- const dataSourceTools = params.tools?.filter((t) => t.type === "web_search_preview" || t.type === "file_search" || t.type === "mcp");
916
- if (!dataSourceTools || dataSourceTools.length === 0) {
917
- logger7.debug("[OpenAI] No data source tools specified, defaulting to web_search_preview");
918
- params.tools = [{ type: "web_search_preview" }, ...params.tools ?? []];
919
- }
920
- const requestBody = {
921
- model: modelName,
922
- input: params.input
923
- };
924
- if (params.instructions) {
925
- requestBody.instructions = params.instructions;
926
- }
927
- if (params.background !== undefined) {
928
- requestBody.background = params.background;
929
- }
930
- if (params.tools && params.tools.length > 0) {
931
- requestBody.tools = params.tools.map(convertToolToApi);
932
- }
933
- if (params.maxToolCalls !== undefined) {
934
- requestBody.max_tool_calls = params.maxToolCalls;
935
- }
936
- if (params.reasoningSummary) {
937
- requestBody.reasoning = { summary: params.reasoningSummary };
938
- }
939
- logger7.debug(`[OpenAI] Research request body: ${JSON.stringify(requestBody, null, 2)}`);
940
- const details = {
941
- model: modelName,
942
- systemPrompt: params.instructions ?? "",
943
- userPrompt: params.input,
944
- temperature: 0,
945
- maxTokens: 0,
946
- purpose: "external_llm",
947
- actionType: "openai.responses.create"
948
- };
949
- const data = await recordLlmCall3(runtime, details, async () => {
950
- const response = await fetch(`${baseURL}/responses`, {
951
- method: "POST",
952
- headers: {
953
- Authorization: `Bearer ${apiKey}`,
954
- "Content-Type": "application/json"
955
- },
956
- body: JSON.stringify(requestBody),
957
- signal: AbortSignal.timeout(timeout)
958
- });
959
- if (!response.ok) {
960
- const errorText = await response.text();
961
- logger7.error(`[OpenAI] Research request failed: ${response.status} ${errorText}`);
962
- throw new Error(`Deep research request failed: ${response.status} ${response.statusText}`);
963
- }
964
- const responseData = await response.json();
965
- details.response = responseData.output_text ?? "";
966
- return responseData;
967
- });
968
- if (data.error) {
969
- logger7.error(`[OpenAI] Research API error: ${data.error.message}`);
970
- throw new Error(`Deep research error: ${data.error.message}`);
971
- }
972
- logger7.debug(`[OpenAI] Research response received. Status: ${data.status ?? "completed"}`);
973
- const { text, annotations } = extractTextAndAnnotations(data);
974
- const outputItems = [];
975
- if (data.output) {
976
- for (const item of data.output) {
977
- const converted = convertOutputItem(item);
978
- if (converted) {
979
- outputItems.push(converted);
980
- }
981
- }
982
- }
983
- const result = {
984
- id: data.id,
985
- text,
986
- annotations,
987
- outputItems,
988
- status: data.status
989
- };
990
- logger7.info(`[OpenAI] Research completed. Text length: ${text.length}, Annotations: ${annotations.length}, Output items: ${outputItems.length}`);
991
- return result;
992
- }
993
- // models/text.ts
994
- import {
995
- buildCanonicalSystemPrompt,
996
- dropDuplicateLeadingSystemMessage,
997
- logger as logger8,
998
- ModelType as ModelType3,
999
- normalizeSchemaForCerebras,
1000
- recordLlmCall as recordLlmCall4,
1001
- resolveEffectiveSystemPrompt,
1002
- sanitizeFunctionNameForCerebras
1003
- } from "@elizaos/core";
1004
- import {
1005
- generateText,
1006
- jsonSchema,
1007
- Output,
1008
- streamText
1009
- } from "ai";
1010
-
1011
- // providers/openai.ts
1012
- import { createOpenAI } from "@ai-sdk/openai";
1013
- var PROXY_API_KEY = "sk-proxy";
1014
- function createOpenAIClient(runtime) {
1015
- const baseURL = getBaseURL(runtime);
1016
- const apiKey = getApiKey(runtime);
1017
- if (!apiKey && isProxyMode(runtime)) {
1018
- return createOpenAI({
1019
- apiKey: PROXY_API_KEY,
1020
- baseURL
1021
- });
1022
- }
1023
- if (!apiKey) {
1024
- throw new Error("OPENAI_API_KEY is required. Set it in your environment variables or runtime settings.");
1025
- }
1026
- return createOpenAI({
1027
- apiKey,
1028
- baseURL
1029
- });
1030
- }
1031
- // models/text.ts
1032
- var TEXT_NANO_MODEL_TYPE = ModelType3.TEXT_NANO ?? "TEXT_NANO";
1033
- var TEXT_MEDIUM_MODEL_TYPE = ModelType3.TEXT_MEDIUM ?? "TEXT_MEDIUM";
1034
- var TEXT_MEGA_MODEL_TYPE = ModelType3.TEXT_MEGA ?? "TEXT_MEGA";
1035
- var RESPONSE_HANDLER_MODEL_TYPE = ModelType3.RESPONSE_HANDLER ?? "RESPONSE_HANDLER";
1036
- var ACTION_PLANNER_MODEL_TYPE = ModelType3.ACTION_PLANNER ?? "ACTION_PLANNER";
1037
- function buildUserContent(params) {
1038
- const content = [{ type: "text", text: params.prompt }];
1039
- for (const attachment of params.attachments ?? []) {
1040
- content.push({
1041
- type: "file",
1042
- data: attachment.data,
1043
- mediaType: attachment.mediaType,
1044
- ...attachment.filename ? { filename: attachment.filename } : {}
1045
- });
1046
- }
1047
- return content;
1048
- }
1049
- function convertUsage(usage) {
1050
- if (!usage) {
1051
- return;
1052
- }
1053
- const promptTokens = usage.inputTokens ?? 0;
1054
- const completionTokens = usage.outputTokens ?? 0;
1055
- const usageWithCache = usage;
1056
- const cachedInput = firstNumber(usageWithCache.cacheReadInputTokens, usageWithCache.cachedInputTokens, usageWithCache.inputTokenDetails?.cacheReadTokens, usageWithCache.inputTokenDetails?.cachedInputTokens, usageWithCache.input_tokens_details?.cache_read_input_tokens, usageWithCache.input_tokens_details?.cached_tokens, usageWithCache.prompt_tokens_details?.cached_tokens) ?? undefined;
1057
- const cacheCreationInput = firstNumber(usageWithCache.cacheCreationInputTokens, usageWithCache.cacheWriteInputTokens, usageWithCache.inputTokenDetails?.cacheCreationInputTokens, usageWithCache.inputTokenDetails?.cacheCreationTokens, usageWithCache.inputTokenDetails?.cacheWriteTokens, usageWithCache.input_tokens_details?.cache_creation_input_tokens);
1058
- return {
1059
- promptTokens,
1060
- completionTokens,
1061
- totalTokens: promptTokens + completionTokens,
1062
- cachedPromptTokens: cachedInput,
1063
- cacheReadInputTokens: cachedInput,
1064
- cacheCreationInputTokens: cacheCreationInput
1065
- };
1066
- }
1067
- function firstNumber(...values) {
1068
- for (const value of values) {
1069
- if (typeof value === "number" && Number.isFinite(value)) {
1070
- return value;
1071
- }
1072
- if (typeof value === "string" && value.trim().length > 0) {
1073
- const parsed = Number(value);
1074
- if (Number.isFinite(parsed)) {
1075
- return parsed;
1076
- }
1077
- }
1078
- }
1079
- return;
1080
- }
1081
- function resolvePromptCacheOptions(params) {
1082
- const withOpenAIOptions = params;
1083
- return {
1084
- promptCacheKey: withOpenAIOptions.providerOptions?.openai?.promptCacheKey,
1085
- promptCacheRetention: withOpenAIOptions.providerOptions?.openai?.promptCacheRetention
1086
- };
1087
- }
1088
- function resolveProviderOptions(params, runtime) {
1089
- const withOpenAIOptions = params;
1090
- const rawProviderOptions = withOpenAIOptions.providerOptions;
1091
- const promptCacheOptions = resolvePromptCacheOptions(params);
1092
- if (!rawProviderOptions && !promptCacheOptions.promptCacheKey && !promptCacheOptions.promptCacheRetention) {
1093
- return;
1094
- }
1095
- const skipCacheRetention = isCerebrasMode(runtime);
1096
- const { agentName: _agentName, openai: rawOpenAIOptions, ...rest } = rawProviderOptions ?? {};
1097
- const sanitizedRawOpenAIOptions = (() => {
1098
- if (!rawOpenAIOptions || typeof rawOpenAIOptions !== "object")
1099
- return rawOpenAIOptions;
1100
- if (!skipCacheRetention)
1101
- return rawOpenAIOptions;
1102
- const { promptCacheRetention: _drop, ...rest2 } = rawOpenAIOptions;
1103
- return rest2;
1104
- })();
1105
- const openaiOptions = {
1106
- ...sanitizedRawOpenAIOptions ?? {},
1107
- ...promptCacheOptions.promptCacheKey ? { promptCacheKey: promptCacheOptions.promptCacheKey } : {},
1108
- ...!skipCacheRetention && promptCacheOptions.promptCacheRetention ? { promptCacheRetention: promptCacheOptions.promptCacheRetention } : {}
1109
- };
1110
- const providerOptions = {
1111
- ...rest,
1112
- ...Object.keys(openaiOptions).length > 0 ? { openai: openaiOptions } : {}
1113
- };
1114
- return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
1115
- }
1116
- function buildStructuredOutput(responseSchema) {
1117
- if (responseSchema && typeof responseSchema === "object" && "responseFormat" in responseSchema && "parseCompleteOutput" in responseSchema) {
1118
- return responseSchema;
1119
- }
1120
- const schemaOptions = responseSchema && typeof responseSchema === "object" && "schema" in responseSchema ? responseSchema : { schema: responseSchema };
1121
- return Output.object({
1122
- schema: jsonSchema(sanitizeJsonSchema(schemaOptions.schema, true)),
1123
- ...schemaOptions.name ? { name: schemaOptions.name } : {},
1124
- ...schemaOptions.description ? { description: schemaOptions.description } : {}
1125
- });
1126
- }
1127
- function normalizeNativeTools(tools, options = {}) {
1128
- if (!tools) {
1129
- return;
1130
- }
1131
- if (!Array.isArray(tools)) {
1132
- return tools;
1133
- }
1134
- const toolSet = {};
1135
- for (const rawTool of tools) {
1136
- const tool = asRecord(rawTool);
1137
- const functionTool = asRecord(tool.function);
1138
- const name = firstString(tool.name, functionTool.name);
1139
- if (!name) {
1140
- throw new Error("[OpenAI] Native tool definition is missing a name.");
1141
- }
1142
- const description = firstString(tool.description, functionTool.description);
1143
- const rawSchema = tool.parameters ?? functionTool.parameters ?? { type: "object" };
1144
- let inputSchema = sanitizeJsonSchema(rawSchema, true);
1145
- if (options.cerebrasMode) {
1146
- inputSchema = normalizeSchemaForCerebras(inputSchema);
1147
- }
1148
- const registeredName = options.cerebrasMode ? sanitizeFunctionNameForCerebras(name) : name;
1149
- toolSet[registeredName] = {
1150
- ...description ? { description } : {},
1151
- inputSchema: jsonSchema(inputSchema)
1152
- };
1153
- }
1154
- return Object.keys(toolSet).length > 0 ? toolSet : undefined;
1155
- }
1156
- function normalizeNativeMessages(messages) {
1157
- if (!Array.isArray(messages)) {
1158
- return;
1159
- }
1160
- return messages.map((message) => normalizeNativeMessage(message));
1161
- }
1162
- function normalizeNativeMessage(message) {
1163
- const raw = asRecord(message);
1164
- const providerOptions = asOptionalRecord(raw.providerOptions);
1165
- if (raw.role === "system") {
1166
- return {
1167
- role: "system",
1168
- content: stringifyMessageContent(raw.content),
1169
- ...providerOptions ? { providerOptions } : {}
1170
- };
1171
- }
1172
- if (raw.role === "assistant") {
1173
- return {
1174
- role: "assistant",
1175
- content: normalizeAssistantContent(raw),
1176
- ...providerOptions ? { providerOptions } : {}
1177
- };
1178
- }
1179
- if (raw.role === "tool") {
1180
- return {
1181
- role: "tool",
1182
- content: normalizeToolContent(raw),
1183
- ...providerOptions ? { providerOptions } : {}
1184
- };
1185
- }
1186
- return {
1187
- role: "user",
1188
- content: normalizeUserContent(raw.content),
1189
- ...providerOptions ? { providerOptions } : {}
1190
- };
1191
- }
1192
- function normalizeAssistantContent(message) {
1193
- const toolCalls = Array.isArray(message.toolCalls) ? message.toolCalls : [];
1194
- if (toolCalls.length === 0) {
1195
- if (Array.isArray(message.content) || typeof message.content === "string") {
1196
- return message.content;
1197
- }
1198
- return "";
1199
- }
1200
- const parts = [];
1201
- if (typeof message.content === "string" && message.content.length > 0) {
1202
- parts.push({ type: "text", text: message.content });
1203
- } else if (Array.isArray(message.content)) {
1204
- parts.push(...message.content);
1205
- }
1206
- for (const toolCall of toolCalls) {
1207
- const rawCall = asRecord(toolCall);
1208
- const rawFunction = asRecord(rawCall.function);
1209
- const toolCallId = firstString(rawCall.toolCallId, rawCall.id);
1210
- const toolName = firstString(rawCall.toolName, rawCall.name, rawFunction.name);
1211
- if (!toolCallId || !toolName) {
1212
- continue;
1213
- }
1214
- parts.push({
1215
- type: "tool-call",
1216
- toolCallId,
1217
- toolName,
1218
- input: parseToolCallInput(rawCall, rawFunction)
1219
- });
1220
- }
1221
- return parts;
1222
- }
1223
- function normalizeToolContent(message) {
1224
- if (Array.isArray(message.content)) {
1225
- return message.content;
1226
- }
1227
- const toolCallId = firstString(message.toolCallId, message.id) ?? "tool-call";
1228
- const toolName = firstString(message.toolName, message.name) ?? "tool";
1229
- const parsed = parseJsonIfPossible(message.content);
1230
- return [
1231
- {
1232
- type: "tool-result",
1233
- toolCallId,
1234
- toolName,
1235
- output: typeof parsed === "string" ? { type: "text", value: parsed } : { type: "json", value: parsed }
1236
- }
1237
- ];
1238
- }
1239
- function normalizeUserContent(content) {
1240
- if (Array.isArray(content)) {
1241
- return content;
1242
- }
1243
- return stringifyMessageContent(content);
1244
- }
1245
- function stringifyMessageContent(content) {
1246
- if (typeof content === "string") {
1247
- return content;
1248
- }
1249
- if (content == null) {
1250
- return "";
1251
- }
1252
- return typeof content === "object" ? JSON.stringify(content) : String(content);
1253
- }
1254
- function parseToolCallInput(rawCall, rawFunction) {
1255
- if ("input" in rawCall) {
1256
- return rawCall.input;
1257
- }
1258
- return parseJsonIfPossible(rawCall.arguments ?? rawFunction.arguments ?? {});
1259
- }
1260
- function parseJsonIfPossible(value) {
1261
- if (typeof value !== "string") {
1262
- return value ?? "";
1263
- }
1264
- try {
1265
- return JSON.parse(value);
1266
- } catch {
1267
- return value;
1268
- }
1269
- }
1270
- function normalizeToolChoice(toolChoice) {
1271
- if (!toolChoice) {
1272
- return;
1273
- }
1274
- if (typeof toolChoice === "string" && (toolChoice === "auto" || toolChoice === "none" || toolChoice === "required")) {
1275
- return toolChoice;
1276
- }
1277
- const choice = asRecord(toolChoice);
1278
- if (choice.type === "tool") {
1279
- if (typeof choice.toolName === "string" && choice.toolName.length > 0) {
1280
- return toolChoice;
1281
- }
1282
- const toolName = firstString(choice.toolName, choice.name);
1283
- if (toolName) {
1284
- return { type: "tool", toolName };
1285
- }
1286
- }
1287
- if (choice.type === "function") {
1288
- const fn = asRecord(choice.function);
1289
- const toolName = firstString(fn.name);
1290
- if (toolName) {
1291
- return { type: "tool", toolName };
1292
- }
1293
- }
1294
- const namedTool = firstString(choice.name);
1295
- if (namedTool) {
1296
- return { type: "tool", toolName: namedTool };
1297
- }
1298
- return toolChoice;
1299
- }
1300
- function sanitizeJsonSchema(schema, isRoot = false) {
1301
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
1302
- return { type: "object" };
1303
- }
1304
- const record = schema;
1305
- const sanitized = { ...record };
1306
- if (typeof sanitized.type !== "string") {
1307
- const inferredType = inferJsonSchemaType(sanitized, isRoot);
1308
- if (inferredType) {
1309
- sanitized.type = inferredType;
1310
- }
1311
- }
1312
- if (sanitized.properties && typeof sanitized.properties === "object" && !Array.isArray(sanitized.properties)) {
1313
- const properties = {};
1314
- for (const [key, value] of Object.entries(sanitized.properties)) {
1315
- properties[key] = sanitizeJsonSchema(value);
1316
- }
1317
- sanitized.properties = properties;
1318
- const propertyKeys = Object.keys(properties);
1319
- const existingRequired = Array.isArray(sanitized.required) ? sanitized.required.filter((key) => typeof key === "string") : [];
1320
- sanitized.required = [...new Set([...existingRequired, ...propertyKeys])];
1321
- }
1322
- if (sanitized.type === "object" && sanitized.additionalProperties !== false) {
1323
- sanitized.additionalProperties = false;
1324
- }
1325
- if (sanitized.items) {
1326
- sanitized.items = Array.isArray(sanitized.items) ? sanitized.items.map((item) => sanitizeJsonSchema(item)) : sanitizeJsonSchema(sanitized.items);
1327
- }
1328
- for (const unionKey of ["anyOf", "oneOf", "allOf"]) {
1329
- const value = sanitized[unionKey];
1330
- if (Array.isArray(value)) {
1331
- sanitized[unionKey] = value.map((item) => sanitizeJsonSchema(item));
1332
- }
1333
- }
1334
- return sanitized;
1335
- }
1336
- function inferJsonSchemaType(schema, isRoot) {
1337
- if ("properties" in schema || "required" in schema || "additionalProperties" in schema || isRoot) {
1338
- return "object";
1339
- }
1340
- if ("items" in schema) {
1341
- return "array";
1342
- }
1343
- if (Array.isArray(schema.enum) && schema.enum.length > 0) {
1344
- const types = new Set(schema.enum.map((value) => typeof value));
1345
- if (types.size === 1) {
1346
- const [type] = [...types];
1347
- if (type === "string" || type === "number" || type === "boolean") {
1348
- return type;
1349
- }
1350
- }
1351
- }
1352
- return;
1353
- }
1354
- function asRecord(value) {
1355
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1356
- }
1357
- function asOptionalRecord(value) {
1358
- return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
1359
- }
1360
- function firstString(...values) {
1361
- for (const value of values) {
1362
- if (typeof value === "string" && value.length > 0) {
1363
- return value;
1364
- }
1365
- }
1366
- return;
1367
- }
1368
- function usesNativeTextResult(params) {
1369
- return Boolean(params.messages || params.tools || params.toolChoice || params.responseSchema);
1370
- }
1371
- function buildNativeTextResult(result, modelName) {
1372
- return {
1373
- text: result.text,
1374
- toolCalls: result.toolCalls ?? [],
1375
- finishReason: result.finishReason,
1376
- usage: convertUsage(result.usage),
1377
- providerMetadata: mergeProviderModelName(result.providerMetadata, modelName)
1378
- };
1379
- }
1380
- function mergeProviderModelName(providerMetadata, modelName) {
1381
- if (!modelName) {
1382
- return providerMetadata;
1383
- }
1384
- if (providerMetadata && typeof providerMetadata === "object" && !Array.isArray(providerMetadata)) {
1385
- return {
1386
- ...providerMetadata,
1387
- modelName
1388
- };
1389
- }
1390
- return { modelName };
1391
- }
1392
- function createLlmCallDetails(modelName, params, systemPrompt, actionType, modelType, providerOptions, generateParams) {
1393
- const originalParams = params;
1394
- const nativeParams = generateParams;
1395
- const nativePrompt = nativeParams && "prompt" in nativeParams ? nativeParams.prompt : undefined;
1396
- const nativeMessages = nativeParams && "messages" in nativeParams && Array.isArray(nativeParams.messages) ? nativeParams.messages : undefined;
1397
- const nativeSystem = typeof nativeParams?.system === "string" ? nativeParams.system : systemPrompt;
1398
- return {
1399
- model: modelName,
1400
- modelType,
1401
- provider: "vercel-ai-sdk",
1402
- systemPrompt: nativeSystem ?? "",
1403
- userPrompt: typeof nativePrompt === "string" ? nativePrompt : typeof params.prompt === "string" ? params.prompt : "",
1404
- prompt: typeof nativePrompt === "string" ? nativePrompt : undefined,
1405
- messages: nativeMessages,
1406
- tools: nativeParams?.tools ?? originalParams.tools,
1407
- toolChoice: nativeParams?.toolChoice ?? originalParams.toolChoice,
1408
- output: nativeParams?.output !== undefined ? buildTrajectoryOutputDescriptor(originalParams.responseSchema, nativeParams.output) : undefined,
1409
- responseSchema: originalParams.responseSchema,
1410
- providerOptions: providerOptions ?? nativeParams?.providerOptions ?? originalParams.providerOptions,
1411
- temperature: params.temperature ?? 0,
1412
- maxTokens: typeof nativeParams?.maxOutputTokens === "number" ? nativeParams.maxOutputTokens : params.maxTokens ?? 8192,
1413
- purpose: "external_llm",
1414
- actionType
1415
- };
1416
- }
1417
- function buildTrajectoryOutputDescriptor(responseSchema, output) {
1418
- if (responseSchema !== undefined) {
1419
- return {
1420
- type: "object",
1421
- schema: responseSchema
1422
- };
1423
- }
1424
- return toTrajectoryJsonSafe(output);
1425
- }
1426
- function toTrajectoryJsonSafe(value) {
1427
- try {
1428
- return JSON.parse(JSON.stringify(value, (_key, nested) => {
1429
- if (typeof nested === "function")
1430
- return;
1431
- if (typeof nested === "bigint")
1432
- return nested.toString();
1433
- return nested;
1434
- }));
1435
- } catch {
1436
- return String(value);
1437
- }
1438
- }
1439
- function applyUsageToDetails(details, usage) {
1440
- if (!usage) {
1441
- return;
1442
- }
1443
- details.promptTokens = usage.inputTokens ?? 0;
1444
- details.completionTokens = usage.outputTokens ?? 0;
1445
- }
1446
- async function generateTextByModelType(runtime, params, modelType, getModelFn) {
1447
- const paramsWithAttachments = params;
1448
- const openai = createOpenAIClient(runtime);
1449
- const modelName = getModelFn(runtime);
1450
- logger8.debug(`[OpenAI] Using ${modelType} model: ${modelName}`);
1451
- const providerOptions = resolveProviderOptions(params, runtime);
1452
- const hasAttachments = (paramsWithAttachments.attachments?.length ?? 0) > 0;
1453
- const userContent = hasAttachments ? buildUserContent(paramsWithAttachments) : undefined;
1454
- const shouldReturnNativeResult = usesNativeTextResult(paramsWithAttachments);
1455
- const systemPrompt = resolveEffectiveSystemPrompt({
1456
- params: paramsWithAttachments,
1457
- fallback: buildCanonicalSystemPrompt({ character: runtime.character })
1458
- });
1459
- const agentName = paramsWithAttachments.providerOptions?.agentName;
1460
- const telemetryConfig = {
1461
- isEnabled: getExperimentalTelemetry(runtime),
1462
- functionId: agentName ? `agent:${agentName}` : undefined,
1463
- metadata: agentName ? { agentName } : undefined
1464
- };
1465
- const model = openai.chat(modelName);
1466
- const cerebrasMode = isCerebrasMode(runtime);
1467
- const normalizedTools = normalizeNativeTools(paramsWithAttachments.tools, {
1468
- cerebrasMode
1469
- });
1470
- const normalizedToolChoice = normalizeToolChoice(paramsWithAttachments.toolChoice);
1471
- const normalizedMessages = normalizeNativeMessages(paramsWithAttachments.messages);
1472
- const wireMessages = dropDuplicateLeadingSystemMessage(normalizedMessages, systemPrompt);
1473
- const effectiveMessages = wireMessages && wireMessages.length > 0 ? wireMessages : normalizedMessages;
1474
- const promptText = typeof params.prompt === "string" && params.prompt.length > 0 ? params.prompt : "";
1475
- const promptOrMessages = effectiveMessages && effectiveMessages.length > 0 ? { messages: effectiveMessages } : userContent ? { messages: [{ role: "user", content: userContent }] } : { prompt: promptText };
1476
- const generateParams = {
1477
- model,
1478
- ...promptOrMessages,
1479
- system: systemPrompt,
1480
- allowSystemInMessages: true,
1481
- maxOutputTokens: params.maxTokens ?? 8192,
1482
- experimental_telemetry: telemetryConfig,
1483
- ...normalizedTools ? { tools: normalizedTools } : {},
1484
- ...normalizedToolChoice ? { toolChoice: normalizedToolChoice } : {},
1485
- ...paramsWithAttachments.responseSchema && !isCerebrasMode(runtime) ? { output: buildStructuredOutput(paramsWithAttachments.responseSchema) } : {},
1486
- ...providerOptions ? { providerOptions } : {}
1487
- };
1488
- if (params.stream) {
1489
- const details2 = createLlmCallDetails(modelName, params, systemPrompt, "ai.streamText", modelType, providerOptions, generateParams);
1490
- details2.response = "";
1491
- const result2 = await recordLlmCall4(runtime, details2, () => streamText(generateParams));
1492
- return {
1493
- textStream: result2.textStream,
1494
- text: Promise.resolve(result2.text),
1495
- ...shouldReturnNativeResult ? { toolCalls: Promise.resolve(result2.toolCalls) } : {},
1496
- usage: Promise.resolve(result2.usage).then(convertUsage),
1497
- finishReason: Promise.resolve(result2.finishReason).then((r) => r)
1498
- };
1499
- }
1500
- const details = createLlmCallDetails(modelName, params, systemPrompt, "ai.generateText", modelType, providerOptions, generateParams);
1501
- const result = await recordLlmCall4(runtime, details, async () => {
1502
- const result2 = await generateText(generateParams);
1503
- details.response = result2.text;
1504
- details.toolCalls = result2.toolCalls ?? [];
1505
- details.finishReason = result2.finishReason;
1506
- details.providerMetadata = result2.providerMetadata;
1507
- applyUsageToDetails(details, result2.usage);
1508
- return result2;
1509
- });
1510
- if (result.usage) {
1511
- emitModelUsageEvent(runtime, modelType, params.prompt ?? "", result.usage);
1512
- }
1513
- if (shouldReturnNativeResult) {
1514
- return buildNativeTextResult(result, modelName);
1515
- }
1516
- return result.text;
1517
- }
1518
- async function handleTextSmall(runtime, params) {
1519
- return generateTextByModelType(runtime, params, ModelType3.TEXT_SMALL, getSmallModel);
1520
- }
1521
- async function handleTextNano(runtime, params) {
1522
- return generateTextByModelType(runtime, params, TEXT_NANO_MODEL_TYPE, getNanoModel);
1523
- }
1524
- async function handleTextMedium(runtime, params) {
1525
- return generateTextByModelType(runtime, params, TEXT_MEDIUM_MODEL_TYPE, getMediumModel);
1526
- }
1527
- async function handleTextLarge(runtime, params) {
1528
- return generateTextByModelType(runtime, params, ModelType3.TEXT_LARGE, getLargeModel);
1529
- }
1530
- async function handleTextMega(runtime, params) {
1531
- return generateTextByModelType(runtime, params, TEXT_MEGA_MODEL_TYPE, getMegaModel);
1532
- }
1533
- async function handleResponseHandler(runtime, params) {
1534
- return generateTextByModelType(runtime, params, RESPONSE_HANDLER_MODEL_TYPE, getResponseHandlerModel);
1535
- }
1536
- async function handleActionPlanner(runtime, params) {
1537
- return generateTextByModelType(runtime, params, ACTION_PLANNER_MODEL_TYPE, getActionPlannerModel);
1538
- }
1539
- // models/tokenizer.ts
1540
- import { ModelType as ModelType5 } from "@elizaos/core";
1541
-
1542
- // utils/tokenization.ts
1543
- import { ModelType as ModelType4 } from "@elizaos/core";
1544
- import {
1545
- encodingForModel,
1546
- getEncoding
1547
- } from "js-tiktoken";
1548
- function resolveTokenizerEncoding(modelName) {
1549
- const normalized = modelName.toLowerCase();
1550
- const fallbackEncoding = normalized.includes("4o") ? "o200k_base" : "cl100k_base";
1551
- try {
1552
- return encodingForModel(modelName);
1553
- } catch {
1554
- return getEncoding(fallbackEncoding);
1555
- }
1556
- }
1557
- function getModelName(runtime, modelType) {
1558
- if (modelType === ModelType4.TEXT_SMALL) {
1559
- return getSmallModel(runtime);
1560
- }
1561
- return getLargeModel(runtime);
1562
- }
1563
- function tokenizeText(runtime, modelType, text) {
1564
- const modelName = getModelName(runtime, modelType);
1565
- const encoder = resolveTokenizerEncoding(modelName);
1566
- return encoder.encode(text);
1567
- }
1568
- function detokenizeText(runtime, modelType, tokens) {
1569
- const modelName = getModelName(runtime, modelType);
1570
- const encoder = resolveTokenizerEncoding(modelName);
1571
- return encoder.decode(tokens);
1572
- }
1573
-
1574
- // models/tokenizer.ts
1575
- async function handleTokenizerEncode(runtime, params) {
1576
- if (!params.prompt) {
1577
- throw new Error("Tokenization requires a non-empty prompt");
1578
- }
1579
- const modelType = params.modelType ?? ModelType5.TEXT_LARGE;
1580
- return tokenizeText(runtime, modelType, params.prompt);
1581
- }
1582
- async function handleTokenizerDecode(runtime, params) {
1583
- if (!params.tokens || !Array.isArray(params.tokens)) {
1584
- throw new Error("Detokenization requires a valid tokens array");
1585
- }
1586
- if (params.tokens.length === 0) {
1587
- return "";
1588
- }
1589
- for (let i = 0;i < params.tokens.length; i++) {
1590
- const token = params.tokens[i];
1591
- if (typeof token !== "number" || !Number.isFinite(token)) {
1592
- throw new Error(`Invalid token at index ${i}: expected number`);
1593
- }
1594
- }
1595
- const modelType = params.modelType ?? ModelType5.TEXT_LARGE;
1596
- return detokenizeText(runtime, modelType, params.tokens);
1597
- }
1598
- // index.ts
1599
- function getProcessEnv() {
1600
- if (typeof process === "undefined") {
1601
- return {};
1602
- }
1603
- return process.env;
1604
- }
1605
- var env = getProcessEnv();
1606
- var TEXT_NANO_MODEL_TYPE2 = ModelType6.TEXT_NANO ?? "TEXT_NANO";
1607
- var TEXT_MEDIUM_MODEL_TYPE2 = ModelType6.TEXT_MEDIUM ?? "TEXT_MEDIUM";
1608
- var TEXT_MEGA_MODEL_TYPE2 = ModelType6.TEXT_MEGA ?? "TEXT_MEGA";
1609
- var RESPONSE_HANDLER_MODEL_TYPE2 = ModelType6.RESPONSE_HANDLER ?? "RESPONSE_HANDLER";
1610
- var ACTION_PLANNER_MODEL_TYPE2 = ModelType6.ACTION_PLANNER ?? "ACTION_PLANNER";
1611
- var openaiPlugin = {
1612
- name: "openai",
1613
- description: "OpenAI API integration for text, image, audio, and embedding models",
1614
- autoEnable: {
1615
- envKeys: ["OPENAI_API_KEY"]
1616
- },
1617
- config: {
1618
- OPENAI_API_KEY: env.OPENAI_API_KEY ?? null,
1619
- OPENAI_BASE_URL: env.OPENAI_BASE_URL ?? null,
1620
- OPENAI_NANO_MODEL: env.OPENAI_NANO_MODEL ?? null,
1621
- OPENAI_MEDIUM_MODEL: env.OPENAI_MEDIUM_MODEL ?? null,
1622
- OPENAI_SMALL_MODEL: env.OPENAI_SMALL_MODEL ?? null,
1623
- OPENAI_LARGE_MODEL: env.OPENAI_LARGE_MODEL ?? null,
1624
- OPENAI_MEGA_MODEL: env.OPENAI_MEGA_MODEL ?? null,
1625
- OPENAI_RESPONSE_HANDLER_MODEL: env.OPENAI_RESPONSE_HANDLER_MODEL ?? null,
1626
- OPENAI_SHOULD_RESPOND_MODEL: env.OPENAI_SHOULD_RESPOND_MODEL ?? null,
1627
- OPENAI_ACTION_PLANNER_MODEL: env.OPENAI_ACTION_PLANNER_MODEL ?? null,
1628
- OPENAI_PLANNER_MODEL: env.OPENAI_PLANNER_MODEL ?? null,
1629
- NANO_MODEL: env.NANO_MODEL ?? null,
1630
- MEDIUM_MODEL: env.MEDIUM_MODEL ?? null,
1631
- SMALL_MODEL: env.SMALL_MODEL ?? null,
1632
- LARGE_MODEL: env.LARGE_MODEL ?? null,
1633
- MEGA_MODEL: env.MEGA_MODEL ?? null,
1634
- RESPONSE_HANDLER_MODEL: env.RESPONSE_HANDLER_MODEL ?? null,
1635
- SHOULD_RESPOND_MODEL: env.SHOULD_RESPOND_MODEL ?? null,
1636
- ACTION_PLANNER_MODEL: env.ACTION_PLANNER_MODEL ?? null,
1637
- PLANNER_MODEL: env.PLANNER_MODEL ?? null,
1638
- OPENAI_EMBEDDING_MODEL: env.OPENAI_EMBEDDING_MODEL ?? null,
1639
- OPENAI_EMBEDDING_API_KEY: env.OPENAI_EMBEDDING_API_KEY ?? null,
1640
- OPENAI_EMBEDDING_URL: env.OPENAI_EMBEDDING_URL ?? null,
1641
- OPENAI_EMBEDDING_DIMENSIONS: env.OPENAI_EMBEDDING_DIMENSIONS ?? null,
1642
- OPENAI_IMAGE_DESCRIPTION_MODEL: env.OPENAI_IMAGE_DESCRIPTION_MODEL ?? null,
1643
- OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS: env.OPENAI_IMAGE_DESCRIPTION_MAX_TOKENS ?? null,
1644
- OPENAI_EXPERIMENTAL_TELEMETRY: env.OPENAI_EXPERIMENTAL_TELEMETRY ?? null,
1645
- OPENAI_RESEARCH_MODEL: env.OPENAI_RESEARCH_MODEL ?? null,
1646
- OPENAI_RESEARCH_TIMEOUT: env.OPENAI_RESEARCH_TIMEOUT ?? null
1647
- },
1648
- async init(config, runtime) {
1649
- initializeOpenAI(config, runtime);
1650
- },
1651
- models: {
1652
- [ModelType6.TEXT_EMBEDDING]: async (runtime, params) => {
1653
- return handleTextEmbedding(runtime, params);
1654
- },
1655
- [ModelType6.TEXT_TOKENIZER_ENCODE]: async (runtime, params) => {
1656
- return handleTokenizerEncode(runtime, params);
1657
- },
1658
- [ModelType6.TEXT_TOKENIZER_DECODE]: async (runtime, params) => {
1659
- return handleTokenizerDecode(runtime, params);
1660
- },
1661
- [ModelType6.TEXT_SMALL]: async (runtime, params) => {
1662
- return handleTextSmall(runtime, params);
1663
- },
1664
- [TEXT_NANO_MODEL_TYPE2]: async (runtime, params) => {
1665
- return handleTextNano(runtime, params);
1666
- },
1667
- [TEXT_MEDIUM_MODEL_TYPE2]: async (runtime, params) => {
1668
- return handleTextMedium(runtime, params);
1669
- },
1670
- [ModelType6.TEXT_LARGE]: async (runtime, params) => {
1671
- return handleTextLarge(runtime, params);
1672
- },
1673
- [TEXT_MEGA_MODEL_TYPE2]: async (runtime, params) => {
1674
- return handleTextMega(runtime, params);
1675
- },
1676
- [RESPONSE_HANDLER_MODEL_TYPE2]: async (runtime, params) => {
1677
- return handleResponseHandler(runtime, params);
1678
- },
1679
- [ACTION_PLANNER_MODEL_TYPE2]: async (runtime, params) => {
1680
- return handleActionPlanner(runtime, params);
1681
- },
1682
- [ModelType6.IMAGE]: async (runtime, params) => {
1683
- return handleImageGeneration(runtime, params);
1684
- },
1685
- [ModelType6.IMAGE_DESCRIPTION]: async (runtime, params) => {
1686
- return handleImageDescription(runtime, params);
1687
- },
1688
- [ModelType6.TRANSCRIPTION]: async (runtime, input) => {
1689
- return handleTranscription(runtime, input);
1690
- },
1691
- [ModelType6.TEXT_TO_SPEECH]: async (runtime, input) => {
1692
- return handleTextToSpeech(runtime, input);
1693
- },
1694
- [ModelType6.RESEARCH]: async (runtime, params) => {
1695
- return handleResearch(runtime, params);
1696
- }
1697
- },
1698
- tests: [
1699
- {
1700
- name: "openai_plugin_tests",
1701
- tests: [
1702
- {
1703
- name: "openai_test_api_connectivity",
1704
- fn: async (runtime) => {
1705
- const baseURL = getBaseURL(runtime);
1706
- const response = await fetch(`${baseURL}/models`, {
1707
- headers: getAuthHeader(runtime)
1708
- });
1709
- if (!response.ok) {
1710
- throw new Error(`API connectivity test failed: ${response.status} ${response.statusText}`);
1711
- }
1712
- const data = await response.json();
1713
- logger9.info(`[OpenAI Test] API connected. ${data.data?.length ?? 0} models available.`);
1714
- }
1715
- },
1716
- {
1717
- name: "openai_test_text_embedding",
1718
- fn: async (runtime) => {
1719
- const embedding = await runtime.useModel(ModelType6.TEXT_EMBEDDING, {
1720
- text: "Hello, world!"
1721
- });
1722
- if (!Array.isArray(embedding) || embedding.length === 0) {
1723
- throw new Error("Embedding should return a non-empty array");
1724
- }
1725
- logger9.info(`[OpenAI Test] Generated embedding with ${embedding.length} dimensions`);
1726
- }
1727
- },
1728
- {
1729
- name: "openai_test_text_small",
1730
- fn: async (runtime) => {
1731
- const text = await runtime.useModel(ModelType6.TEXT_SMALL, {
1732
- prompt: "Say hello in exactly 5 words."
1733
- });
1734
- if (typeof text !== "string" || text.length === 0) {
1735
- throw new Error("TEXT_SMALL should return non-empty string");
1736
- }
1737
- logger9.info(`[OpenAI Test] TEXT_SMALL generated: "${text.substring(0, 50)}..."`);
1738
- }
1739
- },
1740
- {
1741
- name: "openai_test_text_large",
1742
- fn: async (runtime) => {
1743
- const text = await runtime.useModel(ModelType6.TEXT_LARGE, {
1744
- prompt: "Explain quantum computing in 2 sentences."
1745
- });
1746
- if (typeof text !== "string" || text.length === 0) {
1747
- throw new Error("TEXT_LARGE should return non-empty string");
1748
- }
1749
- logger9.info(`[OpenAI Test] TEXT_LARGE generated: "${text.substring(0, 50)}..."`);
1750
- }
1751
- },
1752
- {
1753
- name: "openai_test_tokenizer_roundtrip",
1754
- fn: async (runtime) => {
1755
- const originalText = "Hello, tokenizer test!";
1756
- const tokens = await runtime.useModel(ModelType6.TEXT_TOKENIZER_ENCODE, {
1757
- prompt: originalText,
1758
- modelType: ModelType6.TEXT_SMALL
1759
- });
1760
- if (!Array.isArray(tokens) || tokens.length === 0) {
1761
- throw new Error("Tokenization should return non-empty token array");
1762
- }
1763
- const decodedText = await runtime.useModel(ModelType6.TEXT_TOKENIZER_DECODE, {
1764
- tokens,
1765
- modelType: ModelType6.TEXT_SMALL
1766
- });
1767
- if (decodedText !== originalText) {
1768
- throw new Error(`Tokenizer roundtrip failed: expected "${originalText}", got "${decodedText}"`);
1769
- }
1770
- logger9.info(`[OpenAI Test] Tokenizer roundtrip successful (${tokens.length} tokens)`);
1771
- }
1772
- },
1773
- {
1774
- name: "openai_test_streaming",
1775
- fn: async (runtime) => {
1776
- const chunks = [];
1777
- const result = await runtime.useModel(ModelType6.TEXT_LARGE, {
1778
- prompt: "Count from 1 to 5, one number per line.",
1779
- stream: true,
1780
- onStreamChunk: (chunk) => {
1781
- chunks.push(chunk);
1782
- }
1783
- });
1784
- if (typeof result !== "string" || result.length === 0) {
1785
- throw new Error("Streaming should return non-empty result");
1786
- }
1787
- if (chunks.length === 0) {
1788
- throw new Error("No streaming chunks received");
1789
- }
1790
- logger9.info(`[OpenAI Test] Streaming test: ${chunks.length} chunks received`);
1791
- }
1792
- },
1793
- {
1794
- name: "openai_test_image_description",
1795
- fn: async (runtime) => {
1796
- const testImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Camponotus_flavomarginatus_ant.jpg/440px-Camponotus_flavomarginatus_ant.jpg";
1797
- const result = await runtime.useModel(ModelType6.IMAGE_DESCRIPTION, testImageUrl);
1798
- if (!result || typeof result !== "object" || !("title" in result) || !("description" in result)) {
1799
- throw new Error("Image description should return { title, description }");
1800
- }
1801
- logger9.info(`[OpenAI Test] Image described: "${result.title}"`);
1802
- }
1803
- },
1804
- {
1805
- name: "openai_test_transcription",
1806
- fn: async (runtime) => {
1807
- const audioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/25/En-Open_Source.ogg";
1808
- const response = await fetch(audioUrl);
1809
- const arrayBuffer = await response.arrayBuffer();
1810
- const audioBuffer = Buffer.from(new Uint8Array(arrayBuffer));
1811
- const transcription = await runtime.useModel(ModelType6.TRANSCRIPTION, audioBuffer);
1812
- if (typeof transcription !== "string") {
1813
- throw new Error("Transcription should return a string");
1814
- }
1815
- logger9.info(`[OpenAI Test] Transcription: "${transcription.substring(0, 50)}..."`);
1816
- }
1817
- },
1818
- {
1819
- name: "openai_test_text_to_speech",
1820
- fn: async (runtime) => {
1821
- const audioData = await runtime.useModel(ModelType6.TEXT_TO_SPEECH, {
1822
- text: "Hello, this is a text-to-speech test."
1823
- });
1824
- if (!(audioData instanceof ArrayBuffer) || audioData.byteLength === 0) {
1825
- throw new Error("TTS should return non-empty ArrayBuffer");
1826
- }
1827
- logger9.info(`[OpenAI Test] TTS generated ${audioData.byteLength} bytes of audio`);
1828
- }
1829
- },
1830
- {
1831
- name: "openai_test_structured_output_via_text_large",
1832
- fn: async (runtime) => {
1833
- const result = await runtime.useModel(ModelType6.TEXT_LARGE, {
1834
- prompt: "Return a JSON object with exactly these fields: name (string), age (number), active (boolean)",
1835
- responseSchema: {
1836
- type: "object",
1837
- properties: {
1838
- name: { type: "string" },
1839
- age: { type: "number" },
1840
- active: { type: "boolean" }
1841
- },
1842
- required: ["name", "age", "active"]
1843
- }
1844
- });
1845
- if (!result || typeof result !== "object" && typeof result !== "string") {
1846
- throw new Error("Structured output should return an object or text");
1847
- }
1848
- logger9.info(`[OpenAI Test] Structured output: ${JSON.stringify(result).substring(0, 100)}`);
1849
- }
1850
- },
1851
- {
1852
- name: "openai_test_research",
1853
- fn: async (runtime) => {
1854
- const result = await runtime.useModel(ModelType6.RESEARCH, {
1855
- input: "What is the current date and time?",
1856
- tools: [{ type: "web_search_preview" }],
1857
- maxToolCalls: 3
1858
- });
1859
- if (!result || typeof result !== "object" || !("text" in result)) {
1860
- throw new Error("Research should return an object with text property");
1861
- }
1862
- if (typeof result.text !== "string" || result.text.length === 0) {
1863
- throw new Error("Research result text should be a non-empty string");
1864
- }
1865
- logger9.info(`[OpenAI Test] Research completed. Text length: ${result.text.length}, Annotations: ${result.annotations?.length ?? 0}`);
1866
- }
1867
- }
1868
- ]
1869
- }
1870
- ]
1871
- };
1872
- var plugin_openai_default = openaiPlugin;
1873
-
1874
- // index.node.ts
1875
- var index_node_default = plugin_openai_default;
1876
- export {
1877
- openaiPlugin,
1878
- index_node_default as default
1879
- };
1880
-
1881
- //# debugId=D3370FEEF676E11164756E2164756E21