Baking ChatGPT into CakePHP: A Delicious Recipe for Improved User Interactions

Baking ChatGPT into CakePHP: A Delicious Recipe for Improved User Interactions

In today's digital age, providing seamless and intuitive user experiences is crucial for success. That's why we're excited to announce the integration of ChatGPT, OpenAI's powerful language model, into CakePHP, one of the most popular PHP web application frameworks. ChatGPT integration with CakePHP offers an innovative solution for improving user interactions and elevating the quality of customer service. By harnessing the advanced capabilities of AI, we can deliver faster and more accurate responses, leading to enhanced customer satisfaction and reduced workloads for your support team.

In this blog, let’s explore the delicious recipe for integrating ChatGPT into CakePHP and how it has the potential to revolutionize the way you interact with your users!


Steps to Integrate OpenAI's GPT Model into Your Web Application using cURL

First, let’s check out a step-by-step guide to integrating OpenAI's GPT model using cURL in a CakePHP web app.

Mentioned below is a detailed explanation of the integrateChatGPT method and how it uses cURL to send a POST request to the OpenAI API endpoint.
 

<?php
namespace App\Model\Behavior;

use Cake\ORM\Behavior;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use DateTime;
use Cake\Network\Http\Client;

 

/**
* Chatgpt behavior
*/
class ChatGPTBehavior extends Behavior
{
    /**
    * Default configuration.
    *
    * @var array
    */
    protected $_defaultConfig = [];
    public function integrateChatGPT($prompt_question)
    {
       
        // Initialize cURL session
        $curl = curl_init();
       
        // Set the API endpoint
        curl_setopt($curl, CURLOPT_URL, 'https://api.openai.com/v1/completions');
       
        // Set the request type to POST
        curl_setopt($curl, CURLOPT_POST, 1);
       
        // Set the request headers
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer '.env('OPEN_AI_API_KEY'),
        ]);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
       
        // Set the request body
        $data = [    'model' => 'text-davinci-003',    'prompt' => $prompt_question,    'temperature' => 0,    'max_tokens' => 256,];
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
       
        // Return the response as a string
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
       
        // Execute the cURL request
        $result = curl_exec($curl);
        if ($result === false) {
            echo 'cURL Error: ' . curl_error($curl);
            }
        // Close the cURL session
        curl_close($curl);
       
        // Decode the response JSON
        $result = json_decode($result, true);
        $text = $result['choices'][0]['text'];
        $text = preg_replace('/^[\s\t\r\n]+/', '', $text);
        $text = preg_replace('/[\s\t\r\n,]+$/', '', $text);
        return $text;
     
     
    }
}


cURL is a library used to send HTTP requests in PHP. In the context of ChatGPT integration in CakePHP, cURL is used to send a request to the OpenAI API to generate a response to the provided prompt question using the ChatGPT behavior. The cURL library is used to set the API endpoint, request type, headers, body, and response format. It then executes the request and returns the response as a JSON string, which is then decoded and processed for the final response.


To send a cURL request, we will make a cURL request by making a behavior called ChatGPTBehavior.
 

To know how to integrate OpenAI's GPT model into a web app using cURL in PHP, let’s take a look at the above code. The following steps are performed using the PHP cURL library:

  1. Initializing the cURL session: curl_init() function is used to initialize a new cURL session.
  2. Setting the API endpoint: curl_setopt() function is used to set the API endpoint URL to 'https://api.openai.com/v1/completions'.
  3. Setting the request type to POST: curl_setopt() function is used to set the request type to POST.
  4. Setting the request headers: curl_setopt() function is used to set the request headers, which include the content type and authorization header.
  5. Setting the request body: curl_setopt() function is used to set the request body, which includes the request data encoded as a JSON string.
  6. Returning the response as a string: curl_setopt() function is used to set the option to return the response as a string, instead of printing it.
  7. Executing the cURL request: curl_exec() function is used to execute the cURL request.
  8. Closing the cURL session: curl_close() function is used to close the cURL session.
  9. Decoding the response JSON: json_decode() function is used to decode the JSON response string into a PHP array.

 

The above steps are performed to make a request to the OpenAI API and retrieve the completion text generated by the "text-davinci-003" model based on the given prompt question.
The Controller Method that is responsible for accepting prompts and generating answers:

public function generateAnswer()

    {

      if ($this->request->is(['post'])) {

 

        $promptQuestion= $this->request->getData(['prompt']);

          $answer=$this->integrateChatGPT($promptQuestion);

      }

      $this->set(compact('answer'));

 

    }


The controller action checks whether the current request is a POST request using the $this->request->is(['post']) method. If the current request is a POST request, the action proceeds to the next step.

 

The controller action retrieves the value of the prompt field from the form using the $this->request->getData(['prompt']) method. This value is then assigned to the $promptQuestion variable. It is then passed to the behavior method integrateChatGPT, which generates the answer and stores it in the $answer variable. Following this, it is passed to the view file, which renders the answer against the question.

 

The view which takes prompt question as input generate_answer.ctp

<div class="card">

    <div class="card-body">

        <?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'generateAnswer']]) ?>

        <?= $this->Form->input('prompt', ['class' => 'form-control']) ?>

        <?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary']) ?>

        <?= $this->Form->end() ?>

        <?php if (isset($answer)):?>

       <p><?=$answer?></p>

       <?php endif;?>

    </div>

</div>


In conclusion, ChatGPT integration with CakePHP is a simple and straightforward process. With the help of the cURL library, you can easily send HTTP requests to OpenAI's API and retrieve the generated text as a response. By passing a prompt as input, you can generate text for a variety of use cases, such as chatbots, content creation, and more.

 

In this discussion, we went through the process of integrating ChatGPT into CakePHP using cURL. We also explored how to create a form that takes prompts as input, hits a controller function, and generates a response using the GPT model. 

Overall, integrating OpenAI's GPT model into your web application can help you generate accurate and high-quality responses that can be used in a variety of applications. By following the steps outlined in this discussion, you can quickly get started with integrating this powerful tool into your CakePHP application. If you need any further assistance, don’t hesitate to reach out to our skilled and experienced software experts!

Author Profile Picture
Admin
Why Is Customer Relationship Management So Important?

Why CRM is important

Ismail Hossain
Tips for Setting Up Cron Job in CakePHP Project

How to Set Up Cron Job in CakePHP Project

Fokrul Hasan

SJ Innovation - FACT SHEET

ADMIN