xref: /plugin/aichat/Model/AbstractModel.php (revision 7c3b69cbd638c7d1775b012bfb9b48d8136f76b9)
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;
282e22aefbSAndreas Gohr    /** @var string The provider name */
292e22aefbSAndreas Gohr    protected $selfIdent;
3034a1c478SAndreas Gohr
31dce0dee5SAndreas Gohr    /** @var int input tokens used since last reset */
3234a1c478SAndreas Gohr    protected $inputTokensUsed = 0;
33dce0dee5SAndreas Gohr    /** @var int output tokens used since last reset */
3434a1c478SAndreas Gohr    protected $outputTokensUsed = 0;
35dce0dee5SAndreas Gohr    /** @var int total time spent in requests since last reset */
36f6ef2e50SAndreas Gohr    protected $timeUsed = 0;
37dce0dee5SAndreas Gohr    /** @var int total number of requests made since last reset */
38f6ef2e50SAndreas Gohr    protected $requestsMade = 0;
39294a9eafSAndreas Gohr    /** @var int start time of the current request chain (may be multiple when retries needed) */
40294a9eafSAndreas Gohr    protected $requestStart = 0;
41f6ef2e50SAndreas Gohr
42dce0dee5SAndreas Gohr    /** @var int How often to retry a request if it fails */
43dce0dee5SAndreas Gohr    public const MAX_RETRIES = 3;
44dce0dee5SAndreas Gohr
45dce0dee5SAndreas Gohr    /** @var DokuHTTPClient */
46dce0dee5SAndreas Gohr    protected $http;
47dce0dee5SAndreas Gohr    /** @var bool debug API communication */
48dce0dee5SAndreas Gohr    protected $debug = false;
49dce0dee5SAndreas Gohr
50*7c3b69cbSAndreas Gohr    /** @var array The plugin configuration */
51*7c3b69cbSAndreas Gohr    protected $config;
52*7c3b69cbSAndreas Gohr
53dce0dee5SAndreas Gohr    // region ModelInterface
54dce0dee5SAndreas Gohr
55dce0dee5SAndreas Gohr    /** @inheritdoc */
56dce0dee5SAndreas Gohr    public function __construct(string $name, array $config)
57294a9eafSAndreas Gohr    {
58dce0dee5SAndreas Gohr        $this->modelName = $name;
59*7c3b69cbSAndreas Gohr        $this->config = $config;
60dce0dee5SAndreas Gohr
61dce0dee5SAndreas Gohr        $reflect = new \ReflectionClass($this);
62dce0dee5SAndreas Gohr        $json = dirname($reflect->getFileName()) . '/models.json';
63dce0dee5SAndreas Gohr        if (!file_exists($json)) {
6442b2c6e8SAndreas Gohr            throw new \Exception('Model info file not found at ' . $json, 2001);
65294a9eafSAndreas Gohr        }
66dce0dee5SAndreas Gohr        try {
67dce0dee5SAndreas Gohr            $modelinfos = json_decode(file_get_contents($json), true, 512, JSON_THROW_ON_ERROR);
68dce0dee5SAndreas Gohr        } catch (\JsonException $e) {
6942b2c6e8SAndreas Gohr            throw new \Exception('Failed to parse model info file: ' . $e->getMessage(), 2002, $e);
70dce0dee5SAndreas Gohr        }
71dce0dee5SAndreas Gohr
722e22aefbSAndreas Gohr        $this->selfIdent = basename(dirname($reflect->getFileName()));
73e3b34a2bSAndreas Gohr        $this->modelFullName = basename(dirname($reflect->getFileName())) . ' ' . $name;
74b446155bSAndreas Gohr
75dce0dee5SAndreas Gohr        if ($this instanceof ChatInterface) {
764dd0657eSAndreas Gohr            if (isset($modelinfos['chat'][$name])) {
77dce0dee5SAndreas Gohr                $this->modelInfo = $modelinfos['chat'][$name];
784dd0657eSAndreas Gohr            } else {
794dd0657eSAndreas Gohr                $this->modelInfo = $this->loadUnknownModelInfo();
804dd0657eSAndreas Gohr            }
814dd0657eSAndreas Gohr
82dce0dee5SAndreas Gohr        }
83dce0dee5SAndreas Gohr
84dce0dee5SAndreas Gohr        if ($this instanceof EmbeddingInterface) {
854dd0657eSAndreas Gohr            if (isset($modelinfos['embedding'][$name])) {
86dce0dee5SAndreas Gohr                $this->modelInfo = $modelinfos['embedding'][$name];
874dd0657eSAndreas Gohr            } else {
884dd0657eSAndreas Gohr                $this->modelInfo = $this->loadUnknownModelInfo();
894dd0657eSAndreas Gohr            }
90dce0dee5SAndreas Gohr        }
91dce0dee5SAndreas Gohr    }
92dce0dee5SAndreas Gohr
93dce0dee5SAndreas Gohr    /** @inheritdoc */
94b446155bSAndreas Gohr    public function __toString(): string
95b446155bSAndreas Gohr    {
96b446155bSAndreas Gohr        return $this->modelFullName;
97b446155bSAndreas Gohr    }
98b446155bSAndreas Gohr
99b446155bSAndreas Gohr    /** @inheritdoc */
100dce0dee5SAndreas Gohr    public function getModelName()
101dce0dee5SAndreas Gohr    {
102dce0dee5SAndreas Gohr        return $this->modelName;
103dce0dee5SAndreas Gohr    }
104dce0dee5SAndreas Gohr
105dce0dee5SAndreas Gohr    /**
106dce0dee5SAndreas Gohr     * Reset the usage statistics
107dce0dee5SAndreas Gohr     *
108dce0dee5SAndreas Gohr     * Usually not needed when only handling one operation per request, but useful in CLI
109dce0dee5SAndreas Gohr     */
110dce0dee5SAndreas Gohr    public function resetUsageStats()
111dce0dee5SAndreas Gohr    {
1122071dcedSAndreas Gohr        $this->inputTokensUsed = 0;
1132071dcedSAndreas Gohr        $this->outputTokensUsed = 0;
114dce0dee5SAndreas Gohr        $this->timeUsed = 0;
115dce0dee5SAndreas Gohr        $this->requestsMade = 0;
116dce0dee5SAndreas Gohr    }
117dce0dee5SAndreas Gohr
118dce0dee5SAndreas Gohr    /**
119dce0dee5SAndreas Gohr     * Get the usage statistics for this instance
120dce0dee5SAndreas Gohr     *
121dce0dee5SAndreas Gohr     * @return string[]
122dce0dee5SAndreas Gohr     */
123dce0dee5SAndreas Gohr    public function getUsageStats()
124dce0dee5SAndreas Gohr    {
125dce0dee5SAndreas Gohr
126dce0dee5SAndreas Gohr        $cost = 0;
127dce0dee5SAndreas Gohr        $cost += $this->inputTokensUsed * $this->getInputTokenPrice();
128dce0dee5SAndreas Gohr        if ($this instanceof ChatInterface) {
129dce0dee5SAndreas Gohr            $cost += $this->outputTokensUsed * $this->getOutputTokenPrice();
130dce0dee5SAndreas Gohr        }
131dce0dee5SAndreas Gohr
132dce0dee5SAndreas Gohr        return [
133dce0dee5SAndreas Gohr            'tokens' => $this->inputTokensUsed + $this->outputTokensUsed,
134c2b7a1f7SAndreas Gohr            'cost' => sprintf("%.6f", $cost / 1_000_000),
135dce0dee5SAndreas Gohr            'time' => round($this->timeUsed, 2),
136dce0dee5SAndreas Gohr            'requests' => $this->requestsMade,
137dce0dee5SAndreas Gohr        ];
138dce0dee5SAndreas Gohr    }
139dce0dee5SAndreas Gohr
140dce0dee5SAndreas Gohr    /** @inheritdoc */
141dce0dee5SAndreas Gohr    public function getMaxInputTokenLength(): int
142dce0dee5SAndreas Gohr    {
1437be8078eSAndreas Gohr        return $this->modelInfo['inputTokens'] ?? 0;
144dce0dee5SAndreas Gohr    }
145dce0dee5SAndreas Gohr
146dce0dee5SAndreas Gohr    /** @inheritdoc */
147dce0dee5SAndreas Gohr    public function getInputTokenPrice(): float
148dce0dee5SAndreas Gohr    {
1497be8078eSAndreas Gohr        return $this->modelInfo['inputTokenPrice'] ?? 0;
150dce0dee5SAndreas Gohr    }
151dce0dee5SAndreas Gohr
1524dd0657eSAndreas Gohr    /** @inheritdoc */
1534dd0657eSAndreas Gohr    function loadUnknownModelInfo(): array
1544dd0657eSAndreas Gohr    {
1554dd0657eSAndreas Gohr        $info = [
1564dd0657eSAndreas Gohr            'description' => $this->modelFullName,
1577be8078eSAndreas Gohr            'inputTokens' => 0,
1584dd0657eSAndreas Gohr            'inputTokenPrice' => 0,
1594dd0657eSAndreas Gohr        ];
1604dd0657eSAndreas Gohr
1614dd0657eSAndreas Gohr        if ($this instanceof ChatInterface) {
1627be8078eSAndreas Gohr            $info['outputTokens'] = 0;
1634dd0657eSAndreas Gohr            $info['outputTokenPrice'] = 0;
1644dd0657eSAndreas Gohr        } elseif ($this instanceof EmbeddingInterface) {
1654dd0657eSAndreas Gohr            $info['dimensions'] = 512;
1664dd0657eSAndreas Gohr        }
1674dd0657eSAndreas Gohr
1684dd0657eSAndreas Gohr        return $info;
1694dd0657eSAndreas Gohr    }
1704dd0657eSAndreas Gohr
171dce0dee5SAndreas Gohr    // endregion
172dce0dee5SAndreas Gohr
173dce0dee5SAndreas Gohr    // region EmbeddingInterface
174dce0dee5SAndreas Gohr
175dce0dee5SAndreas Gohr    /** @inheritdoc */
176dce0dee5SAndreas Gohr    public function getDimensions(): int
177dce0dee5SAndreas Gohr    {
178dce0dee5SAndreas Gohr        return $this->modelInfo['dimensions'];
179dce0dee5SAndreas Gohr    }
180dce0dee5SAndreas Gohr
181dce0dee5SAndreas Gohr    // endregion
182dce0dee5SAndreas Gohr
183dce0dee5SAndreas Gohr    // region ChatInterface
184dce0dee5SAndreas Gohr
185dce0dee5SAndreas Gohr    public function getMaxOutputTokenLength(): int
186dce0dee5SAndreas Gohr    {
187dce0dee5SAndreas Gohr        return $this->modelInfo['outputTokens'];
188dce0dee5SAndreas Gohr    }
189dce0dee5SAndreas Gohr
190dce0dee5SAndreas Gohr    public function getOutputTokenPrice(): float
191dce0dee5SAndreas Gohr    {
192dce0dee5SAndreas Gohr        return $this->modelInfo['outputTokenPrice'];
193dce0dee5SAndreas Gohr    }
194dce0dee5SAndreas Gohr
195dce0dee5SAndreas Gohr    // endregion
196dce0dee5SAndreas Gohr
197dce0dee5SAndreas Gohr    // region API communication
198f6ef2e50SAndreas Gohr
199f6ef2e50SAndreas Gohr    /**
20034a1c478SAndreas Gohr     * When enabled, the input/output of the API will be printed to STDOUT
20134a1c478SAndreas Gohr     *
20234a1c478SAndreas Gohr     * @param bool $debug
20334a1c478SAndreas Gohr     */
20434a1c478SAndreas Gohr    public function setDebug($debug = true)
20534a1c478SAndreas Gohr    {
20634a1c478SAndreas Gohr        $this->debug = $debug;
20734a1c478SAndreas Gohr    }
20834a1c478SAndreas Gohr
20934a1c478SAndreas Gohr    /**
210*7c3b69cbSAndreas Gohr     * Get the HTTP client used for API requests
211*7c3b69cbSAndreas Gohr     *
212*7c3b69cbSAndreas Gohr     * This method will create a new DokuHTTPClient instance if it does not exist yet.
213*7c3b69cbSAndreas Gohr     * The client will be configured with a timeout and the appropriate headers for JSON communication.
214*7c3b69cbSAndreas Gohr     * Inheriting models should override this method if they need to add additional headers or configuration
215*7c3b69cbSAndreas Gohr     * to the HTTP client.
216*7c3b69cbSAndreas Gohr     *
217*7c3b69cbSAndreas Gohr     * @return DokuHTTPClient
218*7c3b69cbSAndreas Gohr     */
219*7c3b69cbSAndreas Gohr    protected function getHttpClient()
220*7c3b69cbSAndreas Gohr    {
221*7c3b69cbSAndreas Gohr        if($this->http === null) {
222*7c3b69cbSAndreas Gohr            $this->http = new DokuHTTPClient();
223*7c3b69cbSAndreas Gohr            $this->http->timeout = 60;
224*7c3b69cbSAndreas Gohr            $this->http->headers['Content-Type'] = 'application/json';
225*7c3b69cbSAndreas Gohr            $this->http->headers['Accept'] = 'application/json';
226*7c3b69cbSAndreas Gohr        }
227*7c3b69cbSAndreas Gohr
228*7c3b69cbSAndreas Gohr        return $this->http;
229*7c3b69cbSAndreas Gohr    }
230*7c3b69cbSAndreas Gohr
231*7c3b69cbSAndreas Gohr    /**
232294a9eafSAndreas Gohr     * This method should check the response for any errors. If the API singalled an error,
233294a9eafSAndreas Gohr     * this method should throw an Exception with a meaningful error message.
234294a9eafSAndreas Gohr     *
235294a9eafSAndreas Gohr     * If the response returned any info on used tokens, they should be added to $this->tokensUsed
236294a9eafSAndreas Gohr     *
237294a9eafSAndreas Gohr     * The method should return the parsed response, which will be passed to the calling method.
238294a9eafSAndreas Gohr     *
239294a9eafSAndreas Gohr     * @param mixed $response the parsed JSON response from the API
240294a9eafSAndreas Gohr     * @return mixed
241294a9eafSAndreas Gohr     * @throws \Exception when the response indicates an error
242294a9eafSAndreas Gohr     */
243294a9eafSAndreas Gohr    abstract protected function parseAPIResponse($response);
244294a9eafSAndreas Gohr
245294a9eafSAndreas Gohr    /**
246294a9eafSAndreas Gohr     * Send a request to the API
247294a9eafSAndreas Gohr     *
248294a9eafSAndreas Gohr     * Model classes should use this method to send requests to the API.
249294a9eafSAndreas Gohr     *
250294a9eafSAndreas Gohr     * This method will take care of retrying and logging basic statistics.
251294a9eafSAndreas Gohr     *
252294a9eafSAndreas Gohr     * It is assumed that all APIs speak JSON.
253294a9eafSAndreas Gohr     *
254294a9eafSAndreas Gohr     * @param string $method The HTTP method to use (GET, POST, PUT, DELETE, etc.)
255294a9eafSAndreas Gohr     * @param string $url The full URL to send the request to
2564dd0657eSAndreas Gohr     * @param array|string $data Payload to send, will be encoded to JSON
257294a9eafSAndreas Gohr     * @param int $retry How often this request has been retried, do not set externally
258294a9eafSAndreas Gohr     * @return array API response as returned by parseAPIResponse
259294a9eafSAndreas Gohr     * @throws \Exception when anything goes wrong
260294a9eafSAndreas Gohr     */
261294a9eafSAndreas Gohr    protected function sendAPIRequest($method, $url, $data, $retry = 0)
262294a9eafSAndreas Gohr    {
263294a9eafSAndreas Gohr        // init statistics
264294a9eafSAndreas Gohr        if ($retry === 0) {
265294a9eafSAndreas Gohr            $this->requestStart = microtime(true);
266294a9eafSAndreas Gohr        } else {
267294a9eafSAndreas Gohr            sleep($retry); // wait a bit between retries
268294a9eafSAndreas Gohr        }
269294a9eafSAndreas Gohr        $this->requestsMade++;
270294a9eafSAndreas Gohr
271294a9eafSAndreas Gohr        // encode payload data
272294a9eafSAndreas Gohr        try {
27334a1c478SAndreas Gohr            $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
274294a9eafSAndreas Gohr        } catch (\JsonException $e) {
275294a9eafSAndreas Gohr            $this->timeUsed += $this->requestStart - microtime(true);
27642b2c6e8SAndreas Gohr            throw new \Exception('Failed to encode JSON for API:' . $e->getMessage(), 2003, $e);
277294a9eafSAndreas Gohr        }
278294a9eafSAndreas Gohr
27934a1c478SAndreas Gohr        if ($this->debug) {
28034a1c478SAndreas Gohr            echo 'Sending ' . $method . ' request to ' . $url . ' with payload:' . "\n";
28134a1c478SAndreas Gohr            print_r($json);
28251aa8517SAndreas Gohr            echo "\n";
28334a1c478SAndreas Gohr        }
28434a1c478SAndreas Gohr
285294a9eafSAndreas Gohr        // send request and handle retries
286*7c3b69cbSAndreas Gohr        $http = $this->getHttpClient();
287*7c3b69cbSAndreas Gohr        $http->sendRequest($url, $json, $method);
288*7c3b69cbSAndreas Gohr        $response = $http->resp_body;
289*7c3b69cbSAndreas Gohr        if ($response === false || $http->error) {
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;
294*7c3b69cbSAndreas Gohr            throw new \Exception('API returned no response. ' . $http->error, 2004);
295294a9eafSAndreas Gohr        }
296294a9eafSAndreas Gohr
29734a1c478SAndreas Gohr        if ($this->debug) {
29834a1c478SAndreas Gohr            echo 'Received response:' . "\n";
29934a1c478SAndreas Gohr            print_r($response);
30051aa8517SAndreas Gohr            echo "\n";
30134a1c478SAndreas Gohr        }
30234a1c478SAndreas Gohr
303294a9eafSAndreas Gohr        // decode the response
304294a9eafSAndreas Gohr        try {
305294a9eafSAndreas Gohr            $result = json_decode((string)$response, true, 512, JSON_THROW_ON_ERROR);
306294a9eafSAndreas Gohr        } catch (\JsonException $e) {
307294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
30842b2c6e8SAndreas Gohr            throw new \Exception('API returned invalid JSON: ' . $response, 2005, $e);
309294a9eafSAndreas Gohr        }
310294a9eafSAndreas Gohr
311294a9eafSAndreas Gohr        // parse the response, retry on error
312294a9eafSAndreas Gohr        try {
313294a9eafSAndreas Gohr            $result = $this->parseAPIResponse($result);
314294a9eafSAndreas Gohr        } catch (\Exception $e) {
315294a9eafSAndreas Gohr            if ($retry < self::MAX_RETRIES) {
316294a9eafSAndreas Gohr                return $this->sendAPIRequest($method, $url, $data, $retry + 1);
317294a9eafSAndreas Gohr            }
318294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
319294a9eafSAndreas Gohr            throw $e;
320294a9eafSAndreas Gohr        }
321294a9eafSAndreas Gohr
322294a9eafSAndreas Gohr        $this->timeUsed += microtime(true) - $this->requestStart;
323294a9eafSAndreas Gohr        return $result;
324294a9eafSAndreas Gohr    }
325294a9eafSAndreas Gohr
326dce0dee5SAndreas Gohr    // endregion
3272e22aefbSAndreas Gohr
3282e22aefbSAndreas Gohr    // region Tools
3292e22aefbSAndreas Gohr
3302e22aefbSAndreas Gohr    /**
3312e22aefbSAndreas Gohr     * Get a configuration value
3322e22aefbSAndreas Gohr     *
3332e22aefbSAndreas Gohr     * The given key is prefixed by the model namespace
3342e22aefbSAndreas Gohr     *
3352e22aefbSAndreas Gohr     * @param string $key
3362e22aefbSAndreas Gohr     * @param mixed $default The default to return if the key is not found. When set to null an Exception is thrown.
3372e22aefbSAndreas Gohr     * @return mixed
3382e22aefbSAndreas Gohr     * @throws ModelException when the key is not found and no default is given
3392e22aefbSAndreas Gohr     */
340*7c3b69cbSAndreas Gohr    public function getFromConf(string $key, $default = null)
3412e22aefbSAndreas Gohr    {
342*7c3b69cbSAndreas Gohr        $config = $this->config;
343*7c3b69cbSAndreas Gohr
3442e22aefbSAndreas Gohr        $key = strtolower($this->selfIdent) . '_' . $key;
3452e22aefbSAndreas Gohr        if (isset($config[$key])) {
3462e22aefbSAndreas Gohr            return $config[$key];
3472e22aefbSAndreas Gohr        }
3482e22aefbSAndreas Gohr        if ($default !== null) {
3492e22aefbSAndreas Gohr            return $default;
3502e22aefbSAndreas Gohr        }
3512e22aefbSAndreas Gohr        throw new ModelException('Key ' . $key . ' not found in configuration', 3001);
3522e22aefbSAndreas Gohr    }
3532e22aefbSAndreas Gohr
3542e22aefbSAndreas Gohr    // endregion
355f6ef2e50SAndreas Gohr}
356