Creating Interactive Chatbot with OpenAI API in PHP

How can we help?
< All Topics
Print

Creating Interactive Chatbot with OpenAI API in PHP

This tutorial will discuss the implementation of the Open AI Chat Model using PHP as the continuation of the previous tutorial where we talked about the Completions Model. Here, we will focus more on creating an interactive chatbot using Open AI API.

Before we go further, make sure you have read the previous tutorial because we will not discuss the basics, such as creating an OpenAI account or generating the API key, in this tutorial.

About Chats Models

Let’s recap about what and how Chats works. Chats is an assignment that allows users to directly interact with the model. The model will respond to every question or statement created by the user and answer it in sequence as if we are talking with a real human. This model is very useful to create a natural and dynamic conversation experience.

Model Selection and Its Distinction from Completions API

According to OpenAI documentation, the Chat Models use Endpoint https://api.openai.com/v1/chat/completions with gpt-3.5-turbo as the recommended standard model.

Meanwhile, the Completions Model uses Endpoint https://api.openai.com/v1/completions with text-davinci-003 as the recommended standard model.

The main difference between the Completions and Chats model is the ability to understand the context from previous interactions owned by Chats. Thus, Chats can generate more natural responses compared to the Completions model.

API Request Structure for Chats

The following is an example of API request structure for Chat models using cURL.

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {"role": "system", "content": "Anda adalah asisten yang membantu dalam pertanyaan seputar destinasi wisata dengan penuh keramahan."},
      {"role": "user", "content": "Hello!"}
    ],
    "temperature": 0.2,
    "max_tokens": 512,
    "top_p": 0.2,
    "frequency_penalty": 0.0,
    "presence_penalty": 0.6
  }'

Now, we will convert it into a PHP

<?php

$openaiApiKey = "YOUR_API_KEY";

$data = array(
  "model" => "gpt-3.5-turbo",
  "messages" => array(
    array("role" => "system", "content" => "Anda adalah asisten yang membantu dalam pertanyaan seputar destinasi wisata dengan penuh keramahan."),
    array("role" => "user", "content" => "Hai!")
  ),
  "temperature" => 0.2,
  "max_tokens" => 512,
  "top_p" => 0.2,
  "frequency_penalty" => 0.0,
  "presence_penalty" => 0.6
);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.openai.com/v1/chat/completions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($data),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . $openaiApiKey,
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$result = json_decode($response, true);
$content = $result['choices'][0]['message']['content'];
echo $content;

?>

The following is the result of the API request syntax seen from a browser.

Hai! Selamat datang di layanan bantuan destinasi wisata. Ada yang bisa saya bantu?

There are no significant changes in the essential and optional parameters, which you can configure directly in the API call. Like the model, temperature, max tokens, top probability, etc., like what we have learned from the previous tutorial.

However, in Chats API, we use the “messages” parameter instead of the “prompt” used by the Completions model. This parameter is also can be configured as an array.

Messages here refer to the question or statement given by the user, which requires two fields, role and content.

  • role: message sender (system, user, or assistant)
  • content: message content (such as, write me a beautiful poem)

These fields make the Chat model able to create more dynamic conversations.

Messages can also contain an optional field, called name. This field will give a name to the message sender, such as example-user, Alice, Blackbeadrbot, etc. The name cannot contain space.

The Chat model works by creating a conversation followed by clear instructions on what the model should do, followed by a message from the user, and lastly a message from the assistant.

Do note, that the gpt-3.5-turbo does not put heavy weight into the system message as if what gpt-4 does. Thus, it is recommended that all important instructions be placed in the message from users.

The Working of Chats

Let’s take a look at another example of the Chats API call to see how it works.

  • In some cases, it is easier to show the model of what we want than tell the model of what we want.
    One way to show the model of what we want is to create a false scenario:
<?php

$openaiApiKey = "YOUR_API_KEY";

$data = array(
  "model" => "gpt-3.5-turbo",
  "messages" => array(
array("role" => "system", "content" => "Kamu adalah asisten yang membantu dan mengikuti pola."),
    array("role" => "user", "content" => "Bantu aku menerjemahkan contoh kiasan berikut"),
    array("role" => "assistant", "content" => "Tentu, dengan senang hati!"),
    array("role" => "user", "content" => "Hatinya lembut seperti?"),
    array("role" => "assistant", "content" => "Kapas"),   
    array("role" => "user", "content" => "Pemikirannya keras seperti?"),
    array("role" => "assistant", "content" => "Batu"),     
    array("role" => "user", "content" => "Tindakannya kasar seperti?")
  ),
  "temperature" => 0.2,
  "max_tokens" => 512,
  "top_p" => 0.2,
  "frequency_penalty" => 0.0,
  "presence_penalty" => 0.6
);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.openai.com/v1/chat/completions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($data),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . $openaiApiKey,
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$result = json_decode($response, true);
$content = $result['choices'][0]['message']['content'];
echo $content;

?>

The following is the result of the API request syntax seen in browser.

Kerikil

  • To tell the system that it is not a real conversation and should not be replicate for the second time by the model, we can change the name in the message from system to user_example and assistant_example.
<?php

$openaiApiKey = "YOUR_API_KEY";

$data = array(
  "model" => "gpt-3.5-turbo",
  "messages" => array(
    array("role" => "system", "content" => "Kamu adalah asisten yang membantu dan mengikuti pola."),
    array("role" => "system", "name" => "user_contoh", "content" => "Bantu aku menerjemahkan contoh kiasan berikut"),
    array("role" => "system", "name" => "assistant_contoh", "content" => "Tentu, dengan senang hati!"),
    array("role" => "system", "name" => "user_contoh", "content" => "Hatinya lembut seperti?"),
    array("role" => "system", "name" => "assistant_contoh", "content" => "Kapas"),   
    array("role" => "system", "name" => "user_contoh", "content" => "Pemikirannya keras seperti?"),
    array("role" => "system", "name" => "assistant_contoh", "content" => "Batu"),     
    array("role" => "user", "content" => "Tindakannya kasar seperti?")     
  ),
  "temperature" => 0.2,
  "max_tokens" => 512,
  "top_p" => 0.2,
  "frequency_penalty" => 0.0,
  "presence_penalty" => 0.6
);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.openai.com/v1/chat/completions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($data),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . $openaiApiKey,
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$result = json_decode($response, true);
$content = $result['choices'][0]['message']['content'];
echo $content;

?>

The following is the result of the API request syntax seen in browser.

Kerikil

Further Improvisation

From the static script example above, we can make further improvements by adding an input field. The input field function as the receiver of the user message, which the model then generate the response to answer the message.

We can improve it further by developing the model to store the questions already asked by the user during the usage. This will create continuation in the discussion as asks things related to the previous questions.

We have created a simple PHP application in CloudRaya’s VM as an example, which functions as a Trip Advisor that allows users to interact with the bot and ask about interesting tourism spots or deny the question if it does not relate to the tourism theme.

Conclusion

We hope this tutorial can help you understand on how to integrate OpenAI API for the Chat model in your website project using PHP language in CloudRaya’s VM.

Visit CloudRaya’s Knowledge Base for more tutorials surrounding cloud computing or you can visit our YouTube channel if you prefer a video format.

Table of Contents

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

Ready, Set, Cloud

Ready, Set, Cloud