Question:
I’m having issues over & over again trying to implement a chatbot on my Wix Studio site. The code I’m entering for backend (chatbot.jsw) is:
import { fetch } from 'wix-fetch';
import { secrets } from 'wix-secrets-backend';
export async function getOpenAIResponse(userMessage) {
try {
const apiKey = await secrets.get("OpenAI_API_Key"); // Retrieve the API key securely
if (!apiKey) {
throw new Error("API Key is missing or not set up in Wix Secrets Manager.");
}
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: userMessage }],
max_tokens: 100
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`OpenAI API Error: ${response.status} - ${errorText}`);
}
const data = await response.json();
return data.choices[0].message.content; // Return AI response
} catch (error) {
console.error("OpenAI API Error:", error);
return "Sorry, something went wrong.";
}
}
Then for the frontend:
import { getOpenAIResponse } from 'backend/chatbot';
$w.onReady(function () {
$w('#sendButton').onClick(async () => {
const userMessage = $w('#chatInput').value.trim();
if (!userMessage) {
$w('#aiResponseText').text = "Please enter a message.";
return;
}
$w('#aiResponseText').text = "Thinking..."; // Show loading message
try {
const aiResponse = await getOpenAIResponse(userMessage);
$w('#aiResponseText').text = aiResponse;
} catch (error) {
console.error("Chatbot error:", error);
$w('#aiResponseText').text = "Sorry, something went wrong.";
}
});
});
Please, what am I doing wrong!?! I’ve tried over and over. The error message I’m continuing to get is:
OpenAI API Error: Cannot read properties of undefined (reading ‘get’)
I’ve checked, double-checked and triple-checked everything but continuously running into issues! Any help would be much appreciated!
Product:
Wix Studio
What are you trying to achieve:
I’m trying to create a chatbot which can answer questions for guests relating to Airbnb properties they are staying in.
What have you already tried:
I have tried making a text input for questions, submit button & text box for answers with API key.