Created
December 8, 2023 01:38
-
-
Save HelgeSverre/2ce659450164530a902acbce42f61ad3 to your computer and use it in GitHub Desktop.
QUICK N DIRTY AI WRAPPER
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Support\Arr; | |
use OpenAI\Laravel\Facades\OpenAI; | |
use OpenAI\Responses\Chat\CreateResponse; | |
use Throwable; | |
class AI | |
{ | |
public static int $maxTokens = 4096; | |
public static float $temperature = 0.5; | |
public static function text($prompt, ?int $max = null, bool $fast = true): string | |
{ | |
return self::toText(OpenAI::chat()->create([ | |
'model' => $fast ? 'gpt-3.5-turbo-1106' : 'gpt-4-1106-preview', | |
'max_tokens' => $max ?? self::$maxTokens, | |
'temperature' => self::$temperature, | |
'messages' => [ | |
['role' => 'user', 'content' => $prompt], | |
], | |
])); | |
} | |
public static function json($prompt, ?int $max = null, bool $fast = true): ?array | |
{ | |
try { | |
return json_decode(self::toText(OpenAI::chat()->create([ | |
'model' => $fast ? 'gpt-3.5-turbo-1106' : 'gpt-4-1106-preview', | |
'max_tokens' => $max ?? self::$maxTokens, | |
'temperature' => self::$temperature, | |
'response_format' => ['type' => 'json_object'], | |
'messages' => [ | |
['role' => 'user', 'content' => $prompt], | |
], | |
])), associative: true); | |
} catch (Throwable $error) { | |
return null; | |
} | |
} | |
public static function list($prompt, ?int $max = null, bool $fast = true): array | |
{ | |
try { | |
$text = self::toText(OpenAI::chat()->create([ | |
'model' => $fast ? 'gpt-3.5-turbo-1106' : 'gpt-4-1106-preview', | |
'max_tokens' => $max ?? self::$maxTokens, | |
'temperature' => self::$temperature, | |
'response_format' => ['type' => 'json_object'], | |
'messages' => [ | |
[ | |
'role' => 'user', | |
'content' => "{$prompt}\n Output the list as a JSON array, under the key 'items'", | |
], | |
], | |
])); | |
return Arr::get(json_decode($text, associative: true), 'items'); | |
} catch (Throwable $error) { | |
return []; | |
} | |
} | |
protected static function toText(CreateResponse $response): ?string | |
{ | |
return rescue(fn () => $response->choices[0]->message->content); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment