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

@ -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),
},
};
}