Files
shared-memory/apps/web/lib/memory-excerpt.ts
T

99 lines
3.5 KiB
TypeScript
Raw Normal View History

/**
* Short excerpts for memory.list / memory.search results.
*
* Those tools used to return every memory's full body, so one search over
* a few dozen long memories could pour thousands of words into the
* caller's context. They now return an excerpt plus `contentLength` /
* `truncated`, and the caller fetches the whole body with memory.get when
* the excerpt says it's worth it.
*
* With a query, the excerpt is the window matching the most distinct
* query terms (case-insensitive substring match, so "launch" also finds
* "launched"). Without one — or when no term appears, e.g. a vector-only
* hit — it is the start of the memory, which is usually its summary line.
*/
export const EXCERPT_CHARS = 200;
/** Context kept before the first matched term so the passage reads naturally. */
const LEAD_CHARS = 40;
/** Cap on occurrences examined per term, to keep huge memories cheap. */
const MAX_OCCURRENCES_PER_TERM = 25;
const STOPWORDS = new Set([
"the", "and", "for", "are", "but", "not", "you", "all", "any", "can",
"had", "her", "was", "one", "our", "out", "has", "his", "how", "its",
"who", "did", "get", "may", "use", "she", "him", "too", "via",
"that", "this", "with", "from", "they", "have", "what", "when", "where",
"which", "there", "their", "about", "into", "than", "then", "them",
"does", "should", "would", "could",
]);
export interface Excerpt {
excerpt: string;
/** True when the excerpt is not the whole (whitespace-collapsed) memory. */
truncated: boolean;
}
function queryTerms(query: string): string[] {
const terms = query
.toLowerCase()
.split(/[^\p{L}\p{N}]+/u)
.filter((t) => t.length >= 3 && !STOPWORDS.has(t));
return [...new Set(terms)];
}
/** Start offset of the best-matching window, or 0 when nothing matches. */
function bestWindowStart(lower: string, terms: string[], max: number): number {
let best = 0;
let bestScore = 0;
for (const term of terms) {
let i = -1;
for (let n = 0; n < MAX_OCCURRENCES_PER_TERM; n++) {
i = lower.indexOf(term, i + 1);
if (i === -1) break;
const start = Math.max(0, i - LEAD_CHARS);
const window = lower.slice(start, start + max);
const score = terms.reduce((s, t) => s + (window.includes(t) ? 1 : 0), 0);
if (score > bestScore || (score === bestScore && start < best)) {
best = start;
bestScore = score;
}
}
}
return best;
}
export function makeExcerpt(
content: string,
query?: string,
max: number = EXCERPT_CHARS,
): Excerpt {
const text = content.replace(/\s+/g, " ").trim();
if (text.length <= max) return { excerpt: text, truncated: false };
const terms = query ? queryTerms(query) : [];
let start = terms.length > 0 ? bestWindowStart(text.toLowerCase(), terms, max) : 0;
// A match near the end would leave a stub; slide back to fill the window.
start = Math.min(start, text.length - max);
// Snap the start forward to a word boundary (never mid-word).
if (start > 0 && text[start - 1] !== " ") {
const space = text.indexOf(" ", start);
if (space !== -1 && space - start < 20) start = space + 1;
}
let end = Math.min(text.length, start + max);
// Snap the end back to a word boundary.
if (end < text.length && text[end] !== " ") {
const space = text.lastIndexOf(" ", end);
if (space > start + max / 2) end = space;
}
const body = text.slice(start, end).trim();
return {
excerpt: `${start > 0 ? "…" : ""}${body}${end < text.length ? "…" : ""}`,
truncated: true,
};
}