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        if (empty($config['mistral_apikey'])) {
19            throw new \Exception('Mistral API key not configured');
20        }
21        $this->http->headers['Authorization'] = 'Bearer ' . $config['mistral_apikey'];
22    }
23
24    /**
25     * Send a request to the OpenAI API
26     *
27     * @param string $endpoint
28     * @param array $data Payload to send
29     * @return array API response
30     * @throws \Exception
31     */
32    protected function request($endpoint, $data)
33    {
34        $url = 'https://api.mistral.ai/v1/' . $endpoint;
35        return $this->sendAPIRequest('POST', $url, $data);
36    }
37
38    /** @inheritdoc */
39    protected function parseAPIResponse($response)
40    {
41        if (isset($response['usage'])) {
42            $this->inputTokensUsed += $response['usage']['prompt_tokens'];
43            $this->outputTokensUsed += $response['usage']['completion_tokens'] ?? 0;
44        }
45
46        if (isset($response['object']) && $response['object'] === 'error') {
47            throw new \Exception('Mistral API error: ' . $response['message']);
48        }
49
50        return $response;
51    }
52
53    /**
54     * @internal for checking available models
55     */
56    public function listUpstreamModels()
57    {
58        $url = 'https://api.openai.com/v1/models';
59        return $this->http->get($url);
60    }
61}
62