gthinking 1.0.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/README.md +283 -0
- package/analysis.ts +986 -0
- package/creativity.ts +1002 -0
- package/dist/analysis.d.ts +52 -0
- package/dist/analysis.d.ts.map +1 -0
- package/dist/analysis.js +792 -0
- package/dist/analysis.js.map +1 -0
- package/dist/creativity.d.ts +80 -0
- package/dist/creativity.d.ts.map +1 -0
- package/dist/creativity.js +778 -0
- package/dist/creativity.js.map +1 -0
- package/dist/engine.d.ts +76 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +675 -0
- package/dist/engine.js.map +1 -0
- package/dist/examples.d.ts +7 -0
- package/dist/examples.d.ts.map +1 -0
- package/dist/examples.js +506 -0
- package/dist/examples.js.map +1 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +126 -0
- package/dist/index.js.map +1 -0
- package/dist/learning.d.ts +72 -0
- package/dist/learning.d.ts.map +1 -0
- package/dist/learning.js +615 -0
- package/dist/learning.js.map +1 -0
- package/dist/planning.d.ts +58 -0
- package/dist/planning.d.ts.map +1 -0
- package/dist/planning.js +824 -0
- package/dist/planning.js.map +1 -0
- package/dist/reasoning.d.ts +72 -0
- package/dist/reasoning.d.ts.map +1 -0
- package/dist/reasoning.js +792 -0
- package/dist/reasoning.js.map +1 -0
- package/dist/search-discovery.d.ts +73 -0
- package/dist/search-discovery.d.ts.map +1 -0
- package/dist/search-discovery.js +505 -0
- package/dist/search-discovery.js.map +1 -0
- package/dist/types.d.ts +535 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +77 -0
- package/dist/types.js.map +1 -0
- package/engine.ts +928 -0
- package/examples.ts +717 -0
- package/index.ts +106 -0
- package/learning.ts +779 -0
- package/package.json +51 -0
- package/planning.ts +1028 -0
- package/reasoning.ts +1019 -0
- package/search-discovery.ts +654 -0
- package/tsconfig.json +25 -0
- package/types.ts +674 -0
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Reasoning Module
|
|
4
|
+
* Advanced logical reasoning with Chain of Thought, hypothesis testing, and multi-step problem solving
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.reasoningEngine = exports.ReasoningEngine = void 0;
|
|
8
|
+
const types_1 = require("./types");
|
|
9
|
+
const events_1 = require("events");
|
|
10
|
+
class LogicalRulesEngine {
|
|
11
|
+
constructor() {
|
|
12
|
+
this.rules = new Map();
|
|
13
|
+
}
|
|
14
|
+
addRule(rule) {
|
|
15
|
+
this.rules.set(rule.id, rule);
|
|
16
|
+
}
|
|
17
|
+
infer(facts) {
|
|
18
|
+
const inferences = [];
|
|
19
|
+
this.rules.forEach(rule => {
|
|
20
|
+
const premisesMet = rule.premises.every(premise => facts.some(fact => this.match(fact, premise)));
|
|
21
|
+
if (premisesMet) {
|
|
22
|
+
inferences.push({
|
|
23
|
+
conclusion: rule.conclusion,
|
|
24
|
+
confidence: rule.confidence,
|
|
25
|
+
rule
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
return inferences.sort((a, b) => b.confidence - a.confidence);
|
|
30
|
+
}
|
|
31
|
+
match(fact, premise) {
|
|
32
|
+
// Simple pattern matching - in real implementation use NLP
|
|
33
|
+
const factWords = fact.toLowerCase().split(/\s+/);
|
|
34
|
+
const premiseWords = premise.toLowerCase().split(/\s+/);
|
|
35
|
+
const matchCount = premiseWords.filter(pw => factWords.some(fw => fw.includes(pw) || pw.includes(fw))).length;
|
|
36
|
+
return matchCount / premiseWords.length > 0.7;
|
|
37
|
+
}
|
|
38
|
+
getRulesByDomain(domain) {
|
|
39
|
+
return Array.from(this.rules.values()).filter(r => r.domain === domain);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// ============================================================================
|
|
43
|
+
// CHAIN OF THOUGHT GENERATOR
|
|
44
|
+
// ============================================================================
|
|
45
|
+
class ChainOfThoughtGenerator {
|
|
46
|
+
constructor() {
|
|
47
|
+
this.thoughtId = 0;
|
|
48
|
+
}
|
|
49
|
+
generate(question, maxDepth = 5) {
|
|
50
|
+
const thoughts = [];
|
|
51
|
+
const rootThought = {
|
|
52
|
+
id: this.nextThoughtId(),
|
|
53
|
+
content: question,
|
|
54
|
+
children: [],
|
|
55
|
+
depth: 0,
|
|
56
|
+
confidence: 1.0,
|
|
57
|
+
type: 'question'
|
|
58
|
+
};
|
|
59
|
+
thoughts.push(rootThought);
|
|
60
|
+
// Generate thought chain
|
|
61
|
+
this.expandThought(rootThought, thoughts, maxDepth, 0);
|
|
62
|
+
// Generate final answer based on thought chain
|
|
63
|
+
const finalAnswer = this.synthesizeAnswer(thoughts);
|
|
64
|
+
return {
|
|
65
|
+
id: `cot_${Date.now()}`,
|
|
66
|
+
initialQuestion: question,
|
|
67
|
+
thoughts,
|
|
68
|
+
finalAnswer,
|
|
69
|
+
completeness: this.calculateCompleteness(thoughts)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
expandThought(parent, thoughts, maxDepth, currentDepth) {
|
|
73
|
+
if (currentDepth >= maxDepth)
|
|
74
|
+
return;
|
|
75
|
+
const expansions = this.generateExpansions(parent, currentDepth);
|
|
76
|
+
expansions.forEach(expansion => {
|
|
77
|
+
const child = {
|
|
78
|
+
id: this.nextThoughtId(),
|
|
79
|
+
content: expansion.content,
|
|
80
|
+
parentId: parent.id,
|
|
81
|
+
children: [],
|
|
82
|
+
depth: currentDepth + 1,
|
|
83
|
+
confidence: expansion.confidence * parent.confidence,
|
|
84
|
+
type: expansion.type
|
|
85
|
+
};
|
|
86
|
+
parent.children.push(child.id);
|
|
87
|
+
thoughts.push(child);
|
|
88
|
+
// Recursively expand if it's an observation or inference
|
|
89
|
+
if (expansion.type === 'observation' || expansion.type === 'inference') {
|
|
90
|
+
this.expandThought(child, thoughts, maxDepth, currentDepth + 1);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
generateExpansions(thought, depth) {
|
|
95
|
+
const expansions = [];
|
|
96
|
+
const content = thought.content.toLowerCase();
|
|
97
|
+
// Generate contextual expansions based on thought type
|
|
98
|
+
if (thought.type === 'question') {
|
|
99
|
+
expansions.push({ content: `Let me break down this question into parts.`, type: 'observation', confidence: 0.9 }, { content: `What are the key elements involved?`, type: 'observation', confidence: 0.85 }, { content: `What do I already know about this?`, type: 'observation', confidence: 0.8 });
|
|
100
|
+
}
|
|
101
|
+
else if (thought.type === 'observation') {
|
|
102
|
+
expansions.push({ content: `This suggests that...`, type: 'inference', confidence: 0.75 }, { content: `One implication is...`, type: 'inference', confidence: 0.7 }, { content: `However, we must also consider...`, type: 'observation', confidence: 0.65 });
|
|
103
|
+
}
|
|
104
|
+
else if (thought.type === 'inference') {
|
|
105
|
+
if (depth < 3) {
|
|
106
|
+
expansions.push({ content: `Building on this inference...`, type: 'inference', confidence: 0.7 }, { content: `This leads to the conclusion that...`, type: 'conclusion', confidence: 0.8 });
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
expansions.push({ content: `Therefore, we can conclude...`, type: 'conclusion', confidence: 0.85 });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return expansions;
|
|
113
|
+
}
|
|
114
|
+
synthesizeAnswer(thoughts) {
|
|
115
|
+
const conclusions = thoughts.filter(t => t.type === 'conclusion');
|
|
116
|
+
const inferences = thoughts.filter(t => t.type === 'inference');
|
|
117
|
+
if (conclusions.length > 0) {
|
|
118
|
+
const topConclusion = conclusions.sort((a, b) => b.confidence - a.confidence)[0];
|
|
119
|
+
return topConclusion.content + ' Based on the analysis: ' +
|
|
120
|
+
inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
|
|
121
|
+
}
|
|
122
|
+
return 'Based on the analysis: ' + inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
|
|
123
|
+
}
|
|
124
|
+
calculateCompleteness(thoughts) {
|
|
125
|
+
const hasQuestion = thoughts.some(t => t.type === 'question');
|
|
126
|
+
const hasObservations = thoughts.some(t => t.type === 'observation');
|
|
127
|
+
const hasInferences = thoughts.some(t => t.type === 'inference');
|
|
128
|
+
const hasConclusions = thoughts.some(t => t.type === 'conclusion');
|
|
129
|
+
const elements = [hasQuestion, hasObservations, hasInferences, hasConclusions];
|
|
130
|
+
return elements.filter(Boolean).length / elements.length;
|
|
131
|
+
}
|
|
132
|
+
nextThoughtId() {
|
|
133
|
+
return `thought_${++this.thoughtId}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// ============================================================================
|
|
137
|
+
// HYPOTHESIS MANAGER
|
|
138
|
+
// ============================================================================
|
|
139
|
+
class HypothesisManager {
|
|
140
|
+
constructor() {
|
|
141
|
+
this.hypotheses = new Map();
|
|
142
|
+
}
|
|
143
|
+
createHypothesis(statement) {
|
|
144
|
+
const hypothesis = {
|
|
145
|
+
id: `hypothesis_${Date.now()}`,
|
|
146
|
+
statement,
|
|
147
|
+
supportingEvidence: [],
|
|
148
|
+
contradictingEvidence: [],
|
|
149
|
+
tests: [],
|
|
150
|
+
status: 'proposed',
|
|
151
|
+
confidence: 0.5
|
|
152
|
+
};
|
|
153
|
+
this.hypotheses.set(hypothesis.id, hypothesis);
|
|
154
|
+
return hypothesis;
|
|
155
|
+
}
|
|
156
|
+
addEvidence(hypothesisId, evidence, supporting) {
|
|
157
|
+
const hypothesis = this.hypotheses.get(hypothesisId);
|
|
158
|
+
if (!hypothesis)
|
|
159
|
+
throw new Error(`Hypothesis ${hypothesisId} not found`);
|
|
160
|
+
if (supporting) {
|
|
161
|
+
hypothesis.supportingEvidence.push(evidence);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
hypothesis.contradictingEvidence.push(evidence);
|
|
165
|
+
}
|
|
166
|
+
this.updateConfidence(hypothesis);
|
|
167
|
+
}
|
|
168
|
+
addTest(hypothesisId, test) {
|
|
169
|
+
const hypothesis = this.hypotheses.get(hypothesisId);
|
|
170
|
+
if (!hypothesis)
|
|
171
|
+
throw new Error(`Hypothesis ${hypothesisId} not found`);
|
|
172
|
+
hypothesis.tests.push(test);
|
|
173
|
+
}
|
|
174
|
+
runTest(hypothesisId, testId, outcome) {
|
|
175
|
+
const hypothesis = this.hypotheses.get(hypothesisId);
|
|
176
|
+
if (!hypothesis)
|
|
177
|
+
throw new Error(`Hypothesis ${hypothesisId} not found`);
|
|
178
|
+
const test = hypothesis.tests.find(t => t.id === testId);
|
|
179
|
+
if (!test)
|
|
180
|
+
throw new Error(`Test ${testId} not found`);
|
|
181
|
+
test.actualOutcome = outcome;
|
|
182
|
+
test.passed = outcome === test.expectedOutcome;
|
|
183
|
+
this.updateStatus(hypothesis);
|
|
184
|
+
}
|
|
185
|
+
updateConfidence(hypothesis) {
|
|
186
|
+
const supportWeight = hypothesis.supportingEvidence.reduce((sum, e) => sum + e.strength, 0);
|
|
187
|
+
const contradictWeight = hypothesis.contradictingEvidence.reduce((sum, e) => sum + e.strength, 0);
|
|
188
|
+
const totalWeight = supportWeight + contradictWeight;
|
|
189
|
+
if (totalWeight === 0) {
|
|
190
|
+
hypothesis.confidence = 0.5;
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
hypothesis.confidence = supportWeight / totalWeight;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
updateStatus(hypothesis) {
|
|
197
|
+
const completedTests = hypothesis.tests.filter(t => t.passed !== undefined);
|
|
198
|
+
const passedTests = completedTests.filter(t => t.passed);
|
|
199
|
+
if (completedTests.length === 0) {
|
|
200
|
+
hypothesis.status = 'testing';
|
|
201
|
+
}
|
|
202
|
+
else if (passedTests.length === completedTests.length && hypothesis.confidence > 0.8) {
|
|
203
|
+
hypothesis.status = 'confirmed';
|
|
204
|
+
}
|
|
205
|
+
else if (passedTests.length === 0 && completedTests.length > 2) {
|
|
206
|
+
hypothesis.status = 'rejected';
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
hypothesis.status = 'testing';
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
getHypothesis(id) {
|
|
213
|
+
return this.hypotheses.get(id);
|
|
214
|
+
}
|
|
215
|
+
getAllHypotheses() {
|
|
216
|
+
return Array.from(this.hypotheses.values());
|
|
217
|
+
}
|
|
218
|
+
getHypothesesByStatus(status) {
|
|
219
|
+
return this.getAllHypotheses().filter(h => h.status === status);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// ============================================================================
|
|
223
|
+
// PROBLEM DECOMPOSITION ENGINE
|
|
224
|
+
// ============================================================================
|
|
225
|
+
class ProblemDecompositionEngine {
|
|
226
|
+
decompose(problem) {
|
|
227
|
+
const subProblems = [];
|
|
228
|
+
const dependencies = [];
|
|
229
|
+
// Analyze problem structure
|
|
230
|
+
const problemParts = this.identifyProblemParts(problem);
|
|
231
|
+
// Create sub-problems
|
|
232
|
+
problemParts.forEach((part, index) => {
|
|
233
|
+
const subProblem = {
|
|
234
|
+
id: `sub_${index}`,
|
|
235
|
+
description: part.description,
|
|
236
|
+
difficulty: part.difficulty,
|
|
237
|
+
estimatedTime: part.estimatedTime,
|
|
238
|
+
prerequisites: [],
|
|
239
|
+
status: types_1.TaskStatus.PENDING
|
|
240
|
+
};
|
|
241
|
+
subProblems.push(subProblem);
|
|
242
|
+
});
|
|
243
|
+
// Identify dependencies
|
|
244
|
+
subProblems.forEach((sub, i) => {
|
|
245
|
+
subProblems.forEach((other, j) => {
|
|
246
|
+
if (i !== j && this.hasDependency(sub, other)) {
|
|
247
|
+
dependencies.push({
|
|
248
|
+
from: sub.id,
|
|
249
|
+
to: other.id,
|
|
250
|
+
type: 'requires'
|
|
251
|
+
});
|
|
252
|
+
sub.prerequisites.push(other.id);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
// Determine solution strategy
|
|
257
|
+
const solutionStrategy = this.determineStrategy(subProblems, dependencies);
|
|
258
|
+
return {
|
|
259
|
+
id: `decomp_${Date.now()}`,
|
|
260
|
+
originalProblem: problem,
|
|
261
|
+
subProblems,
|
|
262
|
+
dependencies,
|
|
263
|
+
solutionStrategy
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
identifyProblemParts(problem) {
|
|
267
|
+
const parts = [];
|
|
268
|
+
// Simple decomposition based on keywords
|
|
269
|
+
const keywords = {
|
|
270
|
+
research: { difficulty: 0.7, time: 120 },
|
|
271
|
+
analyze: { difficulty: 0.6, time: 90 },
|
|
272
|
+
design: { difficulty: 0.8, time: 180 },
|
|
273
|
+
implement: { difficulty: 0.75, time: 240 },
|
|
274
|
+
test: { difficulty: 0.5, time: 60 },
|
|
275
|
+
optimize: { difficulty: 0.85, time: 150 },
|
|
276
|
+
evaluate: { difficulty: 0.55, time: 45 },
|
|
277
|
+
plan: { difficulty: 0.4, time: 30 }
|
|
278
|
+
};
|
|
279
|
+
const problemLower = problem.toLowerCase();
|
|
280
|
+
Object.entries(keywords).forEach(([keyword, config]) => {
|
|
281
|
+
if (problemLower.includes(keyword)) {
|
|
282
|
+
parts.push({
|
|
283
|
+
description: `${keyword.charAt(0).toUpperCase() + keyword.slice(1)} phase of the problem`,
|
|
284
|
+
difficulty: config.difficulty,
|
|
285
|
+
estimatedTime: config.time
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
// If no specific parts identified, create generic ones
|
|
290
|
+
if (parts.length === 0) {
|
|
291
|
+
parts.push({ description: 'Understand the problem', difficulty: 0.4, estimatedTime: 30 }, { description: 'Research and gather information', difficulty: 0.6, estimatedTime: 60 }, { description: 'Develop solution approach', difficulty: 0.7, estimatedTime: 90 }, { description: 'Implement the solution', difficulty: 0.75, estimatedTime: 120 }, { description: 'Verify and validate', difficulty: 0.5, estimatedTime: 45 });
|
|
292
|
+
}
|
|
293
|
+
return parts;
|
|
294
|
+
}
|
|
295
|
+
hasDependency(sub1, sub2) {
|
|
296
|
+
// Check if sub1 requires sub2 based on description
|
|
297
|
+
const orderIndicators = {
|
|
298
|
+
'understand': [],
|
|
299
|
+
'research': ['understand'],
|
|
300
|
+
'design': ['research', 'understand'],
|
|
301
|
+
'implement': ['design', 'research'],
|
|
302
|
+
'test': ['implement'],
|
|
303
|
+
'optimize': ['test', 'implement'],
|
|
304
|
+
'evaluate': ['test', 'implement', 'optimize'],
|
|
305
|
+
'plan': ['understand', 'research']
|
|
306
|
+
};
|
|
307
|
+
const sub1Keywords = Object.keys(orderIndicators).filter(k => sub1.description.toLowerCase().includes(k));
|
|
308
|
+
const sub2Keywords = Object.keys(orderIndicators).filter(k => sub2.description.toLowerCase().includes(k));
|
|
309
|
+
return sub1Keywords.some(k1 => sub2Keywords.some(k2 => orderIndicators[k1]?.includes(k2)));
|
|
310
|
+
}
|
|
311
|
+
determineStrategy(subProblems, dependencies) {
|
|
312
|
+
const criticalPath = this.findCriticalPath(subProblems, dependencies);
|
|
313
|
+
const totalTime = subProblems.reduce((sum, sp) => sum + sp.estimatedTime, 0);
|
|
314
|
+
const avgDifficulty = subProblems.reduce((sum, sp) => sum + sp.difficulty, 0) / subProblems.length;
|
|
315
|
+
if (avgDifficulty > 0.7) {
|
|
316
|
+
return `Divide-and-conquer approach recommended. Tackle critical path first: ${criticalPath.join(' → ')}. Estimated total time: ${totalTime} minutes.`;
|
|
317
|
+
}
|
|
318
|
+
else if (dependencies.length > subProblems.length) {
|
|
319
|
+
return `Sequential approach with careful dependency management. Start with: ${criticalPath[0]}.`;
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
return `Parallel processing possible. Focus on: ${criticalPath.join(', ')}.`;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
findCriticalPath(subProblems, dependencies) {
|
|
326
|
+
// Simplified critical path - in real implementation use topological sort
|
|
327
|
+
const visited = new Set();
|
|
328
|
+
const path = [];
|
|
329
|
+
const visit = (subId) => {
|
|
330
|
+
if (visited.has(subId))
|
|
331
|
+
return;
|
|
332
|
+
visited.add(subId);
|
|
333
|
+
const prereqs = dependencies
|
|
334
|
+
.filter(d => d.to === subId && d.type === 'requires')
|
|
335
|
+
.map(d => d.from);
|
|
336
|
+
prereqs.forEach(visit);
|
|
337
|
+
const sub = subProblems.find(s => s.id === subId);
|
|
338
|
+
if (sub)
|
|
339
|
+
path.push(sub.description);
|
|
340
|
+
};
|
|
341
|
+
subProblems.forEach(sp => visit(sp.id));
|
|
342
|
+
return path.length > 0 ? path : subProblems.map(s => s.description);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
// ============================================================================
|
|
346
|
+
// REASONING ENGINE
|
|
347
|
+
// ============================================================================
|
|
348
|
+
class ReasoningEngine extends events_1.EventEmitter {
|
|
349
|
+
constructor() {
|
|
350
|
+
super();
|
|
351
|
+
this.sessions = new Map();
|
|
352
|
+
this.rulesEngine = new LogicalRulesEngine();
|
|
353
|
+
this.cotGenerator = new ChainOfThoughtGenerator();
|
|
354
|
+
this.hypothesisManager = new HypothesisManager();
|
|
355
|
+
this.decompositionEngine = new ProblemDecompositionEngine();
|
|
356
|
+
this.initializeDefaultRules();
|
|
357
|
+
}
|
|
358
|
+
initializeDefaultRules() {
|
|
359
|
+
// Add some default logical rules
|
|
360
|
+
this.rulesEngine.addRule({
|
|
361
|
+
id: 'rule_cause_effect',
|
|
362
|
+
premises: ['A causes B', 'A occurred'],
|
|
363
|
+
conclusion: 'B will occur',
|
|
364
|
+
confidence: 0.8,
|
|
365
|
+
domain: 'causality'
|
|
366
|
+
});
|
|
367
|
+
this.rulesEngine.addRule({
|
|
368
|
+
id: 'rule_generalization',
|
|
369
|
+
premises: ['All X are Y', 'Z is X'],
|
|
370
|
+
conclusion: 'Z is Y',
|
|
371
|
+
confidence: 0.95,
|
|
372
|
+
domain: 'logic'
|
|
373
|
+
});
|
|
374
|
+
this.rulesEngine.addRule({
|
|
375
|
+
id: 'rule_analogy',
|
|
376
|
+
premises: ['A is similar to B', 'A has property P'],
|
|
377
|
+
conclusion: 'B likely has property P',
|
|
378
|
+
confidence: 0.7,
|
|
379
|
+
domain: 'analogy'
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Perform reasoning on a problem
|
|
384
|
+
*/
|
|
385
|
+
async reason(problem, options = {}) {
|
|
386
|
+
const { type = types_1.ReasoningType.DEDUCTIVE, maxSteps = 5, generateCOT = true } = options;
|
|
387
|
+
const sessionId = this.generateId();
|
|
388
|
+
const startTime = Date.now();
|
|
389
|
+
const session = {
|
|
390
|
+
id: sessionId,
|
|
391
|
+
problem,
|
|
392
|
+
type,
|
|
393
|
+
steps: [],
|
|
394
|
+
confidence: 0,
|
|
395
|
+
startTime: new Date()
|
|
396
|
+
};
|
|
397
|
+
this.sessions.set(sessionId, session);
|
|
398
|
+
this.emit('reasoning_start', {
|
|
399
|
+
id: sessionId,
|
|
400
|
+
stage: types_1.ThinkingStage.REASONING,
|
|
401
|
+
timestamp: new Date(),
|
|
402
|
+
data: { problem, type }
|
|
403
|
+
});
|
|
404
|
+
try {
|
|
405
|
+
// Generate Chain of Thought if enabled
|
|
406
|
+
let cot;
|
|
407
|
+
if (generateCOT) {
|
|
408
|
+
cot = this.cotGenerator.generate(problem, maxSteps);
|
|
409
|
+
}
|
|
410
|
+
// Execute reasoning based on type
|
|
411
|
+
switch (type) {
|
|
412
|
+
case types_1.ReasoningType.DEDUCTIVE:
|
|
413
|
+
await this.executeDeductiveReasoning(session, maxSteps);
|
|
414
|
+
break;
|
|
415
|
+
case types_1.ReasoningType.INDUCTIVE:
|
|
416
|
+
await this.executeInductiveReasoning(session, maxSteps);
|
|
417
|
+
break;
|
|
418
|
+
case types_1.ReasoningType.ABDUCTIVE:
|
|
419
|
+
await this.executeAbductiveReasoning(session, maxSteps);
|
|
420
|
+
break;
|
|
421
|
+
case types_1.ReasoningType.ANALOGICAL:
|
|
422
|
+
await this.executeAnalogicalReasoning(session, maxSteps);
|
|
423
|
+
break;
|
|
424
|
+
case types_1.ReasoningType.CAUSAL:
|
|
425
|
+
await this.executeCausalReasoning(session, maxSteps);
|
|
426
|
+
break;
|
|
427
|
+
case types_1.ReasoningType.COUNTERFACTUAL:
|
|
428
|
+
await this.executeCounterfactualReasoning(session, maxSteps);
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
// Generate conclusion
|
|
432
|
+
session.conclusion = this.generateConclusion(session, cot);
|
|
433
|
+
session.confidence = this.calculateSessionConfidence(session);
|
|
434
|
+
session.endTime = new Date();
|
|
435
|
+
this.emit('reasoning_complete', {
|
|
436
|
+
id: sessionId,
|
|
437
|
+
stage: types_1.ThinkingStage.REASONING,
|
|
438
|
+
timestamp: new Date(),
|
|
439
|
+
data: {
|
|
440
|
+
session,
|
|
441
|
+
steps: session.steps.length,
|
|
442
|
+
confidence: session.confidence
|
|
443
|
+
}
|
|
444
|
+
});
|
|
445
|
+
return session;
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
this.emit('reasoning_error', {
|
|
449
|
+
id: sessionId,
|
|
450
|
+
stage: types_1.ThinkingStage.REASONING,
|
|
451
|
+
timestamp: new Date(),
|
|
452
|
+
data: { error }
|
|
453
|
+
});
|
|
454
|
+
throw new types_1.ThinkingError(`Reasoning failed: ${error instanceof Error ? error.message : 'Unknown error'}`, types_1.ThinkingStage.REASONING, true, error instanceof Error ? error : undefined);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
async executeDeductiveReasoning(session, maxSteps) {
|
|
458
|
+
const facts = this.extractFacts(session.problem);
|
|
459
|
+
for (let i = 0; i < maxSteps; i++) {
|
|
460
|
+
const inferences = this.rulesEngine.infer(facts);
|
|
461
|
+
if (inferences.length === 0)
|
|
462
|
+
break;
|
|
463
|
+
const topInference = inferences[0];
|
|
464
|
+
const step = {
|
|
465
|
+
id: `step_${i}`,
|
|
466
|
+
stepNumber: i + 1,
|
|
467
|
+
premise: facts.join(', '),
|
|
468
|
+
inference: topInference.conclusion,
|
|
469
|
+
evidence: [{
|
|
470
|
+
source: 'logical_rules',
|
|
471
|
+
excerpt: `Rule: ${topInference.rule.premises.join(' AND ')} => ${topInference.rule.conclusion}`,
|
|
472
|
+
location: 'rules_engine',
|
|
473
|
+
strength: topInference.confidence
|
|
474
|
+
}],
|
|
475
|
+
assumptions: topInference.rule.premises,
|
|
476
|
+
confidence: topInference.confidence,
|
|
477
|
+
nextSteps: inferences.slice(1).map(inf => inf.conclusion)
|
|
478
|
+
};
|
|
479
|
+
session.steps.push(step);
|
|
480
|
+
facts.push(topInference.conclusion);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async executeInductiveReasoning(session, maxSteps) {
|
|
484
|
+
// Pattern-based reasoning from specific to general
|
|
485
|
+
const observations = this.extractObservations(session.problem);
|
|
486
|
+
for (let i = 0; i < maxSteps && i < observations.length; i++) {
|
|
487
|
+
const pattern = this.identifyPattern(observations.slice(0, i + 1));
|
|
488
|
+
const step = {
|
|
489
|
+
id: `step_${i}`,
|
|
490
|
+
stepNumber: i + 1,
|
|
491
|
+
premise: observations.slice(0, i + 1).join('; '),
|
|
492
|
+
inference: `Pattern identified: ${pattern.description}`,
|
|
493
|
+
evidence: observations.map(obs => ({
|
|
494
|
+
source: 'observation',
|
|
495
|
+
excerpt: obs,
|
|
496
|
+
location: 'problem_statement',
|
|
497
|
+
strength: 0.7
|
|
498
|
+
})),
|
|
499
|
+
assumptions: ['Observations are representative', 'Pattern will continue'],
|
|
500
|
+
confidence: pattern.confidence,
|
|
501
|
+
nextSteps: ['Test pattern with new data', 'Formulate general rule']
|
|
502
|
+
};
|
|
503
|
+
session.steps.push(step);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async executeAbductiveReasoning(session, maxSteps) {
|
|
507
|
+
// Inference to the best explanation
|
|
508
|
+
const observations = this.extractObservations(session.problem);
|
|
509
|
+
const possibleExplanations = this.generateExplanations(observations);
|
|
510
|
+
for (let i = 0; i < maxSteps && i < possibleExplanations.length; i++) {
|
|
511
|
+
const explanation = possibleExplanations[i];
|
|
512
|
+
const step = {
|
|
513
|
+
id: `step_${i}`,
|
|
514
|
+
stepNumber: i + 1,
|
|
515
|
+
premise: observations.join('; '),
|
|
516
|
+
inference: `Best explanation: ${explanation.description}`,
|
|
517
|
+
evidence: [{
|
|
518
|
+
source: 'abductive_inference',
|
|
519
|
+
excerpt: explanation.supportingEvidence,
|
|
520
|
+
location: 'generated_explanation',
|
|
521
|
+
strength: explanation.plausibility
|
|
522
|
+
}],
|
|
523
|
+
assumptions: explanation.assumptions,
|
|
524
|
+
confidence: explanation.plausibility,
|
|
525
|
+
nextSteps: possibleExplanations.slice(i + 1).map(e => `Alternative: ${e.description}`)
|
|
526
|
+
};
|
|
527
|
+
session.steps.push(step);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async executeAnalogicalReasoning(session, maxSteps) {
|
|
531
|
+
// Reasoning by analogy
|
|
532
|
+
const sourceDomain = this.extractDomain(session.problem);
|
|
533
|
+
const analogies = this.findAnalogies(sourceDomain);
|
|
534
|
+
for (let i = 0; i < maxSteps && i < analogies.length; i++) {
|
|
535
|
+
const analogy = analogies[i];
|
|
536
|
+
const step = {
|
|
537
|
+
id: `step_${i}`,
|
|
538
|
+
stepNumber: i + 1,
|
|
539
|
+
premise: `Source domain: ${sourceDomain}`,
|
|
540
|
+
inference: `Analogous to: ${analogy.targetDomain}. Therefore: ${analogy.inferredProperty}`,
|
|
541
|
+
evidence: [{
|
|
542
|
+
source: 'analogy',
|
|
543
|
+
excerpt: `Similarity: ${analogy.similarityDescription}`,
|
|
544
|
+
location: 'analogy_mapping',
|
|
545
|
+
strength: analogy.similarityScore
|
|
546
|
+
}],
|
|
547
|
+
assumptions: ['Analogous domains share relevant properties'],
|
|
548
|
+
confidence: analogy.similarityScore,
|
|
549
|
+
nextSteps: analogies.slice(i + 1).map(a => `Alternative analogy: ${a.targetDomain}`)
|
|
550
|
+
};
|
|
551
|
+
session.steps.push(step);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async executeCausalReasoning(session, maxSteps) {
|
|
555
|
+
// Cause-effect reasoning
|
|
556
|
+
const causalChain = this.identifyCausalChain(session.problem);
|
|
557
|
+
for (let i = 0; i < maxSteps && i < causalChain.length; i++) {
|
|
558
|
+
const causalLink = causalChain[i];
|
|
559
|
+
const step = {
|
|
560
|
+
id: `step_${i}`,
|
|
561
|
+
stepNumber: i + 1,
|
|
562
|
+
premise: `Cause: ${causalLink.cause}`,
|
|
563
|
+
inference: `Effect: ${causalLink.effect}`,
|
|
564
|
+
evidence: [{
|
|
565
|
+
source: 'causal_analysis',
|
|
566
|
+
excerpt: causalLink.mechanism,
|
|
567
|
+
location: 'causal_chain',
|
|
568
|
+
strength: causalLink.confidence
|
|
569
|
+
}],
|
|
570
|
+
assumptions: ['Causal relationship is consistent', 'No confounding factors'],
|
|
571
|
+
confidence: causalLink.confidence,
|
|
572
|
+
nextSteps: causalChain.slice(i + 1).map(c => `Next effect: ${c.effect}`)
|
|
573
|
+
};
|
|
574
|
+
session.steps.push(step);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
async executeCounterfactualReasoning(session, maxSteps) {
|
|
578
|
+
// What-if reasoning
|
|
579
|
+
const counterfactuals = this.generateCounterfactuals(session.problem);
|
|
580
|
+
for (let i = 0; i < maxSteps && i < counterfactuals.length; i++) {
|
|
581
|
+
const cf = counterfactuals[i];
|
|
582
|
+
const step = {
|
|
583
|
+
id: `step_${i}`,
|
|
584
|
+
stepNumber: i + 1,
|
|
585
|
+
premise: `Actual: ${cf.actual}`,
|
|
586
|
+
inference: `If ${cf.condition}, then ${cf.outcome}`,
|
|
587
|
+
evidence: [{
|
|
588
|
+
source: 'counterfactual',
|
|
589
|
+
excerpt: cf.reasoning,
|
|
590
|
+
location: 'counterfactual_analysis',
|
|
591
|
+
strength: cf.plausibility
|
|
592
|
+
}],
|
|
593
|
+
assumptions: cf.assumptions,
|
|
594
|
+
confidence: cf.plausibility,
|
|
595
|
+
nextSteps: counterfactuals.slice(i + 1).map(c => `Alternative: If ${c.condition}`)
|
|
596
|
+
};
|
|
597
|
+
session.steps.push(step);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Create and test a hypothesis
|
|
602
|
+
*/
|
|
603
|
+
createHypothesis(statement) {
|
|
604
|
+
return this.hypothesisManager.createHypothesis(statement);
|
|
605
|
+
}
|
|
606
|
+
addEvidenceToHypothesis(hypothesisId, evidence, supporting) {
|
|
607
|
+
this.hypothesisManager.addEvidence(hypothesisId, evidence, supporting);
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Decompose a complex problem
|
|
611
|
+
*/
|
|
612
|
+
decomposeProblem(problem) {
|
|
613
|
+
return this.decompositionEngine.decompose(problem);
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Generate Chain of Thought for a question
|
|
617
|
+
*/
|
|
618
|
+
generateChainOfThought(question, maxDepth) {
|
|
619
|
+
return this.cotGenerator.generate(question, maxDepth);
|
|
620
|
+
}
|
|
621
|
+
// Helper methods
|
|
622
|
+
generateId() {
|
|
623
|
+
return `reasoning_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
624
|
+
}
|
|
625
|
+
extractFacts(problem) {
|
|
626
|
+
// Simplified fact extraction
|
|
627
|
+
return problem
|
|
628
|
+
.split(/[.!?]+/)
|
|
629
|
+
.map(s => s.trim())
|
|
630
|
+
.filter(s => s.length > 10);
|
|
631
|
+
}
|
|
632
|
+
extractObservations(problem) {
|
|
633
|
+
return this.extractFacts(problem);
|
|
634
|
+
}
|
|
635
|
+
identifyPattern(observations) {
|
|
636
|
+
// Simplified pattern identification
|
|
637
|
+
const commonWords = this.findCommonElements(observations);
|
|
638
|
+
return {
|
|
639
|
+
description: `Common elements: ${commonWords.join(', ')}`,
|
|
640
|
+
confidence: Math.min(0.9, observations.length * 0.2)
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
findCommonElements(strings) {
|
|
644
|
+
if (strings.length === 0)
|
|
645
|
+
return [];
|
|
646
|
+
const wordSets = strings.map(s => new Set(s.toLowerCase().split(/\s+/)));
|
|
647
|
+
const common = Array.from(wordSets[0]).filter(word => wordSets.every(set => set.has(word)) && word.length > 4);
|
|
648
|
+
return common.slice(0, 5);
|
|
649
|
+
}
|
|
650
|
+
generateExplanations(observations) {
|
|
651
|
+
return [
|
|
652
|
+
{
|
|
653
|
+
description: `Explanation based on ${observations.length} observations`,
|
|
654
|
+
plausibility: 0.7,
|
|
655
|
+
supportingEvidence: observations.join('; '),
|
|
656
|
+
assumptions: ['Observations are accurate', 'No hidden factors']
|
|
657
|
+
}
|
|
658
|
+
];
|
|
659
|
+
}
|
|
660
|
+
extractDomain(problem) {
|
|
661
|
+
const domains = ['business', 'technology', 'science', 'health', 'education', 'finance'];
|
|
662
|
+
const problemLower = problem.toLowerCase();
|
|
663
|
+
return domains.find(d => problemLower.includes(d)) || 'general';
|
|
664
|
+
}
|
|
665
|
+
findAnalogies(sourceDomain) {
|
|
666
|
+
const analogies = {
|
|
667
|
+
business: [
|
|
668
|
+
{ target: 'ecosystem', property: 'interconnected components', similarity: 'both have interdependent parts' },
|
|
669
|
+
{ target: 'organism', property: 'growth and adaptation', similarity: 'both evolve over time' }
|
|
670
|
+
],
|
|
671
|
+
technology: [
|
|
672
|
+
{ target: 'biology', property: 'modular components', similarity: 'both use building blocks' },
|
|
673
|
+
{ target: 'language', property: 'syntax and structure', similarity: 'both have rules and patterns' }
|
|
674
|
+
]
|
|
675
|
+
};
|
|
676
|
+
return (analogies[sourceDomain] || []).map(a => ({
|
|
677
|
+
targetDomain: a.target,
|
|
678
|
+
inferredProperty: a.property,
|
|
679
|
+
similarityDescription: a.similarity,
|
|
680
|
+
similarityScore: 0.7
|
|
681
|
+
}));
|
|
682
|
+
}
|
|
683
|
+
identifyCausalChain(problem) {
|
|
684
|
+
const causalIndicators = ['causes', 'leads to', 'results in', 'because', 'due to', 'therefore'];
|
|
685
|
+
const chain = [];
|
|
686
|
+
causalIndicators.forEach(indicator => {
|
|
687
|
+
const regex = new RegExp(`(.+?)\\s+${indicator}\\s+(.+?)[.!?]`, 'gi');
|
|
688
|
+
let match;
|
|
689
|
+
while ((match = regex.exec(problem)) !== null) {
|
|
690
|
+
chain.push({
|
|
691
|
+
cause: match[1].trim(),
|
|
692
|
+
effect: match[2].trim(),
|
|
693
|
+
mechanism: `${match[1].trim()} ${indicator} ${match[2].trim()}`,
|
|
694
|
+
confidence: 0.75
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
return chain.length > 0 ? chain : [{
|
|
699
|
+
cause: 'Initial condition',
|
|
700
|
+
effect: 'Observed outcome',
|
|
701
|
+
mechanism: 'Causal relationship inferred from context',
|
|
702
|
+
confidence: 0.5
|
|
703
|
+
}];
|
|
704
|
+
}
|
|
705
|
+
generateCounterfactuals(problem) {
|
|
706
|
+
return [
|
|
707
|
+
{
|
|
708
|
+
actual: problem,
|
|
709
|
+
condition: 'conditions were different',
|
|
710
|
+
outcome: 'outcome would change',
|
|
711
|
+
reasoning: 'Counterfactual analysis based on problem context',
|
|
712
|
+
plausibility: 0.6,
|
|
713
|
+
assumptions: ['Minimal change principle', 'Ceteris paribus']
|
|
714
|
+
}
|
|
715
|
+
];
|
|
716
|
+
}
|
|
717
|
+
generateConclusion(session, cot) {
|
|
718
|
+
const stepConclusions = session.steps.map(s => s.inference);
|
|
719
|
+
if (cot?.finalAnswer) {
|
|
720
|
+
return `${cot.finalAnswer} Based on ${session.steps.length} reasoning steps.`;
|
|
721
|
+
}
|
|
722
|
+
return `After ${session.steps.length} steps of ${session.type} reasoning: ${stepConclusions.slice(-2).join('; ')}.`;
|
|
723
|
+
}
|
|
724
|
+
calculateSessionConfidence(session) {
|
|
725
|
+
if (session.steps.length === 0)
|
|
726
|
+
return 0;
|
|
727
|
+
const avgConfidence = session.steps.reduce((sum, s) => sum + s.confidence, 0) / session.steps.length;
|
|
728
|
+
return Math.min(0.95, avgConfidence);
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Get reasoning session
|
|
732
|
+
*/
|
|
733
|
+
getSession(sessionId) {
|
|
734
|
+
return this.sessions.get(sessionId);
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Add custom logical rule
|
|
738
|
+
*/
|
|
739
|
+
addRule(rule) {
|
|
740
|
+
this.rulesEngine.addRule(rule);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
exports.ReasoningEngine = ReasoningEngine;
|
|
744
|
+
// ============================================================================
|
|
745
|
+
// EXPORT SINGLETON INSTANCE
|
|
746
|
+
// ============================================================================
|
|
747
|
+
exports.reasoningEngine = new ReasoningEngine();
|
|
748
|
+
// ============================================================================
|
|
749
|
+
// EXAMPLE USAGE
|
|
750
|
+
// ============================================================================
|
|
751
|
+
/*
|
|
752
|
+
// Deductive reasoning
|
|
753
|
+
const deductiveResult = await reasoningEngine.reason(
|
|
754
|
+
"All software requires maintenance. This application is software. Therefore...",
|
|
755
|
+
{ type: ReasoningType.DEDUCTIVE }
|
|
756
|
+
);
|
|
757
|
+
|
|
758
|
+
// Inductive reasoning
|
|
759
|
+
const inductiveResult = await reasoningEngine.reason(
|
|
760
|
+
"Every software project I've seen with good documentation succeeded. " +
|
|
761
|
+
"Projects with poor documentation often failed. Therefore...",
|
|
762
|
+
{ type: ReasoningType.INDUCTIVE }
|
|
763
|
+
);
|
|
764
|
+
|
|
765
|
+
// Hypothesis testing
|
|
766
|
+
const hypothesis = reasoningEngine.createHypothesis(
|
|
767
|
+
"Using TypeScript reduces bug count by 30%"
|
|
768
|
+
);
|
|
769
|
+
|
|
770
|
+
reasoningEngine.addEvidenceToHypothesis(
|
|
771
|
+
hypothesis.id,
|
|
772
|
+
{
|
|
773
|
+
source: 'study',
|
|
774
|
+
excerpt: 'TypeScript projects had 15% fewer bugs',
|
|
775
|
+
location: 'research_paper',
|
|
776
|
+
strength: 0.8
|
|
777
|
+
},
|
|
778
|
+
true
|
|
779
|
+
);
|
|
780
|
+
|
|
781
|
+
// Problem decomposition
|
|
782
|
+
const decomposition = reasoningEngine.decomposeProblem(
|
|
783
|
+
"Build a scalable e-commerce platform with AI recommendations"
|
|
784
|
+
);
|
|
785
|
+
|
|
786
|
+
// Chain of Thought
|
|
787
|
+
const cot = reasoningEngine.generateChainOfThought(
|
|
788
|
+
"How can we improve software development productivity?",
|
|
789
|
+
5
|
|
790
|
+
);
|
|
791
|
+
*/
|
|
792
|
+
//# sourceMappingURL=reasoning.js.map
|