Skip to main content

 

🔥 Full Beginner Tutorial: Create Your Own Chatbot Using ChatGPT API Key

🟩 Introduction

In this tutorial, you will learn how to create your own AI chatbot using the ChatGPT API.
This is perfect for:

✔ Websites
✔ Blogger blogs
✔ Personal projects
✔ Portfolio projects

We will create a chatbot that:

  • Sends user messages to the ChatGPT API

  • Gets responses

  • Displays chat bubbles

  • Works on any device

  • Uses your OpenAI API key


🟦 How the Chatbot Works (Explained in Simple Words)

1. HTML Structure

This creates:

  • A chat screen

  • A message input box

  • A send button

2. CSS Styling

This gives the chatbot:

  • Clean look

  • Chat bubbles

  • Responsive UI

3. JavaScript

This is the real brain:

  • Detect user’s message

  • Send it to ChatGPT API

  • Wait for reply

  • Show reply on screen

We use fetch() to call:

https://api.openai.com/v1/chat/completions

with your API key.


🟥 Very Important

Replace:

YOUR_API_KEY_HERE

with your real ChatGPT API key.

You can get one from:

https://platform.openai.com



ChatGPT Chatbot (Secure)

Copy This Code



<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>ChatGPT Chatbot</title>

  <style>
    body { font-family: system-ui, Arial; margin:0; padding:0; background:#f4f6f8; }
    .app { max-width:700px; margin:24px auto; background:#fff; border-radius:12px; box-shadow:0 6px 24px rgba(0,0,0,0.06); overflow:hidden; }
    .chat { height:60vh; overflow:auto; padding:18px; }
    .bubble { display:inline-block; padding:12px 14px; border-radius:12px; margin:8px 0; max-width:80%; }
    .user { background:#007bff; color:#fff; margin-left:auto; }
    .bot { background:#eee; color:#000; margin-right:auto; }
    .controls { display:flex; gap:8px; padding:12px; border-top:1px solid #f0f0f0; }
    input[type="text"] { flex:1; padding:10px 12px; border-radius:8px; border:1px solid #ddd; }
    button { padding:10px 14px; border-radius:8px; border:none; background:#007bff; color:#fff; cursor:pointer; }
    @media(max-width:600px){ .chat{height:50vh} }
  </style>
</head>
<body>

<div class="app">
  <div class="chat" id="chat"></div>

  <div class="controls">
    <input id="prompt" type="text" placeholder="Type a message..." />
    <button id="send">Send</button>
  </div>
</div>

<script>
(() => {
  const API_KEY = "sk-REPLACE_WITH_YOUR_KEY";

  const chatEl = document.getElementById("chat");
  const promptEl = document.getElementById("prompt");
  const sendBtn = document.getElementById("send");

  function appendBubble(text, who = "bot") {
    const d = document.createElement("div");
    d.className = "bubble " + (who === "user" ? "user" : "bot");
    d.innerText = text;
    chatEl.appendChild(d);
    chatEl.scrollTop = chatEl.scrollHeight;
  }

  async function sendMessage() {
    const text = promptEl.value.trim();
    if (!text) return;

    appendBubble(text, "user");
    promptEl.value = "";
    appendBubble("...", "bot");

    try {
      const res = await fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + API_KEY
        },
        body: JSON.stringify({
          model: "gpt-4.1-mini",
          messages: [{ role: "user", content: text }]
        })
      });

      const data = await res.json();

      const last = chatEl.querySelectorAll(".bot");
      if (last.length) last[last.length - 1].remove();

      appendBubble(data.choices?.[0]?.message?.content || "(no reply)", "bot");

    } catch (err) {
      const last = chatEl.querySelectorAll(".bot");
      if (last.length) last[last.length - 1].remove();
      appendBubble("Error: " + err.message, "bot");
    }
  }

  sendBtn.addEventListener("click", sendMessage);
  promptEl.addEventListener("keydown", e => {
    if (e.key === "Enter") sendMessage();
  });
})();
</script>

</body>
</html>

Comments

Popular posts from this blog

HTML Tables Tutorial — Learn Tables with Examples Tables organize tabular data (rows & columns). They are great for schedules, price lists, spec sheets, comparison charts, and any data that fits a grid. This guide covers: Table basics: <table> , <tr> , <td> , <th> Headers, captions, and groups ( <caption> , <thead> , <tbody> , <tfoot> ) Colspan & rowspan Styling and responsive tables Accessibility and best practices Table of Contents Basic Structure Headers & Captions Colspan & Rowspan Grouping Rows: thead / tbody / tfoot Styling Tables Responsive Tables Accessibility Tips Practical Examples Best Practices 1. Basic Structure Minimal valid table: <table> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </table> Elements: <table> — container for the table <tr> — table ...
HTML Forms Tutorial HTML Forms Tutorial HTML Forms allow users to enter and submit data. They are used everywhere—login forms, signup forms, search boxes, feedback forms, etc. In this complete tutorial, you will learn all form elements with examples and demos. 1. What is an HTML Form? A form collects user input using different form elements like text fields, checkboxes, radio buttons, buttons, and more. <form> Form elements go here... </form> 2. Basic Form Structure <form action="#" method="post"> <input type="text" placeholder="Enter name"> <button>Submit</button> </form> Submit Attributes: action → URL where form data is sent method="POST" → Secure data sending method="GET" → Data shows in URL 3. Text Input Field <input type="text" placeholder="Your Name...
What is HTML? A Beginner-Friendly Explanation If you want to become a web developer, HTML is the first language you should learn. It is the foundation of every website on the internet. In simple words: HTML (HyperText Markup Language) is used to create the structure and content of a webpage. Why HTML is important? Websites cannot exist without HTML It is simple and beginner-friendly Used with CSS and JavaScript Works on all browsers How does HTML work? HTML is made of tags . Tags tell the browser what type of content is being shown. Example of an HTML tag: <p>This is a paragraph.</p> Here: <p> is the opening tag </p> is the closing tag The text inside is the content Basic HTML Page Example Below is a simple webpage example you can try: <!DOCTYPE html> <html> <head> <title>My First Webpage</title> </head> <body> <h1>Hello World!</h1> <p>This is my...