xref: /plugin/aichat/Model/Gemini/ChatModel.php (revision c7364d3d9343f44d2b2570a7580dc5ce8fad1cd7)
110789c17SAndreas Gohr<?php
210789c17SAndreas Gohr
310789c17SAndreas Gohrnamespace dokuwiki\plugin\aichat\Model\Gemini;
410789c17SAndreas Gohr
510789c17SAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface;
610789c17SAndreas Gohr
710789c17SAndreas Gohrclass ChatModel extends AbstractGeminiModel implements ChatInterface
810789c17SAndreas Gohr{
910789c17SAndreas Gohr    /** @inheritdoc */
1010789c17SAndreas Gohr    public function getAnswer(array $messages): string
1110789c17SAndreas Gohr    {
1210789c17SAndreas Gohr        // Gemini payload is weird, we convert OpenAI style here
1310789c17SAndreas Gohr        $data = [
1410789c17SAndreas Gohr            'contents' => [],
1510789c17SAndreas Gohr        ];
1610789c17SAndreas Gohr        foreach ($messages as $message) {
1710789c17SAndreas Gohr            if ($message['role'] === 'system') {
1810789c17SAndreas Gohr                // system messages go to extra array
1910789c17SAndreas Gohr                if (!isset($data['system_instructions'])) {
2010789c17SAndreas Gohr                    $data['system_instructions'] = [];
2110789c17SAndreas Gohr                    $data['system_instructions']['parts'] = [];
2210789c17SAndreas Gohr                }
2310789c17SAndreas Gohr                $data['system_instructions']['parts'][] = ['text' => $message['content']];
2410789c17SAndreas Gohr            } else {
2510789c17SAndreas Gohr                $data['contents'][] = [
26*c7364d3dSAndreas Gohr                    'role' => $message['role'] === 'assistant' ? 'model' : 'user',
2710789c17SAndreas Gohr                    'parts' => [
2810789c17SAndreas Gohr                        ['text' => $message['content']]
2910789c17SAndreas Gohr                    ]
3010789c17SAndreas Gohr                ];
3110789c17SAndreas Gohr            }
3210789c17SAndreas Gohr        }
3310789c17SAndreas Gohr
3410789c17SAndreas Gohr        $response = $this->request($this->getModelName(), 'generateContent', $data);
3510789c17SAndreas Gohr        return $response['candidates'][0]['content']['parts'][0]['text'];
3610789c17SAndreas Gohr    }
3710789c17SAndreas Gohr}
38