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; 24b446155bSAndreas Gohr /** @var string The full model name */ 25b446155bSAndreas Gohr protected $modelFullName; 26dce0dee5SAndreas Gohr /** @var array The model info from the model.json file */ 27dce0dee5SAndreas Gohr protected $modelInfo; 2834a1c478SAndreas Gohr 29dce0dee5SAndreas Gohr /** @var int input tokens used since last reset */ 3034a1c478SAndreas Gohr protected $inputTokensUsed = 0; 31dce0dee5SAndreas Gohr /** @var int output tokens used since last reset */ 3234a1c478SAndreas Gohr protected $outputTokensUsed = 0; 33dce0dee5SAndreas Gohr /** @var int total time spent in requests since last reset */ 34f6ef2e50SAndreas Gohr protected $timeUsed = 0; 35dce0dee5SAndreas Gohr /** @var int total number of requests made since last reset */ 36f6ef2e50SAndreas Gohr protected $requestsMade = 0; 37294a9eafSAndreas Gohr /** @var int start time of the current request chain (may be multiple when retries needed) */ 38294a9eafSAndreas Gohr protected $requestStart = 0; 39f6ef2e50SAndreas Gohr 40dce0dee5SAndreas Gohr /** @var int How often to retry a request if it fails */ 41dce0dee5SAndreas Gohr public const MAX_RETRIES = 3; 42dce0dee5SAndreas Gohr 43dce0dee5SAndreas Gohr /** @var DokuHTTPClient */ 44dce0dee5SAndreas Gohr protected $http; 45dce0dee5SAndreas Gohr /** @var bool debug API communication */ 46dce0dee5SAndreas Gohr protected $debug = false; 47dce0dee5SAndreas Gohr 48dce0dee5SAndreas Gohr // region ModelInterface 49dce0dee5SAndreas Gohr 50dce0dee5SAndreas Gohr /** @inheritdoc */ 51dce0dee5SAndreas Gohr public function __construct(string $name, array $config) 52294a9eafSAndreas Gohr { 53dce0dee5SAndreas Gohr $this->modelName = $name; 54294a9eafSAndreas Gohr $this->http = new DokuHTTPClient(); 55294a9eafSAndreas Gohr $this->http->timeout = 60; 56294a9eafSAndreas Gohr $this->http->headers['Content-Type'] = 'application/json'; 57cfd76f4aSAndreas Gohr $this->http->headers['Accept'] = 'application/json'; 58dce0dee5SAndreas Gohr 59dce0dee5SAndreas Gohr $reflect = new \ReflectionClass($this); 60dce0dee5SAndreas Gohr $json = dirname($reflect->getFileName()) . '/models.json'; 61dce0dee5SAndreas Gohr if (!file_exists($json)) { 62*42b2c6e8SAndreas Gohr throw new \Exception('Model info file not found at ' . $json, 2001); 63294a9eafSAndreas Gohr } 64dce0dee5SAndreas Gohr try { 65dce0dee5SAndreas Gohr $modelinfos = json_decode(file_get_contents($json), true, 512, JSON_THROW_ON_ERROR); 66dce0dee5SAndreas Gohr } catch (\JsonException $e) { 67*42b2c6e8SAndreas Gohr throw new \Exception('Failed to parse model info file: ' . $e->getMessage(), 2002, $e); 68dce0dee5SAndreas Gohr } 69dce0dee5SAndreas Gohr 70b446155bSAndreas Gohr $this->modelFullName = basename(dirname($reflect->getFileName()) . ' ' . $name); 71b446155bSAndreas Gohr 72dce0dee5SAndreas Gohr if ($this instanceof ChatInterface) { 734dd0657eSAndreas Gohr if (isset($modelinfos['chat'][$name])) { 74dce0dee5SAndreas Gohr $this->modelInfo = $modelinfos['chat'][$name]; 754dd0657eSAndreas Gohr } else { 764dd0657eSAndreas Gohr $this->modelInfo = $this->loadUnknownModelInfo(); 774dd0657eSAndreas Gohr } 784dd0657eSAndreas Gohr 79dce0dee5SAndreas Gohr } 80dce0dee5SAndreas Gohr 81dce0dee5SAndreas Gohr if ($this instanceof EmbeddingInterface) { 824dd0657eSAndreas Gohr if (isset($modelinfos['embedding'][$name])) { 83dce0dee5SAndreas Gohr $this->modelInfo = $modelinfos['embedding'][$name]; 844dd0657eSAndreas Gohr } else { 854dd0657eSAndreas Gohr $this->modelInfo = $this->loadUnknownModelInfo(); 864dd0657eSAndreas Gohr } 87dce0dee5SAndreas Gohr } 88dce0dee5SAndreas Gohr } 89dce0dee5SAndreas Gohr 90dce0dee5SAndreas Gohr /** @inheritdoc */ 91b446155bSAndreas Gohr public function __toString(): string 92b446155bSAndreas Gohr { 93b446155bSAndreas Gohr return $this->modelFullName; 94b446155bSAndreas Gohr } 95b446155bSAndreas Gohr 96b446155bSAndreas Gohr 97b446155bSAndreas Gohr /** @inheritdoc */ 98dce0dee5SAndreas Gohr public function getModelName() 99dce0dee5SAndreas Gohr { 100dce0dee5SAndreas Gohr return $this->modelName; 101dce0dee5SAndreas Gohr } 102dce0dee5SAndreas Gohr 103dce0dee5SAndreas Gohr /** 104dce0dee5SAndreas Gohr * Reset the usage statistics 105dce0dee5SAndreas Gohr * 106dce0dee5SAndreas Gohr * Usually not needed when only handling one operation per request, but useful in CLI 107dce0dee5SAndreas Gohr */ 108dce0dee5SAndreas Gohr public function resetUsageStats() 109dce0dee5SAndreas Gohr { 1102071dcedSAndreas Gohr $this->inputTokensUsed = 0; 1112071dcedSAndreas Gohr $this->outputTokensUsed = 0; 112dce0dee5SAndreas Gohr $this->timeUsed = 0; 113dce0dee5SAndreas Gohr $this->requestsMade = 0; 114dce0dee5SAndreas Gohr } 115dce0dee5SAndreas Gohr 116dce0dee5SAndreas Gohr /** 117dce0dee5SAndreas Gohr * Get the usage statistics for this instance 118dce0dee5SAndreas Gohr * 119dce0dee5SAndreas Gohr * @return string[] 120dce0dee5SAndreas Gohr */ 121dce0dee5SAndreas Gohr public function getUsageStats() 122dce0dee5SAndreas Gohr { 123dce0dee5SAndreas Gohr 124dce0dee5SAndreas Gohr $cost = 0; 125dce0dee5SAndreas Gohr $cost += $this->inputTokensUsed * $this->getInputTokenPrice(); 126dce0dee5SAndreas Gohr if ($this instanceof ChatInterface) { 127dce0dee5SAndreas Gohr $cost += $this->outputTokensUsed * $this->getOutputTokenPrice(); 128dce0dee5SAndreas Gohr } 129dce0dee5SAndreas Gohr 130dce0dee5SAndreas Gohr return [ 131dce0dee5SAndreas Gohr 'tokens' => $this->inputTokensUsed + $this->outputTokensUsed, 132c2b7a1f7SAndreas Gohr 'cost' => sprintf("%.6f", $cost / 1_000_000), 133dce0dee5SAndreas Gohr 'time' => round($this->timeUsed, 2), 134dce0dee5SAndreas Gohr 'requests' => $this->requestsMade, 135dce0dee5SAndreas Gohr ]; 136dce0dee5SAndreas Gohr } 137dce0dee5SAndreas Gohr 138dce0dee5SAndreas Gohr /** @inheritdoc */ 139dce0dee5SAndreas Gohr public function getMaxInputTokenLength(): int 140dce0dee5SAndreas Gohr { 141dce0dee5SAndreas Gohr return $this->modelInfo['inputTokens']; 142dce0dee5SAndreas Gohr } 143dce0dee5SAndreas Gohr 144dce0dee5SAndreas Gohr /** @inheritdoc */ 145dce0dee5SAndreas Gohr public function getInputTokenPrice(): float 146dce0dee5SAndreas Gohr { 147dce0dee5SAndreas Gohr return $this->modelInfo['inputTokenPrice']; 148dce0dee5SAndreas Gohr } 149dce0dee5SAndreas Gohr 1504dd0657eSAndreas Gohr /** @inheritdoc */ 1514dd0657eSAndreas Gohr function loadUnknownModelInfo(): array 1524dd0657eSAndreas Gohr { 1534dd0657eSAndreas Gohr $info = [ 1544dd0657eSAndreas Gohr 'description' => $this->modelFullName, 1554dd0657eSAndreas Gohr 'inputTokens' => 1024, 1564dd0657eSAndreas Gohr 'inputTokenPrice' => 0, 1574dd0657eSAndreas Gohr ]; 1584dd0657eSAndreas Gohr 1594dd0657eSAndreas Gohr if ($this instanceof ChatInterface) { 1604dd0657eSAndreas Gohr $info['outputTokens'] = 1024; 1614dd0657eSAndreas Gohr $info['outputTokenPrice'] = 0; 1624dd0657eSAndreas Gohr } elseif ($this instanceof EmbeddingInterface) { 1634dd0657eSAndreas Gohr $info['dimensions'] = 512; 1644dd0657eSAndreas Gohr } 1654dd0657eSAndreas Gohr 1664dd0657eSAndreas Gohr return $info; 1674dd0657eSAndreas Gohr } 1684dd0657eSAndreas Gohr 169dce0dee5SAndreas Gohr // endregion 170dce0dee5SAndreas Gohr 171dce0dee5SAndreas Gohr // region EmbeddingInterface 172dce0dee5SAndreas Gohr 173dce0dee5SAndreas Gohr /** @inheritdoc */ 174dce0dee5SAndreas Gohr public function getDimensions(): int 175dce0dee5SAndreas Gohr { 176dce0dee5SAndreas Gohr return $this->modelInfo['dimensions']; 177dce0dee5SAndreas Gohr } 178dce0dee5SAndreas Gohr 179dce0dee5SAndreas Gohr // endregion 180dce0dee5SAndreas Gohr 181dce0dee5SAndreas Gohr // region ChatInterface 182dce0dee5SAndreas Gohr 183dce0dee5SAndreas Gohr public function getMaxOutputTokenLength(): int 184dce0dee5SAndreas Gohr { 185dce0dee5SAndreas Gohr return $this->modelInfo['outputTokens']; 186dce0dee5SAndreas Gohr } 187dce0dee5SAndreas Gohr 188dce0dee5SAndreas Gohr public function getOutputTokenPrice(): float 189dce0dee5SAndreas Gohr { 190dce0dee5SAndreas Gohr return $this->modelInfo['outputTokenPrice']; 191dce0dee5SAndreas Gohr } 192dce0dee5SAndreas Gohr 193dce0dee5SAndreas Gohr // endregion 194dce0dee5SAndreas Gohr 195dce0dee5SAndreas Gohr // region API communication 196f6ef2e50SAndreas Gohr 197f6ef2e50SAndreas Gohr /** 19834a1c478SAndreas Gohr * When enabled, the input/output of the API will be printed to STDOUT 19934a1c478SAndreas Gohr * 20034a1c478SAndreas Gohr * @param bool $debug 20134a1c478SAndreas Gohr */ 20234a1c478SAndreas Gohr public function setDebug($debug = true) 20334a1c478SAndreas Gohr { 20434a1c478SAndreas Gohr $this->debug = $debug; 20534a1c478SAndreas Gohr } 20634a1c478SAndreas Gohr 20734a1c478SAndreas Gohr /** 208294a9eafSAndreas Gohr * This method should check the response for any errors. If the API singalled an error, 209294a9eafSAndreas Gohr * this method should throw an Exception with a meaningful error message. 210294a9eafSAndreas Gohr * 211294a9eafSAndreas Gohr * If the response returned any info on used tokens, they should be added to $this->tokensUsed 212294a9eafSAndreas Gohr * 213294a9eafSAndreas Gohr * The method should return the parsed response, which will be passed to the calling method. 214294a9eafSAndreas Gohr * 215294a9eafSAndreas Gohr * @param mixed $response the parsed JSON response from the API 216294a9eafSAndreas Gohr * @return mixed 217294a9eafSAndreas Gohr * @throws \Exception when the response indicates an error 218294a9eafSAndreas Gohr */ 219294a9eafSAndreas Gohr abstract protected function parseAPIResponse($response); 220294a9eafSAndreas Gohr 221294a9eafSAndreas Gohr /** 222294a9eafSAndreas Gohr * Send a request to the API 223294a9eafSAndreas Gohr * 224294a9eafSAndreas Gohr * Model classes should use this method to send requests to the API. 225294a9eafSAndreas Gohr * 226294a9eafSAndreas Gohr * This method will take care of retrying and logging basic statistics. 227294a9eafSAndreas Gohr * 228294a9eafSAndreas Gohr * It is assumed that all APIs speak JSON. 229294a9eafSAndreas Gohr * 230294a9eafSAndreas Gohr * @param string $method The HTTP method to use (GET, POST, PUT, DELETE, etc.) 231294a9eafSAndreas Gohr * @param string $url The full URL to send the request to 2324dd0657eSAndreas Gohr * @param array|string $data Payload to send, will be encoded to JSON 233294a9eafSAndreas Gohr * @param int $retry How often this request has been retried, do not set externally 234294a9eafSAndreas Gohr * @return array API response as returned by parseAPIResponse 235294a9eafSAndreas Gohr * @throws \Exception when anything goes wrong 236294a9eafSAndreas Gohr */ 237294a9eafSAndreas Gohr protected function sendAPIRequest($method, $url, $data, $retry = 0) 238294a9eafSAndreas Gohr { 239294a9eafSAndreas Gohr // init statistics 240294a9eafSAndreas Gohr if ($retry === 0) { 241294a9eafSAndreas Gohr $this->requestStart = microtime(true); 242294a9eafSAndreas Gohr } else { 243294a9eafSAndreas Gohr sleep($retry); // wait a bit between retries 244294a9eafSAndreas Gohr } 245294a9eafSAndreas Gohr $this->requestsMade++; 246294a9eafSAndreas Gohr 247294a9eafSAndreas Gohr // encode payload data 248294a9eafSAndreas Gohr try { 24934a1c478SAndreas Gohr $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT); 250294a9eafSAndreas Gohr } catch (\JsonException $e) { 251294a9eafSAndreas Gohr $this->timeUsed += $this->requestStart - microtime(true); 252*42b2c6e8SAndreas Gohr throw new \Exception('Failed to encode JSON for API:' . $e->getMessage(), 2003, $e); 253294a9eafSAndreas Gohr } 254294a9eafSAndreas Gohr 25534a1c478SAndreas Gohr if ($this->debug) { 25634a1c478SAndreas Gohr echo 'Sending ' . $method . ' request to ' . $url . ' with payload:' . "\n"; 25734a1c478SAndreas Gohr print_r($json); 25851aa8517SAndreas Gohr echo "\n"; 25934a1c478SAndreas Gohr } 26034a1c478SAndreas Gohr 261294a9eafSAndreas Gohr // send request and handle retries 262294a9eafSAndreas Gohr $this->http->sendRequest($url, $json, $method); 263294a9eafSAndreas Gohr $response = $this->http->resp_body; 264294a9eafSAndreas Gohr if ($response === false || $this->http->error) { 265294a9eafSAndreas Gohr if ($retry < self::MAX_RETRIES) { 266294a9eafSAndreas Gohr return $this->sendAPIRequest($method, $url, $data, $retry + 1); 267294a9eafSAndreas Gohr } 268294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 269*42b2c6e8SAndreas Gohr throw new \Exception('API returned no response. ' . $this->http->error, 2004); 270294a9eafSAndreas Gohr } 271294a9eafSAndreas Gohr 27234a1c478SAndreas Gohr if ($this->debug) { 27334a1c478SAndreas Gohr echo 'Received response:' . "\n"; 27434a1c478SAndreas Gohr print_r($response); 27551aa8517SAndreas Gohr echo "\n"; 27634a1c478SAndreas Gohr } 27734a1c478SAndreas Gohr 278294a9eafSAndreas Gohr // decode the response 279294a9eafSAndreas Gohr try { 280294a9eafSAndreas Gohr $result = json_decode((string)$response, true, 512, JSON_THROW_ON_ERROR); 281294a9eafSAndreas Gohr } catch (\JsonException $e) { 282294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 283*42b2c6e8SAndreas Gohr throw new \Exception('API returned invalid JSON: ' . $response, 2005, $e); 284294a9eafSAndreas Gohr } 285294a9eafSAndreas Gohr 286294a9eafSAndreas Gohr // parse the response, retry on error 287294a9eafSAndreas Gohr try { 288294a9eafSAndreas Gohr $result = $this->parseAPIResponse($result); 289294a9eafSAndreas Gohr } catch (\Exception $e) { 290294a9eafSAndreas Gohr if ($retry < self::MAX_RETRIES) { 291294a9eafSAndreas Gohr return $this->sendAPIRequest($method, $url, $data, $retry + 1); 292294a9eafSAndreas Gohr } 293294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 294294a9eafSAndreas Gohr throw $e; 295294a9eafSAndreas Gohr } 296294a9eafSAndreas Gohr 297294a9eafSAndreas Gohr $this->timeUsed += microtime(true) - $this->requestStart; 298294a9eafSAndreas Gohr return $result; 299294a9eafSAndreas Gohr } 300294a9eafSAndreas Gohr 301dce0dee5SAndreas Gohr // endregion 302f6ef2e50SAndreas Gohr} 303