1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Gemini;
4
5use dokuwiki\plugin\aichat\Model\AbstractModel;
6
7abstract class AbstractGeminiModel extends AbstractModel
8{
9
10    /** @var string Gemini API key */
11    protected $apikey;
12
13    /** @inheritdoc */
14    public function __construct(string $name, array $config)
15    {
16        if (empty($config['gemini_apikey'])) {
17            throw new \Exception('Gemini API key not configured', 3001);
18        }
19
20        $this->apikey = $config['gemini_apikey'];
21
22        parent::__construct($name, $config);
23    }
24
25    /** @inheritdoc */
26    function loadUnknownModelInfo(): array
27    {
28        $url = sprintf(
29            'https://generativelanguage.googleapis.com/v1beta/models/%s?key=%s',
30            $this->modelName,
31            $this->apikey
32        );
33        $result = $this->sendAPIRequest('GET', $url, '');
34        if(!$result) {
35            throw new \Exception('Failed to load model info for '.$this->modelFullName, 3003);
36        }
37
38        $info = parent::loadUnknownModelInfo();
39        $info['description'] = $result['description'];
40        $info['inputTokens'] = $result['inputTokenLimit'];
41        $info['outputTokens'] = $result['outputTokenLimit'];
42        return $info;
43    }
44
45    /**
46     * Send a request to the Gemini API
47     *
48     * @param string $endpoint
49     * @param array $data Payload to send
50     * @return array API response
51     * @throws \Exception
52     */
53    protected function request($model, $endpoint, $data)
54    {
55        $url = sprintf(
56            'https://generativelanguage.googleapis.com/v1beta/models/%s:%s?key=%s',
57            $model,
58            $endpoint,
59            $this->apikey
60        );
61
62        return $this->sendAPIRequest('POST', $url, $data);
63    }
64
65    /** @inheritdoc */
66    protected function parseAPIResponse($response)
67    {
68        if (isset($response['usageMetadata'])) {
69            $this->inputTokensUsed += $response['usageMetadata']['promptTokenCount'];
70            $this->outputTokensUsed += $response['usageMetadata']['candidatesTokenCount'] ?? 0;
71        }
72
73        if (isset($response['error'])) {
74            throw new \Exception('Gemini API error: ' . $response['error']['message'], 3002);
75        }
76
77        return $response;
78    }
79
80
81}
82