Skip to content

forestbook1/design_configulator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Design Configurator

An AI-powered orchestration system for architectural, urban, and spatial design that treats design problems as constraint satisfaction and structural exploration problems (SEP). The system coordinates interaction between AI components (for interpretation and orchestration), deterministic computational engines (for validation and exploration), and human decision makers (for final accountability).

✨ Key Features

  • πŸ€– LLM-Powered Intelligence - Natural language requirement interpretation using GPT-4, Claude, or local models
  • πŸ”€ LangGraph Workflow - Advanced workflow orchestration with conditional routing and state management
  • 🌍 Multi-Language Support - Process requirements in English, Chinese, Japanese, Spanish, and more
  • πŸ” Conflict Detection - Automatic identification and resolution of conflicting constraints
  • πŸ“Š Task Decomposition - Intelligent breakdown of complex design problems
  • βœ… Deterministic Validation - Computational engines guarantee correctness
  • 🧩 SEP_Solver Integration - Structural exploration and constraint satisfaction solving with web UI support
  • πŸ”’ Human-in-the-Loop - AI outputs require human approval for critical decisions
  • πŸ“ˆ Cost Tracking - Real-time monitoring of LLM usage and costs
  • ⚑ Response Caching - 90%+ cost reduction for repeated requests
  • πŸ”„ Automatic Fallback - Falls back to rule-based mode on LLM failures
  • πŸ“ Complete Audit Trail - Full traceability from requirements to decisions
  • πŸ”Œ Extensible Architecture - Integrate RAG, MCP tools, or company-specific knowledge sources

πŸ—οΈ Architecture

The system follows a three-layer architecture with strict separation of concerns:

AI Orchestration Layer

AI thinks about the design (interpretation, planning, analysis):

  • Requirement Interpreter - Converts natural language to structured constraints
  • Task Decomposer - Breaks down complex problems into manageable tasks
  • Conflict Analyzer - Identifies and suggests resolutions for conflicts
  • LLM Providers - OpenAI, Anthropic, Local (Ollama), Mock

Deterministic Engine Layer

Computers prove correctness (validation, exploration, simulation):

  • Geometry Engine - Spatial validation and calculations
  • Rule Checker - Regulatory compliance verification
  • Structural Analyzer - Engineering constraint validation
  • Environmental Simulator - Performance analysis
  • Aesthetic Evaluator - Design quality assessment
  • SEP_Solver - Structural exploration and constraint satisfaction solving

Human Interface Layer

Humans take responsibility (approval gates, decision making):

  • Approval Gates - Human confirmation for AI outputs
  • Decision Tracking - Complete audit trail
  • Stakeholder Management - Multi-stakeholder coordination
  • Design State Management - Persistent state tracking

πŸš€ Quick Start

Installation

# Clone the repository
git clone <repository-url>
cd design_configulator

# Install dependencies
pip install -r requirements.txt

Configuration

  1. Set up LLM providers - See docs/README_LLM_SETUP.md
  2. Configure llm_config.json with your API keys
  3. Optional: Set up environment variables in .env

Run the Web Application

python web_app.py

Then open your browser to:

Try Examples

# Interactive CLI
python examples/interactive_cli.py

# Batch processing
python examples/batch_workflow.py

# SEP_Solver integration
python examples/sep_solver_integration_example.py

πŸ“š Documentation

All documentation is in the docs/ directory:

Getting Started

Architecture & Design

Advanced Topics

πŸš€ Quick Start

cd design-configurator

Install dependencies

pip install -r requirements.txt

Install LLM providers (choose one or more)

pip install openai # For OpenAI (GPT-4, GPT-3.5) pip install anthropic # For Anthropic (Claude) pip install requests # For local models (Ollama)

Install development dependencies (optional)

pip install -e ".[dev]"


### LLM Setup

1. **Get an API key** from [OpenAI](https://platform.openai.com/api-keys) (recommended)

2. **Configure** `llm_config.json`:
```json
{
  "enabled": true,
  "provider": "openai",
  "openai_api_key": "sk-proj-YOUR-KEY-HERE",
  "openai_model": "gpt-4o-mini",
  "fallback_to_rules": true,
  "max_cost_per_day": 10.0,
  "enable_response_caching": true
}
  1. Test the setup:
python examples/llm_quickstart.py

Expected output:

βœ“ LLM Enabled: True
βœ“ Provider: openai
βœ“ All examples completed successfully!
Total Cost: $0.0011

See README_LLM_SETUP.md for detailed LLM configuration.

πŸ’» Usage Examples

LangGraph Workflow (Recommended)

from design_configurator.orchestration import WorkflowEngine, WorkflowConfig
from design_configurator.llm_integration import (
    RequirementInterpreter,
    ConflictAnalyzer,
    TaskDecomposer,
)
from design_configurator.llm_integration.provider_factory import create_llm_provider

# Create LLM provider
provider = create_llm_provider(config)

# Initialize components
interpreter = RequirementInterpreter(llm_provider=provider)
analyzer = ConflictAnalyzer(llm_provider=provider)
decomposer = TaskDecomposer(llm_provider=provider)

# Create workflow engine (powered by LangGraph)
engine = WorkflowEngine(
    interpreter=interpreter,
    analyzer=analyzer,
    decomposer=decomposer,
    translator=translator,
    config=WorkflowConfig()
)

# Run complete pipeline with conditional routing
requirements = [
    "The building must have at least 3 floors",
    "Total height must not exceed 15 meters",
    "Maximize natural light"
]

result = engine.run_full_pipeline(requirements)

print(f"Success: {result['success']}")
print(f"Constraints: {result['constraints_count']}")
for stage in result['stages']:
    print(f"  {stage['stage']}: {stage['duration_ms']:.2f}ms")

See docs/LANGGRAPH_INTEGRATION.md for advanced features.

Basic Requirement Interpretation

from design_configurator.llm_integration import (
    LLMConfiguration,
    RequirementInterpreter,
    RequirementInput,
)
from design_configurator.llm_integration.provider_factory import create_llm_provider
import json

# Load configuration
with open('llm_config.json', 'r') as f:
    config = LLMConfiguration.from_dict(json.load(f))

# Create LLM provider
provider = create_llm_provider(config)

# Create interpreter with LLM support
interpreter = RequirementInterpreter(
    llm_provider=provider
)

# Interpret a requirement
requirement = RequirementInput(
    text="The building height must not exceed 50 meters",
    stakeholder_id="architect_001",
    context="Urban residential project"
)

candidates = interpreter.interpret_requirement(requirement)

for candidate in candidates:
    print(f"Type: {candidate.constraint_type.value}")
    print(f"Confidence: {candidate.confidence:.2f}")
    print(f"Source: {candidate.source}")
    print(f"Explanation: {candidate.explanation}")
    print(f"Axes: {', '.join(candidate.evaluation_axes)}")

Multi-Language Support

# English
requirement_en = RequirementInput(
    text="The building must have parking for 100 vehicles",
    stakeholder_id="developer_001"
)

# Chinese (δΈ­ζ–‡)
requirement_zh = RequirementInput(
    text="ε»Ίη­‘εΏ…ι‘»ζœ‰100δΈͺ停车位",
    stakeholder_id="developer_002"
)

# Japanese (ζ—₯本θͺž)
requirement_ja = RequirementInput(
    text="駐車場は100ε°εˆ†εΏ…θ¦γ§γ™",
    stakeholder_id="developer_003"
)

# All work identically!
for req in [requirement_en, requirement_zh, requirement_ja]:
    candidates = interpreter.interpret_requirement(req)
    print(f"Interpreted: {candidates[0].explanation}")

Conflict Analysis

from design_configurator.llm_integration import ConflictAnalyzer
from design_configurator.core.models import Constraint, ConstraintSource
from design_configurator.core.types import ConstraintType

analyzer = ConflictAnalyzer(
    llm_provider=provider
)

constraints = [
    Constraint(
        natural_language="Building height must not exceed 50 meters",
        type=ConstraintType.HARD,
        source=ConstraintSource(stakeholder_id="city_planner")
    ),
    Constraint(
        natural_language="Building must be at least 60 meters tall",
        type=ConstraintType.HARD,
        source=ConstraintSource(stakeholder_id="developer")
    ),
]

conflicts = analyzer.analyze_conflicts(constraints)

for conflict in conflicts:
    print(f"Conflict Type: {conflict.conflict_type}")
    print(f"Severity: {conflict.severity}")
    print(f"Explanation: {conflict.explanation}")
    print(f"Resolution Strategies:")
    for strategy in conflict.resolution_strategies:
        print(f"  - {strategy}")

Usage Monitoring

# Get real-time usage statistics
stats = provider.get_usage_stats()

print(f"Total Requests: {stats.request_count}")
print(f"Total Tokens: {stats.total_tokens:,}")
print(f"Total Cost: ${stats.total_cost_usd:.4f}")
print(f"Average Latency: {stats.average_latency_ms:.2f}ms")
print(f"Cache Hit Rate: {stats.cache_hits / (stats.cache_hits + stats.cache_misses) * 100:.1f}%")

SEP_Solver Integration

The system integrates with SEP_Solver for structural exploration and constraint satisfaction:

from design_configurator.solvers import SEPSolverAdapter
from design_configurator.core.models import DesignProblem, Constraint
from design_configurator.core.types import ConstraintType
from design_configurator.core.expressions import InequalityExpression, ExpressionValue

# Create a design problem with constraints
problem = DesignProblem(
    problem_id="building_001",
    constraints=[
        Constraint(
            id="c1",
            natural_language="Height must not exceed 15 meters",
            type=ConstraintType.HARD,
            layer="regulation",
            expression=InequalityExpression(
                operator="<=",
                left=ExpressionValue(type="var", value="height"),
                right=ExpressionValue(type="const", value=15)
            )
        )
    ]
)

# Define variables
variables = {
    "height": {
        "type": "number",
        "domain": {"min": 0, "max": 20},
        "unit": "meters"
    }
}

# Solve with SEP_Solver
adapter = SEPSolverAdapter()
result = adapter.solve_problem(problem, variables)

if result.success:
    print(f"Found {len(result.solutions)} solutions")
    for solution in result.solutions:
        print(f"  Height: {solution.variable_assignments['height']} meters")
else:
    print(f"No solutions found: {result.error_message}")

Web UI Integration:

The integrated workflow page provides a "Solve with SEP_Solver" button that:

  • Collects problem definition from the web form
  • Sends it to the /api/solve-with-sep endpoint
  • Displays solutions in a formatted table
  • Shows solve time, iterations, and metadata

See docs/SEP_SOLVER_INTEGRATION.md for complete documentation.

Interactive CLI

For an interactive experience, use the CLI tools:

# Full-featured CLI with session management
python examples/interactive_cli.py

# Simple one-requirement-at-a-time mode
python examples/simple_interactive.py

Interactive CLI Features:

  • 🎯 Add requirements interactively
  • πŸ“‹ List and manage requirements
  • ⚠️ Analyze conflicts in real-time
  • οΏ½ Decompose problems into tasks
  • οΏ½πŸ’Ύ Save/load sessions
  • πŸ“Š Track usage and costs
  • 🌍 Multi-language support
  • πŸ”„ Alternative interpretations

See examples/INTERACTIVE_DEMO.md for detailed usage guide.

πŸ§ͺ Testing

Run Tests

# Run all tests
pytest

# Run unit tests only
pytest -m unit

# Run property-based tests only  
pytest -m property

# Run LLM integration tests
pytest tests/unit/llm_integration/

# Run with coverage
pytest --cov=design_configurator --cov-report=html

Run Examples

# Quick start (all features)
python examples/llm_quickstart.py

# Japanese language test
python examples/japanese_test.py

# Interactive CLI (full-featured)
python examples/interactive_cli.py

# Simple interactive mode
python examples/simple_interactive.py

See examples/INTERACTIVE_DEMO.md for interactive usage guide.

πŸ“ Project Structure

design-configurator/
β”œβ”€β”€ src/design_configurator/
β”‚   β”œβ”€β”€ core/                           # Core data models and types
β”‚   β”‚   β”œβ”€β”€ models.py                   # Constraint, Task, Conflict models
β”‚   β”‚   β”œβ”€β”€ types.py                    # Enums and type definitions
β”‚   β”‚   └── expressions.py              # Constraint expression types
β”‚   β”‚
β”‚   β”œβ”€β”€ llm_integration/                # LLM-powered AI components
β”‚   β”‚   β”œβ”€β”€ requirement_interpreter.py  # Natural language β†’ constraints
β”‚   β”‚   β”œβ”€β”€ task_decomposer.py         # Problem β†’ tasks
β”‚   β”‚   β”œβ”€β”€ conflict_analyzer.py       # Conflict detection & resolution
β”‚   β”‚   β”œβ”€β”€ openai_provider.py         # OpenAI (GPT-4, GPT-3.5)
β”‚   β”‚   β”œβ”€β”€ anthropic_provider.py      # Anthropic (Claude)
β”‚   β”‚   β”œβ”€β”€ local_provider.py          # Local models (Ollama)
β”‚   β”‚   β”œβ”€β”€ mock_provider.py           # Testing provider
β”‚   β”‚   β”œβ”€β”€ cached_provider.py         # Response caching wrapper
β”‚   β”‚   β”œβ”€β”€ configuration.py           # LLM configuration
β”‚   β”‚   β”œβ”€β”€ pricing.py                 # Cost tracking
β”‚   β”‚   β”œβ”€β”€ usage_tracker.py           # Usage statistics
β”‚   β”‚   β”œβ”€β”€ validator.py               # Output validation
β”‚   β”‚   β”œβ”€β”€ security.py                # API key encryption
β”‚   β”‚   └── audit_logging.py           # Audit trail
β”‚   β”‚
β”‚   β”œβ”€β”€ solvers/                        # Solver integrations
β”‚   β”‚   β”œβ”€β”€ sep_adapter.py             # SEP_Solver adapter
β”‚   β”‚   β”œβ”€β”€ sep_solver_client.py       # SEP_Solver client
β”‚   β”‚   └── constraint_evaluator.py    # Constraint expression evaluator
β”‚   β”‚
β”‚   β”œβ”€β”€ deterministic_engines/          # Computational validation
β”‚   β”‚   β”œβ”€β”€ geometry_engine.py         # Spatial validation
β”‚   β”‚   β”œβ”€β”€ rule_checker.py            # Regulatory compliance
β”‚   β”‚   β”œβ”€β”€ structural_analyzer.py     # Engineering validation
β”‚   β”‚   └── environmental_simulator.py # Performance analysis
β”‚   β”‚
β”‚   β”œβ”€β”€ human_interface/                # Human decision gates
β”‚   β”‚   β”œβ”€β”€ approval_gates.py          # Human confirmation
β”‚   β”‚   └── decision_tracking.py       # Audit trail
β”‚   β”‚
β”‚   └── state_management/               # Design state persistence
β”‚       └── design_state.py            # State management
β”‚
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ unit/                          # Unit tests
β”‚   β”‚   β”œβ”€β”€ llm_integration/          # LLM component tests
β”‚   β”‚   β”œβ”€β”€ solvers/                  # Solver integration tests
β”‚   β”‚   └── core/                     # Core model tests
β”‚   β”œβ”€β”€ test_properties.py            # Property-based tests
β”‚   └── conftest.py                   # Test fixtures
β”‚
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ llm_quickstart.py             # Quick start demo
β”‚   β”œβ”€β”€ japanese_test.py              # Multi-language demo
β”‚   └── sep_solver_integration_example.py  # SEP_Solver demo
β”‚
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ SEP_SOLVER_INTEGRATION.md     # SEP_Solver integration guide
β”‚   β”œβ”€β”€ SEP_SOLVER_QUICK_START.md     # SEP_Solver quick start
β”‚   β”œβ”€β”€ CONSTRAINT_EVALUATION_EXAMPLES.md  # Constraint examples
β”‚   └── SEP_SOLVER_TROUBLESHOOTING.md # Troubleshooting guide
β”‚
β”œβ”€β”€ llm_config.json                    # LLM configuration
β”œβ”€β”€ README.md                          # This file
β”œβ”€β”€ README_LLM_SETUP.md               # Detailed LLM setup guide
└── requirements.txt                   # Python dependencies

πŸ”‘ Key Principles

1. AI Safety

AI outputs are never executed directly - they require validation or human approval:

# All AI outputs require human confirmation
for candidate in candidates:
    assert candidate.requires_human_confirmation is True

2. Reproducibility

Deterministic engines guarantee identical results for identical inputs:

# Same input always produces same output
result1 = geometry_engine.validate(constraint)
result2 = geometry_engine.validate(constraint)
assert result1 == result2

3. Traceability

Complete audit trail from requirements to final design decisions:

# Every decision is logged
audit_logger.log_llm_request(prompt, response, cost)
audit_logger.log_human_decision(decision, justification)

4. Accountability

Human decision gates for all critical operations:

# Critical decisions require human approval
if candidate.constraint_type == ConstraintType.HARD:
    approval = await human_interface.request_approval(candidate)
    if not approval.approved:
        continue

5. Cost Control

Real-time monitoring and daily limits prevent unexpected charges:

# Automatic cost limits
config.max_cost_per_day = 10.0  # $10 daily limit
config.enable_cost_tracking = True

# Falls back to rule-based mode when limit reached
if stats.total_cost_usd >= config.max_cost_per_day:
    use_llm = False

πŸ“Š LLM Provider Comparison

Provider Model Cost/Request Quality Speed Best For
OpenAI gpt-4o-mini $0.0001-0.0007 ⭐⭐⭐⭐ ⚑⚑⚑ Recommended
OpenAI gpt-4o $0.002-0.01 ⭐⭐⭐⭐⭐ ⚑⚑ Critical apps
OpenAI gpt-3.5-turbo $0.0001-0.0003 ⭐⭐⭐ ⚑⚑⚑⚑ Development
Anthropic claude-3-sonnet $0.001-0.005 ⭐⭐⭐⭐ ⚑⚑⚑ Alternative
Local llama2 $0 ⭐⭐ ⚑ Privacy/offline
Mock - $0 ⭐ ⚑⚑⚑⚑⚑ Testing

Recommendation: Start with gpt-4o-mini - best balance of quality, speed, and cost.

πŸ”’ Security

API Key Protection

  • Never commit API keys to version control
  • Use environment variables or encrypted config
  • Add llm_config.json to .gitignore

Cost Controls

  • Set daily spending limits
  • Enable real-time cost tracking
  • Automatic fallback when limits reached

Audit Logging

  • All LLM requests logged
  • Complete traceability
  • Human decision tracking

Data Privacy

  • Use local models for sensitive data
  • API key encryption support
  • Configurable data retention

πŸ“ˆ Performance Optimization

Response Caching

Enable caching to reduce costs by 90%+:

{
  "enable_response_caching": true,
  "cache_ttl_hours": 24
}

Model Selection

  • Development: gpt-4o-mini or mock
  • Production: gpt-4o-mini (recommended)
  • Critical: gpt-4o (only when needed)

Token Optimization

  • Set appropriate max_tokens limits
  • Use concise prompts
  • Batch similar requests

πŸ› Troubleshooting

Common Issues

"Model not found"

  • Use gpt-4o-mini instead of gpt-4
  • Verify you have access to the model

"Insufficient quota"

  • Add credits to your OpenAI account
  • System automatically falls back to rule-based mode

"Authentication failed"

  • Check API key in llm_config.json
  • Verify key hasn't been revoked

Slow responses

  • Enable caching for repeated requests
  • Use faster models like gpt-4o-mini
  • Reduce max_tokens

See README_LLM_SETUP.md for detailed troubleshooting.

πŸ“š Documentation

🀝 Contributing

  1. Follow the established architecture patterns
  2. Maintain strict layer separation (AI / Deterministic / Human)
  3. Add property-based tests for new functionality
  4. Ensure all AI outputs require human confirmation
  5. Update documentation for new components
  6. Test with multiple LLM providers

Development Setup

# Install development dependencies
pip install -e ".[dev]"

# Set up pre-commit hooks
pre-commit install

# Run code quality checks
black src/ tests/
isort src/ tests/
mypy src/
flake8 src/ tests/

# Run tests
pytest

πŸ“‹ Requirements Coverage

This implementation covers all requirements with comprehensive testing:

  • βœ… Requirements 1-19: Complete implementation with traceability
  • βœ… Properties 1-39: Property-based testing using Hypothesis
  • βœ… Layer Separation: Strict boundaries between AI, deterministic, and human layers
  • βœ… Safety Guarantees: AI outputs never execute without validation/approval
  • βœ… Multi-Language: Support for English, Chinese, Japanese, Spanish, and more
  • βœ… Cost Controls: Real-time monitoring and daily limits
  • βœ… Audit Trail: Complete traceability from requirements to decisions

🎯 Roadmap

  • Core constraint satisfaction framework
  • LLM integration (OpenAI, Anthropic, Local)
  • Multi-language support
  • Conflict detection and resolution
  • Task decomposition
  • Cost tracking and optimization
  • Response caching
  • Audit logging
  • SEP_Solver integration with constraint evaluation
  • Web UI for SEP_Solver integration
  • Web UI for human approval gates
  • Advanced visualization tools
  • Integration with CAD systems
  • Real-time collaboration features

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

Built with:

  • OpenAI GPT-4 for natural language understanding
  • Anthropic Claude for alternative LLM support
  • Hypothesis for property-based testing
  • Pydantic for data validation

Ready to get started?

  1. Install dependencies: pip install -r requirements.txt
  2. Set up LLM: See README_LLM_SETUP.md
  3. Run quick start: python examples/llm_quickstart.py
  4. Try SEP_Solver: python examples/sep_solver_integration_example.py
  5. Start building! πŸš€

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors