xref: /plugin/aichat/Model/Mistral/ChatModel.php (revision c2b7a1f7fd0f6c6579c9ee46f0437ff89c2fc4b3)
1cfd76f4aSAndreas Gohr<?php
2cfd76f4aSAndreas Gohr
3cfd76f4aSAndreas Gohrnamespace dokuwiki\plugin\aichat\Model\Mistral;
4cfd76f4aSAndreas Gohr
5cfd76f4aSAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface;
6cfd76f4aSAndreas Gohr
7cfd76f4aSAndreas Gohrclass ChatModel extends AbstractMistralModel implements ChatInterface
8cfd76f4aSAndreas Gohr{
9cfd76f4aSAndreas Gohr    /** @inheritdoc */
10cfd76f4aSAndreas Gohr    public function getAnswer(array $messages): string
11cfd76f4aSAndreas Gohr    {
12*c2b7a1f7SAndreas Gohr        // Mistral allows only for a system message at the beginning of the chat
13*c2b7a1f7SAndreas Gohr        // https://discord.com/channels/1144547040454508606/1220314306844037150
14*c2b7a1f7SAndreas Gohr        $system = '';
15*c2b7a1f7SAndreas Gohr        $chat = [];
16*c2b7a1f7SAndreas Gohr        foreach ($messages as $message) {
17*c2b7a1f7SAndreas Gohr            if ($message['role'] === 'system') {
18*c2b7a1f7SAndreas Gohr                $system .= $message['content'] . "\n";
19*c2b7a1f7SAndreas Gohr            } else {
20*c2b7a1f7SAndreas Gohr                $chat[] = $message;
21*c2b7a1f7SAndreas Gohr            }
22*c2b7a1f7SAndreas Gohr        }
23*c2b7a1f7SAndreas Gohr        $system = trim($system);
24*c2b7a1f7SAndreas Gohr        if ($system) {
25*c2b7a1f7SAndreas Gohr            array_unshift($chat, ['role' => 'system', 'content' => $system]);
26*c2b7a1f7SAndreas Gohr        }
27*c2b7a1f7SAndreas Gohr
28*c2b7a1f7SAndreas Gohr
29cfd76f4aSAndreas Gohr        $data = [
30*c2b7a1f7SAndreas Gohr            'messages' => $chat,
31cfd76f4aSAndreas Gohr            'model' => $this->getModelName(),
32cfd76f4aSAndreas Gohr            'max_tokens' => null,
33cfd76f4aSAndreas Gohr            'stream' => false,
34cfd76f4aSAndreas Gohr            'temperature' => 0.0,
35cfd76f4aSAndreas Gohr        ];
36cfd76f4aSAndreas Gohr        $response = $this->request('chat/completions', $data);
37cfd76f4aSAndreas Gohr        return $response['choices'][0]['message']['content'];
38cfd76f4aSAndreas Gohr    }
39cfd76f4aSAndreas Gohr}
40