s
Virtual assistance

OPENAI API INTEGRATION

In this section you can learn about integration process of OpenAI models.

Step-by-Step Guide to Integrating OpenAI API into Your Website

Step 1: Get OpenAI API Key

  • Sign up or log in to OpenAI.
  • Go to the API Keys section.
  • Click on "Create a new secret key" and copy it. (You'll need this later.)

Step 2: Set Up Your Website (HTML, CSS, JavaScript)

You can integrate the API into any website, but here’s a simple frontend using HTML + JavaScript.

Create an HTML File (index.html)


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAI API Integration</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin: 50px; }
textarea { width: 80%; height: 100px; margin-bottom: 10px; }
button { padding: 10px 20px; font-size: 16px; }
#response { margin-top: 20px; font-weight: bold; }
</style>
</head>
<body>
<h2>Ask OpenAI</h2>
<textarea id="userInput" placeholder="Enter your prompt..."></textarea><br>
<button onclick="fetchResponse()">Submit</button>
<div id="response"></div>
<script src="script.js"></script>
</body>
</html>

									

Step 3: Write JavaScript to Call OpenAI API

Create a JavaScript File (script.js)


const apiKey = "YOUR_OPENAI_API_KEY";  // Replace with your OpenAI API key
async function fetchResponse() {
const userInput = document.getElementById("userInput").value;
if (!userInput) {
alert("Please enter a prompt.");
return;
}
const apiUrl = "https://api.openai.com/v1/chat/completions";
	
const requestData = {
model: "gpt-3.5-turbo",  // Change to "gpt-4" if using GPT-4
messages: [{ role: "user", content: userInput }],
max_tokens: 100
};

try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify(requestData)
});

const data = await response.json();
document.getElementById("response").innerText = data.choices[0].message.content;
} catch (error) {
console.error("Error:", error);
document.getElementById("response").innerText = "Error fetching response.";
}
}

Step 4: Host Your Website

  • Localhost: Open index.html in a browser.
  • GitHub Pages: Push your files to a GitHub repository and enable Pages.
  • Netlify/Vercel: Drag and drop your files for free hosting.

Security Warning

  • Do NOT expose your API key in JavaScript on a public website!
  • Use a backend server (Node.js, Python, PHP) to handle API calls securely.