Introduction:
Hello All! I have successfully created code that makes backend API calls to ChatGPT on a wix website without the use of 3rd party downloaded packages. I created this for a school project and it allows a user to submit a text-based transcript on a web page and the website automatically prompts ChatGPT to identify relevant information contained within and display it to the user.
This took me quite a while as previous recommendation on this forum and others failed to work properly for me. This instruction page is inspired by the work previously done by the Integrating ChatGPT question by @CODE-NINJA, but I have updated it to work without extra packages to download (They use axiom if that is something you want to try).
If you want to accomplish a similar feat, feel free to follow my code/instructions below.
How I did it:
[0] Create a FRONT END trigger.
This step requires you to add some kind of trigger on the FRONT END. This could be something like pressing a button or submitting a form. Example code is shown below for grabbing value from a form and feeding it to backend code:
import {getChatGPTResponse} from 'backend/gptCall.web.js'
$w.onReady(function () {
// Click "Run", or Preview your site, to execute your code
const submit = $w("#form1").onSubmit(async (value) => {
// Test to see if the click goes through
console.log("Form Submission: ", value.transcript);
// create a variable to hold the transcript
let prompt = "Summarize this: " + value.transcript;
try {
const response = await getChatGPTResponse(prompt);
$w('#text52').text = response.choices[0].message.content;
} catch (err) {
console.error("Error:", err);
}
});
});
[1] Grab an API Key for chatGPT.
The next step is to get an API key from ChatGPT. I will not go into specifics here as there are instructions of the GPT website on how to do this and I do not want to misinform if things are updated later. I will, however note 2 things:
- Ensure there are some credits on the account associated with this or else you will not be able to make the call.
- Store the API call in wix-Secrets to ensure that it is saved securely and there will be no security breach. All you need to so is search “Wix Secrets” on the search bar within the editor. Once you click into this service, you will be allowed to save the variable and recall it on the backed.
[2] The Code Itself.
I feel that the following code is relatively easy to understand, but I will go over it just in case.
Firstly, we import the needed Velo packages. Fetch allows you to send the request to the chatGPT website, secrets-backend allows you to grab the securely stored API key, and web-module ensures that anyone can make the request to the outside website (prevents transmissions from wix to OpenAI from being blocked).
As for the code body itself, all you need to do is copy/modify the format of the request you are sending and return the result to the front end. NOTES: you must include export so the function can be used by the front end.
import { fetch } from 'wix-fetch';
import { getSecret } from 'wix-secrets-backend';
import { Permissions, webMethod } from 'wix-web-module';
export const getChatGPTResponse = webMethod(Permissions.Anyone, async (prompt) => {
// Retrieve the API key securely from Secrets Manager
const apiKey = await getSecret("Copy YOUR KEY Name HERE");
const url = "https://api.openai.com/v1/chat/completions";
// create request body including model type and message
const body = {
model: "gpt-3.5-turbo", // Example model
messages: [{ role: "user", content: prompt }]
};
// Describe how you are going to send message (can likely copy/update)
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(body)
};
// Send the request using the fetch() method
const httpResponse = await fetch(url, options);
// wait for response and return accordingly.
if (httpResponse.ok) {
// Process and return the JSON response
return await httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
});
[3] Utilize data on the front end
The data is automatically returned to the front end code and you are free to do with it as you please. In the code from section [1], I set a text box to the response I receive.
FINAL NOTES:
- This code is something I created for a school project and should not be assumed to be secure. I would advise only professional developers use this so that they can understand what the code is doing and make security advancements as needed.
- PLEASE do not save the API key anywhere front end and use WIX Secrets to ensure things are relatively secure. DO NOT risk security for any reason.
- I cannot guarantee this code will work for you and acknowledge it may become outdated. This is simply a way to share my discovery and provide a starting point for someone trying to do something similar.
Good Luck and Have Fun with your future coding endeavors!