Obtain an API Key from OpenAI:
- First, sign up for an account on OpenAI's website.
- Once registered, access your API keys in the OpenAI dashboard.
Set Up a Backend Server:
- You'll need a backend server to handle API requests. This can be done using Node.js, Python, or any server-side language you prefer.
Create an Endpoint Route on Your Server:
- This route will receive messages from your website's frontend and make requests to the ChatGPT API.
Example Code in Node.js:
javascriptconst express = require('express'); const axios = require('axios'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; const apiKey = 'YOUR_API_KEY'; // Replace with your OpenAI API key app.use(bodyParser.json()); app.post('/chat', async (req, res) => { const userMessage = req.body.message; try { const response = await axios.post( 'https://api.openai.com/v1/engines/davinci-codex/completions', { prompt: userMessage, max_tokens: 150, temperature: 0.7, top_p: 1, frequency_penalty: 0, presence_penalty: 0, }, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } } ); res.json(response.data.choices[0].text.trim()); } catch (error) { console.error(error); res.status(500).send('Error communicating with ChatGPT'); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Frontend:
- In the frontend, capture the user's input and send it to your server. Here’s a simple example using HTML and JavaScript:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ChatGPT Integration</title> <style> body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background-color: #f0f0f0; } #chat { display: flex; flex-direction: column; width: 300px; border: 1px solid #ccc; padding: 10px; background-color: #fff; border-radius: 5px; } #userMessage { margin-bottom: 10px; padding: 5px; border: 1px solid #ccc; border-radius: 3px; } #response { margin-top: 10px; white-space: pre-wrap; } </style> </head> <body> <h1>ChatGPT</h1> <div id="chat"> <input type="text" id="userMessage" placeholder="Type your message here"> <button onclick="sendMessage()">Send</button> <div id="response"></div> </div> <script> async function sendMessage() { const userMessage = document.getElementById('userMessage').value; document.getElementById('response').innerText = "Please wait..."; const response = await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: userMessage }) }); const data = await response.json(); document.getElementById('response').innerText = data; } </script> </body> </html>
Additional Considerations
Security
Protecting Your API Key:
- Never expose your API key on the frontend. Always make API calls from the backend to keep your key secure.
Rate Limiting:
- Implement rate limiting to prevent abuse. OpenAI also enforces usage limits that should be respected.
Customization
API Parameters:
- max_tokens: Sets the maximum number of tokens in the response.
- temperature: Controls the randomness of responses. Higher values (up to 1) make responses more creative, while lower values (0.2-0.5) make them more focused and deterministic.
- top_p: Samples responses from the top probability tokens.
- frequency_penalty and presence_penalty: Adjust penalties for repetitive words.
Conversation History:
- For a richer experience, you can implement conversation history by sending previous context along with the new message to the API.
Example of Implementing Conversation History
To add conversation history, modify the backend to include previous messages:
javascriptlet conversationHistory = [];
app.post('/chat', async (req, res) => {
const userMessage = req.body.message;
conversationHistory.push(`User: ${userMessage}`);
try {
const response = await axios.post(
'https://api.openai.com/v1/engines/davinci-codex/completions',
{
prompt: conversationHistory.join("\n"),
max_tokens: 150,
temperature: 0.7,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
},
{
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
}
);
const botMessage = response.data.choices[0].text.trim();
conversationHistory.push(`ChatGPT: ${botMessage}`);
res.json(botMessage);
} catch (error) {
console.error(error);
res.status(500).send('Error communicating with ChatGPT');
}
});
This guide should give you a solid foundation for integrating ChatGPT into your website. If you need more details or assistance with any specific step, feel free to ask!