Updated dir structure to put the actual source code in the general /src dir
Some checks failed
Update Wiki from JSDoc / update-wiki (pull_request) Has been cancelled
Lint JavaScript/Node.js / lint-js (pull_request) Failing after 11s
DRB Tests / drb_mocha_tests (pull_request) Has been cancelled

This commit is contained in:
Logan Cusano
2024-08-17 18:44:18 -04:00
parent 8f2891f5d8
commit 066404dd10
44 changed files with 2493 additions and 1678 deletions

View File

@@ -0,0 +1,254 @@
import { DebugBuilder } from "../../modules/debugger.mjs";
import { requestNodeJoinSystem } from "../../modules/socketServerWrappers.mjs";
import { getSystemByName } from "../../modules/mongo-wrappers/mongoSystemsWrappers.mjs";
import { getConfig } from "../../modules/mongo-wrappers/mongoConfigWrappers.mjs";
import { getAvailableTokensInGuild } from "../modules/wrappers.mjs";
import dotenv from "dotenv";
import { OpenAI } from "openai";
import { EventEmitter } from "events";
// Initialize environment variables
dotenv.config();
const log = new DebugBuilder("server", "discordBot.modules.gptHandler");
let assistant;
let eventHandler;
(async () => {
try {
const openai = new OpenAI(process.env.OPENAI_API_KEY);
assistant = await openai.beta.assistants.create({
name: "Emmelia",
instructions: (await getConfig("emmeliaInitialPrompt")) || "",
model: "gpt-4o-mini",
tools: [
{
type: "function",
function: {
name: "checkUserVoiceChannel",
description: "Check if the user is in a voice channel",
parameters: {
type: "object",
properties: {
userId: {
type: "string",
description: "The ID of the user",
},
guildId: {
type: "string",
description: "The ID of the guild",
},
},
required: ["userId", "guildId"],
},
},
},
{
type: "function",
function: {
name: "getSelectedSystem",
description: "Retrieve the selected system details",
parameters: {
type: "object",
properties: {
systemName: {
type: "string",
description: "The name of the system",
},
},
required: ["systemName"],
},
},
},
{
type: "function",
function: {
name: "joinSelectedSystem",
description: "Join the selected system in the user's voice channel",
parameters: {
type: "object",
properties: {
userId: {
type: "string",
description: "The ID of the user",
},
guildId: {
type: "string",
description: "The ID of the guild",
},
systemName: {
type: "string",
description: "The name of the system",
},
channelId: {
type: "string",
description: "The ID of the voice channel",
},
},
required: ["userId", "guildId", "systemName", "channelId"],
},
},
},
],
});
class EventHandler extends EventEmitter {
constructor(client) {
super();
this.client = client;
}
async onEvent(event) {
try {
console.log(event);
if (event.event === "thread.run.requires_action") {
await this.handleRequiresAction(
event.data,
event.data.id,
event.data.thread_id,
);
}
} catch (error) {
console.error("Error handling event:", error);
}
}
async handleRequiresAction(data, runId, threadId) {
try {
const toolOutputs = await Promise.all(
data.required_action.submit_tool_outputs.tool_calls.map(
async (toolCall) => {
switch (toolCall.function.name) {
case "checkUserVoiceChannel":
return await this.checkUserVoiceChannel(toolCall);
case "getSelectedSystem":
return await this.getSelectedSystem(toolCall);
case "joinSelectedSystem":
return await this.joinSelectedSystem(toolCall);
default:
throw new Error(
`Unknown function: ${toolCall.function.name}`,
);
}
},
),
);
await this.submitToolOutputs(toolOutputs, runId, threadId);
} catch (error) {
console.error("Error processing required action:", error);
}
}
async checkUserVoiceChannel(toolCall) {
const { userId, guildId } = JSON.parse(toolCall.function.arguments);
const guild = await this.client.guilds.get(guildId);
const member = await guild.members.get(userId);
const isInVoiceChannel = !!member.voice.channel;
return {
tool_call_id: toolCall.id,
output: JSON.stringify({
isInVoiceChannel,
channelId: member.voice.channelId,
}),
};
}
async getSelectedSystem(toolCall) {
const { systemName } = JSON.parse(toolCall.function.arguments);
const system = await getSystemByName(systemName);
return {
tool_call_id: toolCall.id,
output: JSON.stringify(system),
};
}
async joinSelectedSystem(toolCall) {
const { userId, guildId, systemName, channelId } = JSON.parse(
toolCall.function.arguments,
);
const system = await getSystemByName(systemName);
const guild = await this.client.guilds.fetch(guildId);
const discordToken = await getAvailableTokensInGuild(guildId);
if (discordToken) {
const result = await requestNodeJoinSystem(
system,
channelId,
discordToken,
);
return {
tool_call_id: toolCall.id,
output: JSON.stringify({ success: true, result }),
};
} else {
return {
tool_call_id: toolCall.id,
output: JSON.stringify({
success: false,
message: "No available bots.",
}),
};
}
}
async submitToolOutputs(toolOutputs, runId, threadId) {
try {
const stream =
this.client.beta.threads.runs.submitToolOutputsStream(
threadId,
runId,
{ tool_outputs: toolOutputs },
);
for await (const event of stream) {
this.emit("event", event);
}
} catch (error) {
console.error("Error submitting tool outputs:", error);
}
}
}
eventHandler = new EventHandler(openai);
eventHandler.on("event", eventHandler.onEvent.bind(eventHandler));
} catch (error) {
console.error("Initialization error:", error);
}
})();
export const gptHandler = async (additionalMessages) => {
try {
const thread = await openai.beta.threads.create();
for (const msgObj of additionalMessages) {
await openai.beta.threads.messages.create(thread.id, msgObj);
}
const stream = await openai.beta.threads.runs.stream(
thread.id,
{ assistant_id: assistant.id },
eventHandler,
);
for await (const event of stream) {
eventHandler.emit("event", event);
}
const messages = await openai.beta.threads.messages.list(thread.id);
const response = messages.data[0].content[0].text.value;
log.DEBUG("AI Response:", response);
if (!response) {
return false;
}
return response;
} catch (error) {
console.error("Error generating response:", error);
return false;
}
};