xref: /plugin/aichat/Model/Mistral/AbstractMistralModel.php (revision cfd76f4aad2ef41879e225ffbf2e137d24b4a079)
1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Mistral;
4
5use dokuwiki\plugin\aichat\Model\AbstractModel;
6
7/**
8 * Abstract OpenAI Model
9 *
10 * This class provides a basic interface to the OpenAI API
11 */
12abstract class AbstractMistralModel extends AbstractModel
13{
14    /** @inheritdoc */
15    public function __construct(string $name, array $config)
16    {
17        parent::__construct($name, $config);
18        $this->http->headers['Authorization'] = 'Bearer ' . $config['mistral_apikey'] ?? '';
19    }
20
21    /**
22     * Send a request to the OpenAI API
23     *
24     * @param string $endpoint
25     * @param array $data Payload to send
26     * @return array API response
27     * @throws \Exception
28     */
29    protected function request($endpoint, $data)
30    {
31        $url = 'https://api.mistral.ai/v1/' . $endpoint;
32        return $this->sendAPIRequest('POST', $url, $data);
33    }
34
35    /** @inheritdoc */
36    protected function parseAPIResponse($response)
37    {
38        if (isset($response['usage'])) {
39            $this->inputTokensUsed += $response['usage']['prompt_tokens'];
40            $this->outputTokensUsed += $response['usage']['completion_tokens'] ?? 0;
41        }
42
43        if (isset($response['error'])) {
44            throw new \Exception('Mistral API error: ' . $response['error']['message']);
45        }
46
47        return $response;
48    }
49
50    /**
51     * @internal for checking available models
52     */
53    public function listUpstreamModels()
54    {
55        $url = 'https://api.openai.com/v1/models';
56        return $this->http->get($url);
57    }
58}
59