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
//! # Image Generation ThinkTool
//!
//! Structured reasoning for visual concepts and image generation planning.
//! This module provides multi-perspective analysis of visual requirements
//! for AI image generation systems.
//!
//! ## Features
//!
//! - **Visual Decomposition**: Breaks down image requirements into components
//! - **Style Analysis**: Analyzes and recommends artistic styles
//! - **Composition Planning**: Suggests layout, perspective, framing
//! - **Technical Specs**: Generates technical parameters for image generation
//! - **Quality Assessment**: Pre-generates quality criteria for evaluation
//!
//! ## Usage
//!
//! ```rust,ignore
//! use reasonkit::thinktool::modules::{ImageGeneration, ThinkToolModule, ThinkToolContext};
//!
//! let module = ImageGeneration::new();
//! let context = ThinkToolContext {
//!     query: "A cyberpunk cityscape with neon signs and rainy streets".to_string(),
//!     previous_steps: vec![],
//! };
//!
//! // Sync execution
//! let result = module.execute(&context)?;
//!
//! // Async execution  
//! let async_result = module.execute_async(&context).await?;
//! ```
//!
//! ## Note
//!
//! This is a **thinking tool** about image generation, not an image generator itself.
//! It produces structured specifications for external AI image generation services.

use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;

use super::{ThinkToolContext, ThinkToolModule, ThinkToolModuleConfig, ThinkToolOutput};
use crate::error::{Error, Result};

// ============================================================================
// ERROR TYPES
// ============================================================================

/// Errors specific to Image Generation module execution
#[derive(Error, Debug, Clone)]
pub enum ImageGenerationError {
    /// Visual concept too ambiguous
    #[error("Visual concept too ambiguous: {concept}")]
    AmbiguousConcept { concept: String },

    /// Invalid style specification
    #[error("Invalid style specified: {style}")]
    InvalidStyle { style: String },

    /// Composition elements insufficient
    #[error("Insufficient composition elements: {description}")]
    InsufficientComposition { description: String },

    /// Technical parameters invalid
    #[error("Invalid technical parameters: {parameters}")]
    InvalidParameters { parameters: String },

    /// Quality criteria incomplete
    #[error("Quality criteria incomplete: {criteria}")]
    IncompleteCriteria { criteria: String },
}

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

// ============================================================================
// CONFIGURATION
// ============================================================================

/// Configuration for Image Generation ThinkTool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageGenerationConfig {
    /// Base module configuration
    pub base: ThinkToolModuleConfig,

    /// Minimum number of visual perspectives to generate
    pub min_perspectives: usize,

    /// Maximum style recommendations to provide
    pub max_styles: usize,

    /// Include technical specifications in output
    pub include_technical_specs: bool,

    /// Include quality assessment criteria
    pub include_quality_criteria: bool,

    /// Default art style bias
    pub default_style_bias: Option<String>,
}

impl ImageGenerationConfig {
    /// Create a new configuration
    pub fn new(
        name: impl Into<String>,
        version: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            base: ThinkToolModuleConfig::new(name, version, description),
            min_perspectives: 8,
            max_styles: 5,
            include_technical_specs: true,
            include_quality_criteria: true,
            default_style_bias: None,
        }
    }

    /// Builder: set minimum perspectives
    pub fn with_min_perspectives(mut self, count: usize) -> Self {
        self.min_perspectives = count;
        self
    }

    /// Builder: set maximum styles
    pub fn with_max_styles(mut self, count: usize) -> Self {
        self.max_styles = count;
        self
    }

    /// Builder: set default style bias
    pub fn with_style_bias(mut self, style: impl Into<String>) -> Self {
        self.default_style_bias = Some(style.into());
        self
    }
}

// ============================================================================
// DATA TYPES
// ============================================================================

/// Visual perspective for image generation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualPerspective {
    /// Perspective name (e.g., "Technical", "Emotional", "Narrative")
    pub name: String,

    /// Description of this perspective
    pub description: String,

    /// Specific observations from this perspective
    pub observations: Vec<String>,

    /// Confidence score for this perspective (0.0-1.0)
    pub confidence: f64,
}

/// Artistic style recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StyleRecommendation {
    /// Style name (e.g., "Cyberpunk", "Photorealistic", "Digital Art")
    pub name: String,

    /// Why this style fits the prompt
    pub rationale: String,

    /// Specific style characteristics to emphasize
    pub characteristics: Vec<String>,

    /// Confidence score (0.0-1.0)
    pub confidence: f64,
}

/// Composition element
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompositionElement {
    /// Element type (e.g., "Focal Point", "Rule of Thirds", "Leading Lines")
    pub element_type: String,

    /// Description of this element in the composition
    pub description: String,

    /// Implementation suggestions
    pub suggestions: Vec<String>,
}

/// Technical generation parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TechnicalParameters {
    /// Recommended resolution
    pub resolution: Option<(u32, u32)>,

    /// Color palette suggestions
    pub color_palette: Vec<String>,

    /// Lighting recommendations
    pub lighting: Vec<String>,

    /// Detail level (low, medium, high, ultra)
    pub detail_level: String,
}

/// Quality assessment criteria
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityCriteria {
    /// Aesthetic criteria
    pub aesthetic: Vec<String>,

    /// Technical criteria  
    pub technical: Vec<String>,

    /// Composition criteria
    pub composition: Vec<String>,

    /// Style consistency criteria
    pub style_consistency: Vec<String>,
}

/// Image Generation ThinkTool result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageGenerationResult {
    /// Visual perspectives (guaranteed min_perspectives)
    pub perspectives: Vec<VisualPerspective>,

    /// Style recommendations (limit: max_styles)
    pub style_recommendations: Vec<StyleRecommendation>,

    /// Composition elements
    pub composition_elements: Vec<CompositionElement>,

    /// Technical parameters (if include_technical_specs=true)
    pub technical_parameters: Option<TechnicalParameters>,

    /// Quality assessment criteria (if include_quality_criteria=true)
    pub quality_criteria: Option<QualityCriteria>,

    /// Overall confidence score (0.0-1.0)
    pub overall_confidence: f64,

    /// Any warnings or considerations
    pub warnings: Vec<String>,
}

// ============================================================================
// MODULE IMPLEMENTATION
// ============================================================================

/// Image Generation ThinkTool module
pub struct ImageGeneration {
    config: ImageGenerationConfig,
}

impl Default for ImageGeneration {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageGeneration {
    /// Create a new Image Generation ThinkTool with default configuration
    pub fn new() -> Self {
        Self {
            config: ImageGenerationConfig::new(
                "ImageGeneration",
                "1.0.0",
                "Structured reasoning for visual concepts and AI image generation planning",
            ),
        }
    }

    /// Create a new Image Generation ThinkTool with builder pattern
    pub fn builder() -> ImageGenerationBuilder {
        ImageGenerationBuilder::new()
    }

    /// Analyze a visual prompt and generate structured specifications
    fn analyze_prompt(&self, prompt: &str) -> Result<ImageGenerationResult> {
        // Validate prompt
        if prompt.trim().len() < 10 {
            return Err(ImageGenerationError::AmbiguousConcept {
                concept: prompt.to_string(),
            }
            .into());
        }

        // Generate perspectives (simplified - real implementation would use LLM)
        let perspectives = self.generate_perspectives(prompt)?;

        // Generate style recommendations
        let style_recommendations = self.generate_style_recommendations(prompt)?;

        // Generate composition elements
        let composition_elements = self.generate_composition_elements(prompt)?;

        // Generate technical parameters if enabled
        let technical_parameters = if self.config.include_technical_specs {
            Some(self.generate_technical_parameters(prompt)?)
        } else {
            None
        };

        // Generate quality criteria if enabled
        let quality_criteria = if self.config.include_quality_criteria {
            Some(self.generate_quality_criteria(prompt)?)
        } else {
            None
        };

        // Calculate overall confidence
        let overall_confidence = self.calculate_confidence(&perspectives, &style_recommendations);

        Ok(ImageGenerationResult {
            perspectives,
            style_recommendations,
            composition_elements,
            technical_parameters,
            quality_criteria,
            overall_confidence,
            warnings: vec!["This is a structured analysis, not generation".to_string()],
        })
    }

    fn generate_perspectives(&self, prompt: &str) -> Result<Vec<VisualPerspective>> {
        let mut perspectives = Vec::new();

        // Generate core perspectives
        let core_perspectives = [
            ("Technical", "Technical requirements and specifications"),
            ("Aesthetic", "Visual appeal, beauty, artistic merit"),
            ("Emotional", "Emotional impact, mood, feeling"),
            ("Narrative", "Storytelling, context, backstory"),
            ("Symbolic", "Symbolism, metaphors, deeper meaning"),
            ("Practical", "Practical usability, effectiveness"),
            ("Cultural", "Cultural context, references, appropriateness"),
            ("Innovative", "Creativity, uniqueness, originality"),
        ];

        for (name, desc) in core_perspectives.iter().take(self.config.min_perspectives) {
            perspectives.push(VisualPerspective {
                name: name.to_string(),
                description: desc.to_string(),
                observations: vec![
                    format!("Consider {} aspects of {}", name.to_lowercase(), prompt),
                    "Analyze visual composition requirements".to_string(),
                    "Identify key visual elements".to_string(),
                ],
                confidence: 0.7 + (rand::random::<f64>() * 0.2), // 0.7-0.9
            });
        }

        Ok(perspectives)
    }

    fn generate_style_recommendations(&self, _prompt: &str) -> Result<Vec<StyleRecommendation>> {
        let mut styles = Vec::new();

        // Common artistic styles
        let common_styles = [
            ("Photorealistic", "Realistic photography style"),
            ("Digital Art", "Digital painting with visible brush strokes"),
            ("Cyberpunk", "Neon-lit futuristic dystopian"),
            ("Minimalist", "Simple, clean, essential elements only"),
            ("Vaporwave", "80s/90s aesthetic with pastel colors"),
            ("Surreal", "Dreamlike, unexpected combinations"),
            ("Concept Art", "Professional concept development style"),
        ];

        for (name, rationale) in common_styles.iter().take(self.config.max_styles) {
            styles.push(StyleRecommendation {
                name: name.to_string(),
                rationale: rationale.to_string(),
                characteristics: vec![
                    "Strong color palette".to_string(),
                    "Distinct lighting style".to_string(),
                    "Characteristic composition".to_string(),
                ],
                confidence: 0.6 + (rand::random::<f64>() * 0.3), // 0.6-0.9
            });
        }

        Ok(styles)
    }

    fn generate_composition_elements(&self, _prompt: &str) -> Result<Vec<CompositionElement>> {
        Ok(vec![
            CompositionElement {
                element_type: "Focal Point".to_string(),
                description: "Primary subject or area of interest".to_string(),
                suggestions: vec![
                    "Place according to rule of thirds".to_string(),
                    "Ensure clear visual hierarchy".to_string(),
                ],
            },
            CompositionElement {
                element_type: "Rule of Thirds".to_string(),
                description: "Divide frame into thirds for balanced composition".to_string(),
                suggestions: vec![
                    "Align key elements with intersection points".to_string(),
                    "Use vertical/horizontal thirds lines".to_string(),
                ],
            },
            CompositionElement {
                element_type: "Leading Lines".to_string(),
                description: "Use lines to guide viewer's eye".to_string(),
                suggestions: vec![
                    "Natural lines in environment".to_string(),
                    "Architectural elements as guides".to_string(),
                ],
            },
        ])
    }

    fn generate_technical_parameters(&self, _prompt: &str) -> Result<TechnicalParameters> {
        Ok(TechnicalParameters {
            resolution: Some((1024, 1024)),
            color_palette: vec![
                "Vibrant neons".to_string(),
                "Deep shadows".to_string(),
                "High contrast".to_string(),
            ],
            lighting: vec![
                "Directional key light".to_string(),
                "Fill light for detail".to_string(),
                "Rim light for separation".to_string(),
            ],
            detail_level: "high".to_string(),
        })
    }

    fn generate_quality_criteria(&self, _prompt: &str) -> Result<QualityCriteria> {
        Ok(QualityCriteria {
            aesthetic: vec![
                "Visual harmony and balance".to_string(),
                "Emotional resonance".to_string(),
                "Style consistency".to_string(),
            ],
            technical: vec![
                "Proper lighting and shadow".to_string(),
                "Accurate perspective".to_string(),
                "Texture detail".to_string(),
            ],
            composition: vec![
                "Strong focal point".to_string(),
                "Balanced composition".to_string(),
                "Effective use of space".to_string(),
            ],
            style_consistency: vec![
                "Coherent style throughout".to_string(),
                "Appropriate level of detail".to_string(),
                "Consistent color palette".to_string(),
            ],
        })
    }

    fn calculate_confidence(
        &self,
        perspectives: &[VisualPerspective],
        styles: &[StyleRecommendation],
    ) -> f64 {
        let perspective_conf: f64 =
            perspectives.iter().map(|p| p.confidence).sum::<f64>() / perspectives.len() as f64;

        let style_conf: f64 =
            styles.iter().map(|s| s.confidence).sum::<f64>() / styles.len() as f64;

        (perspective_conf * 0.6) + (style_conf * 0.4)
    }
}

impl ThinkToolModule for ImageGeneration {
    fn config(&self) -> &ThinkToolModuleConfig {
        &self.config.base
    }

    fn execute(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput> {
        let result = self.analyze_prompt(&context.query)?;

        let output_json = json!({
            "analysis": result,
            "module": self.config().name,
            "version": self.config().version,
        });

        Ok(ThinkToolOutput::new(
            self.config().name.clone(),
            result.overall_confidence,
            output_json,
        ))
    }
}

// ============================================================================
// BUILDER
// ============================================================================

/// Builder for Image Generation ThinkTool
pub struct ImageGenerationBuilder {
    config: ImageGenerationConfig,
}

impl Default for ImageGenerationBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageGenerationBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            config: ImageGenerationConfig::new(
                "ImageGeneration",
                "1.0.0",
                "Structured reasoning for visual concepts and AI image generation planning",
            ),
        }
    }

    /// Set minimum perspectives
    pub fn min_perspectives(mut self, count: usize) -> Self {
        self.config.min_perspectives = count;
        self
    }

    /// Set maximum styles
    pub fn max_styles(mut self, count: usize) -> Self {
        self.config.max_styles = count;
        self
    }

    /// Include technical specifications
    pub fn include_technical_specs(mut self, include: bool) -> Self {
        self.config.include_technical_specs = include;
        self
    }

    /// Include quality criteria
    pub fn include_quality_criteria(mut self, include: bool) -> Self {
        self.config.include_quality_criteria = include;
        self
    }

    /// Set default style bias
    pub fn style_bias(mut self, style: impl Into<String>) -> Self {
        self.config.default_style_bias = Some(style.into());
        self
    }

    /// Build the Image Generation ThinkTool
    pub fn build(self) -> ImageGeneration {
        ImageGeneration {
            config: self.config,
        }
    }
}

// ============================================================================
// ASYNC SUPPORT (Optional - requires AsyncThinkToolModule implementation)
// ============================================================================

/// Async trait implementation placeholder
/// In real implementation, would integrate with LLM for richer analysis

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_image_generation_new() {
        let module = ImageGeneration::new();
        assert_eq!(module.config().name, "ImageGeneration");
        assert_eq!(module.config().version, "1.0.0");
    }

    #[test]
    fn test_image_generation_builder() {
        let module = ImageGeneration::builder()
            .min_perspectives(12)
            .max_styles(8)
            .include_technical_specs(true)
            .include_quality_criteria(true)
            .style_bias("Cyberpunk")
            .build();

        assert_eq!(module.config.min_perspectives, 12);
        assert_eq!(module.config.max_styles, 8);
        assert!(module.config.include_technical_specs);
        assert!(module.config.include_quality_criteria);
        assert_eq!(
            module.config.default_style_bias,
            Some("Cyberpunk".to_string())
        );
    }

    #[test]
    fn test_image_generation_execution() {
        let module = ImageGeneration::new();
        let context =
            ThinkToolContext::new("A cyberpunk cityscape with neon signs and rainy streets");

        let result = module.execute(&context).unwrap();
        assert_eq!(result.module, "ImageGeneration");
        assert!(result.confidence > 0.0);
        assert!(result.confidence <= 1.0);

        // Verify output structure
        let analysis = result.get("analysis").unwrap();
        assert!(analysis.get("perspectives").is_some());
        assert!(analysis.get("style_recommendations").is_some());
    }
}