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['openaikey'] ?? ''; 20 $openAIOrg = $config['openaiorg'] ?? ''; 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->tokensUsed += $response['usage']['total_tokens']; 47 } 48 49 if (isset($response['error'])) { 50 throw new \Exception('OpenAI API error: ' . $response['error']['message']); 51 } 52 53 return $response; 54 } 55 56 /** 57 * @internal for checking available models 58 */ 59 public function listUpstreamModels() 60 { 61 $url = 'https://api.openai.com/v1/models'; 62 return $this->http->get($url); 63 } 64} 65