Make your own ChatGPT using OpenAI API with PHP

0
1400

OpenAI’s GPT-3 (Generative Pretrained Transformer 3) technology is available through an API, also known as the OpenAI API or the GPT-3 API. The API allows developers to integrate GPT-3’s advanced language capabilities into their applications and services.

GPT-3 is trained on a massive amount of diverse text data, allowing it to generate human-like responses to a wide range of language tasks. It can be fine-tuned for specific use cases and applications, making it a versatile tool for developers.

With the API, developers can build conversational AI systems, language translation systems, and other advanced language-based applications. The API offers a wide range of functionality, including text completion, text generation, question-answering, and summarization, among others.

The API is a cloud-based service and can be accessed over the internet through standard HTTP requests. It is also highly scalable, meaning that it can handle a large number of requests from multiple clients simultaneously.

Follow this video for complete guidance :

Steps to Build Your Own ChatGPT

1. Get Your API key by signing in to your account here

https://openai.com/api/

2. Save Your API Key in api_key.txt file

3. Create a composer.json file

{
    "require": {
        "orhanerday/open-ai": "^3.4",
        "league/commonmark": "^2.3"
    },
    "config": {
        "platform-check": false
    }
}

4. Run composer install

composer install

5. Create a chat view with following code

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

<style type="text/css">
  body,.container-fluid{
    padding: 0;
    margin: 0;
  }
  .header{
    background: #000;
    color:#fff;
    height:80px;
  }
  .chat-message{
    border-radius: 10px;
      padding: 5px 15px;
      margin: 10px 0;
      line-height: 1.5em;
  }
  .message-out{
    background: #ddd;
  }
  .message-in{
    background: #3e4343;
    color:#fff;
  }
  .input-box{
    width:100%;
    position: fixed;
    bottom:0;
    height:120px;
    padding:20px 0px;
    background: #000;
  }
  #chat-input{
    margin: 20px auto;
      resize: none;
      border: none;
      color: #fff;
      background-color: #3e4343;
      outline: none;
      padding: 15px;
      font-size: 1.1em;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      width: 75%;
  }
  #cursor{
    width: 5px;
      height: 20px;
      background-color: #fff;
      display: inline-block;
      animation: blink 1s infinite;
  }
  @keyframes blink {
      0% {
          opacity: 0;
      }
      50% {
          opacity: 1;
      }
      100% {
          opacity: 0;
      }
  }
</style>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>

<div class="container-fluid">
  <div class="row">
    <div class="col-12">
      <div class="header d-flex align-items-center justify-content-center">
        <h1>ChatJPT</h1>
      </div>
    </div>
  </div>
</div>

<div class="container mt-3 chat-content" style="margin-bottom:150px;">
  <div class="chat-messages">
    
  </div>
</div>
<div class="input-box">
  <textarea id="chat-input" placeholder="Type Here"></textarea>
</div>

<script type="text/javascript">
  var chat_input = $("#chat-input");
  var chat_container = $(".chat-content");
  var context = [];


  $(document).on('keypress',function(e) {
      if(e.which == 13) {
      	message();
      	e.preventDefault();
      }
  });

  function appendMessage(flag,message,className){
    html = '<div class="'+className+' chat-message message-'+flag+'">'+message+'</div>';
    chat_container.append(html);
    	$("html, body").animate({ scrollTop: $(document).height() }, 300);

  }

  function message(){
    query = chat_input.val();
    appendMessage('out',query,'');
    appendMessage('in','<div id="cursor"></div>','temp');

    chat_input.val('');
    chat_input.focus();

    postData = {
      'message':query,
      'context':JSON.stringify(context)
    };
    url = 'message.php';
    $.ajax({
      url:url,
      type:'post',
      data:postData,
      success:function(res){
        if(res.status=='success'){
          $(".chat-message.temp").remove();
          appendMessage('in',res.message);
          context.push([query, res.raw_message]);
          hljs.highlightAll();
        }
      }
    });
  }
</script>

 

ALSO READ  Export jQuery DataTables to CSV

6. Create a message.php file to actually call OpenAI chat

<?php
require_once(__DIR__."/vendor/autoload.php");

$api_key = file_get_contents("api_key.txt");
$api_key = trim($api_key);

use Orhanerday\OpenAi\OpenAi;
use League\CommonMark\CommonMarkConverter;

header("Content-Type: application/json");

$previous_conversation = json_decode($_POST['context'] ?? "[]", true);
$message = $_POST['message'];

$openai = new OpenAi($api_key);

$prompt = "Format the response in Markdown format if there's code in it. Also always explain your answer in detail.\n";
$prompt .= "Use previous conversation as context:\n";

foreach ($previous_conversation as $entry) {
    $prompt .= "Question: " . $entry[0] . "\n";
    $prompt .= "Answer: " . $entry[1] . "\n\n";
}

$prompt .= "New Question: " . $message . "\n\nAnswer:\n\n";

$complete = json_decode($openai->completion([
    'model' => 'text-davinci-003',
    'prompt' => $prompt,
    'temperature' => 0.9,
    'max_tokens' => 2000,
    'top_p' => 1,
    'frequency_penalty' => 0,
    'presence_penalty' => 0,
    'stop' => [
        "\nNote:",
        "\nQuestion:"
    ]
]));

if (isset($complete->choices[0]->text)) {
    $text = str_replace("\\n", "\n", $complete->choices[0]->text);
} elseif (isset($complete->error->message)) {
    $text = $complete->error->message;
} else {
    $text = "Sorry, but I don't know how to answer that.";
}

$converter = new CommonMarkConverter();
$styled_text = $converter->convert($text);

echo json_encode([
    "message" => (string)$styled_text,
    "raw_message" => $text,
    "status" => "success",
]);

 

The parameters for the $openai->completion method are as follows:

  • model: ID of the OpenAI language model to use.
  • prompt: The text prompt that the model should complete.
  • temperature: Controls the “creativity” of the model’s response, with a higher temperature leading to more unexpected and diverse completions.
  • max_tokens: Maximum number of tokens (words or word-like units) in the response.
  • top_p: Controls the diversity of the completions generated by the model, with a higher value leading to more diverse completions and a lower value leading to more focused completions.
  • frequency_penalty: Controls the balance between selecting tokens that are frequent in the model’s training data and selecting tokens that are rare.
  • presence_penalty: Controls the balance between selecting tokens that are present in the prompt and selecting tokens that are not.
  • stop: A list of strings that, if encountered in the generated text, cause the completion to stop.
ALSO READ  Top 10 Essential Questions for a PHP Developer Interview with Expert Answers

Comments are closed.