xref: /plugin/aichat/Model/OpenAI/AbstractOpenAIModel.php (revision e3640be850ce50dedfa84d85fcca5c951393e714)
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(string $name, array $config)
16    {
17        parent::__construct($name, $config);
18
19        $openAIKey = $config['openai_apikey'] ?? '';
20        $openAIOrg = $config['openai_org'] ?? '';
21
22        $this->http->headers['Authorization'] = 'Bearer ' . $openAIKey;
23        if ($openAIOrg) {
24            $this->http->headers['OpenAI-Organization'] = $openAIOrg;
25        }
26    }
27
28    /**
29     * Send a request to the OpenAI API
30     *
31     * @param string $endpoint
32     * @param array $data Payload to send
33     * @return array API response
34     * @throws \Exception
35     */
36    protected function request($endpoint, $data)
37    {
38        $url = 'https://api.openai.com/v1/' . $endpoint;
39        return $this->sendAPIRequest('POST', $url, $data);
40    }
41
42    /** @inheritdoc */
43    protected function parseAPIResponse($response)
44    {
45        if (isset($response['usage'])) {
46            $this->inputTokensUsed += $response['usage']['prompt_tokens'];
47            $this->outputTokensUsed += $response['usage']['completion_tokens'] ?? 0;
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