Skip to content

Commit

Permalink
add chat gpt function and fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
boxblinkracer committed Jun 6, 2023
1 parent 65e679c commit e549018
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion src/Service/OpenAI/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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);
}
}

0 comments on commit e549018

Please sign in to comment.