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        parent::__construct($name, $config);
17
18        if (empty($config['gemini_apikey'])) {
19            throw new \Exception('Gemini API key not configured');
20        }
21
22        $this->apikey = $config['gemini_apikey'];
23    }
24
25    /**
26     * Send a request to the Gemini API
27     *
28     * @param string $endpoint
29     * @param array $data Payload to send
30     * @return array API response
31     * @throws \Exception
32     */
33    protected function request($model, $endpoint, $data)
34    {
35        $url = sprintf(
36            'https://generativelanguage.googleapis.com/v1beta/models/%s:%s?key=%s',
37            $model,
38            $endpoint,
39            $this->apikey
40        );
41
42        return $this->sendAPIRequest('POST', $url, $data);
43    }
44
45    /** @inheritdoc */
46    protected function parseAPIResponse($response)
47    {
48        if (isset($response['usageMetadata'])) {
49            $this->inputTokensUsed += $response['usageMetadata']['promptTokenCount'];
50            $this->outputTokensUsed += $response['usageMetadata']['candidatesTokenCount'] ?? 0;
51        }
52
53        if (isset($response['error'])) {
54            throw new \Exception('Gemini API error: ' . $response['error']['message']);
55        }
56
57        return $response;
58    }
59
60
61}
62