I am developing an assistant chatbot app for a company, I use ionic framework 7 and I want to use the openai assistant to connect as the chatbot of that application. I am having problems with the connection with the openai assistant and the bot’s responses.
This is the code of my server.js file
import express from "express";
import * as dotenv from "dotenv";
import cors from "cors";
import fs from "fs";
import path from "path";
import OpenAI from "openai";
import { fileURLToPath } from 'url';
import { calculateSimilarity } from './similarity.js';
dotenv.config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
organization: process.env.OPENAI_ORG_ID,
project: process.env.OPENAI_PROJECT_ID,
});
const assistantId = process.env.OPENAI_ASSISTANT_ID;
const app = express();
app.use(cors());
app.use(express.json());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const embeddings = JSON.parse(fs.readFileSync(path.resolve(__dirname, './embeddings.json'), 'utf8'));
function findRelevantEmbedding(prompt, embeddings) {
let mostRelevantEmbedding = embeddings[0];
let highestSimilarity = -Infinity;
embeddings.forEach(embedding => {
const similarity = calculateSimilarity(prompt, embedding.content);
if (similarity > highestSimilarity) {
highestSimilarity = similarity;
mostRelevantEmbedding = embedding;
}
});
return mostRelevantEmbedding;
}
async function createThread() {
const thread = await openai.beta.threads.create();
return thread.id;
}
async function addMessage(threadId, prompt) {
const response = await openai.beta.threads.messages.create(threadId, {
role: "user",
content: prompt
});
return response;
}
async function runAssistant(threadId) {
const response = await openai.beta.threads.runs.create(threadId, {
assistant_id: assistantId
});
console.log(response);
return response;
}
async function getRunStatus(threadId, runId) {
const runObject = await openai.beta.threads.runs.retrieve(threadId, runId);
return runObject;
}
app.get("/", async (req, res) => {
res.status(200).send({
message: 'Sea bienvenido a nuestro Chatbot',
});
});
app.post("/", async (req, res) => {
try {
const prompt = req.body.prompt;
const relevantEmbedding = findRelevantEmbedding(prompt, embeddings);
const threadId = await createThread();
await addMessage(threadId, relevantEmbedding.content.substring(0, 2000));
await addMessage(threadId, prompt.substring(0, 1000));
const runResponse = await runAssistant(threadId);
const runId = runResponse.id;
let runStatus = await getRunStatus(threadId, runId);
const pollingInterval = setInterval(async () => {
runStatus = await getRunStatus(threadId, runId);
if (runStatus.status === 'completed') {
clearInterval(pollingInterval);
const messagesList = await openai.beta.threads.messages.list(threadId);
const botResponse = messagesList.data[messagesList.data.length - 1].content || "Lo siento, no pude entender tu pregunta. ¿Podrías ser más específico?";
res.status(200).send({ bot: botResponse });
} else if (runStatus.status === 'failed' || runStatus.status === 'expired') {
clearInterval(pollingInterval);
res.status(500).send({ error: "Error en la ejecución del asistente." });
}
}, 5000);
} catch (error) {
console.log(error);
res.status(500).send({ error: error.message });
}
});
app.listen(3000, () =>
console.log('Server is running on port: http://localhost:3000')
);
and this is the code of my page.ts file
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { IonContent } from '@ionic/angular';
import { Message } from 'src/app/models/message.model';
import { OpenaiService } from 'src/app/services/openai.service';
@Component({
selector: 'app-tab4-faq',
templateUrl: './tab4-faq.page.html',
styleUrls: ['./tab4-faq.page.scss'],
})
export class Tab4FaqPage implements OnInit {
@ViewChild(IonContent, { static: false }) content!: IonContent;
messages: Message[] = [];
form = new FormGroup({
prompt: new FormControl('', [Validators.required]),
});
loading: boolean = false;
constructor(private openAi: OpenaiService) {}
ngOnInit() {}
submit() {
if (this.form.valid) {
let prompt = this.form.value.prompt as string;
// === MENSAJES DEL USUARIO ===
let userMsg: Message = { sender: 'me', content: prompt };
this.messages.push(userMsg);
this.scrollToBottom();
this.form.reset();
this.form.disable();
this.loading = true;
this.openAi.sendQuestion(prompt).subscribe({
next: (res: any) => {
this.loading = false;
let botMsg: Message = { sender: 'bot', content: res.bot };
this.messages.push(botMsg);
this.scrollToBottom();
this.form.enable();
},
error: (error: any) => {
console.log(error);
},
});
}
}
scrollToBottom() {
this.content.scrollToBottom(2000);
}
}