1f6ef2e50SAndreas Gohr<?php 2f6ef2e50SAndreas Gohr 3f6ef2e50SAndreas Gohrnamespace dokuwiki\plugin\aichat\Model; 4f6ef2e50SAndreas Gohr 5294a9eafSAndreas Gohruse dokuwiki\HTTP\DokuHTTPClient; 6294a9eafSAndreas Gohr 7294a9eafSAndreas Gohr/** 8294a9eafSAndreas Gohr * Base class for all models 9294a9eafSAndreas Gohr * 10294a9eafSAndreas Gohr * Model classes also need to implement one of the following interfaces: 11294a9eafSAndreas Gohr * - ChatInterface 12294a9eafSAndreas Gohr * - EmbeddingInterface 13dce0dee5SAndreas Gohr * 14dce0dee5SAndreas Gohr * This class already implements most of the requirements for these interfaces. 15dce0dee5SAndreas Gohr * 16dce0dee5SAndreas Gohr * In addition to any missing interface methods, model implementations will need to 17dce0dee5SAndreas Gohr * extend the constructor to handle the plugin configuration and implement the 18dce0dee5SAndreas Gohr * parseAPIResponse() method to handle the specific API response. 19294a9eafSAndreas Gohr */ 20dce0dee5SAndreas Gohrabstract class AbstractModel implements ModelInterface 217ebc7895Ssplitbrain{ 22dce0dee5SAndreas Gohr /** @var string The model name */ 23dce0dee5SAndreas Gohr protected $modelName; 24dce0dee5SAndreas Gohr /** @var array The model info from the model.json file */ 25dce0dee5SAndreas Gohr protected $modelInfo; 2634a1c478SAndreas Gohr 27dce0dee5SAndreas Gohr /** @var int input tokens used since last reset */ 2834a1c478SAndreas Gohr protected $inputTokensUsed = 0; 29dce0dee5SAndreas Gohr /** @var int output tokens used since last reset */ 3034a1c478SAndreas Gohr protected $outputTokensUsed = 0; 31dce0dee5SAndreas Gohr /** @var int total time spent in requests since last reset */ 32f6ef2e50SAndreas Gohr protected $timeUsed = 0; 33dce0dee5SAndreas Gohr /** @var int total number of requests made since last reset */ 34f6ef2e50SAndreas Gohr protected $requestsMade = 0; 35294a9eafSAndreas Gohr /** @var int start time of the current request chain (may be multiple when retries needed) */ 36294a9eafSAndreas Gohr protected $requestStart = 0; 37f6ef2e50SAndreas Gohr 38dce0dee5SAndreas Gohr /** @var int How often to retry a request if it fails */ 39dce0dee5SAndreas Gohr public const MAX_RETRIES = 3; 40dce0dee5SAndreas Gohr 41dce0dee5SAndreas Gohr /** @var DokuHTTPClient */ 42dce0dee5SAndreas Gohr protected $http; 43dce0dee5SAndreas Gohr /** @var bool debug API communication */ 44dce0dee5SAndreas Gohr protected $debug = false; 45dce0dee5SAndreas Gohr 46dce0dee5SAndreas Gohr // region ModelInterface 47dce0dee5SAndreas Gohr 48dce0dee5SAndreas Gohr /** @inheritdoc */ 49dce0dee5SAndreas Gohr public function __construct(string $name, array $config) 50294a9eafSAndreas Gohr { 51dce0dee5SAndreas Gohr $this->modelName = $name; 52294a9eafSAndreas Gohr $this->http = new DokuHTTPClient(); 53294a9eafSAndreas Gohr $this->http->timeout = 60; 54294a9eafSAndreas Gohr $this->http->headers['Content-Type'] = 'application/json'; 55cfd76f4aSAndreas Gohr $this->http->headers['Accept'] = 'application/json'; 56dce0dee5SAndreas Gohr 57dce0dee5SAndreas Gohr $reflect = new \ReflectionClass($this); 58dce0dee5SAndreas Gohr $json = dirname($reflect->getFileName()) . '/models.json'; 59dce0dee5SAndreas Gohr if (!file_exists($json)) { 60dce0dee5SAndreas Gohr throw new \Exception('Model info file not found at ' . $json); 61294a9eafSAndreas Gohr } 62dce0dee5SAndreas Gohr try { 63dce0dee5SAndreas Gohr $modelinfos = json_decode(file_get_contents($json), true, 512, JSON_THROW_ON_ERROR); 64dce0dee5SAndreas Gohr } catch (\JsonException $e) { 65dce0dee5SAndreas Gohr throw new \Exception('Failed to parse model info file: ' . $e->getMessage(), $e->getCode(), $e); 66dce0dee5SAndreas Gohr } 67dce0dee5SAndreas Gohr 68dce0dee5SAndreas Gohr if ($this instanceof ChatInterface) { 69dce0dee5SAndreas Gohr if (!isset($modelinfos['chat'][$name])) { 70dce0dee5SAndreas Gohr throw new \Exception('Invalid chat model configured: ' . $name); 71dce0dee5SAndreas Gohr } 72dce0dee5SAndreas Gohr $this->modelInfo = $modelinfos['chat'][$name]; 73dce0dee5SAndreas Gohr } 74dce0dee5SAndreas Gohr 75dce0dee5SAndreas Gohr if ($this instanceof EmbeddingInterface) { 76dce0dee5SAndreas Gohr if (!isset($modelinfos['embedding'][$name])) { 77dce0dee5SAndreas Gohr throw new \Exception('Invalid embedding model configured: ' . $name); 78dce0dee5SAndreas Gohr } 79dce0dee5SAndreas Gohr $this->modelInfo = $modelinfos['embedding'][$name]; 80dce0dee5SAndreas Gohr } 81dce0dee5SAndreas Gohr } 82dce0dee5SAndreas Gohr 83dce0dee5SAndreas Gohr /** @inheritdoc */ 84dce0dee5SAndreas Gohr public function getModelName() 85dce0dee5SAndreas Gohr { 86dce0dee5SAndreas Gohr return $this->modelName; 87dce0dee5SAndreas Gohr } 88dce0dee5SAndreas Gohr 89dce0dee5SAndreas Gohr /** 90dce0dee5SAndreas Gohr * Reset the usage statistics 91dce0dee5SAndreas Gohr * 92dce0dee5SAndreas Gohr * Usually not needed when only handling one operation per request, but useful in CLI 93dce0dee5SAndreas Gohr */ 94dce0dee5SAndreas Gohr public function resetUsageStats() 95dce0dee5SAndreas Gohr { 96dce0dee5SAndreas Gohr $this->tokensUsed = 0; 97dce0dee5SAndreas Gohr $this->timeUsed = 0; 98dce0dee5SAndreas Gohr $this->requestsMade = 0; 99dce0dee5SAndreas Gohr } 100dce0dee5SAndreas Gohr 101dce0dee5SAndreas Gohr /** 102dce0dee5SAndreas Gohr * Get the usage statistics for this instance 103dce0dee5SAndreas Gohr * 104dce0dee5SAndreas Gohr * @return string[] 105dce0dee5SAndreas Gohr */ 106dce0dee5SAndreas Gohr public function getUsageStats() 107dce0dee5SAndreas Gohr { 108dce0dee5SAndreas Gohr 109dce0dee5SAndreas Gohr $cost = 0; 110dce0dee5SAndreas Gohr $cost += $this->inputTokensUsed * $this->getInputTokenPrice(); 111dce0dee5SAndreas Gohr if ($this instanceof ChatInterface) { 112dce0dee5SAndreas Gohr $cost += $this->outputTokensUsed * $this->getOutputTokenPrice(); 113dce0dee5SAndreas Gohr } 114dce0dee5SAndreas Gohr 115dce0dee5SAndreas Gohr return [ 116dce0dee5SAndreas Gohr 'tokens' => $this->inputTokensUsed + $this->outputTokensUsed, 117*c2b7a1f7SAndreas Gohr 'cost' => sprintf("%.6f", $cost / 1_000_000), 118dce0dee5SAndreas Gohr 'time' => round($this->timeUsed, 2), 119dce0dee5SAndreas Gohr 'requests' => $this->requestsMade, 120dce0dee5SAndreas Gohr ]; 121dce0dee5SAndreas Gohr } 122dce0dee5SAndreas Gohr 123dce0dee5SAndreas Gohr /** @inheritdoc */ 124dce0dee5SAndreas Gohr public function getMaxInputTokenLength(): int 125dce0dee5SAndreas Gohr { 126dce0dee5SAndreas Gohr return $this->modelInfo['inputTokens']; 127dce0dee5SAndreas Gohr } 128dce0dee5SAndreas Gohr 129dce0dee5SAndreas Gohr /** @inheritdoc */ 130dce0dee5SAndreas Gohr public function getInputTokenPrice(): float 131dce0dee5SAndreas Gohr { 132dce0dee5SAndreas Gohr return $this->modelInfo['inputTokenPrice']; 133dce0dee5SAndreas Gohr } 134dce0dee5SAndreas Gohr 135dce0dee5SAndreas Gohr // endregion 136dce0dee5SAndreas Gohr 137dce0dee5SAndreas Gohr // region EmbeddingInterface 138dce0dee5SAndreas Gohr 139dce0dee5SAndreas Gohr /** @inheritdoc */ 140dce0dee5SAndreas Gohr public function getDimensions(): int 141dce0dee5SAndreas Gohr { 142dce0dee5SAndreas Gohr return $this->modelInfo['dimensions']; 143dce0dee5SAndreas Gohr } 144dce0dee5SAndreas Gohr 145dce0dee5SAndreas Gohr // endregion 146dce0dee5SAndreas Gohr 147dce0dee5SAndreas Gohr // region ChatInterface 148dce0dee5SAndreas Gohr 149dce0dee5SAndreas Gohr public function getMaxOutputTokenLength(): int 150dce0dee5SAndreas Gohr { 151dce0dee5SAndreas Gohr return $this->modelInfo['outputTokens']; 152dce0dee5SAndreas Gohr } 153dce0dee5SAndreas Gohr 154dce0dee5SAndreas Gohr public function getOutputTokenPrice(): float 155dce0dee5SAndreas Gohr { 156dce0dee5SAndreas Gohr return $this->modelInfo['outputTokenPrice']; 157dce0dee5SAndreas Gohr } 158dce0dee5SAndreas Gohr 159dce0dee5SAndreas Gohr // endregion 160dce0dee5SAndreas Gohr 161dce0dee5SAndreas Gohr // region API communication 162f6ef2e50SAndreas Gohr 163f6ef2e50SAndreas Gohr /** 16434a1c478SAndreas Gohr * When enabled, the input/output of the API will be printed to STDOUT 16534a1c478SAndreas Gohr * 16634a1c478SAndreas Gohr * @param bool $debug 16734a1c478SAndreas Gohr */ 16834a1c478SAndreas Gohr public function setDebug($debug = true) 16934a1c478SAndreas Gohr { 17034a1c478SAndreas Gohr $this->debug = $debug; 17134a1c478SAndreas Gohr } 17234a1c478SAndreas Gohr 17334a1c478SAndreas Gohr /** 174294a9eafSAndreas Gohr * This method should check the response for any errors. If the API singalled an error, 175294a9eafSAndreas Gohr * this method should throw an Exception with a meaningful error message. 176294a9eafSAndreas Gohr * 177294a9eafSAndreas Gohr * If the response returned any info on used tokens, they should be added to $this->tokensUsed 178294a9eafSAndreas Gohr * 179294a9eafSAndreas Gohr * The method should return the parsed response, which will be passed to the calling method. 180294a9eafSAndreas Gohr * 181294a9eafSAndreas Gohr * @param mixed $response the parsed JSON response from the API 182294a9eafSAndreas Gohr * @return mixed 183294a9eafSAndreas Gohr * @throws \Exception when the response indicates an error 184294a9eafSAndreas Gohr */ 185294a9eafSAndreas Gohr abstract protected function parseAPIResponse($response); 186294a9eafSAndreas Gohr 187294a9eafSAndreas Gohr /** 188294a9eafSAndreas Gohr * Send a request to the API 189294a9eafSAndreas Gohr * 190294a9eafSAndreas Gohr * Model classes should use this method to send requests to the API. 191294a9eafSAndreas Gohr * 192294a9eafSAndreas Gohr * This method will take care of retrying and logging basic statistics. 193294a9eafSAndreas Gohr * 194294a9eafSAndreas Gohr * It is assumed that all APIs speak JSON. 195294a9eafSAndreas Gohr * 196294a9eafSAndreas Gohr * @param string $method The HTTP method to use (GET, POST, PUT, DELETE, etc.) 197294a9eafSAndreas Gohr * @param string $url The full URL to send the request to 198294a9eafSAndreas Gohr * @param array $data Payload to send, will be encoded to JSON 199294a9eafSAndreas Gohr * @param int $retry How often this request has been retried, do not set externally 200294a9eafSAndreas Gohr * @return array API response as returned by parseAPIResponse 201294a9eafSAndreas Gohr * @throws \Exception when anything goes wrong 202294a9eafSAndreas Gohr */ 203294a9eafSAndreas Gohr protected function sendAPIRequest($method, $url, $data, $retry = 0) 204294a9eafSAndreas Gohr { 205294a9eafSAndreas Gohr // init statistics 206294a9eafSAndreas Gohr if ($retry === 0) { 207294a9eafSAndreas Gohr $this->requestStart = microtime(true); 208294a9eafSAndreas Gohr } else { 209294a9eafSAndreas Gohr sleep($retry); // wait a bit between retries 210294a9eafSAndreas Gohr } 211294a9eafSAndreas Gohr $this->requestsMade++; 212294a9eafSAndreas Gohr 213294a9eafSAndreas Gohr // encode payload data 214294a9eafSAndreas Gohr try { 21534a1c478SAndreas Gohr $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT); 216294a9eafSAndreas Gohr } catch (\JsonException $e) { 217294a9eafSAndreas Gohr $this->timeUsed += $this->requestStart - microtime(true); 218294a9eafSAndreas Gohr throw new \Exception('Failed to encode JSON for API:' . $e->getMessage(), $e->getCode(), $e); 219294a9eafSAndreas Gohr } 220294a9eafSAndreas Gohr 22134a1c478SAndreas Gohr if ($this->debug) { 22234a1c478SAndreas Gohr echo 'Sending ' . $method . ' request to ' . $url . ' with payload:' . "\n"; 22334a1c478SAndreas Gohr print_r($json); 22451aa8517SAndreas Gohr echo "\n"; 22534a1c478SAndreas Gohr } 22634a1c478SAndreas Gohr 227294a9eafSAndreas Gohr // send request and handle retries 228294a9eafSAndreas Gohr $this->http->sendRequest($url, $json, $method); 229294a9eafSAndreas Gohr $response = $this->http->resp_body; 230294a9eafSAndreas Gohr if ($response === false || $this->http->error) { 231294a9eafSAndreas Gohr if ($retry < self::MAX_RETRIES) { 232294a9eafSAndreas Gohr return $this->sendAPIRequest($method, $url, $data, $retry + 1); 233294a9eafSAndreas Gohr } 234294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 235294a9eafSAndreas Gohr throw new \Exception('API returned no response. ' . $this->http->error); 236294a9eafSAndreas Gohr } 237294a9eafSAndreas Gohr 23834a1c478SAndreas Gohr if ($this->debug) { 23934a1c478SAndreas Gohr echo 'Received response:' . "\n"; 24034a1c478SAndreas Gohr print_r($response); 24151aa8517SAndreas Gohr echo "\n"; 24234a1c478SAndreas Gohr } 24334a1c478SAndreas Gohr 244294a9eafSAndreas Gohr // decode the response 245294a9eafSAndreas Gohr try { 246294a9eafSAndreas Gohr $result = json_decode((string)$response, true, 512, JSON_THROW_ON_ERROR); 247294a9eafSAndreas Gohr } catch (\JsonException $e) { 248294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 249294a9eafSAndreas Gohr throw new \Exception('API returned invalid JSON: ' . $response, 0, $e); 250294a9eafSAndreas Gohr } 251294a9eafSAndreas Gohr 252294a9eafSAndreas Gohr // parse the response, retry on error 253294a9eafSAndreas Gohr try { 254294a9eafSAndreas Gohr $result = $this->parseAPIResponse($result); 255294a9eafSAndreas Gohr } catch (\Exception $e) { 256294a9eafSAndreas Gohr if ($retry < self::MAX_RETRIES) { 257294a9eafSAndreas Gohr return $this->sendAPIRequest($method, $url, $data, $retry + 1); 258294a9eafSAndreas Gohr } 259294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 260294a9eafSAndreas Gohr throw $e; 261294a9eafSAndreas Gohr } 262294a9eafSAndreas Gohr 263294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 264294a9eafSAndreas Gohr return $result; 265294a9eafSAndreas Gohr } 266294a9eafSAndreas Gohr 267dce0dee5SAndreas Gohr // endregion 268f6ef2e50SAndreas Gohr} 269