Introduction:
Embarking on the journey of creating your own AI assistant is an exciting endeavor, especially when leveraging the incredible capabilities of OpenAI. In this blog post, we’ll guide you through the process of not only integrating OpenAI with Node.js but also constructing a personalized AI assistant that can engage in dynamic conversations and provide intelligent responses.
Prerequisites:
Before diving into the development, make sure you have the following prerequisites installed on your system:
- Node.js: Download and install Node.js from https://nodejs.org/.
- OpenAI API Key: Sign up on the OpenAI platform to obtain your API key.
Setting Up Your Node.js Project:
- Create a New Project:
Open your terminal and create a new directory for your project. Navigate to the project directory
mkdir custom-assistant-nodejs
cd custom-assistant-nodejs2. Initialize Your Node.js Project:
Run the following command to initialize your Node.js project and create a package.json file
npm init -y3. Install Necessary Packages:
Install both the openai and readline npm packages
npm install openai readlineBuilding Your Custom Assistant:
- Create a JavaScript File:
Create a new JavaScript file (e.g., custom-assistant.js) using your preferred code editor.
2. Import Required Modules:
Import the necessary modules at the beginning of your file
const OpenAI = require('openai');
const readline = require('readline');3. Configure OpenAI Client:
Set up the OpenAI client with your API key
const openai = new OpenAI({ key: 'YOUR_OPENAI_API_KEY' });4 . Create your Assistant:
Setup your Assistant
export async function createAssistantIfNeeded() {
try {
const file = await openai.files.create({
file: fs.createReadStream("mydata.txt"),
purpose: "assistants",
});
// Check if the assistant already exists
const existingAssistants = await openai.beta.assistants.list();
const existingAssistant = existingAssistants.data.find(
(assistant) => assistant.name === "LegalGuide AI"
);
if (existingAssistant) {
console.log("Assistant already exists:", existingAssistant);
return existingAssistant; // Return the existing assistant if found
}
// If not found, create a new assistant
const assistant = await openai.beta.assistants.create({
name: "LegalGuide AI",
instructions:
"LegalGuide AI is your intelligent legal companion, designed to assist you in navigating the complex world of laws and regulations effortlessly.",
model: "gpt-3.5-turbo",
tools: [{ type: "code_interpreter" }],
file_ids: [file.id],
});
console.log("New assistant created:", assistant);
return assistant;
} catch (error) {
console.error("Error creating assistant:", error);
}
}
createAssistantIfNeeded();5. Creating Thread, Messages and running the Assistant for response:
Writing functions in server.js file for creating threads, adding messages and running the assistant.
import express from "express";
import { openai } from "./Assistant.js";
import { createAssistantIfNeeded } from "./Assistant.js";
// Setup Express
const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
const assistant = await createAssistantIfNeeded();
// Assistant can be created via API or UI
const assistantId = assistant.id;
let pollingInterval;
// Set up a Thread
async function createThread() {
console.log("Creating a new thread...");
const thread = await openai.beta.threads.create();
console.log(thread);
return thread;
}
async function addMessage(threadId, message) {
console.log("Adding a new message to thread: " + threadId);
const response = await openai.beta.threads.messages.create(threadId, {
role: "user",
content: message,
});
return response;
}
async function runAssistant(threadId) {
console.log("Running assistant for thread: " + threadId);
const response = await openai.beta.threads.runs.create(threadId, {
assistant_id: assistantId,
});
console.log(response);
return response;
}
async function checkingStatus(res, threadId, runId) {
const runObject = await openai.beta.threads.runs.retrieve(threadId, runId);
const status = runObject.status;
console.log(runObject);
console.log("Current status: " + status);
if (status == "completed") {
clearInterval(pollingInterval);
const messagesList = await openai.beta.threads.messages.list(threadId);
let messages = [];
messagesList.body.data.forEach((message) => {
messages.push(message.content);
});
res.json({ messages });
}
}6. Creating Routes for using API to POST and Fetch requested Data:
Create a route to get thread id and send message on that thread to the newly created assistant using a post request.
// Open a new thread
app.get("/thread", (req, res) => {
createThread().then((thread) => {
res.json({ threadId: thread.id });
});
});
app.post("/message", (req, res) => {
const { message, threadId } = req.body;
addMessage(threadId, message).then((message) => {
// res.json({ messageId: message.id });
// Run the assistant
runAssistant(threadId).then((run) => {
const runId = run.id;
// Check the status
pollingInterval = setInterval(() => {
checkingStatus(res, threadId, runId);
}, 5000);
});
});
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});Testing Your Custom Assistant:
Run your server.js file.
npm run serverConclusion:
Congratulations! You’ve successfully built your own AI assistant using OpenAI and Node.js. This customizable assistant opens up a world of possibilities for creating personalized, intelligent interactions in your applications. Experiment with different prompts, tweak parameters, and tailor the assistant to suit your specific needs. Enjoy exploring the potential of your new AI-powered companion!
