From e549018e1c06c839453be49217423fe0dade3ae0 Mon Sep 17 00:00:00 2001 From: Christian Dangl Date: Tue, 6 Jun 2023 20:49:03 +0200 Subject: [PATCH] add chat gpt function and fix errors --- src/Service/OpenAI/Client.php | 56 ++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/Service/OpenAI/Client.php b/src/Service/OpenAI/Client.php index c4e1759..3ddd4fc 100644 --- a/src/Service/OpenAI/Client.php +++ b/src/Service/OpenAI/Client.php @@ -49,7 +49,7 @@ public function generateText(string $prompt): Choice } if (isset($json['error'])) { - $msg = 'OpenAI Error: ' . $json['error'] . '['.$json['code'].']'; + $msg = 'OpenAI Error: ' . $json['error']['message'] . '[' . $json['error']['code'] . ']'; throw new \Exception($msg); } @@ -102,4 +102,58 @@ public function generateImage(string $prompt, string $size): string return (string)$json['data'][0]['url']; } + + /** + * @param string $prompt + * @throws \JsonException + * @return Choice + */ + public function askChatGPT(string $prompt): Choice + { + $params = [ + 'model' => "gpt-3.5-turbo", + 'messages' => [ + ['role' => 'user', 'content' => $prompt], + ], + 'temperature' => 0.8, + 'max_tokens' => 400, + 'top_p' => 1.0, + 'frequency_penalty' => 0.0, + 'presence_penalty' => 0.0, + ]; + + + $complete = (string)$this->openAi->chat($params); + + $json = json_decode($complete, true, 512, JSON_THROW_ON_ERROR); + + if (!is_array($json)) { + return new Choice(''); + } + + if (isset($json['error'])) { + $msg = 'OpenAI Error: ' . $json['error']['message'] . '[' . $json['error']['code'] . ']'; + throw new \Exception($msg); + } + + if (!isset($json['choices'])) { + throw new \Exception('No choices found in OpenAI response.'); + } + + $choices = $json['choices']; + + if (!is_array($choices) || count($choices) <= 0) { + return new Choice(''); + } + + if (!isset($choices[0]['message']['content'])) { + return new Choice(''); + } + + $choiceData = $choices[0]; + + $text = trim($choiceData['message']['content']); + + return new Choice($text); + } }