Connect Athena vision image generation and speech to LibreChat

This commit is contained in:
Mikei386 committed 2026-10-12 19:19:11 +02:00
1 parent 824fb32339
commit bc3aadc699
7 files changed
+546

No files matched your search

+5
View File
@@ -120,3 +120,8 @@ Keine neue Registrierung erzwungen, keine Credentials neu erzeugt.
Die direkte Node-Anbindung wurde inzwischen eingerichtet. Aufbau und Abnahme
stehen in [nodes/README.md](nodes/README.md). Der Mac-Worker bleibt ein separater
nächster Schritt. OpenWebUI und Athena wurden dafür nicht neu gestartet.
## Bild und Sprache
Athena Bildgenerierung, Vision, STT und TTS am 12.10.2026 angebunden;
Konfiguration, Tests und Einschränkungen in [media/README.md](media/README.md).
@@ -0,0 +1,418 @@
const axios = require('axios');
const { v4 } = require('uuid');
const OpenAI = require('openai');
const FormData = require('form-data');
const { logger } = require('@librechat/data-schemas');
const { tool } = require('@librechat/agents/langchain/tools');
const { ContentTypes, EImageOutputType } = require('librechat-data-provider');
const {
logAxiosError,
oaiToolkit,
extractBaseURL,
getProxyDispatcher,
applyAxiosProxyConfig,
} = require('@librechat/api');
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
const { getFiles } = require('~/models');
const displayMessage =
"The tool displayed an image. All generated images are already plainly visible, so don't repeat the descriptions in detail. Do not list download links as they are available in the UI already. The user may download the images by clicking on them, but do not mention anything about downloading to the user.";
/**
* Replaces unwanted characters from the input string
* @param {string} inputString - The input string to process
* @returns {string} - The processed string
*/
function replaceUnwantedChars(inputString) {
return inputString
.replace(/\r\n|\r|\n/g, ' ')
.replace(/"/g, '')
.trim();
}
function returnValue(value) {
if (typeof value === 'string') {
return [value, {}];
} else if (typeof value === 'object') {
if (Array.isArray(value)) {
return value;
}
return [displayMessage, value];
}
return value;
}
function createAbortHandler() {
return function () {
logger.debug('[ImageGenOAI] Image generation aborted');
};
}
/**
* Creates OpenAI Image tools (generation and editing)
* @param {Object} fields - Configuration fields
* @param {ServerRequest} fields.req - Whether the tool is being used in an agent context
* @param {boolean} fields.isAgent - Whether the tool is being used in an agent context
* @param {string} fields.IMAGE_GEN_OAI_API_KEY - The OpenAI API key
* @param {boolean} [fields.override] - Whether to override the API key check, necessary for app initialization
* @param {MongoFile[]} [fields.imageFiles] - The images to be used for editing
* @param {string} [fields.imageOutputType] - The image output type configuration
* @param {string} [fields.fileStrategy] - The file storage strategy
* @returns {Array<ReturnType<tool>>} - Array of image tools
*/
function createOpenAIImageTools(fields = {}) {
/** @type {boolean} Used to initialize the Tool without necessary variables. */
const override = fields.override ?? false;
/** @type {boolean} */
if (!override && !fields.isAgent) {
throw new Error('This tool is only available for agents.');
}
const { req } = fields;
const imageOutputType = fields.imageOutputType || EImageOutputType.PNG;
const appFileStrategy = fields.fileStrategy;
const getApiKey = () => {
const apiKey = process.env.IMAGE_GEN_OAI_API_KEY ?? '';
if (!apiKey && !override) {
throw new Error('Missing IMAGE_GEN_OAI_API_KEY environment variable.');
}
return apiKey;
};
let apiKey = fields.IMAGE_GEN_OAI_API_KEY ?? getApiKey();
const closureConfig = { apiKey };
const imageModel = process.env.IMAGE_GEN_OAI_MODEL || 'gpt-image-1';
let baseURL = 'https://api.openai.com/v1/';
if (!override && process.env.IMAGE_GEN_OAI_BASEURL) {
baseURL = extractBaseURL(process.env.IMAGE_GEN_OAI_BASEURL);
closureConfig.baseURL = baseURL;
}
// Note: Azure may not yet support the latest image generation models
if (
!override &&
process.env.IMAGE_GEN_OAI_AZURE_API_VERSION &&
process.env.IMAGE_GEN_OAI_BASEURL
) {
baseURL = process.env.IMAGE_GEN_OAI_BASEURL;
closureConfig.baseURL = baseURL;
closureConfig.defaultQuery = { 'api-version': process.env.IMAGE_GEN_OAI_AZURE_API_VERSION };
closureConfig.defaultHeaders = {
'api-key': process.env.IMAGE_GEN_OAI_API_KEY,
'Content-Type': 'application/json',
};
closureConfig.apiKey = process.env.IMAGE_GEN_OAI_API_KEY;
}
const imageFiles = fields.imageFiles ?? [];
/**
* Image Generation Tool
*/
const imageGenTool = tool(
async (
{
prompt,
background = 'auto',
n = 1,
output_compression = 100,
quality = 'auto',
size = 'auto',
},
runnableConfig,
) => {
if (!prompt) {
throw new Error('Missing required field: prompt');
}
const clientConfig = { ...closureConfig };
const proxyDispatcher = getProxyDispatcher();
if (proxyDispatcher) {
clientConfig.fetchOptions = {
dispatcher: proxyDispatcher,
};
}
/** @type {OpenAI} */
const openai = new OpenAI(clientConfig);
let output_format = imageOutputType;
if (
background === 'transparent' &&
output_format !== EImageOutputType.PNG &&
output_format !== EImageOutputType.WEBP
) {
logger.warn(
'[ImageGenOAI] Transparent background requires PNG or WebP format, defaulting to PNG',
);
output_format = EImageOutputType.PNG;
}
let resp;
/** @type {AbortSignal} */
let derivedSignal = null;
/** @type {() => void} */
let abortHandler = null;
try {
if (runnableConfig?.signal) {
derivedSignal = AbortSignal.any([runnableConfig.signal]);
abortHandler = createAbortHandler();
derivedSignal.addEventListener('abort', abortHandler, { once: true });
}
resp = await openai.images.generate(
imageModel === 'athena-image'
? { model: imageModel, prompt: replaceUnwantedChars(prompt), n: 1,
size, response_format: 'b64_json' }
: {
model: imageModel,
prompt: replaceUnwantedChars(prompt),
n: Math.min(Math.max(1, n), 10),
background,
output_format,
output_compression:
output_format === EImageOutputType.WEBP || output_format === EImageOutputType.JPEG
? output_compression
: undefined,
quality,
size,
},
{
signal: derivedSignal,
},
);
} catch (error) {
const message = '[image_gen_oai] Problem generating the image:';
logAxiosError({ error, message });
return returnValue(`Something went wrong when trying to generate the image. The OpenAI API may be unavailable:
Error Message: ${error.message}`);
} finally {
if (abortHandler && derivedSignal) {
derivedSignal.removeEventListener('abort', abortHandler);
}
}
if (!resp) {
return returnValue(
'Something went wrong when trying to generate the image. The OpenAI API may be unavailable',
);
}
// For gpt-image-1, the response contains base64-encoded images
// TODO: handle cost in `resp.usage`
const base64Image = resp.data[0].b64_json;
if (!base64Image) {
return returnValue(
'No image data returned from OpenAI API. There may be a problem with the API or your configuration.',
);
}
const content = [
{
type: ContentTypes.IMAGE_URL,
image_url: {
url: `data:image/${output_format};base64,${base64Image}`,
},
},
];
const file_ids = [v4()];
const response = [
{
type: ContentTypes.TEXT,
text: displayMessage + `\n\ngenerated_image_id: "${file_ids[0]}"`,
},
];
return [response, { content, file_ids }];
},
oaiToolkit.image_gen_oai,
);
/**
* Image Editing Tool
*/
const imageEditTool = tool(
async ({ prompt, image_ids, quality = 'auto', size = 'auto' }, runnableConfig) => {
if (!prompt) {
throw new Error('Missing required field: prompt');
}
const clientConfig = { ...closureConfig };
const proxyDispatcher = getProxyDispatcher();
if (proxyDispatcher) {
clientConfig.fetchOptions = {
dispatcher: proxyDispatcher,
};
}
const formData = new FormData();
formData.append('model', imageModel);
formData.append('prompt', replaceUnwantedChars(prompt));
// TODO: `mask` support
// TODO: more than 1 image support
// formData.append('n', n.toString());
formData.append('quality', quality);
formData.append('size', size);
/** @type {Record<FileSources, undefined | NodeStreamDownloader<File>>} */
const streamMethods = {};
const requestFilesMap = Object.fromEntries(imageFiles.map((f) => [f.file_id, { ...f }]));
const orderedFiles = new Array(image_ids.length);
const idsToFetch = [];
const indexOfMissing = Object.create(null);
for (let i = 0; i < image_ids.length; i++) {
const id = image_ids[i];
const file = requestFilesMap[id];
if (file) {
orderedFiles[i] = file;
} else {
idsToFetch.push(id);
indexOfMissing[id] = i;
}
}
if (idsToFetch.length) {
const fetchedFiles = await getFiles(
{
user: req.user.id,
file_id: { $in: idsToFetch },
height: { $exists: true },
width: { $exists: true },
},
{},
{},
);
for (const file of fetchedFiles) {
requestFilesMap[file.file_id] = file;
orderedFiles[indexOfMissing[file.file_id]] = file;
}
}
for (const imageFile of orderedFiles) {
if (!imageFile) {
continue;
}
/** @type {NodeStream<File>} */
let stream;
/** @type {NodeStreamDownloader<File>} */
let getDownloadStream;
const source = imageFile.source || appFileStrategy;
if (!source) {
throw new Error('No source found for image file');
}
if (streamMethods[source]) {
getDownloadStream = streamMethods[source];
} else {
({ getDownloadStream } = getStrategyFunctions(source));
streamMethods[source] = getDownloadStream;
}
if (!getDownloadStream) {
throw new Error(`No download stream method found for source: ${source}`);
}
stream = await getDownloadStream(req, imageFile.filepath);
if (!stream) {
throw new Error('Failed to get download stream for image file');
}
formData.append('image[]', stream, {
filename: imageFile.filename,
contentType: imageFile.type,
});
}
/** @type {import('axios').RawAxiosHeaders} */
let headers = {
...formData.getHeaders(),
};
if (process.env.IMAGE_GEN_OAI_AZURE_API_VERSION && process.env.IMAGE_GEN_OAI_BASEURL) {
headers['api-key'] = apiKey;
} else {
headers['Authorization'] = `Bearer ${apiKey}`;
}
/** @type {AbortSignal} */
let derivedSignal = null;
/** @type {() => void} */
let abortHandler = null;
try {
if (runnableConfig?.signal) {
derivedSignal = AbortSignal.any([runnableConfig.signal]);
abortHandler = createAbortHandler();
derivedSignal.addEventListener('abort', abortHandler, { once: true });
}
/** @type {import('axios').AxiosRequestConfig} */
const axiosConfig = {
headers,
...clientConfig,
signal: derivedSignal,
baseURL,
};
applyAxiosProxyConfig(axiosConfig, baseURL);
if (process.env.IMAGE_GEN_OAI_AZURE_API_VERSION && process.env.IMAGE_GEN_OAI_BASEURL) {
axiosConfig.params = {
'api-version': process.env.IMAGE_GEN_OAI_AZURE_API_VERSION,
...axiosConfig.params,
};
}
const response = await axios.post('/images/edits', formData, axiosConfig);
if (!response.data || !response.data.data || !response.data.data.length) {
return returnValue(
'No image data returned from OpenAI API. There may be a problem with the API or your configuration.',
);
}
const base64Image = response.data.data[0].b64_json;
if (!base64Image) {
return returnValue(
'No image data returned from OpenAI API. There may be a problem with the API or your configuration.',
);
}
const content = [
{
type: ContentTypes.IMAGE_URL,
image_url: {
url: `data:image/${imageOutputType};base64,${base64Image}`,
},
},
];
const file_ids = [v4()];
const textResponse = [
{
type: ContentTypes.TEXT,
text:
displayMessage +
`\n\ngenerated_image_id: "${file_ids[0]}"\nreferenced_image_ids: ["${image_ids.join('", "')}"]`,
},
];
return [textResponse, { content, file_ids }];
} catch (error) {
const message = '[image_edit_oai] Problem editing the image:';
logAxiosError({ error, message });
return returnValue(`Something went wrong when trying to edit the image. The OpenAI API may be unavailable:
Error Message: ${error.message || 'Unknown error'}`);
} finally {
if (abortHandler && derivedSignal) {
derivedSignal.removeEventListener('abort', abortHandler);
}
}
},
oaiToolkit.image_edit_oai,
);
return imageModel === 'athena-image' ? [imageGenTool] : [imageGenTool, imageEditTool];
}
module.exports = createOpenAIImageTools;
@@ -0,0 +1,84 @@
# Athena Bild, Vision, STT und TTS in LibreChat
12.10.2026, bestehender LibreChat-Dev-Build v0.8.8; kein neuer Container.
Athena API `http://192.168.1.212:8120/v1`, bestehender ATHENA_API_KEY intern
übernommen. Kein Geheimnis in Git. Keine Athena-/OpenWebUI-Neustarts.
## Konfiguration
- Bild: `IMAGE_GEN_OAI_BASEURL`, `IMAGE_GEN_OAI_MODEL=athena-image`,
`IMAGE_GEN_OAI_API_KEY` aus bestehendem Athena-Key in geschützter Unraid-XML.
Agent Athena mit Terminal erhält `image_gen_oai`; eigene neue Agenten müssen
dieses Werkzeug in ihrer Tool-Auswahl hinzufügen.
- Vision: vorhandene Athena-Projektoren bleiben backendseitig. Bildinhalt als
OpenAI-kompatible image_url in chat/completions, kein separater Projektor in
LibreChat zu installieren. Kein pauschales Umkonfigurieren visionloser Modelle.
- STT: speech.stt.openai in librechat.yaml, vollständige URL
`/v1/audio/transcriptions`, Modell qwen3-asr-stt, Key `${ATHENA_API_KEY}`.
- TTS: speech.tts.openai, vollständige URL `/v1/audio/speech`, Modell qwen-tts,
Stimme Serena. Backend liefert WAV; Sprache folgt vorhandenem deutschen Profil.
- Nur `192.168.1.212:8120` in beiden speech.allowedAddresses (gezielte private
SSRF-Ausnahme). Keine Abschaltung von SSRF oder Zertifikatsprüfung.
- UI-Defaults: external STT/TTS, Sprache de, Serena; automatisches Vorlesen
nicht aktiviert. Bestehende benutzereigene Browserpräferenzen können Defaults
überschreiben; in Spracheinstellungen External/Serena auswählen.
## Kleine Bild-API-Kompatibilitätsanpassung
LibreChats Standard-OpenAIImageTools senden background, output_format,
quality und output_compression. Athena akzeptiert nur model/prompt/n/size/
response_format/user. Native Werkzeug-JS ausschließlich für Modell
athena-image angepasst: ein Bild, response_format=b64_json, size als Präferenz.
Bildparameter/Qualität folgen Athena-Profil. Andere Modelle unverändert.
Athena-Branch stellt nur Generation bereit; Bildbearbeitung über dieses Toolkit
nicht aktiviert/abgenommen. Kein zusätzliches MCP für den vorhandenen API-Endpunkt.
Öffentliche Quelldatei unter `librechat/compat/OpenAIImageTools.js`, read-only
Bind-Mount auf `/app/api/app/clients/tools/structured/OpenAIImageTools.js`.
Das ist ausdrücklich eine lokale Kompatibilitätsanpassung, keine offizielle
LibreChat-Konfigurationsoption. Upstream-Quelle LibreChat Dev-Image-Digest wie
übergeordnete README; ursprüngliche JS-Prüfsumme:
`4f33b5454287e1de0b6c58bce2d9c6ef5b6f5a990f3bbf7f92969600f631d957`.
Bei LibreChat-Upgrade gegen neue Originaldatei prüfen/neu anwenden; nicht
unbesehen eine alte vollständige Quelldatei über einen neuen Build legen.
Quellcode steht unter LibreChats Upstream-Lizenz AGPL-3.0.
## Abnahme
Tests verwenden ausschließlich synthetischen Inhalt, keine privaten Chats,
Aufnahmen oder Produktionslogs. Native LibreChat TTSService/STTService direkt
mit gespeicherten speech-Schemas und derselben SSRF-/Env-Auflösung aufgerufen:
- TTS HTTP200, 103724 Bytes, RIFF/WAV, kurzer deutscher Testsatz, Serena.
- STT, synthetische Anna-Testaufnahme 2,877 s PCM16/mono/16kHz:
`Dies ist ein kurzer Test der Spracherkennung.` korrekt erkannt.
- Vision-Anfrage aus LibreChat-Container an tatsächliches Medium-Profil,
synthetisches rotes 64x64-PNG: HTTP200, Antwort `Rot`.
- Native Bildwerkzeug mit lokalem synthetischem HTTP-Gegenstück: ausschließlich
bestätigte Athena-Parameter gesendet, Bild-Artefakt zurückgegeben. Dies allein
ist kein Beweis einer echten GPU-Bildgenerierung. Zusätzlich wurde das native
Werkzeug gegen den echten Athena-Endpunkt aufgerufen: roter Kreis auf weißem
Grund erfolgreich generiert, Rückgabe enthält generated_image_id.
Keine Bild-/Audio-UI-Abnahme oder Browserwiedergabe dadurch behaupten.
Keine vollständige UI-Abnahme für Upload/Mikrofon/Vorlesen in diesem Schritt.
LibreChat läuft bisher auf HTTP192.168.1.2:3080: Browser-Mikrofonzugriff verlangt
normalerweise einen sicheren HTTPS-Kontext (localhost-Ausnahme hier nicht
anwendbar). Server-STT funktioniert dennoch für Audio-Uploads. HTTPS-UI noch
nicht eingerichtet; keine Browser-Sicherheitsumgehung hinzufügen.
## Backup / Restore
Vorherige YAML/XML geschützt unter
`librechat/install-backups/media-20261012-171200`.
Zusätzlich `librechat/compat` und aktualisierte XML/YAML in verschlüsselte
Vollsicherung aufnehmen, Agent-Tool-Zuordnung in MongoDB sichern.
Installationshelfer hier enthalten keine Schlüssel, übernehmen vorhandenen Key.
Sie sind Unraid-spezifisch, prüfen tatsächliches configSchema, sichern vor
Änderung und ersetzen nur den bestehenden LibreChat-Container.
Für nativen Debian-Zielbetrieb weiterhin registrierte Studio-Container;
Athena-Dienste unverändert. Backendmodelle/Gewichte/Audio-Policy im separaten
Athena-Restore erhalten. Vollständiger frischer Restore nicht getestet.
Quellen: [Speech](https://www.librechat.ai/docs/configuration/librechat_yaml/object_structure/speech),
[Bildwerkzeuge](https://www.librechat.ai/docs/features/image_gen).
@@ -0,0 +1,7 @@
const fs=require('fs'),yaml=require('js-yaml'),mongoose=require('mongoose');
const {configSchema}=require('librechat-data-provider');
(async()=>{const path='/app/librechat.yaml',v=yaml.load(fs.readFileSync(path,'utf8'));
v.speech={stt:{allowedAddresses:['192.168.1.212:8120'],openai:{url:'http://192.168.1.212:8120/v1/audio/transcriptions',apiKey:'${ATHENA_API_KEY}',model:'qwen3-asr-stt'}},tts:{allowedAddresses:['192.168.1.212:8120'],openai:{url:'http://192.168.1.212:8120/v1/audio/speech',apiKey:'${ATHENA_API_KEY}',model:'qwen-tts',voices:['Serena']}},speechTab:{conversationMode:false,speechToText:{engineSTT:'external',languageSTT:'de',autoTranscribeAudio:false},textToSpeech:{engineTTS:'external',voice:'Serena',languageTTS:'de',automaticPlayback:false,cacheTTS:true}}};
const r=configSchema.safeParse(v);if(!r.success){console.log(JSON.stringify(r.error.issues));process.exit(1)}
fs.writeFileSync("/tmp/librechat-media.yaml",yaml.dump(v,{lineWidth:120,noRefs:true}));
await mongoose.connect(process.env.MONGO_URI);await mongoose.connection.db.collection('agents').updateOne({id:'agent_SYrfQkHi6aaPipUYXBdCC'},{$addToSet:{tools:'image_gen_oai'}});await mongoose.disconnect();console.log('Speech config validated and saved; image generator enabled on Athena mit Terminal.');})().catch(e=>{console.error(e.name);process.exit(1)});
@@ -0,0 +1,13 @@
<?php
function run($a){$p=proc_open($a,[1=>['pipe','w'],2=>['pipe','w']],$ps);$o=stream_get_contents($ps[1]);$e=stream_get_contents($ps[2]);foreach($ps as$s)fclose($s);$c=proc_close($p);if($c)throw new Exception('Command failed exit '.$c);return $o;}
$root='/mnt/nvme-storage/appdata/librechat';$xp='/boot/config/plugins/dockerMan/templates-user/my-LibreChat.xml';$x=simplexml_load_file($xp);$back=$root.'/install-backups/media-'.gmdate('Ymd-His');mkdir($back,0700,true);copy($xp,$back.'/my-LibreChat.xml');chmod($back.'/my-LibreChat.xml',0600);copy($root.'/librechat.yaml',$back.'/librechat.yaml');
if(!is_dir($root.'/compat'))mkdir($root.'/compat',0755,true);copy('/tmp/OpenAIImageTools.js',$root.'/compat/OpenAIImageTools.js');chmod($root.'/compat/OpenAIImageTools.js',0644);
run(['docker','cp','/tmp/configure-media.js','LibreChat:/tmp/configure-media.js']);
echo run(['docker','exec','LibreChat','node','-e','eval(require("fs").readFileSync("/tmp/configure-media.js","utf8"))']);
run(['docker','cp','LibreChat:/tmp/librechat-media.yaml',$root.'/librechat.yaml']);
$key=null;foreach($x->Config as$c)if((string)$c['Target']==='ATHENA_API_KEY')$key=(string)$c;if(!$key)throw new Exception('Existing Athena key missing');
$env=['IMAGE_GEN_OAI_API_KEY'=>$key,'IMAGE_GEN_OAI_BASEURL'=>'http://192.168.1.212:8120/v1','IMAGE_GEN_OAI_MODEL'=>'athena-image','IMAGE_GEN_OAI_DESCRIPTION'=>'Generate one image using the local Athena image generator. Image dimensions and settings follow the Athena profile.','IMAGE_GEN_OAI_PROMPT_DESCRIPTION'=>'Describe the requested image.'];
foreach($env as$k=>$v){$found=false;foreach($x->Config as$c)if((string)$c['Target']===$k){$c[0]=$v;$found=true;}if(!$found){$c=$x->addChild('Config',htmlspecialchars($v,ENT_XML1));foreach(['Name'=>$k,'Target'=>$k,'Type'=>'Variable','Mode'=>'','Display'=>'always','Mask'=>strpos($k,'API_KEY')!==false?'true':'false']as$a=>$z)$c->addAttribute($a,$z);}}
$target='/app/api/app/clients/tools/structured/OpenAIImageTools.js';$found=false;foreach($x->Config as$c)if((string)$c['Target']===$target)$found=true;if(!$found){$c=$x->addChild('Config',$root.'/compat/OpenAIImageTools.js');foreach(['Name'=>'Athena Image API compatibility','Target'=>$target,'Type'=>'Path','Mode'=>'ro','Display'=>'always']as$a=>$z)$c->addAttribute($a,$z);}$x->asXML($xp);chmod($xp,0600);
$a=['docker','create','--name','LibreChat','--network','bridge','--restart','unless-stopped','--pids-limit','2048','-l','net.unraid.docker.managed=dockerman'];foreach(['WebUI'=>'net.unraid.docker.webui','Icon'=>'net.unraid.docker.icon']as$k=>$v)if((string)$x->$k!='')array_push($a,'-l',$v.'='.(string)$x->$k);foreach($x->Config as$c){$v=(string)$c;$target=(string)$c['Target'];$type=(string)$c['Type'];if($type==='Variable')array_push($a,'-e',$target.'='.$v);elseif($type==='Port')array_push($a,'-p',$v.':'.$target.'/'.(string)$c['Mode']);elseif($type==='Path')array_push($a,'-v',$v.':'.$target.':'.(string)$c['Mode']);else throw new Exception('Unknown config type');}$a[]=(string)$x->Repository;
run(['docker','stop','--time','30','LibreChat']);run(['docker','rm','LibreChat']);run($a);run(['docker','start','LibreChat']);echo json_encode(['media_configured'=>true,'backup'=>$back])."\n";
@@ -0,0 +1,2 @@
require('module-alias/register');require('module-alias').addAlias('~','/app/api');
(async()=>{const create=require('/app/api/app/clients/tools/structured/OpenAIImageTools');const [tool]=create({isAgent:true,req:{}});const result=await tool.invoke({prompt:'A simple red circle on a plain white background. No text.',size:'auto'});let value=result;const str=JSON.stringify(result);console.log(JSON.stringify({imageGenerated:str.includes('generated_image_id'),hasImage:str.includes('data:image/'),message:str.includes('Something went wrong')?String(result[0]).slice(0,400):undefined}));process.exit(str.includes('generated_image_id')?0:1)})().catch(e=>{console.log(JSON.stringify({error:e.name}));process.exit(1)});
@@ -0,0 +1,17 @@
require('module-alias/register'); require('module-alias').addAlias('~','/app/api');
const fs=require('fs'),yaml=require('js-yaml'),http=require('http');
const conf=yaml.load(fs.readFileSync('/app/librechat.yaml','utf8'));
const {TTSService}=require('/app/api/server/services/Files/Audio/TTSService');
const {STTService}=require('/app/api/server/services/Files/Audio/STTService');
(async()=>{
const tts=new TTSService(),stt=new STTService();
console.log(JSON.stringify({configuration:{tts:tts.getProvider(conf),sttModel:conf.speech.stt.openai.model,voice:conf.speech.tts.openai.voices[0]}}));
try{const r=await tts.ttsRequest('openai',conf.speech.tts.openai,{input:'Dies ist ein kurzer Test.',voice:'Serena',stream:false},conf.speech.tts.allowedAddresses);let buf=Buffer.from(r.data);console.log(JSON.stringify({ttsStatus:r.status,bytes:buf.length,magic:buf.subarray(0,4).toString('ascii')}));fs.writeFileSync('/tmp/librechat-tts-test.wav',buf)}catch(e){console.log(JSON.stringify({ttsErrorStatus:e.response?.status,code:e.response?.data?.error?.code||e.code,message:Buffer.isBuffer(e.response?.data)?JSON.parse(e.response.data.toString()).error?.message:e.response?.data?.error?.message}));}
try{const r=await stt.sttRequest('openai',conf.speech.stt.openai,{audioBuffer:fs.readFileSync('/tmp/librechat-stt-test.wav'),audioFile:{originalname:'stt-test.wav',mimetype:'audio/wav'},language:'de'},conf.speech.stt.allowedAddresses);console.log(JSON.stringify({sttResult:r}));}catch(e){console.log(JSON.stringify({sttErrorStatus:e.response?.status,code:e.response?.data?.error?.code||e.code,message:e.response?.data?.error?.message}));}
const png=fs.readFileSync('/tmp/librechat-vision-test.png').toString('base64');
try{const r=await fetch('http://192.168.1.212:8120/v1/chat/completions',{method:'POST',headers:{Authorization:'Bearer '+process.env.ATHENA_API_KEY,'Content-Type':'application/json'},body:JSON.stringify({model:'qwen3-8-27b-medium',messages:[{role:'user',content:[{type:'text',text:'Welche Farbe hat das Bild? Antworte nur mit der Farbe.'},{type:'image_url',image_url:{url:'data:image/png;base64,'+png}}]}],max_tokens:32,reasoning_effort:'low'}),signal:AbortSignal.timeout(180000)});const j=await r.json();console.log(JSON.stringify({visionStatus:r.status,answer:j.choices?.[0]?.message?.content,error:j.error?.code}));}catch(e){console.log(JSON.stringify({visionError:e.name}));}
let imageRequest;
const server=http.createServer((req,res)=>{let raw='';req.on('data',d=>raw+=d);req.on('end',()=>{imageRequest=JSON.parse(raw);res.setHeader('Content-Type','application/json');res.end(JSON.stringify({created:Math.floor(Date.now()/1000),data:[{b64_json:png}]}));});});await new Promise(r=>server.listen(0,'127.0.0.1',r));
process.env.IMAGE_GEN_OAI_BASEURL='http://127.0.0.1:'+server.address().port+'/v1';
try{const create=require('/app/api/app/clients/tools/structured/OpenAIImageTools');const tools=create({isAgent:true,req:{}});const result=await tools[0].invoke({prompt:'Synthetic red square',size:'auto'});console.log(JSON.stringify({imageToolNames:tools.map(t=>t.name),imageRequest,hasOutput:!!result}));}catch(e){console.log(JSON.stringify({imageToolError:e.name,message:e.message}));}finally{server.close();}
})().catch(e=>{console.log(JSON.stringify({testError:e.name}));process.exit(1)});