The OpenAI Assistants chat on my website is not working. Help. What am I doing wrong?
Created the openai.js Backend file in Wix.
I checked the code of the Backend file via curl. Everything is working correctly.
I have configured Wix Secrets Manager.
import { ok, badRequest, serverError } from 'wix-http-functions';
import { fetch } from 'wix-fetch';
import { getSecret } from 'wix-secrets-backend';
// Wix HTTP function for processing requests to /_functions/openai
export async function post_openai(request) {
try {
const body = await request.body.json();
if (!body || !body.prompt) {
return badRequest({ error: 'Missing prompt in request body' });
}
// Getting the OpenAI API key from Wix Secrets Manager
const OPENAI_API_KEY = await getSecret('OPENAI_API_KEY');
if (!OPENAI_API_KEY) {
return serverError({ error: 'Missing API Key in Wix Secrets Manager' });
}
// 📌 1. Create a new thread in the OpenAI API
const threadResponse = await fetch('https://api.openai.com/v1/threads', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'OpenAI-Organization': 'org-z3ndKqkioEvGaNvq8DWrt802',
'OpenAI-Project': 'proj_8EBZTjUSpFEPU8iReN0CaEB7',
'OpenAI-Beta': 'assistants=v2'
},
body: JSON.stringify({})
});
const threadData = await threadResponse.json();
if (!threadData.id) {
return serverError({ error: 'Failed to create thread' });
}
const threadId = threadData.id;
// 📌2. Launch the assistant in this thread
const runResponse = await fetch(`https://api.openai.com/v1/threads/${threadId}/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'OpenAI-Organization': 'org-z3ndKqkioEvGaNvq8DWrt802',
'OpenAI-Project': 'proj_8EBZTjUSpFEPU8iReN0CaEB7',
'OpenAI-Beta': 'assistants=v2'
},
body: JSON.stringify({ assistant_id: 'asst_jCDZoY1D8rqfbXYjPXROZedC' })
});
const runData = await runResponse.json();
if (!runData.id) {
return serverError({ error: 'Failed to start assistant' });
}
// 📌 3. We are waiting for the assistant's response (2 sec delay)
await new Promise(resolve => setTimeout(resolve, 2000));
// 📌 4. We receive the assistant's response
const messageResponse = await fetch(`https://api.openai.com/v1/threads/${threadId}/messages`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'OpenAI-Organization': 'org-z3ndKqkioEvGaNvq8DWrt802',
'OpenAI-Project': 'proj_8EBZTjUSpFEPU8iReN0CaEB7',
'OpenAI-Beta': 'assistants=v2'
}
});
const messageData = await messageResponse.json();
if (!messageData.messages || messageData.messages.length === 0) {
return serverError({ error: 'No response from assistant' });
}
return ok({ message: messageData.messages[0].content });
} catch (error) {
console.error('Ошибка обработки запроса:', error);
return serverError({ error: 'Failed to process request' });
}
}
Set up Frontend (Wix Page Code)
$w('#submitButton').onClick(async () => {
const userPrompt = $w('#inputField').value.trim();
if (!userPrompt) {
$w('#outputField').text = 'Enter a message!';
return;
}
$w('#outputField').text = 'Generating a response...';
try {
const response = await fetch('/_functions/openai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt: userPrompt }),
});
const responseText = await response.text();
console.log('Response from the server:', responseText);
if (!response.ok) {
$w('#outputField').text = `Error: ${responseText}`;
return;
}
const responseData = JSON.parse(responseText);
$w('#outputField').text = responseData.message;
} catch (error) {
console.Error('Error:', error);
$w('#outputField').text = `Error: ${error.message}`;
}
});