Integrating ChatGPT Prompt into Your Web Page Using JavaScript:

Integrating ChatGPT Prompt into Your Web Page Using JavaScript:

In today's digital age, creating engaging and interactive web pages has become essential. One way to make your web page more dynamic is by integrating ChatGPT's prompt feature. This allows your users to interact with OpenAI's powerful language model directly on your website. In this tutorial, we will walk you through the process of adding a ChatGPT prompt to your web page using JavaScript.

Prerequisites :

Before we dive into the implementation, make sure you have the following:

  1. A basic understanding of HTML, CSS, and JavaScript.
  2. An OpenAI API key to access the ChatGPT API.
  3. A code editor for making changes to your web page's code.

Step 1: Set Up Your HTML

First, let's create the basic structure of your web page. In your HTML file, you've provided a search bar code. For this tutorial, we'll use this as our starting point. You can customize it further according to your design preferences.

<!DOCTYPE html>
<html>
<head>
  <!-- Your head content -->
</head>
<body>
  <div class="container">
    <form class="search-bar">
      <input type="text" placeholder="Ask a question" id="user-input" />
      <button type="button" id="submit-button">Submit</button>
    </form>
  </div>
  <div class="chat-container" id="chat-container">
    <!-- ChatGPT conversation will be displayed here -->
  </div>
  
  <!-- Your script tags and other content -->
</body>
</html>
        

Step 2: Add JavaScript for ChatGPT Interaction

Now, let's add the JavaScript code that will enable ChatGPT interaction on your web page.

<!-- Add this script to the bottom of the body or in the head, after loading the HTML content -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  // Get elements
  const userInput = document.getElementById("user-input");
  const submitButton = document.getElementById("submit-button");
  const chatContainer = document.getElementById("chat-container");

  // OpenAI API key (replace 'YOUR_API_KEY' with your actual API key)
  const apiKey = "YOUR_API_KEY";

  // Create conversation history
  let conversation = [];

  // Event listener for submit button
  submitButton.addEventListener("click", () => {
    const userMessage = userInput.value.trim();
    if (userMessage !== "") {
      // Display user message in the chat container
      conversation.push({ role: "user", content: userMessage });
      renderChat();

      // Send user message to ChatGPT
      fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
          messages: conversation,
        }),
      })
        .then((response) => response.json())
        .then((data) => {
          // Get and display ChatGPT's reply
          const reply = data.choices[0].message.content;
          conversation.push({ role: "assistant", content: reply });
          renderChat();
        })
        .catch((error) => console.error("Error:", error));
      
      // Clear user input field
      userInput.value = "";
    }
  });

  // Render conversation in the chat container
  function renderChat() {
    chatContainer.innerHTML = "";
    conversation.forEach((message) => {
      const messageElement = document.createElement("div");
      messageElement.classList.add("message", message.role);
      messageElement.innerText = message.content;
      chatContainer.appendChild(messageElement);
    });
  }
</script>
        

Step 3: Style the Chat Interface

To make the chat interface visually appealing, you can add CSS rules. Update your existing <style> tag or add a new one to your HTML's <head> section:

<style>
  /* Your existing styles */

  .chat-container {
    margin-top: 20px;
    max-width: 300px;
    background-color: white;
    border-radius: 10px;
    padding: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .message {
    margin-bottom: 10px;
    padding: 8px;
    border-radius: 6px;
  }

  .user {
    background-color: #f1f1f1;
    text-align: right;
  }

  .assistant {
    background-color: #e1e1e1;
  }
</style>
        

Conclusion :

Congratulations! You've successfully integrated a ChatGPT prompt into your web page using JavaScript. Users can now ask questions or input text, and ChatGPT will provide responses that are displayed in a conversation format on the page. This integration opens up a world of possibilities for enhancing user engagement and providing valuable information in a conversational manner. Feel free to further customize the design and functionality to fit your website's theme and purpose.

要查看或添加评论,请登录

Nikita Sharma的更多文章

社区洞察

其他会员也浏览了