Skip to content

Instantly share code, notes, and snippets.

@HelgeSverre
Created December 8, 2023 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HelgeSverre/2ce659450164530a902acbce42f61ad3 to your computer and use it in GitHub Desktop.
Save HelgeSverre/2ce659450164530a902acbce42f61ad3 to your computer and use it in GitHub Desktop.
QUICK N DIRTY AI WRAPPER
<?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