xref: /plugin/aichat/Model/Gemini/ChatModel.php (revision 10789c175b44bee75b54261fbdf3bb1e6d176759)
1*10789c17SAndreas Gohr<?php
2*10789c17SAndreas Gohr
3*10789c17SAndreas Gohrnamespace dokuwiki\plugin\aichat\Model\Gemini;
4*10789c17SAndreas Gohr
5*10789c17SAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface;
6*10789c17SAndreas Gohr
7*10789c17SAndreas Gohrclass ChatModel extends AbstractGeminiModel implements ChatInterface
8*10789c17SAndreas Gohr{
9*10789c17SAndreas Gohr    /** @inheritdoc */
10*10789c17SAndreas Gohr    public function getAnswer(array $messages): string
11*10789c17SAndreas Gohr    {
12*10789c17SAndreas Gohr        // Gemini payload is weird, we convert OpenAI style here
13*10789c17SAndreas Gohr        $data = [
14*10789c17SAndreas Gohr            'contents' => [],
15*10789c17SAndreas Gohr        ];
16*10789c17SAndreas Gohr        foreach ($messages as $message) {
17*10789c17SAndreas Gohr            if ($message['role'] === 'system') {
18*10789c17SAndreas Gohr                // system messages go to extra array
19*10789c17SAndreas Gohr                if (!isset($data['system_instructions'])) {
20*10789c17SAndreas Gohr                    $data['system_instructions'] = [];
21*10789c17SAndreas Gohr                    $data['system_instructions']['parts'] = [];
22*10789c17SAndreas Gohr                }
23*10789c17SAndreas Gohr                $data['system_instructions']['parts'][] = ['text' => $message['content']];
24*10789c17SAndreas Gohr            } else {
25*10789c17SAndreas Gohr                $data['contents'][] = [
26*10789c17SAndreas Gohr                    'role' => $message['role'],
27*10789c17SAndreas Gohr                    'parts' => [
28*10789c17SAndreas Gohr                        ['text' => $message['content']]
29*10789c17SAndreas Gohr                    ]
30*10789c17SAndreas Gohr                ];
31*10789c17SAndreas Gohr            }
32*10789c17SAndreas Gohr        }
33*10789c17SAndreas Gohr
34*10789c17SAndreas Gohr        $response = $this->request($this->getModelName(), 'generateContent', $data);
35*10789c17SAndreas Gohr        return $response['candidates'][0]['content']['parts'][0]['text'];
36*10789c17SAndreas Gohr    }
37*10789c17SAndreas Gohr}
38