30 public $lastRequest =
"";
33 public $lastResponse =
"";
36 public $lastUsage = array();
54 private $maxTokens = 0;
65 public function __construct(
string $type,
string $key,
string $baseUrl,
string $model,
int $timeout)
67 $this->
type = strtolower($type);
69 $this->baseUrl = rtrim($baseUrl,
'/');
70 $this->model = $model;
71 $this->timeout = $timeout;
83 $this->maxTokens = max(0, $maxTokens);
102 public function generate(
string $system,
string $userMsg,
string $mode =
'text', array $attachments = array(), array $history = array()): ?string
104 switch ($this->
type) {
106 return $this->
callAnthropic($system, $userMsg, $mode, $attachments, $history);
108 return $this->
callGoogle($system, $userMsg, $mode, $attachments, $history);
110 return $this->
callOpenAI($system, $userMsg, $mode, $attachments, $history);
124 private function callOpenAI(
string $sys,
string $msg,
string $mode =
'text', array $attachments = array(), array $history = array()): ?string
126 $url = $this->baseUrl;
127 if (strpos($url,
'/chat/completions') ===
false && strpos($url,
'/generate') ===
false) {
128 $url .=
'/chat/completions';
134 if (!empty($attachments)) {
135 $userContent = array(array(
"type" =>
"text",
"text" => $msg));
136 foreach ($attachments as $att) {
137 if ($att[
'mime'] ===
'application/pdf') {
140 $userContent[] = array(
143 "filename" =>
"document.pdf",
144 "file_data" =>
"data:application/pdf;base64,".$att[
'data']
148 $userContent[] = array(
149 "type" =>
"image_url",
150 "image_url" => array(
"url" =>
"data:".$att[
'mime'].
";base64,".$att[
'data'])
156 $messages = array(array(
"role" =>
"system",
"content" => $sys));
157 foreach ($history as $turn) {
158 $messages[] = array(
"role" => (($turn[
'role'] ??
'') ===
'assistant' ?
'assistant' :
'user'),
"content" => (
string) $turn[
'text']);
160 $messages[] = array(
"role" =>
"user",
"content" => $userContent);
163 "model" => $this->model,
164 "messages" => $messages,
167 if ($this->maxTokens > 0) {
168 $data[
"max_tokens"] = $this->maxTokens;
169 } elseif (!empty($attachments)) {
170 $data[
"max_tokens"] = 8192;
175 if ($mode ===
'json') {
177 if (strpos($url,
'openai') !==
false || strpos($url,
'deepseek') !==
false || strpos($url,
'perplexity') !==
false || strpos($url,
'mistral') !==
false || strpos($url,
'zai') !==
false) {
178 $data[
"response_format"] = array(
"type" =>
"json_object");
185 dol_syslog(
'callOpenAI url='.$url, LOG_DEBUG, 0,
'_ai');
188 $answer = $this->
curl($url, $data, array(
"Content-Type: application/json",
"Authorization: Bearer " . $this->key));
204 private function callAnthropic(
string $sys,
string $msg,
string $mode =
'text', array $attachments = array(), array $history = array())
207 $url = $this->baseUrl . (strpos($this->baseUrl,
'/messages') ===
false ?
'/messages' :
'');
213 if (!empty($attachments)) {
214 $userContent = array();
215 foreach ($attachments as $att) {
216 $userContent[] = array(
217 "type" => ($att[
'mime'] ===
'application/pdf' ?
"document" :
"image"),
220 "source" => array(
"type" =>
"base64",
"media_type" => $att[
'mime'],
"data" => $att[
'data'])
223 $userContent[] = array(
"type" =>
"text",
"text" => $msg);
228 foreach ($history as $turn) {
229 $messages[] = array(
"role" => (($turn[
'role'] ??
'') ===
'assistant' ?
'assistant' :
'user'),
"content" => (
string) $turn[
'text']);
231 $messages[] = array(
"role" =>
"user",
"content" => $userContent);
234 "model" => $this->model,
236 "messages" => $messages,
237 "max_tokens" => ($this->maxTokens > 0 ? $this->maxTokens : $maxTokens)
242 return $this->
curl($url, $data, array(
"content-type: application/json",
"x-api-key: " . $this->key,
"anthropic-version: 2023-06-01"),
true);
256 private function callGoogle(
string $sys,
string $msg,
string $mode =
'text', array $attachments = array(), array $history = array())
258 $url = $this->baseUrl;
261 if (strpos($url,
':generateContent') ===
false) {
262 if (strpos($url,
'/models/') ===
false) {
263 $url .=
"/models/" . $this->model;
265 $url .=
":generateContent";
268 $url .=
"?key=" . $this->key;
273 foreach ($attachments as $att) {
274 $parts[] = array(
"inline_data" => array(
"mime_type" => $att[
'mime'],
"data" => $att[
'data']));
276 $parts[] = array(
"text" => $sys .
"\nUser: " . $msg);
283 if (!empty($history)) {
284 foreach ($history as $turn) {
286 "role" => (($turn[
'role'] ??
'') ===
'assistant' ?
'model' :
'user'),
287 "parts" => array(array(
"text" => (
string) $turn[
'text']))
290 $contents[] = array(
"role" =>
"user",
"parts" => $parts);
292 $contents[] = array(
"parts" => $parts);
296 "contents" => $contents,
297 "generationConfig" => (empty($attachments) ? array(
"temperature" => 0.1) : array(
"temperature" => 0.1,
"maxOutputTokens" => 16384))
299 if ($this->maxTokens > 0) {
300 $data[
"generationConfig"][
"maxOutputTokens"] = $this->maxTokens;
305 return $this->
curl($url, $data, array(
"Content-Type: application/json"),
false,
true);
317 if (!is_object($db) || !is_object(
$conf)) {
324 $rec = json_decode($raw,
true);
325 if (!is_array($rec) || (
string) ($rec[
'model'] ??
'') !== (
string) $this->model) {
328 include_once DOL_DOCUMENT_ROOT.
'/core/lib/admin.lib.php';
342 if (!preg_match(
'/model/i', $msg)) {
345 return (
bool) preg_match(
'/not.?found|does not exist|not exist|unsupported|not supported|not available|unavailable|deprecated|no longer|retired|invalid/i', $msg);
363 if (!is_object($db) || !is_object(
$conf)) {
366 if (!self::isModelUnavailableError($msg)) {
369 include_once DOL_DOCUMENT_ROOT.
'/core/lib/admin.lib.php';
374 'model' => $this->model,
376 'http_code' => $httpCode,
378 )),
'chaine', 0,
'',
$conf->entity);
392 $json = json_encode($data);
396 $out = preg_replace_callback(
397 '~((?:[A-Za-z0-9+=]++|\\\\/)+)~',
402 static function (array $m) {
403 if (strlen($m[1]) < 512) {
407 return '[base64 elided, '.strlen($m[1]).
' chars]';
412 return ($out ===
null) ? $json : $out;
425 private function curl(
string $url, array $data, array $headers,
bool $isClaude =
false,
bool $isGemini =
false): ?string
427 include_once DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
431 global $dolibarr_ai_allow_local_endpoints;
433 $localurl = empty($dolibarr_ai_allow_local_endpoints) ? 0 : 2;
438 $this->lastUsage = array();
440 $result =
getURLContent($url,
'POST', json_encode($data), 1, $headers, array(
'http',
'https'), $localurl, -1, 0, $this->timeout);
442 $body = (string) ($result[
'content'] ??
'');
443 $httpCode = (int) ($result[
'http_code'] ?? 0);
444 $effectiveUrl = (string) ($result[
'url'] ?? $url);
448 $effectiveUrl = preg_replace(
'/([?&]key=)[^&\s]+/',
'$1***', $effectiveUrl);
452 $this->lastResponse =
"HTTP " . $httpCode .
" from " . $effectiveUrl .
"\n--- body (" . strlen($body) .
" bytes) ---\n" . $body;
455 dol_syslog(
'curl answer received, HTTP = '.$httpCode.
', size of response string = '.strlen($body), LOG_DEBUG, 0,
'_ai');
458 if (!empty($result[
'curl_error_no'])) {
460 dol_syslog(
"Error: cURL #" . $result[
'curl_error_no'] .
" " . $result[
'curl_error_msg'] .
" (url=" . $effectiveUrl .
")", LOG_DEBUG, 0,
'_ai');
462 return "Error: cURL #" . $result[
'curl_error_no'] .
" " . $result[
'curl_error_msg'] .
" (url=" . $effectiveUrl .
")";
465 $json = json_decode($body,
true);
468 dol_syslog(
"curl answer body=" . var_export($body,
true), LOG_DEBUG, 0,
'_ai');
469 dol_syslog(
"curl answer json_decoded=" . var_export($json,
true), LOG_DEBUG, 0,
'_ai');
472 if ($json ===
null && json_last_error() !== JSON_ERROR_NONE) {
476 $snippet = substr($body, 0, 500);
478 dol_syslog(
"Error: Invalid JSON response from API (HTTP " . $httpCode .
", " . strlen($body) .
" bytes). Body snippet: " . ($snippet !==
'' ? $snippet :
'<empty>'), LOG_DEBUG, 0,
'_ai');
480 return "Error: Invalid JSON response from API (HTTP " . $httpCode .
", " . strlen($body) .
" bytes). Body snippet: " . ($snippet !==
'' ? $snippet :
'<empty>');
485 if (isset($json[
'error']) || (is_array($json) && ($json[
'object'] ??
'') ===
'error')) {
486 if (isset($json[
'error'])) {
487 $msg = $json[
'error'][
'message'] ?? json_encode($json[
'error']);
489 $msg = $json[
'message'] ?? json_encode($json);
491 if (!is_string($msg)) {
492 $msg = json_encode($msg);
496 dol_syslog(
"Error: API " . $msg, LOG_DEBUG, 0,
'_ai');
498 return "Error: API " . $msg;
508 $this->lastUsage = array(
'model' => $this->model);
510 $this->lastUsage[
'input'] = (int) ($json[
'usageMetadata'][
'promptTokenCount'] ?? 0);
511 $this->lastUsage[
'output'] = (int) ($json[
'usageMetadata'][
'candidatesTokenCount'] ?? 0) + (int) ($json[
'usageMetadata'][
'thoughtsTokenCount'] ?? 0);
512 } elseif ($isClaude) {
513 $this->lastUsage[
'input'] = (int) ($json[
'usage'][
'input_tokens'] ?? 0);
514 $this->lastUsage[
'output'] = (int) ($json[
'usage'][
'output_tokens'] ?? 0);
516 $this->lastUsage[
'input'] = (int) ($json[
'usage'][
'prompt_tokens'] ?? 0);
517 $this->lastUsage[
'output'] = (int) ($json[
'usage'][
'completion_tokens'] ?? 0);
525 $answer = $json[
'content'] ??
null;
526 } elseif ($isGemini) {
527 $answer = $json[
'candidates'][0][
'content'][
'parts'][0][
'text'] ??
null;
530 if ($answer ===
null) {
532 $answer = $json[
'choices'][0][
'message'][
'content'] ??
null;
537 if (is_array($answer)) {
539 foreach ($answer as $chunk) {
540 if (is_array($chunk) && ($chunk[
'type'] ??
'') ===
'text' && is_string($chunk[
'text'] ??
null)) {
541 $text .= $chunk[
'text'];
544 $answer = ($text !==
'') ? $text :
null;
548 if (empty($answer) && !empty($json[
'choices'][0][
'message'][
'tool_calls'])) {
549 $answer = json_encode($json[
'choices'][0][
'message'][
'tool_calls']);
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
clearModelFailure()
Drop a recorded model failure once that model answers again.
curl(string $url, array $data, array $headers, bool $isClaude=false, bool $isGemini=false)
Execute HTTP Request via cURL.
__construct(string $type, string $key, string $baseUrl, string $model, int $timeout)
Constructor.
generate(string $system, string $userMsg, string $mode='text', array $attachments=array(), array $history=array())
Generate a response using the configured LLM provider.
recordModelFailure(int $httpCode, string $msg)
Record a "model not found / retired" type provider failure into the constant AI_MODEL_RUNTIME_FAILURE...
callGoogle(string $sys, string $msg, string $mode='text', array $attachments=array(), array $history=array())
Call Google Gemini API.
setMaxTokens(int $maxTokens)
Set the maximum number of tokens of the answer, for callers that expect long answers (with thinking m...
encodeRequestForLog(array $data)
JSON-encode a request for the log with base64 payloads removed, so the 60k truncation in ai_log_reque...
static isModelUnavailableError(string $msg)
Tell if a provider error message says the requested model is unknown, retired or not available (not a...
callAnthropic(string $sys, string $msg, string $mode='text', array $attachments=array(), array $history=array())
Call Anthropic API (Claude)
callOpenAI(string $sys, string $msg, string $mode='text', array $attachments=array(), array $history=array())
Call OpenAI-compatible API.
dol_now($mode='gmt')
Return date for now.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).