Skip to content

Commit

Permalink
code cleanup and fix eslint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Steve-KX-RL committed Apr 11, 2024
1 parent 5c785ac commit 785f9b7
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 121 deletions.
6 changes: 0 additions & 6 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,3 @@ module.exports.beatPort = argv.udpPort || 52316;
module.exports.persistToCloud = false;

module.exports.allowSecureMode = argv.secure || process.env.ALLOW_SECURE_MODE === 'true';

// Azure OpenAI API configs
// const endpoint = '';
// const azureApiKey = '';
// module.exports.endpoint = endpoint;
// module.exports.azureApiKey = azureApiKey;
222 changes: 107 additions & 115 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -1951,24 +1951,6 @@ function objectWebServer() {
webServer.get('/status', function(req, res) {
res.sendStatus(200); // OK
});

function parseCategory_old(result) {
let category = parseInt(result);
if (!isNaN(category) && typeof category === 'number') return category;

let match = result.match(/\d+/); // \d+ matches a sequence of digits
if (match) {
let result = parseInt(match[0], 10); // Convert the string to an integer, using base-10
if (result < 1 || result > 6) {
console.error('Error in AI classifying category: no such category.');
return 6;
} else {
return result;
}
} else {
return 6; // default return the 6th category --- other
}
}

function parseCategory(result) {
console.log('result in parseCategory(): ' + result);
Expand All @@ -1989,26 +1971,24 @@ function objectWebServer() {
}
}

const { ChatCompletionsJsonResponseFormat, OpenAIClient, AzureKeyCredential } = require("@azure/openai");
// const { endpoint, azureApiKey } = require("./config.js");
// const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
let client = null;
const deploymentId = "gpt-35-turbo-16k";

webServer.post('/ai-start', async function(req, res) {
if (client !== null) {
let json = JSON.stringify({answer: 'success'})
let json = JSON.stringify({answer: 'success'});
res.status(200).send(json);
return;
}
let endpoint = req.body.endpoint;
let azureApiKey = req.body.azureApiKey;
client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
let json = JSON.stringify({answer: 'success'})

let json = JSON.stringify({answer: 'success'});
res.status(200).send(json);
})
});

webServer.post('/ai', async function(req, res) {
let conversation = req.body.conversation;
let conversation_length = Object.keys(conversation).length;
Expand All @@ -2020,7 +2000,7 @@ function objectWebServer() {
let chatAll = last_dialogue.communicationToolInfo.chatAll;
delete last_dialogue.communicationToolInfo;


const category_messages = [
{ role: "system", content: "You are a helpful assistant." },
...Object.values(conversation)
Expand All @@ -2029,101 +2009,113 @@ function objectWebServer() {
{ role: "system", content: "You are a helpful assistant." },
...Object.values(conversation)
];


let result = await client.getChatCompletions(deploymentId, category_messages);
let actualResult = result.choices[0].message.content;
let actualCategory = parseCategory(actualResult);
let json = null;


switch (actualCategory) {
case 6:
last_dialogue.content = last_dialogue_original_content;

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
json = JSON.stringify({category: `${actualCategory}`, answer: `${actualResult}`});
res.status(200).send(json);
break;
case 1:
last_dialogue.content = last_dialogue_original_content;

let toolRegex = new RegExp("\\b[a-zA-Z0-9]{6}\\b", 'g');
let avatarRegex = new RegExp("\\b[a-zA-Z0-9]{6}\\b", 'g');
// todo Steve: use regex to regulate the prompt
// Don't change the names starting with '_WORLD_' or '_AVATAR_' in your response
// Don't change the names with the regular expression ${}, ${}

let enhancedPrompt = [
...messages,
{ role: "user", content: `Here's a log of events. In your response, give me a detailed report in three paragraphs at most. In the report, don't change the IDs satisfying the regular expressions ${toolRegex} and ${avatarRegex}. These IDs are linked to real objects and therefore you must keep these UUIDs unchanged.` },
// { role: "user", content: `Here's a log of events. In your response, give me a detailed report in three paragraphs at most. In the report, don't change the IDs satisfying the regular expressions ${toolRegex} and ${avatarRegex}. Always respond with the Name and ID pair in the format Name:ID. It is paramount that you do not change the ID's as they are needed to identify the names.` },
]
result = await client.getChatCompletions(deploymentId, enhancedPrompt);
actualResult = result.choices[0].message.content;

// todo Steve: if there is communication info, then let ai make a summary of the chat history, and populate it to the actualResult
actualResult += '\n\n';
for (let i = 1; i <= authorAll.length; i++) {
let chatQuestion = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: `${chatAll[i - 1]} Give me a summary of this conversation. Use at most 3 sentences.` },
];
let chatSummaryResult = await client.getChatCompletions(deploymentId, chatQuestion);
let chatSummary = chatSummaryResult.choices[0].message.content;
let idx = '';
if (i === 1) {
idx = '1st';
} else if (i === 2) {
idx = '2nd';
} else if (i === 3) {
idx = '3rd';
} else {
idx = `${i}th`;
}
actualResult += `In the ${idx} communication tool chat history, ${authorAll[i - 1]} discussed about: ${chatSummary}`;
actualResult += '\n\n';
}

json = JSON.stringify({category: `${actualCategory}`, answer: `${actualResult}`});
res.status(200).send(json);
break;
case 2:
case 4:
last_dialogue.content = last_dialogue_original_content;

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
json = JSON.stringify({category: `${actualCategory}`, answer: `${actualResult}. Need to further refer to files in the database.`});
res.status(200).send(json);
break;
case 3:
case 5:
last_dialogue.content = last_dialogue_original_content + 'What tools are mentioned? You answer can only include the following words, separated by newline character: "spatialDraw", "communication", "spatialVideo", "spatialAnalytics", "spatialMeasure", "onshapeTool". ';

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
let toolList = ["spatialDraw", "communication", "spatialVideo", "spatialAnalytics", "spatialMeasure", "onshapeTool"]; // todo Steve: to make it more generalized, add support to ignore upper/lower letters & correct spelling
let resultList = [];
for (let toolName of toolList) {
if (actualResult.includes(toolName)) resultList.push(toolName);
case 6: {
last_dialogue.content = last_dialogue_original_content;

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
json = JSON.stringify({category: `${actualCategory}`, answer: `${actualResult}`});
res.status(200).send(json);
break;
}
case 1: {
last_dialogue.content = last_dialogue_original_content;

let toolRegex = new RegExp("\\b[a-zA-Z0-9]{6}\\b", 'g');
let avatarRegex = new RegExp("\\b[a-zA-Z0-9]{6}\\b", 'g');
// todo Steve: use regex to regulate the prompt
// Don't change the names starting with '_WORLD_' or '_AVATAR_' in your response
// Don't change the names with the regular expression ${}, ${}

let enhancedPrompt = [...messages, {
role: "user",
content: `Here's a log of events. In your response, give me a detailed report in three paragraphs at most. In the report, don't change the IDs satisfying the regular expressions ${toolRegex} and ${avatarRegex}. These IDs are linked to real objects and therefore you must keep these UUIDs unchanged.`
}];
// { role: "user", content: `Here's a log of events. In your response, give me a detailed report in three paragraphs at most. In the report, don't change the IDs satisfying the regular expressions ${toolRegex} and ${avatarRegex}. Always respond with the Name and ID pair in the format Name:ID. It is paramount that you do not change the ID's as they are needed to identify the names.` }
result = await client.getChatCompletions(deploymentId, enhancedPrompt);
actualResult = result.choices[0].message.content;

// todo Steve: if there is communication info, then let ai make a summary of the chat history, and populate it to the actualResult
actualResult += '\n\n';
for (let i = 1; i <= authorAll.length; i++) {
let chatQuestion = [
{role: "system", content: "You are a helpful assistant."},
{
role: "user",
content: `${chatAll[i - 1]} Give me a summary of this conversation. Use at most 3 sentences.`
},
];
let chatSummaryResult = await client.getChatCompletions(deploymentId, chatQuestion);
let chatSummary = chatSummaryResult.choices[0].message.content;
let idx = '';
if (i === 1) {
idx = '1st';
} else if (i === 2) {
idx = '2nd';
} else if (i === 3) {
idx = '3rd';
} else {
idx = `${i}th`;
}
let resultTools = '';
for (let i = 0; i < resultList.length; i++) {
if (i === resultList.length - 1) {
resultTools += `${resultList[i]}`;
continue;
}
resultTools += `${resultList[i]}\n`;
actualResult += `In the ${idx} communication tool chat history, ${authorAll[i - 1]} discussed about: ${chatSummary}`;
actualResult += '\n\n';
}

json = JSON.stringify({category: `${actualCategory}`, answer: `${actualResult}`});
res.status(200).send(json);
break;
}
case 2:
case 4: {
last_dialogue.content = last_dialogue_original_content;

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
json = JSON.stringify({
category: `${actualCategory}`,
answer: `${actualResult}. Need to further refer to files in the database.`
});
res.status(200).send(json);
break;
}
case 3:
case 5: {
last_dialogue.content = last_dialogue_original_content + 'What tools are mentioned? You answer can only include the following words, separated by newline character: "spatialDraw", "communication", "spatialVideo", "spatialAnalytics", "spatialMeasure", "onshapeTool". ';

result = await client.getChatCompletions(deploymentId, messages);
actualResult = result.choices[0].message.content;
// todo Steve: to make it more generalized, add support to ignore upper/lower letters & correct spelling
let toolList = ["spatialDraw", "communication", "spatialVideo", "spatialAnalytics", "spatialMeasure", "onshapeTool"];
let resultList = [];
for (let toolName of toolList) {
if (actualResult.includes(toolName)) resultList.push(toolName);
}
let resultTools = '';
for (let i = 0; i < resultList.length; i++) {
if (i === resultList.length - 1) {
resultTools += `${resultList[i]}`;
continue;
}
json = JSON.stringify({category: `${actualCategory}`, tools: `${resultTools}`});
res.status(200).send(json);
break;
default:
break;
resultTools += `${resultList[i]}\n`;
}
json = JSON.stringify({category: `${actualCategory}`, tools: `${resultTools}`});
res.status(200).send(json);
break;
}
default: {
break;
}
})
}
});

// receivePost blocks can be triggered with a post request. *1 is the object *2 is the logic *3 is the link id
// abbreviated POST syntax, searches over all objects and frames to find the block with that ID
Expand Down

0 comments on commit 785f9b7

Please sign in to comment.