I am trying to use Assistants API
I have attached 2 json files
one containing exercises from my database and other containing workouts
im giving it prompt to create new workouts based on my requirements that should match exact data structure but i am getting no responses from API
Attaching errors and code:
**// functions.ts : **
import { OpenAI } from "openai";
import { config } from "dotenv";
import { FileHandler } from "./files_handler.ts";
import { AssistantHandler } from "./assistant_handler.ts";
import { MessageHandler } from "./message_handler.ts";
config();
const openAiKey = process.env.OPENAI_API_KEY;
const openai = new OpenAI({
apiKey: openAiKey,
});
async function main() {
try {
var assistantDetails = await AssistantHandler.getAssistantDetails(openai);
if (assistantDetails === null) {
console.log("Assistant not found");
return;
}
console.log(
"Hello there! I am your workout creator assistant. I will help you create a workout based on your preferences. The instructions you have provided are as follows: n",
assistantDetails.instructions
);
// now we need to upload the files exercises.json and workouts.json if they are not already uploaded
await FileHandler.uploadFiles(openai, assistantDetails);
assistantDetails = await AssistantHandler.getAssistantDetails(openai);
console.log("assistantDetails", assistantDetails);
if (assistantDetails === null) {
return;
}
const fileIds = assistantDetails.vector_store_ids || null;
console.log("fileIds", fileIds);
if (fileIds === null || fileIds.length < 1) {
console.log("No files uploaded");
return;
}
let prompt = "i am Aqib. I want to exercise my chest and biceps.";
console.log("Prompt: ", prompt);
await MessageHandler.sendMessage(openai, assistantDetails, prompt);
} catch (error) {
console.log(error);
}
}
main();
assistant_handler.ts :
import * as fs from "fs";
import { OpenAI } from "openai";
const assistantFilePath = "./assistant.json";
export class AssistantHandler {
static async getAssistantDetails(openai: OpenAI) {
let assistantDetails: {
name: string;
instructions: string;
tools: OpenAI.Beta.Assistants.FileSearchTool[];
model: string;
assistantId: string;
vector_store_ids?: string[];
};
try {
if (fs.existsSync(assistantFilePath)) {
assistantDetails = JSON.parse(
fs.readFileSync(assistantFilePath, "utf-8")
);
// check if assistant is already in openai
try {
const assistantInOpenAI = await openai.beta.assistants.retrieve(
assistantDetails.assistantId
);
if (assistantInOpenAI === null) {
assistantDetails = await AssistantHandler._createAssistant(
openai,
assistantDetails
);
}
} catch (error) {
console.log(
"Assistant not found in openai. Creating a new assistant"
);
assistantDetails = await AssistantHandler._createAssistant(
openai,
assistantDetails
);
}
console.log("Assistant loaded");
} else {
assistantDetails = await AssistantHandler._createAssistant(
openai,
assistantDetails
);
}
return assistantDetails;
} catch (error) {
console.log(error);
return null;
}
}
private static async _createAssistant(
openai: OpenAI,
assistantDetails: {
name: string;
instructions: string;
tools: OpenAI.Beta.Assistants.FileSearchTool[];
model: string;
assistantId: string;
vector_store_ids?: string[];
}
) {
console.log("Assistant not found. Creating a new assistant");
const assistant = await openai.beta.assistants.create({
name: "Workout Creator Assistant",
instructions:
"You are a workout creator assistant. You will be provided some exercises and already made workouts and you will be asked to create a workout for a user based on their preferences like target body parts etc. you have to create the workouts from given exercises and use them and create the workouts in exact same structure as the previous workouts.",
model: "gpt-3.5-turbo",
tools: [{ type: "file_search" }],
});
assistantDetails = {
assistantId: assistant.id,
name: "Workout Creator Assistant",
instructions:
"You are a workout creator assistant. You will be provided some exercises and already made workouts and you will be asked to create a workout for a user based on their preferences like target body parts etc. you have to create the workouts from given exercises and use them and create the workouts in exact same structure as the previous workouts.",
tools: [{ type: "file_search" }],
model: "gpt-3.5-turbo",
};
// Save assistant details to file
fs.writeFileSync(assistantFilePath, JSON.stringify(assistantDetails));
return assistantDetails;
}
}
Files_handler.ts:
import * as fs from "fs";
import { OpenAI } from "openai";
export class FileHandler {
static async uploadFiles(
openai: OpenAI,
assistantDetails: { vector_store_ids?: string[]; assistantId: string }
) {
const files = await openai.files.list();
let existingFiles = assistantDetails.vector_store_ids || [];
console.log("existingFiles", existingFiles);
let exercisesFile = files.data.find(
(file) => file.filename === "exercises.json"
);
let workoutsFile = files.data.find(
(file) => file.filename === "workouts.json"
);
if (
exercisesFile === null ||
workoutsFile === null ||
existingFiles.length < 1 ||
files.data.length < 2
) {
console.log("Uploading files");
await FileHandler._deleteExistingFiles(openai, files);
await FileHandler._uploadFiles(openai, assistantDetails);
} else {
console.log("Files already uploaded");
}
}
private static async _deleteExistingFiles(openai: OpenAI, files: any) {
let fileIds = files.data.map((file) => file.id);
console.log("total files to delete", fileIds.length);
if (fileIds.length > 0) {
for (let fileId of fileIds) {
console.log("deleting file", fileId);
await openai.files.del(fileId);
}
}
console.log("Existing files deleted");
}
private static async _uploadFiles(
openai: OpenAI,
assistantDetails: { vector_store_ids?: string[]; assistantId: string }
) {
const exercisesFilePath = "./exercises.json";
const workoutsFilePath = "./workouts.json";
console.log("Uploading exercises.json and workouts.json");
const fileSteams = [exercisesFilePath, workoutsFilePath].map((filePath) =>
fs.createReadStream(filePath)
);
let vectorStore = await openai.beta.vectorStores.create({
name: "Workout Creator Assistant Files",
});
await openai.beta.vectorStores.fileBatches.uploadAndPoll(vectorStore.id, {
files: fileSteams,
});
assistantDetails.vector_store_ids = [
// ...assistantDetails.vector_store_ids,
vectorStore.id,
];
console.log("assistantDetails updating", assistantDetails);
fs.writeFileSync("./assistant.json", JSON.stringify(assistantDetails));
await openai.beta.assistants.update(assistantDetails.assistantId, {
tool_resources: {
file_search: {
vector_store_ids: [
// ...assistantDetails.vector_store_ids,
vectorStore.id,
],
},
},
});
console.log("Files uploaded successfully, creating thread");
}
}
Messages_handler.ts:
import { OpenAI } from "openai";
import * as fs from "fs";
export class MessageHandler {
static async sendMessage(
openai: OpenAI,
assistantDetails: {
name: string;
instructions: string;
tools: OpenAI.Beta.Assistants.FileSearchTool[];
model: string;
assistantId: string;
vector_store_ids?: string[];
},
prompt: string
) {
console.log("assistantDetails for sending message are ", assistantDetails);
console.log("Prompt for sending message is ", prompt);
const exerciseFile = await openai.files.create({
file: fs.createReadStream("./exercises.json"),
purpose: "assistants",
});
const workoutFile = await openai.files.create({
file: fs.createReadStream("./workouts.json"),
purpose: "assistants",
});
const thread = await openai.beta.threads.create({
messages: [
{
role: "user",
content: prompt,
// Attach the new file to the message.
attachments: [
{ file_id: exerciseFile.id, tools: [{ type: "file_search" }] },
{ file_id: workoutFile.id, tools: [{ type: "file_search" }] },
],
},
],
});
console.log(
"Message sent to assistant. Waiting for response, thread id is ",
thread.id
);
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistantDetails.assistantId,
});
console.log(
"Assistant is running. Please wait for the response, run id is ",
run.id
);
const messages = await openai.beta.threads.messages.list(thread.id, {
run_id: run.id,
});
// delay of 5 seconds to wait for the assistant to respond
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log("messages data: ", messages);
const message = messages.data.pop()!;
console.log("Assistant response: ", message);
}
}
The Error: ( response im getting )
Assistant loaded
Hello there! I am your workout creator assistant. I will help you create a workout based on your preferences. The instructions you have provided are as follows:
You are a workout creator assistant. You will be provided some exercises and already made workouts and you will be asked to create a workout for a user based on their preferences like target body parts etc. you have to create the workouts from given exercises and use them and create the workouts in exact same structure as the previous workouts.
existingFiles [ 'vs_2fmyDakwxDeJHVX5L17aWHes' ]
Files already uploaded
Assistant loaded
assistantDetails {
assistantId: 'asst_KdlpJ5vmqaXKv2nqChl1XYOU',
name: 'Workout Creator Assistant',
instructions: 'You are a workout creator assistant. You will be provided some exercises and already made workouts and you will be asked to create a workout for a user based on their preferences like target body parts etc. you have to create the workouts from given exercises and use them and create the workouts in exact same structure as the previous workouts.',
tools: [ { type: 'file_search' } ],
model: 'gpt-3.5-turbo',
vector_store_ids: [ 'vs_2fmyDakwxDeJHVX5L17aWHes' ]
}
fileIds [ 'vs_2fmyDakwxDeJHVX5L17aWHes' ]
Prompt: i am Aqib. I want to exercise my chest and biceps.
assistantDetails for sending message are {
assistantId: 'asst_KdlpJ5vmqaXKv2nqChl1XYOU',
name: 'Workout Creator Assistant',
instructions: 'You are a workout creator assistant. You will be provided some exercises and already made workouts and you will be asked to create a workout for a user based on their preferences like target body parts etc. you have to create the workouts from given exercises and use them and create the workouts in exact same structure as the previous workouts.',
tools: [ { type: 'file_search' } ],
model: 'gpt-3.5-turbo',
vector_store_ids: [ 'vs_2fmyDakwxDeJHVX5L17aWHes' ]
}
Prompt for sending message is i am Aqib. I want to exercise my chest and biceps.
Message sent to assistant. Waiting for response, thread id is thread_9ABjEwWgHs7NexCxHwKwupks
Assistant is running. Please wait for the response, run id is run_F1OPMTOrbdG7iCx0nbkm2VGA
messages data: MessagesPage {
options: {
method: 'get',
path: '/threads/thread_9ABjEwWgHs7NexCxHwKwupks/messages',
query: { run_id: 'run_F1OPMTOrbdG7iCx0nbkm2VGA' },
headers: { 'OpenAI-Beta': 'assistants=v2' }
},
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [Gunzip], disturbed: true, error: null },
[Symbol(Response internals)]: {
url: 'https://api.openai.com/v1/threads/thread_9ABjEwWgHs7NexCxHwKwupks/messages?run_id=run_F1OPMTOrbdG7iCx0nbkm2VGA',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
},
body: {
object: 'list',
data: [],
first_id: null,
last_id: null,
has_more: false
},
data: []
}
Assistant response: undefined
I am expecting the API to return something to me ( exercises or workouts based on my requirements)