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.
 
 getAIErrorMessage ($result)
 Return a user-friendly error message from the error array returned by Ai\generateContent()
 
 aiAdminPrepareHead ()
 Prepare admin pages header.
 
 getAiAssistantProviderLabel ()
 Resolve the AI provider/service currently configured for the AI Assistant (e.g.
 
 getAiAssistantDefaultModel ()
 Resolve the text model used by the AI Assistant when the picker is on "Auto" (same resolution order as assistant/parse_intent.php).
 
 getAiAssistantProviderUrl ()
 Resolve the API URL used by the AI Assistant for the configured provider (same resolution order as assistant/parse_intent.php).
 
 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', $openconversation=0)
 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.
 
 aiNameWords ($text)
 Words of a text as the third party matcher compares them: runs of letters or digits, lower-cased and without accents, with their byte offsets in the text.
 
 aiThirdpartyNatureHint ($text, $langs)
 Nature of third party a text points at, from its own words: "supplier" when it speaks of a supplier (or vendor), "customer" when it speaks of a customer, '' when it says neither or both.
 
 aiNameWordsEqual ($a, $b)
 Whether two words of a name are the same word: equal, or the same word with a different ending ("solution" / "solutions") one starts with the other, both have at least 4 letters, and they differ by at most 2 letters.
 
 aiNameWordsInSequence ($phrase, $name)
 Whether the words of a phrase appear in a name one after the other, in the same order each word compared with aiNameWordsEqual().
 
 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), in any order and not necessarily all of them: "Anthropic" names "Anthropic Ireland, Limited", "Jensen LLC" and "Jensen Jon" name "Jon Jensen LLC". Words may differ by their ending ("solution" / "solutions").
 
 aiExtractDocumentBlocks ($text, $langs)
 Set aside the documents a chat message carries, so what is done to the request (third parties resolved to their ids) is never done to the document itself.
 
 aiRestoreDocumentBlocks ($text, array $blocks)
 Put back, unchanged, the documents set aside by aiExtractDocumentBlocks().
 
 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 PrivacyGuard\maskNames(): the words as written, the names and trade names of the matching third parties, and the values of the name keys of a result ("name", "nom", "name_alias", "socname", ...).
 
 aiUnitIdFromName ($db, $name)
 Unit id from the word a user used for it: code, short label or label, in the user's language, singular or plural ("piece", "pieces", "pcs").
 
 aiParseDocumentCommand ($db, $text, $user=null, $side='sell')
 Read a one-line document command of the chat palette, e.g.
 
 aiParseDocumentGroup ($db, array $tokens, array $asProduct, $user, $side)
 Lines of one group of a document command: quantity, optional unit, product, optional unit price.
 
 aiDocumentProductExists ($db, $user, $typed, $side)
 Whether the words of a command line name at least one product the user may put on that kind of document.
 
 aiFindProducts ($db, $user, $text, $side='sell', $limit=10)
 Products of the catalogue matching what a user typed: every word must be in the ref or the label, in any order.
 
 aiRecentProducts ($db, $user, $socid, $side='sell', $limit=8)
 Products of a third party's latest documents, newest first: what is most likely to be sold (or bought) again.
 
 aiPaletteToolTitle ($langs, $name, $route)
 Plain name of a tool for the palette of the chat: "Get invoice" rather than api_invoices_get.
 
 aiPaletteToolDescription ($description)
 Description of a tool for the palette: without the sentence every generated bridge tool repeats, which says nothing to the person choosing.
 

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 aiCommandAnswer(), 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 548 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 1260 of file ai.lib.php.

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

◆ aiDocumentProductExists()

aiDocumentProductExists ( $db,
$user,
$typed,
$side )

Whether the words of a command line name at least one product the user may put on that kind of document.

Parameters
DoliDB$dbDatabase handler
User$userUser
string$typedProduct as typed ("#" and quotes allowed)
string$side'sell' or 'buy'
Returns
bool

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

References aiFindProducts().

Referenced by aiParseDocumentGroup().

◆ aiExtractDocumentBlocks()

aiExtractDocumentBlocks ( $text,
$langs )

Set aside the documents a chat message carries, so what is done to the request (third parties resolved to their ids) is never done to the document itself.

The chat wraps each attached document between the DocContextIntro and DocContextOutro texts, in the language of the user: they are matched in that language and in English.

Parameters
string$textMessage as received
Translate$langsLanguage of the user
Returns
array{text:string, blocks:array<string,string>} The message with a placeholder per document, and the documents by placeholder

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

◆ aiFindProducts()

aiFindProducts ( $db,
$user,
$text,
$side = 'sell',
$limit = 10 )

Products of the catalogue matching what a user typed: every word must be in the ref or the label, in any order.

A product whose ref or label is exactly the text comes first. Only products the user may read, on sale (or on purchase for a supplier document).

Parameters
DoliDB$dbDatabase handler
User$userUser
string$textWhat was typed
string$side'sell' (customer documents) or 'buy' (supplier documents)
int$limitRows to return
Returns
array<int, array{id:int, ref:string, label:string, price:float, fk_unit:int, stock:float, exact:bool}>

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

References dol_strtolower(), and dol_syslog().

Referenced by aiDocumentProductExists().

◆ aiFindThirdpartiesInText()

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), in any order and not necessarily all of them: "Anthropic" names "Anthropic Ireland, Limited", "Jensen LLC" and "Jensen Jon" name "Jon Jensen LLC". Words may differ by their ending ("solution" / "solutions").

Nothing is guessed here: a phrase is reported only when every word of it is a word of the name, and every third party it fits is returned so the caller can ask when there are several. A phrase that is a whole name keeps only the third parties carrying that whole name. Keywords and legal forms (LLC, ΑΕ...) never identify a third party on their own.

Parameters
DoliDB$dbDatabase handler
User$userUser the text comes from (visibility of candidates)
string$textText to scan
string$nature'supplier' or 'customer' to narrow candidates when that leaves at least one, '' for all
array<string>$stopwords Words never accepted alone as a partial name (translated keywords)
int$maxwordsDistinct words looked up, in order of appearance
Returns
array<int, array{phrase:string, raw:string, start:int, end:int, exact:bool, first:bool, words:int, candidates:array<int, array{id:int, name:string, name_alias:string, client:int, fournisseur:int, town:string, visible:bool}>}>
Parameters
array{id:int,name:string,name_alias:string,client:int,fournisseur:int,town:string,visible:bool}$c Candidate
Returns
bool

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

References $c, $id, aiNameWords(), aiNameWordsEqual(), aiNameWordsInSequence(), dol_strlen(), dol_substr(), and dol_syslog().

Referenced by aiThirdpartyNamesToMask(), ToolApiBridge\normaliseWriteArgs(), ToolApiBridge\resolveWriteTarget(), and ToolApiBridge\writePrecheck().

◆ aiNameWords()

aiNameWords ( $text)

Words of a text as the third party matcher compares them: runs of letters or digits, lower-cased and without accents, with their byte offsets in the text.

"Anthropic Ireland, Limited" and "anthropic ireland limited" give the same words.

Parameters
string$textText to split
Returns
array<int, array{0:string, 1:int, 2:int}> Normalised word, start offset, end offset

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

References dol_string_unaccent(), and dol_strtolower().

Referenced by aiFindThirdpartiesInText(), and aiThirdpartyNatureHint().

◆ aiNameWordsEqual()

aiNameWordsEqual ( $a,
$b )

Whether two words of a name are the same word: equal, or the same word with a different ending ("solution" / "solutions") one starts with the other, both have at least 4 letters, and they differ by at most 2 letters.

Parameters
string$aNormalised word (see aiNameWords())
string$bNormalised word
Returns
bool

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

References dol_strlen().

Referenced by aiFindThirdpartiesInText(), and aiNameWordsInSequence().

◆ aiNameWordsInSequence()

aiNameWordsInSequence ( $phrase,
$name )

Whether the words of a phrase appear in a name one after the other, in the same order each word compared with aiNameWordsEqual().

Parameters
string[]$phraseNormalised words of the phrase
string[]$nameNormalised words of the name
Returns
bool

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

References aiNameWordsEqual().

Referenced by aiFindThirdpartiesInText().

◆ aiPaletteToolDescription()

aiPaletteToolDescription ( $description)

Description of a tool for the palette: without the sentence every generated bridge tool repeats, which says nothing to the person choosing.

Parameters
string$descriptionDescription the model gets
Returns
string Description to show

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

◆ aiPaletteToolTitle()

aiPaletteToolTitle ( $langs,
$name,
$route )

Plain name of a tool for the palette of the chat: "Get invoice" rather than api_invoices_get.

A bridge tool is named from what it does (list, get, create...) and the record it works on, in the user's language when Dolibarr has a word for that record; any other tool from its own name.

Parameters
Translate$langsLanguages, in the user's language
string$nameTool name
array{endpoint:string,method:string,suffix:string,label:string}|null$route Route of a bridge tool, null for another tool
Returns
string Plain name

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

References dol_strtolower(), and dol_ucfirst().

◆ aiParseDocumentCommand()

aiParseDocumentCommand ( $db,
$text,
$user = null,
$side = 'sell' )

Read a one-line document command of the chat palette, e.g.

"AI SOLUTION 4 pieces popularpt 10; 2 widget" or, on a card, "4 popularpt 10".

Everything before the first number is the third party (empty = the one of the page). Then one line per group, groups separated by ";" or by ", " before a number: quantity, an optional unit ("pieces", "kg"), the product (ref or label, several words allowed), an optional unit price. Decimals may use a dot or a comma ("10,50"). "ref:XYZ" anywhere gives the supplier's own document number.

With a user, lines written one after the other without ";" ("4 pieces popularpt 2 pieces widget") are told apart too, but only when the words do not name a product as a whole and each part names one.

Parameters
DoliDB$dbDatabase handler (units dictionary, products)
string$textCommand text, without the command name
User | null$userUser the products are searched for, null to split on ";" only
string$side'sell' (customer documents) or 'buy' (supplier documents)
Returns
array{name:string, ref:string, lines:array<int, array<string, mixed>>, error:string}

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

References aiParseDocumentGroup().

◆ aiParseDocumentGroup()

aiParseDocumentGroup ( $db,
array $tokens,
array $asProduct,
$user,
$side )

Lines of one group of a document command: quantity, optional unit, product, optional unit price.

Several lines written without ";" are split here when a user is given (see aiParseDocumentCommand()).

Parameters
DoliDB$dbDatabase handler
string[]$tokensWords of the group
array<string,string>$asProduct Quoted products set aside: mark => "name"
User | null$userUser the products are searched for, null to never split
string$side'sell' or 'buy'
Returns
array<int, array<string, mixed>> Lines, none when the group is not a line

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

References aiDocumentProductExists(), aiParseDocumentGroup(), and aiUnitIdFromName().

Referenced by aiParseDocumentCommand(), and aiParseDocumentGroup().

◆ aiRecentProducts()

aiRecentProducts ( $db,
$user,
$socid,
$side = 'sell',
$limit = 8 )

Products of a third party's latest documents, newest first: what is most likely to be sold (or bought) again.

Parameters
DoliDB$dbDatabase handler
User$userUser
int$socidThird party
string$side'sell' (customer invoices) or 'buy' (supplier invoices)
int$limitRows to return
Returns
array<int, array{id:int, ref:string, label:string, price:float, fk_unit:int, stock:float, exact:bool}>

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

References checkUserAccessToObject().

◆ aiRestoreDocumentBlocks()

aiRestoreDocumentBlocks ( $text,
array $blocks )

Put back, unchanged, the documents set aside by aiExtractDocumentBlocks().

Parameters
string$textMessage with placeholders
array<string,string>$blocks Documents by placeholder
Returns
string Message with its documents

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

◆ 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 1317 of file ai.lib.php.

References aiStripPersonalExtrafields().

Referenced by aiStripPersonalExtrafields(), and ToolApiBridge\execute().

◆ 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 768 of file ai.lib.php.

◆ aiThirdpartyNamesToMask()

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 PrivacyGuard\maskNames(): the words as written, the names and trade names of the matching third parties, and the values of the name keys of a result ("name", "nom", "name_alias", "socname", ...).

Parameters
DoliDB$dbDatabase handler
User$userUser
string$textText that will be sent
array<string>$stopwords Translated keywords never accepted alone
mixed$dataDecoded tool result the text was built from, or null
Returns
array<string> Names to mask
Parameters
mixed$valueValue
int | string$keyKey
Returns
void
Parameters
string$nName
Returns
bool

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

References $c, and aiFindThirdpartiesInText().

◆ aiThirdpartyNatureHint()

aiThirdpartyNatureHint ( $text,
$langs )

Nature of third party a text points at, from its own words: "supplier" when it speaks of a supplier (or vendor), "customer" when it speaks of a customer, '' when it says neither or both.

Used only to narrow a list of candidates, never to choose one.

Parameters
string$textText of the request
Translate$langsLanguage of the user
Returns
string 'supplier', 'customer' or ''

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

References aiNameWords(), dol_strlen(), and dol_substr().

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

◆ aiUnitIdFromName()

aiUnitIdFromName ( $db,
$name )

Unit id from the word a user used for it: code, short label or label, in the user's language, singular or plural ("piece", "pieces", "pcs").

Parameters
DoliDB$dbDatabase handler
string$nameUnit as written
Returns
int Rowid of the unit, 0 when none or several match

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

References dol_strtolower().

Referenced by aiParseDocumentGroup(), and ToolApiBridge\unitIdFromName().

◆ getAiAssistantDefaultModel()

getAiAssistantDefaultModel ( )

Resolve the text model used by the AI Assistant when the picker is on "Auto" (same resolution order as assistant/parse_intent.php).

Returns
string The model id, or '' if no service is configured

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

References getDolGlobalString(), and getListOfAIServices().

Referenced by getAiChatAssistantHtml().

◆ 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 618 of file ai.lib.php.

References getDolGlobalString(), and getListOfAIServices().

Referenced by getAiChatAssistantHtml().

◆ getAiAssistantProviderUrl()

getAiAssistantProviderUrl ( )

Resolve the API URL used by the AI Assistant for the configured provider (same resolution order as assistant/parse_intent.php).

Returns
string The API base URL, or '' if no service is configured

Definition at line 658 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 795 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',
$openconversation = 0 )

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
int$openconversationConversation id to reopen on load (page mode only, 0 = none)
Returns
string HTML content

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

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

◆ getAIErrorMessage()

getAIErrorMessage ( $result)

Return a user-friendly error message from the error array returned by Ai\generateContent()

Parameters
array{error:bool,message:string,curl_error_no?:int,service?:string,model?:string}$result Error array returned by generateContent()
Returns
string Error message

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

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

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