@modusensus/dsh-mneme 0.6.7 → 0.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +463 -463
- package/cordis.patch.yml +15 -15
- package/lib/api.js +783 -783
- package/lib/client.js +1757 -1757
- package/lib/commands.js +64 -64
- package/lib/config.js +288 -288
- package/lib/dream/clustering.js +118 -118
- package/lib/dream/decisions.js +439 -439
- package/lib/dream/sleep.js +561 -554
- package/lib/dream/tag-extractor.js +156 -156
- package/lib/dream.js +935 -929
- package/lib/embedding.js +154 -154
- package/lib/entities/extractor.js +242 -242
- package/lib/hot-memory.js +53 -53
- package/lib/index.js +361 -361
- package/lib/inject.js +208 -208
- package/lib/local-embedder.js +282 -282
- package/lib/mirror.js +170 -170
- package/lib/parser/tag.js +59 -59
- package/lib/parser/wiki-link.js +38 -38
- package/lib/quality-filter.js +123 -123
- package/lib/reranker.js +218 -218
- package/lib/search/adaptive.js +22 -22
- package/lib/search/bm25.js +96 -96
- package/lib/search/tag-boost.js +61 -61
- package/lib/service.js +1726 -1726
- package/lib/settings.js +172 -172
- package/lib/store.js +2238 -2238
- package/lib/summarize.js +236 -236
- package/lib/tools.js +290 -290
- package/lib/vector-index.js +116 -116
- package/package.json +80 -80
- package/scripts/benchmark-embed.js +201 -201
- package/scripts/benchmark-recall.js +133 -133
- package/scripts/benchmark-rerank.js +166 -166
- package/scripts/e2e-dsh.js +218 -218
- package/scripts/stress-dsh.js +255 -255
- package/scripts/sync-lib.js +52 -52
- package/src/api.js +783 -783
- package/src/commands.js +64 -64
- package/src/config.js +288 -288
- package/src/dream/clustering.js +118 -118
- package/src/dream/decisions.js +439 -439
- package/src/dream/sleep.js +561 -554
- package/src/dream/tag-extractor.js +156 -156
- package/src/dream.js +935 -929
- package/src/embedding.js +154 -154
- package/src/entities/extractor.js +242 -242
- package/src/hot-memory.js +53 -53
- package/src/index.js +361 -361
- package/src/inject.js +208 -208
- package/src/local-embedder.js +282 -282
- package/src/mirror.js +170 -170
- package/src/parser/tag.js +59 -59
- package/src/parser/wiki-link.js +38 -38
- package/src/quality-filter.js +123 -123
- package/src/reranker.js +218 -218
- package/src/search/adaptive.js +22 -22
- package/src/search/bm25.js +96 -96
- package/src/search/tag-boost.js +61 -61
- package/src/service.js +1726 -1726
- package/src/settings.js +172 -172
- package/src/store.js +2238 -2238
- package/src/summarize.js +236 -236
- package/src/tools.js +290 -290
- package/src/vector-index.js +116 -116
- package/test/api.test.js +594 -594
- package/test/audit.test.js +448 -448
- package/test/benchmark.test.js +35 -35
- package/test/boundary-v0625.test.js +82 -82
- package/test/client.test.js +368 -368
- package/test/clustering.test.js +100 -100
- package/test/commands.test.js +69 -69
- package/test/config.test.js +50 -50
- package/test/conflict-freeze.test.js +290 -290
- package/test/directory.test.js +134 -134
- package/test/dream.test.js +903 -901
- package/test/entities.test.js +522 -522
- package/test/epistemic.test.js +298 -298
- package/test/fnew-0112.test.js +311 -311
- package/test/fnew-03.test.js +422 -422
- package/test/graph-api.test.js +175 -175
- package/test/helpers/dream-mock.js +82 -82
- package/test/hot-memory.test.js +174 -174
- package/test/inject.test.js +103 -103
- package/test/llm-audit.test.js +279 -279
- package/test/local-embedder.test.js +227 -227
- package/test/mirror-dirty.test.js +424 -424
- package/test/mirror-edit-digest.test.js +187 -187
- package/test/mirror-generation.test.js +499 -499
- package/test/mirror.test.js +249 -249
- package/test/normalize-decisions.test.js +120 -120
- package/test/peer-blockers.test.js +190 -190
- package/test/policy-epoch.test.js +259 -259
- package/test/provenance.test.js +103 -103
- package/test/quality-filter.test.js +118 -118
- package/test/reasoning-effort.test.js +199 -199
- package/test/recall-evals.test.js +235 -235
- package/test/recall-layer.test.js +315 -315
- package/test/receipt-chain.test.js +451 -451
- package/test/reflection.test.js +226 -226
- package/test/reranker.test.js +240 -240
- package/test/search-fusion.test.js +90 -90
- package/test/semantic.test.js +124 -124
- package/test/service-search.test.js +199 -199
- package/test/service.test.js +435 -435
- package/test/settings.test.js +118 -118
- package/test/sleep.test.js +365 -365
- package/test/store.test.js +436 -436
- package/test/stress.test.js +209 -209
- package/test/summarize.test.js +191 -191
- package/test/tag-boost.test.js +125 -125
- package/test/tag.test.js +312 -312
- package/test/tools.test.js +285 -285
- package/test/vector-index.test.js +221 -221
- package/test/wiki-link.test.js +332 -332
|
@@ -1,242 +1,242 @@
|
|
|
1
|
-
const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
|
|
2
|
-
const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
|
|
3
|
-
const MAX_MEMORY_CHARS = 4000;
|
|
4
|
-
|
|
5
|
-
function buildSystemPrompt(config) {
|
|
6
|
-
const maxEntities = config.entityExtractionMaxEntities ?? 10;
|
|
7
|
-
const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
|
|
8
|
-
|
|
9
|
-
return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
|
|
10
|
-
|
|
11
|
-
RULES:
|
|
12
|
-
- Entities are concrete people, projects, technologies, concepts, or organizations.
|
|
13
|
-
- Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
|
|
14
|
-
- Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
|
|
15
|
-
- Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
|
|
16
|
-
- Output MUST be strict JSON with this exact structure:
|
|
17
|
-
{
|
|
18
|
-
"entities": [
|
|
19
|
-
{"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
|
|
20
|
-
],
|
|
21
|
-
"relations": [
|
|
22
|
-
{"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
|
|
23
|
-
]
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
CONSTRAINTS:
|
|
27
|
-
- "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
|
|
28
|
-
- "relations" from/to must reference entity names from the "entities" list.
|
|
29
|
-
- Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
|
|
30
|
-
- Only include entity-related attributes. Ignore irrelevant miscellaneous details.
|
|
31
|
-
- Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function buildUserMessage(memoryText) {
|
|
35
|
-
const truncated = memoryText.length > MAX_MEMORY_CHARS
|
|
36
|
-
? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
|
|
37
|
-
: memoryText;
|
|
38
|
-
return truncated;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function extractJsonFromText(text) {
|
|
42
|
-
if (!text || typeof text !== "string") return null;
|
|
43
|
-
|
|
44
|
-
// Try direct parse first
|
|
45
|
-
try {
|
|
46
|
-
return JSON.parse(text);
|
|
47
|
-
} catch {
|
|
48
|
-
// fall through
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Try to find first {...} block
|
|
52
|
-
const match = text.match(/\{[\s\S]*\}/);
|
|
53
|
-
if (match) {
|
|
54
|
-
try {
|
|
55
|
-
return JSON.parse(match[0]);
|
|
56
|
-
} catch {
|
|
57
|
-
return null;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function sanitizeType(type) {
|
|
65
|
-
if (VALID_TYPES.has(type)) return type;
|
|
66
|
-
return "concept";
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function sanitizeConfidence(conf) {
|
|
70
|
-
const num = Number(conf);
|
|
71
|
-
if (Number.isNaN(num)) return 0.9;
|
|
72
|
-
return Math.min(1, Math.max(0, num));
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function sanitizeRelationType(type) {
|
|
76
|
-
if (VALID_RELATIONS.has(type)) return type;
|
|
77
|
-
return "related_to";
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function sanitizeExtractedData(data, config) {
|
|
81
|
-
const maxEntities = config.entityExtractionMaxEntities ?? 10;
|
|
82
|
-
const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
|
|
83
|
-
|
|
84
|
-
if (!data || !Array.isArray(data.entities)) {
|
|
85
|
-
throw new Error("Invalid extraction: missing entities array");
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const entities = [];
|
|
89
|
-
const seenNames = new Set();
|
|
90
|
-
|
|
91
|
-
for (const rawEntity of data.entities.slice(0, maxEntities)) {
|
|
92
|
-
if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
|
|
93
|
-
|
|
94
|
-
const name = rawEntity.name.trim();
|
|
95
|
-
if (seenNames.has(name)) continue;
|
|
96
|
-
seenNames.add(name);
|
|
97
|
-
|
|
98
|
-
const attrs = [];
|
|
99
|
-
if (Array.isArray(rawEntity.attrs)) {
|
|
100
|
-
for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
|
|
101
|
-
if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
|
|
102
|
-
attrs.push({
|
|
103
|
-
key: rawAttr.key.trim(),
|
|
104
|
-
value: rawAttr.value.trim(),
|
|
105
|
-
confidence: sanitizeConfidence(rawAttr.confidence)
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
entities.push({
|
|
111
|
-
name,
|
|
112
|
-
type: sanitizeType(rawEntity.type),
|
|
113
|
-
attrs
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
const relations = [];
|
|
118
|
-
if (Array.isArray(data.relations)) {
|
|
119
|
-
for (const rawRel of data.relations) {
|
|
120
|
-
if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
|
|
121
|
-
if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
|
|
122
|
-
relations.push({
|
|
123
|
-
from: rawRel.from,
|
|
124
|
-
to: rawRel.to,
|
|
125
|
-
type: sanitizeRelationType(rawRel.type)
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
return { entities, relations };
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
async function resolveEntity(entity, store) {
|
|
134
|
-
const existing = store.findEntityByName(entity.name);
|
|
135
|
-
if (existing) {
|
|
136
|
-
store.updateEntity(existing.id, {});
|
|
137
|
-
return existing.id;
|
|
138
|
-
}
|
|
139
|
-
const created = store.createEntity({ name: entity.name, type: entity.type });
|
|
140
|
-
return created.id;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export async function extractEntities(memory, { store, config, callLLM, logger }) {
|
|
144
|
-
try {
|
|
145
|
-
if (!memory || !memory.content) {
|
|
146
|
-
return { ok: false, error: "Invalid memory: missing content" };
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const model = config.entityExtractionModel || null;
|
|
150
|
-
const systemPrompt = buildSystemPrompt(config);
|
|
151
|
-
const userText = buildUserMessage(memory.content);
|
|
152
|
-
|
|
153
|
-
const messages = [
|
|
154
|
-
{ role: "system", content: [{ type: "text", text: systemPrompt }] },
|
|
155
|
-
{ role: "user", content: [{ type: "text", text: userText }] }
|
|
156
|
-
];
|
|
157
|
-
|
|
158
|
-
const options = model ? { model } : {};
|
|
159
|
-
const llmResponse = await callLLM(messages, options);
|
|
160
|
-
|
|
161
|
-
if (!llmResponse) {
|
|
162
|
-
return { ok: false, error: "LLM returned empty response" };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
const rawData = extractJsonFromText(llmResponse);
|
|
166
|
-
if (!rawData) {
|
|
167
|
-
return { ok: false, error: "Failed to parse JSON from LLM response" };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const { entities, relations } = sanitizeExtractedData(rawData, config);
|
|
171
|
-
|
|
172
|
-
const resolvedEntities = [];
|
|
173
|
-
const entityIdMap = new Map();
|
|
174
|
-
let skipCount = 0;
|
|
175
|
-
|
|
176
|
-
// Resolve entities
|
|
177
|
-
for (const entity of entities) {
|
|
178
|
-
try {
|
|
179
|
-
const entityId = await resolveEntity(entity, store);
|
|
180
|
-
entityIdMap.set(entity.name, entityId);
|
|
181
|
-
resolvedEntities.push({ ...entity, entity_id: entityId });
|
|
182
|
-
} catch (err) {
|
|
183
|
-
skipCount++;
|
|
184
|
-
logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Record attributes
|
|
189
|
-
const attrs = [];
|
|
190
|
-
for (const entity of resolvedEntities) {
|
|
191
|
-
for (const attr of entity.attrs) {
|
|
192
|
-
try {
|
|
193
|
-
const saved = store.saveAttr({
|
|
194
|
-
entity_id: entity.entity_id,
|
|
195
|
-
attr_key: attr.key,
|
|
196
|
-
attr_value: String(attr.value),
|
|
197
|
-
memory_id: memory.id,
|
|
198
|
-
confidence: attr.confidence,
|
|
199
|
-
source: "llm_extract"
|
|
200
|
-
});
|
|
201
|
-
attrs.push(saved);
|
|
202
|
-
} catch (err) {
|
|
203
|
-
skipCount++;
|
|
204
|
-
logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// Record relations
|
|
210
|
-
const savedRelations = [];
|
|
211
|
-
for (const rel of relations) {
|
|
212
|
-
const fromId = entityIdMap.get(rel.from);
|
|
213
|
-
const toId = entityIdMap.get(rel.to);
|
|
214
|
-
if (!fromId || !toId) continue;
|
|
215
|
-
|
|
216
|
-
try {
|
|
217
|
-
const saved = store.saveRelation({
|
|
218
|
-
from_entity: fromId,
|
|
219
|
-
to_entity: toId,
|
|
220
|
-
relation_type: rel.type,
|
|
221
|
-
memory_id: memory.id,
|
|
222
|
-
metadata: { model: model || "default" }
|
|
223
|
-
});
|
|
224
|
-
savedRelations.push(saved);
|
|
225
|
-
} catch (err) {
|
|
226
|
-
skipCount++;
|
|
227
|
-
logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
return {
|
|
232
|
-
ok: true,
|
|
233
|
-
entities: resolvedEntities,
|
|
234
|
-
attrs,
|
|
235
|
-
relations: savedRelations,
|
|
236
|
-
skipped: skipCount
|
|
237
|
-
};
|
|
238
|
-
|
|
239
|
-
} catch (err) {
|
|
240
|
-
return { ok: false, error: String(err) };
|
|
241
|
-
}
|
|
242
|
-
}
|
|
1
|
+
const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
|
|
2
|
+
const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
|
|
3
|
+
const MAX_MEMORY_CHARS = 4000;
|
|
4
|
+
|
|
5
|
+
function buildSystemPrompt(config) {
|
|
6
|
+
const maxEntities = config.entityExtractionMaxEntities ?? 10;
|
|
7
|
+
const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
|
|
8
|
+
|
|
9
|
+
return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
|
|
10
|
+
|
|
11
|
+
RULES:
|
|
12
|
+
- Entities are concrete people, projects, technologies, concepts, or organizations.
|
|
13
|
+
- Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
|
|
14
|
+
- Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
|
|
15
|
+
- Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
|
|
16
|
+
- Output MUST be strict JSON with this exact structure:
|
|
17
|
+
{
|
|
18
|
+
"entities": [
|
|
19
|
+
{"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
|
|
20
|
+
],
|
|
21
|
+
"relations": [
|
|
22
|
+
{"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
|
|
23
|
+
]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
CONSTRAINTS:
|
|
27
|
+
- "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
|
|
28
|
+
- "relations" from/to must reference entity names from the "entities" list.
|
|
29
|
+
- Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
|
|
30
|
+
- Only include entity-related attributes. Ignore irrelevant miscellaneous details.
|
|
31
|
+
- Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function buildUserMessage(memoryText) {
|
|
35
|
+
const truncated = memoryText.length > MAX_MEMORY_CHARS
|
|
36
|
+
? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
|
|
37
|
+
: memoryText;
|
|
38
|
+
return truncated;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function extractJsonFromText(text) {
|
|
42
|
+
if (!text || typeof text !== "string") return null;
|
|
43
|
+
|
|
44
|
+
// Try direct parse first
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(text);
|
|
47
|
+
} catch {
|
|
48
|
+
// fall through
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Try to find first {...} block
|
|
52
|
+
const match = text.match(/\{[\s\S]*\}/);
|
|
53
|
+
if (match) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(match[0]);
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sanitizeType(type) {
|
|
65
|
+
if (VALID_TYPES.has(type)) return type;
|
|
66
|
+
return "concept";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function sanitizeConfidence(conf) {
|
|
70
|
+
const num = Number(conf);
|
|
71
|
+
if (Number.isNaN(num)) return 0.9;
|
|
72
|
+
return Math.min(1, Math.max(0, num));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sanitizeRelationType(type) {
|
|
76
|
+
if (VALID_RELATIONS.has(type)) return type;
|
|
77
|
+
return "related_to";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function sanitizeExtractedData(data, config) {
|
|
81
|
+
const maxEntities = config.entityExtractionMaxEntities ?? 10;
|
|
82
|
+
const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
|
|
83
|
+
|
|
84
|
+
if (!data || !Array.isArray(data.entities)) {
|
|
85
|
+
throw new Error("Invalid extraction: missing entities array");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const entities = [];
|
|
89
|
+
const seenNames = new Set();
|
|
90
|
+
|
|
91
|
+
for (const rawEntity of data.entities.slice(0, maxEntities)) {
|
|
92
|
+
if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
|
|
93
|
+
|
|
94
|
+
const name = rawEntity.name.trim();
|
|
95
|
+
if (seenNames.has(name)) continue;
|
|
96
|
+
seenNames.add(name);
|
|
97
|
+
|
|
98
|
+
const attrs = [];
|
|
99
|
+
if (Array.isArray(rawEntity.attrs)) {
|
|
100
|
+
for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
|
|
101
|
+
if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
|
|
102
|
+
attrs.push({
|
|
103
|
+
key: rawAttr.key.trim(),
|
|
104
|
+
value: rawAttr.value.trim(),
|
|
105
|
+
confidence: sanitizeConfidence(rawAttr.confidence)
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
entities.push({
|
|
111
|
+
name,
|
|
112
|
+
type: sanitizeType(rawEntity.type),
|
|
113
|
+
attrs
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const relations = [];
|
|
118
|
+
if (Array.isArray(data.relations)) {
|
|
119
|
+
for (const rawRel of data.relations) {
|
|
120
|
+
if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
|
|
121
|
+
if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
|
|
122
|
+
relations.push({
|
|
123
|
+
from: rawRel.from,
|
|
124
|
+
to: rawRel.to,
|
|
125
|
+
type: sanitizeRelationType(rawRel.type)
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return { entities, relations };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function resolveEntity(entity, store) {
|
|
134
|
+
const existing = store.findEntityByName(entity.name);
|
|
135
|
+
if (existing) {
|
|
136
|
+
store.updateEntity(existing.id, {});
|
|
137
|
+
return existing.id;
|
|
138
|
+
}
|
|
139
|
+
const created = store.createEntity({ name: entity.name, type: entity.type });
|
|
140
|
+
return created.id;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function extractEntities(memory, { store, config, callLLM, logger }) {
|
|
144
|
+
try {
|
|
145
|
+
if (!memory || !memory.content) {
|
|
146
|
+
return { ok: false, error: "Invalid memory: missing content" };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const model = config.entityExtractionModel || null;
|
|
150
|
+
const systemPrompt = buildSystemPrompt(config);
|
|
151
|
+
const userText = buildUserMessage(memory.content);
|
|
152
|
+
|
|
153
|
+
const messages = [
|
|
154
|
+
{ role: "system", content: [{ type: "text", text: systemPrompt }] },
|
|
155
|
+
{ role: "user", content: [{ type: "text", text: userText }] }
|
|
156
|
+
];
|
|
157
|
+
|
|
158
|
+
const options = model ? { model } : {};
|
|
159
|
+
const llmResponse = await callLLM(messages, options);
|
|
160
|
+
|
|
161
|
+
if (!llmResponse) {
|
|
162
|
+
return { ok: false, error: "LLM returned empty response" };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const rawData = extractJsonFromText(llmResponse);
|
|
166
|
+
if (!rawData) {
|
|
167
|
+
return { ok: false, error: "Failed to parse JSON from LLM response" };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const { entities, relations } = sanitizeExtractedData(rawData, config);
|
|
171
|
+
|
|
172
|
+
const resolvedEntities = [];
|
|
173
|
+
const entityIdMap = new Map();
|
|
174
|
+
let skipCount = 0;
|
|
175
|
+
|
|
176
|
+
// Resolve entities
|
|
177
|
+
for (const entity of entities) {
|
|
178
|
+
try {
|
|
179
|
+
const entityId = await resolveEntity(entity, store);
|
|
180
|
+
entityIdMap.set(entity.name, entityId);
|
|
181
|
+
resolvedEntities.push({ ...entity, entity_id: entityId });
|
|
182
|
+
} catch (err) {
|
|
183
|
+
skipCount++;
|
|
184
|
+
logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Record attributes
|
|
189
|
+
const attrs = [];
|
|
190
|
+
for (const entity of resolvedEntities) {
|
|
191
|
+
for (const attr of entity.attrs) {
|
|
192
|
+
try {
|
|
193
|
+
const saved = store.saveAttr({
|
|
194
|
+
entity_id: entity.entity_id,
|
|
195
|
+
attr_key: attr.key,
|
|
196
|
+
attr_value: String(attr.value),
|
|
197
|
+
memory_id: memory.id,
|
|
198
|
+
confidence: attr.confidence,
|
|
199
|
+
source: "llm_extract"
|
|
200
|
+
});
|
|
201
|
+
attrs.push(saved);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
skipCount++;
|
|
204
|
+
logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Record relations
|
|
210
|
+
const savedRelations = [];
|
|
211
|
+
for (const rel of relations) {
|
|
212
|
+
const fromId = entityIdMap.get(rel.from);
|
|
213
|
+
const toId = entityIdMap.get(rel.to);
|
|
214
|
+
if (!fromId || !toId) continue;
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
const saved = store.saveRelation({
|
|
218
|
+
from_entity: fromId,
|
|
219
|
+
to_entity: toId,
|
|
220
|
+
relation_type: rel.type,
|
|
221
|
+
memory_id: memory.id,
|
|
222
|
+
metadata: { model: model || "default" }
|
|
223
|
+
});
|
|
224
|
+
savedRelations.push(saved);
|
|
225
|
+
} catch (err) {
|
|
226
|
+
skipCount++;
|
|
227
|
+
logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
ok: true,
|
|
233
|
+
entities: resolvedEntities,
|
|
234
|
+
attrs,
|
|
235
|
+
relations: savedRelations,
|
|
236
|
+
skipped: skipCount
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
} catch (err) {
|
|
240
|
+
return { ok: false, error: String(err) };
|
|
241
|
+
}
|
|
242
|
+
}
|
package/src/hot-memory.js
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
// Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
|
|
2
|
-
// the latest dialogue rounds, kept strictly apart from the long-term memory
|
|
3
|
-
// store. The injector renders it ahead of the long-term recall block so the
|
|
4
|
-
// agent sees "what we were just talking about" without those rounds ever
|
|
5
|
-
// being persisted as memories. Bounded two ways: maxRounds (count) and
|
|
6
|
-
// maxTokens (budget) — whichever evicts first.
|
|
7
|
-
|
|
8
|
-
// CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
|
|
9
|
-
// behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
|
|
10
|
-
export function estimateTokens(text) {
|
|
11
|
-
const s = String(text ?? "");
|
|
12
|
-
let cjk = 0;
|
|
13
|
-
for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
|
|
14
|
-
return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* @param {{maxRounds?: number, maxTokens?: number}} opts
|
|
19
|
-
* @returns {{add(round: {query: string, response?: string}): void,
|
|
20
|
-
* getContext(): string,
|
|
21
|
-
* rounds(): Array, clear(): void}}
|
|
22
|
-
*/
|
|
23
|
-
export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
|
|
24
|
-
// Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
|
|
25
|
-
// null, "2") would make the eviction while-loop unbounded — the buffer can
|
|
26
|
-
// never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
|
|
27
|
-
// Fall back to the defaults so a hostile/buggy caller can never wedge the
|
|
28
|
-
// hot-memory buffer in an infinite loop.
|
|
29
|
-
maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
|
|
30
|
-
maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
|
|
31
|
-
const buffer = [];
|
|
32
|
-
|
|
33
|
-
function totalTokens() {
|
|
34
|
-
return buffer.reduce(
|
|
35
|
-
(sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
|
|
36
|
-
0
|
|
37
|
-
);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return {
|
|
41
|
-
add(round) {
|
|
42
|
-
if (!round?.query) return;
|
|
43
|
-
buffer.push({ query: String(round.query), response: String(round.response ?? "") });
|
|
44
|
-
while (buffer.length > maxRounds) buffer.shift();
|
|
45
|
-
while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
|
|
46
|
-
},
|
|
47
|
-
getContext() {
|
|
48
|
-
return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
|
|
49
|
-
},
|
|
50
|
-
rounds: () => [...buffer],
|
|
51
|
-
clear() { buffer.length = 0; }
|
|
52
|
-
};
|
|
53
|
-
}
|
|
1
|
+
// Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
|
|
2
|
+
// the latest dialogue rounds, kept strictly apart from the long-term memory
|
|
3
|
+
// store. The injector renders it ahead of the long-term recall block so the
|
|
4
|
+
// agent sees "what we were just talking about" without those rounds ever
|
|
5
|
+
// being persisted as memories. Bounded two ways: maxRounds (count) and
|
|
6
|
+
// maxTokens (budget) — whichever evicts first.
|
|
7
|
+
|
|
8
|
+
// CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
|
|
9
|
+
// behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
|
|
10
|
+
export function estimateTokens(text) {
|
|
11
|
+
const s = String(text ?? "");
|
|
12
|
+
let cjk = 0;
|
|
13
|
+
for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
|
|
14
|
+
return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{maxRounds?: number, maxTokens?: number}} opts
|
|
19
|
+
* @returns {{add(round: {query: string, response?: string}): void,
|
|
20
|
+
* getContext(): string,
|
|
21
|
+
* rounds(): Array, clear(): void}}
|
|
22
|
+
*/
|
|
23
|
+
export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
|
|
24
|
+
// Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
|
|
25
|
+
// null, "2") would make the eviction while-loop unbounded — the buffer can
|
|
26
|
+
// never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
|
|
27
|
+
// Fall back to the defaults so a hostile/buggy caller can never wedge the
|
|
28
|
+
// hot-memory buffer in an infinite loop.
|
|
29
|
+
maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
|
|
30
|
+
maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
|
|
31
|
+
const buffer = [];
|
|
32
|
+
|
|
33
|
+
function totalTokens() {
|
|
34
|
+
return buffer.reduce(
|
|
35
|
+
(sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
|
|
36
|
+
0
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
add(round) {
|
|
42
|
+
if (!round?.query) return;
|
|
43
|
+
buffer.push({ query: String(round.query), response: String(round.response ?? "") });
|
|
44
|
+
while (buffer.length > maxRounds) buffer.shift();
|
|
45
|
+
while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
|
|
46
|
+
},
|
|
47
|
+
getContext() {
|
|
48
|
+
return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
|
|
49
|
+
},
|
|
50
|
+
rounds: () => [...buffer],
|
|
51
|
+
clear() { buffer.length = 0; }
|
|
52
|
+
};
|
|
53
|
+
}
|