![]() Server : Apache System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64 User : corals ( 1002) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /home/corals/old/vendor/mageworx/module-open-ai/Model/ |
<?php namespace MageWorx\OpenAI\Model; use Magento\Framework\Exception\LocalizedException; use MageWorx\OpenAI\Api\MessengerInterface; use MageWorx\OpenAI\Api\OptionsInterfaceFactory; use MageWorx\OpenAI\Api\OptionsInterface; use MageWorx\OpenAI\Api\RequestInterfaceFactory; use MageWorx\OpenAI\Api\ResponseInterface; use MageWorx\OpenAI\Api\ResponseInterfaceFactory; use MageWorx\OpenAI\Helper\Data as Helper; class Messenger implements MessengerInterface { const API_URL = 'https://api.openai.com/'; protected Helper $helper; protected OptionsInterfaceFactory $optionsFactory; protected RequestInterfaceFactory $requestFactory; protected ResponseInterfaceFactory $responseFactory; public function __construct( Helper $helper, OptionsInterfaceFactory $optionsFactory, RequestInterfaceFactory $requestFactory, ResponseInterfaceFactory $responseFactory ) { $this->helper = $helper; $this->optionsFactory = $optionsFactory; $this->requestFactory = $requestFactory; $this->responseFactory = $responseFactory; } /** * @param array $data * @param OptionsInterface $options * @return ResponseInterface * @throws LocalizedException */ public function send(array $data, OptionsInterface $options): ResponseInterface { $response = $this->sendRequest($data, $options); // Handle the response $result = json_decode($response, true); /** @var ResponseInterface $responseObject */ $responseObject = $this->responseFactory->create(); if (isset($result['choices'][0]['message']['content'])) { $content = $result['choices'][0]['message']['content']; $responseObject->setIsError(false); } else { $content = 'Error: ' . $response; $responseObject->setIsError(true); } $responseObject->setChatResponse($result); $responseObject->setContent($content); return $responseObject; } /** * Send request and get raw data (json string) * * @param array $data * @param OptionsInterface $options * @return string * @throws LocalizedException */ protected function sendRequest(array $data, OptionsInterface $options): string { // Convert data to JSON $jsonData = json_encode($data); // Initialize curl $ch = curl_init(); // Set the curl options curl_setopt($ch, CURLOPT_URL, static::API_URL . $options->getPath()); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_HTTPHEADER, $options->getHeaders()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); // Check for errors if ($response === false) { $exception = new LocalizedException(__('Curl Error: %1', curl_error($ch))); curl_close($ch); throw $exception; } // Close curl curl_close($ch); return $response; } }