-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproviders.js
More file actions
573 lines (535 loc) · 22.9 KB
/
providers.js
File metadata and controls
573 lines (535 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
const DEFAULT_TIMEOUT_MS = 120000;
let geminiImageSessionFallbackModel = '';
function withTimeout(promise, timeoutMs, label) {
const ms = Math.max(1000, Number(timeoutMs || DEFAULT_TIMEOUT_MS));
return new Promise((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error(`${label || 'Request'} timed out after ${ms}ms`));
}, ms);
Promise.resolve(promise).then((value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
}).catch((error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(error);
});
});
}
async function fetchJson(url, init, timeoutMs, label) {
const response = await withTimeout(fetch(url, init), timeoutMs, label);
const text = await response.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch (_) {}
if (!response.ok) {
const baseMessage = (json && (json.error?.message || json.message || json.result?.error)) || text.slice(0, 600);
const extraParts = [];
const details = Array.isArray(json?.error?.details) ? json.error.details : [];
for (const detail of details) {
const type = String(detail?.['@type'] || detail?.type || '').toLowerCase();
if (type.includes('google.rpc.quotafailure')) {
const violations = Array.isArray(detail?.violations) ? detail.violations : [];
for (const v of violations) {
const metric = String(v?.quotaMetric || '').trim();
const id = String(v?.quotaId || '').trim();
if (metric) extraParts.push(`quotaMetric=${metric}`);
if (id) extraParts.push(`quotaId=${id}`);
const dims = v?.quotaDimensions && typeof v.quotaDimensions === 'object' ? v.quotaDimensions : null;
if (dims) {
const model = String(dims.model || dims.Model || '').trim();
if (model) extraParts.push(`quotaModel=${model}`);
}
if (v?.quotaValue != null && String(v.quotaValue).trim()) {
extraParts.push(`quotaValue=${String(v.quotaValue).trim()}`);
}
}
}
if (type.includes('google.rpc.retryinfo')) {
const retryDelay = String(detail?.retryDelay || '').trim();
if (retryDelay) extraParts.push(`retryDelay=${retryDelay}`);
}
}
const suffix = extraParts.length ? ` [${extraParts.join('; ')}]` : '';
throw new Error(`${label || 'Request'} failed (${response.status}): ${baseMessage}${suffix}`);
}
return { response, text, json };
}
async function fetchBufferFromUrl(url, timeoutMs, label) {
const res = await withTimeout(fetch(url), timeoutMs, label || 'Image download');
if (!res.ok) throw new Error(`Image download failed (${res.status})`);
const arrayBuffer = await res.arrayBuffer();
return Buffer.from(arrayBuffer);
}
function resolveProviderValue(providerConfig, key, fallbackEnvKey) {
if (providerConfig && providerConfig[key]) return String(providerConfig[key]);
if (providerConfig && providerConfig[`${key}_env`]) {
const envKey = String(providerConfig[`${key}_env`]);
if (process.env[envKey]) return String(process.env[envKey]);
}
if (fallbackEnvKey && process.env[fallbackEnvKey]) return String(process.env[fallbackEnvKey]);
return '';
}
function normalizeGeminiModel(model) {
const raw = String(model || '').trim();
if (!raw) return '';
return raw.replace(/^models\//i, '');
}
function resolveGeminiImageModelForSession(requestedModel) {
const requested = normalizeGeminiModel(requestedModel);
const sticky = normalizeGeminiModel(geminiImageSessionFallbackModel);
if (sticky) return sticky;
return requested;
}
function getGeminiText(json) {
const parts = json?.candidates?.[0]?.content?.parts || [];
return parts.map((p) => p?.text || '').filter(Boolean).join(' ').trim();
}
function getCohereText(json) {
const direct = String(json?.text || '').trim();
if (direct) return direct;
const messageContent = Array.isArray(json?.message?.content) ? json.message.content : [];
const parts = messageContent
.map((item) => String(item?.text || '').trim())
.filter(Boolean);
if (parts.length) return parts.join('\n').trim();
return '';
}
function extractGeminiInlineImage(json) {
const candidates = Array.isArray(json?.candidates) ? json.candidates : [];
for (const candidate of candidates) {
const parts = Array.isArray(candidate?.content?.parts) ? candidate.content.parts : [];
for (const part of parts) {
const data = String(part?.inlineData?.data || '').trim();
if (!data) continue;
return {
data,
mimeType: String(part?.inlineData?.mimeType || 'image/png').trim() || 'image/png'
};
}
}
return null;
}
function isGeminiDailyQuotaError(errorLike) {
const msg = String(errorLike?.message || errorLike || '').toLowerCase();
if (!msg.includes('failed (429)')) return false;
const hasPerDaySignal = msg.includes('request per day')
|| msg.includes('perday')
|| msg.includes('per_day')
|| msg.includes('quotaid=')
|| msg.includes('quotametric=');
if (hasPerDaySignal && msg.includes('perminute')) return false;
if (msg.includes('quotaid=') || msg.includes('quotametric=')) {
return msg.includes('perday') || msg.includes('per_day');
}
return msg.includes('request per day')
|| msg.includes('rpd')
|| msg.includes('please migrate to gemini 2.5 flash image');
}
function decodeDataUri(value) {
const raw = String(value || '');
const match = raw.match(/^data:[^;]+;base64,(.+)$/i);
if (!match) return null;
return Buffer.from(match[1], 'base64');
}
function normalizeBaseUrl(value, fallback) {
const raw = String(value || fallback || '').trim();
if (!raw) return '';
const normalized = raw.replace(/\/+$/, '');
// Hugging Face deprecated api-inference endpoint now redirects to router API.
if (/^https?:\/\/api-inference\.huggingface\.co$/i.test(normalized)) {
return 'https://router.huggingface.co/hf-inference';
}
return normalized;
}
function buildHuggingFaceModelUrl(providerConfig, model) {
const configuredBase = resolveProviderValue(providerConfig, 'base_url', 'HUGGINGFACE_BASE_URL');
const base = normalizeBaseUrl(configuredBase, 'https://router.huggingface.co/hf-inference');
return `${base}/models/${encodeURIComponent(String(model || '').trim())}`;
}
const NO_TEXT_IMAGE_SUFFIX = [
'STRICT NO-TEXT RULE:',
'Do not render any words, letters, numbers, symbols, labels, signs, logos, UI text, speech bubbles, subtitles, captions, or watermarks.',
'Output must be fully text-free artwork.'
].join(' ');
function enforceNoTextImagePrompt(prompt) {
const base = String(prompt || '').trim();
const lower = base.toLowerCase();
if (!base) return NO_TEXT_IMAGE_SUFFIX;
if (lower.includes('strict no-text rule')) return base;
return `${base}\n\n${NO_TEXT_IMAGE_SUFFIX}`.trim();
}
function rethrowCloudflareAuthError(error, kind) {
const msg = String(error?.message || error || '');
const low = msg.toLowerCase();
const isAuth = low.includes('cloudflare') && (low.includes('failed (401)') || low.includes('"code":10000') || low.includes('authentication error'));
if (!isAuth) throw error;
const label = kind === 'image' ? 'image' : 'text';
throw new Error(
`Cloudflare ${label} authentication failed. Check CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN (Workers AI scope) in /keys, or switch provider with /vendor gemini. Original: ${msg}`
);
}
async function generateTextWithProvider(providerConfig, prompt, runtimeConfig) {
const provider = String(providerConfig.provider || '').toLowerCase();
const model = provider === 'gemini'
? normalizeGeminiModel(providerConfig.model)
: String(providerConfig.model || '').trim();
const timeoutMs = Number(runtimeConfig.timeout_ms || DEFAULT_TIMEOUT_MS);
const temperature = Number(runtimeConfig && runtimeConfig.text_temperature);
const hasTemperature = Number.isFinite(temperature);
if (provider === 'gemini') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'GEMINI_API_KEY');
if (!apiKey) throw new Error('Missing GEMINI_API_KEY for Gemini text provider');
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const { json } = await fetchJson(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
maxOutputTokens: 4096,
...(hasTemperature ? { temperature } : {})
}
})
}, timeoutMs, 'Gemini text');
const text = getGeminiText(json);
if (!text) throw new Error('Gemini text response was empty');
return text;
}
if (provider === 'openai') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'OPENAI_API_KEY');
if (!apiKey) throw new Error('Missing OPENAI_API_KEY for OpenAI text provider');
const { json } = await fetchJson('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
temperature: hasTemperature ? temperature : 0.3
})
}, timeoutMs, 'OpenAI text');
const text = String(json?.choices?.[0]?.message?.content || '').trim();
if (!text) throw new Error('OpenAI text response was empty');
return text;
}
if (provider === 'openrouter') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'OPENROUTER_API_KEY');
if (!apiKey) throw new Error('Missing OPENROUTER_API_KEY for OpenRouter text provider');
const { json } = await fetchJson('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://web2comics.local',
'X-Title': 'Web2Comics Engine'
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
temperature: hasTemperature ? temperature : 0.3
})
}, timeoutMs, 'OpenRouter text');
const text = String(json?.choices?.[0]?.message?.content || '').trim();
if (!text) throw new Error('OpenRouter text response was empty');
return text;
}
if (provider === 'groq') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'GROQ_API_KEY');
if (!apiKey) throw new Error('Missing GROQ_API_KEY for Groq text provider');
const { json } = await fetchJson('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
temperature: hasTemperature ? temperature : 0.3
})
}, timeoutMs, 'Groq text');
const text = String(json?.choices?.[0]?.message?.content || '').trim();
if (!text) throw new Error('Groq text response was empty');
return text;
}
if (provider === 'cohere') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'COHERE_API_KEY');
if (!apiKey) throw new Error('Missing COHERE_API_KEY for Cohere text provider');
const baseUrl = normalizeBaseUrl(resolveProviderValue(providerConfig, 'base_url', 'COHERE_BASE_URL'), 'https://api.cohere.com');
const { json } = await fetchJson(`${baseUrl}/v2/chat`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
temperature: hasTemperature ? temperature : 0.3,
max_tokens: 2048
})
}, timeoutMs, 'Cohere text');
const text = getCohereText(json);
if (!text) throw new Error('Cohere text response was empty');
return text;
}
if (provider === 'cloudflare') {
const accountId = resolveProviderValue(providerConfig, 'account_id', 'CLOUDFLARE_ACCOUNT_ID');
const apiToken = resolveProviderValue(providerConfig, 'api_token', 'CLOUDFLARE_API_TOKEN');
if (!accountId || !apiToken) throw new Error('Missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN for Cloudflare text provider');
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`;
try {
const { json } = await fetchJson(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
...(hasTemperature ? { temperature } : {})
})
}, timeoutMs, 'Cloudflare text');
const text = String(json?.result?.response || json?.result?.text || '').trim();
if (!text) throw new Error('Cloudflare text response was empty');
return text;
} catch (error) {
rethrowCloudflareAuthError(error, 'text');
throw error;
}
}
if (provider === 'huggingface') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'HUGGINGFACE_INFERENCE_API_TOKEN') || process.env.HUGGINGFACE_API_KEY || '';
if (!apiKey) throw new Error('Missing HUGGINGFACE_INFERENCE_API_TOKEN for Hugging Face text provider');
const { json } = await fetchJson(buildHuggingFaceModelUrl(providerConfig, model), {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
inputs: prompt,
parameters: {
max_new_tokens: 512,
...(hasTemperature ? { temperature } : {})
}
})
}, timeoutMs, 'Hugging Face text');
const text = Array.isArray(json)
? String(json[0]?.generated_text || '').trim()
: String(json?.generated_text || json?.[0]?.generated_text || '').trim();
if (!text) throw new Error('Hugging Face text response was empty');
return text;
}
if (provider === 'groq') {
throw new Error('Groq image provider is not supported');
}
throw new Error(`Unsupported text provider: ${provider}`);
}
async function generateImageWithProvider(providerConfig, prompt, runtimeConfig, options = {}) {
const provider = String(providerConfig.provider || '').toLowerCase();
const model = provider === 'gemini'
? normalizeGeminiModel(providerConfig.model)
: String(providerConfig.model || '').trim();
const timeoutMs = Number(runtimeConfig.timeout_ms || DEFAULT_TIMEOUT_MS);
const referenceImage = options && options.referenceImage ? options.referenceImage : null;
const safePrompt = enforceNoTextImagePrompt(prompt);
if (provider === 'gemini') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'GEMINI_API_KEY');
if (!apiKey) throw new Error('Missing GEMINI_API_KEY for Gemini image provider');
const requestOnce = async (modelId, responseModalities, promptText) => {
const url = `https://generativelanguage.googleapis.com/v1beta/models/${normalizeGeminiModel(modelId)}:generateContent?key=${apiKey}`;
const requestParts = [];
if (referenceImage && Buffer.isBuffer(referenceImage.buffer) && referenceImage.buffer.length) {
requestParts.push({
inlineData: {
mimeType: String(referenceImage.mimeType || 'image/png'),
data: referenceImage.buffer.toString('base64')
}
});
}
requestParts.push({ text: promptText });
const { json } = await fetchJson(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: requestParts }],
generationConfig: { responseModalities, maxOutputTokens: 512 }
})
}, timeoutMs, 'Gemini image');
const inline = extractGeminiInlineImage(json);
if (inline && inline.data) {
return {
buffer: Buffer.from(inline.data, 'base64'),
mimeType: inline.mimeType || 'image/png'
};
}
const finishReason = String((json?.candidates?.[0]?.finishReason || '')).trim();
const firstText = getGeminiText(json);
const hint = firstText ? `; text="${firstText.slice(0, 180)}"` : '';
const finishHint = finishReason ? `; finishReason=${finishReason}` : '';
throw new Error(`Gemini image response did not include inline image bytes${finishHint}${hint}`);
};
const tryModel = async (modelId) => {
try {
return await requestOnce(modelId, ['image', 'text'], safePrompt);
} catch (firstError) {
const fallbackPrompt = `${safePrompt}\nReturn image output only. Do not return any text.`.trim();
try {
return await requestOnce(modelId, ['image'], fallbackPrompt);
} catch (_) {
throw firstError;
}
}
};
const initialModel = resolveGeminiImageModelForSession(model);
try {
return await tryModel(initialModel);
} catch (firstError) {
const quotaFallbackModel = 'gemini-2.5-flash-image';
if (normalizeGeminiModel(initialModel) !== quotaFallbackModel && isGeminiDailyQuotaError(firstError)) {
geminiImageSessionFallbackModel = quotaFallbackModel;
try {
return await tryModel(quotaFallbackModel);
} catch (fallbackError) {
throw new Error(
`${String(firstError?.message || firstError)}; fallback ${quotaFallbackModel} failed: ${String(fallbackError?.message || fallbackError)}`
);
}
}
throw firstError;
}
}
if (provider === 'openai') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'OPENAI_API_KEY');
if (!apiKey) throw new Error('Missing OPENAI_API_KEY for OpenAI image provider');
const size = String(providerConfig.size || '1024x1024');
const { json } = await fetchJson('https://api.openai.com/v1/images/generations', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model,
prompt: safePrompt,
size,
quality: String(providerConfig.quality || 'standard'),
n: 1
})
}, timeoutMs, 'OpenAI image');
const item = json?.data?.[0] || {};
if (item.b64_json) {
return { buffer: Buffer.from(item.b64_json, 'base64'), mimeType: 'image/png' };
}
if (item.url) {
const buffer = await fetchBufferFromUrl(item.url, timeoutMs, 'OpenAI image URL');
return { buffer, mimeType: 'image/png' };
}
throw new Error('OpenAI image response had no image data');
}
if (provider === 'openrouter') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'OPENROUTER_API_KEY');
if (!apiKey) throw new Error('Missing OPENROUTER_API_KEY for OpenRouter image provider');
const { json } = await fetchJson('https://openrouter.ai/api/v1/images/generations', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://web2comics.local',
'X-Title': 'Web2Comics Engine'
},
body: JSON.stringify({
model,
prompt: safePrompt,
size: String(providerConfig.size || '1024x1024'),
n: 1
})
}, timeoutMs, 'OpenRouter image');
const item = json?.data?.[0] || {};
if (item.b64_json) return { buffer: Buffer.from(item.b64_json, 'base64'), mimeType: 'image/png' };
if (item.url) return { buffer: await fetchBufferFromUrl(item.url, timeoutMs, 'OpenRouter image URL'), mimeType: 'image/png' };
throw new Error('OpenRouter image response had no image data');
}
if (provider === 'cloudflare') {
const accountId = resolveProviderValue(providerConfig, 'account_id', 'CLOUDFLARE_ACCOUNT_ID');
const apiToken = resolveProviderValue(providerConfig, 'api_token', 'CLOUDFLARE_API_TOKEN');
if (!accountId || !apiToken) throw new Error('Missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN for Cloudflare image provider');
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`;
try {
const { json } = await fetchJson(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: safePrompt })
}, timeoutMs, 'Cloudflare image');
const imagePayload = json?.result?.image || json?.result?.output?.[0] || '';
if (!imagePayload) throw new Error('Cloudflare image response had no image payload');
const dataUriBuffer = decodeDataUri(imagePayload);
if (dataUriBuffer) return { buffer: dataUriBuffer, mimeType: 'image/png' };
return { buffer: Buffer.from(String(imagePayload), 'base64'), mimeType: 'image/png' };
} catch (error) {
rethrowCloudflareAuthError(error, 'image');
throw error;
}
}
if (provider === 'huggingface') {
const apiKey = resolveProviderValue(providerConfig, 'api_key', 'HUGGINGFACE_INFERENCE_API_TOKEN') || process.env.HUGGINGFACE_API_KEY || '';
if (!apiKey) throw new Error('Missing HUGGINGFACE_INFERENCE_API_TOKEN for Hugging Face image provider');
const response = await withTimeout(fetch(buildHuggingFaceModelUrl(providerConfig, model), {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ inputs: safePrompt })
}), timeoutMs, 'Hugging Face image');
if (!response.ok) {
const text = await response.text();
throw new Error(`Hugging Face image failed (${response.status}): ${text.slice(0, 400)}`);
}
const arrayBuffer = await response.arrayBuffer();
return {
buffer: Buffer.from(arrayBuffer),
mimeType: response.headers.get('content-type') || 'image/png'
};
}
throw new Error(`Unsupported image provider: ${provider}`);
}
function supportsImageReferenceInput(providerConfig) {
const explicit = providerConfig?.supports_image_reference;
if (explicit != null) {
if (typeof explicit === 'boolean') return explicit;
const normalized = String(explicit).trim().toLowerCase();
if (normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on') return true;
if (normalized === '0' || normalized === 'false' || normalized === 'no' || normalized === 'off') return false;
}
const provider = String(providerConfig?.provider || '').trim().toLowerCase();
const model = String(providerConfig?.model || '').trim().toLowerCase();
if (provider === 'gemini') {
return /image|flash-exp-image-generation|image-preview/.test(model);
}
return false;
}
module.exports = {
generateTextWithProvider,
generateImageWithProvider,
supportsImageReferenceInput,
enforceNoTextImagePrompt,
extractGeminiInlineImage,
__resetProviderSessionStateForTests: () => {
geminiImageSessionFallbackModel = '';
}
};