@aleph-ai/tinyaleph 1.5.6 → 1.6.0
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/core/alexander-module.js +1469 -0
- package/core/arithmetic-link-kernel.js +1338 -0
- package/core/index.js +95 -2
- package/examples/01-hello-world.js +69 -0
- package/examples/02-basic-hash.js +90 -0
- package/examples/02-observer-stack.js +385 -0
- package/examples/03-quantum-coin.js +136 -0
- package/examples/05-symbolic-resonance.js +146 -0
- package/examples/06-symbol-database.js +150 -0
- package/examples/07-semantic-inference.js +223 -0
- package/examples/08-compound-symbols.js +219 -0
- package/examples/README.md +170 -0
- package/examples/ai/01-embeddings.js +155 -0
- package/examples/ai/02-semantic-memory.js +243 -0
- package/examples/ai/03-reasoning.js +243 -0
- package/examples/ai/04-knowledge-graph.js +279 -0
- package/examples/ai/05-llm-integration.js +333 -0
- package/examples/ai/06-agent.js +294 -0
- package/examples/ai/07-hybrid-ai.js +223 -0
- package/examples/ai/08-entropy-reasoning.js +259 -0
- package/examples/ai/09-concept-learning.js +271 -0
- package/examples/ai/10-prompt-primes.js +312 -0
- package/examples/ai/11-rag.js +332 -0
- package/examples/ai/12-neuro-symbolic.js +321 -0
- package/examples/ai/README.md +80 -0
- package/examples/arithmetic-topology/01-legendre-symbol.js +78 -0
- package/examples/arithmetic-topology/02-redei-symbol.js +126 -0
- package/examples/arithmetic-topology/03-alk-kuramoto.js +138 -0
- package/examples/arithmetic-topology/04-alexander-module.js +117 -0
- package/examples/arithmetic-topology/05-signature-memory.js +118 -0
- package/examples/arithmetic-topology/README.md +291 -0
- package/examples/bioinformatics/01-dna-encoding.js +108 -0
- package/examples/bioinformatics/02-central-dogma.js +162 -0
- package/examples/bioinformatics/03-protein-folding.js +206 -0
- package/examples/bioinformatics/04-dna-computing.js +192 -0
- package/examples/bioinformatics/05-molecular-binding.js +209 -0
- package/examples/chat.js +105 -0
- package/examples/crt-homology/01-residue-encoding.js +87 -0
- package/examples/crt-homology/02-birkhoff-attention.js +100 -0
- package/examples/crt-homology/03-homology-loss.js +132 -0
- package/examples/crt-homology/04-crt-resoformer.js +132 -0
- package/examples/crt-homology/README.md +67 -0
- package/examples/crypto/01-password-hash.js +210 -0
- package/examples/crypto/02-key-derivation.js +210 -0
- package/examples/crypto/03-hmac.js +229 -0
- package/examples/crypto/04-file-integrity.js +263 -0
- package/examples/crypto/05-content-hash.js +263 -0
- package/examples/crypto/README.md +99 -0
- package/examples/demo-modular.js +223 -0
- package/examples/demo-two-layer.js +196 -0
- package/examples/discrete/01-integer-sine-table.js +120 -0
- package/examples/discrete/02-codebook-tunneling.js +118 -0
- package/examples/discrete/03-canonical-fusion.js +135 -0
- package/examples/discrete/04-tick-gate.js +139 -0
- package/examples/discrete/README.md +142 -0
- package/examples/formal-semantics/01-typed-terms.js +156 -0
- package/examples/formal-semantics/02-reduction.js +202 -0
- package/examples/formal-semantics/03-lambda-translation.js +206 -0
- package/examples/formal-semantics/04-enochian-language.js +257 -0
- package/examples/formal-semantics/README.md +98 -0
- package/examples/math/01-quaternions.js +237 -0
- package/examples/math/02-octonions.js +192 -0
- package/examples/math/03-prime-factorization.js +215 -0
- package/examples/math/04-vector-spaces.js +210 -0
- package/examples/math/05-gaussian-primes.js +234 -0
- package/examples/math/README.md +93 -0
- package/examples/physics/01-oscillator.js +177 -0
- package/examples/physics/02-lyapunov.js +201 -0
- package/examples/physics/03-collapse.js +183 -0
- package/examples/physics/04-kuramoto.js +212 -0
- package/examples/physics/05-entropy.js +226 -0
- package/examples/physics/05-sync-models.js +298 -0
- package/examples/physics/06-primeon-ladder.js +233 -0
- package/examples/physics/07-kuramoto-coupled-ladder.js +298 -0
- package/examples/physics/README.md +126 -0
- package/examples/resonance/01-prime-hilbert-space.js +140 -0
- package/examples/resonance/02-prime-resonance-network.js +221 -0
- package/examples/resonance/03-resoformer.js +349 -0
- package/examples/resonance/04-resoformer-training.js +329 -0
- package/examples/resonance/05-language-model.js +484 -0
- package/examples/resonance/README.md +238 -0
- package/examples/run-examples.js +417 -0
- package/examples/scientific/01-single-qubit.js +185 -0
- package/examples/scientific/02-two-qubit.js +209 -0
- package/examples/scientific/03-quantum-circuits.js +270 -0
- package/examples/scientific/04-measurement.js +229 -0
- package/examples/scientific/05-algorithms.js +245 -0
- package/examples/scientific/06-random.js +225 -0
- package/examples/scientific/07-wavefunction.js +192 -0
- package/examples/scientific/README.md +118 -0
- package/examples/semantic/01-vocabulary.js +186 -0
- package/examples/semantic/02-similarity.js +263 -0
- package/examples/semantic/03-word-algebra.js +295 -0
- package/examples/semantic/04-clustering.js +348 -0
- package/examples/semantic/05-classification.js +386 -0
- package/examples/semantic/06-dna-encoding.js +228 -0
- package/examples/semantic/07-search.js +304 -0
- package/examples/semantic/08-qa-system.js +278 -0
- package/examples/semantic/README.md +116 -0
- package/examples/topology/01-108-invariant.js +81 -0
- package/examples/topology/02-trefoil-constants.js +112 -0
- package/examples/topology/03-gauge-symmetry.js +112 -0
- package/examples/topology/04-free-energy-dynamics.js +124 -0
- package/examples/topology/README.md +129 -0
- package/index.js +32 -0
- package/modular.js +63 -2
- package/observer/agency.js +885 -0
- package/observer/assays.js +973 -0
- package/observer/boundary.js +1155 -0
- package/observer/entanglement.js +673 -0
- package/observer/hqe.js +1465 -0
- package/observer/index.js +158 -0
- package/observer/prsc.js +1289 -0
- package/observer/safety.js +815 -0
- package/observer/smf.js +1015 -0
- package/observer/symbolic-smf.js +726 -0
- package/observer/symbolic-temporal.js +790 -0
- package/observer/temporal.js +669 -0
- package/package.json +9 -3
- package/physics/alk-kuramoto.js +817 -0
- package/physics/index.js +23 -2
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @example Semantic Memory
|
|
3
|
+
* @description Long-term memory for AI agents using prime embeddings
|
|
4
|
+
*
|
|
5
|
+
* This example shows how to build a semantic memory system that:
|
|
6
|
+
* - Stores experiences/facts with timestamps
|
|
7
|
+
* - Retrieves by semantic similarity (not just keywords)
|
|
8
|
+
* - Supports memory decay and consolidation
|
|
9
|
+
* - Maintains associative connections between memories
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const { SemanticBackend, Hypercomplex } = require('../../modular');
|
|
13
|
+
|
|
14
|
+
// ===========================================
|
|
15
|
+
// SETUP
|
|
16
|
+
// ===========================================
|
|
17
|
+
|
|
18
|
+
const backend = new SemanticBackend({ dimension: 16 });
|
|
19
|
+
|
|
20
|
+
// ===========================================
|
|
21
|
+
// SEMANTIC MEMORY CLASS
|
|
22
|
+
// ===========================================
|
|
23
|
+
|
|
24
|
+
class SemanticMemory {
|
|
25
|
+
constructor(backend, options = {}) {
|
|
26
|
+
this.backend = backend;
|
|
27
|
+
this.memories = [];
|
|
28
|
+
this.decayRate = options.decayRate || 0.01;
|
|
29
|
+
this.similarityThreshold = options.similarityThreshold || 0.7;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Store a new memory
|
|
33
|
+
store(content, metadata = {}) {
|
|
34
|
+
const embedding = this.backend.textToOrderedState(content);
|
|
35
|
+
const memory = {
|
|
36
|
+
id: Date.now() + Math.random(),
|
|
37
|
+
content,
|
|
38
|
+
embedding,
|
|
39
|
+
timestamp: Date.now(),
|
|
40
|
+
accessCount: 0,
|
|
41
|
+
strength: 1.0,
|
|
42
|
+
metadata
|
|
43
|
+
};
|
|
44
|
+
this.memories.push(memory);
|
|
45
|
+
return memory.id;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Compute cosine similarity
|
|
49
|
+
similarity(a, b) {
|
|
50
|
+
let dot = 0, magA = 0, magB = 0;
|
|
51
|
+
for (let i = 0; i < a.c.length; i++) {
|
|
52
|
+
dot += a.c[i] * b.c[i];
|
|
53
|
+
magA += a.c[i] * a.c[i];
|
|
54
|
+
magB += b.c[i] * b.c[i];
|
|
55
|
+
}
|
|
56
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Retrieve memories by semantic query
|
|
60
|
+
recall(query, topK = 5) {
|
|
61
|
+
const queryEmbedding = this.backend.textToOrderedState(query);
|
|
62
|
+
|
|
63
|
+
// Score all memories
|
|
64
|
+
const scored = this.memories.map(mem => ({
|
|
65
|
+
memory: mem,
|
|
66
|
+
score: this.similarity(queryEmbedding, mem.embedding) * mem.strength
|
|
67
|
+
}));
|
|
68
|
+
|
|
69
|
+
// Sort by score, return top K
|
|
70
|
+
scored.sort((a, b) => b.score - a.score);
|
|
71
|
+
const results = scored.slice(0, topK);
|
|
72
|
+
|
|
73
|
+
// Update access counts (strengthens recalled memories)
|
|
74
|
+
for (const { memory } of results) {
|
|
75
|
+
memory.accessCount++;
|
|
76
|
+
memory.strength = Math.min(2.0, memory.strength * 1.1);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return results;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Find associated memories (memories that are similar to each other)
|
|
83
|
+
findAssociations(memoryId, topK = 3) {
|
|
84
|
+
const target = this.memories.find(m => m.id === memoryId);
|
|
85
|
+
if (!target) return [];
|
|
86
|
+
|
|
87
|
+
const scored = this.memories
|
|
88
|
+
.filter(m => m.id !== memoryId)
|
|
89
|
+
.map(mem => ({
|
|
90
|
+
memory: mem,
|
|
91
|
+
score: this.similarity(target.embedding, mem.embedding)
|
|
92
|
+
}));
|
|
93
|
+
|
|
94
|
+
scored.sort((a, b) => b.score - a.score);
|
|
95
|
+
return scored.slice(0, topK);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Apply memory decay (forgetting)
|
|
99
|
+
decay() {
|
|
100
|
+
const now = Date.now();
|
|
101
|
+
for (const memory of this.memories) {
|
|
102
|
+
const age = (now - memory.timestamp) / 1000 / 60; // Age in minutes
|
|
103
|
+
memory.strength *= Math.exp(-this.decayRate * age / (memory.accessCount + 1));
|
|
104
|
+
}
|
|
105
|
+
// Remove very weak memories
|
|
106
|
+
this.memories = this.memories.filter(m => m.strength > 0.1);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Consolidate similar memories
|
|
110
|
+
consolidate() {
|
|
111
|
+
const consolidated = [];
|
|
112
|
+
const merged = new Set();
|
|
113
|
+
|
|
114
|
+
for (let i = 0; i < this.memories.length; i++) {
|
|
115
|
+
if (merged.has(i)) continue;
|
|
116
|
+
|
|
117
|
+
const similar = [];
|
|
118
|
+
for (let j = i + 1; j < this.memories.length; j++) {
|
|
119
|
+
if (merged.has(j)) continue;
|
|
120
|
+
const sim = this.similarity(
|
|
121
|
+
this.memories[i].embedding,
|
|
122
|
+
this.memories[j].embedding
|
|
123
|
+
);
|
|
124
|
+
if (sim > this.similarityThreshold) {
|
|
125
|
+
similar.push(j);
|
|
126
|
+
merged.add(j);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (similar.length > 0) {
|
|
131
|
+
// Merge similar memories
|
|
132
|
+
const contents = [this.memories[i].content];
|
|
133
|
+
for (const j of similar) {
|
|
134
|
+
contents.push(this.memories[j].content);
|
|
135
|
+
}
|
|
136
|
+
const mergedContent = `[Consolidated: ${contents.join(' | ')}]`;
|
|
137
|
+
const mergedEmbedding = this.backend.textToOrderedState(mergedContent);
|
|
138
|
+
consolidated.push({
|
|
139
|
+
...this.memories[i],
|
|
140
|
+
content: mergedContent,
|
|
141
|
+
embedding: mergedEmbedding,
|
|
142
|
+
strength: this.memories[i].strength * 1.5
|
|
143
|
+
});
|
|
144
|
+
} else {
|
|
145
|
+
consolidated.push(this.memories[i]);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
this.memories = consolidated;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Get memory stats
|
|
153
|
+
stats() {
|
|
154
|
+
return {
|
|
155
|
+
total: this.memories.length,
|
|
156
|
+
avgStrength: this.memories.reduce((s, m) => s + m.strength, 0) / (this.memories.length || 1),
|
|
157
|
+
oldestAge: this.memories.length > 0
|
|
158
|
+
? (Date.now() - Math.min(...this.memories.map(m => m.timestamp))) / 1000
|
|
159
|
+
: 0
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ===========================================
|
|
165
|
+
// EXAMPLE USAGE
|
|
166
|
+
// ===========================================
|
|
167
|
+
|
|
168
|
+
console.log('TinyAleph Semantic Memory Example');
|
|
169
|
+
console.log('==================================\n');
|
|
170
|
+
|
|
171
|
+
const memory = new SemanticMemory(backend);
|
|
172
|
+
|
|
173
|
+
// Store some experiences
|
|
174
|
+
console.log('Storing memories...');
|
|
175
|
+
memory.store('The user asked about machine learning algorithms', { type: 'conversation' });
|
|
176
|
+
memory.store('We discussed neural networks and deep learning', { type: 'conversation' });
|
|
177
|
+
memory.store('The user is interested in AI applications', { type: 'preference' });
|
|
178
|
+
memory.store('Last meeting was about natural language processing', { type: 'event' });
|
|
179
|
+
memory.store('The user mentioned working on a chatbot project', { type: 'project' });
|
|
180
|
+
memory.store('We talked about weather and weekend plans', { type: 'casual' });
|
|
181
|
+
|
|
182
|
+
console.log(`Stored ${memory.stats().total} memories\n`);
|
|
183
|
+
|
|
184
|
+
// ===========================================
|
|
185
|
+
// SEMANTIC RECALL
|
|
186
|
+
// ===========================================
|
|
187
|
+
|
|
188
|
+
console.log('==================================');
|
|
189
|
+
console.log('Semantic Recall:');
|
|
190
|
+
console.log('==================================\n');
|
|
191
|
+
|
|
192
|
+
const query = 'artificial intelligence topics';
|
|
193
|
+
console.log(`Query: "${query}"\n`);
|
|
194
|
+
|
|
195
|
+
const recalled = memory.recall(query, 3);
|
|
196
|
+
for (const { memory: mem, score } of recalled) {
|
|
197
|
+
console.log(` [${score.toFixed(3)}] ${mem.content.substring(0, 50)}...`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ===========================================
|
|
201
|
+
// ASSOCIATIVE MEMORY
|
|
202
|
+
// ===========================================
|
|
203
|
+
|
|
204
|
+
console.log('\n==================================');
|
|
205
|
+
console.log('Associative Recall:');
|
|
206
|
+
console.log('==================================\n');
|
|
207
|
+
|
|
208
|
+
const mlMemory = memory.memories.find(m => m.content.includes('machine learning'));
|
|
209
|
+
console.log(`Finding associations for: "${mlMemory.content.substring(0, 40)}..."\n`);
|
|
210
|
+
|
|
211
|
+
const associations = memory.findAssociations(mlMemory.id, 3);
|
|
212
|
+
for (const { memory: mem, score } of associations) {
|
|
213
|
+
console.log(` [${score.toFixed(3)}] ${mem.content.substring(0, 50)}...`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ===========================================
|
|
217
|
+
// MEMORY CONSOLIDATION
|
|
218
|
+
// ===========================================
|
|
219
|
+
|
|
220
|
+
console.log('\n==================================');
|
|
221
|
+
console.log('Memory Consolidation:');
|
|
222
|
+
console.log('==================================\n');
|
|
223
|
+
|
|
224
|
+
// Add some similar memories
|
|
225
|
+
memory.store('Neural networks are a key AI technique', { type: 'fact' });
|
|
226
|
+
memory.store('Deep learning uses neural network architectures', { type: 'fact' });
|
|
227
|
+
|
|
228
|
+
console.log(`Before consolidation: ${memory.stats().total} memories`);
|
|
229
|
+
memory.consolidate();
|
|
230
|
+
console.log(`After consolidation: ${memory.stats().total} memories`);
|
|
231
|
+
|
|
232
|
+
// ===========================================
|
|
233
|
+
// KEY TAKEAWAYS
|
|
234
|
+
// ===========================================
|
|
235
|
+
|
|
236
|
+
console.log('\n==================================');
|
|
237
|
+
console.log('KEY TAKEAWAYS:');
|
|
238
|
+
console.log('1. Semantic memory retrieves by meaning, not keywords');
|
|
239
|
+
console.log('2. Memory strength increases with access (spaced repetition)');
|
|
240
|
+
console.log('3. Decay removes unused memories over time');
|
|
241
|
+
console.log('4. Consolidation merges similar memories');
|
|
242
|
+
console.log('5. Associations reveal hidden connections');
|
|
243
|
+
console.log('6. Use this for chatbots, agents, and knowledge systems');
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @example Reasoning Chains
|
|
3
|
+
* @description Multi-step inference using semantic transforms
|
|
4
|
+
*
|
|
5
|
+
* TinyAleph supports symbolic reasoning through transforms that
|
|
6
|
+
* manipulate hypercomplex states. This example demonstrates:
|
|
7
|
+
* - Building reasoning chains
|
|
8
|
+
* - Applying logical transformations
|
|
9
|
+
* - Tracking confidence through inference
|
|
10
|
+
* - Combining multiple evidence sources
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const { SemanticBackend, Hypercomplex } = require('../../modular');
|
|
14
|
+
|
|
15
|
+
// ===========================================
|
|
16
|
+
// SETUP
|
|
17
|
+
// ===========================================
|
|
18
|
+
|
|
19
|
+
const backend = new SemanticBackend({ dimension: 16 });
|
|
20
|
+
|
|
21
|
+
// ===========================================
|
|
22
|
+
// REASONING ENGINE
|
|
23
|
+
// ===========================================
|
|
24
|
+
|
|
25
|
+
class ReasoningEngine {
|
|
26
|
+
constructor(backend) {
|
|
27
|
+
this.backend = backend;
|
|
28
|
+
this.facts = new Map();
|
|
29
|
+
this.rules = [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Add a fact with its embedding
|
|
33
|
+
addFact(name, statement, confidence = 1.0) {
|
|
34
|
+
this.facts.set(name, {
|
|
35
|
+
statement,
|
|
36
|
+
embedding: this.backend.textToOrderedState(statement),
|
|
37
|
+
confidence
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Add an inference rule
|
|
42
|
+
addRule(name, premises, conclusion, transform = 'identity') {
|
|
43
|
+
this.rules.push({
|
|
44
|
+
name,
|
|
45
|
+
premises, // Array of fact names required
|
|
46
|
+
conclusion, // What we can conclude
|
|
47
|
+
transform // How to transform the embedding
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Compute similarity between embeddings
|
|
52
|
+
similarity(a, b) {
|
|
53
|
+
let dot = 0, magA = 0, magB = 0;
|
|
54
|
+
for (let i = 0; i < a.c.length; i++) {
|
|
55
|
+
dot += a.c[i] * b.c[i];
|
|
56
|
+
magA += a.c[i] * a.c[i];
|
|
57
|
+
magB += b.c[i] * b.c[i];
|
|
58
|
+
}
|
|
59
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Apply a reasoning step
|
|
63
|
+
reason() {
|
|
64
|
+
const newFacts = [];
|
|
65
|
+
|
|
66
|
+
for (const rule of this.rules) {
|
|
67
|
+
// Check if all premises are satisfied
|
|
68
|
+
const premisesFacts = rule.premises.map(p => this.facts.get(p));
|
|
69
|
+
if (premisesFacts.some(f => !f)) continue;
|
|
70
|
+
|
|
71
|
+
// Calculate combined confidence
|
|
72
|
+
const confidence = premisesFacts.reduce((c, f) => c * f.confidence, 1.0);
|
|
73
|
+
if (confidence < 0.1) continue; // Too uncertain
|
|
74
|
+
|
|
75
|
+
// Combine premise embeddings
|
|
76
|
+
const combined = Hypercomplex.zero(16);
|
|
77
|
+
for (const fact of premisesFacts) {
|
|
78
|
+
for (let i = 0; i < 16; i++) {
|
|
79
|
+
combined.c[i] += fact.embedding.c[i] / premisesFacts.length;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Create conclusion fact
|
|
84
|
+
const conclusionName = `${rule.name}_conclusion`;
|
|
85
|
+
if (!this.facts.has(conclusionName)) {
|
|
86
|
+
newFacts.push({
|
|
87
|
+
name: conclusionName,
|
|
88
|
+
statement: rule.conclusion,
|
|
89
|
+
embedding: combined.normalize(),
|
|
90
|
+
confidence: confidence * 0.9, // Slight confidence decay
|
|
91
|
+
derivedFrom: rule.name
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Add new facts
|
|
97
|
+
for (const fact of newFacts) {
|
|
98
|
+
this.facts.set(fact.name, fact);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return newFacts;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Query: find facts similar to a question
|
|
105
|
+
query(question, threshold = 0.5) {
|
|
106
|
+
const queryEmbed = this.backend.textToOrderedState(question);
|
|
107
|
+
const results = [];
|
|
108
|
+
|
|
109
|
+
for (const [name, fact] of this.facts) {
|
|
110
|
+
const sim = this.similarity(queryEmbed, fact.embedding);
|
|
111
|
+
if (sim > threshold) {
|
|
112
|
+
results.push({
|
|
113
|
+
name,
|
|
114
|
+
statement: fact.statement,
|
|
115
|
+
similarity: sim,
|
|
116
|
+
confidence: fact.confidence,
|
|
117
|
+
derivedFrom: fact.derivedFrom
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
results.sort((a, b) => (b.similarity * b.confidence) - (a.similarity * a.confidence));
|
|
123
|
+
return results;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Run complete reasoning chain
|
|
127
|
+
runChain(maxSteps = 5) {
|
|
128
|
+
const history = [];
|
|
129
|
+
for (let step = 0; step < maxSteps; step++) {
|
|
130
|
+
const newFacts = this.reason();
|
|
131
|
+
if (newFacts.length === 0) break;
|
|
132
|
+
history.push({ step: step + 1, derived: newFacts.map(f => f.name) });
|
|
133
|
+
}
|
|
134
|
+
return history;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ===========================================
|
|
139
|
+
// EXAMPLE: SIMPLE SYLLOGISM
|
|
140
|
+
// ===========================================
|
|
141
|
+
|
|
142
|
+
console.log('TinyAleph Reasoning Chains Example');
|
|
143
|
+
console.log('===================================\n');
|
|
144
|
+
|
|
145
|
+
const engine = new ReasoningEngine(backend);
|
|
146
|
+
|
|
147
|
+
// Add base facts
|
|
148
|
+
console.log('Adding facts...');
|
|
149
|
+
engine.addFact('all_men_mortal', 'All men are mortal');
|
|
150
|
+
engine.addFact('socrates_man', 'Socrates is a man');
|
|
151
|
+
engine.addFact('plato_man', 'Plato is a man');
|
|
152
|
+
engine.addFact('cats_animals', 'Cats are animals');
|
|
153
|
+
|
|
154
|
+
// Add inference rules
|
|
155
|
+
console.log('Adding rules...\n');
|
|
156
|
+
engine.addRule(
|
|
157
|
+
'socrates_mortality',
|
|
158
|
+
['all_men_mortal', 'socrates_man'],
|
|
159
|
+
'Socrates is mortal'
|
|
160
|
+
);
|
|
161
|
+
engine.addRule(
|
|
162
|
+
'plato_mortality',
|
|
163
|
+
['all_men_mortal', 'plato_man'],
|
|
164
|
+
'Plato is mortal'
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
// Run reasoning
|
|
168
|
+
console.log('===================================');
|
|
169
|
+
console.log('Running Reasoning Chain:');
|
|
170
|
+
console.log('===================================\n');
|
|
171
|
+
|
|
172
|
+
const history = engine.runChain();
|
|
173
|
+
for (const step of history) {
|
|
174
|
+
console.log(`Step ${step.step}: Derived ${step.derived.join(', ')}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ===========================================
|
|
178
|
+
// QUERYING THE KNOWLEDGE BASE
|
|
179
|
+
// ===========================================
|
|
180
|
+
|
|
181
|
+
console.log('\n===================================');
|
|
182
|
+
console.log('Querying the Knowledge Base:');
|
|
183
|
+
console.log('===================================\n');
|
|
184
|
+
|
|
185
|
+
const queries = [
|
|
186
|
+
'Is Socrates mortal?',
|
|
187
|
+
'What do we know about Plato?',
|
|
188
|
+
'Are cats mortal?', // Should be uncertain
|
|
189
|
+
];
|
|
190
|
+
|
|
191
|
+
for (const q of queries) {
|
|
192
|
+
console.log(`Q: "${q}"`);
|
|
193
|
+
const results = engine.query(q, 0.3);
|
|
194
|
+
if (results.length === 0) {
|
|
195
|
+
console.log(' No relevant facts found.\n');
|
|
196
|
+
} else {
|
|
197
|
+
for (const r of results.slice(0, 2)) {
|
|
198
|
+
console.log(` [sim: ${r.similarity.toFixed(2)}, conf: ${r.confidence.toFixed(2)}] ${r.statement}`);
|
|
199
|
+
if (r.derivedFrom) console.log(` (derived from: ${r.derivedFrom})`);
|
|
200
|
+
}
|
|
201
|
+
console.log();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ===========================================
|
|
206
|
+
// CONFIDENCE PROPAGATION
|
|
207
|
+
// ===========================================
|
|
208
|
+
|
|
209
|
+
console.log('===================================');
|
|
210
|
+
console.log('Confidence Propagation:');
|
|
211
|
+
console.log('===================================\n');
|
|
212
|
+
|
|
213
|
+
const engine2 = new ReasoningEngine(backend);
|
|
214
|
+
|
|
215
|
+
// Facts with varying confidence
|
|
216
|
+
engine2.addFact('birds_fly', 'Birds can fly', 0.9); // Most, not all
|
|
217
|
+
engine2.addFact('penguin_bird', 'A penguin is a bird', 1.0);
|
|
218
|
+
engine2.addFact('sparrow_bird', 'A sparrow is a bird', 1.0);
|
|
219
|
+
|
|
220
|
+
engine2.addRule('penguin_flies', ['birds_fly', 'penguin_bird'], 'A penguin can fly');
|
|
221
|
+
engine2.addRule('sparrow_flies', ['birds_fly', 'sparrow_bird'], 'A sparrow can fly');
|
|
222
|
+
|
|
223
|
+
engine2.runChain();
|
|
224
|
+
|
|
225
|
+
console.log('Derived facts with confidence:');
|
|
226
|
+
for (const [name, fact] of engine2.facts) {
|
|
227
|
+
if (fact.derivedFrom) {
|
|
228
|
+
console.log(` ${fact.statement}: ${(fact.confidence * 100).toFixed(0)}% confidence`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ===========================================
|
|
233
|
+
// KEY TAKEAWAYS
|
|
234
|
+
// ===========================================
|
|
235
|
+
|
|
236
|
+
console.log('\n===================================');
|
|
237
|
+
console.log('KEY TAKEAWAYS:');
|
|
238
|
+
console.log('1. Facts are stored as hypercomplex embeddings');
|
|
239
|
+
console.log('2. Rules combine premise embeddings to derive conclusions');
|
|
240
|
+
console.log('3. Confidence propagates and decays through inference');
|
|
241
|
+
console.log('4. Queries find semantically similar facts');
|
|
242
|
+
console.log('5. Multi-step reasoning chains build complex knowledge');
|
|
243
|
+
console.log('6. Transforms can modify meaning during inference');
|