dolibarr 25.0.0-alpha
custom_prompt.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2022 Alice Adminson <aadminson@example.com>
4 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
6 * Copyright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2026 Nick Fragoulis
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
29// Load Dolibarr environment
30require '../../main.inc.php';
38require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
39require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
40require_once DOL_DOCUMENT_ROOT."/ai/lib/ai.lib.php";
41require_once DOL_DOCUMENT_ROOT."/ai/class/ai.class.php";
42require_once DOL_DOCUMENT_ROOT."/core/class/html.formai.class.php";
43
44$langs->loadLangs(array("admin", "website", "other"));
45
46$arrayofaifeatures = getListOfAIFeatures();
47$arrayofai = getListOfAIServices();
48
49// Parameters
50$action = GETPOST('action', 'aZ09');
51$backtopage = GETPOST('backtopage', 'alpha');
52$cancel = GETPOST('cancel', 'alpha');
53$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php
54
55$functioncode = GETPOST('functioncode', 'alpha');
56$pre_prompt = GETPOST('prePrompt');
57$post_prompt = GETPOST('postPrompt');
58$blacklists = GETPOST('blacklists');
59$test = GETPOST('test');
60$key = (string) GETPOST('key', 'alpha');
61
62if (empty($action)) {
63 $action = 'edit';
64}
65
66$error = 0;
67$setupnotempty = 0;
68
69// Access control
70if (!$user->admin) {
72}
73if (!isModEnabled('ai')) {
74 accessforbidden('Module AI not activated.');
75}
76
77// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only
78$useFormSetup = 1;
79
80if (!class_exists('FormSetup')) {
81 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php';
82}
83
84$form = new Form($db);
85$formSetup = new FormSetup($db);
86$aiservice = getDolGlobalString('AI_API_SERVICE', 'chatgpt');
87
88// Model used for the OCR (AI_API_<SERVICE>_MODEL_DOCPARSING) and its hardcoded fallback default.
89// The "Test OCR" button is grayed when the field is empty and no default model exists for the service.
90$ocrmodelfieldname = 'AI_API_'.strtoupper($aiservice).'_MODEL_DOCPARSING';
91$ocrmodeldefault = (!empty($arrayofai[$aiservice]['docparsing']['default']) && $arrayofai[$aiservice]['docparsing']['default'] != 'na') ? $arrayofai[$aiservice]['docparsing']['default'] : '';
92$modelforocr = getDolGlobalString($ocrmodelfieldname, $ocrmodeldefault);
93
94// Setup conf for AI model
95$formSetup->formHiddenInputs['action'] = "updatefeaturemodel";
96foreach ($arrayofaifeatures as $featurekey => $feature) {
97 $newfeaturekey = $featurekey;
98 if (preg_match('/^text/', $featurekey)) {
99 $newfeaturekey = 'textgeneration';
100 }
101 $item = $formSetup->newItem('AI_API_'.strtoupper($aiservice).'_MODEL_'.$feature["function"]); // Name of constant must end with _KEY so it is encrypted when saved into database.
102 // No default value for models when the service is 'custom': the hardcoded default has no meaning for an unknown provider.
103 if ($aiservice == 'custom') {
104 $item->nameText = $langs->trans("AI_API_MODEL_".$feature["function"]);
105 } elseif (!empty($arrayofai[$aiservice][$newfeaturekey]['default']) && $arrayofai[$aiservice][$newfeaturekey]['default'] != 'na') {
106 $item->nameText = '<span class="valignmiddle">'.$langs->trans("AI_API_MODEL_".$feature["function"]).' </span><span class="opacitymedium valignmiddle">('.$langs->trans("Default").' = '.$arrayofai[$aiservice][$newfeaturekey]['default'].')</span>';
107 if (!empty($arrayofai[$aiservice][$newfeaturekey]['examples'])) {
108 $htmltooltip = $langs->trans("Example").': '.$arrayofai[$aiservice][$newfeaturekey]['examples'];
109 $item->nameText .= $form->textwithpicto('', $htmltooltip);
110 }
111 } else {
112 $item->nameText = $langs->trans("AI_API_MODEL_".$feature["function"]).' <span class="opacitymedium">('.$langs->trans("None").')</span>';
113 }
114 // When the raw file is sent to the AI service, the docparsing model is also used by the "Import direct" screen to convert files into text
115 if ($feature["function"] == 'DOCPARSING' && getDolGlobalString('AI_USED_FOR_FILE_TO_TEXT_CONVERTION')) {
116 $item->nameText .= ' '.$form->textwithpicto('', $langs->trans("AIUsedForFileToTextConvertionModelHelp"), 1, 'info');
117 }
118 $item->cssClass = 'minwidth500 input';
119}
120
121$setupnotempty += count($formSetup->items);
122
123$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
124
125
126/*
127 * Actions
128 */
129
130// get all configs in const AI
131
132$currentConfigurationsJson = getDolGlobalString('AI_CONFIGURATIONS_PROMPT');
133$currentConfigurations = json_decode($currentConfigurationsJson, true);
134
135if ($action == 'updatefeaturemodel' && !empty($user->admin)) {
136 $formSetup->saveConfFromPost();
137 $action = 'edit';
138}
139
140if ($action == 'update' && $cancel) {
141 $action = 'edit';
142}
143
144if ($action == 'update' && !$cancel && !$test) {
145 $error = 0;
146 if (empty($functioncode)) {
147 $error++;
148 setEventMessages($langs->trans('ErrorInputRequired'), null, 'errors');
149 }
150 if (!is_array($currentConfigurations)) {
151 $currentConfigurations = [];
152 }
153
154 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
155
156 if (empty($functioncode) || (empty($pre_prompt) && empty($post_prompt) && empty($blacklists))) {
157 if (isset($currentConfigurations[$functioncode])) {
158 unset($currentConfigurations[$functioncode]);
159 }
160 } else {
161 $currentConfigurations[$functioncode] = [
162 'prePrompt' => $pre_prompt,
163 'postPrompt' => $post_prompt,
164 'blacklists' => $blacklistArray,
165 ];
166 }
167
168 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
169 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
170 if (!$error) {
171 if ($result) {
172 header("Location: ".$_SERVER['PHP_SELF']);
173 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
174 exit;
175 } else {
176 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
177 }
178 }
179
180 $action = 'edit';
181}
182
183// Update entry
184if ($action == 'updatePrompts' && !$test) {
185 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
186
187 $currentConfigurations[$key] = [
188 'prePrompt' => $pre_prompt,
189 'postPrompt' => $post_prompt,
190 'blacklists' => $blacklistArray,
191 ];
192
193 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
194 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
195 if (!$error) {
196 $action = 'edit';
197 if ($result) {
198 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
199 } else {
200 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
201 }
202 }
203}
204
205// Test entry
206if ($action == 'updatePrompts' && $test) {
207 $action = 'edit';
208}
209
210// Delete entry
211if ($action == 'confirm_deleteproperty' && GETPOST('confirm') == 'yes') {
212 if (isset($currentConfigurations[$key])) {
213 unset($currentConfigurations[$key]);
214
215 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
216 $res = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
217 if ($res) {
218 header("Location: ".$_SERVER['PHP_SELF']);
219 setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
220 exit;
221 } else {
222 setEventMessages($langs->trans("NoRecordDeleted"), null, 'errors');
223 }
224 }
225}
226
227
228// Test the OCR function (the test form is shown by clicking on the "Test OCR" button placed after the input field
229// of the model for the OCR, and this button is grayed when the field is empty and no default model exists)
230$ocrtestresult = '';
231$ocrtestfilename = '';
232$ocrtestservice = '';
233$ocrtestmodel = '';
234$ocrtestduration = 0;
235$ocrtstformvisible = 0;
236if ($action == 'testocr') {
237 // The test was just submitted, so we keep the form visible to show the result
238 $ocrtstformvisible = 1;
239 $upload_dir = $conf->ai->dir_temp;
240 dol_mkdir($upload_dir);
241
242 if (empty($_FILES['ocrtstfile']['name']) || !empty($_FILES['ocrtstfile']['error'])) {
243 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
244 } else {
245 $ocrtestfilename = (string) $_FILES['ocrtstfile']['name'];
246 $filetotest = $upload_dir.'/ocrtst-uid'.$user->id.'-'.dol_sanitizeFileName($ocrtestfilename);
247 $resupload = dol_move_uploaded_file($_FILES['ocrtstfile']['tmp_name'], $filetotest, 1, 0, (int) $_FILES['ocrtstfile']['error'], 0, 'ocrtstfile', $upload_dir);
248 if ($resupload > 0) {
249 $ai = new Ai($db);
250 $ocrtestservice = $ai->getApiService();
251 $rawfile = $ai->getPayloadToConvertRawFileIntoText($filetotest);
252 if (!empty($rawfile['error'])) {
253 setEventMessages($rawfile['message'], null, 'errors');
254 } else {
255 // The model is into the payload built by getPayloadToConvertRawFileIntoText()
256 $ocrtestmodel = (isset($rawfile['payload']['model']) && is_scalar($rawfile['payload']['model'])) ? (string) $rawfile['payload']['model'] : '';
257 $microtimestart = microtime(true);
258 $result = $ai->generateContent($rawfile['payload'], 'auto', $rawfile['function'], '');
259 $ocrtestduration = microtime(true) - $microtimestart;
260 if (is_array($result)) { // If array, there is an error
261 setEventMessages(getAIErrorMessage($result), null, 'errors');
262 } else {
263 $ocrtestresult = (string) $result;
264 }
265 }
266 dol_delete_file($filetotest);
267 } else {
268 setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
269 }
270 }
271 $action = 'edit';
272}
273
274
275/*
276 * View
277 */
278
279$formai = new FormAI($db);
280
281$help_url = '';
282$title = "AiSetup";
283
284llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin_custom_prompt');
285
286$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').'<span class="hideonsmartphone">'.$langs->trans("BackToModuleList").'</span></a>';
287
288print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
289
290// Configuration header
291$head = aiAdminPrepareHead();
292print dol_get_fiche_head($head, 'custom', $langs->trans($title), -1, "ai");
293
294$newcardbutton = dolGetButtonTitle($langs->trans('NewCustomPrompt'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=create', '', 1);
295/*
296$newbutton = '<a href="'.$_SERVER["PHP_SELF"].'?action=create" title="'.$langs->trans("NewCustomPrompt").'">';
297$newbutton .= img_picto('', 'add');
298$newbutton .= '</a>';
299*/
300
301print '<br>';
302
303print load_fiche_titre($langs->trans("AIPromptForFeatures", $arrayofai[$aiservice]['label']), $newcardbutton, '');
304
305if ($action == 'deleteproperty') {
306 $formconfirm = $form->formconfirm(
307 $_SERVER["PHP_SELF"].'?key='.urlencode(GETPOST('key', 'alpha')),
308 $langs->trans('Delete'),
309 $langs->trans('ConfirmDeleteSetup', GETPOST('key', 'alpha')),
310 'confirm_deleteproperty',
311 '',
312 0,
313 1
314 );
315 print $formconfirm;
316}
317
318if ($action == 'create') {
319 $out = '<div class="addcustomprompt">';
320
321 $out .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
322 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
323 $out .= '<input type="hidden" name="action" value="update">';
324
325
326 $out .= '<table class="noborder centpercent">';
327 $out .= '<thead>';
328 $out .= '<tr class="liste_titre">';
329 $out .= '<td>'.$langs->trans('NewCustomPrompt').'</td>';
330 $out .= '<td></td>';
331 $out .= '</tr>';
332 $out .= '</thead>';
333
334 $out .= '<tbody>';
335 $out .= '<tr class="oddeven">';
336 $out .= '<td class="col-setup-title titlefield">';
337 $out .= '<span id="module" class="spanforparamtooltip">'.$langs->trans("Feature").'</span>';
338 $out .= '</td>';
339 $out .= '<td>';
340 // Combo list of AI features
341 $out .= '<select name="functioncode" id="functioncode" class="flat minwidth500">';
342 $out .= '<option>&nbsp;</option>';
343 foreach ($arrayofaifeatures as $featurekey => $feature) {
344 $labelhtml = $langs->trans($arrayofaifeatures[$featurekey]['label']).($arrayofaifeatures[$featurekey]['status'] == 'notused' ? ' <span class="opacitymedium">('.$langs->trans("NotYetAvailable").')</span>' : "");
345 $labeltext = $langs->trans($arrayofaifeatures[$featurekey]['label']);
346 $out .= '<option value="'.dolPrintHTMLForAttribute($featurekey).'" data-html="'.dolPrintHTMLForAttribute($labelhtml).'">'.dolPrintHTML($labeltext).'</option>';
347 }
348 $out .= '</select>';
349 $out .= ajax_combobox("functioncode");
350 $out .= '<script type="text/javascript">
351 jQuery(document).ready(function() {
352 jQuery("#functioncode").on("change", function() {
353 console.log("We change value of ai function");
354 var changedValue = $(this).val();
355 console.log(changedValue);
356 var arrayplaceholder = {';
357 foreach ($arrayofaifeatures as $featurekey => $feature) {
358 $out .= dol_sanitizeKeyCode($featurekey).': \''.dol_escape_js(empty($feature['placeholder']) ? '' : $feature['placeholder']).'\',';
359 }
360 $out .= '}
361 jQuery("#prePromptInput'.dol_sanitizeKeyCode($key).'").val(arrayplaceholder[changedValue]);
362 });
363 });
364 </script>
365 ';
366
367 $out .= '</td>';
368 $out .= '</tr>';
369
370 $out .= '<tr class="oddeven">';
371 $out .= '<td class="col-setup-title">';
372 $out .= '<span id="prePrompt" class="spanforparamtooltip">';
373 $out .= $form->textwithpicto($langs->trans("Pre-Prompt"), $langs->trans("Pre-PromptHelp"));
374 $out .= '</span>';
375 $out .= '</td>';
376 $out .= '<td>';
377 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput'.$key.'" name="prePrompt" rows="2"></textarea>';
378 $out .= '</td>';
379 $out .= '</tr>';
380 $out .= '<tr class="oddeven">';
381 $out .= '<td class="col-setup-title">';
382 $out .= '<span id="postPrompt" class="spanforparamtooltip">';
383 $out .= $form->textwithpicto($langs->trans("Post-Prompt"), $langs->trans("Post-PromptHelp"));
384 $out .= '</span>';
385 $out .= '</td>';
386 $out .= '<td>';
387 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput" name="postPrompt" rows="2"></textarea>';
388 $out .= '</td>';
389 $out .= '</tr>';
390 $out .= '<tr class="oddeven">';
391 $out .= '<td class="col-setup-title">';
392 $out .= '<span id="blacklists" class="spanforparamtooltip">';
393 $out .= $form->textwithpicto($langs->trans("BlackListWords"), $langs->trans("BlackListWordsAIHelp").'.<br>'.$langs->trans("BlackListWordsHelp"));
394 $out .= '</span>';
395 $out .= '</td>';
396 $out .= '<td>';
397 $out .= '<input type="text" class="flat minwidth500 quatrevingtpercent" id="blacklistsInput" name="blacklists">';
398 $out .= '</td>';
399 $out .= '</tr>';
400 $out .= '</tbody>';
401 $out .= '</table>';
402
403 $out .= $form->buttonsSaveCancel("Add", "");
404 $out .= '</form>';
405
406 $out .= "<br>";
407 $out .= "<br>";
408
409 $out .= '</div>';
410
411 print $out;
412}
413
414if ($action == 'edit' || $action == 'create' || $action == 'deleteproperty') {
415 $out = '';
416
417 if (empty($currentConfigurations)) {
418 if ($action != 'create') {
419 print '<!-- no custom prompt-->'."\n";
420 print '<span class="opacitymedium">'.$langs->trans("None").'</span>';
421 print '<br>';
422 print '<br>';
423 }
424 print '<br>';
425 } else {
426 print '<br>';
427
428 foreach ($currentConfigurations as $confkey => $config) {
429 if (!empty($confkey) && !preg_match('/^[a-z]+$/i', $confkey)) { // Ignore empty saved setup
430 continue;
431 }
432
433 $out .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
434 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
435 $out .= '<input type="hidden" name="key" value="'.$confkey.'" />';
436 $out .= '<input type="hidden" name="action" value="updatePrompts">';
437 $out .= '<input type="hidden" name="page_y" value="">';
438
439 $out .= '<table class="noborder centpercent">';
440 $out .= '<thead>';
441 $out .= '<tr class="liste_titre">';
442 $out .= '<td class="titlefield">'.$arrayofaifeatures[$confkey]['picto'].' '.$langs->trans($arrayofaifeatures[$confkey]['label']);
443 $out .= '<a class="deletefielda reposition marginleftonly right" href="'.$_SERVER["PHP_SELF"].'?action=deleteproperty&token='.newToken().'&key='.urlencode($confkey).'">'.img_delete().'</a>';
444 $out .= '</td>';
445 $out .= '<td></td>';
446 $out .= '</tr>';
447 $out .= '</thead>';
448 $out .= '<tbody>';
449
450 $out .= '<tr class="oddeven">';
451 $out .= '<td class="col-setup-title">';
452 $out .= '<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans("Pre-Prompt").'</span>';
453 $out .= '</td>';
454 $out .= '<td>';
455 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput_'.$confkey.'" name="prePrompt" rows="2">'.$config['prePrompt'].'</textarea>';
456 $out .= '</td>';
457 $out .= '</tr>';
458
459 $out .= '<tr class="oddeven">';
460 $out .= '<td class="col-setup-title">';
461 $out .= '<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans("Post-Prompt").'</span>';
462 $out .= '</td>';
463 $out .= '<td>';
464 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput_'.$confkey.'" name="postPrompt" rows="2">'.$config['postPrompt'].'</textarea>';
465 $out .= '</td>';
466 $out .= '</tr>';
467
468 $out .= '<tr id="fichetwothirdright-'.$confkey.'" class="oddeven">';
469 $out .= '<td>'.$form->textwithpicto($langs->trans("BlackListWords"), $langs->trans("BlackListWordsHelp")).'</td>';
470 $out .= '<td>';
471 $out .= '<input type="text" class="flat minwidth500 quatrevingtpercent" id="blacklist_'.$confkey.'" name="blacklists" value="'.(isset($config['blacklists']) ? implode(', ', (array) $config['blacklists']) : '').'">';
472 $out .= '</td>';
473 $out .= '</tr>';
474
475 $out .= '<tr>';
476 $out .= '<td>'.$langs->trans("Test").'</td>';
477 $out .= '<td>';
478
479 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
480 $formmail = new FormMail($db);
481 $formmail->withaiprompt = 'html'; // set format
482
483 $showlinktoai = $confkey; // 'textgenerationemail', 'textgenerationwebpage', 'imagegeneration', ...
484 $showlinktoailabel = $langs->trans("ToTest");
485 $htmlname = $confkey;
486 $onlyenhancements = $confkey;
487 $showlinktolayout = 0;
488
489 // Fill $out
490 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
491
492 $out .= '<div id="'.$htmlname.'"></div>';
493
494 $out .= '</td>';
495 $out .= '</tr>';
496
497 $out .= '</tbody>';
498 $out .= '</table>';
499
500 $out .= '<center><input type="submit" class="button small submitBtn reposition" name="modify" data-index="'.$confkey.'" value="'.dol_escape_htmltag($langs->trans("Save")).'"/></center>';
501
502 $out .= '</form>';
503
504 $out .= '<br><br>';
505 }
506 }
507
508 print $out;
509
510 print '<br>';
511}
512
513// Availability alert: when the adapter recorded a runtime "model not found /
514// retired" provider error, warn on screen on the page where the models are
515// actually fixed, suggesting the closest model currently offered. Warn only —
516// nothing is changed automatically.
517$runfail = json_decode(getDolGlobalString('AI_MODEL_RUNTIME_FAILURE'), true);
518// Only warn about the provider and model in use now: a record left by another
519// provider describes a setup the administrator has already moved away from.
520$runfailservice = is_array($runfail) ? (string) ($runfail['service'] ?? '') : '';
521if ($runfailservice !== '' && $runfailservice !== getDolGlobalString('AI_API_SERVICE')) {
522 $runfail = null;
523}
524if (is_array($runfail) && !empty($runfail['model'])) {
525 $msg = $langs->trans(
526 "AIModelRuntimeFailureBanner",
527 dol_escape_htmltag((string) $runfail['model']),
528 dol_print_date((int) ($runfail['ts'] ?? 0), 'dayhour'),
529 dol_escape_htmltag((string) ($runfail['message'] ?? ''))
530 );
531 $modellist = getAiProviderModelList($db);
532 if (!empty($modellist['models'])) {
533 $suggest = aiSuggestClosestModel((string) $runfail['model'], $modellist['models']);
534 if ($suggest !== '') {
535 $msg .= ' '.dol_escape_htmltag($langs->trans("AIModelClosestAvailable", $suggest));
536 }
537 }
538 print info_admin($msg, 0, 0, 'warning');
539}
540
541// Custom models
542if ($action == 'edit' || $action == 'create' || $action == 'deleteproperty') {
543 print load_fiche_titre($langs->trans("AIModelForFeature", $arrayofai[$aiservice]['label']), '', '');
544
545 print $formSetup->generateOutput(true);
546}
547
548// Test form of the OCR function, hidden by default and shown by clicking on the "Test OCR" button placed after
549// the input field of the model for the OCR. The button is grayed and not clickable when the field is empty
550// and no default model exists for the service.
551if ($action == 'edit' || $action == 'create' || $action == 'deleteproperty') {
552 print '<div id="ocrtstformdiv"'.(empty($ocrtstformvisible) ? ' style="display: none"' : '').'>';
553 print '<br><br>';
554 print load_fiche_titre($langs->trans("AITestOCRFunction"), '', '');
555
556 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/form-data">';
557 print '<input type="hidden" name="token" value="'.newToken().'">';
558 print '<input type="hidden" name="action" value="testocr">';
559 print '<input type="hidden" name="page_y" value="">';
560 print '<table class="noborder centpercent">';
561 print '<thead>';
562 print '<tr class="liste_titre">';
563 print '<td class="titlefield" colspan="2">'.$langs->trans("AI_API_MODEL_DOCPARSING").' : '.dolPrintLabel($modelforocr !== '' ? $modelforocr : $langs->trans("None")).'</td>';
564 print '</tr>';
565 print '</thead>';
566 print '<tbody>';
567 print '<tr class="oddeven">';
568 print '<td class="col-setup-title">'.$langs->trans("File").'</td>';
569 print '<td><input type="file" class="flat minwidth500" name="ocrtstfile" accept="application/pdf,image/png,image/jpeg,image/gif,image/bmp,image/tiff,image/webp"></td>';
570 print '</tr>';
571 print '</tbody>';
572 print '</table>';
573 print '<center><input type="submit" class="button small reposition" name="testocr" value="'.dol_escape_htmltag($langs->trans("Test")).'"></center>';
574 print '</form>';
575
576 if ($ocrtestresult !== '') {
577 print '<br><br>';
578 // Reminder of the context of the test: file name, service, model used and duration of the AI call
579 $ocrtestservicelabel = (isset($arrayofai[$ocrtestservice]['label']) && is_string($arrayofai[$ocrtestservice]['label'])) ? $arrayofai[$ocrtestservice]['label'] : $ocrtestservice;
580 print '<div class="opacitymedium">';
581 print $langs->trans("File").' : '.dolPrintLabel($ocrtestfilename).' &nbsp;-&nbsp; '.dolPrintLabel($ocrtestservicelabel);
582 print ' &nbsp;-&nbsp; '.$langs->trans("AI_API_MODEL_DOCPARSING").' : '.dolPrintLabel($ocrtestmodel);
583 print ' &nbsp;-&nbsp; '.$langs->trans("Duration").' : '.sprintf('%.1f', $ocrtestduration).' s';
584 print '</div>';
585 print '<div class="ocrtstresult"><div style="white-space: pre-wrap; line-height: 1em;" class="neutral">'.dolPrintText($ocrtestresult).'</div></div>';
586 }
587 print '</div>';
588
589 // Button "Test OCR" placed at the end of the input field of the model for the OCR, to show or hide the test form.
590 // The button is grayed and not clickable when the field is empty and no default model exists for the service.
591 print '<script nonce="'.getNonce().'">
592var ocrmodeldefaultisset = '.($ocrmodeldefault !== '' ? 'true' : 'false').';
593document.querySelectorAll("input[name=\''.dol_escape_js($ocrmodelfieldname).'\']").forEach(function (i) {
594 var b = document.createElement("a");
595 b.href = "#";
596 b.textContent = \''.dol_escape_js($langs->trans("TestOCR")).'\';
597 var refreshbuttonstate = function () {
598 b.disabled = (!i.value && !ocrmodeldefaultisset);
599 b.className = "button smallpaddingimp".concat(b.disabled ? " disabled" : "");
600 };
601 b.onclick = function () {
602 if (b.disabled) { return false; }
603 var d = document.getElementById("ocrtstformdiv");
604 if (d) { d.style.display = (d.style.display === "none" ? "" : "none"); }
605 return false;
606 };
607 i.insertAdjacentElement("afterend", b);
608 i.addEventListener("input", refreshbuttonstate);
609 refreshbuttonstate();
610});
611</script>'."\n";
612}
613
614
615if (empty($setupnotempty)) {
616 print '<br>'.$langs->trans("NothingToSetup");
617}
618
619
620// Datalist of the provider's available model ids (fed by ajax/list_models.php,
621// cached 1h server-side): every *_MODEL_* text input gets autocompletion, which
622// avoids typos in the seven free-text model fields. The fields stay plain free
623// text (a datalist only suggests, never constrains — required for local AI
624// providers with no model-listing API, where this whole block is a no-op).
625// Active check: a saved model absent from the provider's current list gets a
626// warning picto — warn only, never block, since a listing can be incomplete
627// (aliases, fine-tunes) while the value still works.
628print '<datalist id="ai-model-ids"></datalist>'."\n";
629print '<script nonce="'.getNonce().'">
630fetch("'.dol_buildpath('/ai/ajax/list_models.php', 1).'").then(function (r) { return r.json(); }).then(function (j) {
631 if (!j || !j.models || !j.models.length) return;
632 var dl = document.getElementById("ai-model-ids");
633 j.models.forEach(function (id) { var o = document.createElement("option"); o.value = id; dl.appendChild(o); });
634 document.querySelectorAll("input[name*=\'_MODEL_\']").forEach(function (i) {
635 i.setAttribute("list", "ai-model-ids");
636 if (i.value && j.models.indexOf(i.value) < 0) {
637 // Closest-match suggestion: longest shared prefix with an offered id
638 var v = i.value.toLowerCase(), best = "", bestlen = 0;
639 j.models.forEach(function (m) {
640 var b = m.toLowerCase(), n = 0;
641 while (n < v.length && n < b.length && v.charAt(n) === b.charAt(n)) n++;
642 if (n > bestlen) { bestlen = n; best = m; }
643 });
644 var w = document.createElement("span");
645 w.className = "fas fa-exclamation-triangle pictowarning paddingleft";
646 w.title = \''.dol_escape_js($langs->trans("AIModelNotInProviderList")).'\';
647 if (best && bestlen >= 4) {
648 w.title += \' \' + \''.dol_escape_js($langs->trans("AIModelClosestAvailable", '{m}')).'\'.replace("{m}", best);
649 }
650 i.insertAdjacentElement("afterend", w);
651 }
652 });
653}).catch(function () {});
654</script>'."\n";
655
656// Page end
657print dol_get_fiche_end();
658
659llxFooter();
660$db->close();
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
getListOfAIFeatures()
Prepare admin pages header.
Definition ai.lib.php:37
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:548
getAiProviderModelList($db, $forcerefresh=false)
Return the list of model ids offered by the configured AI provider, with a 1-hour cache in the consta...
Definition ai.lib.php:681
getListOfAIServices()
Get list of available ai services.
Definition ai.lib.php:69
getAIErrorMessage($result)
Return a user-friendly error message from the error array returned by Ai\generateContent()
Definition ai.lib.php:532
aiSuggestClosestModel($missing, array $models)
Suggest the closest available model id for a model that disappeared from the provider's list: same fa...
Definition ai.lib.php:768
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class for AI feature.
Definition ai.class.php:37
Class to generate HTML forms for single email Usage: $formai = new FormAI($db) $formai->proprietes=1 ...
Class to manage generation of HTML components Only common components must be here.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
This class help you create setup render.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_sanitizeKeyCode($str)
Clean a string to use it as a key or code.
isModEnabled($module)
Is Dolibarr module enabled.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
a disabled