dolibarr 25.0.0-alpha
ai.lib.php File Reference

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.
 

Detailed Description

Library files with common functions for Ai.

Definition in file ai.lib.php.

Function Documentation

◆ ai_log_request()

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.

Parameters
DoliDB$dbDatabase object
User$userUser object
string$queryThe query sent to the AI
array<string,mixed>$response The full response from the AI
string$providerThe AI provider (e.g., 'OpenAI', 'Anthropic')
float$timeExecution time in seconds
float$confidenceConfidence score from the AI (if any)
string$statusStatus of the request (e.g., 'success', 'error')
string$errorError message, if any
string$rawReqRaw request payload
string$rawResRaw 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$logIdOutput: inserted row id, or 0 when logging is disabled or fails
-outint $logId
Returns
int Return 0

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()

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.

Parameters
array<int,array{mime:string,data:string}>$attachments Parsed attachments
string$errorSet to a client-safe message when validation fails
Returns
bool True when all attachments may be sent

Definition at line 317 of file ai.lib.php.

References getDolGlobalInt(), getDolGlobalString(), and getListOfAIServices().

◆ aiAdminPrepareHead()

aiAdminPrepareHead ( )

Prepare admin pages header.

Returns
array<array{0:string,1:string,2:string}>

Definition at line 531 of file ai.lib.php.

References $conf, complete_head_from_modules(), dol_buildpath(), and getDolGlobalString().

◆ aiCheckCsrfToken()

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:

  • it only runs when MAIN_SECURITY_CSRF_WITH_TOKEN is enabled (it is optional),
  • it reads the token from $_GET/$_POST only,
  • and when the token is present but invalid it merely clears $_POST, which does not protect an endpoint reading its payload from the raw php://input body.

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.)

Parameters
string$contextEndpoint name, used for logging only
Returns
void Emits a 403 JSON response and exits when the token is invalid

Definition at line 1065 of file ai.lib.php.

References $context, dol_syslog(), and GETPOST().

◆ aiStripPersonalExtrafields()

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.

Parameters
DoliDB$dbDatabase handler.
array<mixed>|mixed$payload Serialized API output (object or list of objects).
string$elementtypeElement type as used by ExtraFields (e.g. 'facture').
Returns
array<mixed>|mixed Payload without personal-data extrafields.

Definition at line 1122 of file ai.lib.php.

References aiStripPersonalExtrafields().

Referenced by aiStripPersonalExtrafields(), ToolApiBridge\execute(), ToolCategories\getCategoryDetails(), and ToolProducts\getDetails().

◆ aiSuggestClosestModel()

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.

Parameters
string$missingConfigured model id that is no longer offered
string[]$modelsModel ids currently offered by the provider
Returns
string Closest model id, or '' when nothing is similar enough to be a useful suggestion

Definition at line 711 of file ai.lib.php.

◆ aiTruncateForLog()

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.

Parameters
string$textPayload to trim.
int$maxMaximum number of characters to keep.
Returns
string Trimmed payload, unchanged when short enough.

Definition at line 383 of file ai.lib.php.

References dol_strlen(), and dol_substr().

Referenced by ai_log_request().

◆ getAiAssistantProviderLabel()

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.

Returns
string The provider label, or '' if no service is configured

Definition at line 601 of file ai.lib.php.

References getDolGlobalString(), and getListOfAIServices().

Referenced by getAiChatAssistantHtml().

◆ getAiChatAssistantConfig()

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.

Returns
array{mode:string,labels:array<string,string>,baseUrl:string,token:string,userInitial:string}

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()

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.

Parameters
string$mode'page' for the standalone full page, 'popover' for the topbar popover fragment
Returns
string HTML content

Definition at line 910 of file ai.lib.php.

References $conf, dol_buildpath(), dol_escape_htmltag(), getAiAssistantProviderLabel(), and getAiChatAssistantConfig().

◆ getAiProviderModelList()

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.

Parameters
DoliDB$dbDatabase handler (to store the cache constant)
bool$forcerefreshTrue to bypass the cache and query the live list
Returns
array{service:string,models:string[]} Active service key and its sorted model ids (empty list when the provider is not configured, offers no listing API, or the call fails)

Definition at line 624 of file ai.lib.php.

References $conf, dol_now(), dolDecrypt(), dolibarr_set_const(), getDolGlobalString(), getListOfAIServices(), and getURLContent().

◆ getListForAIRephraseStyle()

getListForAIRephraseStyle ( )

Get list for AI style of writing.

Returns
array<int|string,mixed>

Definition at line 515 of file ai.lib.php.

Referenced by FormAI\getSectionForAIEnhancement().

◆ getListForAISummarize()

getListForAISummarize ( )

Get list for AI summarize.

Returns
array<int|string,mixed>

Definition at line 493 of file ai.lib.php.

Referenced by FormAI\getSectionForAIEnhancement().

◆ getListOfAIFeatures()

getListOfAIFeatures ( )

Prepare admin pages header.

Returns
array<string,array<string,string>>

Definition at line 37 of file ai.lib.php.

◆ getListOfAIServices()

getListOfAIServices ( )

Get list of available ai services.

Returns
array<int|string,mixed>

Definition at line 69 of file ai.lib.php.

Referenced by ai_validate_attachments(), Ai\generateContent(), getAiAssistantProviderLabel(), getAiChatAssistantConfig(), getAiProviderModelList(), and testAIConnection().

◆ 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.

Parameters
string$serviceThe identifier of the AI service (e.g., 'google', 'anthropic', 'openai', 'mistral').
string$keyThe API key for the service.
string$urlThe base URL of the AI service's API endpoint.
Returns
array{success: bool, message: string} An associative array indicating the result of the test.
  • 'success' is true on a successful connection (HTTP 2xx), false otherwise.
  • 'message' provides details, such as "OK (HTTP 200)" or an error description.

Definition at line 213 of file ai.lib.php.

References getDolGlobalString(), getListOfAIServices(), and getURLContent().