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