1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Groq;
4
5use dokuwiki\plugin\aichat\Model\AbstractModel;
6use dokuwiki\plugin\aichat\Model\ChatInterface;
7
8class ChatModel extends AbstractModel implements ChatInterface
9{
10    /** @inheritdoc */
11    public function __construct(string $name, array $config)
12    {
13        parent::__construct($name, $config);
14
15        if (empty($config['groq_apikey'])) {
16            throw new \Exception('Groq API key not configured');
17        }
18
19        $this->http->headers['Authorization'] = 'Bearer ' . $config['groq_apikey'];
20    }
21
22    /** @inheritdoc */
23    public function getAnswer(array $messages): string
24    {
25        $data = [
26            'messages' => $messages,
27            'model' => $this->getModelName(),
28            'max_tokens' => null,
29            'stream' => false,
30            'n' => 1, // number of completions
31            'temperature' => 0.0,
32        ];
33        $response = $this->request('chat/completions', $data);
34        return $response['choices'][0]['message']['content'];
35    }
36
37    /**
38     * Send a request to the API
39     *
40     * @param string $endpoint
41     * @param array $data Payload to send
42     * @return array API response
43     * @throws \Exception
44     */
45    protected function request($endpoint, $data)
46    {
47        $url = 'https://api.groq.com/openai/v1/' . $endpoint;
48        return $this->sendAPIRequest('POST', $url, $data);
49    }
50
51    /** @inheritdoc */
52    protected function parseAPIResponse($response)
53    {
54        if (isset($response['usage'])) {
55            $this->inputTokensUsed += $response['usage']['prompt_tokens'];
56            $this->outputTokensUsed += $response['usage']['completion_tokens'] ?? 0;
57        }
58
59        if (isset($response['error'])) {
60            throw new \Exception('Groq API error: ' . $response['error']['message']);
61        }
62
63        return $response;
64    }
65}
66