# LaserLogic Module API Documentation
Version: 3.0.0
The LaserLogic module performs rigorous logical analysis with first-order logic
translation, formal fallacy detection, and argument structure validation.
## 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
LaserLogic applies precision deductive reasoning to validate arguments and detect
logical fallacies. It translates natural language to formal logic, checks validity
and soundness, and identifies common reasoning errors.
Key capabilities:
- First-order logic (FOL) translation and validation
- Formal fallacy detection (10+ types)
- Argument structure validation
- Syllogism analysis
- Contradiction detection
- Confidence scoring based on logical rigor
## Configuration
### LaserLogicConfig
Configuration struct controlling LaserLogic analysis depth and features.
```rust
pub struct LaserLogicConfig {
pub detect_fallacies: bool,
pub check_validity: bool,
pub check_soundness: bool,
pub max_premise_depth: usize,
pub analyze_syllogisms: bool,
pub detect_contradictions: bool,
pub confidence_threshold: f64,
pub verbose_output: bool,
}
```
#### Fields
| `detect_fallacies` | `bool` | Yes | `true` | Enable detection of logical fallacies. Improves argument quality. |
| `check_validity` | `bool` | Yes | `true` | Enable validity checking (conclusion follows from premises). Core functionality. |
| `check_soundness` | `bool` | Yes | `true` | Enable soundness checking (valid + true premises). Comprehensive validation. |
| `max_premise_depth` | `usize` | Yes | `10` | Maximum number of premises to analyze. Prevents complexity overload. |
| `analyze_syllogisms` | `bool` | Yes | `true` | Enable syllogism detection and analysis. Handles classical logic forms. |
| `detect_contradictions` | `bool` | Yes | `true` | Enable contradiction detection. Ensures logical consistency. |
| `confidence_threshold` | `f64` | Yes | `0.7` | Minimum confidence threshold for conclusions. Range: 0.0-1.0. |
| `verbose_output` | `bool` | Yes | `false` | Enable verbose output with reasoning steps. Useful for debugging. |
#### Implementation
```rust
impl Default for LaserLogicConfig {
fn default() -> Self {
Self {
detect_fallacies: true,
check_validity: true,
check_soundness: true,
max_premise_depth: 10,
analyze_syllogisms: true,
detect_contradictions: true,
confidence_threshold: 0.7,
verbose_output: false,
}
}
}
impl LaserLogicConfig {
/// Quick check mode - validity and basic fallacy detection only
pub fn quick() -> Self {
Self {
detect_fallacies: true,
check_validity: true,
check_soundness: false,
max_premise_depth: 5,
analyze_syllogisms: false,
detect_contradictions: false,
confidence_threshold: 0.6,
verbose_output: false,
}
}
/// Deep analysis mode - all features enabled
pub fn deep() -> Self {
Self {
detect_fallacies: true,
check_validity: true,
check_soundness: true,
max_premise_depth: 20,
analyze_syllogisms: true,
detect_contradictions: true,
confidence_threshold: 0.8,
verbose_output: true,
}
}
}
```
## Core Types
### LaserLogic
Main module struct implementing the ThinkToolModule trait.
```rust
pub struct LaserLogic {
config: ThinkToolModuleConfig,
laser_config: LaserLogicConfig,
}
```
#### Fields
| `config` | `ThinkToolModuleConfig` | Standard module configuration metadata |
| `laser_config` | `LaserLogicConfig` | LaserLogic-specific configuration parameters |
### LaserLogicResult
Structured output from LaserLogic execution containing logical analysis.
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaserLogicResult {
pub argument_form: Option<ArgumentForm>,
pub validity_status: ValidityStatus,
pub soundness_status: SoundnessStatus,
pub premises: Vec<Premise>,
pub fallacies: Vec<DetectedFallacy>,
pub contradictions: Vec<Contradiction>,
pub confidence: f64,
pub analysis_steps: Option<Vec<String>>,
}
```
#### Fields
| `argument_form` | `Option<ArgumentForm>` | Identified argument structure |
| `validity_status` | `ValidityStatus` | Validity assessment |
| `soundness_status` | `SoundnessStatus` | Soundness assessment |
| `premises` | `Vec<Premise>` | Analyzed premises |
| `fallacies` | `Vec<DetectedFallacy>` | Detected logical fallacies |
| `contradictions` | `Vec<Contradiction>` | Found contradictions |
| `confidence` | `f64` | Overall confidence in analysis |
| `analysis_steps` | `Option<Vec<String>>` | Detailed reasoning steps (when verbose) |
### Premise
Individual premise in an argument with classification and confidence.
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Premise {
pub id: usize,
pub text: String,
pub r#type: PremiseType,
pub confidence: f64,
pub issues: Vec<String>,
pub logical_form: Option<Formula>,
}
```
#### Fields
| `id` | `usize` | Unique identifier |
| `text` | `String` | Premise statement |
| `type` | `PremiseType` | Classification of premise |
| `confidence` | `f64` | Confidence in premise accuracy |
| `issues` | `Vec<String>` | Potential issues with premise |
| `logical_form` | `Option<Formula>` | First-order logic translation |
### PremiseType
Classification of premise types for targeted analysis.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PremiseType {
Factual, // Based on observable facts
Definitional, // Clarifies terminology
Assumptive, // Assumed for argument's sake
Inferential, // Derived from other premises
Normative, // Value-based statements
Conditional, // If-then statements
}
```
### DetectedFallacy
Identification of logical fallacies with explanation and severity.
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedFallacy {
pub fallacy: Fallacy,
pub premise_index: Option<usize>,
pub description: String,
pub severity: FlawSeverity,
pub counter_example: Option<String>,
}
```
#### Fields
| `fallacy` | `Fallacy` | Type of logical fallacy |
| `premise_index` | `Option<usize>` | Which premise contains the fallacy |
| `description` | `String` | Explanation of the fallacy |
| `severity` | `FlawSeverity` | Seriousness of the fallacy |
| `counter_example` | `Option<String>` | Example showing why it's fallacious |
### Fallacy
Enumeration of detectable logical fallacies.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Fallacy {
AdHominem,
StrawMan,
FalseDilemma,
SlipperySlope,
CircularReasoning,
AppealToAuthority,
HastyGeneralization,
RedHerring,
FalseCause,
BeggingTheQuestion,
Equivocation,
AppealToEmotion,
}
```
### ArgumentForm
Classification of argument structures for specialized handling.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ArgumentForm {
pub form_type: ArgumentFormType,
pub major_premise: Option<usize>,
pub minor_premise: Option<usize>,
pub conclusion: Option<usize>,
}
```
#### Fields
| `form_type` | `ArgumentFormType` | Type of argument structure |
| `major_premise` | `Option<usize>` | Index of major premise |
| `minor_premise` | `Option<usize>` | Index of minor premise |
| `conclusion` | `Option<usize>` | Index of conclusion |
### ArgumentFormType
Types of recognized argument forms.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArgumentFormType {
CategoricalSyllogism,
HypotheticalSyllogism,
DisjunctiveSyllogism,
ModusPonens,
ModusTollens,
Enthymeme,
Sorites,
}
```
### ValidityStatus
Assessment of whether conclusion logically follows from premises.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ValidityStatus {
Valid, // Conclusion follows logically
Invalid, // Conclusion does not follow
Uncertain, // Cannot determine validity
Partial, // Some parts valid, others not
}
```
### SoundnessStatus
Assessment combining validity with premise truth.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SoundnessStatus {
Sound, // Valid and true premises
Unsound, // Invalid or false premises
Contested, // Premise truth disputed
Provisional, // Temporarily sound
}
```
### Contradiction
Logical contradiction between premises or with conclusion.
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contradiction {
pub r#type: ContradictionType,
pub premise_indices: Vec<usize>,
pub description: String,
pub severity: FlawSeverity,
}
```
#### Fields
| `type` | `ContradictionType` | Type of contradiction |
| `premise_indices` | `Vec<usize>` | Indices of contradictory premises |
| `description` | `String` | Explanation of contradiction |
| `severity` | `FlawSeverity` | Seriousness of contradiction |
### ContradictionType
Types of logical contradictions.
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContradictionType {
Direct, // Explicit contradiction (A and not-A)
Implicit, // Indirect contradiction
Temporal, // Time-based inconsistency
Modal, // Possibility/necessity conflict
}
```
## Methods
### LaserLogic::new()
Create a new LaserLogic module with default configuration.
```rust
pub fn new() -> Self
```
Returns: `LaserLogic` instance with default settings.
Example:
```rust
let module = LaserLogic::new();
assert_eq!(module.name(), "LaserLogic");
assert_eq!(module.version(), "3.0.0");
```
### LaserLogic::with_config()
Create a new LaserLogic module with custom configuration.
```rust
pub fn with_config(config: LaserLogicConfig) -> Self
```
Parameters:
- `config`: `LaserLogicConfig` - Custom configuration parameters
Returns: `LaserLogic` instance with specified configuration.
Example:
```rust
let config = LaserLogicConfig::deep();
let module = LaserLogic::with_config(config);
```
### LaserLogic::analyze_argument()
Direct analysis of a logical argument with premises and conclusion.
```rust
pub fn analyze_argument(
&self,
premises: &[&str],
conclusion: &str
) -> Result<LaserLogicResult>
```
Parameters:
- `premises`: `&[&str]` - Slice of premise statements
- `conclusion`: `&str` - Conclusion statement to evaluate
Returns: `Result<LaserLogicResult>` - Analysis results or error.
Example:
```rust
let module = LaserLogic::new();
let result = module.analyze_argument(
&["All humans are mortal", "Socrates is human"],
"Socrates is mortal"
)?;
```
### LaserLogic::execute()
Execute the LaserLogic module synchronously.
```rust
impl ThinkToolModule for LaserLogic {
fn execute(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput>
}
```
Parameters:
- `context`: `&ThinkToolContext` - Execution context with JSON argument data
Returns: `Result<ThinkToolOutput>` - Structured output or error.
Example:
```rust
let module = LaserLogic::new();
let context = ThinkToolContext::new(r#"{
"premises": ["All birds can fly", "Penguins are birds"],
"conclusion": "Penguins can fly"
}"#);
let result = module.execute(&context)?;
```
### LaserLogic::config()
Get the module configuration.
```rust
pub fn config(&self) -> &LaserLogicConfig
```
Returns: `&LaserLogicConfig` - Reference to current configuration.
Example:
```rust
let module = LaserLogic::new();
let config = module.config();
assert!(config.detect_fallacies);
```
## Usage Examples
### Basic Argument Analysis
```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, ThinkToolModule};
// Create module with default settings
let module = LaserLogic::new();
// Direct argument analysis
let result = module.analyze_argument(
&["All mammals are warm-blooded", "Whales are mammals"],
"Whales are warm-blooded"
)?;
// Check validity
match result.validity_status {
ValidityStatus::Valid => println!("Argument is logically valid"),
ValidityStatus::Invalid => println!("Argument contains logical errors"),
_ => println!("Validity uncertain"),
}
// Check for fallacies
if !result.fallacies.is_empty() {
println!("Found {} fallacies:", result.fallacies.len());
for fallacy in &result.fallacies {
println!("- {}: {}", fallacy.fallacy, fallacy.description);
}
}
```
### JSON Context-Based Execution
```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, ThinkToolModule};
// Create module with custom configuration
let module = LaserLogic::with_config(
LaserLogicConfig::quick()
);
// Prepare JSON context
let context = ThinkToolContext::new(r#"{
"premises": [
"If it rains, then the ground gets wet",
"The ground is wet"
],
"conclusion": "It rained"
}"#);
// Execute analysis
let result = module.execute(&context)?;
// Access fallacy detection
let fallacies = result.get_array("fallacies").unwrap();
if !fallacies.is_empty() {
println!("Detected fallacy: Affirming the consequent");
}
```
### Deep Analysis Configuration
```rust
use reasonkit::thinktool::modules::{LaserLogic, LaserLogicConfig, ThinkToolContext};
// Configure for comprehensive analysis
let config = LaserLogicConfig {
max_premise_depth: 15,
analyze_syllogisms: true,
detect_contradictions: true,
verbose_output: true,
..LaserLogicConfig::deep()
};
let module = LaserLogic::with_config(config);
// Complex argument analysis
let context = ThinkToolContext::new(r#"{
"premises": [
"All philosophers are thinkers",
"Some thinkers are logicians",
"No logicians are illogical"
],
"conclusion": "Some philosophers are logical"
}"#);
let result = module.execute(&context)?;
// Access detailed analysis steps
if let Some(steps) = result.get_array("analysis_steps") {
println!("Analysis steps:");
for step in steps {
println!("- {}", step.as_str().unwrap());
}
}
```
## Error Handling
LaserLogic defines specific error types for logical analysis failures:
### LaserLogicError
Enumeration of all possible module-specific errors.
```rust
#[derive(Error, Debug, Clone)]
pub enum LaserLogicError {
InvalidArgumentFormat { message: String },
TooManyPremises { count: usize, max: usize },
AnalysisTimeout { duration_ms: u64 },
FolTranslationFailed { reason: String },
FallacyDetectionFailed { reason: String },
ContradictionDetectionFailed { reason: String },
}
```
### Error Descriptions
| `InvalidArgumentFormat` | `message` | Malformed argument input JSON |
| `TooManyPremises` | `count`, `max` | Exceeded maximum premise limit |
| `AnalysisTimeout` | `duration_ms` | Logical analysis took too long |
| `FolTranslationFailed` | `reason` | Failed to translate to first-order logic |
| `FallacyDetectionFailed` | `reason` | Error during fallacy detection |
| `ContradictionDetectionFailed` | `reason` | Error detecting contradictions |
### Error Conversion
All LaserLogicError variants are automatically converted to the standard Error type:
```rust
impl From<LaserLogicError> for Error {
fn from(err: LaserLogicError) -> Self {
Error::ThinkToolExecutionError(err.to_string())
}
}
```
### Handling Errors
```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, LaserLogicError};
let module = LaserLogic::new();
let context = ThinkToolContext::new(r#"{"invalid": "json"}"#); // Malformed JSON
match module.execute(&context) {
Ok(result) => {
// Process successful result
println!("Analysis completed with confidence: {}", result.confidence);
}
Err(e) => {
// Handle specific LaserLogic errors
if let Some(ll_err) = e.downcast_ref::<LaserLogicError>() {
match ll_err {
LaserLogicError::InvalidArgumentFormat { message } => {
eprintln!("Invalid argument format: {}", message);
}
LaserLogicError::TooManyPremises { count, max } => {
eprintln!("Too many premises: {} (max: {})", count, max);
}
LaserLogicError::AnalysisTimeout { duration_ms } => {
eprintln!("Analysis timed out after {}ms", duration_ms);
}
_ => eprintln!("LaserLogic error: {}", ll_err),
}
} else {
// Handle other errors
eprintln!("Other error: {}", e);
}
}
}
```
## Performance Considerations
1. **Premise Limit**: Control `max_premise_depth` to manage complexity
2. **Feature Selection**: Disable unused features (e.g., syllogism analysis)
3. **Verbose Output**: Disable for production use to reduce overhead
4. **Timeout Settings**: Set appropriate timeouts based on argument complexity
5. **Fallacy Detection**: Can be disabled for speed-critical applications
## Integration Notes
When using LaserLogic in protocol execution:
```rust
use reasonkit::thinktool::{ProtocolExecutor, ProtocolInput};
// ProtocolExecutor handles LLM integration automatically
let executor = ProtocolExecutor::new()?;
let result = executor.execute(
"laserlogic",
ProtocolInput::json(r#"{"premises": [...], "conclusion": "..."}"#)
).await?;
```
The protocol-based approach provides:
- Automatic LLM selection for complex translations
- Streaming output for real-time progress
- Built-in retry logic for failed logical operations
- Comprehensive execution tracing and audit trails