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