xref: /plugin/aichat/Model/Anthropic/ChatModel.php (revision 2e22aefbcc83da0bc9ab21a2175b8ada4ba79826)
1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Anthropic;
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
16        $this->http->headers['x-api-key'] = $this->getFromConf($config, 'apikey');
17        $this->http->headers['anthropic-version'] = '2023-06-01';
18    }
19
20    /** @inheritdoc */
21    public function getAnswer(array $messages): string
22    {
23        // system message is separate from the messages array
24        $system = '';
25        $chat = [];
26        foreach ($messages as $message) {
27            if ($message['role'] === 'system') {
28                $system .= $message['content'] . "\n";
29            } else {
30                $chat[] = $message;
31            }
32        }
33
34        $data = [
35            'messages' => $chat,
36            'model' => $this->getModelName(),
37            'max_tokens' => $this->getMaxOutputTokenLength(),
38            'stream' => false,
39            'temperature' => 0.0,
40        ];
41
42        if ($system) {
43            $data['system'] = $system;
44        }
45
46        $response = $this->request('messages', $data);
47        return $response['content'][0]['text'];
48    }
49
50    /**
51     * Send a request to the API
52     *
53     * @param string $endpoint
54     * @param array $data Payload to send
55     * @return array API response
56     * @throws \Exception
57     */
58    protected function request($endpoint, $data)
59    {
60        $url = 'https://api.anthropic.com/v1/' . $endpoint;
61        return $this->sendAPIRequest('POST', $url, $data);
62    }
63
64    /** @inheritdoc */
65    protected function parseAPIResponse($response)
66    {
67        if (isset($response['usage'])) {
68            $this->inputTokensUsed += $response['usage']['input_tokens'];
69            $this->outputTokensUsed += $response['usage']['output_tokens'];
70        }
71
72        if (isset($response['error'])) {
73            throw new ModelException('Anthropic API error: ' . $response['error']['message'], 3002);
74        }
75
76        return $response;
77    }
78}
79