Exclude bot prompts from default history retrieval
This commit is contained in:
parent
37765ce246
commit
0ce27b933f
23 changed files with 683 additions and 247 deletions
|
|
@ -279,6 +279,7 @@ export async function handlePrompt(options: PromptHandlerOptions): Promise<void>
|
|||
query: options.prompt,
|
||||
limit: initialRetrievalLimit,
|
||||
guildId: options.guildContext.guildId,
|
||||
preserveOverfetch: true,
|
||||
}),
|
||||
options.prompt,
|
||||
).slice(0, initialRetrievalLimit)
|
||||
|
|
@ -492,10 +493,15 @@ export async function handleRejectJob(options: {
|
|||
export async function handleSearchHistory(
|
||||
interaction: ChatInputCommandInteraction<CacheType>,
|
||||
retrievalService: RetrievalService,
|
||||
archiveRepository: FileMessageArchiveRepository,
|
||||
systemMessages: SystemMessageCatalog,
|
||||
): Promise<void> {
|
||||
const query = interaction.options.getString("query", true);
|
||||
const results = await retrievalService.searchHistory(query, 5, {
|
||||
const results = await searchHistoryWithArchiveFallback({
|
||||
retrievalService,
|
||||
archiveRepository,
|
||||
query,
|
||||
limit: 5,
|
||||
guildId: interaction.guildId ?? undefined,
|
||||
});
|
||||
|
||||
|
|
@ -603,6 +609,8 @@ export async function handleReindexChannel(
|
|||
channelIndexing: AppConfig["channelIndexing"],
|
||||
permissionEngine: PermissionEngine,
|
||||
ragPipeline: RagPipeline,
|
||||
botUserId: string | undefined,
|
||||
botRoleIds: string[],
|
||||
systemMessages: SystemMessageCatalog,
|
||||
): Promise<void> {
|
||||
if (!permissionEngine.canReindex(actor)) {
|
||||
|
|
@ -632,7 +640,9 @@ export async function handleReindexChannel(
|
|||
}
|
||||
|
||||
const fetched = await interaction.channel.messages.fetch({ limit: 100 });
|
||||
const archivedMessages = [...fetched.values()].map(convertDiscordMessageToArchive);
|
||||
const archivedMessages = [...fetched.values()].map((message) =>
|
||||
convertDiscordMessageToArchive(message, { botUserId, botRoleIds }),
|
||||
);
|
||||
const result = await ragPipeline.upsertMessages(archivedMessages);
|
||||
|
||||
await replyEphemeral(
|
||||
|
|
|
|||
|
|
@ -17,11 +17,11 @@ import {
|
|||
import type { ProviderRegistry } from "@voidbot/providers";
|
||||
import {
|
||||
RagPipeline,
|
||||
FileMessageArchiveRepository,
|
||||
RetrievalService,
|
||||
type ArchivedMessageRecord,
|
||||
} from "@voidbot/rag";
|
||||
import {
|
||||
setArchivedMessageKind,
|
||||
type Actor,
|
||||
type ArchivedMessage,
|
||||
type ChannelIndexingPolicy,
|
||||
|
|
@ -35,6 +35,11 @@ import {
|
|||
shouldIndexChannel,
|
||||
} from "@voidbot/shared";
|
||||
|
||||
export {
|
||||
filterPromptEchoHistoryResults,
|
||||
searchHistoryWithArchiveFallback,
|
||||
} from "@voidbot/rag";
|
||||
|
||||
export function buildActorFromMessage(message: Message): Actor {
|
||||
return {
|
||||
id: message.author.id,
|
||||
|
|
@ -110,12 +115,16 @@ export async function ingestIfIndexed(
|
|||
message: Message,
|
||||
channelIndexing: ChannelIndexingPolicy,
|
||||
ragPipeline: RagPipeline,
|
||||
botUserId?: string,
|
||||
botRoleIds: string[] = [],
|
||||
): Promise<void> {
|
||||
if (!shouldIndexChannel(channelIndexing, buildChannelIndexingTarget(message.channel))) {
|
||||
return;
|
||||
}
|
||||
|
||||
await ragPipeline.upsertMessages([convertDiscordMessageToArchive(message)]);
|
||||
await ragPipeline.upsertMessages([
|
||||
convertDiscordMessageToArchive(message, { botUserId, botRoleIds }),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function rememberAmbientVoidReference(
|
||||
|
|
@ -161,7 +170,13 @@ export function buildChannelIndexingTarget(
|
|||
return target;
|
||||
}
|
||||
|
||||
export function convertDiscordMessageToArchive(message: Message): ArchivedMessage {
|
||||
export function convertDiscordMessageToArchive(
|
||||
message: Message,
|
||||
options?: {
|
||||
botUserId?: string;
|
||||
botRoleIds?: string[];
|
||||
},
|
||||
): ArchivedMessage {
|
||||
const metadata: Record<string, string> = {
|
||||
jumpUrl: message.url,
|
||||
};
|
||||
|
|
@ -196,7 +211,16 @@ export function convertDiscordMessageToArchive(message: Message): ArchivedMessag
|
|||
(attachment) => attachment.url ?? attachment.proxyURL ?? attachment.name,
|
||||
)
|
||||
: undefined,
|
||||
metadata,
|
||||
metadata: setArchivedMessageKind(
|
||||
metadata,
|
||||
isBotDirectedPromptMessage(
|
||||
message,
|
||||
options?.botUserId,
|
||||
options?.botRoleIds ?? [],
|
||||
)
|
||||
? "bot_prompt"
|
||||
: "default",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -339,51 +363,6 @@ export function renderRateLimitMessage(
|
|||
});
|
||||
}
|
||||
|
||||
export async function searchHistoryWithArchiveFallback(options: {
|
||||
retrievalService: RetrievalService;
|
||||
archiveRepository: FileMessageArchiveRepository;
|
||||
query: string;
|
||||
limit: number;
|
||||
guildId?: string;
|
||||
channelId?: string;
|
||||
authorId?: string;
|
||||
}): Promise<RetrievalResult[]> {
|
||||
const overfetchLimit = Math.max(options.limit * 3, options.limit + 4);
|
||||
const vectorResults = await options.retrievalService.searchHistory(options.query, overfetchLimit, {
|
||||
guildId: options.guildId,
|
||||
channelId: options.channelId,
|
||||
authorId: options.authorId,
|
||||
});
|
||||
|
||||
const lexicalResults = await options.archiveRepository.searchLexical(options.query, overfetchLimit, {
|
||||
guildId: options.guildId,
|
||||
channelId: options.channelId,
|
||||
authorId: options.authorId,
|
||||
});
|
||||
|
||||
if (lexicalResults.length === 0) {
|
||||
return vectorResults;
|
||||
}
|
||||
|
||||
const merged = [...vectorResults];
|
||||
const seenSourceIds = new Set(merged.map((result) => result.sourceId));
|
||||
|
||||
for (const result of lexicalResults) {
|
||||
if (seenSourceIds.has(result.sourceId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
merged.push(result);
|
||||
seenSourceIds.add(result.sourceId);
|
||||
|
||||
if (merged.length >= overfetchLimit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function formatHistoryResults(
|
||||
results: Awaited<ReturnType<RetrievalService["searchHistory"]>>,
|
||||
): Array<Record<string, unknown>> {
|
||||
|
|
@ -420,96 +399,6 @@ export function formatSourceResults(
|
|||
}));
|
||||
}
|
||||
|
||||
export function filterPromptEchoHistoryResults<
|
||||
T extends {
|
||||
text: string;
|
||||
},
|
||||
>(results: T[], query: string): T[] {
|
||||
const normalizedQuery = normalizeHistoryEchoText(query);
|
||||
const queryTokens = buildHistoryEchoTokens(normalizedQuery);
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const filtered = results.filter((result) => {
|
||||
const normalizedResult = normalizeHistoryEchoText(result.text);
|
||||
|
||||
if (normalizedResult.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalizedResult === normalizedQuery) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryTokens.length >= 4) {
|
||||
const resultTokens = buildHistoryEchoTokens(normalizedResult);
|
||||
const sharedTokenCount = countSharedTokens(queryTokens, resultTokens);
|
||||
const similarity = sharedTokenCount / Math.max(Math.min(queryTokens.length, resultTokens.length), 1);
|
||||
|
||||
if (similarity >= 0.7) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedQuery.length >= 48 &&
|
||||
(normalizedResult.includes(normalizedQuery) || normalizedQuery.includes(normalizedResult))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return filtered.length > 0 ? filtered : results;
|
||||
}
|
||||
|
||||
function normalizeHistoryEchoText(value: string): string {
|
||||
return value
|
||||
.replace(/<@!?\d+>/g, " ")
|
||||
.replace(/<@&\d+>/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function buildHistoryEchoTokens(value: string): string[] {
|
||||
return [...new Set(
|
||||
value
|
||||
.split(/[^\p{L}\p{N}]+/u)
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length >= 4)
|
||||
.filter((token) => !HISTORY_ECHO_STOP_WORDS.has(token)),
|
||||
)];
|
||||
}
|
||||
|
||||
function countSharedTokens(left: string[], right: string[]): number {
|
||||
const rightSet = new Set(right);
|
||||
return left.reduce((count, token) => count + (rightSet.has(token) ? 1 : 0), 0);
|
||||
}
|
||||
|
||||
const HISTORY_ECHO_STOP_WORDS = new Set([
|
||||
"about",
|
||||
"after",
|
||||
"before",
|
||||
"could",
|
||||
"from",
|
||||
"have",
|
||||
"please",
|
||||
"pretty",
|
||||
"tell",
|
||||
"that",
|
||||
"them",
|
||||
"they",
|
||||
"this",
|
||||
"what",
|
||||
"with",
|
||||
"would",
|
||||
"your",
|
||||
]);
|
||||
|
||||
export function formatArchivedMessageContext(
|
||||
message: ArchivedMessageRecord,
|
||||
anchorMessageId: string,
|
||||
|
|
@ -972,3 +861,19 @@ function isAmbientVoidReference(
|
|||
|
||||
return true;
|
||||
}
|
||||
|
||||
function isBotDirectedPromptMessage(
|
||||
message: Message,
|
||||
botUserId: string | undefined,
|
||||
botRoleIds: string[],
|
||||
): boolean {
|
||||
if (!message.inGuild()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (botUserId && message.mentions.has(botUserId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return botRoleIds.some((roleId) => message.mentions.roles.has(roleId));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ import {
|
|||
buildChannelIndexingTarget,
|
||||
buildGuildContextFromInteraction,
|
||||
buildGuildContextFromMessage,
|
||||
filterPromptEchoHistoryResults,
|
||||
formatArchivedMessageContext,
|
||||
formatHistoryResults,
|
||||
formatProviderStatuses,
|
||||
|
|
@ -69,50 +70,6 @@ import {
|
|||
stripBotMention,
|
||||
} from "./discord-bot-support";
|
||||
|
||||
function filterPromptEchoHistoryResults<
|
||||
T extends {
|
||||
text: string;
|
||||
},
|
||||
>(results: T[], query: string): T[] {
|
||||
const normalizedQuery = normalizeHistoryEchoText(query);
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const filtered = results.filter((result) => {
|
||||
const normalizedResult = normalizeHistoryEchoText(result.text);
|
||||
|
||||
if (normalizedResult.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalizedResult === normalizedQuery) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedQuery.length >= 48 &&
|
||||
(normalizedResult.includes(normalizedQuery) || normalizedQuery.includes(normalizedResult))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return filtered.length > 0 ? filtered : results;
|
||||
}
|
||||
|
||||
function normalizeHistoryEchoText(value: string): string {
|
||||
return value
|
||||
.replace(/<@!?\d+>/g, " ")
|
||||
.replace(/<@&\d+>/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export async function startBot(): Promise<void> {
|
||||
const config = loadConfig();
|
||||
|
||||
|
|
@ -244,6 +201,7 @@ export async function startBot(): Promise<void> {
|
|||
guildId: input.guildId,
|
||||
channelId: input.channelId,
|
||||
authorId: input.authorId,
|
||||
preserveOverfetch: true,
|
||||
});
|
||||
const results = filterPromptEchoHistoryResults(rawResults, input.query).slice(0, input.limit);
|
||||
|
||||
|
|
@ -333,7 +291,13 @@ export async function startBot(): Promise<void> {
|
|||
|
||||
const isDirectMessage = !message.inGuild();
|
||||
|
||||
await ingestIfIndexed(message, config.channelIndexing, ragPipeline);
|
||||
await ingestIfIndexed(
|
||||
message,
|
||||
config.channelIndexing,
|
||||
ragPipeline,
|
||||
client.user?.id,
|
||||
config.botTriggerRoleIds,
|
||||
);
|
||||
await rememberAmbientVoidReference(message, client.user?.id, interactionMemory);
|
||||
|
||||
if (!client.user || (!isDirectMessage && !message.mentions.has(client.user))) {
|
||||
|
|
@ -403,7 +367,13 @@ export async function startBot(): Promise<void> {
|
|||
return;
|
||||
}
|
||||
|
||||
await ingestIfIndexed(materializedMessage, config.channelIndexing, ragPipeline);
|
||||
await ingestIfIndexed(
|
||||
materializedMessage,
|
||||
config.channelIndexing,
|
||||
ragPipeline,
|
||||
client.user?.id,
|
||||
config.botTriggerRoleIds,
|
||||
);
|
||||
await rememberAmbientVoidReference(
|
||||
materializedMessage,
|
||||
client.user?.id,
|
||||
|
|
@ -535,7 +505,12 @@ export async function startBot(): Promise<void> {
|
|||
});
|
||||
break;
|
||||
case "search-history":
|
||||
await handleSearchHistory(interaction, retrievalService, activeSystemMessages);
|
||||
await handleSearchHistory(
|
||||
interaction,
|
||||
retrievalService,
|
||||
archiveRepository,
|
||||
activeSystemMessages,
|
||||
);
|
||||
break;
|
||||
case "summarize-channel":
|
||||
await handleSummarizeChannel(interaction, activeSystemMessages);
|
||||
|
|
@ -547,6 +522,8 @@ export async function startBot(): Promise<void> {
|
|||
config.channelIndexing,
|
||||
permissionEngine,
|
||||
ragPipeline,
|
||||
client.user?.id,
|
||||
config.botTriggerRoleIds,
|
||||
activeSystemMessages,
|
||||
);
|
||||
break;
|
||||
|
|
|
|||
Loading…
Reference in a new issue