30require
'../../main.inc.php';
38require_once DOL_DOCUMENT_ROOT.
"/core/lib/admin.lib.php";
39require_once DOL_DOCUMENT_ROOT.
"/ai/lib/ai.lib.php";
40require_once DOL_DOCUMENT_ROOT.
"/core/class/html.formai.class.php";
42$langs->loadLangs(array(
"admin",
"website",
"other"));
48$action =
GETPOST(
'action',
'aZ09');
49$backtopage =
GETPOST(
'backtopage',
'alpha');
50$cancel =
GETPOST(
'cancel',
'alpha');
51$modulepart =
GETPOST(
'modulepart',
'aZ09');
53$functioncode =
GETPOST(
'functioncode',
'alpha');
54$pre_prompt =
GETPOST(
'prePrompt');
55$post_prompt =
GETPOST(
'postPrompt');
56$blacklists =
GETPOST(
'blacklists');
58$key = (string)
GETPOST(
'key',
'alpha');
78if (!class_exists(
'FormSetup')) {
79 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formsetup.class.php';
87$formSetup->formHiddenInputs[
'action'] =
"updatefeaturemodel";
88foreach ($arrayofaifeatures as $featurekey => $feature) {
89 $newfeaturekey = $featurekey;
90 if (preg_match(
'/^text/', $featurekey)) {
91 $newfeaturekey =
'textgeneration';
93 $item = $formSetup->newItem(
'AI_API_'.strtoupper($aiservice).
'_MODEL_'.$feature[
"function"]);
94 if (!empty($arrayofai[$aiservice][$newfeaturekey][
'default']) && $arrayofai[$aiservice][$newfeaturekey][
'default'] !=
'na') {
95 $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>';
96 if (!empty($arrayofai[$aiservice][$newfeaturekey][
'examples'])) {
97 $htmltooltip = $langs->trans(
"Example").
': '.$arrayofai[$aiservice][$newfeaturekey][
'examples'];
98 $item->nameText .= $form->textwithpicto(
'', $htmltooltip);
101 $item->nameText = $langs->trans(
"AI_API_MODEL_".$feature[
"function"]).
' <span class="opacitymedium">('.$langs->trans(
"None").
')</span>';
103 $item->cssClass =
'minwidth500 input';
106$setupnotempty += count($formSetup->items);
108$dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
118$currentConfigurations = json_decode($currentConfigurationsJson,
true);
120if ($action ==
'updatefeaturemodel' && !empty($user->admin)) {
121 $formSetup->saveConfFromPost();
125if ($action ==
'update' && $cancel) {
129if ($action ==
'update' && !$cancel && !$test) {
131 if (empty($functioncode)) {
133 setEventMessages($langs->trans(
'ErrorInputRequired'),
null,
'errors');
135 if (!is_array($currentConfigurations)) {
136 $currentConfigurations = [];
139 $blacklistArray = array_filter(array_map(
'trim', explode(
',', $blacklists)));
141 if (empty($functioncode) || (empty($pre_prompt) && empty($post_prompt) && empty($blacklists))) {
142 if (isset($currentConfigurations[$functioncode])) {
143 unset($currentConfigurations[$functioncode]);
146 $currentConfigurations[$functioncode] = [
147 'prePrompt' => $pre_prompt,
148 'postPrompt' => $post_prompt,
149 'blacklists' => $blacklistArray,
153 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
154 $result =
dolibarr_set_const($db,
'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson,
'chaine', 0,
'',
$conf->entity);
157 header(
"Location: ".$_SERVER[
'PHP_SELF']);
158 setEventMessages($langs->trans(
"SetupSaved"),
null,
'mesgs');
161 setEventMessages($langs->trans(
"ErrorUpdating"),
null,
'errors');
169if ($action ==
'updatePrompts' && !$test) {
170 $blacklistArray = array_filter(array_map(
'trim', explode(
',', $blacklists)));
172 $currentConfigurations[$key] = [
173 'prePrompt' => $pre_prompt,
174 'postPrompt' => $post_prompt,
175 'blacklists' => $blacklistArray,
178 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
179 $result =
dolibarr_set_const($db,
'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson,
'chaine', 0,
'',
$conf->entity);
183 setEventMessages($langs->trans(
"SetupSaved"),
null,
'mesgs');
185 setEventMessages($langs->trans(
"ErrorUpdating"),
null,
'errors');
191if ($action ==
'updatePrompts' && $test) {
196if ($action ==
'confirm_deleteproperty' &&
GETPOST(
'confirm') ==
'yes') {
197 if (isset($currentConfigurations[$key])) {
198 unset($currentConfigurations[$key]);
200 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
201 $res =
dolibarr_set_const($db,
'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson,
'chaine', 0,
'',
$conf->entity);
203 header(
"Location: ".$_SERVER[
'PHP_SELF']);
204 setEventMessages($langs->trans(
"RecordDeleted"),
null,
'mesgs');
207 setEventMessages($langs->trans(
"NoRecordDeleted"),
null,
'errors');
222llxHeader(
'', $langs->trans($title), $help_url,
'', 0, 0,
'',
'',
'',
'mod-ai page-admin_custom_prompt');
224$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>';
232$newcardbutton =
dolGetButtonTitle($langs->trans(
'NewCustomPrompt'),
'',
'fa fa-plus-circle', $_SERVER[
"PHP_SELF"].
'?action=create',
'', 1);
239print
load_fiche_titre($langs->trans(
"AIPromptForFeatures", $arrayofai[$aiservice][
'label']), $newcardbutton,
'');
242if ($action ==
'deleteproperty') {
243 $formconfirm = $form->formconfirm(
244 $_SERVER[
"PHP_SELF"].
'?key='.urlencode(
GETPOST(
'key',
'alpha')),
245 $langs->trans(
'Delete'),
246 $langs->trans(
'ConfirmDeleteSetup',
GETPOST(
'key',
'alpha')),
247 'confirm_deleteproperty',
255if ($action ==
'create') {
256 $out =
'<div class="addcustomprompt">';
258 $out .=
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
259 $out .=
'<input type="hidden" name="token" value="'.newToken().
'">';
260 $out .=
'<input type="hidden" name="action" value="update">';
263 $out .=
'<table class="noborder centpercent">';
265 $out .=
'<tr class="liste_titre">';
266 $out .=
'<td>'.$langs->trans(
'NewCustomPrompt').
'</td>';
272 $out .=
'<tr class="oddeven">';
273 $out .=
'<td class="col-setup-title titlefield">';
274 $out .=
'<span id="module" class="spanforparamtooltip">'.$langs->trans(
"Feature").
'</span>';
278 $out .=
'<select name="functioncode" id="functioncode" class="flat minwidth500">';
279 $out .=
'<option> </option>';
280 foreach ($arrayofaifeatures as $featurekey => $feature) {
281 $labelhtml = $langs->trans($arrayofaifeatures[$featurekey][
'label']).($arrayofaifeatures[$featurekey][
'status'] ==
'notused' ?
' <span class="opacitymedium">('.$langs->trans(
"NotYetAvailable").
')</span>' :
"");
282 $labeltext = $langs->trans($arrayofaifeatures[$featurekey][
'label']);
283 $out .=
'<option value="'.dolPrintHTMLForAttribute($featurekey).
'" data-html="'.dolPrintHTMLForAttribute($labelhtml).
'">'.dolPrintHTML($labeltext).
'</option>';
287 $out .=
'<script type="text/javascript">
288 jQuery(document).ready(function() {
289 jQuery("#functioncode").on("change", function() {
290 console.log("We change value of ai function");
291 var changedValue = $(this).val();
292 console.log(changedValue);
293 var arrayplaceholder = {';
294 foreach ($arrayofaifeatures as $featurekey => $feature) {
298 jQuery("#prePromptInput'.dol_sanitizeKeyCode($key).
'").val(arrayplaceholder[changedValue]);
307 $out .=
'<tr class="oddeven">';
308 $out .=
'<td class="col-setup-title">';
309 $out .=
'<span id="prePrompt" class="spanforparamtooltip">';
310 $out .= $form->textwithpicto($langs->trans(
"Pre-Prompt"), $langs->trans(
"Pre-PromptHelp"));
314 $out .=
'<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput'.$key.
'" name="prePrompt" rows="2"></textarea>';
317 $out .=
'<tr class="oddeven">';
318 $out .=
'<td class="col-setup-title">';
319 $out .=
'<span id="postPrompt" class="spanforparamtooltip">';
320 $out .= $form->textwithpicto($langs->trans(
"Post-Prompt"), $langs->trans(
"Post-PromptHelp"));
324 $out .=
'<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput" name="postPrompt" rows="2"></textarea>';
327 $out .=
'<tr class="oddeven">';
328 $out .=
'<td class="col-setup-title">';
329 $out .=
'<span id="blacklists" class="spanforparamtooltip">';
330 $out .= $form->textwithpicto($langs->trans(
"BlackListWords"), $langs->trans(
"BlackListWordsAIHelp").
'.<br>'.$langs->trans(
"BlackListWordsHelp"));
334 $out .=
'<input type="text" class="flat minwidth500 quatrevingtpercent" id="blacklistsInput" name="blacklists">';
340 $out .= $form->buttonsSaveCancel(
"Add",
"");
351if ($action ==
'edit' || $action ==
'create' || $action ==
'deleteproperty') {
354 if (empty($currentConfigurations)) {
355 if ($action !=
'create') {
356 print
'<!-- no custom prompt-->'.
"\n";
357 print
'<span class="opacitymedium">'.$langs->trans(
"None").
'</span>';
365 foreach ($currentConfigurations as $confkey => $config) {
366 if (!empty($confkey) && !preg_match(
'/^[a-z]+$/i', $confkey)) {
370 $out .=
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
371 $out .=
'<input type="hidden" name="token" value="'.newToken().
'">';
372 $out .=
'<input type="hidden" name="key" value="'.$confkey.
'" />';
373 $out .=
'<input type="hidden" name="action" value="updatePrompts">';
374 $out .=
'<input type="hidden" name="page_y" value="">';
376 $out .=
'<table class="noborder centpercent">';
378 $out .=
'<tr class="liste_titre">';
379 $out .=
'<td class="titlefield">'.$arrayofaifeatures[$confkey][
'picto'].
' '.$langs->trans($arrayofaifeatures[$confkey][
'label']);
380 $out .=
'<a class="deletefielda reposition marginleftonly right" href="'.$_SERVER[
"PHP_SELF"].
'?action=deleteproperty&token='.
newToken().
'&key='.urlencode($confkey).
'">'.img_delete().
'</a>';
387 $out .=
'<tr class="oddeven">';
388 $out .=
'<td class="col-setup-title">';
389 $out .=
'<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans(
"Pre-Prompt").
'</span>';
392 $out .=
'<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput_'.$confkey.
'" name="prePrompt" rows="2">'.$config[
'prePrompt'].
'</textarea>';
396 $out .=
'<tr class="oddeven">';
397 $out .=
'<td class="col-setup-title">';
398 $out .=
'<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans(
"Post-Prompt").
'</span>';
401 $out .=
'<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput_'.$confkey.
'" name="postPrompt" rows="2">'.$config[
'postPrompt'].
'</textarea>';
405 $out .=
'<tr id="fichetwothirdright-'.$confkey.
'" class="oddeven">';
406 $out .=
'<td>'.$form->textwithpicto($langs->trans(
"BlackListWords"), $langs->trans(
"BlackListWordsHelp")).
'</td>';
408 $out .=
'<input type="text" class="flat minwidth500 quatrevingtpercent" id="blacklist_'.$confkey.
'" name="blacklists" value="'.(isset($config[
'blacklists']) ? implode(
', ', (array) $config[
'blacklists']) :
'').
'">';
413 $out .=
'<td>'.$langs->trans(
"Test").
'</td>';
416 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
418 $formmail->withaiprompt =
'html';
420 $showlinktoai = $confkey;
421 $showlinktoailabel = $langs->trans(
"ToTest");
422 $htmlname = $confkey;
423 $onlyenhancements = $confkey;
424 $showlinktolayout = 0;
427 include DOL_DOCUMENT_ROOT.
'/core/tpl/formlayoutai.tpl.php';
429 $out .=
'<div id="'.$htmlname.
'"></div>';
437 $out .=
'<center><input type="submit" class="button small submitBtn reposition" name="modify" data-index="'.$confkey.
'" value="'.
dol_escape_htmltag($langs->trans(
"Save")).
'"/></center>';
457$runfailservice = is_array($runfail) ? (string) ($runfail[
'service'] ??
'') :
'';
458if ($runfailservice !==
'' && $runfailservice !==
getDolGlobalString(
'AI_API_SERVICE')) {
461if (is_array($runfail) && !empty($runfail[
'model'])) {
462 $msg = $langs->trans(
463 "AIModelRuntimeFailureBanner",
469 if (!empty($modellist[
'models'])) {
471 if ($suggest !==
'') {
472 $msg .=
' '.dol_escape_htmltag($langs->trans(
"AIModelClosestAvailable", $suggest));
479if ($action ==
'edit' || $action ==
'create' || $action ==
'deleteproperty') {
480 print
load_fiche_titre($langs->trans(
"AIModelForFeature", $arrayofai[$aiservice][
'label']),
'',
'');
482 print $formSetup->generateOutput(
true);
486if (empty($setupnotempty)) {
487 print
'<br>'.$langs->trans(
"NothingToSetup");
499print
'<datalist id="ai-model-ids"></datalist>'.
"\n";
500print
'<script nonce="'.getNonce().
'">
501fetch("'.
dol_buildpath(
'/ai/ajax/list_models.php', 1).
'").then(function (r) { return r.json(); }).then(function (j) {
502 if (!j || !j.models || !j.models.length) return;
503 var dl = document.getElementById("ai-model-ids");
504 j.models.forEach(function (id) { var o = document.createElement("option"); o.value = id; dl.appendChild(o); });
505 document.querySelectorAll("input[name*=\'_MODEL_\']").forEach(function (i) {
506 i.setAttribute("list", "ai-model-ids");
507 if (i.value && j.models.indexOf(i.value) < 0) {
508 // Closest-match suggestion: longest shared prefix with an offered id
509 var v = i.value.toLowerCase(), best = "", bestlen = 0;
510 j.models.forEach(function (m) {
511 var b = m.toLowerCase(), n = 0;
512 while (n < v.length && n < b.length && v.charAt(n) === b.charAt(n)) n++;
513 if (n > bestlen) { bestlen = n; best = m; }
515 var w = document.createElement("span");
516 w.className = "fas fa-exclamation-triangle pictowarning paddingleft";
517 w.title = \''.
dol_escape_js($langs->trans(
"AIModelNotInProviderList")).
'\';
518 if (best && bestlen >= 4) {
519 w.title += \
' \' + \''.dol_escape_js($langs->trans(
"AIModelClosestAvailable",
'{m}')).
'\'.replace(
"{m}", best);
521 i.insertAdjacentElement(
"afterend", w);
524}).
catch(
function () {});
528print dol_get_fiche_end();
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.
aiAdminPrepareHead()
Prepare admin pages header.
getAiProviderModelList($db, $forcerefresh=false)
Return the list of model ids offered by the configured AI provider, with a 1-hour cache in the consta...
getListOfAIServices()
Get list of available ai services.
aiSuggestClosestModel($missing, array $models)
Suggest the closest available model id for a model that disappeared from the provider's list: same fa...
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
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.
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_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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_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.
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)
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.