xref: /plugin/aichat/Model/OpenAI/AbstractOpenAIModel.php (revision 294a9eaf76b94a3f99dceca7f1750a7898de3dd9)
1<?php
2
3namespace dokuwiki\plugin\aichat\Model\OpenAI;
4
5use dokuwiki\plugin\aichat\Model\AbstractModel;
6
7/**
8 * Abstract OpenAI Model
9 *
10 * This class provides a basic interface to the OpenAI API
11 */
12abstract class AbstractOpenAIModel extends AbstractModel
13{
14    /** @inheritdoc */
15    public function __construct($config)
16    {
17        parent::__construct($config);
18
19        $openAIKey = $config['key'] ?? '';
20        $openAIOrg = $config['org'] ?? '';
21
22
23        $this->http->headers['Authorization'] = 'Bearer ' . $openAIKey;
24        if ($openAIOrg) {
25            $this->http->headers['OpenAI-Organization'] = $openAIOrg;
26        }
27    }
28
29    /**
30     * Send a request to the OpenAI API
31     *
32     * @param string $endpoint
33     * @param array $data Payload to send
34     * @return array API response
35     * @throws \Exception
36     */
37    protected function request($endpoint, $data)
38    {
39        $url = 'https://api.openai.com/v1/' . $endpoint;
40        return $this->sendAPIRequest('POST', $url, $data);
41    }
42
43    /** @inheritdoc */
44    protected function parseAPIResponse($response)
45    {
46        if (isset($response['usage'])) {
47            $this->tokensUsed += $response['usage']['total_tokens'];
48        }
49
50        if (isset($response['error'])) {
51            throw new \Exception('OpenAI API error: ' . $response['error']['message']);
52        }
53
54        return $response;
55    }
56
57    /**
58     * @internal for checking available models
59     */
60    public function listUpstreamModels()
61    {
62        $url = 'https://api.openai.com/v1/models';
63        return $this->http->get($url);
64    }
65}
66