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