xref: /plugin/aichat/Model/Anthropic/ChatModel.php (revision e8451b21b9ca52de6bf419c0f1a2020e9bcd5276)
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        // convert OpenAI Style to Anthropic style
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
51        print_r($response);
52
53        return $response['content'][0]['text'];
54    }
55
56    /**
57     * Send a request to the OpenAI API
58     *
59     * @param string $endpoint
60     * @param array $data Payload to send
61     * @return array API response
62     * @throws \Exception
63     */
64    protected function request($endpoint, $data)
65    {
66        $url = 'https://api.anthropic.com/v1/' . $endpoint;
67        return $this->sendAPIRequest('POST', $url, $data);
68    }
69
70    /** @inheritdoc */
71    protected function parseAPIResponse($response)
72    {
73        if (isset($response['usage'])) {
74            $this->tokensUsed += $response['usage']['input_tokens'] + $response['usage']['output_tokens'];
75        }
76
77        if (isset($response['error'])) {
78            throw new \Exception('Anthropic API error: ' . $response['error']['message']);
79        }
80
81        return $response;
82    }
83}
84