Cant seem to get the Assistant API to work for me :(

I can’t seem to get my API code to work in JS for my chatbot in HTML…

Here is the code:
// Function to fetch a response from OpenAI
const getResponse = async (userMessage) => {
try {
const response = await fetch(‘https://api.openai.com/v1/assistants’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: Bearer ${OPENAI_API_KEY},
‘OpenAI-Beta’: ‘assistants=v2’ // Add this header
},
body: JSON.stringify({
assistant_id: ASSISTANT_ID, // Use assistant ID here
messages: [
{ role: “system”, content: “You are chatting with an AI assistant.” },
{ role: “user”, content: userMessage }
],
max_tokens: 150
})
});

    // Parse the response
    const data = await response.json();

    // Log the entire response for debugging
    console.log("API response:", data);

    // Handle response error
    if (!response.ok) {
        throw new Error(data.error.message || "API request failed");
    }

    // Check if data and choices exist
    if (data.choices && data.choices.length > 0) {
        return data.choices[0].message.content.trim();
    } else {
        throw new Error("No valid choices returned in the response");
    }
} catch (error) {
    console.error("Error fetching response:", error);
    return "Der opstod en fejl ved hentning af svar fra assistenten.";
}

};

TIA

if i understand correctly that you already have assistant existing, you can start by creating a thread and run.

const getResponse = async (userMessage) => {

const response = await fetch(`https://api.openai.com/v1/threads/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'OpenAI-Beta': 'assistants=v2'
},
body: JSON.stringify({
      assistant_id: ASSISTANT_ID,
      instructions: "You are chatting with an AI assistant.",
      thread: {
        messages: [
          {role: "user", content: userMessage}
        ]
      }
    })
})

const result = await response.json()
// result will contain run id and thread id etc

...
}

then do polling to check for the status of the run by retrieving it.

if the status is completed, get the messages.

Yes it is correct, I already have my assistant_ID ready.
I yet still can’t seem to get it working…
It works perfectly in my simple Python code:

def get_response(thread_id, message):
try:
client.beta.threads.messages.create(
thread_id=thread_id,
role=“user”,
content=message
)

    class EventHandler(AssistantEventHandler):
        @override
        def on_text_created(self, text) -> None:
            print(f"\nassistant > ", end="", flush=True)

        @override
        def on_text_delta(self, delta, snapshot):
            print(delta.value, end="", flush=True)

        def on_tool_call_created(self, tool_call):
            print(f"\nassistant > {tool_call.type}\n", flush=True)

        def on_tool_call_delta(self, delta, snapshot):
            if delta.type == 'code_interpreter':
                if delta.code_interpreter.input:
                    print(delta.code_interpreter.input, end="", flush=True)
                if delta.code_interpreter.outputs:
                    print(f"\n\noutput >", flush=True)
                    for output in delta.code_interpreter.outputs:
                        if output.type == "logs":
                            print(f"\n{output.logs}", flush=True)

    with client.beta.threads.runs.stream(
        thread_id=thread_id,
        assistant_id=assistant_id,
        event_handler=EventHandler(),
    ) as stream:
        stream.until_done()

except Exception as e:
    print(f"An error occurred: {e}")

I have now made the JS code, to make a thread, post the message, get the response, but somehow it still won’t give me / show me the response.

Thank you