How to integrate ChatGPT into Laravel?

In this post, we will learn how to implement ChatGPT in our Laravel system. However, we first need to obtain our API keys. To generate API keys, log in or create an account on platform.openai.com. After logging in, you will find the API keys option on the left sidebar. Click on that, and you can generate your API keys there.

use GuzzleHttp\Client as GuzzleClient;



public function generateAiContent()
{
    // URL for the OpenAI API endpoint for generating chat completions
    $apiUrl = 'https://api.openai.com/v1/chat/completions';

    // Your API key for accessing OpenAI services
    $apiKey = 'SECRET_KEY';
    
    // The version of the model you want to use (e.g., GPT-3.5 or GPT-4)
    $modelVersion = 'gpt-4o'; // gpt-3.5-turbo || gpt-4o-mini || gpt-4o

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

    // The prompt or question to send to the AI model
    $ai_prompt = 'What makes Spider-Man such a great hero?';

    // Data to be sent to the API, including the model version and messages
    $data = [
        'model' => $modelVersion,
        'messages' => [
            [
                'role' => 'system',
                'content' => 'You are a helpful assistant.',
            ],
            [
                'role' => 'user',
                'content' => $ai_prompt,
            ],
        ],
    ];

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

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

    // Decode the JSON response from the API
    $result = json_decode($response->getBody(), true);

    // Check if the API returned a valid response and extract the content
    if(isset($result['choices'][0]['message']['content']))
    {
        $ai_content = $result['choices'][0]['message']['content'];
    }
    else
    {
        // Fallback message in case something went wrong
        $ai_content = 'Something went wrong.';
    }

    // Return the generated content
    return $ai_content;
}

Important: Ensure that the 'model' version you are using is enabled on your OpenAI dashboard.