File size: 6,082 Bytes
6111b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | import { Memory, MemoryType } from "./types";
import { getDbInstance } from "../db/core";
import { deleteMemory, createMemory } from "./store";
export interface SummarizationResult {
originalCount: number;
summarizedCount: number;
tokensSaved: number;
}
export async function summarizeMemories(
apiKeyId: string,
sessionId?: string,
maxTokens: number = 4000
): Promise<SummarizationResult> {
const db = getDbInstance();
const whereClause = sessionId
? "WHERE api_key_id = ? AND session_id = ?"
: "WHERE api_key_id = ?";
const params = sessionId ? [apiKeyId, sessionId] : [apiKeyId];
const memories = db
.prepare(`SELECT * FROM memories ${whereClause} ORDER BY created_at DESC`)
.all(...params) as MemoryRow[];
if (memories.length === 0) {
return { originalCount: 0, summarizedCount: 0, tokensSaved: 0 };
}
let totalTokens = 0;
const toSummarize: Memory[] = [];
const toKeep: Memory[] = [];
for (const mem of memories) {
const tokens = estimateTokens(mem.content);
if (totalTokens + tokens <= maxTokens) {
toKeep.push(rowToMemory(mem));
totalTokens += tokens;
} else {
toSummarize.push(rowToMemory(mem));
}
}
const summarizedCount = toSummarize.length;
let tokensSaved = 0;
for (const mem of toSummarize) {
const summary = generateSummary(mem.content);
const oldTokens = estimateTokens(mem.content);
const newTokens = estimateTokens(summary);
tokensSaved += oldTokens - newTokens;
db.prepare("UPDATE memories SET content = ?, updated_at = ? WHERE id = ?").run(
summary,
new Date().toISOString(),
mem.id
);
}
return {
originalCount: memories.length,
summarizedCount,
tokensSaved,
};
}
// ββββββββββββββββ Types ββββββββββββββββ
interface MemoryRow {
id: string;
api_key_id: string;
session_id: string | null;
type: string;
key: string | null;
content: string;
metadata: string | null;
created_at: string;
updated_at: string;
expires_at: string | null;
}
function rowToMemory(row: MemoryRow): Memory {
return {
id: String(row.id),
apiKeyId: String(row.api_key_id),
sessionId: typeof row.session_id === "string" ? row.session_id : "",
type: row.type as MemoryType,
key: typeof row.key === "string" ? row.key : "",
content: String(row.content),
metadata: row.metadata
? (() => {
try {
const p = JSON.parse(row.metadata);
return typeof p === "object" && p !== null ? p : {};
} catch {
return {};
}
})()
: {},
createdAt: new Date(String(row.created_at)),
updatedAt: new Date(String(row.updated_at)),
expiresAt: row.expires_at ? new Date(String(row.expires_at)) : null,
};
}
function estimateTokens(text: string): number {
return Math.ceil(text.length / 4);
}
function generateSummary(content: string): string {
const sentences = content
.split(/[.!?]+/)
.map((sentence) => sentence.trim())
.filter((sentence) => sentence.length > 0);
if (sentences.length <= 3) {
return content;
}
return sentences.slice(0, 3).join(". ") + ".";
}
// ββββββββββββββββ Plan 21 D19: summarizeMemoriesOlderThan ββββββββββββββββ
export interface SummarizeOlderThanResult {
candidates: Memory[];
totalTokens: number;
deletedCount: number;
summaryId: string | null;
dryRun: boolean;
}
/**
* Summarize (or dry-run preview) memories older than `days` days for a given apiKeyId.
*
* - dryRun=true: returns candidates + totalTokens without touching the DB.
* - dryRun=false: creates ONE summary memory (type="semantic"), deletes all candidates,
* returns { candidates, totalTokens, deletedCount, summaryId, dryRun:false }.
*
* Used by POST /api/memory/summarize (F6).
*/
export async function summarizeMemoriesOlderThan(
apiKeyId: string | undefined,
days: number,
dryRun: boolean
): Promise<SummarizeOlderThanResult> {
const db = getDbInstance();
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
const rows: MemoryRow[] = apiKeyId
? (db
.prepare(
"SELECT * FROM memories WHERE api_key_id = ? AND created_at < ? ORDER BY created_at ASC"
)
.all(apiKeyId, cutoff) as MemoryRow[])
: (db
.prepare("SELECT * FROM memories WHERE created_at < ? ORDER BY created_at ASC")
.all(cutoff) as MemoryRow[]);
const candidates = rows.map(rowToMemory);
const totalTokens = candidates.reduce((sum, m) => sum + estimateTokens(m.content), 0);
if (dryRun || candidates.length === 0) {
return { candidates, totalTokens, deletedCount: 0, summaryId: null, dryRun: true };
}
// Build a condensed summary text from all candidates
const summaryLines = candidates.map(
(m) => `[${m.type}] ${m.key ? m.key + ": " : ""}${generateSummary(m.content)}`
);
const summaryContent = `Resumo de ${candidates.length} memΓ³rias (>${days} dias):\n${summaryLines.join("\n")}`;
// Create ONE new summary memory
const summaryMemory = await createMemory({
apiKeyId: apiKeyId ?? "",
sessionId: "",
type: MemoryType.SEMANTIC,
key: `summary_${new Date().toISOString()}`,
content: summaryContent,
metadata: {
summarizedCount: candidates.length,
olderThanDays: days,
generatedAt: new Date().toISOString(),
},
expiresAt: null,
});
// Delete all original candidates (use deleteMemory to ensure vec + Qdrant sync)
let deletedCount = 0;
for (const candidate of candidates) {
const ok = await deleteMemory(candidate.id);
if (ok) deletedCount++;
}
return {
candidates,
totalTokens,
deletedCount,
summaryId: summaryMemory.id,
dryRun: false,
};
}
|