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