Question:
How do i connect a form to open AI:s API?
Product:
Wix website editor
What are you trying to achieve:
I want to create a simple form where the user puts in one word and gets a response from an assistant or GPT from OpenAI. I have created a GPT which will provide the response I want.
What have you already tried:
I have this code in the Velos Page Code section
// Add this code in Velo’s Page Code section
import { chatGPTQuery } from ‘backend/chat-gpt-module’;
$w.onReady(function () {
// When the user submits the job title
$w(“#submitButton”).onClick(async function () {
const jobTitle = $w(“#jobTitleInput”).value;
// Check if the job title is not empty
if (jobTitle.trim() === "") {
$w("#responseText").text = "Please enter a job title.";
return;
}
try {
$w("#responseText").text = "Loading...";
// This calls the backend function
const response = await getGPTResponse(jobTitle);
// Display the ChatGPT response
$w("#responseText").text = response;
} catch (error) {
$w("#responseText").text = "Error: " + error.message;
}
});
});
/**
- Calls the backend function which interacts with the ChatGPT API.
- @param {string} jobTitle The job title entered by the user.
- @return {Promise} The ChatGPT response as a string.
*/
function getGPTResponse(jobTitle) {
chatGPTQuery(jobTitle)
.then(response => {
return response;
})
.catch(err => {
console.error(err);
throw new Error(‘There was an error processing your request.’);
});
return wixBackendFunction(‘chatGPTQuery’, { jobTitle });
}
I have the following code in a js file in the back-end section. I have inserted an API key from Open AI wherer it says “API-Key”
import {fetch} from ‘wix-fetch’;
/// WHAT URL SHOULD BE USED?
export function chatGPTQuery(message) {
const url = “https://api.openai.com/v1/chat/completions”;
const headers = {
“Authorization”: `Bearer API-KEY,
“Content-Type”: “application/json”
};
const body = JSON.stringify({
model: “gpt-3.5-turbo”, // Specify the model version
messages: [{role: “user”, content: message}]
});
return fetch(url, {method: 'POST', headers: headers, body: body})
.then(response => response.json())
.then(data => data.choices[0].message.content);
}
Additional information:
I have created an AI assistant in open ai:s platform which is connected to the API key. I can’t figure out what is wrong.