|
dolibarr 25.0.0-alpha
|
Library files with common functions for Ai. More...
Go to the source code of this file.
Functions | |
| getListOfAIFeatures () | |
| Prepare admin pages header. | |
| getListOfAIServices () | |
| Get list of available ai services. | |
| testAIConnection (string $service, string $key, string $url) | |
| Tests the connection to an AI service using its API key and URL by sending message "Hello". | |
| ai_validate_attachments (array $attachments, &$error) | |
| Validate chat attachments before they reach any LLM provider. | |
| aiTruncateForLog ($text, $max=60000) | |
| Trim a payload for the request log, keeping the beginning and the end. | |
| 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. | |
| getListForAISummarize () | |
| Get list for AI summarize. | |
| getListForAIRephraseStyle () | |
| Get list for AI style of writing. | |
| aiAdminPrepareHead () | |
| Prepare admin pages header. | |
| getAiAssistantProviderLabel () | |
| Resolve the AI provider/service currently configured for the AI Assistant (e.g. | |
| getAiProviderModelList ($db, $forcerefresh=false) | |
| Return the list of model ids offered by the configured AI provider, with a 1-hour cache in the constant AI_MODELS_LIST_CACHE (Anthropic GET /models, Google GET /models, OpenAI-compatible GET /models). | |
| aiSuggestClosestModel ($missing, array $models) | |
| Suggest the closest available model id for a model that disappeared from the provider's list: same family first (shared leading token, e.g. | |
| getAiChatAssistantConfig () | |
| Build the configuration array consumed by the AI Assistant chat frontend (ai/js/ai_assistant.js). | |
| getAiChatAssistantHtml ($mode='page') | |
| Build the HTML of the AI Assistant chat interface. | |
| aiCheckCsrfToken ($context='') | |
| Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints. | |
| aiStripPersonalExtrafields ($db, $payload, $elementtype) | |
| Remove extrafields flagged as personal data from an API-shaped payload. | |
Library files with common functions for Ai.
Definition in file ai.lib.php.
| 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.
| DoliDB | $db | Database object |
| User | $user | User object |
| string | $query | The query sent to the AI |
| array<string,mixed> | $response The full response from the AI | |
| string | $provider | The AI provider (e.g., 'OpenAI', 'Anthropic') |
| float | $time | Execution time in seconds |
| float | $confidence | Confidence score from the AI (if any) |
| string | $status | Status of the request (e.g., 'success', 'error') |
| string | $error | Error message, if any |
| string | $rawReq | Raw request payload |
| string | $rawRes | Raw response payload |
| array{fk_actioncomm?:int,input_hash?:string,output_hash?:string,security_hash?:string,preserve_payloads?:bool,tokens_input?:int,tokens_output?:int,model?:string} | $context Optional event link, audit metadata and provider token usage | |
| int | null | $logId | Output: inserted row id, or 0 when logging is disabled or fails |
| -out | int $logId |
Definition at line 416 of file ai.lib.php.
References $conf, $context, aiTruncateForLog(), dol_now(), dol_syslog(), and getDolGlobalInt().
Referenced by EmailCleaner\insertAiRequestLogRow(), and mcp_log_request().
| ai_validate_attachments | ( | array | $attachments, |
| & | $error ) |
Validate chat attachments before they reach any LLM provider.
The MIME type comes from the browser's File.type (client-controlled), so it is checked server-side against a strict allowlist of what every wired provider can natively consume (images and PDF). Size is bounded per attachment and in total: base64 travels inside the JSON POST body and is re-sent to the provider, so an unbounded payload is both a memory and a billing hazard. When the privacy redaction policy is enforced, attachments are refused entirely: text is masked by PrivacyGuard before a cloud call, but a document's content cannot be, so sending it would bypass the policy.
| array<int,array{mime:string,data:string}> | $attachments Parsed attachments | |
| string | $error | Set to a client-safe message when validation fails |
Definition at line 317 of file ai.lib.php.
References getDolGlobalInt(), getDolGlobalString(), and getListOfAIServices().
| aiAdminPrepareHead | ( | ) |
Prepare admin pages header.
Definition at line 531 of file ai.lib.php.
References $conf, complete_head_from_modules(), dol_buildpath(), and getDolGlobalString().
| aiCheckCsrfToken | ( | $context = '' | ) |
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
The check cannot be delegated to main.inc.php for those endpoints:
The token is read from the X-CSRF-Token header, then from the 'token' parameter (the chat frontend appends it to the endpoint URL, see getAiChatAssistantConfig() and epUrl() in ai/js/ai_assistant.js). It is compared to both session tokens because the endpoints define NOTOKENRENEWAL and therefore never rotate them: 'newtoken' is the value handed to the frontend by newToken(), 'token' is the value it has been promoted to by a page that does rotate. Both are legitimate for a call issued from a page of the current session. (Port of #39393 to develop.)
| string | $context | Endpoint name, used for logging only |
Definition at line 1065 of file ai.lib.php.
References $context, dol_syslog(), and GETPOST().
| aiStripPersonalExtrafields | ( | $db, | |
| $payload, | |||
| $elementtype ) |
Remove extrafields flagged as personal data from an API-shaped payload.
Dolibarr lets an administrator mark an extrafield as personal data (GDPR). Such values must not travel to an AI provider, but the REST objects the bridge returns carry every extrafield in array_options, and the assistant tools that read array_options directly do the same. This walks an already-serialized payload (single object or list) and drops those keys, leaving everything else untouched.
The per-element list is cached for the life of the process: a change to the personal_data flag is honored from the next request on.
| DoliDB | $db | Database handler. |
| array<mixed>|mixed | $payload Serialized API output (object or list of objects). | |
| string | $elementtype | Element type as used by ExtraFields (e.g. 'facture'). |
Definition at line 1122 of file ai.lib.php.
References aiStripPersonalExtrafields().
Referenced by aiStripPersonalExtrafields(), ToolApiBridge\execute(), ToolCategories\getCategoryDetails(), and ToolProducts\getDetails().
| aiSuggestClosestModel | ( | $missing, | |
| array | $models ) |
Suggest the closest available model id for a model that disappeared from the provider's list: same family first (shared leading token, e.g.
'gemini', 'gpt', 'claude'), then overall string similarity. Used by the warning banner of the admin models page to propose a replacement.
| string | $missing | Configured model id that is no longer offered |
| string[] | $models | Model ids currently offered by the provider |
Definition at line 711 of file ai.lib.php.
| aiTruncateForLog | ( | $text, | |
| $max = 60000 ) |
Trim a payload for the request log, keeping the beginning and the end.
Request payloads start with the tool schemas and end with what a human actually looks for: the system rules, the user query and the page context. A plain head cut removes the interesting half, so keep both sides and state how much was dropped in between.
| string | $text | Payload to trim. |
| int | $max | Maximum number of characters to keep. |
Definition at line 383 of file ai.lib.php.
References dol_strlen(), and dol_substr().
Referenced by ai_log_request().
| getAiAssistantProviderLabel | ( | ) |
Resolve the AI provider/service currently configured for the AI Assistant (e.g.
"ChatGPT (OpenAI)", "Google Gemini", "Anthropic (Claude)"), so it can be displayed in the chat header. The precise model name is intentionally not shown here, only which AI is in use.
Definition at line 601 of file ai.lib.php.
References getDolGlobalString(), and getListOfAIServices().
Referenced by getAiChatAssistantHtml().
| getAiChatAssistantConfig | ( | ) |
Build the configuration array consumed by the AI Assistant chat frontend (ai/js/ai_assistant.js).
It is serialized as JSON into the data-ai-config attribute of the chat container.
Definition at line 736 of file ai.lib.php.
References $conf, dol_buildpath(), dol_strtoupper(), dol_substr(), getDolGlobalInt(), getDolGlobalString(), getListOfAIServices(), and newToken().
Referenced by getAiChatAssistantHtml().
| getAiChatAssistantHtml | ( | $mode = 'page' | ) |
Build the HTML of the AI Assistant chat interface.
Shared by the standalone page (ai/assistant/index.php) and the topbar popover fragment (ai/assistant/popover.php) so both render the exact same chat.
| string | $mode | 'page' for the standalone full page, 'popover' for the topbar popover fragment |
Definition at line 910 of file ai.lib.php.
References $conf, dol_buildpath(), dol_escape_htmltag(), getAiAssistantProviderLabel(), and getAiChatAssistantConfig().
| getAiProviderModelList | ( | $db, | |
| $forcerefresh = false ) |
Return the list of model ids offered by the configured AI provider, with a 1-hour cache in the constant AI_MODELS_LIST_CACHE (Anthropic GET /models, Google GET /models, OpenAI-compatible GET /models).
Shared by the AJAX endpoint ai/ajax/list_models.php (datalists, chat picker) and by the model-availability warning banner of the admin models page.
| DoliDB | $db | Database handler (to store the cache constant) |
| bool | $forcerefresh | True to bypass the cache and query the live list |
Definition at line 624 of file ai.lib.php.
References $conf, dol_now(), dolDecrypt(), dolibarr_set_const(), getDolGlobalString(), getListOfAIServices(), and getURLContent().
| getListForAIRephraseStyle | ( | ) |
Get list for AI style of writing.
Definition at line 515 of file ai.lib.php.
Referenced by FormAI\getSectionForAIEnhancement().
| getListForAISummarize | ( | ) |
Get list for AI summarize.
Definition at line 493 of file ai.lib.php.
Referenced by FormAI\getSectionForAIEnhancement().
| getListOfAIFeatures | ( | ) |
Prepare admin pages header.
Definition at line 37 of file ai.lib.php.
| getListOfAIServices | ( | ) |
Get list of available ai services.
Definition at line 69 of file ai.lib.php.
Referenced by ai_validate_attachments(), Ai\generateContent(), getAiAssistantProviderLabel(), getAiChatAssistantConfig(), getAiProviderModelList(), and testAIConnection().
| testAIConnection | ( | string | $service, |
| string | $key, | ||
| string | $url ) |
Tests the connection to an AI service using its API key and URL by sending message "Hello".
This function supports multiple AI providers (Google Gemini, Anthropic Claude, and OpenAI-compatible APIs like Mistral, Groq, and DeepSeek). It constructs a minimal, provider-specific request payload and sends it to the given endpoint to verify that the API key is valid and the service is reachable.
| string | $service | The identifier of the AI service (e.g., 'google', 'anthropic', 'openai', 'mistral'). |
| string | $key | The API key for the service. |
| string | $url | The base URL of the AI service's API endpoint. |
Definition at line 213 of file ai.lib.php.
References getDolGlobalString(), getListOfAIServices(), and getURLContent().