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
# GigaThink Module API Documentation

Version: 2.1.0

The GigaThink module implements expansive creative thinking through divergent analysis,
generating 10+ diverse perspectives to explore problems from multiple angles.

## Table of Contents

1. [Module Overview]#module-overview
2. [Configuration]#configuration
3. [Core Types]#core-types
4. [Methods]#methods
5. [Usage Examples]#usage-examples
6. [Error Handling]#error-handling

## Module Overview

GigaThink is designed to break free from linear thinking patterns by systematically
generating multiple analytical perspectives. It employs dimensional analysis across
12 distinct thinking frameworks to ensure comprehensive coverage of the problem space.

Key capabilities:

- Generates minimum 10 distinct perspectives
- Applies 12 analytical dimensions for thorough analysis
- Provides evidence-based confidence scoring
- Supports both synchronous and asynchronous execution
- Includes cross-validation for perspective coherence

## Configuration

### GigaThinkConfig

Configuration struct controlling GigaThink behavior and analysis depth.

```rust
pub struct GigaThinkConfig {
    pub min_perspectives: usize,
    pub max_perspectives: usize,
    pub analysis_depth: usize,
    pub cross_validate: bool,
    pub timeout_ms: u64,
    pub enable_synthesis: bool,
    pub confidence_threshold: f64,
}
```

#### Fields

| Field                  | Type    | Required | Default | Description                                                                             |
| ---------------------- | ------- | -------- | ------- | --------------------------------------------------------------------------------------- |
| `min_perspectives`     | `usize` | Yes      | `10`    | Minimum number of perspectives to generate. Guarantees comprehensive analysis coverage. |
| `max_perspectives`     | `usize` | Yes      | `20`    | Maximum number of perspectives to generate. Prevents excessive computation.             |
| `analysis_depth`       | `usize` | Yes      | `3`     | Depth of dimensional analysis per perspective. Higher values provide deeper insights.   |
| `cross_validate`       | `bool`  | Yes      | `true`  | Enable cross-validation of perspectives for coherence. Improves output quality.         |
| `timeout_ms`           | `u64`   | Yes      | `30000` | Execution timeout in milliseconds. Prevents hanging operations.                         |
| `enable_synthesis`     | `bool`  | Yes      | `true`  | Generate synthesized insights from all perspectives. Provides holistic understanding.   |
| `confidence_threshold` | `f64`   | Yes      | `0.6`   | Minimum confidence for accepted perspectives. Range: 0.0-1.0.                           |

#### Implementation

```rust
impl Default for GigaThinkConfig {
    fn default() -> Self {
        Self {
            min_perspectives: 10,
            max_perspectives: 20,
            analysis_depth: 3,
            cross_validate: true,
            timeout_ms: 30000,
            enable_synthesis: true,
            confidence_threshold: 0.6,
        }
    }
}

impl GigaThinkConfig {
    /// Create configuration optimized for speed
    pub fn fast() -> Self {
        Self {
            min_perspectives: 5,
            max_perspectives: 10,
            analysis_depth: 2,
            cross_validate: false,
            timeout_ms: 15000,
            enable_synthesis: false,
            confidence_threshold: 0.5,
        }
    }

    /// Create configuration for deep analysis
    pub fn deep() -> Self {
        Self {
            min_perspectives: 15,
            max_perspectives: 30,
            analysis_depth: 5,
            cross_validate: true,
            timeout_ms: 60000,
            enable_synthesis: true,
            confidence_threshold: 0.7,
        }
    }
}
```

## Core Types

### GigaThink

Main module struct implementing the ThinkToolModule trait.

```rust
pub struct GigaThink {
    config: ThinkToolModuleConfig,
    gigathink_config: GigaThinkConfig,
}
```

#### Fields

| Field              | Type                    | Description                                 |
| ------------------ | ----------------------- | ------------------------------------------- |
| `config`           | `ThinkToolModuleConfig` | Standard module configuration metadata      |
| `gigathink_config` | `GigaThinkConfig`       | GigaThink-specific configuration parameters |

### GigaThinkResult

Structured output from GigaThink execution containing all analysis results.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigaThinkResult {
    pub perspectives: Vec<Perspective>,
    pub themes: Vec<Theme>,
    pub synthesis: Option<SynthesizedInsight>,
    pub metadata: GigaThinkMetadata,
    pub confidence: f64,
}
```

#### Fields

| Field          | Type                         | Description                            |
| -------------- | ---------------------------- | -------------------------------------- |
| `perspectives` | `Vec<Perspective>`           | Generated analytical perspectives      |
| `themes`       | `Vec<Theme>`                 | Common themes across perspectives      |
| `synthesis`    | `Option<SynthesizedInsight>` | Holistic insight from all perspectives |
| `metadata`     | `GigaThinkMetadata`          | Execution metadata and statistics      |
| `confidence`   | `f64`                        | Overall confidence score (0.0-1.0)     |

### Perspective

Individual analytical viewpoint with supporting rationale and evidence.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Perspective {
    pub id: usize,
    pub viewpoint: String,
    pub rationale: String,
    pub evidence: String,
    pub confidence: f64,
    pub dimensions: Vec<String>,
    pub novelty_score: f64,
}
```

#### Fields

| Field           | Type          | Description                                      |
| --------------- | ------------- | ------------------------------------------------ |
| `id`            | `usize`       | Unique identifier for this perspective           |
| `viewpoint`     | `String`      | The analytical viewpoint or lens                 |
| `rationale`     | `String`      | Reasoning behind this perspective                |
| `evidence`      | `String`      | Supporting evidence or examples                  |
| `confidence`    | `f64`         | Confidence in this perspective (0.0-1.0)         |
| `dimensions`    | `Vec<String>` | Analytical dimensions this perspective addresses |
| `novelty_score` | `f64`         | How novel/unique this perspective is (0.0-1.0)   |

### Theme

Common analytical theme identified across multiple perspectives.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Theme {
    pub name: String,
    pub description: String,
    pub perspective_count: usize,
    pub confidence: f64,
    pub representative_perspectives: Vec<usize>,
}
```

#### Fields

| Field                         | Type         | Description                                 |
| ----------------------------- | ------------ | ------------------------------------------- |
| `name`                        | `String`     | Theme name (e.g., "Economic Impact")        |
| `description`                 | `String`     | Detailed theme description                  |
| `perspective_count`           | `usize`      | How many perspectives mention this theme    |
| `confidence`                  | `f64`        | Confidence in this theme's significance     |
| `representative_perspectives` | `Vec<usize>` | IDs of perspectives exemplifying this theme |

### SynthesizedInsight

Holistic insight synthesized from all generated perspectives.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SynthesizedInsight {
    pub overview: String,
    pub key_takeaways: Vec<String>,
    pub tensions_and_tradeoffs: Vec<String>,
    pub confidence: f64,
}
```

#### Fields

| Field                    | Type          | Description                               |
| ------------------------ | ------------- | ----------------------------------------- |
| `overview`               | `String`      | Comprehensive summary of all perspectives |
| `key_takeaways`          | `Vec<String>` | Most important insights extracted         |
| `tensions_and_tradeoffs` | `Vec<String>` | Conflicting viewpoints and compromises    |
| `confidence`             | `f64`         | Confidence in the synthesis (0.0-1.0)     |

### GigaThinkMetadata

Execution metadata and performance statistics.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigaThinkMetadata {
    pub execution_time_ms: u64,
    pub perspectives_generated: usize,
    pub cross_validation_passed: bool,
    pub dimensional_coverage: HashMap<String, usize>,
    pub novelty_distribution: Vec<f64>,
}
```

#### Fields

| Field                     | Type                     | Description                                |
| ------------------------- | ------------------------ | ------------------------------------------ |
| `execution_time_ms`       | `u64`                    | Total execution time in milliseconds       |
| `perspectives_generated`  | `usize`                  | Actual number of perspectives created      |
| `cross_validation_passed` | `bool`                   | Whether cross-validation succeeded         |
| `dimensional_coverage`    | `HashMap<String, usize>` | Coverage across analytical dimensions      |
| `novelty_distribution`    | `Vec<f64>`               | Distribution of perspective novelty scores |

### AnalysisDimension

Framework for analytical thinking across specific domains.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisDimension {
    pub name: String,
    pub description: String,
    pub questioning_template: String,
    pub weight: f64,
}
```

#### Fields

| Field                  | Type     | Description                             |
| ---------------------- | -------- | --------------------------------------- |
| `name`                 | `String` | Dimension name (e.g., "Economic")       |
| `description`          | `String` | Explanation of analytical focus         |
| `questioning_template` | `String` | Template for generating questions       |
| `weight`               | `f64`    | Importance weight in analysis (0.0-1.0) |

## Methods

### GigaThink::new()

Create a new GigaThink module with default configuration.

```rust
pub fn new() -> Self
```

Returns: `GigaThink` instance with default settings.

Example:

```rust
let module = GigaThink::new();
assert_eq!(module.name(), "GigaThink");
assert_eq!(module.version(), "2.1.0");
```

### GigaThink::with_config()

Create a new GigaThink module with custom configuration.

```rust
pub fn with_config(config: GigaThinkConfig) -> Self
```

Parameters:

- `config`: `GigaThinkConfig` - Custom configuration parameters

Returns: `GigaThink` instance with specified configuration.

Example:

```rust
let config = GigaThinkConfig::deep();
let module = GigaThink::with_config(config);
```

### GigaThink::builder()

Create a builder for fluent configuration.

```rust
pub fn builder() -> GigaThinkBuilder
```

Returns: `GigaThinkBuilder` for constructing customized instances.

Example:

```rust
let module = GigaThink::builder()
    .min_perspectives(15)
    .analysis_depth(4)
    .build();
```

### GigaThink::execute()

Execute the GigaThink module synchronously.

```rust
impl ThinkToolModule for GigaThink {
    fn execute(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput>
}
```

Parameters:

- `context`: `&ThinkToolContext` - Execution context with query and previous steps

Returns: `Result<ThinkToolOutput>` - Structured output or error.

Example:

```rust
let module = GigaThink::new();
let context = ThinkToolContext::new("What factors drive startup success?");
let result = module.execute(&context)?;
```

### GigaThink::execute_async()

Execute the GigaThink module asynchronously.

```rust
impl AsyncThinkToolModule for GigaThink {
    async fn execute_async(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput>
}
```

Parameters:

- `context`: `&ThinkToolContext` - Execution context with query and previous steps

Returns: `Result<ThinkToolOutput>` - Structured output or error.

Example:

```rust
let module = GigaThink::new();
let context = ThinkToolContext::new("Analyze AI regulation impacts");
let result = module.execute_async(&context).await?;
```

### GigaThink::config()

Get the module configuration.

```rust
pub fn config(&self) -> &GigaThinkConfig
```

Returns: `&GigaThinkConfig` - Reference to current configuration.

Example:

```rust
let module = GigaThink::new();
let config = module.config();
assert_eq!(config.min_perspectives, 10);
```

## Usage Examples

### Basic Usage

```rust
use reasonkit::thinktool::modules::{GigaThink, ThinkToolContext, ThinkToolModule};

// Create module with default settings
let module = GigaThink::new();

// Prepare context
let context = ThinkToolContext::new("What are the implications of remote work?");

// Execute analysis
let result = module.execute(&context)?;

// Access perspectives
let perspectives = result.get_array("perspectives").unwrap();
println!("Generated {} perspectives", perspectives.len());

// Access synthesis
let synthesis = result.get_str("synthesis").unwrap();
println!("Synthesis: {}", synthesis);
```

### Custom Configuration

```rust
use reasonkit::thinktool::modules::{GigaThink, GigaThinkConfig, ThinkToolContext};

// Create custom configuration
let config = GigaThinkConfig {
    min_perspectives: 15,
    max_perspectives: 25,
    analysis_depth: 4,
    timeout_ms: 45000,
    ..Default::default()
};

// Create module with custom config
let module = GigaThink::with_config(config);

// Execute with complex query
let context = ThinkToolContext::new(
    "Analyze the strategic implications of quantum computing for cybersecurity"
);
let result = module.execute(&context)?;
```

### Fluent Builder Pattern

```rust
use reasonkit::thinktool::modules::{GigaThink, ThinkToolContext};

// Use builder for fluent configuration
let module = GigaThink::builder()
    .min_perspectives(20)
    .max_perspectives(30)
    .analysis_depth(5)
    .timeout_ms(60000)
    .enable_synthesis(true)
    .build();

// Execute comprehensive analysis
let context = ThinkToolContext::new("Evaluate the future of sustainable energy");
let result = module.execute(&context)?;
```

## Error Handling

GigaThink defines specific error types for various failure modes:

### GigaThinkError

Enumeration of all possible module-specific errors.

```rust
#[derive(Error, Debug, Clone)]
pub enum GigaThinkError {
    InsufficientPerspectives { generated: usize, required: usize },
    InvalidDimension { dimension: String },
    QueryTooShort { length: usize, minimum: usize },
    QueryTooLong { length: usize, maximum: usize },
    LowConfidence { confidence: f64, threshold: f64 },
    CrossValidationFailed { reason: String },
    SynthesisFailed { reason: String },
    ExecutionTimeout { duration_ms: u64 },
}
```

### Error Descriptions

| Error Variant              | Parameters                | Description                                        |
| -------------------------- | ------------------------- | -------------------------------------------------- |
| `InsufficientPerspectives` | `generated`, `required`   | Generated fewer perspectives than required minimum |
| `InvalidDimension`         | `dimension`               | Specified analytical dimension is not recognized   |
| `QueryTooShort`            | `length`, `minimum`       | Input query is too brief for meaningful analysis   |
| `QueryTooLong`             | `length`, `maximum`       | Input query exceeds maximum allowed length         |
| `LowConfidence`            | `confidence`, `threshold` | Overall confidence falls below threshold           |
| `CrossValidationFailed`    | `reason`                  | Perspective coherence validation failed            |
| `SynthesisFailed`          | `reason`                  | Unable to synthesize perspectives                  |
| `ExecutionTimeout`         | `duration_ms`             | Operation exceeded timeout limit                   |

### Error Conversion

All GigaThinkError variants are automatically converted to the standard Error type:

```rust
impl From<GigaThinkError> for Error {
    fn from(err: GigaThinkError) -> Self {
        Error::ThinkToolExecutionError(err.to_string())
    }
}
```

### Handling Errors

```rust
use reasonkit::thinktool::modules::{GigaThink, ThinkToolContext, GigaThinkError};

let module = GigaThink::new();
let context = ThinkToolContext::new(""); // Empty query

match module.execute(&context) {
    Ok(result) => {
        // Process successful result
        println!("Analysis completed with confidence: {}", result.confidence);
    }
    Err(e) => {
        // Handle specific GigaThink errors
        if let Some(gt_err) = e.downcast_ref::<GigaThinkError>() {
            match gt_err {
                GigaThinkError::QueryTooShort { length, minimum } => {
                    eprintln!("Query too short: {} chars, minimum {}", length, minimum);
                }
                GigaThinkError::ExecutionTimeout { duration_ms } => {
                    eprintln!("Timed out after {}ms", duration_ms);
                }
                _ => eprintln!("GigaThink error: {}", gt_err),
            }
        } else {
            // Handle other errors
            eprintln!("Other error: {}", e);
        }
    }
}
```

## Performance Considerations

1. **Timeout Management**: Set appropriate timeouts based on analysis depth
2. **Perspective Count**: Balance comprehensiveness with performance
3. **Cross-Validation**: Disable for faster execution when quality is less critical
4. **Synthesis Generation**: Can be disabled for speed-focused applications
5. **Dimensional Analysis**: Reduce analysis_depth for quicker results

## Integration Notes

When using GigaThink in protocol execution:

```rust
use reasonkit::thinktool::{ProtocolExecutor, ProtocolInput};

// ProtocolExecutor handles LLM integration automatically
let executor = ProtocolExecutor::new()?;
let result = executor.execute(
    "gigathink",
    ProtocolInput::query("Complex strategic question")
).await?;
```

The protocol-based approach provides:

- Automatic LLM selection and configuration
- Streaming output for real-time progress
- Built-in retry logic for failed steps
- Comprehensive execution tracing