@aleph-ai/tinyaleph 1.5.7 → 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/package.json +8 -3
- package/physics/alk-kuramoto.js +817 -0
- package/physics/index.js +23 -2
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @example Agent Architecture
|
|
3
|
+
* @description Build a simple reasoning agent using TinyAleph
|
|
4
|
+
*
|
|
5
|
+
* This example demonstrates a basic AI agent architecture that uses
|
|
6
|
+
* prime-based semantic computing for:
|
|
7
|
+
* - Goal representation and tracking
|
|
8
|
+
* - Action selection based on semantic matching
|
|
9
|
+
* - State management and memory
|
|
10
|
+
* - Plan generation and execution
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const { SemanticBackend, Hypercomplex } = require('../../modular');
|
|
14
|
+
|
|
15
|
+
// ===========================================
|
|
16
|
+
// SETUP
|
|
17
|
+
// ===========================================
|
|
18
|
+
|
|
19
|
+
const backend = new SemanticBackend({ dimension: 16 });
|
|
20
|
+
|
|
21
|
+
// ===========================================
|
|
22
|
+
// AGENT CLASS
|
|
23
|
+
// ===========================================
|
|
24
|
+
|
|
25
|
+
class SemanticAgent {
|
|
26
|
+
constructor(backend, name) {
|
|
27
|
+
this.backend = backend;
|
|
28
|
+
this.name = name;
|
|
29
|
+
this.state = new Map();
|
|
30
|
+
this.goals = [];
|
|
31
|
+
this.actions = [];
|
|
32
|
+
this.memory = [];
|
|
33
|
+
this.currentPlan = [];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Compute similarity
|
|
37
|
+
similarity(a, b) {
|
|
38
|
+
let dot = 0, magA = 0, magB = 0;
|
|
39
|
+
for (let i = 0; i < a.c.length; i++) {
|
|
40
|
+
dot += a.c[i] * b.c[i];
|
|
41
|
+
magA += a.c[i] * a.c[i];
|
|
42
|
+
magB += b.c[i] * b.c[i];
|
|
43
|
+
}
|
|
44
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Set agent state
|
|
48
|
+
setState(key, value) {
|
|
49
|
+
this.state.set(key, {
|
|
50
|
+
value,
|
|
51
|
+
embedding: this.backend.textToOrderedState(`${key}: ${value}`)
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Get combined state embedding
|
|
56
|
+
getStateEmbedding() {
|
|
57
|
+
const combined = Hypercomplex.zero(16);
|
|
58
|
+
for (const [key, data] of this.state) {
|
|
59
|
+
for (let i = 0; i < 16; i++) {
|
|
60
|
+
combined.c[i] += data.embedding.c[i];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Normalize
|
|
64
|
+
return combined.normalize();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Add a goal
|
|
68
|
+
addGoal(description, priority = 1.0) {
|
|
69
|
+
this.goals.push({
|
|
70
|
+
description,
|
|
71
|
+
embedding: this.backend.textToOrderedState(description),
|
|
72
|
+
priority,
|
|
73
|
+
achieved: false
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Register an available action
|
|
78
|
+
registerAction(name, description, preconditions, effects, executor) {
|
|
79
|
+
this.actions.push({
|
|
80
|
+
name,
|
|
81
|
+
description,
|
|
82
|
+
embedding: this.backend.textToOrderedState(description),
|
|
83
|
+
preconditions, // Array of required state conditions
|
|
84
|
+
effects, // What state changes this action causes
|
|
85
|
+
executor // Function to run the action
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Find best action for current state and goals
|
|
90
|
+
selectAction() {
|
|
91
|
+
const stateEmbed = this.getStateEmbedding();
|
|
92
|
+
|
|
93
|
+
// Find highest priority unachieved goal
|
|
94
|
+
const activeGoals = this.goals
|
|
95
|
+
.filter(g => !g.achieved)
|
|
96
|
+
.sort((a, b) => b.priority - a.priority);
|
|
97
|
+
|
|
98
|
+
if (activeGoals.length === 0) return null;
|
|
99
|
+
|
|
100
|
+
const currentGoal = activeGoals[0];
|
|
101
|
+
|
|
102
|
+
// Score actions by how well they move toward the goal
|
|
103
|
+
let bestAction = null;
|
|
104
|
+
let bestScore = -Infinity;
|
|
105
|
+
|
|
106
|
+
for (const action of this.actions) {
|
|
107
|
+
// Check preconditions
|
|
108
|
+
const preConditionsMet = action.preconditions.every(cond => {
|
|
109
|
+
const stateVal = this.state.get(cond.key);
|
|
110
|
+
return stateVal && stateVal.value === cond.value;
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (!preConditionsMet) continue;
|
|
114
|
+
|
|
115
|
+
// Score: similarity of action to goal
|
|
116
|
+
const goalAlignment = this.similarity(action.embedding, currentGoal.embedding);
|
|
117
|
+
|
|
118
|
+
// Bonus for matching current state context
|
|
119
|
+
const stateAlignment = this.similarity(action.embedding, stateEmbed);
|
|
120
|
+
|
|
121
|
+
const score = goalAlignment * 0.7 + stateAlignment * 0.3;
|
|
122
|
+
|
|
123
|
+
if (score > bestScore) {
|
|
124
|
+
bestScore = score;
|
|
125
|
+
bestAction = { action, score, goal: currentGoal };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return bestAction;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Execute selected action
|
|
133
|
+
executeAction(selection) {
|
|
134
|
+
if (!selection) return null;
|
|
135
|
+
|
|
136
|
+
const { action, goal } = selection;
|
|
137
|
+
|
|
138
|
+
// Run the action
|
|
139
|
+
const result = action.executor(this);
|
|
140
|
+
|
|
141
|
+
// Apply effects
|
|
142
|
+
for (const effect of action.effects) {
|
|
143
|
+
this.setState(effect.key, effect.value);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Record in memory
|
|
147
|
+
this.memory.push({
|
|
148
|
+
action: action.name,
|
|
149
|
+
goal: goal.description,
|
|
150
|
+
timestamp: Date.now(),
|
|
151
|
+
result
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// Check if goal is now achieved
|
|
155
|
+
const goalStateMatch = this.similarity(
|
|
156
|
+
this.getStateEmbedding(),
|
|
157
|
+
goal.embedding
|
|
158
|
+
);
|
|
159
|
+
if (goalStateMatch > 0.8) {
|
|
160
|
+
goal.achieved = true;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Run agent loop
|
|
167
|
+
run(maxSteps = 10) {
|
|
168
|
+
const log = [];
|
|
169
|
+
|
|
170
|
+
for (let step = 0; step < maxSteps; step++) {
|
|
171
|
+
const selection = this.selectAction();
|
|
172
|
+
|
|
173
|
+
if (!selection) {
|
|
174
|
+
log.push({ step: step + 1, status: 'NO_ACTION', reason: 'No valid action found' });
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const result = this.executeAction(selection);
|
|
179
|
+
|
|
180
|
+
log.push({
|
|
181
|
+
step: step + 1,
|
|
182
|
+
action: selection.action.name,
|
|
183
|
+
score: selection.score.toFixed(3),
|
|
184
|
+
goal: selection.goal.description,
|
|
185
|
+
result
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// Check if all goals achieved
|
|
189
|
+
if (this.goals.every(g => g.achieved)) {
|
|
190
|
+
log.push({ step: step + 2, status: 'COMPLETE', reason: 'All goals achieved' });
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return log;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ===========================================
|
|
200
|
+
// EXAMPLE: SIMPLE TASK AGENT
|
|
201
|
+
// ===========================================
|
|
202
|
+
|
|
203
|
+
console.log('TinyAleph Agent Architecture Example');
|
|
204
|
+
console.log('=====================================\n');
|
|
205
|
+
|
|
206
|
+
const agent = new SemanticAgent(backend, 'TaskBot');
|
|
207
|
+
|
|
208
|
+
// Set initial state
|
|
209
|
+
agent.setState('location', 'home');
|
|
210
|
+
agent.setState('has_coffee', 'no');
|
|
211
|
+
agent.setState('is_working', 'no');
|
|
212
|
+
agent.setState('task_complete', 'no');
|
|
213
|
+
|
|
214
|
+
// Add goals
|
|
215
|
+
agent.addGoal('Complete the work task successfully', 2.0);
|
|
216
|
+
agent.addGoal('Get energized with coffee', 1.0);
|
|
217
|
+
|
|
218
|
+
// Register actions
|
|
219
|
+
agent.registerAction(
|
|
220
|
+
'go_to_office',
|
|
221
|
+
'Travel to the office to start work',
|
|
222
|
+
[{ key: 'location', value: 'home' }],
|
|
223
|
+
[{ key: 'location', value: 'office' }],
|
|
224
|
+
(self) => 'Arrived at office'
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
agent.registerAction(
|
|
228
|
+
'make_coffee',
|
|
229
|
+
'Prepare and drink coffee for energy',
|
|
230
|
+
[{ key: 'location', value: 'office' }],
|
|
231
|
+
[{ key: 'has_coffee', value: 'yes' }],
|
|
232
|
+
(self) => 'Made and drank coffee'
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
agent.registerAction(
|
|
236
|
+
'start_work',
|
|
237
|
+
'Begin working on the assigned task',
|
|
238
|
+
[{ key: 'location', value: 'office' }, { key: 'has_coffee', value: 'yes' }],
|
|
239
|
+
[{ key: 'is_working', value: 'yes' }],
|
|
240
|
+
(self) => 'Started working on task'
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
agent.registerAction(
|
|
244
|
+
'finish_work',
|
|
245
|
+
'Complete the work task',
|
|
246
|
+
[{ key: 'is_working', value: 'yes' }],
|
|
247
|
+
[{ key: 'task_complete', value: 'yes' }, { key: 'is_working', value: 'no' }],
|
|
248
|
+
(self) => 'Task completed successfully!'
|
|
249
|
+
);
|
|
250
|
+
|
|
251
|
+
// Run the agent
|
|
252
|
+
console.log('Initial State:');
|
|
253
|
+
for (const [key, data] of agent.state) {
|
|
254
|
+
console.log(` ${key}: ${data.value}`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
console.log('\nGoals:');
|
|
258
|
+
for (const goal of agent.goals) {
|
|
259
|
+
console.log(` [Priority: ${goal.priority}] ${goal.description}`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
console.log('\n=====================================');
|
|
263
|
+
console.log('Agent Execution Log:');
|
|
264
|
+
console.log('=====================================\n');
|
|
265
|
+
|
|
266
|
+
const log = agent.run();
|
|
267
|
+
|
|
268
|
+
for (const entry of log) {
|
|
269
|
+
if (entry.status) {
|
|
270
|
+
console.log(`Step ${entry.step}: ${entry.status} - ${entry.reason}`);
|
|
271
|
+
} else {
|
|
272
|
+
console.log(`Step ${entry.step}: ${entry.action} [score: ${entry.score}]`);
|
|
273
|
+
console.log(` Result: ${entry.result}`);
|
|
274
|
+
console.log(` Working toward: "${entry.goal}"`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
console.log('\nFinal State:');
|
|
279
|
+
for (const [key, data] of agent.state) {
|
|
280
|
+
console.log(` ${key}: ${data.value}`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ===========================================
|
|
284
|
+
// KEY TAKEAWAYS
|
|
285
|
+
// ===========================================
|
|
286
|
+
|
|
287
|
+
console.log('\n=====================================');
|
|
288
|
+
console.log('KEY TAKEAWAYS:');
|
|
289
|
+
console.log('1. Agent state is embedded for semantic matching');
|
|
290
|
+
console.log('2. Goals are prioritized and tracked via embeddings');
|
|
291
|
+
console.log('3. Actions are selected by semantic alignment to goals');
|
|
292
|
+
console.log('4. Preconditions and effects enable planning');
|
|
293
|
+
console.log('5. Memory tracks action history for learning');
|
|
294
|
+
console.log('6. Extend with LLM integration for natural language');
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @example Hybrid AI (Symbolic + Neural)
|
|
3
|
+
* @description Combine symbolic primes with neural embeddings
|
|
4
|
+
*
|
|
5
|
+
* This example shows how to create a hybrid AI system that combines:
|
|
6
|
+
* - TinyAleph's deterministic prime embeddings (symbolic)
|
|
7
|
+
* - Neural embeddings (simulated here, real from transformers)
|
|
8
|
+
* - Best of both: interpretability + flexibility
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const { SemanticBackend, Hypercomplex } = require('../../modular');
|
|
12
|
+
|
|
13
|
+
// ===========================================
|
|
14
|
+
// SETUP
|
|
15
|
+
// ===========================================
|
|
16
|
+
|
|
17
|
+
const backend = new SemanticBackend({ dimension: 16 });
|
|
18
|
+
|
|
19
|
+
// Simulate neural embeddings (in production, use transformers)
|
|
20
|
+
function simulateNeuralEmbedding(text, dim = 16) {
|
|
21
|
+
// This simulates a neural embedding by hashing text to floats
|
|
22
|
+
const embedding = new Array(dim).fill(0);
|
|
23
|
+
for (let i = 0; i < text.length; i++) {
|
|
24
|
+
const charCode = text.charCodeAt(i);
|
|
25
|
+
embedding[i % dim] += Math.sin(charCode * (i + 1) * 0.1);
|
|
26
|
+
}
|
|
27
|
+
// Normalize
|
|
28
|
+
const mag = Math.sqrt(embedding.reduce((s, x) => s + x * x, 0));
|
|
29
|
+
return embedding.map(x => x / (mag || 1));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ===========================================
|
|
33
|
+
// HYBRID EMBEDDING SYSTEM
|
|
34
|
+
// ===========================================
|
|
35
|
+
|
|
36
|
+
class HybridEmbedding {
|
|
37
|
+
constructor(backend, options = {}) {
|
|
38
|
+
this.backend = backend;
|
|
39
|
+
this.symbolicWeight = options.symbolicWeight || 0.5;
|
|
40
|
+
this.neuralWeight = 1 - this.symbolicWeight;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Get symbolic (prime-based) embedding
|
|
44
|
+
getSymbolic(text) {
|
|
45
|
+
return this.backend.textToOrderedState(text);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Get neural embedding (simulated)
|
|
49
|
+
getNeural(text) {
|
|
50
|
+
const components = simulateNeuralEmbedding(text);
|
|
51
|
+
const h = Hypercomplex.zero(16);
|
|
52
|
+
h.c = new Float64Array(components);
|
|
53
|
+
return h;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Get hybrid embedding (weighted combination)
|
|
57
|
+
getHybrid(text) {
|
|
58
|
+
const symbolic = this.getSymbolic(text);
|
|
59
|
+
const neural = this.getNeural(text);
|
|
60
|
+
|
|
61
|
+
const hybrid = Hypercomplex.zero(16);
|
|
62
|
+
for (let i = 0; i < 16; i++) {
|
|
63
|
+
hybrid.c[i] =
|
|
64
|
+
this.symbolicWeight * symbolic.c[i] +
|
|
65
|
+
this.neuralWeight * neural.c[i];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
hybrid,
|
|
70
|
+
symbolic,
|
|
71
|
+
neural,
|
|
72
|
+
weights: { symbolic: this.symbolicWeight, neural: this.neuralWeight }
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Compare using hybrid similarity
|
|
77
|
+
similarity(a, b) {
|
|
78
|
+
let dot = 0, magA = 0, magB = 0;
|
|
79
|
+
for (let i = 0; i < a.c.length; i++) {
|
|
80
|
+
dot += a.c[i] * b.c[i];
|
|
81
|
+
magA += a.c[i] * a.c[i];
|
|
82
|
+
magB += b.c[i] * b.c[i];
|
|
83
|
+
}
|
|
84
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Analyze embedding breakdown
|
|
88
|
+
analyze(text1, text2) {
|
|
89
|
+
const emb1 = this.getHybrid(text1);
|
|
90
|
+
const emb2 = this.getHybrid(text2);
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
hybrid: this.similarity(emb1.hybrid, emb2.hybrid),
|
|
94
|
+
symbolic: this.similarity(emb1.symbolic, emb2.symbolic),
|
|
95
|
+
neural: this.similarity(emb1.neural, emb2.neural)
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ===========================================
|
|
101
|
+
// EXAMPLE: COMPARING APPROACHES
|
|
102
|
+
// ===========================================
|
|
103
|
+
|
|
104
|
+
console.log('TinyAleph Hybrid AI Example');
|
|
105
|
+
console.log('===========================\n');
|
|
106
|
+
|
|
107
|
+
const hybrid = new HybridEmbedding(backend, { symbolicWeight: 0.6 });
|
|
108
|
+
|
|
109
|
+
// Test pairs
|
|
110
|
+
const pairs = [
|
|
111
|
+
['The cat sat on the mat', 'The dog sat on the rug'],
|
|
112
|
+
['Machine learning is great', 'Deep learning is awesome'],
|
|
113
|
+
['The quick brown fox', 'A fast red wolf'],
|
|
114
|
+
['Hello world', 'Goodbye universe'], // Opposites
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
console.log('Comparing embedding approaches:');
|
|
118
|
+
console.log('(Symbolic weight: 60%, Neural weight: 40%)\n');
|
|
119
|
+
console.log('─'.repeat(60));
|
|
120
|
+
|
|
121
|
+
for (const [text1, text2] of pairs) {
|
|
122
|
+
const analysis = hybrid.analyze(text1, text2);
|
|
123
|
+
|
|
124
|
+
console.log(`\n"${text1}"`);
|
|
125
|
+
console.log(`"${text2}"`);
|
|
126
|
+
console.log(` Symbolic similarity: ${analysis.symbolic.toFixed(4)}`);
|
|
127
|
+
console.log(` Neural similarity: ${analysis.neural.toFixed(4)}`);
|
|
128
|
+
console.log(` Hybrid similarity: ${analysis.hybrid.toFixed(4)}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ===========================================
|
|
132
|
+
// WEIGHT TUNING
|
|
133
|
+
// ===========================================
|
|
134
|
+
|
|
135
|
+
console.log('\n' + '═'.repeat(60));
|
|
136
|
+
console.log('Weight Tuning Analysis:');
|
|
137
|
+
console.log('═'.repeat(60) + '\n');
|
|
138
|
+
|
|
139
|
+
const testText1 = 'Artificial intelligence research';
|
|
140
|
+
const testText2 = 'AI development work';
|
|
141
|
+
|
|
142
|
+
console.log(`Text 1: "${testText1}"`);
|
|
143
|
+
console.log(`Text 2: "${testText2}"\n`);
|
|
144
|
+
|
|
145
|
+
const weights = [0.0, 0.25, 0.5, 0.75, 1.0];
|
|
146
|
+
|
|
147
|
+
console.log('Symbolic% | Neural% | Similarity');
|
|
148
|
+
console.log('─'.repeat(35));
|
|
149
|
+
|
|
150
|
+
for (const w of weights) {
|
|
151
|
+
const h = new HybridEmbedding(backend, { symbolicWeight: w });
|
|
152
|
+
const analysis = h.analyze(testText1, testText2);
|
|
153
|
+
console.log(` ${(w * 100).toFixed(0).padStart(3)}% | ${((1 - w) * 100).toFixed(0).padStart(3)}% | ${analysis.hybrid.toFixed(4)}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ===========================================
|
|
157
|
+
// HYBRID RETRIEVAL SYSTEM
|
|
158
|
+
// ===========================================
|
|
159
|
+
|
|
160
|
+
console.log('\n' + '═'.repeat(60));
|
|
161
|
+
console.log('Hybrid Retrieval System:');
|
|
162
|
+
console.log('═'.repeat(60) + '\n');
|
|
163
|
+
|
|
164
|
+
class HybridRetriever {
|
|
165
|
+
constructor(hybridEmbedding) {
|
|
166
|
+
this.hybrid = hybridEmbedding;
|
|
167
|
+
this.documents = [];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
add(id, text, metadata = {}) {
|
|
171
|
+
const embedding = this.hybrid.getHybrid(text);
|
|
172
|
+
this.documents.push({ id, text, embedding, metadata });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
search(query, topK = 3) {
|
|
176
|
+
const queryEmb = this.hybrid.getHybrid(query);
|
|
177
|
+
|
|
178
|
+
const scored = this.documents.map(doc => ({
|
|
179
|
+
...doc,
|
|
180
|
+
score: this.hybrid.similarity(queryEmb.hybrid, doc.embedding.hybrid)
|
|
181
|
+
}));
|
|
182
|
+
|
|
183
|
+
scored.sort((a, b) => b.score - a.score);
|
|
184
|
+
return scored.slice(0, topK);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const retriever = new HybridRetriever(new HybridEmbedding(backend, { symbolicWeight: 0.5 }));
|
|
189
|
+
|
|
190
|
+
// Add documents
|
|
191
|
+
const docs = [
|
|
192
|
+
{ id: 1, text: 'Python is a popular programming language' },
|
|
193
|
+
{ id: 2, text: 'JavaScript runs in web browsers' },
|
|
194
|
+
{ id: 3, text: 'Machine learning uses statistical methods' },
|
|
195
|
+
{ id: 4, text: 'Deep neural networks have many layers' },
|
|
196
|
+
{ id: 5, text: 'Cats are popular household pets' }
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
for (const doc of docs) {
|
|
200
|
+
retriever.add(doc.id, doc.text);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const query = 'AI and neural networks';
|
|
204
|
+
console.log(`Query: "${query}"\n`);
|
|
205
|
+
|
|
206
|
+
const results = retriever.search(query);
|
|
207
|
+
console.log('Results:');
|
|
208
|
+
for (const result of results) {
|
|
209
|
+
console.log(` [${result.score.toFixed(3)}] ${result.text}`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ===========================================
|
|
213
|
+
// KEY TAKEAWAYS
|
|
214
|
+
// ===========================================
|
|
215
|
+
|
|
216
|
+
console.log('\n' + '═'.repeat(60));
|
|
217
|
+
console.log('KEY TAKEAWAYS:');
|
|
218
|
+
console.log('1. Symbolic embeddings: deterministic, interpretable');
|
|
219
|
+
console.log('2. Neural embeddings: flexible, context-aware');
|
|
220
|
+
console.log('3. Hybrid combines strengths of both approaches');
|
|
221
|
+
console.log('4. Weight tuning adapts to different use cases');
|
|
222
|
+
console.log('5. Use symbolic for precision, neural for flexibility');
|
|
223
|
+
console.log('6. Replace simulated neural with real transformers');
|