dolibarr 25.0.0-alpha
assistant.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 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Coryright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2026 Nick Fragoulis
8 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY, without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30require '../../main.inc.php';
39require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
40require_once DOL_DOCUMENT_ROOT . "/core/class/html.form.class.php";
41require_once DOL_DOCUMENT_ROOT . "/core/class/doleditor.class.php";
42require_once DOL_DOCUMENT_ROOT . "/ai/lib/ai.lib.php";
43require_once DOL_DOCUMENT_ROOT . "/core/lib/functions2.lib.php";
44require_once DOL_DOCUMENT_ROOT . "/core/lib/security.lib.php";
45
46
47$langs->loadLangs(array("admin", "website", "other"));
48
49// Access control
50if (!$user->admin) {
52}
53if (!isModEnabled('ai')) {
54 accessforbidden('Module AI not activated.');
55}
56
57// Parameters
58$action = GETPOST('action', 'aZ09');
59$backtopage = GETPOST('backtopage', 'alpha');
60
61
66// Main Settings
67if ($action == 'update') {
68 $error = 0;
69
70 if (GETPOSTISSET('AI_ASK_FOR_CONFIRMATION')) {
71 $res = dolibarr_set_const($db, "AI_ASK_FOR_CONFIRMATION", GETPOSTINT("AI_ASK_FOR_CONFIRMATION"), 'int', 0, '', $conf->entity);
72 if ($res <= 0) $error++;
73 }
74
75 if (GETPOSTISSET('AI_CHAT_CONTEXT_AUTO_EXCHANGES')) {
76 $res = dolibarr_set_const($db, "AI_CHAT_CONTEXT_AUTO_EXCHANGES", max(0, GETPOSTINT("AI_CHAT_CONTEXT_AUTO_EXCHANGES")), 'int', 0, '', $conf->entity);
77 if ($res <= 0) {
78 $error++;
79 }
80 }
81
82 if (GETPOSTISSET('AI_LOG_RETENTION')) {
83 $res = dolibarr_set_const($db, "AI_LOG_RETENTION", GETPOST("AI_LOG_RETENTION"), 'int', 0, '', $conf->entity);
84 if ($res <= 0) {
85 $error++;
86 }
87 }
88
89 if (GETPOSTISSET('AI_DEFAULT_INPUT_MODE')) {
90 $res = dolibarr_set_const($db, "AI_DEFAULT_INPUT_MODE", GETPOST("AI_DEFAULT_INPUT_MODE"), 'chaine', 0, '', $conf->entity);
91 if ($res <= 0) {
92 $error++;
93 }
94 }
95
96 if (GETPOSTISSET('AI_PRIVACY_REDACTION')) {
97 $res = dolibarr_set_const($db, "AI_PRIVACY_REDACTION", min(2, max(0, GETPOSTINT("AI_PRIVACY_REDACTION"))), 'int', 0, '', $conf->entity);
98 if ($res <= 0) {
99 $error++;
100 }
101 }
102
103 if (GETPOSTISSET('AI_INTENT_PROMPT')) {
104 $res = dolibarr_set_const($db, "AI_INTENT_PROMPT", GETPOST("AI_INTENT_PROMPT"), 'chaine', 0, '', $conf->entity);
105 if ($res <= 0) {
106 $error++;
107 }
108 }
109
110 if ($error) {
111 setEventMessages($langs->trans("ErrorSavingSettings"), null, 'errors');
112 } else {
113 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
114 }
115
116 header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home");
117 exit;
118}
119
120// Test connection
121if ($action == 'test_provider') {
122 $service = GETPOST('service_key', 'aZ09');
123 if ($service) {
124 $credential = getDolGlobalString('AI_API_' . strtoupper($service) . '_KEY');
125 $url = getDolGlobalString('AI_API_' . strtoupper($service) . '_URL');
126
127 // Decrypt if needed
128 if (preg_match('/^crypted:/', $credential)) {
129 $credential = dol_decode(substr($credential, 8));
130 } elseif (preg_match('/^dolcrypt:/', $credential)) {
131 $credential = dolDecrypt($credential, '');
132 }
133
134 // Only proceed if the key is valid (decrypted or not encrypted)
135 if ($credential !== null) {
136 $res = testAIConnection($service, $credential, $url);
137
138 if ($res['success']) {
139 setEventMessages($langs->trans("ConnectionSuccessful") . $res['message'], null, 'mesgs');
140 } else {
141 setEventMessages($langs->trans("ConnectionFailed") . $res['message'], null, 'errors');
142 }
143 }
144 }
145}
146
147// External Access Settings
148if ($action == 'update_external') {
149 $error = 0;
150
151 $user_id = GETPOSTINT("AI_MCP_USER_ID");
152 if (GETPOSTISSET('AI_MCP_USER_ID')) {
153 $res = dolibarr_set_const($db, "AI_MCP_USER_ID", $user_id, 'int', 0, '', $conf->entity);
154 if ($res <= 0) {
155 $error++;
156 }
157 }
158
159 if ($error) {
160 setEventMessages($langs->trans("ErrorSavingSettings"), null, 'errors');
161 } else {
162 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
163 }
164
165 header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home");
166 exit;
167}
168
169// Generate New API Key
170if ($action == 'generate_key') {
171 $newKey = dolGetRandomBytes(64);
172
173 if (empty($newKey)) {
174 setEventMessages($langs->trans("KeyGenerationFailed"), null, 'errors');
175 } else {
176 if (dolibarr_set_const($db, 'AI_MCP_API_KEY', $newKey, 'chaine', 0, '', $conf->entity) > 0) {
177 setEventMessages($langs->trans("KeyGenerationSuccessfull"), null, 'mesgs');
178 } else {
179 setEventMessages($langs->trans("KeySaveFailed"), null, 'errors');
180 }
181 }
182}
183
184
185/*
186 * VIEW
187 */
188
190$title = "AiSetup";
191
192llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin');
193
194$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>';
195
196print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
197
198
199$head = aiAdminPrepareHead();
200print dol_get_fiche_head($head, 'assistant', "MCP Server", -1, "ai");
201
202//print '<span class="opacitymedium">' . $langs->trans("ConfigAssistantHelp") . '</span><br><br>';
203
204$form = new Form($db);
205
206// Load Current Values
207$apiKey = getDolGlobalString('AI_MCP_API_KEY');
208
209// Default Prompt Logic
210$defaultPromptText = " ROLE: Dolibarr ERP AI.
211GOAL: Map user intent to specific JSON commands.
212
213CONSTRAINTS:
2141. OUTPUT: Single valid JSON object ONLY. No Markdown. No text.
215 Format: {\"tool\": \"tool_name\", \"arguments\": {\"argument_name\": \"argument_value\", ...}}
2162. TOOLS: Use ONLY provided tools. If no tool or thirdparty fits, you must first use 'respond_to_user' to inform user.
2173. ARGS: strict adherence to schema. Do not invent parameters.
2184. MISSING INFO: If a required argument (like an ID) is missing, use 'ask_for_clarification'.
2195. SAFETY: For DELETE/UPDATE actions, you MUST use 'ask_for_confirmation'.";
220
221$currentPrompt = getDolGlobalString('AI_INTENT_PROMPT', $defaultPromptText);
222
223// Settings
224print '<div class="neutral">';
225//print '<table class="noborder centpercent">';
226
227// Enable/Disable
228//print '<tr class="oddeven">';
229//print '<td class="titlefield" width="30%">'
230print $form->textwithpicto($langs->trans('EnableAssistant'), $langs->trans('DisableAssistant'));
231//print '</td>';
232//print '<td>';
233print ' &nbsp; ';
234print ajax_constantonoff('AI_ASSISTANT_ENABLED', array(), null, 0, 0, 1);
235//print ' <span class="opacitymedium">' . $langs->trans('DisableMCPAI') . '</span>';
236//print '</td>';
237//print '</tr>';
238
239//print '</table>';
240print '</div>';
241
242print '<br>';
243print '<br>';
244
245if (getDolGlobalString('AI_ASSISTANT_ENABLED')) {
246 print load_fiche_titre($langs->trans("PrivateModeTitle"), '', 'fas fa-lock');
247
248 print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
249 print '<input type="hidden" name="token" value="'.newToken().'">';
250 print '<input type="hidden" name="action" value="update">';
251
252 print '<div class="div-table-responsive-no-min">';
253 print '<table class="noborder centpercent">';
254
255 // Input Mode
256 print '<tr class="oddeven">';
257 print '<td>';
258 print $form->textwithpicto('Default Interface', $langs->trans("InputMethodHelp"));
259 print '</td>';
260 print '<td>';
261 // Same values and pictos than the engine selector of the assistant (see ai.lib.php)
262 $labelcloud = $langs->trans('OptionCloudFast') . ' - ' . $langs->trans('OptionCloudFasthelp');
263 $input_modes = [
264 'text' => array('label' => $langs->trans('OptionTextOnly'), 'data-html' => img_picto('', 'fa-keyboard', 'class="pictofixedwidth"') . dolPrintHTML($langs->trans('OptionTextOnly'))),
265 'cloud' => array('label' => $labelcloud, 'data-html' => img_picto('', 'fa-cloud', 'class="pictofixedwidth"') . dolPrintHTML($labelcloud)),
266 ];
267 // The local whisper mode is experimental: only offered with the experimental features enabled
268 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 1) {
269 $labelwhisper = $langs->trans('OptionWhisperLocal') . ' - ' . $langs->trans('OptionWhisperLocalhelp');
270 $input_modes['whisper'] = array('label' => $labelwhisper, 'data-html' => img_picto('', 'fa-microphone', 'class="pictofixedwidth"') . dolPrintHTML($labelwhisper) . ' <span class="opacitymedium">(' . $langs->trans('VersionExperimental') . ')</span>');
271 }
272 $defaultinputmode = getDolGlobalString('AI_DEFAULT_INPUT_MODE');
273 if ($defaultinputmode == 'native') { // Old value saved before the key was aligned with the assistant selector
274 $defaultinputmode = 'cloud';
275 }
276 print $form->selectarray('AI_DEFAULT_INPUT_MODE', $input_modes, $defaultinputmode, 0, 0, 0, '', 0, 0, 0, '', 'minwidth300');
277 print '</td>';
278 print '</tr>';
279
280 // Enhanced Privacy control
281 print '<tr class="oddeven">';
282 print '<td>' . $form->textwithpicto($langs->trans('ObfuscatePIIData'), $langs->trans("RedactionHelp")) . '</td>';
283 print '<td>';
284 $redaction_options = [
285 '0' => $langs->trans("RedactionNone"),
286 '1' => $langs->trans("RedactionSensitiveData"),
287 '2' => $langs->trans("RedactionSensitiveDataAndThirdparties")
288 ];
289 print $form->selectarray('AI_PRIVACY_REDACTION', $redaction_options, getDolGlobalInt('AI_PRIVACY_REDACTION', 0), 0, 0, 0, '', 0, 0, 0, '', 'minwidth300');
290 print '</td>';
291 print '</tr>';
292
293 // Confirmation Level
294 print '<tr class="oddeven">';
295 print '<td>' . $form->textwithpicto($langs->trans("AskConfirmation"), $langs->trans("AskConfirmationHelp")).'</td>';
296 print '<td>';
297 $confirmation_options = [
298 '0' => $langs->trans("ConfirmNever"),
299 '1' => $langs->trans("ConfirmWriteOnly"),
300 '2' => $langs->trans("ConfirmAlways")
301 ];
302 print $form->selectarray('AI_ASK_FOR_CONFIRMATION', $confirmation_options, getDolGlobalInt('AI_ASK_FOR_CONFIRMATION', 1), 0, 0, 0);
303 print '</td>';
304 print '</tr>';
305
306 // Context window of the chat
307 print '<tr class="oddeven">';
308 print '<td>' . $form->textwithpicto($langs->trans("AIContextAutoExchanges"), $langs->trans("AIContextAutoExchangesHelp")) . '</td>';
309 print '<td><input class="width50" type="number" min="0" name="AI_CHAT_CONTEXT_AUTO_EXCHANGES" value="' . getDolGlobalInt('AI_CHAT_CONTEXT_AUTO_EXCHANGES', 2) . '"></td>';
310 print '</tr>';
311
312 // API tools in the palette of the chat input (the palette itself is always on)
313 print '<tr class="oddeven">';
314 print '<td>' . $form->textwithpicto($langs->trans("AIPaletteApiTools"), $langs->trans("AIPaletteApiToolsHelp")) . '</td>';
315 print '<td>';
316 print ajax_constantonoff('AI_PALETTE_API_TOOLS');
317 print '</td>';
318 print '</tr>';
319
320 // Logging
321 print '<tr class="oddeven">';
322 print '<td>' . $langs->trans('EnableLogging') . '</td>';
323 print '<td>';
324 print ajax_constantonoff('AI_LOG_REQUESTS');
325 print ' &nbsp; <a href="' . DOL_URL_ROOT . '/ai/admin/log_viewer.php" target="_blank" style="padding-top: 4px; padding-bottom: 4px;">'.$langs->trans("ViewLogs").'</a>';
326 print '</td>';
327 print '</tr>';
328
329 print '<tr class="oddeven">';
330 print '<td>' . $langs->trans("LogRetention") . '</td>';
331 print '<td><input class="width50" type="number" name="AI_LOG_RETENTION" value="' . getDolGlobalInt('AI_LOG_RETENTION', 30) . '"> (0 = Forever)</td>';
332 print '</tr>';
333
334 // System Prompt
335 print '<tr class="oddeven">';
336 print '<td colspan="2">';
337 print $form->textwithpicto($langs->trans("SystemPrompt"), $langs->trans("SystemPromptHelp")) . '<br><br>';
338 $doleditor = new DolEditor('AI_INTENT_PROMPT', $currentPrompt, '', 250, 'dolibarr_notes', 'In', false, false, true, ROWS_8, '90%');
339 $doleditor->Create();
340 print '</td>';
341 print '</tr>';
342
343 print '</table>';
344 print '</div>';
345
346 print '<div class="center"><input type="submit" class="button" value="'.$langs->trans("Save").'"></div>';
347 print '</form>';
348
349 print '<br>';
350 print '<br>';
351
352
353 // AI Provider Config and Connection testing
354 $services = getListOfAIServices();
355 $currentService = getDolGlobalString('AI_API_SERVICE');
356
357 print load_fiche_titre($langs->trans("AIProviderConfigTitle"), '', 'fa fa-plug');
358
359 if ((string) $currentService == '-1') {
360 print '<div class="warning">'.$langs->trans("NoAIProviderSelected").' <a href="'.dol_buildpath('/ai/admin/setup.php', 1).'">'.$langs->trans("ConfigureHere").'</a></div>';
361 } else {
362 print '<div class="div-table-responsive-no-min">';
363 print '<table class="noborder centpercent">';
364
365 print '<tr class="oddeven"><td class="titlefield">'.$langs->trans("AIProvider").'</td><td>'.$services[$currentService]['label'].'</td></tr>';
366
367 $prefix = 'AI_API_'.strtoupper($currentService);
368 $modelVal = getDolGlobalString($prefix.'_MODEL_TEXT', $services[$currentService]['textgeneration']['default']);
369
370 print '<tr class="oddeven"><td>'.$langs->trans("AI_API_MODEL").'</td><td>'.$modelVal.'</td></tr>';
371 print '</table></div>';
372
373 print '<div class="center">';
374
375 if ($currentService && $currentService !== '-1') {
376 print '<a class="reposition button smallpaddingimp" href="'.$_SERVER['PHP_SELF'].'?action=test_provider&token='.newToken().'&service_key='.urlencode($currentService).'">'.$langs->trans('TestConnection').'</a>';
377 }
378
379 print '</div>';
380 }
381
382 print '<br><br>';
383
384 // External Access Configuration
385 /*
386 print load_fiche_titre($langs->trans("AiMcpExternalAccess"), '', 'fas fa-lock-open');
387
388 print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
389 print '<input type="hidden" name="token" value="'.newToken().'">';
390 print '<input type="hidden" name="action" value="update_external">';
391
392 print '<div class="div-table-responsive-no-min">';
393 print '<table class="noborder centpercent">';
394
395 // Service User
396 print '<tr class="oddeven">';
397 print '<td>Service User <span class="fa fa-info-circle" title="' . $langs->trans("UserPermissionsTooltip") . '"></span></td>';
398 print '<td>';
399 print '<div style="display: flex; align-items: center;">';
400 print $form->select_dolusers(getDolGlobalInt('AI_MCP_USER_ID'), 'AI_MCP_USER_ID', 1);
401 print ' <input type="submit" class="button" value="'.$langs->trans("Save").'" style="margin-left: 20px;">';
402 print '</div>';
403 print '<span class="opacitymedium small">' . $langs->trans("DedicatedUserRecommendation") . '</span>';
404 print '</td>';
405 print '</tr>';
406
407 print '<tr class="oddeven">';
408 print '<td width="30%">API Key</td>';
409 print '<td>';
410 if ($apiKey) {
411 print '<input type="text" id="apikey" value="'.$apiKey.'" readonly style="width:400px; padding:6px; background:#f4f4f4; border:1px solid #ccc; color:#555;">';
412 print ' <a class="button smallpaddingimp" href="'.$_SERVER["PHP_SELF"].'?action=generate_key&token='.newToken().'">Generate New Key</a>';
413 } else {
414 print '<span class="opacitymedium">' . $langs->trans("NoKeyWarning") . '</span>';
415 print ' <a class="button smallpaddingimp" href="' . $_SERVER["PHP_SELF"] . '?action=generate_key&token=' . newToken() . '">' . $langs->trans("GenerateKey") . '</a>';
416 }
417 print '</td>';
418 print '</tr>';
419
420 $endpoint = dol_buildpath('/ai/server/mcp_server.php', 3);
421
422 print '<tr class="oddeven">';
423 print '<td>Endpoint URL</td>';
424 print '<td>';
425 print '<input type="text" id="endpoint" value="'.$endpoint.'" readonly style="width:600px; border:none; background:transparent;">';
426 print '</td>';
427 print '</tr>';
428
429 print '</table>';
430 print '</div>';
431
432 print '</form>';
433
434 // Configuration Examples
435 print '<br>';
436 print '<div style="background:#fcfcfc; border:1px solid #eee; padding:15px; border-radius:5px;">';
437 print '<strong>' . $langs->trans("ClaudeDesktopConfig") . '</strong><br>';
438 print '<pre style="background:#333; color:#fff; padding:10px; border-radius:4px; overflow:auto; margin-top:10px;">';
439 echo htmlspecialchars('
440 {
441 "mcpServers": {
442 "dolibarr": {
443 "command": "node",
444 "args": ["/path/to/mcp-bridge.js"],
445 "env": {
446 "DOLIBARR_URL": "'.$endpoint.'",
447 "DOLIBARR_API_KEY": "'.($apiKey ? $apiKey : "YOUR_KEY_HERE").'"
448 }
449 }
450 }
451 }');
452 print '</pre>';
453 print '</div>';
454 */
455}
456
457print dol_get_fiche_end();
458
459llxFooter();
460$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).
testAIConnection(string $service, string $key, string $url)
Tests the connection to an AI service using its API key and URL by sending message "Hello".
Definition ai.lib.php:213
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:548
getListOfAIServices()
Get list of available ai services.
Definition ai.lib.php:69
if( $action=='update') if($action=='test_provider') if( $action=='update_external') if($action=='generate_key') $help_url
ACTIONS.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
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 to manage a WYSIWYG editor.
Class to manage generation of HTML components Only common components must be here.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dolGetRandomBytes($length)
Return a string of random bytes (hexa string) with length = $length for cryptographic purposes.
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.