How to integrate ChatGPT image generation into Laravel?

Learn how to seamlessly integrate ChatGPT's image generation capabilities into your Laravel application. This guide covers the essential steps to set up and implement AI-driven image creation. First, we need to obtain our API keys. To generate API keys, log in or create an account on platform.openai.com. Once logged in, find the API keys option on the left sidebar, click on it, and generate your API keys there.

use GuzzleHttp\Client as GuzzleClient;


public static function generateAiImage()
{
    // URL for the OpenAI API endpoint for image generation
    $apiUrl = 'https://api.openai.com/v1/images/generations';

    // Your API key for accessing OpenAI services
    $apiKey = 'SECRET_KEY';
    
    // The version of the model you want to use (e.g., DALL-E 3, DALL-E 2)
    $modelVersion = 'dall-e-3';

    // Initialize a new Guzzle HTTP client
    $guzzleClient = new GuzzleClient();

    // The prompt or description for the image to be generated by the AI model
    $ai_prompt = 'Generate an image of Spider-Man helping everyone.';

    // Parameters to be sent to the API, including the model version and prompt
    $params = [
        'model' => $modelVersion,
        'prompt' => $ai_prompt,
        'n' => 1,
        'size' => '512x512',
        'style' => 'vivid',
        'quality' => 'hd',
    ];

    // Headers for the HTTP request, including content type and authorization
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . $apiKey, // Replace with your actual API key
    ];

    try
    {
        // Send the POST request to the API with the headers and parameters
        $response = $guzzleClient->post($apiUrl, [
            'headers' => $headers,
            'json' => $params,
        ]);

        // Decode the JSON response from the API
        $data = json_decode($response->getBody(), true);
        
        // Extract the URL of the generated image from the response data
        $imageUrl = $data['data'][0]['url'];
        
        // Return the status, message, and image URL in case of success
        return [
            'status' => 'success',
            'message' => '',
            'image_url' => $imageUrl
        ];
    }
    catch (\GuzzleHttp\Exception\RequestException $e)
    {
        // Return the status, error message, and an empty image URL in case of failure
        return [
            'status' => 'error',
            'message' => $e->getMessage(),
            'image_url' => ''
        ];
    }
}

Now, let's break down the parameters we're passing to the API:


- Model Version : For image generation, the available models are DALL-E 2 and DALL-E 3.

- n : Represents the number of images you want to generate. For DALL-E 2, it's limited to a maximum of 10 images.

- Size : Varies based on the model version you use. DALL-E 3 offers more size options compared to DALL-E 2.

- Style : Basic knowledge of image styles is necessary.

- Quality : By default, the quality is set to 'standard'. 'HD' quality is only available with DALL-E 3.


For more information on parameters and details, I recommend reading the official documentation. https://platform.openai.com/docs/guides/images


The image generation is complete. If you want to save the image to your local system, use the code below.

$imageName = time() . rand(1000,9999) . '.' . 'png';
Storage::disk('local')->put($imageName, file_get_contents($imageUrl));

For this example, I am using the local disk. You can change it according to your requirements or create a new disk in 'filesystem.php'. Save '$imageName' to the database for later retrieval.