Make your own ChatGPT using OpenAI API with PHP


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

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="">
<script type="text/javascript" src=""></script>

<style type="text/css">
    padding: 0;
    margin: 0;
    background: #000;
    border-radius: 10px;
      padding: 5px 15px;
      margin: 10px 0;
      line-height: 1.5em;
    background: #ddd;
    background: #3e4343;
    position: fixed;
    padding:20px 0px;
    background: #000;
    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%;
    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;

<link rel="stylesheet" href="">
<script src=""></script>

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

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

<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) {

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


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


    postData = {
    url = 'message.php';
          context.push([query, res.raw_message]);


ALSO READ  Basic Guidelines to Kanchanjunga Base Camp Trek

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


$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' => [

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  Everything you need to know about ChatGPT

Comments are closed.