These will allow you to communicate with the openai-php/laravel package, in a more fluent way.
Add the following code snippet to your config/openai.php file.
/*
|--------------------------------------------------------------------------
| Default Model
|--------------------------------------------------------------------------
|
| The default model to use for requests. You can specify a different model
| for each request if needed.
*/
'default_model' => env('OPENAI_DEFAULT_MODEL', 'gpt-4o'),Below are a few examples of how to use these classes, but there have a look at them, to see the full functionality.
$response = OpenAIService::chat()
->withModel('gpt-4o')
->user('Tell me something about Dan Brown')
->fetch();
// get the raw response from OpenAI
dd($response->raw());Include a base64 encoded image and get the first choice message as well as the usage stats.
$path = 'path/to/image.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/'.$type.';base64,'.base64_encode($data);
$response = OpenAIService::chat()
->withModel('gpt-4o')
->user("Please provide a list of each book in this photo with\n\nStructure:\n* title\n* author")
->withImage($base64)
->withJsonFormat([
'books' => [
[
'title' => 'string or null',
'author' => 'string or null',
],
],
])
->fetch();
dd($response->firstMessage(), $response->usage());The response object will make sure that if any of the fields defined in the schema are missing from the OpenAI response, it will add them with a null value.
$response = OpenAIService::chat()
->user('Please provide details about the author of the following book in JSON format.')
->user("Book: The Da Vinci Code")
->user("Author: Dan Brown")
->withTemperature(1.0)
->withJsonSchema([
'name' => 'book_author',
'strict' => true,
'schema' => [
'type' => 'object',
'properties' => [
'name' => [
'type' => ['string', 'null'],
'description' => 'The full name of the author, based on the book title and author name provided, this is null if the author does not exist',
],
'short_bio' => [
'type' => ['string', 'null'],
'description' => 'Short biography of the author, this is null if the author does not exist',
],
'dob' => [
'type' => ['string', 'null'],
'description' => 'Date of birth of the author. Format: yyyy-mm-dd, this is null if the author does not exist',
],
'dod' => [
'type' => ['string', 'null'],
'description' => 'Date of death of the author. Format: yyyy-mm-dd, this is null if the author does not exist or has not died yet',
],
'wikipedia_url' => [
'type' => ['string', 'null'],
'description' => 'URL to the author\'s Wikipedia page. This is null if the author does not have a Wikipedia page',
],
],
'required' => ['name', 'short_bio', 'dob', 'dod', 'wikipedia_url'],
'additionalProperties' => false
]
])
->fetch();
dd($response->firstMessageViaSchema());