Exclude bot prompts from default history retrieval

This commit is contained in:
Meta Vens 2026-05-04 09:54:27 +01:00
commit 0ce27b933f
23 changed files with 683 additions and 247 deletions

View file

@ -42,6 +42,7 @@ const envSchema = z.object({
DISCORD_APPLICATION_ID: optionalNonEmptyString,
DISCORD_GUILD_ID: optionalNonEmptyString,
DISCORD_OWNER_ID: z.string().min(1, "DISCORD_OWNER_ID is required"),
DISCORD_BOT_TRIGGER_ROLE_IDS: z.string().default(""),
STATE_STORAGE_BACKEND: z.enum(["file", "postgres"]).default("postgres"),
DATABASE_DSN: z.string().min(1).default("postgres://voidbot:voidbot@localhost:5432/voidbot"),
VECTOR_STORE_KIND: z.enum(["local_json", "qdrant"]).default("local_json"),
@ -112,6 +113,7 @@ export interface AppConfig {
applicationId?: string;
developmentGuildId?: string;
ownerDiscordId: string;
botTriggerRoleIds: string[];
stateStorageBackend: "file" | "postgres";
databaseDsn: string;
enabledProviders: ProviderName[];
@ -283,6 +285,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
applicationId: parsed.DISCORD_APPLICATION_ID,
developmentGuildId: parsed.DISCORD_GUILD_ID,
ownerDiscordId: parsed.DISCORD_OWNER_ID,
botTriggerRoleIds: parseList(parsed.DISCORD_BOT_TRIGGER_ROLE_IDS),
stateStorageBackend: parsed.STATE_STORAGE_BACKEND,
databaseDsn: parsed.DATABASE_DSN,
enabledProviders: parseProviders(parsed.ENABLED_PROVIDERS),

View file

@ -250,6 +250,7 @@ function normalizeArchivedMessage(
readString(candidate, ["parentChannel", "name"]) ??
readString(candidate, ["parent", "name"]);
const metadata: Record<string, string> = {
...readStringRecord(candidate.metadata),
sourceFile: basename(sourceFile),
};
@ -338,6 +339,22 @@ function normalizeTimestamp(value: string): string {
return Number.isNaN(parsed.getTime()) ? value : parsed.toISOString();
}
function readStringRecord(value: unknown): Record<string, string> {
if (!isRecord(value)) {
return {};
}
const normalized: Record<string, string> = {};
for (const [key, entry] of Object.entries(value)) {
if (typeof entry === "string") {
normalized[key] = entry;
}
}
return normalized;
}
function readString(source: Record<string, unknown>, path: string[]): string | undefined {
let cursor: unknown = source;

View file

@ -2,6 +2,8 @@ import {
type ArchivedMessage,
type EmbeddingChunk,
type VectorStore,
readArchivedMessageKind,
isArchivedBotPrompt,
} from "@voidbot/shared";
const DEFAULT_CHUNK_SIZE = 420;
@ -23,6 +25,10 @@ export class HistoryIngester {
}
public chunkMessage(message: ArchivedMessage): EmbeddingChunk[] {
if (isArchivedBotPrompt(message)) {
return [];
}
const segments = splitText(message.content, this.chunkSize);
return segments.map((segment, index) => ({
@ -42,6 +48,7 @@ export class HistoryIngester {
chunkIndex: String(index),
threadId: message.threadId ?? "",
editedAt: message.editedAt ?? "",
messageKind: readArchivedMessageKind(message),
},
}));
}

View file

@ -0,0 +1,164 @@
import type { RetrievalFilters, RetrievalResult } from "@voidbot/shared";
import { FileMessageArchiveRepository } from "./message-archive";
import { RetrievalService } from "./retrieval-service";
const HISTORY_ECHO_STOP_WORDS = new Set([
"about",
"after",
"before",
"could",
"from",
"have",
"please",
"pretty",
"tell",
"that",
"them",
"they",
"this",
"what",
"with",
"would",
"your",
]);
interface HistorySearchWithArchiveFallbackOptions {
retrievalService: RetrievalService;
archiveRepository: FileMessageArchiveRepository;
query: string;
limit: number;
guildId?: string;
channelId?: string;
authorId?: string;
includeBotPrompts?: boolean;
preserveOverfetch?: boolean;
}
export async function searchHistoryWithArchiveFallback(
options: HistorySearchWithArchiveFallbackOptions,
): 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,
includeBotPrompts: options.includeBotPrompts ?? false,
},
);
if (lexicalResults.length === 0) {
return options.preserveOverfetch
? vectorResults
: vectorResults.slice(0, options.limit);
}
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 options.preserveOverfetch ? merged : merged.slice(0, options.limit);
}
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,
);
}

View file

@ -1,5 +1,6 @@
export * from "./embedder-factory";
export * from "./history-ingester";
export * from "./history-retrieval";
export * from "./discord-log-importer";
export * from "./file-store";
export * from "./file-vector-store";

View file

@ -2,6 +2,8 @@ import {
type ArchivedMessage,
type RetrievalFilters,
type RetrievalResult,
isArchivedBotPrompt,
readArchivedMessageKind,
} from "@voidbot/shared";
import { normalizeText } from "./history-ingester";
@ -46,6 +48,11 @@ export interface MessageArchiveMutationResult {
changedMessageIds: string[];
}
interface HistoryArchiveFilters
extends Pick<RetrievalFilters, "guildId" | "channelId" | "authorId"> {
includeBotPrompts?: boolean;
}
export class FileMessageArchiveRepository {
private readonly store: SerializedFileStore<MessageArchiveStore>;
@ -186,7 +193,7 @@ export class FileMessageArchiveRepository {
public async searchLexical(
query: string,
limit = 5,
filters?: Pick<RetrievalFilters, "guildId" | "channelId" | "authorId">,
filters?: HistoryArchiveFilters,
): Promise<RetrievalResult[]> {
const normalizedQuery = normalizeSearchText(query);
const queryTokens = extractSearchTokens(normalizedQuery);
@ -265,10 +272,14 @@ function belongsToSameConversation(
function matchesHistoryFilters(
message: ArchivedMessageRecord,
filters?: Pick<RetrievalFilters, "guildId" | "channelId" | "authorId">,
filters?: HistoryArchiveFilters,
): boolean {
if (!filters) {
return true;
return !isArchivedBotPrompt(message);
}
if (!filters.includeBotPrompts && isArchivedBotPrompt(message)) {
return false;
}
if (filters.guildId && message.guildId !== filters.guildId) {
@ -350,6 +361,7 @@ function toRetrievalResult(message: ArchivedMessageRecord, score: number): Retri
threadId: message.threadId ?? "",
jumpUrl: message.metadata?.jumpUrl ?? "",
corpusKind: "discord_history",
messageKind: readArchivedMessageKind(message),
},
};
}

View file

@ -0,0 +1,122 @@
export const archivedMessageKinds = ["default", "bot_prompt"] as const;
export type ArchivedMessageKind = (typeof archivedMessageKinds)[number];
export const ARCHIVED_MESSAGE_KIND_METADATA_KEY = "messageKind";
interface MetadataCarrier {
metadata?: Record<string, string>;
}
interface BotPromptMessageLike extends MetadataCarrier {
content: string;
}
export function readArchivedMessageKind(
message: MetadataCarrier | undefined,
): ArchivedMessageKind {
return message?.metadata?.[ARCHIVED_MESSAGE_KIND_METADATA_KEY] === "bot_prompt"
? "bot_prompt"
: "default";
}
export function isArchivedBotPrompt(
message: MetadataCarrier | undefined,
): boolean {
return readArchivedMessageKind(message) === "bot_prompt";
}
export function setArchivedMessageKind(
metadata: Record<string, string> | undefined,
kind: ArchivedMessageKind,
): Record<string, string> | undefined {
const nextMetadata = { ...(metadata ?? {}) };
if (kind === "default") {
delete nextMetadata[ARCHIVED_MESSAGE_KIND_METADATA_KEY];
return Object.keys(nextMetadata).length > 0 ? nextMetadata : undefined;
}
nextMetadata[ARCHIVED_MESSAGE_KIND_METADATA_KEY] = kind;
return nextMetadata;
}
export function contentMentionsDiscordUser(
content: string,
userId: string | undefined,
): boolean {
if (!userId || userId.trim().length === 0) {
return false;
}
const escapedId = escapeRegExp(userId.trim());
return new RegExp(`<@!?${escapedId}>`).test(content);
}
export function contentMentionsDiscordRole(
content: string,
roleId: string | undefined,
): boolean {
if (!roleId || roleId.trim().length === 0) {
return false;
}
const escapedId = escapeRegExp(roleId.trim());
return new RegExp(`<@&${escapedId}>`).test(content);
}
export function isDiscordBotPromptContent(
content: string,
options: {
botUserId?: string;
botRoleIds?: string[];
} = {},
): boolean {
if (contentMentionsDiscordUser(content, options.botUserId)) {
return true;
}
return (options.botRoleIds ?? []).some((roleId) =>
contentMentionsDiscordRole(content, roleId),
);
}
export function classifyArchivedMessageKind(
message: BotPromptMessageLike,
options: {
botUserId?: string;
botRoleIds?: string[];
} = {},
): ArchivedMessageKind {
if (isArchivedBotPrompt(message)) {
return "bot_prompt";
}
return isDiscordBotPromptContent(message.content, options)
? "bot_prompt"
: "default";
}
export function applyArchivedMessageKind<T extends BotPromptMessageLike>(
message: T,
options: {
botUserId?: string;
botRoleIds?: string[];
} = {},
): T {
const kind = classifyArchivedMessageKind(message, options);
const nextMetadata = setArchivedMessageKind(message.metadata, kind);
const currentKind = readArchivedMessageKind(message);
if (kind === currentKind && nextMetadata === message.metadata) {
return message;
}
return {
...message,
metadata: nextMetadata,
};
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

View file

@ -1,4 +1,5 @@
export * from "./channel-indexing";
export * from "./history-message-kind";
export const commandNames = [
"ask",