29if (!defined(
'NOTOKENRENEWAL')) {
30 define(
'NOTOKENRENEWAL', 1);
32if (!defined(
'NOREQUIREMENU')) {
33 define(
'NOREQUIREMENU', 1);
35if (!defined(
'NOREQUIREHTML')) {
36 define(
'NOREQUIREHTML', 1);
38if (!defined(
'NOREQUIREAJAX')) {
39 define(
'NOREQUIREAJAX', 1);
43if (!defined(
'NOCSRFCHECK')) {
44 define(
'NOCSRFCHECK', 1);
47require
'../../main.inc.php';
48require_once DOL_DOCUMENT_ROOT .
'/ai/class/mcp.class.php';
49require_once DOL_DOCUMENT_ROOT .
'/ai/lib/ai.lib.php';
50require_once DOL_DOCUMENT_ROOT .
'/ai/class/llmadapter.class.php';
51require_once DOL_DOCUMENT_ROOT .
'/ai/class/privacy_guard.class.php';
52require_once DOL_DOCUMENT_ROOT .
'/core/lib/security2.lib.php';
56 http_response_code(403);
60global $db, $user,
$conf, $langs;
64if (!$user->hasRight(
'ai',
'assistant',
'use')) {
81define(
'HIGH_CONFIDENCE', 0.8);
82define(
'MEDIUM_CONFIDENCE', 0.5);
83define(
'LOW_CONFIDENCE', 0.3);
86$startTime = microtime(
true);
89$providerUsed =
"offline";
95$doRedactNames = ($doRedact >= 2);
99if (!$assistantEnabled) {
101 "tool" =>
"respond_to_user",
103 "message" =>
"AI assistant service is currently disabled. Please contact your administrator to enable it."
107 echo json_encode($response);
112 dol_syslog(
"parse_intent.php ***** BEGIN", LOG_INFO, 0,
'_ai');
115set_time_limit($timeout + 5);
119 $raw_input = file_get_contents(
'php://input');
120 $data = json_decode($raw_input,
true);
121 $query = isset($data[
'query']) ? trim($data[
'query']) :
'';
124 $isFollowup = !empty($data[
'followup']);
127 dol_syslog(
"parse_intent.php isFollowup=".($isFollowup ? 1 : 0), LOG_DEBUG, 0,
'_ai');
137 $aiPageContextLine =
'';
138 $ctxNamesToMask = array();
139 if (!empty($data[
'context']) && is_array($data[
'context'])) {
140 $ctxElement = isset($data[
'context'][
'element']) ? (string) $data[
'context'][
'element'] :
'';
141 $ctxId = isset($data[
'context'][
'id']) ? (int) $data[
'context'][
'id'] : 0;
151 'facture' => array(
'/compta/facture/class/facture.class.php',
'Facture',
'customer invoice',
'facture',
'lire'),
152 'invoice_supplier' => array(
'/fourn/class/fournisseur.facture.class.php',
'FactureFournisseur',
'supplier invoice',
'fournisseur',
'facture',
'lire'),
153 'commande' => array(
'/commande/class/commande.class.php',
'Commande',
'sales order',
'commande',
'lire'),
154 'order_supplier' => array(
'/fourn/class/fournisseur.commande.class.php',
'CommandeFournisseur',
'supplier order',
'fournisseur',
'commande',
'lire'),
155 'propal' => array(
'/comm/propal/class/propal.class.php',
'Propal',
'commercial proposal',
'propal',
'lire'),
156 'supplier_proposal' => array(
'/supplier_proposal/class/supplier_proposal.class.php',
'SupplierProposal',
'supplier proposal',
'supplier_proposal',
'lire'),
157 'societe' => array(
'/societe/class/societe.class.php',
'Societe',
'thirdparty',
'societe',
'lire'),
158 'product' => array(
'/product/class/product.class.php',
'Product',
'product or service',
'produit',
'lire'),
159 'shipping' => array(
'/expedition/class/expedition.class.php',
'Expedition',
'shipment',
'expedition',
'lire'),
160 'reception' => array(
'/reception/class/reception.class.php',
'Reception',
'reception',
'reception',
'lire'),
161 'project' => array(
'/projet/class/project.class.php',
'Project',
'project',
'projet',
'lire'),
162 'project_task' => array(
'/projet/class/task.class.php',
'Task',
'project task',
'projet',
'lire'),
163 'contrat' => array(
'/contrat/class/contrat.class.php',
'Contrat',
'contract',
'contrat',
'lire'),
164 'fichinter' => array(
'/fichinter/class/fichinter.class.php',
'Fichinter',
'intervention',
'ficheinter',
'lire'),
165 'ticket' => array(
'/ticket/class/ticket.class.php',
'Ticket',
'support ticket',
'ticket',
'read'),
166 'member' => array(
'/adherents/class/adherent.class.php',
'Adherent',
'member',
'adherent',
'lire'),
167 'expensereport' => array(
'/expensereport/class/expensereport.class.php',
'ExpenseReport',
'expense report',
'expensereport',
'lire'),
168 'holiday' => array(
'/holiday/class/holiday.class.php',
'Holiday',
'leave request',
'holiday',
'read'),
169 'don' => array(
'/don/class/don.class.php',
'Don',
'donation',
'don',
'lire'),
170 'action' => array(
'/comm/action/class/actioncomm.class.php',
'ActionComm',
'agenda event',
'agenda',
'myactions',
'read'),
171 'bom' => array(
'/bom/class/bom.class.php',
'BOM',
'bill of materials',
'bom',
'read'),
172 'mo' => array(
'/mrp/class/mo.class.php',
'Mo',
'manufacturing order',
'mrp',
'read'),
173 'stock' => array(
'/product/stock/class/entrepot.class.php',
'Entrepot',
'warehouse',
'stock',
'lire'),
174 'contact' => array(
'/contact/class/contact.class.php',
'Contact',
'contact',
'societe',
'contact',
'lire'),
175 'bank_account' => array(
'/compta/bank/class/account.class.php',
'Account',
'bank account',
'banque',
'lire'),
176 'category' => array(
'/categories/class/categorie.class.php',
'Categorie',
'category (tag)',
'categorie',
'lire'),
177 'knowledgerecord' => array(
'/knowledgemanagement/class/knowledgerecord.class.php',
'KnowledgeRecord',
'knowledge article',
'knowledgemanagement',
'knowledgerecord',
'read'),
178 'recruitmentjobposition' => array(
'/recruitment/class/recruitmentjobposition.class.php',
'RecruitmentJobPosition',
'job position',
'recruitment',
'recruitmentjobposition',
'read'),
184 $extraArr = json_decode($ctxExtra,
true);
185 if (is_array($extraArr)) {
186 foreach ($extraArr as $extra) {
187 if (!empty($extra[
'element']) && !empty($extra[
'classfile']) && !empty($extra[
'classname']) && !empty($extra[
'rights'][0]) && !isset($ctxMap[$extra[
'element']])) {
188 $ctxMap[(string) $extra[
'element']] = array(
189 (
string) $extra[
'classfile'],
190 (string) $extra[
'classname'],
191 (
string) ($extra[
'label'] ?? $extra[
'element']),
192 (
string) $extra[
'rights'][0],
193 (string) ($extra[
'rights'][1] ??
'read'),
194 (string) ($extra[
'rights'][2] ??
'')
200 if ($ctxId > 0 && isset($ctxMap[$ctxElement]) && $user->hasRight($ctxMap[$ctxElement][3], $ctxMap[$ctxElement][4], $ctxMap[$ctxElement][5] ??
'')) {
201 require_once DOL_DOCUMENT_ROOT.$ctxMap[$ctxElement][0];
202 $ctxObj =
new $ctxMap[$ctxElement][1]($db);
203 if ($ctxObj->fetch($ctxId) > 0 && (empty($ctxObj->entity) || in_array((
int) $ctxObj->entity, explode(
',',
getEntity($ctxElement))))) {
204 $ctxThirdpartyName =
'';
205 if (empty($doRedactNames) && !empty($ctxObj->socid)) {
209 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
211 if ($ctxSoc->fetch((
int) $ctxObj->socid) > 0) {
212 $ctxThirdpartyName =
" (".dol_string_nohtmltag($ctxSoc->name).
")";
215 if (empty($doRedactNames) && $ctxElement ===
'societe' && !empty($ctxObj->name)) {
216 $ctxThirdpartyName =
" (".dol_string_nohtmltag((
string) $ctxObj->name).
")";
221 $ctxNamesToMask[] = (string) $ctxObj->ref;
222 if (!empty($ctxObj->label)) {
223 $ctxNamesToMask[] = (string) $ctxObj->label;
225 if (!empty($ctxObj->name)) {
226 $ctxNamesToMask[] = (string) $ctxObj->name;
228 if (!empty($ctxObj->name_alias)) {
229 $ctxNamesToMask[] = (string) $ctxObj->name_alias;
231 $ctxRefPart =
" with ref \"".$ctxObj->ref.
"\"";
232 if (!empty($doRedactNames) && in_array($ctxElement, array(
'societe',
'contact'),
true)) {
235 $aiPageContextLine =
"The user is currently viewing the ".$ctxMap[$ctxElement][2].$ctxRefPart.
" (id ".(int) $ctxObj->id.(!empty($ctxObj->socid) ?
", thirdparty id ".(int) $ctxObj->socid.$ctxThirdpartyName : $ctxThirdpartyName).
").";
236 $aiPageContextLine .=
" When the user says \"this\"/\"it\" or refers to the current document, use these identifiers as tool arguments";
237 if ($ctxElement ===
'societe') {
238 $aiPageContextLine .=
" - in particular, this thirdparty id is the socid/customer id for any create or search tool";
240 $aiPageContextLine .=
". NEVER ask the user for ids already given here; pass names/refs the user wrote (products, etc.) directly in the matching ref arguments - tools resolve them.";
242 dol_syslog(
"AI Pro: page context accepted: ".$ctxElement.
" #".$ctxId, LOG_INFO, 0,
'_ai');
246 dol_syslog(
"AI Pro: page context rejected (fetch/entity): ".$ctxElement.
" #".$ctxId, LOG_WARNING, 0,
'_ai');
249 } elseif ($ctxId > 0) {
251 dol_syslog(
"AI Pro: page context rejected (whitelist/rights): ".$ctxElement.
" #".$ctxId, LOG_WARNING, 0,
'_ai');
253 } elseif (!empty($data[
'context'][
'dashboard']) && is_string($data[
'context'][
'dashboard'])) {
255 if (preg_match(
'/^[a-z0-9 _-]+$/i', $dash)) {
256 $aiPageContextLine =
"The user is currently on the ".$dash.
" dashboard page. Questions about \"here\"/\"this page\" concern that module's data.";
258 dol_syslog(
"AI Pro: dashboard context accepted: ".$dash, LOG_INFO, 0,
'_ai');
261 } elseif (!empty($data[
'context'][
'list']) && $ctxElement !==
'' && (!empty($data[
'context'][
'filters']) || !empty($data[
'context'][
'ids']) || !empty($data[
'context'][
'selected']))) {
268 foreach ((is_array($data[
'context'][
'filters'] ??
null) ? $data[
'context'][
'filters'] : array()) as $fk => $fv) {
269 if (!is_string($fv) || !preg_match(
'/^(search_[a-z0-9_]+|sall|search_all|sortfield|sortorder)$/', (
string) $fk)) {
281 foreach (array(
'ids' => 100,
'selected' => 25) as $idkey => $cap) {
282 if (!empty($data[
'context'][$idkey]) && is_array($data[
'context'][$idkey])) {
284 foreach ($data[
'context'][$idkey] as $v) {
288 if (count($clean) >= $cap) {
292 if (!empty($clean)) {
293 $idsPart .= ($idkey ===
'ids' ?
" Visible row ids: " :
" Checked/selected row ids (act on these when the user says the selected ones): ").implode(
',', $clean).
".";
297 if (!empty($parts) || $idsPart !==
'') {
298 $aiPageContextLine =
"The user is currently viewing the \"".preg_replace(
'/[^a-z0-9_]/',
'', $ctxElement).
"\" list".(!empty($parts) ?
" filtered by: ".implode(
', ', $parts) :
"").
".".$idsPart;
299 $aiPageContextLine .=
" To act on \"this list\"/\"these records\"/\"the selected ones\", use these ids or translate the filters into the matching arguments of the list/report tools.";
301 dol_syslog(
"AI Pro: list context accepted: ".$ctxElement.
" (".count($parts).
" filters".($idsPart !==
'' ?
", ids" :
"").
")", LOG_INFO, 0,
'_ai');
308 if (empty($query) &&
GETPOST(
'query',
'alphanohtml') ==
'/tools') {
314 echo json_encode([
"status" =>
"ok"]);
324 $attachments = array();
325 if (strpos($query,
'__FILE_ATTACHMENT__') !==
false) {
326 $query = preg_replace_callback(
327 '/__FILE_ATTACHMENT__\[([^\]]*)\]::([A-Za-z0-9+\/=\r\n]+)/',
332 static function (array $m) use (&$attachments) {
333 $attachments[] = array(
334 'mime' => ($m[1] !==
'' ? $m[1] :
'application/octet-stream'),
335 'data' => preg_replace(
'/\s+/',
'', $m[2])
337 return '[attached document]';
341 $query = trim((
string) $query);
342 if ($query ===
'' || $query ===
'[attached document]') {
343 $query =
'Analyze the attached document and describe its content.';
350 $attachmenterror =
'';
353 echo json_encode(array(
354 "tool" =>
"respond_to_user",
355 "arguments" => array(
"message" => $attachmenterror)
361 $langs->loadLangs(array(
"main",
"bills",
"orders",
"propal",
"supplier_invoice",
"supplier_order",
"projects",
"other"));
404 $dynamicStopWords = [];
405 foreach ($blockKeys as $key) {
406 $word = $langs->transnoentities($key);
413 $additionalStopWords = [
'proposition',
'devis'];
417 $commonCommands = [
'show',
'find',
'search',
'list',
'get',
'voir',
'chercher',
'affiche',
'liste',
'montre',
'lista',
'buscar'];
418 $dynamicStopWords = array_unique(array_merge($dynamicStopWords, $additionalStopWords, $commonCommands));
421 dol_syslog(
"parse_intent.php We have dynamicStopWords: ".implode(
',', $dynamicStopWords), LOG_DEBUG, 0,
'_ai');
432 $aiNamesToMask = array();
433 $tpChoices = (!empty($data[
'thirdparty_choices']) && is_array($data[
'thirdparty_choices'])) ? $data[
'thirdparty_choices'] : array();
439 $query = $aiDocuments[
'text'];
440 if (!empty($doRedactNames)) {
441 foreach ($aiDocuments[
'blocks'] as $aiDocument) {
442 $aiNamesToMask = array_merge($aiNamesToMask,
aiThirdpartyNamesToMask($db, $user, $aiDocument, $dynamicStopWords));
449 $tpReplace = array();
450 foreach ($tpFound as $mt) {
451 $aiNamesToMask[] = $mt[
'raw'];
452 $visibleIds = array();
453 foreach ($mt[
'candidates'] as $cid =>
$c) {
454 $aiNamesToMask[] =
$c[
'name'];
455 $aiNamesToMask[] =
$c[
'name_alias'];
457 $visibleIds[] = (int) $cid;
461 if (isset($tpChoices[$mt[
'phrase']]) && is_numeric($tpChoices[$mt[
'phrase']])) {
462 $chosen = (int) $tpChoices[$mt[
'phrase']];
464 if ($chosen === 0 || in_array($chosen, $visibleIds,
true)) {
465 $socidChosen = $chosen;
471 $weak = (!$mt[
'exact'] && $mt[
'words'] === 1 && (empty($doRedactNames) || !$mt[
'first']));
472 if ($socidChosen < 0) {
473 if (count($visibleIds) === 1 && !$weak) {
474 $socidChosen = $visibleIds[0];
475 } elseif (count($visibleIds) === 0) {
477 } elseif (empty($doRedactNames)) {
480 if ($tpAsk ===
null) {
486 if ($socidChosen > 0) {
487 $tpReplace[] = array($mt[
'start'], $mt[
'end'], empty($doRedactNames) ? $mt[
'raw'].
' (socid:'.$socidChosen.
')' :
'socid:'.$socidChosen);
491 if ($tpAsk !==
null) {
492 $langs->loadLangs(array(
'companies',
'other'));
494 foreach ($tpAsk[
'candidates'] as $cid =>
$c) {
495 if (!
$c[
'visible']) {
499 if (in_array(
$c[
'client'], array(1, 3))) {
500 $nat[] = $langs->transnoentitiesnoconv(
'Customer');
502 if (in_array(
$c[
'client'], array(2, 3))) {
503 $nat[] = $langs->transnoentitiesnoconv(
'Prospect');
505 if (
$c[
'fournisseur'] == 1) {
506 $nat[] = $langs->transnoentitiesnoconv(
'Supplier');
510 'label' =>
$c[
'name'].(
$c[
'name_alias'] !==
'' ?
' ('.
$c[
'name_alias'].
')' :
'').(!empty($nat) ?
' - '.implode(
', ', $nat) :
'').(
$c[
'town'] !==
'' ?
' - '.
$c[
'town'] :
'')
513 $finalResponse = array(
514 'tool' =>
'ask_for_clarification',
515 'arguments' => array(
516 'question' => $langs->transnoentitiesnoconv(count($options) === 1 ?
'AIIsThisThirdparty' :
'AIWhichThirdparty', $tpAsk[
'raw']),
517 'thirdparty_choice' => array(
'phrase' => $tpAsk[
'phrase'],
'options' => $options)
521 dol_syslog(
"parse_intent.php ".count($options).
" third parties fit '".$tpAsk[
'phrase'].
"': the user chooses before anything is sent", LOG_DEBUG, 0,
'_ai');
525 echo json_encode($finalResponse);
537 return $b[0] - $a[0];
539 foreach ($tpReplace as $r) {
540 $query = substr($query, 0, $r[0]).$r[2].substr($query, $r[1]);
545 $usageContext = array();
549 if ($doRedact && class_exists(
'PrivacyGuard')) {
551 $query = $guard->mask($doRedactNames ? $guard->maskNames($query, $aiNamesToMask) : $query);
555 if (strpos($query,
'[[') !==
false) {
556 $query .=
"\n\n(Note: tokens like [[REF_1]] or [[ADDR_2]] above are privacy-masked real values. Use them verbatim as tool argument values - they are replaced with the real data before execution. Do not refuse the task because of them and do not ask the user to re-provide masked details.)";
563 $allToolsSchema = [];
565 if ($serviceKey && $serviceKey !==
'-1') {
566 $providerUsed = $serviceKey;
567 $mcp =
new McpHandler($db, $user, $conf, McpHandler::CTX_ASSISTANT);
575 $allToolsSchema = $mcp->getToolsSchema();
576 $llmToolsBase = $mcp->getToolsSchemaForLLM();
581 if ($query ==
'/tools') {
582 $s .=
'<div class="ai-tools-debug">';
583 $s .=
'<strong>Tool families loaded ('.count($mcp->loadedTools).
')</strong>';
584 $s .=
'<ul class="small">';
585 foreach ($mcp->loadedTools as $familyKey => $familyInstance) {
587 $nbInFamily = count(array_filter($mcp->toolsByName, function ($instance) use ($familyInstance): bool {
588 return $instance === $familyInstance;
590 $s .=
'<li><strong>'.dol_escape_htmltag((
string) $familyKey).
'</strong> <span class="opacitymedium">'.
dol_escape_htmltag(get_class($familyInstance)).
' - '.$nbInFamily.
' tool(s)</span></li>';
608 if (!empty($detectedCategories)) {
610 dol_syslog(
"AI Pro: Non-Latin query classified into ".implode(
',', $detectedCategories).
". Filtering schema.", LOG_DEBUG, 0,
'_ai');
615 dol_syslog(
"AI Pro: Non-Latin language detected, no category match. Sending full (cleaned) schema.", LOG_DEBUG, 0,
'_ai');
617 $toolsSchema = $llmToolsBase;
627 dol_syslog(
"AI Pro: Latin script. Detected: " . json_encode($detectedCategories) .
". Filtered to " . count($toolsSchema) .
" tools.", LOG_DEBUG, 0,
'_ai');
641 $isLargeSchema = count($toolsSchema) > 100;
646 if ($query ==
'/tools') {
649 $s .=
'<strong>Tools sent to the LLM ('.count($toolsForLLM).
')</strong>';
650 foreach ($toolsForLLM as $toolDef) {
651 $toolName = (string) ($toolDef[
'name'] ??
'');
652 $s .=
'<details class="ai-tools-tool">';
653 $s .=
'<summary><strong>'.dol_escape_htmltag($toolName).
'</strong>';
654 if (isset($mcp->toolsByName[$toolName])) {
655 $s .=
' <span class="opacitymedium small">'.dol_escape_htmltag(get_class($mcp->toolsByName[$toolName])).
'</span>';
658 $s .=
'<div class="small">'.dol_nl2br(
dol_escape_htmltag((
string) ($toolDef[
'description'] ??
''), 1, 1)).
'</div>';
659 $s .=
'<pre class="small">'.dol_escape_htmltag((
string) json_encode($toolDef[
'parameters'] ?? array(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 1, 1).
'</pre>';
667 "tool" =>
"respond_to_user",
669 "message" => count($toolsForLLM).
" tool(s)",
678 echo json_encode($finalResponse);
685 $systemPrompt =
getDolGlobalString(
'AI_INTENT_PROMPT') ?:
"You are an Assistant for Dolibarr ERP CRM ".DOL_VERSION.
" with access to a set of tools.";
686 $systemPrompt .=
"\n\n";
688 $systemRules =
"## Rules:\n";
689 $systemRules .=
"* Respond ONLY JSON and ensure any json string does not contains special chars and are correctly json encoded.\n";
690 $systemRules .=
'* Answer a JSON message: {"type": "message", "content": "..."} or {"tool":..., "arguments":{...}}'.
"\n";
691 $systemRules .=
"* ALWAYS write user-facing text (the message/question/answer argument values) in the SAME LANGUAGE as the user's message. English context notes, tool names, or schemas never change the response language.\n";
692 $systemRules .=
"* When a tool matches the user request, use it to fulfill the user's request - never explain limitations, and never claim a capability is missing while a matching tool is listed.\n";
695 $systemRules .=
"* If you need to do a search before performing the action the user asked, answer with a search tool `api_theobjecttosearch_list` and add \"needs_followup\": true at the top level of the JSON, next to \"tool\", the result of the search is then sent back to you to perform the action. Do not add it the requested search is itself the FINAL answer.";
697 $systemRules .=
"* Only when genuinely NO tool can fulfill the request, use `respond_to_user` to say so plainly instead of guessing a business reason.\n";
698 $systemRules .=
"\n";
700 $systemPrompt .= $systemRules;
704 $toolsForLLM = array();
707 $systemPrompt .=
"## Tools:\n" . json_encode($toolsForLLM, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES).
"\n";
708 $systemPrompt .=
"\n";
710 $systemPrompt .=
"### sqlfilters format\n";
711 $systemPrompt .=
"- Criterion: (field:operator:value). Each criterion has its own parentheses.\n";
712 $systemPrompt .=
"- field: [a-zA-Z0-9_.]+ (e.g. t.ref).\n";
713 $systemPrompt .=
"- operator: = != < > <= >= like notlike in notin is isnot.\n";
714 $systemPrompt .=
"- value:\n";
715 $systemPrompt .=
" - 'text' or 'date' in single quotes, number, NULL, __NOW__ or __USER_ID__;\n";
716 $systemPrompt .=
" - never ( ) or a quote inside;\n";
717 $systemPrompt .=
" - like/notlike: % and _ wildcards;\n";
718 $systemPrompt .=
" - in/notin: comma-separated list, no parentheses (1,2,3);\n";
719 $systemPrompt .=
" - is/isnot: NULL only.\n";
720 $systemPrompt .=
"- Combining: terms joined only by AND or OR (uppercase, surrounded by spaces).\n";
721 $systemPrompt .=
" Free nesting with balanced parentheses. No NOT.\n";
722 $systemPrompt .=
" Do not mix AND and OR at the same level without parentheses.\n";
726 $systemPrompt .=
"\n";
727 $systemPrompt .=
"Valid: ((t.client:=:1) OR (t.client:in:2,3)) AND (t.nom:like:'a%')\n";
728 $systemPrompt .=
"Invalid: t.ref:=:'A' | (t.ref = 'A') | (t.status:in:(1,2)) | NOT (t.status:=:1) | ((t.a:=:1)\n";
729 $systemPrompt .=
"\n";
737 $systemPrompt .=
"## Privacy rules\n";
738 $systemPrompt .=
"Privacy masking is active: values like [[REF_1]], [[ADDR_2]], [[EMAIL_3]], [[PHONE_4]], [[ZIP_5]], [[NAME_6]] are masking real data, and socid:N is a third party given by its id. Treat them as valid values: when a tool argument needs such a datum, pass the placeholder exactly as written — it is replaced by the real value before execution. Never refuse a task because values look masked, and never invent replacements for them.";
739 $systemPrompt .=
"\n";
745 $date =
new DateTime(
'now',
new DateTimeZone(
'UTC'));
746 $systemPrompt .=
"## Context\n";
747 $systemPrompt .=
"Current UTC date: " . $date->format(
'Y-m-d\TH:i:sP').
" and User timezone: ".($_SESSION[
'dol_tz_string'] ??
'UTC').
".\n";
748 if (!empty($aiPageContextLine)) {
755 if (!empty($doRedact) && !empty($guard)) {
756 $aiPageContextLine = $guard->mask($doRedactNames ? $guard->maskNames($aiPageContextLine, $ctxNamesToMask) : $aiPageContextLine);
758 $systemPrompt .=
"Page context: ".$aiPageContextLine.
"\n";
763 $systemPrompt .=
"Current user rowid: ".((int) $user->id).
"\n";
764 $systemPrompt .=
"Resolve relative periods yourself from the current date — today, yesterday, this week, this month, last month, this quarter, this year — into explicit YYYY-MM-DD values for date parameters (e.g. this month = first day of the current month to the current date). Never ask the user for dates you can compute.\n";
770 if (preg_match(
'/^crypt:/', $apiKey)) {
774 $defUrl = $servicesList[$serviceKey][
'url'] ??
'';
787 $rawDefault = $servicesList[$serviceKey][
'textgeneration'] ??
null;
788 if (is_array($rawDefault)) {
789 $defModel = $rawDefault[
'default'] ??
'gpt-4o-mini';
791 $defModel = $rawDefault ?:
'gpt-4o-mini';
793 $prefix =
'AI_API_' . strtoupper($serviceKey);
798 if (is_array($model)) {
799 $model = $model[
'default'] ?? $defModel;
801 if (!is_string($model) || $model ===
'') {
802 $model = (string) $defModel;
806 if (!empty($data[
'model']) && is_string($data[
'model'])) {
807 $reqModel = preg_replace(
'/[^a-zA-Z0-9._:\/-]/',
'', $data[
'model']);
808 if ($reqModel !==
'' && strlen($reqModel) <= 100) {
812 $adapterType = $servicesList[$serviceKey][
'adapter_type'] ??
'openai';
818 if (!empty($apiKey)) {
821 dol_syslog(
"parse_intent.php Prepare call AI API for model=".$model, LOG_DEBUG);
823 dol_syslog(
"parse_intent.php Prepare call AI API for model=".$model, LOG_DEBUG, 0,
'_ai');
830 if (!empty($aiPageContextLine)) {
835 $aiPageContextShort = strtok($aiPageContextLine,
".").
".";
836 $query .=
"\n\n(Context: ".$aiPageContextShort.
")";
845 if (!empty($data[
'history']) && is_array($data[
'history'])) {
846 $histTurns = array_slice($data[
'history'], 0, 12);
855 foreach ($histTurns as $turn) {
856 if (is_array($turn) && !empty($turn[
'id']) && (
int) $turn[
'id'] > 0) {
857 $histIds[] = (int) $turn[
'id'];
861 if (!empty($histIds)) {
862 $sqlh =
"SELECT m.rowid, m.role, m.content_raw FROM ".$db->prefix().
"ai_chat_message as m";
863 $sqlh .=
" INNER JOIN ".$db->prefix().
"ai_chat_conversation as c ON c.rowid = m.fk_conversation";
864 $sqlh .=
" AND c.fk_user = ".((int) $user->id).
" AND c.entity = ".((int)
getEntity(
'ai'));
865 $sqlh .=
" WHERE m.rowid IN (".$db->sanitize(implode(
',', $histIds)).
")";
866 $resqlh = $db->query($sqlh);
868 while ($objh = $db->fetch_object($resqlh)) {
869 $histRows[(int) $objh->rowid] = array(
'role' => (
string) $objh->role,
'text' => (string) $objh->content_raw);
875 foreach ($histTurns as $turn) {
876 if (is_array($turn) && !empty($turn[
'id'])) {
877 $turn = $histRows[(int) $turn[
'id']] ??
null;
879 if (!is_array($turn) || empty($turn[
'text']) || !is_string($turn[
'text'])) {
882 $htext = preg_replace(
'/__FILE_ATTACHMENT__\[[^\]]*\]::[^\s]+/',
'[attachment removed]', $turn[
'text']);
883 $htext = trim((
string) $htext);
887 if ($guard && $doRedactNames) {
889 $hdata = json_decode((
string) preg_replace(
'/^\[[^\]]*\]\s*/',
'', $htext),
true);
890 $htext = $guard->maskNames($htext, array_merge($aiNamesToMask,
aiThirdpartyNamesToMask($db, $user, $htext, $dynamicStopWords, $hdata)));
896 $htext = $guard->mask($htext);
899 if ($histBudget < 0) {
902 $history[] = array(
'role' => ((($turn[
'role'] ??
'') ===
'assistant') ?
'assistant' :
'user'),
'text' => $htext);
912 $memSql =
"SELECT m.role, m.content_raw FROM ".$db->prefix().
"ai_chat_message AS m JOIN ".$db->prefix().
"ai_chat_conversation AS c ON c.rowid = m.fk_conversation WHERE c.entity IN (".
getEntity(
'ai_chat_conversation').
") AND c.fk_user = ".((int) $user->id).
" AND m.is_error = 0 AND m.content_raw <> ''";
913 $memConvId = !empty($data[
'conversation_id']) ? (int) $data[
'conversation_id'] : 0;
914 if ($memConvId > 0) {
915 $memSql .=
" AND c.rowid <> ".((int) $memConvId);
917 $memSql .=
" ORDER BY m.rowid DESC LIMIT 24";
918 $memRes = $db->query($memSql);
921 $memHistory = array();
922 while ($mobj = $db->fetch_object($memRes)) {
926 foreach (array_reverse($memTurns) as $mobj) {
927 $mtext = trim((
string) $mobj->content_raw);
932 $mtext = $doRedactNames ? $guard->maskNames($mtext, $aiNamesToMask) : $mtext;
933 $mtext = $guard->mask($mtext);
939 if ($memBudget < 0) {
942 $memHistory[] = array(
'role' => ((
string) $mobj->role ===
'assistant' ?
'assistant' :
'user'),
'text' =>
'[earlier conversation] '.$mtext);
945 $history = array_merge($memHistory, $history);
955 if (!empty($history)) {
956 $systemPrompt .=
"\n\nCONVERSATION CONTEXT: the earlier turns are context only, to resolve references needed for final action. The ONLY request to act on is the LAST user message. Never resume, redo or complete an earlier request, even one that looks unanswered or unfinished.";
959 $systemPrompt .=
"\n\nSTEP 2: the tool you chose for the last user message was already executed; its result is the last assistant turn. Now perform the action the user asked for in the last user message, with the ids found in that result. If the result does not identify one object with certainty, or the action cannot be done, answer with respond_to_user and say why. Do not run the same search again and do not add needs_followup.";
965 $systemPrompt .=
"\n\nREMINDER: write all user-facing text (message, question, answer) in the SAME LANGUAGE as the user's message.";
968 dol_syslog(
'parse_intent.php systemPrompt = '.$systemPrompt, LOG_DEBUG, 0,
'_ai');
969 dol_syslog(
'parse_intent.php query = '.$query, LOG_DEBUG, 0,
'_ai');
974 dol_syslog(
'parse_intent.php history = '.json_encode($history, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOG_DEBUG, 0,
'_ai');
979 dol_syslog(
"parse_intent.php call LLM - ".($isFollowup ?
"step ".(count($history) + 1).
": followup with the result of the search sent back by the chat" :
"step 1: initial request").
" (history turns: ".count($history).
")", LOG_INFO, 0,
'_ai');
981 $rawResponse = $adapter->generate($systemPrompt, $query,
'text', $attachments, $history);
989 $rawRequestLog = $adapter->lastRequest;
990 $rawResponseLog = $adapter->lastResponse;
994 if (!empty($adapter->lastUsage)) {
995 $usageContext = array(
996 'tokens_input' => (
int) ($adapter->lastUsage[
'input'] ?? 0),
997 'tokens_output' => (
int) ($adapter->lastUsage[
'output'] ?? 0),
998 'model' => (
string) ($adapter->lastUsage[
'model'] ?? $model),
1003 if (is_string($rawResponse) && strpos($rawResponse,
'Error:') === 0) {
1004 $errorDetails = $rawResponse;
1005 } elseif ($rawResponse) {
1007 $clean = preg_replace(
'/^```json|```$/s',
'', $rawResponse);
1008 $clean = preg_replace(
'/^<glm_block>|<\/glm_block>$/s',
'', $clean);
1009 $clean = preg_replace(
'/^_tool_call/s',
'', $clean);
1010 $clean = trim($clean);
1013 if (preg_match(
'/^\{.*\}$/s', $clean, $matches)) {
1014 $clean = $matches[0];
1015 } elseif (preg_match(
'/\{.*\}/s', $clean, $matches) && strpos($matches[0],
'"tool"') !==
false) {
1020 $clean = $matches[0];
1025 $clean = $guard->unmaskAiResponse($clean);
1029 $clean = preg_replace(
'/[\r\n]/',
' ', $clean);
1032 dol_syslog(
'parse_intent.php response var clean='.$clean, LOG_DEBUG, 0,
'_ai');
1036 if (strpos($clean,
'{') === 0 || strpos($clean,
'[') === 0) {
1042 $intentJSON = json_decode($clean,
true);
1044 dol_syslog(
'parse_intent.php intentJSON = '.var_export($intentJSON,
true), LOG_DEBUG, 0,
'_ai');
1047 if (is_array($intentJSON) && ($intentJSON[
'tool'] ??
'') ===
'respond_to_user') {
1049 if (empty($intentJSON[
'arguments'][
'message']) && isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) {
1050 foreach (array(
'content',
'answer',
'response',
'text',
'reply',
'output') as $altkey) {
1051 if (!empty($intentJSON[
'arguments'][$altkey]) && is_string($intentJSON[
'arguments'][$altkey])) {
1052 $intentJSON[
'arguments'][
'message'] = $intentJSON[
'arguments'][$altkey];
1057 if (empty($intentJSON[
'arguments'][
'message']) && empty($intentJSON[
'arguments'][
'content'])) {
1060 dol_syslog(
'parse_intent.php clean response is "respond_to_user" with a message', LOG_DEBUG, 0,
'_ai');
1062 $intentJSON[
'arguments'][
'message'] =
"I don't understand the answer produced by the IA for this request. Please rephrase or add details.";
1065 dol_syslog(
'parse_intent.php clean response is "respond_to_user" with a messageor content', LOG_DEBUG, 0,
'_ai');
1068 "tool" =>
"respond_to_user",
1070 "message" => $intentJSON[
'arguments'][
'message'] ?? ($intentJSON[
'arguments'][
'content'] ??
'')
1074 } elseif (is_array($intentJSON) && ($intentJSON[
'tool'] ??
'') ===
'ask_for_clarification' && empty($intentJSON[
'arguments'][
'question'])) {
1077 dol_syslog(
'parse_intent.php clean response is "ask_for_clarification" with a question', LOG_DEBUG, 0,
'_ai');
1080 $a = isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments']) ? $intentJSON[
'arguments'] : array();
1082 if (!empty($a[
'reason'])) {
1083 $qparts[] = (string) $a[
'reason'];
1085 if (!empty($a[
'missing_argument']) && stripos(implode(
' ', $qparts), (
string) $a[
'missing_argument']) ===
false) {
1086 $qparts[] =
"Missing: ".(string) $a[
'missing_argument'];
1088 if (empty($qparts) && !empty($a[
'message'])) {
1089 $qparts[] = (string) $a[
'message'];
1091 $intentJSON[
'arguments'][
'question'] = !empty($qparts) ? implode(
' ', $qparts) :
'Could you provide the missing information?';
1092 } elseif (is_array($intentJSON) && ($intentJSON[
'type'] ??
'') ===
'message') {
1094 if (empty($intentJSON[
'content'])) {
1096 dol_syslog(
'parse_intent.php clean response is type="message" but no content for message', LOG_DEBUG, 0,
'_ai');
1100 "tool" =>
"respond_to_user",
1102 "message" =>
'I could not produce an answer for this request. Please rephrase or add details.'
1107 dol_syslog(
'parse_intent.php clean response is type="message" with a content as message', LOG_DEBUG, 0,
'_ai');
1111 "tool" =>
"respond_to_user",
1113 "message" => $intentJSON[
'content'] ??
''
1117 } elseif (is_array($intentJSON) && ($intentJSON[
'name'] ??
'') !==
'' && ($intentJSON[
'arguments'] ??
'') !==
'') {
1120 dol_syslog(
'parse_intent.php clean response is name="toolname" and arguments="arguments"', LOG_DEBUG, 0,
'_ai');
1124 "tool" => $intentJSON[
'name'],
1126 "message" => $intentJSON[
'arguments'] ??
''
1129 } elseif (is_array($intentJSON)) {
1132 dol_syslog(
'parse_intent.php clean response is array', LOG_DEBUG, 0,
'_ai');
1135 foreach ($intentJSON as $f) {
1136 if (($f[
'type'] ??
'') ===
'function' && isset($f[
'function']) && !empty($f[
'function'][
'name']) && !empty($f[
'function'][
'arguments'])) {
1138 "tool" => $f[
'function'][
'name'] ??
'',
1139 'arguments' => json_decode($f[
'function'][
'arguments'],
true) ?? []
1147 "tool" =>
"respond_to_user",
1155 if ($guard && isset($intentJSON[
'arguments'])) {
1160 if ($intentJSON && isset($intentJSON[
'tool'])) {
1161 $validToolNames = array_column($allToolsSchema,
'name');
1162 if (!in_array($intentJSON[
'tool'], $validToolNames)) {
1164 $reqTokens = explode(
'_',
dol_strtolower((
string) $intentJSON[
'tool']));
1165 $candidates = array();
1166 foreach ($validToolNames as $realName) {
1167 if (strpos($realName, $reqTokens[0].
'_') !== 0) {
1170 if (!array_diff($reqTokens, explode(
'_', $realName))) {
1171 $candidates[] = $realName;
1174 if (count($candidates) === 1) {
1175 dol_syslog(
"parse_intent.php AI Validation: tool '".$intentJSON[
'tool'].
"' recovered to '".$candidates[0].
"'.", LOG_INFO);
1176 $intentJSON[
'tool'] = $candidates[0];
1179 if (!in_array($intentJSON[
'tool'], $validToolNames)) {
1180 dol_syslog(
"parse_intent.php AI Validation: Tool '" . $intentJSON[
'tool'] .
"' not found in filtered schema. Send error message via respond_to_user.", LOG_WARNING);
1184 "tool" =>
"respond_to_user",
1186 "message" =>
"I apologize, but the requested functionality is not currently available in the system."
1195 dol_syslog(
"parse_intent.php AI Intent: " . json_encode([
'query' => $query,
'intent' => $intentJSON]), LOG_DEBUG, 0,
'_ai');
1199 if ($intentJSON && $confidence === 0.0) {
1200 $mappedToolsSchema = array_column($toolsSchema,
null,
'name');
1204 dol_syslog(
"parse_intent.php confidence => $confidence", LOG_DEBUG, 0,
'_ai');
1212 if (!$intentJSON || !isset($intentJSON[
'tool'])) {
1213 $message = $langs->transnoentitiesnoconv(
'AICannotUnderstandRequest');
1218 if (strpos($errorDetails,
'Error:') === 0) {
1219 $reason = trim(preg_replace(
'/^Error:\s*(API|cURL #\d+)?\s*/',
'', $errorDetails));
1220 $reason =
dol_trunc(preg_replace(
'/\s+/',
' ', $reason), 200);
1225 foreach ($attachments as $att) {
1226 $hasPdf = $hasPdf || ($att[
'mime'] ===
'application/pdf');
1228 $attachmentWords =
'/\b(?:file|files|pdf|document|image_url|image|attachment|content.?type|mime|multimodal|vision)\b/i';
1229 if (!empty($attachments) && preg_match($attachmentWords, $reason)) {
1230 $message = $langs->transnoentitiesnoconv($hasPdf ?
'AIProviderRejectedPdf' :
'AIProviderRejectedAttachment',
getAiAssistantProviderLabel(), $reason);
1234 $message = $langs->transnoentitiesnoconv(
'AIModelNotAvailableAtProvider', (isset($model) ? $model :
''),
getAiAssistantProviderLabel(), $reason);
1235 } elseif (preg_match(
'/high demand|overloaded|rate limit|quota|too many requests|try again|timed? ?out|HTTP (429|502|503|504)/i', $errorDetails)) {
1236 $message = $langs->transnoentitiesnoconv(
'AIProviderBusy', $reason);
1237 } elseif (!empty($attachments) && preg_match(
'/HTTP (?:400|415|422)/', $errorDetails)) {
1238 $message = $langs->transnoentitiesnoconv($hasPdf ?
'AIProviderRejectedPdf' :
'AIProviderRejectedAttachment',
getAiAssistantProviderLabel(), $reason);
1240 $message = $langs->transnoentitiesnoconv(
'AIProviderError', $reason);
1244 "tool" =>
"respond_to_user",
1246 "message" => $message
1249 if (strpos($errorDetails,
'Error:') === 0) {
1252 $finalResponse[
'status'] =
'error';
1256 ai_log_request($db, $user, $query, $finalResponse, $providerUsed, microtime(
true) - $startTime, 0.0, $langs->transnoentitiesnoconv(
'Error'), $errorDetails, $rawRequestLog, $rawResponseLog, $usageContext);
1259 echo json_encode($finalResponse);
1264 $needsConfirmation =
false;
1265 $toolName = $intentJSON[
'tool'] ??
'';
1271 if (in_array($toolName, array(
'respond_to_user',
'reject_general_question'),
true) && isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) {
1272 if (empty($intentJSON[
'arguments'][
'message'])) {
1273 foreach (array(
'response',
'text',
'answer',
'content',
'reply',
'output') as $altkey) {
1274 if (!empty($intentJSON[
'arguments'][$altkey])) {
1275 $intentJSON[
'arguments'][
'message'] = $intentJSON[
'arguments'][$altkey];
1287 if ($toolName ===
'ask_for_confirmation' && empty($intentJSON[
'arguments'][
'original_intent'])) {
1289 foreach (array(
'message',
'action',
'question',
'text') as $altkey) {
1290 if (!empty($intentJSON[
'arguments'][$altkey]) && is_string($intentJSON[
'arguments'][$altkey])) {
1291 $question = $intentJSON[
'arguments'][$altkey];
1295 dol_syslog(
"parse_intent.php model emitted ask_for_confirmation without an action, downgraded to respond_to_user", LOG_WARNING);
1296 $toolName =
'respond_to_user';
1297 $intentJSON = array(
'tool' =>
'respond_to_user',
'arguments' => array(
'message' => ($question !==
'' ? $question : $langs->transnoentitiesnoconv(
'AICannotUnderstandRequest'))));
1301 $systemTools = array(
'respond_to_user',
'reject_general_question',
'ask_for_clarification',
'ask_for_confirmation',
'navigate_to_page',
'generate_navigation_url');
1306 $resolvedLabel =
'';
1307 if ($isFollowup && !empty($data[
'followup_result']) && is_array($data[
'followup_result']) && isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) {
1311 if ($askForConfirmation > 0) {
1312 $isModifyOperation = preg_match(
'/(create|update|delete|add|remove|modify|edit)/i', $toolName);
1314 if ($askForConfirmation == 1 && $isModifyOperation) {
1315 $needsConfirmation =
true;
1316 } elseif ($askForConfirmation == 2) {
1317 $needsConfirmation =
true;
1325 if (!$needsConfirmation && is_array($intentJSON) && $toolName !==
'' && isset($mcp) && is_object($mcp)) {
1326 $gatedTool = $mcp->toolsByName[$toolName] ??
null;
1327 $gatedArgs = (isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) ? $intentJSON[
'arguments'] : array();
1328 if (is_object($gatedTool) && method_exists($gatedTool,
'writeConfirmationPreview') && ((
string) $gatedTool->writeConfirmationPreview($toolName, $gatedArgs)) !==
McpTool::NO_WRITE) {
1329 $needsConfirmation =
true;
1334 if ($needsConfirmation && isset($mcp) && is_object($mcp)) {
1335 $gatedTool = $mcp->toolsByName[$toolName] ??
null;
1336 $gatedArgs = (isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) ? $intentJSON[
'arguments'] : array();
1337 $refusal = ($gatedTool instanceof
McpTool) ? (
string) $gatedTool->writePrecheck($toolName, $gatedArgs) :
'';
1338 if ($refusal !==
'') {
1339 $finalResponse = array(
'tool' =>
'respond_to_user',
'arguments' => array(
'message' => $refusal));
1340 ai_log_request($db, $user, $query, $finalResponse, $providerUsed, microtime(
true) - $startTime, $confidence,
'Error', $refusal, $rawRequestLog, $rawResponseLog, $usageContext);
1342 echo json_encode($finalResponse);
1348 dol_syslog(
"parse_intent.php needsConfirmation=" . (
string) $needsConfirmation, LOG_DEBUG, 0,
'_ai');
1352 if ($needsConfirmation) {
1353 $allToolsMap = !empty($allToolsSchema)
1354 ? array_column($allToolsSchema,
null,
'name')
1356 $toolDescription = $allToolsMap[$toolName][
'description'] ??
'No description available';
1357 $arguments = $intentJSON[
'arguments'] ?? [];
1365 $toolInstance = $mcp->toolsByName[$toolName] ??
null;
1366 if (is_object($toolInstance) && method_exists($toolInstance,
'writeConfirmationPreview')) {
1367 $preview = (string) $toolInstance->writeConfirmationPreview($toolName, $arguments);
1372 if ($resolvedLabel !==
'') {
1374 $action .=
' - '.dol_escape_htmltag($resolvedLabel);
1377 $confirmationResponse = [
1378 "tool" =>
"ask_for_confirmation",
1380 "action" => $action,
1381 "details" => $details,
1382 "original_intent" => $intentJSON
1387 ai_log_request($db, $user, $query, $confirmationResponse, $providerUsed, microtime(
true) - $startTime, $confidence, $langs->transnoentitiesnoconv(
"Confirm"), $errorDetails, $rawRequestLog, $rawResponseLog, $usageContext);
1390 echo json_encode($confirmationResponse);
1395 if ($confidence < LOW_CONFIDENCE) {
1397 "tool" =>
"respond_to_user",
1399 "message" =>
"I'm not confident about understanding your request. Please try rephrasing it with more specific details."
1404 ai_log_request($db, $user, $query, $finalResponse, $providerUsed, microtime(
true) - $startTime, $confidence,
'low_confidence', $errorDetails, $rawRequestLog, $rawResponseLog, $usageContext);
1407 echo json_encode($finalResponse);
1412 if ($confidence < MEDIUM_CONFIDENCE && isset($intentJSON[
'arguments'])) {
1413 $intentJSON[
'arguments'][
'_confidence_note'] =
"I'm moderately confident about this interpretation. Please verify the results.";
1422 $llmAsksFollowup = !empty($intentJSON[
'needs_followup']);
1423 unset($intentJSON[
'needs_followup']);
1424 if (!$isFollowup && isset($mcp) && is_object($mcp)
1425 && !in_array($toolName, $systemTools,
true)
1426 && !
aiIsWriteTool($mcp, $toolName, (isset($intentJSON[
'arguments']) && is_array($intentJSON[
'arguments'])) ? $intentJSON[
'arguments'] : array())
1428 $intentJSON[
'needs_followup'] = 1;
1430 if (!empty($intentJSON[
'needs_followup'])) {
1432 dol_syslog(
"parse_intent.php needs_followup on ".$toolName.
" (".($llmAsksFollowup ?
'asked by the model' :
'write asked, read answered').
")", LOG_DEBUG, 0,
'_ai');
1436 dol_syslog(
"parse_intent.php needs_followup off ".$toolName, LOG_DEBUG, 0,
'_ai');
1440 if ($resolvedLabel !==
'') {
1442 $intentJSON[
'resolved_label'] = $resolvedLabel;
1446 $finalResponse = $intentJSON;
1447 $execTime = microtime(
true) - $startTime;
1448 ai_log_request($db, $user, $query, $finalResponse, $providerUsed, $execTime, $confidence, $langs->transnoentitiesnoconv(
"Success"), $errorDetails, $rawRequestLog, $rawResponseLog, $usageContext);
1451 echo json_encode($finalResponse);
1452}
catch (Throwable $e) {
1453 $friendlyResponse = [
1454 "tool" =>
"respond_to_user",
1456 "message" =>
"I'm experiencing technical difficulties. Please try again later or contact your administrator."
1460 $realErrorForLog =
"PHP Exception: " . $e->getMessage() .
" in " . $e->getFile() .
" on line " . $e->getLine();
1462 dol_syslog(
"AI Critical Error: " . $realErrorForLog, LOG_ERR);
1464 dol_syslog(
"AI Critical Error: " . $realErrorForLog, LOG_ERR, 0,
'_ai');
1467 if (function_exists(
'ai_log_request') && is_object($db)) {
1471 $query ??
'unknown',
1474 microtime(
true) - $startTime,
1478 $rawRequestLog ??
'',
1479 $rawResponseLog ??
'',
1480 $usageContext ?? array()
1485 echo json_encode($friendlyResponse);
1501 foreach (array(
'Create',
'Add',
'Modify',
'Update',
'Delete',
'Remove',
'Validate',
'Send') as $key) {
1507 $verbs = array_merge($verbs, array(
1508 'create',
'add',
'modify',
'update',
'delete',
'remove',
'validate',
'send',
'change',
'set',
'edit',
'rename',
'close',
'cancel',
1509 'crée',
'cree',
'créer',
'creer',
'ajoute',
'ajouter',
'modifie',
'modifier',
'mets',
'met',
'mettre',
'change',
'changer',
'passe',
'passer',
1510 'supprime',
'supprimer',
'efface',
'effacer',
'retire',
'retirer',
'valide',
'valider',
'envoie',
'envoyer',
'enregistre',
'enregistrer',
'renomme',
'renommer',
'clôture',
'cloture',
'annule',
'annuler'
1513 foreach (array_unique(array_filter($verbs)) as $verb) {
1514 $escaped[] = preg_quote($verb,
'/');
1516 $pattern =
'/(^|[^\p{L}])('.implode(
'|', $escaped).
')([^\p{L}]|$)/iu';
1517 return (
bool) preg_match($pattern,
dol_strtolower((
string) $query));
1530 if (preg_match(
'/(create|update|delete|add|remove|modify|edit|validate|pay|send)/i', $name)) {
1533 $inst = $mcp->toolsByName[$name] ??
null;
1534 if (is_object($inst) && method_exists($inst,
'writeConfirmationPreview')) {
1535 return ((
string) $inst->writeConfirmationPreview($name, $args)) !==
McpTool::NO_WRITE;
1554 $rows = $readResult;
1555 if (isset($rows[
'data']) && is_array($rows[
'data'])) {
1556 $rows = $rows[
'data'];
1558 if (isset($rows[
'id']) || isset($rows[
'rowid'])) {
1559 $rows = array($rows);
1561 foreach ($rows as $row) {
1562 if (!is_array($row)) {
1565 $rowid = (int) ($row[
'id'] ?? $row[
'rowid'] ?? 0);
1566 if ($rowid > 0 && in_array($rowid, $ids,
true)) {
1567 foreach (array(
'name',
'nom',
'ref',
'label',
'subject',
'title',
'login') as $key) {
1568 if (!empty($row[$key]) && is_string($row[$key])) {
1569 return dol_trunc($row[$key], 80).
' (id '.$rowid.
')';
1587 foreach ($args as $k => $v) {
1588 if (is_string($v) && preg_match(
'/^\s*\{/', $v)) {
1589 $decoded = json_decode($v,
true);
1590 if (is_array($decoded)) {
1596 } elseif ((is_int($v) || (is_string($v) && ctype_digit($v))) && preg_match(
'/(^id$|_id$|^socid$|^fk_)/', (
string) $k)) {
1623 if ($guard ===
null) {
1627 if (is_array($data)) {
1633 function ($item) use ($guard) {
1640 if (is_string($data)) {
1641 return $guard->unmask($data);
1662 if (preg_match(
'/\p{Han}|\p{Hiragana}|\p{Katakana}|\p{Hangul}/u', $text)) {
1667 if (preg_match(
'/\p{Cyrillic}/u', $text)) {
1672 if (preg_match(
'/\p{Greek}/u', $text)) {
1677 if (preg_match(
'/\p{Arabic}/u', $text)) {
1682 if (preg_match(
'/\p{Hebrew}/u', $text)) {
1687 if (preg_match(
'/\p{Thai}/u', $text)) {
1711 if (class_exists(
'Normalizer')) {
1712 $decomposed = Normalizer::normalize($w, Normalizer::FORM_D);
1713 if ($decomposed !==
false) {
1714 $w = (string) preg_replace(
'/\p{Mn}+/u',
'', $decomposed);
1721 } elseif ($len == 5) {
1723 } elseif ($len < 3) {
1757 $langs->loadLangs(array(
"main",
"bills",
"orders",
"propal",
"companies",
"products",
"projects",
"dict",
"sendings",
"receptions",
"ticket",
"members",
"agenda",
"interventions"));
1770 'keys' => [
'Bill',
'Invoice',
'Payment',
'Cheque',
'VAT',
'BillStatusUnpaid',
'BillStatusPaid',
'BillStatusDraft',
'Member',
'Subscription'],
1771 'synonyms' => [
'paid',
'unpaid',
'pay',
'money',
'cost',
'amount',
'overdue',
'member',
'membership',
'subscription',
'cotisation',
'adhesion']
1780 'keys' => [
'Order',
'Proposal',
'Quote',
'SupplierOrder',
'OrderStatusDraft',
'Reception',
'Shipment',
'Delivery',
'Intervention'],
1781 'synonyms' => [
'sale',
'buy',
'purchase',
'contract',
'shipping',
'quote',
'reception',
'shipment',
'delivery',
'receive',
'intervention']
1789 'keys' => [
'ThirdParty',
'Customer',
'Supplier',
'Contact',
'Company',
'Ticket',
'Member',
'Subscription',
'Event',
'Agenda'],
1790 'synonyms' => [
'client',
'partner',
'address',
'phone',
'vendor',
'ticket',
'support',
'incident',
'member',
'adherent',
'membership',
'meeting',
'appointment',
'rdv',
'category',
'categorie',
'tag']
1793 'keys' => [
'Product',
'Service',
'Stock',
'Warehouse'],
1794 'synonyms' => [
'item',
'inventory',
'sku',
'location',
'qty',
'warehouse',
'category',
'categorie',
'tag']
1797 'keys' => [
'Project',
'Task',
'Ticket',
'Event',
'Agenda',
'Intervention'],
1798 'synonyms' => [
'task',
'team',
'deadline',
'planning',
'milestone',
'ticket',
'event',
'meeting',
'appointment',
'rdv',
'intervention']
1801 'keys' => [
'Report',
'Statistics',
'Turnover',
'Revenue',
'Income'],
1802 'synonyms' => [
'report',
'statistics',
'analytics',
'chart',
'total',
'turnover']
1807 static $langsEnUs =
null;
1808 if ($langsEnUs ===
null) {
1811 $langsEnUs->setDefaultLang(
'en_US');
1812 $langsEnUs->loadLangs(array(
'main',
'bills',
'companies',
'products',
'projects',
'orders',
'propal',
'stocks',
'other',
'ticket',
'members',
'agenda',
'interventions'));
1815 $detectedCategories = [];
1816 foreach ($intentMap as $category => $data) {
1818 foreach ($data[
'keys'] as $key) {
1823 foreach (array($langs->transnoentities($key), $langsEnUs->transnoentities($key)) as $trans) {
1824 if ($trans ===
'' || ($trans === $key && preg_match(
'/[A-Z]/',
dol_substr($key, 1, 200)))) {
1833 $keywords[] = $trans;
1836 $keywords = array_unique($keywords);
1841 foreach ($data[
'synonyms'] as $syn) {
1844 $keywords = array_unique($keywords);
1847 foreach ($keywords as $word) {
1852 if (preg_match(
'/\b' . preg_quote($word,
'/') .
's?\b/u', $searchQuery)) {
1853 $detectedCategories[] = $category;
1860 $needleStem = $stem;
1861 if ($needleStem !==
'' && mb_strpos($normalizedQuery, $needleStem) !==
false) {
1862 $detectedCategories[] = $category;
1868 return $detectedCategories;
1893 if (empty($activeCategories) || (count($activeCategories) === 1 && $activeCategories[0] ===
'global')) {
1897 $targetCategories = array_merge([
'global'], $activeCategories);
1900 foreach ($allTools as $tool) {
1901 $toolCats = $tool[
'categories'] ?? [
'global'];
1902 if (count(array_intersect($toolCats, $targetCategories)) > 0) {
1903 if (count($activeCategories) > 0 && $toolCats === [
'global']) {
1906 $filtered[] = $tool;
1910 if (count($filtered) < 3) {
1911 dol_syslog(
"AI Filter: Too few tools (" . count($filtered) .
"). Reverting to full schema.", LOG_WARNING);
1930 foreach ($tools as $tool) {
1939 $desc = $tool[
'description'];
1942 $toolParams = $tool[
'parameters'] ?? $tool[
'inputSchema'] ?? [];
1944 if ($isLargeSchema && isset($toolParams[
'properties']) && is_array($toolParams[
'properties'])) {
1945 $requiredList = $toolParams[
'required'] ?? [];
1946 $newProperties = [];
1948 foreach ($toolParams[
'properties'] as $propKey => $propData) {
1949 $isRequired = in_array($propKey, $requiredList);
1959 if (!$isRequired && isset($propData[
'default'])) {
1964 if (isset($propData[
'type']) && $propData[
'type'] ===
'string') {
1965 unset($propData[
'type']);
1971 if (isset($propData[
'description'])) {
1972 unset($propData[
'description']);
1982 if (isset($propData[
'type']) && $propData[
'type'] ===
'object' && isset($propData[
'properties'])) {
1983 unset($propData[
'properties']);
1984 unset($propData[
'required']);
1985 $propData[
'description'] =
"JSON object";
1988 $newProperties[$propKey] = $propData;
1991 $toolParams[
'properties'] = $newProperties;
1994 unset($toolParams[
'type']);
1995 unset($toolParams[
'additionalProperties']);
1999 'name' => $tool[
'name'],
2000 'description' => $desc,
2001 'parameters' => $toolParams
2027 $factors[
'parse_success'] = 0.4;
2031 $hasRequiredFields = !empty($intentJSON[
'tool']) && !empty($intentJSON[
'arguments']);
2032 $factors[
'completeness'] = $hasRequiredFields ? 0.3 : 0.0;
2035 $isValidSchema =
false;
2038 if (isset($intentJSON[
'tool']) && isset($toolsSchema[$intentJSON[
'tool']])) {
2040 $schema = $toolsSchema[$intentJSON[
'tool']][
'parameters']
2041 ?? $toolsSchema[$intentJSON[
'tool']][
'inputSchema']
2045 $providedParams = array_keys($intentJSON[
'arguments'] ?? []);
2048 $properties = $schema[
'properties'] ?? [];
2049 $requiredList = $schema[
'required'] ?? [];
2051 $missingParams = [];
2054 foreach ($properties as $paramKey => $paramDetails) {
2056 if (in_array($paramKey, $requiredList)) {
2058 if (!in_array($paramKey, $providedParams)) {
2059 $missingParams[] = $paramKey;
2065 $isValidSchema = empty($missingParams);
2068 $factors[
'schema_validation'] = $isValidSchema ? 0.2 : 0.0;
2071 $qualityScore = 0.0;
2072 if (is_string($rawResponse)) {
2074 if (!preg_match(
'/error|fail|unable|cannot|sorry/i', $rawResponse)) {
2075 $qualityScore += 0.05;
2079 if (isset($intentJSON[
'tool']) && isset($toolsSchema[$intentJSON[
'tool']])) {
2080 $qualityScore += 0.05;
2083 $factors[
'response_quality'] = $qualityScore;
2086 $confidence = array_sum($factors);
2089 return max(0.0, min(1.0, $confidence));
2100 $formattedArgs = [];
2101 foreach ($arguments as $key => $value) {
2102 if (is_array($value)) {
2103 $formattedArgs[] =
"- {$key}: " . (empty($value) ?
"(empty)" : json_encode($value, JSON_PRETTY_PRINT));
2105 $formattedArgs[] =
"- {$key}: {$value}";
2108 return implode(
"\n", $formattedArgs);
2120 if (preg_match(
'/^(create|update|delete|list|show|find|search|get|view|validate|send)/i', $toolName, $matches)) {
2121 return strtolower($matches[1]);
2123 return 'perform this action';
getListOfAIServices()
Get list of available ai services.
aiRestoreDocumentBlocks($text, array $blocks)
Put back, unchanged, the documents set aside by aiExtractDocumentBlocks().
aiFindThirdpartiesInText($db, $user, $text, $nature='', $stopwords=array(), $maxwords=80)
Third parties named in a text, by the words of their name or trade name (name_alias),...
aiThirdpartyNamesToMask($db, $user, $text, $stopwords=array(), $data=null)
Every form of the third party names found in a text or carried by a tool result, to mask with Privacy...
aiThirdpartyNatureHint($text, $langs)
Nature of third party a text points at, from its own words: "supplier" when it speaks of a supplier (...
ai_validate_attachments(array $attachments, &$error)
Validate chat attachments before they reach any LLM provider.
ai_log_request($db, $user, $query, array $response, $provider, float $time, float $confidence, $status, $error='', $rawReq='', $rawRes='', array $context=array(), &$logId=null)
Log AI Request with Raw Payloads.
aiExtractDocumentBlocks($text, $langs)
Set aside the documents a chat message carries, so what is done to the request (third parties resolve...
getAiAssistantProviderLabel()
Resolve the AI provider/service currently configured for the AI Assistant (e.g.
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
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 handle MCP (Model Context Protocol).
Class to manage privacy data masking and unmasking.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
static isModelUnavailableError(string $msg)
Tell if a provider error message says the requested model is unknown, retired or not available (not a...
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
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_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
extractActionFromTool($toolName)
Extract action from tool name.
formatArgumentsForDisplay($arguments)
Format arguments for display in confirmation.
isComplexScript(string $text)
Detects if the query uses Non-Latin Scripts.
aiIsWriteTool($mcp, $name, array $args)
Does the tool write (create / update / delete / ...)?
calculateConfidence($intentJSON, $toolsSchema, $rawResponse)
Calculate confidence score based on multiple factors.
classifyIntentUniversal(string $query, Translate $langs)
Detect intent categories from a user query.
catch(Throwable $e) aiQueryAsksForWrite($query, $langs)
Does the user's message ask for a write (create / update / delete / ...)? Translated keys of the curr...
aiNormalizeForMatch($word, $asStem=false)
Normalize a keyword or query for inflection-tolerant non-Latin matching.
aiLabelOfResolvedObject(array $readResult, array $writeArgs)
Name of the object a write targets, taken from the read result that produced its id (so the confirmat...
filterToolsProfessional(array $allTools, array $activeCategories)
Filter a list of tools based on active intent categories.
recursiveUnmaskValues($data, ?PrivacyGuard $guard)
Recursively unmask values in a dataset.
cleanToolSchemaForLLM(array $tools, bool $isLargeSchema=false)
Compresses tool schema by removing optional parameters with defaults and stripping descriptions,...
aiIdsOfArguments(array $args)
Ids passed to a tool: values of the id-like keys (id, *_id, socid, fk_*), also inside nested arrays a...
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.