835 MB
10,492 files
Updated 6 months ago
README.md

CA11: Chain of Thought

🧠 Overview

This project implements advanced Chain of Thought (CoT) reasoning systems that enable AI models to solve complex problems through step-by-step reasoning. It features multiple CoT approaches, integration with modern LLMs like Gemini, and comprehensive evaluation frameworks for reasoning capabilities.

🎯 Key Features

Core Capabilities

  • Chain of Thought Reasoning: Step-by-step problem solving
  • Multi-Step Inference: Complex multi-step reasoning processes
  • Reasoning Chain Generation: Automatic generation of reasoning chains
  • Problem Decomposition: Breaking complex problems into simpler steps
  • Verification and Validation: Ensuring reasoning correctness

Advanced Features

  • Gemini API Integration: Advanced reasoning with Google's Gemini
  • LangChain Workflows: Complex reasoning pipeline orchestration
  • LangGraph Integration: Multi-step reasoning workflows
  • Multi-Modal Reasoning: Reasoning across different data modalities
  • Interactive Reasoning: Human-in-the-loop reasoning processes

🏗️ System Architecture

1. Chain of Thought Pipeline

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Problem   │    │ Reasoning   │    │ Solution    │
│  Analysis   │───▶│ Chain Gen.  │───▶│ Generation  │
└─────────────┘    └─────────────┘    └─────────────┘

2. Multi-Step Reasoning Architecture

┌─────────────────────────────────────────────────────────┐
│                Chain of Thought Engine                 │
├─────────────┬─────────────┬─────────────┬─────────────┤
│ Problem     │ Step        │ Reasoning   │ Solution    │
│ Parser      │ Generator   │ Validator   │ Synthesizer │
└─────────────┴─────────────┴─────────────┴─────────────┘

3. LLM Integration Framework

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Input     │    │ LLM         │    │ Reasoning   │
│ Processing  │───▶│ Integration │───▶│ Chain       │
└─────────────┘    └─────────────┘    └─────────────┘

📁 Project Structure

CA11_chain_of_thought/
├── CA11.ipynb                    # Main Jupyter notebook
├── main_execution.py             # Main execution script
├── advanced_execution.py         # Advanced execution script
├── test_gemini.py                # Gemini API testing
├── test_components.py            # Component testing
├── additional_analysis.py       # Additional analysis tools
├── gemini_config.py             # Gemini configuration
├── src/                          # Source code
│   ├── reasoning/                # Reasoning components
│   │   ├── chain_of_thought.py   # Core CoT implementation
│   │   ├── step_generator.py     # Reasoning step generation
│   │   ├── problem_decomposer.py # Problem decomposition
│   │   └── reasoning_validator.py # Reasoning validation
│   ├── llm/                      # LLM integration
│   │   ├── gemini_integration.py # Gemini API integration
│   │   ├── langchain_workflows.py # LangChain workflows
│   │   ├── langgraph_reasoning.py # LangGraph integration
│   │   └── prompt_templates.py   # Prompt templates
│   ├── evaluation/               # Evaluation components
│   │   ├── reasoning_metrics.py  # Reasoning evaluation metrics
│   │   ├── chain_analyzer.py     # Chain analysis tools
│   │   ├── correctness_checker.py # Correctness validation
│   │   └── performance_analyzer.py # Performance analysis
│   ├── applications/             # Application domains
│   │   ├── mathematical_reasoning.py # Mathematical reasoning
│   │   ├── logical_reasoning.py  # Logical reasoning
│   │   ├── commonsense_reasoning.py # Commonsense reasoning
│   │   └── scientific_reasoning.py # Scientific reasoning
│   └── utils/                    # Utility functions
│       ├── visualization.py     # Visualization tools
│       ├── analysis.py          # Analysis utilities
│       └── io_utils.py          # I/O utilities
├── config/                       # Configuration files
│   ├── gemini_config.yaml       # Gemini configuration
│   ├── reasoning_config.yaml    # Reasoning configuration
│   └── evaluation_config.yaml   # Evaluation configuration
├── tests/                        # Test files
│   ├── test_reasoning.py         # Reasoning tests
│   ├── test_llm_integration.py   # LLM integration tests
│   └── test_evaluation.py        # Evaluation tests
├── results/                      # Output results
├── logs/                         # Execution logs
├── visualizations/               # Generated visualizations
├── requirements.txt              # Python dependencies
├── env_example.txt               # Environment variables example
├── run.sh                        # Execution script
└── README.md                     # This file

🚀 Quick Start

Prerequisites

  • Python 3.8+
  • Google Gemini API key (for advanced features)
  • Jupyter Notebook

Installation

  1. Clone the repository
git clone <repository-url>
cd CA11_chain_of_thought
  1. Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Set up API keys
# Copy environment template
cp env_example.txt .env

# Edit .env file with your API keys
# GOOGLE_API_KEY=your_gemini_api_key_here
  1. Run the project
chmod +x run.sh
./run.sh

Manual Execution

# Run basic execution
python main_execution.py

# Run advanced execution with Gemini
python advanced_execution.py

# Test Gemini integration
python test_gemini.py

# Test components
python test_components.py

# Run Jupyter notebook
jupyter notebook CA11.ipynb

🔧 Configuration

Environment Variables

# .env file
GOOGLE_API_KEY=your_gemini_api_key_here
GEMINI_MODEL=gemini-pro
REASONING_TEMPERATURE=0.1
MAX_REASONING_STEPS=10

Reasoning Configuration

# config/reasoning_config.yaml
chain_of_thought:
  max_steps: 10
  step_timeout: 30
  validation_enabled: true
  confidence_threshold: 0.7

problem_decomposition:
  enabled: true
  max_subproblems: 5
  decomposition_strategy: "hierarchical"

reasoning_validation:
  enabled: true
  validation_methods: ["logical", "mathematical", "commonsense"]
  error_detection: true

📊 Features & Capabilities

1. Chain of Thought Reasoning

  • Step-by-Step Reasoning: Breaking problems into logical steps
  • Reasoning Chain Generation: Automatic generation of reasoning chains
  • Problem Decomposition: Breaking complex problems into simpler parts
  • Multi-Step Inference: Performing complex multi-step reasoning

2. LLM Integration

  • Gemini API: Advanced reasoning with Google's Gemini
  • LangChain Workflows: Complex reasoning pipeline orchestration
  • LangGraph Integration: Multi-step reasoning workflows
  • Prompt Engineering: Optimized prompts for reasoning tasks

3. Reasoning Validation

  • Logical Validation: Checking logical consistency
  • Mathematical Validation: Verifying mathematical correctness
  • Commonsense Validation: Ensuring commonsense reasoning
  • Error Detection: Identifying reasoning errors

4. Multi-Domain Applications

  • Mathematical Reasoning: Solving mathematical problems
  • Logical Reasoning: Performing logical inference
  • Commonsense Reasoning: Applying commonsense knowledge
  • Scientific Reasoning: Scientific problem solving

🧪 Experiments & Benchmarks

1. Mathematical Reasoning

  • Arithmetic Problems: Basic arithmetic operations
  • Algebraic Problems: Solving algebraic equations
  • Geometric Problems: Geometric reasoning tasks
  • Calculus Problems: Calculus-based reasoning

2. Logical Reasoning

  • Deductive Reasoning: Logical deduction tasks
  • Inductive Reasoning: Pattern recognition and induction
  • Abductive Reasoning: Best explanation inference
  • Causal Reasoning: Cause-effect relationships

3. Commonsense Reasoning

  • Physical Reasoning: Understanding physical laws
  • Social Reasoning: Understanding social situations
  • Temporal Reasoning: Understanding time and sequence
  • Spatial Reasoning: Understanding spatial relationships

4. Scientific Reasoning

  • Hypothesis Testing: Testing scientific hypotheses
  • Experimental Design: Designing experiments
  • Data Analysis: Analyzing scientific data
  • Theory Building: Constructing scientific theories

📈 Usage Examples

Basic Chain of Thought

from src.reasoning.chain_of_thought import ChainOfThoughtReasoner

# Initialize CoT reasoner
reasoner = ChainOfThoughtReasoner()

# Solve a problem using CoT
problem = "If a train leaves station A at 60 mph and another leaves station B at 40 mph, and they are 200 miles apart, when will they meet?"
solution = reasoner.solve(problem)

print(f"Solution: {solution['answer']}")
print(f"Reasoning chain: {solution['reasoning_chain']}")

Advanced Reasoning with Gemini

from src.llm.gemini_integration import GeminiCoTReasoner

# Initialize Gemini CoT reasoner
gemini_reasoner = GeminiCoTReasoner()

# Solve complex problem
complex_problem = "Design an experiment to test whether plants grow better with classical music or rock music."
result = gemini_reasoner.solve(complex_problem)

print(f"Experimental design: {result['solution']}")
print(f"Reasoning steps: {result['steps']}")
print(f"Confidence: {result['confidence']}")

Problem Decomposition

from src.reasoning.problem_decomposer import ProblemDecomposer

# Initialize problem decomposer
decomposer = ProblemDecomposer()

# Decompose complex problem
complex_problem = "How can we reduce carbon emissions in cities?"
subproblems = decomposer.decompose(complex_problem)

print(f"Subproblems: {subproblems}")

Reasoning Validation

from src.evaluation.reasoning_validator import ReasoningValidator

# Initialize validator
validator = ReasoningValidator()

# Validate reasoning chain
reasoning_chain = [
    "All birds can fly",
    "Penguins are birds",
    "Therefore, penguins can fly"
]

validation_result = validator.validate(reasoning_chain)
print(f"Validation result: {validation_result}")
print(f"Errors found: {validation_result['errors']}")

🔍 Advanced Features

1. Multi-Modal Reasoning

  • Text-Image Reasoning: Reasoning across text and images
  • Audio-Visual Reasoning: Reasoning across audio and visual data
  • Cross-Modal Integration: Integrating different modalities
  • Multimodal Chain Generation: Generating chains across modalities

2. Interactive Reasoning

  • Human-in-the-Loop: Incorporating human feedback
  • Interactive Refinement: Refining reasoning with human input
  • Collaborative Reasoning: Collaborative problem solving
  • Real-Time Feedback: Providing real-time feedback

3. Adaptive Reasoning

  • Dynamic Chain Length: Adapting chain length to problem complexity
  • Strategy Selection: Selecting appropriate reasoning strategies
  • Context Awareness: Adapting to different contexts
  • Learning from Errors: Improving based on reasoning errors

4. Performance Optimization

  • Parallel Reasoning: Parallel reasoning processes
  • Caching: Caching intermediate results
  • Memory Management: Efficient memory usage
  • Speed Optimization: Optimizing reasoning speed

🛠️ Development

Adding New Reasoning Strategies

  1. Create strategy class in src/reasoning/
  2. Implement reasoning logic
  3. Add configuration parameters
  4. Add tests for new strategy
  5. Update documentation

Adding New Evaluation Metrics

  1. Create metric class in src/evaluation/
  2. Implement evaluation logic
  3. Add to evaluation framework
  4. Add tests for new metric
  5. Update documentation

Custom LLM Integration

# Add new LLM provider
from src.llm.base_llm import BaseLLM

class CustomLLM(BaseLLM):
    def __init__(self, config):
        super().__init__(config)

    def generate_reasoning_chain(self, problem):
        # Implement custom reasoning logic
        pass

📚 Theoretical Background

Chain of Thought Reasoning

  • Step-by-Step Reasoning: Breaking problems into logical steps
  • Problem Decomposition: Dividing complex problems into simpler parts
  • Multi-Step Inference: Performing complex reasoning processes
  • Reasoning Validation: Ensuring reasoning correctness

Key Concepts

  • Reasoning Chain: Sequence of reasoning steps
  • Problem Decomposition: Breaking problems into subproblems
  • Inference: Drawing conclusions from premises
  • Validation: Checking reasoning correctness

📖 References

Key Papers

  • Wei, J., et al. "Chain-of-thought prompting elicits reasoning in large language models"
  • Kojima, T., et al. "Large language models are zero-shot reasoners"
  • Zhou, D., et al. "Least-to-most prompting enables complex reasoning in large language models"

Resources

📞 Support

Issues

  • Report bugs via GitHub Issues
  • Request features via GitHub Discussions
  • Ask questions via GitHub Discussions

Documentation

  • API Documentation: docs/api/
  • Tutorials: docs/tutorials/
  • Examples: examples/

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Chain of thought research community
  • Google Gemini API team
  • LangChain and LangGraph developers
  • Reasoning researchers and contributors

✅ Assessment Checklist

Before submission, ensure you have completed:

  • Implement Chain of Thought Engine: Build step-by-step reasoning system with automatic reasoning chain generation
  • Integrate Gemini API: Connect Google Gemini for advanced reasoning with prompt optimization
  • Develop Problem Decomposition: Create system to break complex problems into manageable steps
  • Comprehensive Evaluation: Test on mathematical, logical, and commonsense reasoning benchmarks with metrics

📚 Course Resources

Related Lecture Decks

  • Slides 11: Chain of Thought - Core concepts and techniques
  • Slides 13-14: Test-Time Scaling - Advanced reasoning approaches
  • Slides 19: Reasoning and Abstraction - Systematic reasoning methods

Annotated Notes & Exercises

  • A2I_S11: Chain of Thought - Step-by-step reasoning techniques
  • A2I_S13-14: Test-Time Techniques - Advanced adaptation methods
  • A2I_S19: Reasoning Foundations - Core reasoning principles

Companion Assignments

  • CA12: Tree of Thoughts - Multi-path reasoning extension
  • CA13: Game of 24 - Applied reasoning for problem solving
  • CA8: Neural Program Synthesis - Structured reasoning for code generation

Last Updated: January 2025
Version: 1.0.0
Maintainer: AI Systems Course Team

Total size
835 MB
Files
10,492
Last updated
Jun 17
Pre-warmed CDN
US EU US EU

Contributors