xref: /plugin/aichat/Model/AbstractModel.php (revision 2071dced6f96936ea7b9bf5dbe8a117eef598448)
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    {
96*2071dcedSAndreas Gohr        $this->inputTokensUsed = 0;
97*2071dcedSAndreas Gohr        $this->outputTokensUsed = 0;
98dce0dee5SAndreas Gohr        $this->timeUsed = 0;
99dce0dee5SAndreas Gohr        $this->requestsMade = 0;
100dce0dee5SAndreas Gohr    }
101dce0dee5SAndreas Gohr
102dce0dee5SAndreas Gohr    /**
103dce0dee5SAndreas Gohr     * Get the usage statistics for this instance
104dce0dee5SAndreas Gohr     *
105dce0dee5SAndreas Gohr     * @return string[]
106dce0dee5SAndreas Gohr     */
107dce0dee5SAndreas Gohr    public function getUsageStats()
108dce0dee5SAndreas Gohr    {
109dce0dee5SAndreas Gohr
110dce0dee5SAndreas Gohr        $cost = 0;
111dce0dee5SAndreas Gohr        $cost += $this->inputTokensUsed * $this->getInputTokenPrice();
112dce0dee5SAndreas Gohr        if ($this instanceof ChatInterface) {
113dce0dee5SAndreas Gohr            $cost += $this->outputTokensUsed * $this->getOutputTokenPrice();
114dce0dee5SAndreas Gohr        }
115dce0dee5SAndreas Gohr
116dce0dee5SAndreas Gohr        return [
117dce0dee5SAndreas Gohr            'tokens' => $this->inputTokensUsed + $this->outputTokensUsed,
118c2b7a1f7SAndreas Gohr            'cost' => sprintf("%.6f", $cost / 1_000_000),
119dce0dee5SAndreas Gohr            'time' => round($this->timeUsed, 2),
120dce0dee5SAndreas Gohr            'requests' => $this->requestsMade,
121dce0dee5SAndreas Gohr        ];
122dce0dee5SAndreas Gohr    }
123dce0dee5SAndreas Gohr
124dce0dee5SAndreas Gohr    /** @inheritdoc */
125dce0dee5SAndreas Gohr    public function getMaxInputTokenLength(): int
126dce0dee5SAndreas Gohr    {
127dce0dee5SAndreas Gohr        return $this->modelInfo['inputTokens'];
128dce0dee5SAndreas Gohr    }
129dce0dee5SAndreas Gohr
130dce0dee5SAndreas Gohr    /** @inheritdoc */
131dce0dee5SAndreas Gohr    public function getInputTokenPrice(): float
132dce0dee5SAndreas Gohr    {
133dce0dee5SAndreas Gohr        return $this->modelInfo['inputTokenPrice'];
134dce0dee5SAndreas Gohr    }
135dce0dee5SAndreas Gohr
136dce0dee5SAndreas Gohr    // endregion
137dce0dee5SAndreas Gohr
138dce0dee5SAndreas Gohr    // region EmbeddingInterface
139dce0dee5SAndreas Gohr
140dce0dee5SAndreas Gohr    /** @inheritdoc */
141dce0dee5SAndreas Gohr    public function getDimensions(): int
142dce0dee5SAndreas Gohr    {
143dce0dee5SAndreas Gohr        return $this->modelInfo['dimensions'];
144dce0dee5SAndreas Gohr    }
145dce0dee5SAndreas Gohr
146dce0dee5SAndreas Gohr    // endregion
147dce0dee5SAndreas Gohr
148dce0dee5SAndreas Gohr    // region ChatInterface
149dce0dee5SAndreas Gohr
150dce0dee5SAndreas Gohr    public function getMaxOutputTokenLength(): int
151dce0dee5SAndreas Gohr    {
152dce0dee5SAndreas Gohr        return $this->modelInfo['outputTokens'];
153dce0dee5SAndreas Gohr    }
154dce0dee5SAndreas Gohr
155dce0dee5SAndreas Gohr    public function getOutputTokenPrice(): float
156dce0dee5SAndreas Gohr    {
157dce0dee5SAndreas Gohr        return $this->modelInfo['outputTokenPrice'];
158dce0dee5SAndreas Gohr    }
159dce0dee5SAndreas Gohr
160dce0dee5SAndreas Gohr    // endregion
161dce0dee5SAndreas Gohr
162dce0dee5SAndreas Gohr    // region API communication
163f6ef2e50SAndreas Gohr
164f6ef2e50SAndreas Gohr    /**
16534a1c478SAndreas Gohr     * When enabled, the input/output of the API will be printed to STDOUT
16634a1c478SAndreas Gohr     *
16734a1c478SAndreas Gohr     * @param bool $debug
16834a1c478SAndreas Gohr     */
16934a1c478SAndreas Gohr    public function setDebug($debug = true)
17034a1c478SAndreas Gohr    {
17134a1c478SAndreas Gohr        $this->debug = $debug;
17234a1c478SAndreas Gohr    }
17334a1c478SAndreas Gohr
17434a1c478SAndreas Gohr    /**
175294a9eafSAndreas Gohr     * This method should check the response for any errors. If the API singalled an error,
176294a9eafSAndreas Gohr     * this method should throw an Exception with a meaningful error message.
177294a9eafSAndreas Gohr     *
178294a9eafSAndreas Gohr     * If the response returned any info on used tokens, they should be added to $this->tokensUsed
179294a9eafSAndreas Gohr     *
180294a9eafSAndreas Gohr     * The method should return the parsed response, which will be passed to the calling method.
181294a9eafSAndreas Gohr     *
182294a9eafSAndreas Gohr     * @param mixed $response the parsed JSON response from the API
183294a9eafSAndreas Gohr     * @return mixed
184294a9eafSAndreas Gohr     * @throws \Exception when the response indicates an error
185294a9eafSAndreas Gohr     */
186294a9eafSAndreas Gohr    abstract protected function parseAPIResponse($response);
187294a9eafSAndreas Gohr
188294a9eafSAndreas Gohr    /**
189294a9eafSAndreas Gohr     * Send a request to the API
190294a9eafSAndreas Gohr     *
191294a9eafSAndreas Gohr     * Model classes should use this method to send requests to the API.
192294a9eafSAndreas Gohr     *
193294a9eafSAndreas Gohr     * This method will take care of retrying and logging basic statistics.
194294a9eafSAndreas Gohr     *
195294a9eafSAndreas Gohr     * It is assumed that all APIs speak JSON.
196294a9eafSAndreas Gohr     *
197294a9eafSAndreas Gohr     * @param string $method The HTTP method to use (GET, POST, PUT, DELETE, etc.)
198294a9eafSAndreas Gohr     * @param string $url The full URL to send the request to
199294a9eafSAndreas Gohr     * @param array $data Payload to send, will be encoded to JSON
200294a9eafSAndreas Gohr     * @param int $retry How often this request has been retried, do not set externally
201294a9eafSAndreas Gohr     * @return array API response as returned by parseAPIResponse
202294a9eafSAndreas Gohr     * @throws \Exception when anything goes wrong
203294a9eafSAndreas Gohr     */
204294a9eafSAndreas Gohr    protected function sendAPIRequest($method, $url, $data, $retry = 0)
205294a9eafSAndreas Gohr    {
206294a9eafSAndreas Gohr        // init statistics
207294a9eafSAndreas Gohr        if ($retry === 0) {
208294a9eafSAndreas Gohr            $this->requestStart = microtime(true);
209294a9eafSAndreas Gohr        } else {
210294a9eafSAndreas Gohr            sleep($retry); // wait a bit between retries
211294a9eafSAndreas Gohr        }
212294a9eafSAndreas Gohr        $this->requestsMade++;
213294a9eafSAndreas Gohr
214294a9eafSAndreas Gohr        // encode payload data
215294a9eafSAndreas Gohr        try {
21634a1c478SAndreas Gohr            $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
217294a9eafSAndreas Gohr        } catch (\JsonException $e) {
218294a9eafSAndreas Gohr            $this->timeUsed += $this->requestStart - microtime(true);
219294a9eafSAndreas Gohr            throw new \Exception('Failed to encode JSON for API:' . $e->getMessage(), $e->getCode(), $e);
220294a9eafSAndreas Gohr        }
221294a9eafSAndreas Gohr
22234a1c478SAndreas Gohr        if ($this->debug) {
22334a1c478SAndreas Gohr            echo 'Sending ' . $method . ' request to ' . $url . ' with payload:' . "\n";
22434a1c478SAndreas Gohr            print_r($json);
22551aa8517SAndreas Gohr            echo "\n";
22634a1c478SAndreas Gohr        }
22734a1c478SAndreas Gohr
228294a9eafSAndreas Gohr        // send request and handle retries
229294a9eafSAndreas Gohr        $this->http->sendRequest($url, $json, $method);
230294a9eafSAndreas Gohr        $response = $this->http->resp_body;
231294a9eafSAndreas Gohr        if ($response === false || $this->http->error) {
232294a9eafSAndreas Gohr            if ($retry < self::MAX_RETRIES) {
233294a9eafSAndreas Gohr                return $this->sendAPIRequest($method, $url, $data, $retry + 1);
234294a9eafSAndreas Gohr            }
235294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
236294a9eafSAndreas Gohr            throw new \Exception('API returned no response. ' . $this->http->error);
237294a9eafSAndreas Gohr        }
238294a9eafSAndreas Gohr
23934a1c478SAndreas Gohr        if ($this->debug) {
24034a1c478SAndreas Gohr            echo 'Received response:' . "\n";
24134a1c478SAndreas Gohr            print_r($response);
24251aa8517SAndreas Gohr            echo "\n";
24334a1c478SAndreas Gohr        }
24434a1c478SAndreas Gohr
245294a9eafSAndreas Gohr        // decode the response
246294a9eafSAndreas Gohr        try {
247294a9eafSAndreas Gohr            $result = json_decode((string)$response, true, 512, JSON_THROW_ON_ERROR);
248294a9eafSAndreas Gohr        } catch (\JsonException $e) {
249294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
250294a9eafSAndreas Gohr            throw new \Exception('API returned invalid JSON: ' . $response, 0, $e);
251294a9eafSAndreas Gohr        }
252294a9eafSAndreas Gohr
253294a9eafSAndreas Gohr        // parse the response, retry on error
254294a9eafSAndreas Gohr        try {
255294a9eafSAndreas Gohr            $result = $this->parseAPIResponse($result);
256294a9eafSAndreas Gohr        } catch (\Exception $e) {
257294a9eafSAndreas Gohr            if ($retry < self::MAX_RETRIES) {
258294a9eafSAndreas Gohr                return $this->sendAPIRequest($method, $url, $data, $retry + 1);
259294a9eafSAndreas Gohr            }
260294a9eafSAndreas Gohr            $this->timeUsed += microtime(true) - $this->requestStart;
261294a9eafSAndreas Gohr            throw $e;
262294a9eafSAndreas Gohr        }
263294a9eafSAndreas Gohr
264294a9eafSAndreas Gohr        $this->timeUsed += microtime(true) - $this->requestStart;
265294a9eafSAndreas Gohr        return $result;
266294a9eafSAndreas Gohr    }
267294a9eafSAndreas Gohr
268dce0dee5SAndreas Gohr    // endregion
269f6ef2e50SAndreas Gohr}
270