1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Reka;
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['reka_apikey'])) {
16            throw new \Exception('Reka API key not configured');
17        }
18
19        $this->http->headers['x-api-key'] = $config['reka_apikey'];
20    }
21
22    /** @inheritdoc */
23    public function getAnswer(array $messages): string
24    {
25        $chat = [];
26        foreach ($messages as $message) {
27            if ($message['role'] === 'user') {
28                $chat[] = [
29                    'type' => 'human',
30                    'text' => $message['content'],
31                ];
32            } elseif ($message['role'] === 'assistant') {
33                $chat[] = [
34                    'type' => 'model',
35                    'text' => $message['content'],
36                ];
37            }
38            // system messages are not supported
39        }
40
41        $data = [
42            'conversation_history' => $chat,
43            'model_name' => $this->getModelName(),
44            'temperature' => 0.0,
45        ];
46
47        $response = $this->request('chat', $data);
48        return $response['text'];
49    }
50
51    /**
52     * Send a request to the API
53     *
54     * @param string $endpoint
55     * @param array $data Payload to send
56     * @return array API response
57     * @throws \Exception
58     */
59    protected function request($endpoint, $data)
60    {
61        $url = 'https://api.reka.ai/' . $endpoint;
62        return $this->sendAPIRequest('POST', $url, $data);
63    }
64
65    /** @inheritdoc */
66    protected function parseAPIResponse($response)
67    {
68        if (((int) $this->http->status) !== 200) {
69            if (isset($response['detail'])) {
70                throw new \Exception('Reka API error: ' . $response['detail']);
71            } else {
72                throw new \Exception('Reka API error: ' . $this->http->status . ' ' . $this->http->error);
73            }
74        }
75
76        if (isset($response['metadata'])) {
77            $this->inputTokensUsed += $response['metadata']['input_tokens'];
78            $this->outputTokensUsed += $response['metadata']['generated_tokens'];
79        }
80
81        return $response;
82    }
83}
84