Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

PHP

Make your own ChatGPT using OpenAI API with PHP

By Admin
February 5, 2023 4 Min Read
Comments Off on 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

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>

 

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.

Tags:

chatgptopenai
Author

Admin

Follow Me
Other Articles
Previous

How to add Facebook Login to Your Website

Next

What does ChatGPT says about itself ?

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme