diff --git a/src/execution.ts b/src/execution.ts index 3b8e2fd..dada0a4 100644 --- a/src/execution.ts +++ b/src/execution.ts @@ -237,7 +237,7 @@ async function executeFromQueue(channel: string) { return b.createdTimestamp - a.createdTimestamp; }); - OpenAImessages = toOpenAIMessages(messages.values()); + [OpenAImessages] = toOpenAIMessages(messages.values()); let generatedMessage: ChatCompletionMessage | undefined = undefined; let answer: Awaited>; diff --git a/src/toOpenAIMessages.ts b/src/toOpenAIMessages.ts index f93d235..ccb8421 100644 --- a/src/toOpenAIMessages.ts +++ b/src/toOpenAIMessages.ts @@ -95,28 +95,34 @@ function getAuthorUsername(message: DiscordMessage): string | undefined { /** * Converts the Iterable of Discord Messages to array of OpenAI Messages to send * first message in the interable will be the last of the returned array (reverse order) + * (first should be newest) * @param messages the iterable to convert - * @returns the converted messages + * @returns [0] the converted messages + * @returns [1] username mappings to id */ export default function toOpenAIMessages( messages: Iterable, -): OpenAIMessage[] { - const rvalue: OpenAIMessage[] = []; +): [OpenAIMessage[], Map] { + const rmessages: OpenAIMessage[] = []; + const rUserMap = new Map(); let tokenCount = 0; for (const message of messages) { + // FIXME: multiple users could have the same name here. const content = formatMessage(message); // FIXME: tokens are not being counted properly (it's lower than it is) but it's enough for me for now. tokenCount += countTokens(content); if (tokenCount > config.readLimits.tokens) break; - rvalue.push({ + const name = getAuthorUsername(message); + rmessages.push({ role: message.author.id === message.client.user.id ? "assistant" : "user", content: content, - name: getAuthorUsername(message), + name: name, }); + if (name && rUserMap.has(name)) rUserMap.set(name, message.author.id); } - rvalue.push(...config.systemPrompt([...messages][0]).reverse()); + rmessages.push(...config.systemPrompt([...messages][0]).reverse()); - return rvalue.reverse(); + return [rmessages.reverse(), rUserMap]; }