Skip to main content

Featured Post

How To Integrating ChatGPT with Your React App in 5 Minutes: A Quick and Easy Guide

Are you ready to add a touch of artificial intelligence to your React app? In just five minutes, you can integrate ChatGPT, a powerful language model, and enhance your user interactions. Buckle up, as we guide you through the process with simple steps and code snippets. Step 1 : Get Your OpenAI API Key Before diving in, make sure you have your OpenAI API key ready. If you don’t have one, head over to the OpenAI website, sign up, and grab your API key from the dashboard. Step 2 : Set Up Your React App Assuming you already have a React app up and running, open your project in your favorite code editor. If not, create a new React app using the following commands: npx create-react-app chatgpt-react-app cd chatgpt-react-app Step 3 : Install Axios for API Requests To communicate with the OpenAI API, we’ll need Axios. Install it by running: npm install axios Step 4 : Create a Chat Component In your  src  folder, create a new component, let's call it  Chat.js . This will be the ...

Building Your Own AI Assistant with OpenAI and Node.js: A Comprehensive Guide

 


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:

Setting Up Your Node.js Project:

  1. 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-nodejs

2. Initialize Your Node.js Project:

Run the following command to initialize your Node.js project and create a package.json file

npm init -y

3. Install Necessary Packages:

Install both the openai and readline npm packages

npm install openai readline

Building Your Custom Assistant:

  1. 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 server

Conclusion:

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!

Popular posts from this blog

Will Devin be the Game Changer in Software Programming?

  Devin : AI Software Programmer Introducing Devin, the first AI software engineer Devin, the world’s first fully autonomous AI software engineer. Devin is a tireless, skilled teammate, equally ready to build alongside you or independently complete tasks for you to review. With Devin, engineers can focus on more interesting problems and engineering teams can strive for more ambitious goals. What is Devin Capable of doing? Devin can plan and execute complex engineering tasks requiring thousands of decisions. Devin can recall relevant context at every step, learn over time, and fix mistakes. We’ve also equipped Devin with common developer tools including the shell, code editor, and browser within a sandboxed compute environment — everything a human would need to do their work. Finally, Devin has the ability to actively collaborate with the user. Devin reports on its progress in real time, accepts feedback, and works together with you through design choices as needed. Here’s a sample ...

Building Your Personal Assistant Website with OpenAI, NodeJS, and ReactJS🤖🤖

  In the fast-paced digital era, having a personal assistant to streamline tasks and enhance productivity is a luxury. What if you could create your own personal assistant website tailored to your needs? In this blog, we will guide you through the process of building a personalized virtual assistant using OpenAI, NodeJS, and ReactJS. Step 1: Setting up the Development Environment Before diving into the project, make sure you have Node.js installed on your machine. You can download it from  nodejs.org . Create a new directory for your project and initialize it with the following commands: mkdir personal-assistant cd personal-assistant npm init -y Title: Building Your Personal Assistant Website with OpenAI, NodeJS, and ReactJS In the fast-paced digital era, having a personal assistant to streamline tasks and enhance productivity is a luxury. What if you could create your own personal assistant website tailored to your needs? In this blog, we will guide you through the process ...