Skip to content

Commit

Permalink
feat: add sliceContent
Browse files Browse the repository at this point in the history
  • Loading branch information
supersonictw committed Jun 16, 2024
1 parent c31ad23 commit b56d120
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
29 changes: 29 additions & 0 deletions src/clients/openai.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,34 @@ async function chatWithAI(chatId, prompt) {
return reply;
}

/**
* Slice the message content into multiple snippets.
* @param {string} content - The content to slice.
* @param {number} maxLength - The maximum length of each snippet.
* @param {string} separator - The separator to split the content.
* @return {Array<string>} The sliced snippets.
*/
function sliceContent(content, maxLength, separator="\n") {
const substrings = content.separator(separator);
const snippets = [];

let lastSnippet = "";
for (const text of substrings) {
if (!text) {
lastSnippet += separator;
continue;
}
if (text.length + lastSnippet.length < maxLength) {
lastSnippet += text;
continue;
}
snippets.push(lastSnippet);
lastSnippet = "";
}

return snippets;
}

exports.useClient = () => client;
exports.chatWithAI = chatWithAI;
exports.sliceContent = sliceContent;
12 changes: 10 additions & 2 deletions src/triggers/discord/message_create/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const discord = require("discord.js");
const discordToMatrix = require("../../../bridges/discord_matrix");

const {useClient} = require("../../../clients/discord");
const {chatWithAI} = require("../../../clients/openai");
const {chatWithAI, sliceContent} = require("../../../clients/openai");

/**
* @param {discord.Message} message
Expand Down Expand Up @@ -47,5 +47,13 @@ module.exports = async (message) => {
return;
}

message.reply(responseContent);
if (responseContent.length < 2000) {
message.reply(responseContent);
} else {
const snippets = sliceContent(responseContent, 2000);
message.reply(snippets.shift());
snippets.forEach((snippet) => {
message.channel.send(snippet);
});
}
};

0 comments on commit b56d120

Please sign in to comment.