Help with Openai gpt integration

Question:

Hi all, following on from my previous post I have been playing with trying to set up streaming for my Openai api. I now can’t get the api to work and keep returning a 400 error. Just to recap - I am trying to create an ai chatbot for the homepage of my website.

Product:

I’m using Wix Studio and Openai

What have you already tried:

Here are the 2 codes I’m currently using:

Stream - main api call

import fetch from ‘wix-fetch’;
import axios from ‘axios’;
import sendStreamToFrontend from ‘backend/realtime’;

const EXAMPLE_MESSAGES = [{
role: “system”,
content: “You are a helpful occupational health and safety assistant”,
},
{
role: “user”,
content: “what is the health and safety at work act?”
}
]

export async function getChatStream(messages, resourceId) {
const apiKey = “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”;
const endpoint = “https://api.openai.com/v1/chat/completions”;
const body = {
messages,
model: “gpt-3.5-turbo-0125”,
stream: true,
}

 try {

    const client = axios.create({
        headers: {
            Authorization: `Bearer ${apiKey}`,
        }
     })

    const response = await client.post(endpoint, body, { responseType: 'stream' });

    let receivedChunks = [];

    response.data.on('data', async (chunk) => {
        const chunkString = chunk.toString();
        const deltas = extractDeltasFromString(chunkString);
        receivedChunks = [...receivedChunks, ...deltas];
        sendStreamToFrontend(receivedChunks, resourceId)
       // console.log(receivedChunks.map((chunk)=> chunk.content).join(""));
    })

} catch (error) {
    console.log("Error getting completion", error);
}

}

function extractDeltasFromString(stringData) {
const deltaMatches = stringData.match(/“delta”:\s*({[^{}]*})/g);
console.log(deltaMatches);
let deltas = ;
for (let i = 0; i < deltaMatches.length; i++) {
let delta = JSON.parse(deltaMatches[i].substring(8));
console.log(delta)
deltas.push(delta)

}

return deltas;

}

Realtime add on

import wixRealtimeBackend from ‘wix-realtime-backend’;

export async function sendStreamToFrontend(receivedChunks, resourceId) {
const channel = {
name: “chatbot”,
resourceId,
};

    wixRealtimeBackend.publish(channel, receivedChunks)
        .then(() => {

    });

}

Additional information:

Currently receiving 400 errors when calling the api. Any help would be appreciated.

Hello!

First I wanted to bring to your attention that you posted your API key in your question. You will want to update this to not expose your key

Second, have you tested this API anywhere else such as postman?

Hi amanda, I haven’t tried the api anywhere else but have it set up without the stream and that seems to be ok.
I realised the apikey as soon as I posted so have deleted it and set a new one up.
Just to add a bit of context, I’m a complete beginner and followed a YouTube tutorial to create the code here. It appears to be the same as the instructors but for some reason it just doesn’t work for me.

No problem! So the reason I asked if you had tested it elsewhere first is that the response you are getting means “bad request” which is not specific to Wix.

To test that you have all your headers and API key correct first, you could use something like postman to make sure that everything is working there first.

You can also test with just the fetch part of your code to work with what may be configured incorrectly first

Hey @Michael_Swain

It can be difficult to setup AI chats with code. With Chat with GPT Canvas, you can do the same by simply adding the widget to any page you like. It supports normal conversation and docs editing well. Give it a try!