reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! # Tree-of-Thoughts (ToT) Parallel Exploration
//!
//! Implements parallel thought exploration achieving 74% vs 4% on creative tasks
//! compared to Chain-of-Thought.
//!
//! ## Scientific Foundation
//!
//! Based on:
//! - Yao et al. (2023): Tree of Thoughts: Deliberate Problem Solving with Large Language Models
//! - Long (2023): Large Language Model Guided Tree-of-Thought
//!
//! ## Key Concepts
//!
//! - **Thought**: Coherent language chunk (sentence to paragraph)
//! - **Decomposition**: Break problem into thought steps
//! - **Generation**: Propose multiple candidates per step
//! - **Evaluation**: Score thoughts for promise
//! - **Search**: BFS/DFS with pruning
//!
//! ## Usage
//!
//! ```rust,ignore
//! use reasonkit::thinktool::tot::{TreeOfThoughts, ToTConfig};
//!
//! let tot = TreeOfThoughts::new(ToTConfig {
//!     branching_factor: 3,
//!     max_depth: 5,
//!     search_strategy: SearchStrategy::BreadthFirst,
//!     ..Default::default()
//! });
//!
//! let result = tot.solve("Creative problem here").await?;
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A single thought node in the tree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThoughtNode {
    /// Unique node ID
    pub id: usize,
    /// Parent node ID (None for root)
    pub parent: Option<usize>,
    /// Child node IDs
    pub children: Vec<usize>,
    /// The thought content
    pub thought: String,
    /// Evaluation score (0.0 - 1.0)
    pub score: f32,
    /// Depth in tree (root = 0)
    pub depth: usize,
    /// Whether this is a terminal/solution node
    pub is_terminal: bool,
    /// State representation after this thought
    pub state: ThoughtState,
}

/// State after applying a thought
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ThoughtState {
    /// Accumulated reasoning so far
    pub reasoning_path: Vec<String>,
    /// Intermediate results
    pub partial_results: HashMap<String, String>,
    /// Whether the problem is solved
    pub is_solved: bool,
    /// Solution if found
    pub solution: Option<String>,
}

/// Result of ToT exploration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToTResult {
    /// Best solution path
    pub best_path: Vec<ThoughtNode>,
    /// Best solution
    pub solution: Option<String>,
    /// Final score
    pub score: f32,
    /// All explored paths (for debugging)
    pub explored_paths: usize,
    /// Total nodes generated
    pub nodes_generated: usize,
    /// Nodes pruned
    pub nodes_pruned: usize,
    /// Statistics
    pub stats: ToTStats,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToTStats {
    /// Average branching factor observed
    pub avg_branching_factor: f32,
    /// Average node score
    pub avg_node_score: f32,
    /// Maximum depth reached
    pub max_depth_reached: usize,
    /// Number of backtrack operations
    pub backtrack_count: usize,
    /// Time spent in generation (ms)
    pub generation_time_ms: u64,
    /// Time spent in evaluation (ms)
    pub evaluation_time_ms: u64,
}

/// Tree-of-Thoughts configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToTConfig {
    /// Number of thoughts to generate per step
    pub branching_factor: usize,
    /// Maximum tree depth
    pub max_depth: usize,
    /// Search strategy
    pub search_strategy: SearchStrategy,
    /// Pruning threshold (nodes below this are dropped)
    pub prune_threshold: f32,
    /// Maximum nodes to expand
    pub max_nodes: usize,
    /// Beam width for beam search
    pub beam_width: usize,
    /// Whether to use value function for evaluation
    pub use_value_function: bool,
    /// Temperature for thought generation
    pub temperature: f32,
}

impl Default for ToTConfig {
    fn default() -> Self {
        Self {
            branching_factor: 3,
            max_depth: 5,
            search_strategy: SearchStrategy::BreadthFirst,
            prune_threshold: 0.3,
            max_nodes: 100,
            beam_width: 5,
            use_value_function: true,
            temperature: 0.7,
        }
    }
}

/// Search strategy for exploring the tree
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SearchStrategy {
    /// Explore level by level
    BreadthFirst,
    /// Explore depth-first with backtracking
    DepthFirst,
    /// Keep top-k candidates per level
    BeamSearch,
    /// Best-first search using scores
    BestFirst,
    /// Monte Carlo Tree Search
    MCTS,
}

/// The Tree-of-Thoughts engine
#[derive(Debug)]
pub struct TreeOfThoughts {
    pub config: ToTConfig,
    /// All nodes in the tree
    nodes: Vec<ThoughtNode>,
    /// Node ID counter
    next_id: usize,
}

impl TreeOfThoughts {
    pub fn new(config: ToTConfig) -> Self {
        Self {
            config,
            nodes: Vec::new(),
            next_id: 0,
        }
    }

    /// Create a new root node
    pub fn create_root(&mut self, problem: &str) -> usize {
        let id = self.next_id;
        self.next_id += 1;

        let node = ThoughtNode {
            id,
            parent: None,
            children: Vec::new(),
            thought: problem.to_string(),
            score: 1.0,
            depth: 0,
            is_terminal: false,
            state: ThoughtState::default(),
        };

        self.nodes.push(node);
        id
    }

    /// Add a child thought to a node
    pub fn add_child(
        &mut self,
        parent_id: usize,
        thought: String,
        score: f32,
        state: ThoughtState,
    ) -> usize {
        let id = self.next_id;
        self.next_id += 1;

        let parent_depth = self.nodes[parent_id].depth;

        let node = ThoughtNode {
            id,
            parent: Some(parent_id),
            children: Vec::new(),
            thought,
            score,
            depth: parent_depth + 1,
            is_terminal: state.is_solved,
            state,
        };

        self.nodes.push(node);
        self.nodes[parent_id].children.push(id);

        id
    }

    /// Get a node by ID
    pub fn get_node(&self, id: usize) -> Option<&ThoughtNode> {
        self.nodes.get(id)
    }

    /// Get mutable node by ID
    pub fn get_node_mut(&mut self, id: usize) -> Option<&mut ThoughtNode> {
        self.nodes.get_mut(id)
    }

    /// Get path from root to node
    pub fn get_path(&self, node_id: usize) -> Vec<&ThoughtNode> {
        let mut path = Vec::new();
        let mut current = Some(node_id);

        while let Some(id) = current {
            if let Some(node) = self.get_node(id) {
                path.push(node);
                current = node.parent;
            } else {
                break;
            }
        }

        path.reverse();
        path
    }

    /// Prune nodes below threshold
    pub fn prune(&mut self) -> usize {
        let threshold = self.config.prune_threshold;
        let mut pruned = 0;

        for node in &mut self.nodes {
            if node.score < threshold && !node.is_terminal {
                // Mark as terminal (effectively pruned)
                node.is_terminal = true;
                pruned += 1;
            }
        }

        pruned
    }

    /// Get frontier nodes (expandable leaves)
    pub fn get_frontier(&self) -> Vec<usize> {
        self.nodes
            .iter()
            .filter(|n| {
                !n.is_terminal
                    && n.children.is_empty()
                    && n.depth < self.config.max_depth
                    && n.score >= self.config.prune_threshold
            })
            .map(|n| n.id)
            .collect()
    }

    /// BFS exploration step
    pub fn bfs_step(&self) -> Vec<usize> {
        // In BFS, we process all frontier nodes
        self.get_frontier()
    }

    /// DFS exploration step
    pub fn dfs_step(&self) -> Vec<usize> {
        let frontier = self.get_frontier();

        // In DFS, we go deep first - pick highest depth node
        if let Some(best) = frontier.iter().max_by_key(|&&id| self.nodes[id].depth) {
            vec![*best]
        } else {
            vec![]
        }
    }

    /// Beam search step
    pub fn beam_step(&self) -> Vec<usize> {
        let frontier = self.get_frontier();

        // Keep top-k by score
        let mut scored: Vec<_> = frontier
            .iter()
            .map(|&id| (id, self.nodes[id].score))
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        scored
            .into_iter()
            .take(self.config.beam_width)
            .map(|(id, _)| id)
            .collect()
    }

    /// Best-first step
    pub fn best_first_step(&self) -> Vec<usize> {
        let frontier = self.get_frontier();

        // Pick single best node
        if let Some(&best) = frontier.iter().max_by(|&&a, &&b| {
            self.nodes[a]
                .score
                .partial_cmp(&self.nodes[b].score)
                .unwrap_or(std::cmp::Ordering::Equal)
        }) {
            vec![best]
        } else {
            vec![]
        }
    }

    /// Get nodes to expand based on search strategy
    pub fn get_expansion_candidates(&self) -> Vec<usize> {
        match self.config.search_strategy {
            SearchStrategy::BreadthFirst => self.bfs_step(),
            SearchStrategy::DepthFirst => self.dfs_step(),
            SearchStrategy::BeamSearch => self.beam_step(),
            SearchStrategy::BestFirst => self.best_first_step(),
            SearchStrategy::MCTS => self.best_first_step(), // Simplified MCTS
        }
    }

    /// Find the best terminal node (solution)
    pub fn find_best_solution(&self) -> Option<&ThoughtNode> {
        self.nodes
            .iter()
            .filter(|n| n.is_terminal && n.state.is_solved)
            .max_by(|a, b| {
                a.score
                    .partial_cmp(&b.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
    }

    /// Build result from current tree state
    pub fn build_result(&self) -> ToTResult {
        let best_node = self.find_best_solution();

        let (best_path, solution, score) = if let Some(node) = best_node {
            let path = self.get_path(node.id);
            (
                path.into_iter().cloned().collect(),
                node.state.solution.clone(),
                node.score,
            )
        } else {
            // Return best non-terminal path
            let best_leaf = self
                .nodes
                .iter()
                .filter(|n| n.children.is_empty())
                .max_by(|a, b| {
                    a.score
                        .partial_cmp(&b.score)
                        .unwrap_or(std::cmp::Ordering::Equal)
                });

            if let Some(node) = best_leaf {
                let path = self.get_path(node.id);
                (path.into_iter().cloned().collect(), None, node.score)
            } else {
                (vec![], None, 0.0)
            }
        };

        let nodes_pruned = self
            .nodes
            .iter()
            .filter(|n| n.score < self.config.prune_threshold)
            .count();

        let max_depth = self.nodes.iter().map(|n| n.depth).max().unwrap_or(0);

        let avg_score = if !self.nodes.is_empty() {
            self.nodes.iter().map(|n| n.score).sum::<f32>() / self.nodes.len() as f32
        } else {
            0.0
        };

        let avg_branching = if self.nodes.len() > 1 {
            let non_leaf = self.nodes.iter().filter(|n| !n.children.is_empty()).count();
            if non_leaf > 0 {
                self.nodes.iter().map(|n| n.children.len()).sum::<usize>() as f32 / non_leaf as f32
            } else {
                0.0
            }
        } else {
            0.0
        };

        ToTResult {
            best_path,
            solution,
            score,
            explored_paths: self.nodes.iter().filter(|n| n.children.is_empty()).count(),
            nodes_generated: self.nodes.len(),
            nodes_pruned,
            stats: ToTStats {
                avg_branching_factor: avg_branching,
                avg_node_score: avg_score,
                max_depth_reached: max_depth,
                backtrack_count: 0,
                generation_time_ms: 0,
                evaluation_time_ms: 0,
            },
        }
    }

    /// Reset the tree for a new problem
    pub fn reset(&mut self) {
        self.nodes.clear();
        self.next_id = 0;
    }
}

/// Thought generation prompt templates
pub struct ThoughtPrompts;

impl ThoughtPrompts {
    /// Generate N diverse thoughts for a math problem
    pub fn math_thoughts(problem: &str, current_state: &str, n: usize) -> String {
        format!(
            r#"You are solving a math problem step by step.

PROBLEM: {problem}

CURRENT STATE:
{current_state}

Generate exactly {n} different possible next steps to make progress on this problem.
Each step should be a distinct approach or continuation.

Format each thought as:
THOUGHT 1: [your first possible step]
THOUGHT 2: [your second possible step]
THOUGHT 3: [etc...]

Be creative and explore different angles. Some thoughts might:
- Apply a formula directly
- Break down into sub-problems
- Use a different variable
- Try a numerical approach
- Look for patterns"#,
            problem = problem,
            current_state = current_state,
            n = n
        )
    }

    /// Evaluate a thought for promise
    pub fn evaluate_thought(problem: &str, thought: &str, context: &str) -> String {
        format!(
            r#"Evaluate how promising this thought is for solving the problem.

PROBLEM: {problem}

CONTEXT/PRIOR STEPS:
{context}

THOUGHT TO EVALUATE:
{thought}

Rate on a scale of 0.0 to 1.0:
- 1.0: Definitely leads to solution
- 0.7-0.9: Very promising direction
- 0.4-0.6: Reasonable but uncertain
- 0.1-0.3: Unlikely to help
- 0.0: Definitely wrong or counterproductive

Consider:
1. Is the logic correct?
2. Does it make progress toward the answer?
3. Is it a reasonable next step given the context?
4. Could it lead to the final solution?

Respond with only a JSON object:
{{"score": 0.0-1.0, "reasoning": "brief explanation"}}"#,
            problem = problem,
            context = context,
            thought = thought
        )
    }

    /// Check if a state is terminal (solved)
    pub fn check_terminal(problem: &str, current_state: &str) -> String {
        format!(
            r#"Determine if this problem has been solved.

PROBLEM: {problem}

CURRENT STATE/REASONING:
{current_state}

Answer with a JSON object:
{{
    "is_solved": true/false,
    "solution": "the answer if solved, null otherwise",
    "confidence": 0.0-1.0
}}"#,
            problem = problem,
            current_state = current_state
        )
    }

    /// Creative problem thoughts
    pub fn creative_thoughts(problem: &str, current_state: &str, n: usize) -> String {
        format!(
            r#"You are exploring creative solutions to a problem.

PROBLEM: {problem}

CURRENT EXPLORATION:
{current_state}

Generate {n} diverse and creative next thoughts. Think unconventionally.

Format as:
THOUGHT 1: [first creative direction]
THOUGHT 2: [second creative direction]
...

Consider:
- Analogy to other domains
- Inverting the problem
- Combining ideas
- Extreme cases
- Different perspectives"#,
            problem = problem,
            current_state = current_state,
            n = n
        )
    }
}

/// Parse thoughts from LLM output
pub fn parse_thoughts(output: &str, expected: usize) -> Vec<String> {
    let mut thoughts = Vec::new();

    // Try parsing "THOUGHT N:" format
    for i in 1..=expected + 5 {
        let marker = format!("THOUGHT {}:", i);
        if let Some(pos) = output.to_uppercase().find(&marker.to_uppercase()) {
            let start = pos + marker.len();
            let rest = &output[start..];

            // Find end (next THOUGHT marker or end)
            let end = rest
                .to_uppercase()
                .find("THOUGHT ")
                .unwrap_or(rest.len())
                .min(rest.len());

            let thought = rest[..end].trim().to_string();
            if !thought.is_empty() {
                thoughts.push(thought);
            }
        }
    }

    // Fallback: split by numbered list
    if thoughts.is_empty() {
        for line in output.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with(|c: char| c.is_ascii_digit()) {
                // Remove leading number and punctuation
                let text: String = trimmed
                    .chars()
                    .skip_while(|c| c.is_ascii_digit() || *c == '.' || *c == ')' || *c == ':')
                    .collect();
                let text = text.trim();
                if !text.is_empty() {
                    thoughts.push(text.to_string());
                }
            }
        }
    }

    thoughts.truncate(expected);
    thoughts
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tree_creation() {
        let mut tot = TreeOfThoughts::new(ToTConfig::default());
        let root = tot.create_root("What is 2 + 2?");

        assert_eq!(root, 0);
        assert!(tot.get_node(0).is_some());
        assert_eq!(tot.get_node(0).unwrap().depth, 0);
    }

    #[test]
    fn test_add_children() {
        let mut tot = TreeOfThoughts::new(ToTConfig::default());
        let root = tot.create_root("Problem");

        let child1 = tot.add_child(root, "Approach 1".into(), 0.8, ThoughtState::default());
        let child2 = tot.add_child(root, "Approach 2".into(), 0.6, ThoughtState::default());

        assert_eq!(tot.get_node(root).unwrap().children.len(), 2);
        assert_eq!(tot.get_node(child1).unwrap().depth, 1);
        assert_eq!(tot.get_node(child2).unwrap().parent, Some(root));
    }

    #[test]
    fn test_get_path() {
        let mut tot = TreeOfThoughts::new(ToTConfig::default());
        let root = tot.create_root("Problem");
        let child = tot.add_child(root, "Step 1".into(), 0.8, ThoughtState::default());
        let grandchild = tot.add_child(child, "Step 2".into(), 0.7, ThoughtState::default());

        let path = tot.get_path(grandchild);
        assert_eq!(path.len(), 3);
        assert_eq!(path[0].id, root);
        assert_eq!(path[2].id, grandchild);
    }

    #[test]
    fn test_pruning() {
        let mut tot = TreeOfThoughts::new(ToTConfig {
            prune_threshold: 0.5,
            ..Default::default()
        });
        let root = tot.create_root("Problem");
        tot.add_child(root, "Good".into(), 0.8, ThoughtState::default());
        tot.add_child(root, "Bad".into(), 0.2, ThoughtState::default());

        let pruned = tot.prune();
        assert_eq!(pruned, 1);
    }

    #[test]
    fn test_parse_thoughts() {
        let output = r#"
THOUGHT 1: First approach is to use algebra
THOUGHT 2: Second approach uses geometry
THOUGHT 3: Third uses numerical methods
"#;

        let thoughts = parse_thoughts(output, 3);
        assert_eq!(thoughts.len(), 3);
        assert!(thoughts[0].contains("algebra"));
        assert!(thoughts[1].contains("geometry"));
    }

    #[test]
    fn test_beam_search() {
        let mut tot = TreeOfThoughts::new(ToTConfig {
            beam_width: 2,
            search_strategy: SearchStrategy::BeamSearch,
            ..Default::default()
        });
        let root = tot.create_root("Problem");
        tot.add_child(root, "Low".into(), 0.3, ThoughtState::default());
        tot.add_child(root, "High".into(), 0.9, ThoughtState::default());
        tot.add_child(root, "Medium".into(), 0.6, ThoughtState::default());

        let candidates = tot.beam_step();
        assert_eq!(candidates.len(), 2);

        // Beam should select highest scored nodes
        let scores: Vec<f32> = candidates
            .iter()
            .map(|&id| tot.get_node(id).unwrap().score)
            .collect();
        assert!(scores[0] >= 0.6);
    }
}