xref: /plugin/aichat/Model/AbstractModel.php (revision 7be8078ef9026e317a5c01f90a94183276bbbbd2)
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
50dce0dee5SAndreas Gohr    // region ModelInterface
51dce0dee5SAndreas Gohr
52dce0dee5SAndreas Gohr    /** @inheritdoc */
53dce0dee5SAndreas Gohr    public function __construct(string $name, array $config)
54294a9eafSAndreas Gohr    {
55dce0dee5SAndreas Gohr        $this->modelName = $name;
56294a9eafSAndreas Gohr        $this->http = new DokuHTTPClient();
57294a9eafSAndreas Gohr        $this->http->timeout = 60;
58294a9eafSAndreas Gohr        $this->http->headers['Content-Type'] = 'application/json';
59cfd76f4aSAndreas Gohr        $this->http->headers['Accept'] = 'application/json';
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    {
143*7be8078eSAndreas Gohr        return $this->modelInfo['inputTokens'] ?? 0;
144dce0dee5SAndreas Gohr    }
145dce0dee5SAndreas Gohr
146dce0dee5SAndreas Gohr    /** @inheritdoc */
147dce0dee5SAndreas Gohr    public function getInputTokenPrice(): float
148dce0dee5SAndreas Gohr    {
149*7be8078eSAndreas 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,
157*7be8078eSAndreas Gohr            'inputTokens' => 0,
1584dd0657eSAndreas Gohr            'inputTokenPrice' => 0,
1594dd0657eSAndreas Gohr        ];
1604dd0657eSAndreas Gohr
1614dd0657eSAndreas Gohr        if ($this instanceof ChatInterface) {
162*7be8078eSAndreas 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    /**
210294a9eafSAndreas Gohr     * This method should check the response for any errors. If the API singalled an error,
211294a9eafSAndreas Gohr     * this method should throw an Exception with a meaningful error message.
212294a9eafSAndreas Gohr     *
213294a9eafSAndreas Gohr     * If the response returned any info on used tokens, they should be added to $this->tokensUsed
214294a9eafSAndreas Gohr     *
215294a9eafSAndreas Gohr     * The method should return the parsed response, which will be passed to the calling method.
216294a9eafSAndreas Gohr     *
217294a9eafSAndreas Gohr     * @param mixed $response the parsed JSON response from the API
218294a9eafSAndreas Gohr     * @return mixed
219294a9eafSAndreas Gohr     * @throws \Exception when the response indicates an error
220294a9eafSAndreas Gohr     */
221294a9eafSAndreas Gohr    abstract protected function parseAPIResponse($response);
222294a9eafSAndreas Gohr
223294a9eafSAndreas Gohr    /**
224294a9eafSAndreas Gohr     * Send a request to the API
225294a9eafSAndreas Gohr     *
226294a9eafSAndreas Gohr     * Model classes should use this method to send requests to the API.
227294a9eafSAndreas Gohr     *
228294a9eafSAndreas Gohr     * This method will take care of retrying and logging basic statistics.
229294a9eafSAndreas Gohr     *
230294a9eafSAndreas Gohr     * It is assumed that all APIs speak JSON.
231294a9eafSAndreas Gohr     *
232294a9eafSAndreas Gohr     * @param string $method The HTTP method to use (GET, POST, PUT, DELETE, etc.)
233294a9eafSAndreas Gohr     * @param string $url The full URL to send the request to
2344dd0657eSAndreas Gohr     * @param array|string $data Payload to send, will be encoded to JSON
235294a9eafSAndreas Gohr     * @param int $retry How often this request has been retried, do not set externally
236294a9eafSAndreas Gohr     * @return array API response as returned by parseAPIResponse
237294a9eafSAndreas Gohr     * @throws \Exception when anything goes wrong
238294a9eafSAndreas Gohr     */
239294a9eafSAndreas Gohr    protected function sendAPIRequest($method, $url, $data, $retry = 0)
240294a9eafSAndreas Gohr    {
241294a9eafSAndreas Gohr        // init statistics
242294a9eafSAndreas Gohr        if ($retry === 0) {
243294a9eafSAndreas Gohr            $this->requestStart = microtime(true);
244294a9eafSAndreas Gohr        } else {
245294a9eafSAndreas Gohr            sleep($retry); // wait a bit between retries
246294a9eafSAndreas Gohr        }
247294a9eafSAndreas Gohr        $this->requestsMade++;
248294a9eafSAndreas Gohr
249294a9eafSAndreas Gohr        // encode payload data
250294a9eafSAndreas Gohr        try {
25134a1c478SAndreas Gohr            $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
252294a9eafSAndreas Gohr        } catch (\JsonException $e) {
253294a9eafSAndreas Gohr            $this->timeUsed += $this->requestStart - microtime(true);
25442b2c6e8SAndreas Gohr            throw new \Exception('Failed to encode JSON for API:' . $e->getMessage(), 2003, $e);
255294a9eafSAndreas Gohr        }
256294a9eafSAndreas Gohr
25734a1c478SAndreas Gohr        if ($this->debug) {
25834a1c478SAndreas Gohr            echo 'Sending ' . $method . ' request to ' . $url . ' with payload:' . "\n";
25934a1c478SAndreas Gohr            print_r($json);
26051aa8517SAndreas Gohr            echo "\n";
26134a1c478SAndreas Gohr        }
26234a1c478SAndreas Gohr
263294a9eafSAndreas Gohr        // send request and handle retries
264294a9eafSAndreas Gohr        $this->http->sendRequest($url, $json, $method);
265294a9eafSAndreas Gohr        $response = $this->http->resp_body;
266294a9eafSAndreas Gohr        if ($response === false || $this->http->error) {
267294a9eafSAndreas Gohr            if ($retry < self::MAX_RETRIES) {
268294a9eafSAndreas Gohr                return $this->sendAPIRequest($method, $url, $data, $retry + 1);
269294a9eafSAndreas Gohr            }
270294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
27142b2c6e8SAndreas Gohr            throw new \Exception('API returned no response. ' . $this->http->error, 2004);
272294a9eafSAndreas Gohr        }
273294a9eafSAndreas Gohr
27434a1c478SAndreas Gohr        if ($this->debug) {
27534a1c478SAndreas Gohr            echo 'Received response:' . "\n";
27634a1c478SAndreas Gohr            print_r($response);
27751aa8517SAndreas Gohr            echo "\n";
27834a1c478SAndreas Gohr        }
27934a1c478SAndreas Gohr
280294a9eafSAndreas Gohr        // decode the response
281294a9eafSAndreas Gohr        try {
282294a9eafSAndreas Gohr            $result = json_decode((string)$response, true, 512, JSON_THROW_ON_ERROR);
283294a9eafSAndreas Gohr        } catch (\JsonException $e) {
284294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
28542b2c6e8SAndreas Gohr            throw new \Exception('API returned invalid JSON: ' . $response, 2005, $e);
286294a9eafSAndreas Gohr        }
287294a9eafSAndreas Gohr
288294a9eafSAndreas Gohr        // parse the response, retry on error
289294a9eafSAndreas Gohr        try {
290294a9eafSAndreas Gohr            $result = $this->parseAPIResponse($result);
291294a9eafSAndreas Gohr        } catch (\Exception $e) {
292294a9eafSAndreas Gohr            if ($retry < self::MAX_RETRIES) {
293294a9eafSAndreas Gohr                return $this->sendAPIRequest($method, $url, $data, $retry + 1);
294294a9eafSAndreas Gohr            }
295294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
296294a9eafSAndreas Gohr            throw $e;
297294a9eafSAndreas Gohr        }
298294a9eafSAndreas Gohr
299294a9eafSAndreas Gohr        $this->timeUsed += microtime(true) - $this->requestStart;
300294a9eafSAndreas Gohr        return $result;
301294a9eafSAndreas Gohr    }
302294a9eafSAndreas Gohr
303dce0dee5SAndreas Gohr    // endregion
3042e22aefbSAndreas Gohr
3052e22aefbSAndreas Gohr    // region Tools
3062e22aefbSAndreas Gohr
3072e22aefbSAndreas Gohr    /**
3082e22aefbSAndreas Gohr     * Get a configuration value
3092e22aefbSAndreas Gohr     *
3102e22aefbSAndreas Gohr     * The given key is prefixed by the model namespace
3112e22aefbSAndreas Gohr     *
3122e22aefbSAndreas Gohr     * @param string $key
3132e22aefbSAndreas Gohr     * @param mixed $default The default to return if the key is not found. When set to null an Exception is thrown.
3142e22aefbSAndreas Gohr     * @return mixed
3152e22aefbSAndreas Gohr     * @throws ModelException when the key is not found and no default is given
3162e22aefbSAndreas Gohr     */
3172e22aefbSAndreas Gohr    public function getFromConf(array $config, string $key, $default = null)
3182e22aefbSAndreas Gohr    {
3192e22aefbSAndreas Gohr        $key = strtolower($this->selfIdent) . '_' . $key;
3202e22aefbSAndreas Gohr        if (isset($config[$key])) {
3212e22aefbSAndreas Gohr            return $config[$key];
3222e22aefbSAndreas Gohr        }
3232e22aefbSAndreas Gohr        if ($default !== null) {
3242e22aefbSAndreas Gohr            return $default;
3252e22aefbSAndreas Gohr        }
3262e22aefbSAndreas Gohr        throw new ModelException('Key ' . $key . ' not found in configuration', 3001);
3272e22aefbSAndreas Gohr    }
3282e22aefbSAndreas Gohr
3292e22aefbSAndreas Gohr// endregion
330f6ef2e50SAndreas Gohr}
331