🚀 KIC-AI Assistant v1.3.0 - Complete project with 3 AI interaction modes
✨ New Features: - 3 AI Interaction Modes: Analysis (Safe), Advisory (Guided), Assistant (Interactive) - Mode-specific AI responses and behavior - Enhanced user interface with mode selection dropdown - Step-by-step guidance in Advisory mode - Interactive assistance framework for future automation 📸 Documentation: - Added 3 screenshots showing main interface, mode selection, and PCB analysis - Comprehensive README with mode explanations and examples - Installation guide (INSTALL.md) with troubleshooting - Upgrade notes and changelog 🔧 Technical Improvements: - Enhanced AI dialog with mode detection - Context-aware conversation system - Improved safety warnings and user guidance - Professional project structure with proper organization 📦 Ready for Distribution: - Complete plugin package for KiCad 9.0+ - Compatible with Ollama LLM integration - Supports both PCB and schematic analysis - Three ZIP releases available for different use cases
This commit is contained in:
+37
@@ -0,0 +1,37 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.pyc
|
||||
|
||||
# MacOS
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# KiCad backup files
|
||||
*.bak
|
||||
*-cache.lib
|
||||
*-rescue.lib
|
||||
*.kicad_pcb-bak
|
||||
*.sch-bak
|
||||
|
||||
# Release files
|
||||
*.zip
|
||||
!kic-ai-assistant-v*.zip
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
# Chang## [1.2.1] - 2025-07-30
|
||||
|
||||
### Documentation & UX Improvements
|
||||
- **Clarified Usage Instructions**: Updated README to clearly explain plugin is accessed via PCB Editor toolbar
|
||||
- **Better User Guidance**: Enhanced dialogs to explain analysis mode selection
|
||||
- **Improved Error Handling**: Clear messaging when no project is loaded
|
||||
- **Updated Documentation**: Accurate description of how dual-mode analysis works
|
||||
|
||||
### Bug Fixes
|
||||
- Fixed user expectations about toolbar location (PCB Editor only, not Schematic Editor)
|
||||
- Improved context selection dialog with clearer explanations
|
||||
- Better handling of empty/no project scenarios
|
||||
|
||||
## [1.2.0] - 2025-07-30
|
||||
|
||||
### Major Features Added
|
||||
- **Dual Analysis Mode**: Plugin now offers both PCB Layout and Schematic/Circuit analysis modes
|
||||
- **Smart Context Selection**: User can choose between analyzing circuit design or PCB layout
|
||||
- **Schematic Analysis**: Complete circuit analysis with component grouping, value analysis, and net connectivity
|
||||
- **Enhanced User Guidance**: Clear dialogs explain analysis options and project requirements
|
||||
|
||||
### New Schematic/Circuit Analysis Capabilities
|
||||
- Circuit component analysis grouped by type (R, C, L, U, etc.)
|
||||
- Net connectivity analysis for schematic review
|
||||
- Component value and footprint validation
|
||||
- Circuit topology insights and design recommendations
|
||||
- Circuit-focused AI prompts and responses
|
||||
|
||||
### Enhanced User Experience
|
||||
- Context selection dialog when launching plugin
|
||||
- Dynamic button labels: "Analyze PCB" or "Analyze Schematic" based on selected mode
|
||||
- Mode-specific welcome messages and capabilities
|
||||
- Better error handling and user guidance for project loading
|
||||
- Clear instructions when no project is loaded
|
||||
|
||||
### Technical Improvements
|
||||
- Dual-context architecture supporting both PCB and circuit analysis workflows
|
||||
- Enhanced AI system prompts tailored for circuit design vs PCB layout advice
|
||||
- Improved component data collection for schematic analysis
|
||||
- Better integration with KiCad's design data structures
|
||||
|
||||
### Important Usage Notes
|
||||
- Plugin is accessed through PCB Editor toolbar (KiCad limitation)
|
||||
- Can analyze both schematic and PCB data from the same interface
|
||||
- User selects analysis focus when plugin starts
|
||||
- Requires loaded KiCad project (.kicad_pcb file)
|
||||
|
||||
## [1.1.3] - 2025-07-30
|
||||
|
||||
### Fixed
|
||||
- Plugin icon now displays correctly in KiCad toolbar using Fabrication Toolkit pattern
|
||||
- Implemented proper icon support with both icon_file_name and dark_icon_file_name
|
||||
- Fixed ActionPlugin initialization following KiCad best practices
|
||||
- All UI text and comments now in English for consistency
|
||||
|
||||
### Improved
|
||||
- Plugin initialization follows established KiCad plugin patterns
|
||||
- Better icon handling for both light and dark themes
|
||||
- Cleaner codebase with English documentation
|
||||
|
||||
## [1.1.2] - 2025-07-30
|
||||
|
||||
### Added
|
||||
- Robot icon for better toolbar appearance
|
||||
- Detailed component analysis with specific component information
|
||||
- Enhanced AI context with full PCB data for every user question
|
||||
- Specific component lookup capabilities (e.g., asking about "R1" or specific resistors)
|
||||
|
||||
### Improved
|
||||
- AI now provides specific answers referencing actual component values and positions
|
||||
- Better PCB context integration for targeted component questions
|
||||
- Increased context window for more detailed analysis
|
||||
- Enhanced conversation memory with PCB awareness
|
||||
|
||||
### Fixed
|
||||
- Plugin icon now displays properly in KiCad toolbar
|
||||
- AI responses now reference specific components instead of giving generic answers
|
||||
|
||||
## [1.1.1] - 2025-07-30log
|
||||
|
||||
All notable changes to the KIC-AI Assistant plugin will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.1.0] - 2025-07-30
|
||||
|
||||
### Added
|
||||
- **Conversation Memory**: AI now remembers previous messages in the conversation
|
||||
- **Context Management**: Maintains last 20 messages for contextual responses
|
||||
- **Show Context Button**: View what the AI remembers from your conversation
|
||||
- **Improved Prompting**: Enhanced system prompts for better context awareness
|
||||
- **Larger Context Window**: Increased to 4096 tokens for longer conversations
|
||||
|
||||
### Changed
|
||||
- **Enhanced AI Responses**: AI can now reference previous questions and build upon earlier discussions
|
||||
- **Better Context Handling**: PCB analysis results are included in conversation context
|
||||
- **Improved Welcome Message**: Updated to explain conversation memory feature
|
||||
|
||||
### Fixed
|
||||
- **Conversation Continuity**: AI no longer treats each message as isolated
|
||||
- **Memory Management**: Automatic cleanup of old messages to prevent memory issues
|
||||
|
||||
## [1.0.0] - 2025-07-29
|
||||
|
||||
### Added
|
||||
- Initial release of KIC-AI Assistant
|
||||
- AI-powered chat interface for PCB design assistance
|
||||
- Automatic PCB analysis functionality
|
||||
- Ollama integration with llama3.2:3b model
|
||||
- Real-time design advice and suggestions
|
||||
- English interface with larger, readable fonts
|
||||
- Support for KiCad 6.0+
|
||||
- Component analysis and statistics
|
||||
- Net and track information display
|
||||
- Board dimension reporting
|
||||
- Design best practices recommendations
|
||||
|
||||
### Features
|
||||
- **Chat Interface**: Interactive dialog for asking PCB design questions
|
||||
- **PCB Analysis**: Click-button analysis of current PCB design
|
||||
- **AI Responses**: Context-aware responses using local LLM
|
||||
- **Privacy-First**: All AI processing happens locally via Ollama
|
||||
- **User-Friendly**: Large fonts and clear English interface
|
||||
|
||||
### Requirements
|
||||
- KiCad 6.0 or higher
|
||||
- Python 3.7+
|
||||
- Ollama with llama3.2:3b model
|
||||
- requests Python package
|
||||
|
||||
### Installation
|
||||
- Plugin installable via KiCad Plugin and Content Manager
|
||||
- Also supports manual installation
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
# KIC-AI Assistant Installation Guide
|
||||
|
||||
## Quick Install (Recommended)
|
||||
|
||||
1. **Download** the latest release: `kic-ai-assistant-v1.3.0-with-screenshots.zip`
|
||||
2. **Open KiCad** → Plugin and Content Manager
|
||||
3. **Click** "Install from File"
|
||||
4. **Select** the downloaded ZIP file
|
||||
5. **Restart KiCad**
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the plugin, ensure you have:
|
||||
|
||||
### 1. Ollama Setup
|
||||
```bash
|
||||
# Install Ollama from https://ollama.ai
|
||||
ollama pull llama3.2:3b
|
||||
ollama serve
|
||||
```
|
||||
|
||||
### 2. Python Requirements
|
||||
```bash
|
||||
pip install requests
|
||||
```
|
||||
|
||||
## Manual Installation
|
||||
|
||||
If the Plugin Manager doesn't work:
|
||||
|
||||
### Windows
|
||||
Copy plugin to: `%APPDATA%/kicad/9.0/scripting/plugins/`
|
||||
|
||||
### macOS
|
||||
Copy plugin to: `~/Library/Application Support/kicad/9.0/scripting/plugins/`
|
||||
|
||||
### Linux
|
||||
Copy plugin to: `~/.config/kicad/9.0/scripting/plugins/`
|
||||
|
||||
## First Run
|
||||
|
||||
1. **Open PCB Editor** (not Schematic Editor!)
|
||||
2. **Look for robot icon** 🤖 in toolbar
|
||||
3. **Choose interaction mode**:
|
||||
- 🔍 Analysis (Safe for beginners)
|
||||
- 📋 Advisory (Step-by-step guidance)
|
||||
- 🤖 Assistant (Advanced features)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Plugin doesn't appear
|
||||
- ✅ Check KiCad version (9.0+ required)
|
||||
- ✅ Restart KiCad after installation
|
||||
- ✅ Look in PCB Editor, not Schematic Editor
|
||||
|
||||
### AI doesn't respond
|
||||
- ✅ Start Ollama: `ollama serve`
|
||||
- ✅ Install model: `ollama pull llama3.2:3b`
|
||||
- ✅ Check internet connection
|
||||
- ✅ Install requests: `pip install requests`
|
||||
|
||||
### Permission errors
|
||||
- ✅ Run KiCad as administrator (Windows)
|
||||
- ✅ Check plugin directory permissions
|
||||
- ✅ Use Plugin Manager instead of manual copy
|
||||
|
||||
## Support
|
||||
|
||||
- 📖 See README.md for detailed usage
|
||||
- 🔄 Check CHANGELOG.md for latest features
|
||||
- 📋 Read UPGRADE_NOTES.md for version changes
|
||||
- 🐛 Report issues on GitHub
|
||||
|
||||
---
|
||||
**Quick Start**: Install → Start Ollama → Open PCB Editor → Click 🤖 → Choose Analysis Mode → Start chatting!
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Jochem
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,254 @@
|
||||
# KIC-AI Assistant
|
||||
|
||||
AI-powered PCB design assistant plugin for KiCad with Ollama integration.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## 🤖 Features
|
||||
|
||||
- **AI Chat Interface**: Interactive dialog for PCB design assistance
|
||||
- **Dual Analysis Modes**: Support for both PCB layout and schematic/circuit analysis
|
||||
- **3 Interaction Levels**: Choose from Analysis, Advisory, or Assistant modes based on your needs
|
||||
- **Smart Mode Detection**: AI adapts responses based on selected interaction mode
|
||||
- **Design Advice**: Get practical suggestions for component placement, routing, and best practices
|
||||
- **Local LLM**: Uses Ollama for privacy-focused AI processing
|
||||
- **Conversation Memory**: AI remembers context throughout your design session
|
||||
- **Real-time Help**: Ask questions about your design and get instant, context-aware answers
|
||||
|
||||
## 📋 Requirements
|
||||
|
||||
- **KiCad 9.0+**
|
||||
- **Python 3.7+**
|
||||
- **Ollama** with `llama3.2:3b` model
|
||||
- **requests** Python package
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
### Method 1: KiCad Plugin Manager (Recommended)
|
||||
|
||||
1. Download the latest release ZIP file
|
||||
2. Open KiCad → **Plugin and Content Manager**
|
||||
3. Click **Install from File**
|
||||
4. Select the downloaded ZIP file
|
||||
5. Restart KiCad
|
||||
|
||||
### Method 2: Manual Installation
|
||||
|
||||
1. Download and extract the plugin
|
||||
2. Copy to your KiCad plugins directory:
|
||||
- **Windows**: `%APPDATA%/kicad/9.0/scripting/plugins/`
|
||||
- **macOS**: `~/Library/Application Support/kicad/9.0/scripting/plugins/`
|
||||
- **Linux**: `~/.config/kicad/9.0/scripting/plugins/`
|
||||
|
||||
## 🔧 Setup
|
||||
|
||||
### 1. Install Ollama
|
||||
|
||||
Download and install Ollama from [ollama.ai](https://ollama.ai)
|
||||
|
||||
### 2. Install AI Model
|
||||
|
||||
```bash
|
||||
ollama pull llama3.2:3b
|
||||
```
|
||||
|
||||
### 3. Start Ollama Server
|
||||
|
||||
```bash
|
||||
ollama serve
|
||||
```
|
||||
|
||||
## 💡 Usage
|
||||
|
||||
### How to Use KIC-AI Assistant
|
||||
|
||||
**Important**: The plugin is accessed through KiCad's **PCB Editor (pcbnew)** but can analyze both schematic and PCB data.
|
||||
|
||||
1. **Open your KiCad project in PCB Editor** (File → Open → your_project.kicad_pcb)
|
||||
2. **Click the KIC-AI robot icon** in the PCB Editor toolbar
|
||||
3. **Choose analysis mode**:
|
||||
- **Schematic/Circuit**: Analyze component values, connections, and circuit design
|
||||
- **PCB Layout**: Analyze component placement, routing, and board layout
|
||||
4. **Select AI interaction mode**:
|
||||
- **🔍 Analysis Mode**: Safe recommendations only
|
||||
- **📋 Advisory Mode**: Step-by-step guidance with confirmation
|
||||
- **🤖 Assistant Mode**: Interactive assistance and future automation
|
||||
5. **Start chatting**: Ask questions or click "Analyze" for automatic analysis
|
||||
|
||||
### Dual Mode Capabilities
|
||||
|
||||
#### 📋 Schematic Mode
|
||||
- Circuit analysis and component review
|
||||
- Component value validation
|
||||
- Net connectivity analysis
|
||||
- Circuit design recommendations
|
||||
- Component selection advice
|
||||
|
||||
#### 🔧 PCB Mode
|
||||
- PCB layout analysis
|
||||
- Component placement optimization
|
||||
- Routing suggestions
|
||||
- Design rule checking tips
|
||||
- Manufacturing considerations
|
||||
|
||||
### AI Interaction Modes
|
||||
|
||||
Choose your preferred level of AI assistance:
|
||||
|
||||
#### 🔍 Analysis Mode (Safe)
|
||||
- **What it does**: Analyzes your design and provides recommendations
|
||||
- **Safety**: No modifications to your project
|
||||
- **Best for**: All users, learning, getting design insights
|
||||
- **Example**: "Your power supply has good decoupling, but consider adding a ferrite bead on the input"
|
||||
|
||||
#### 📋 Advisory Mode (Guided)
|
||||
- **What it does**: Provides step-by-step instructions with user confirmation
|
||||
- **Safety**: Guides you through changes with clear steps
|
||||
- **Best for**: Users who want detailed guidance
|
||||
- **Example**: "To improve this circuit: 1) Select R14 2) Change value to 10kΩ 3) Update the schematic. Shall I guide you through this?"
|
||||
|
||||
#### 🤖 Assistant Mode (Interactive)
|
||||
- **What it does**: Interactive design recommendations and future automation
|
||||
- **Safety**: Advanced features for experienced users
|
||||
- **Best for**: Power users, complex design tasks
|
||||
- **Example**: "I can help optimize your power routing. In future versions, I may automate some placement tasks."
|
||||
|
||||
### Example Questions
|
||||
|
||||
**Schematic Mode:**
|
||||
- "Review the power supply circuit"
|
||||
- "Check if R1 value is appropriate"
|
||||
- "Analyze the op-amp configuration"
|
||||
- "Are there any missing decoupling capacitors?"
|
||||
|
||||
**PCB Mode:**
|
||||
- "How can I improve the routing on this PCB?"
|
||||
- "Are there any potential EMI issues?"
|
||||
- "What's the best way to place these components?"
|
||||
- "Can you review my power distribution?"
|
||||
|
||||
**Mode-Specific Examples:**
|
||||
|
||||
*Analysis Mode:*
|
||||
- "What do you think of this design?"
|
||||
- "Any recommendations for improvement?"
|
||||
|
||||
*Advisory Mode:*
|
||||
- "Help me remove resistor R14"
|
||||
- "Guide me through optimizing this layout"
|
||||
- "How do I fix this design rule violation?"
|
||||
|
||||
*Assistant Mode:*
|
||||
- "Optimize my component placement"
|
||||
- "Help me redesign this power section"
|
||||
- "What automated improvements can you suggest?"
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
### Main Interface
|
||||
The AI Assistant provides an intuitive chat interface with 3 interaction modes and dual analysis capabilities.
|
||||
|
||||

|
||||
|
||||
### Mode Selection
|
||||
Choose from 3 different AI interaction modes based on your experience level and needs.
|
||||
|
||||

|
||||
|
||||
### PCB Analysis
|
||||
Automatic analysis provides comprehensive design insights and recommendations.
|
||||
|
||||

|
||||
|
||||
**Analysis Features:**
|
||||
- Component count and types
|
||||
- Board dimensions and layer information
|
||||
- Net and track statistics
|
||||
- Design recommendations
|
||||
- Mode-specific AI responses
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
KIC-AI-Assistant/
|
||||
├── metadata.json # KiCad plugin metadata
|
||||
├── plugins/
|
||||
│ ├── __init__.py # Main plugin entry point
|
||||
│ ├── ai_dialog.py # AI chat dialog interface
|
||||
│ └── robot_icon.png # Plugin icon
|
||||
├── screenshots/ # UI screenshots
|
||||
│ ├── main-interface.png
|
||||
│ ├── mode-selection.png
|
||||
│ └── pcb-analysis.png
|
||||
├── README.md
|
||||
├── LICENSE
|
||||
├── CHANGELOG.md
|
||||
└── UPGRADE_NOTES.md
|
||||
```
|
||||
|
||||
### Building
|
||||
|
||||
To create a release ZIP:
|
||||
|
||||
```bash
|
||||
zip -r kic-ai-assistant.zip metadata.json plugins/ -x "*.pyc" "*__pycache__*"
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
|
||||
1. Fork the project
|
||||
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
|
||||
4. Push to the branch (`git push origin feature/AmazingFeature`)
|
||||
5. Open a Pull Request
|
||||
|
||||
## 📝 License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- **KiCad** team for the excellent PCB design software
|
||||
- **Ollama** team for local LLM capabilities
|
||||
- **Meta** for the Llama model
|
||||
|
||||
## 📞 Support
|
||||
|
||||
If you encounter any issues or have questions:
|
||||
|
||||
1. Check the [Issues](../../issues) page
|
||||
2. Create a new issue with detailed information
|
||||
3. Include your KiCad version and error messages
|
||||
|
||||
## 🔄 Changelog
|
||||
|
||||
### v1.3.0
|
||||
- **NEW**: 3 AI Interaction Modes (Analysis, Advisory, Assistant)
|
||||
- **NEW**: Mode-specific AI responses and behavior
|
||||
- **NEW**: Enhanced user interface with mode selection
|
||||
- **NEW**: Step-by-step guidance in Advisory mode
|
||||
- **NEW**: Interactive assistance framework for future automation
|
||||
- **IMPROVED**: Better mode explanations and help system
|
||||
- **IMPROVED**: Enhanced conversation context awareness
|
||||
|
||||
### v1.2.1
|
||||
- Enhanced dual-mode analysis (PCB + Schematic)
|
||||
- Improved context-aware AI responses
|
||||
- Better user guidance and documentation
|
||||
|
||||
### v1.0.0
|
||||
- Initial release
|
||||
- AI chat interface
|
||||
- PCB analysis functionality
|
||||
- Ollama integration
|
||||
- English interface with larger fonts
|
||||
|
||||
---
|
||||
|
||||
**Made with ❤️ for the KiCad community**
|
||||
@@ -0,0 +1,77 @@
|
||||
# KIC-AI Assistant v1.3.0 - 3 Interaction Modes
|
||||
|
||||
## 🆕 What's New
|
||||
|
||||
### 3 AI Interaction Modes
|
||||
|
||||
De plugin heeft nu 3 verschillende interactie-niveaus:
|
||||
|
||||
#### 🔍 Analysis Mode (Veilig)
|
||||
- **Wat het doet**: Analyseert je ontwerp en geeft aanbevelingen
|
||||
- **Veiligheid**: Geen wijzigingen aan je project
|
||||
- **Voor wie**: Alle gebruikers, leren, design inzichten krijgen
|
||||
- **Voorbeeld**: "Je voeding heeft goede ontkoppeling, maar overweeg een ferriet kraal op de ingang"
|
||||
|
||||
#### 📋 Advisory Mode (Begeleiding)
|
||||
- **Wat het doet**: Geeft stap-voor-stap instructies met gebruikersbevestiging
|
||||
- **Veiligheid**: Begeleidt je door wijzigingen met duidelijke stappen
|
||||
- **Voor wie**: Gebruikers die gedetailleerde begeleiding willen
|
||||
- **Voorbeeld**: "Om dit circuit te verbeteren: 1) Selecteer R14 2) Wijzig waarde naar 10kΩ 3) Update het schema. Zal ik je hierdoor begeleiden?"
|
||||
|
||||
#### 🤖 Assistant Mode (Interactief)
|
||||
- **Wat het doet**: Interactieve design aanbevelingen en toekomstige automatisering
|
||||
- **Veiligheid**: Geavanceerde functies voor ervaren gebruikers
|
||||
- **Voor wie**: Power users, complexe design taken
|
||||
- **Voorbeeld**: "Ik kan je power routing optimaliseren. In toekomstige versies kan ik mogelijk enkele plaatsingstaken automatiseren."
|
||||
|
||||
### Nieuwe UI Features
|
||||
|
||||
- **Mode Selector**: Dropdown om je gewenste interactie niveau te kiezen
|
||||
- **Mode Help**: "?" knop met uitleg van alle modi
|
||||
- **Status Updates**: Toont huidige mode in status balk
|
||||
- **Context Awareness**: AI past antwoorden aan op basis van gekozen mode
|
||||
|
||||
### Verbeterde AI Responses
|
||||
|
||||
- **Mode-Specific Instructions**: AI krijgt verschillende instructies per mode
|
||||
- **Safety Warnings**: Advisory mode voegt waarschuwingen toe bij modificaties
|
||||
- **Interactive Guidance**: Assistant mode kondigt toekomstige automatisering aan
|
||||
- **Conversation Memory**: Verbeterde context awareness
|
||||
|
||||
## 🔧 Technical Changes
|
||||
|
||||
### Code Structure
|
||||
- Nieuwe `interaction_mode` property in AIAssistantDialog
|
||||
- `get_mode_instructions()` method voor mode-specifieke AI instructies
|
||||
- Enhanced `process_user_message()` met mode-specifieke handling
|
||||
- UI uitbreiding met mode selector en help
|
||||
|
||||
### AI Integration
|
||||
- Mode instructions worden toegevoegd aan AI system prompt
|
||||
- Context-aware responses gebaseerd op gekozen mode
|
||||
- Improved conversation history management
|
||||
|
||||
## 🚀 Usage
|
||||
|
||||
1. Open PCB Editor
|
||||
2. Klik KIC-AI robot icon
|
||||
3. **NIEUW**: Kies je AI interaction mode
|
||||
4. Klik "?" voor mode uitleg
|
||||
5. Start chatten of analyseren
|
||||
|
||||
## 🎯 Future Plans
|
||||
|
||||
- **Assistant Mode**: Implementatie van semi-automatische wijzigingen
|
||||
- **Component Management**: Direct component wijzigingen met bevestiging
|
||||
- **Advanced Automation**: Intelligente design optimalisaties
|
||||
- **Multi-language**: Nederlandse interface optie
|
||||
|
||||
## 📝 Migration Notes
|
||||
|
||||
- Bestaande gebruikers starten automatisch in Analysis Mode (veiligste optie)
|
||||
- Alle bestaande functionaliteit blijft beschikbaar
|
||||
- Nieuwe modes voegen functionaliteit toe zonder bestaande workflows te verstoren
|
||||
|
||||
---
|
||||
|
||||
**Veiligheid eerst**: Begin met Analysis Mode om de nieuwe features te verkennen!
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple script to create a robot icon for KIC-AI plugin
|
||||
Creates a basic robot icon using PIL/Pillow
|
||||
"""
|
||||
|
||||
try:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
|
||||
# Create 24x24 icon (standard KiCad toolbar size)
|
||||
size = (24, 24)
|
||||
img = Image.new('RGBA', size, (0, 0, 0, 0)) # Transparent background
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
# Robot colors
|
||||
robot_color = (70, 130, 180) # Steel blue
|
||||
eye_color = (255, 255, 255) # White
|
||||
antenna_color = (200, 200, 200) # Light gray
|
||||
|
||||
# Draw robot head (rectangle)
|
||||
head_rect = [4, 6, 20, 18]
|
||||
draw.rectangle(head_rect, fill=robot_color, outline=(50, 50, 50))
|
||||
|
||||
# Draw antennae
|
||||
draw.line([8, 6, 8, 3], fill=antenna_color, width=1)
|
||||
draw.line([16, 6, 16, 3], fill=antenna_color, width=1)
|
||||
draw.ellipse([7, 2, 9, 4], fill=antenna_color)
|
||||
draw.ellipse([15, 2, 17, 4], fill=antenna_color)
|
||||
|
||||
# Draw eyes
|
||||
draw.ellipse([7, 9, 10, 12], fill=eye_color)
|
||||
draw.ellipse([14, 9, 17, 12], fill=eye_color)
|
||||
|
||||
# Draw pupils
|
||||
draw.ellipse([8, 10, 9, 11], fill=(0, 0, 0))
|
||||
draw.ellipse([15, 10, 16, 11], fill=(0, 0, 0))
|
||||
|
||||
# Draw mouth
|
||||
draw.rectangle([10, 14, 14, 15], fill=(50, 50, 50))
|
||||
|
||||
# Draw body
|
||||
body_rect = [6, 18, 18, 24]
|
||||
draw.rectangle(body_rect, fill=robot_color, outline=(50, 50, 50))
|
||||
|
||||
# Save icon
|
||||
icon_path = os.path.join(os.path.dirname(__file__), 'plugins', 'robot_icon.png')
|
||||
img.save(icon_path, 'PNG')
|
||||
print(f"Robot icon created: {icon_path}")
|
||||
|
||||
except ImportError:
|
||||
print("PIL/Pillow not available - using default KiCad icon instead")
|
||||
except Exception as e:
|
||||
print(f"Error creating icon: {e}")
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"$schema": "https://go.kicad.org/pcm/schemas/v1",
|
||||
"name": "KIC-AI Assistant",
|
||||
"description": "AI-powered PCB design assistant with 3 interaction modes and Ollama integration",
|
||||
"description_full": "AI assistant for KiCad PCB design with Ollama LLM integration. Features 3 interaction modes (Analysis, Advisory, Assistant) for different user needs. Analyze both PCB layouts and schematics, get design advice, and receive guided assistance.",
|
||||
"identifier": "com.jochem.kic-ai-assistant",
|
||||
"type": "plugin",
|
||||
"author": {
|
||||
"name": "Jochem",
|
||||
"contact": {
|
||||
"web": ""
|
||||
}
|
||||
},
|
||||
"maintainer": {
|
||||
"name": "Jochem",
|
||||
"contact": {
|
||||
"web": ""
|
||||
}
|
||||
},
|
||||
"license": "MIT",
|
||||
"resources": {
|
||||
"homepage": "",
|
||||
"repository": ""
|
||||
},
|
||||
"tags": [
|
||||
"ai",
|
||||
"assistant",
|
||||
"pcb",
|
||||
"schematic",
|
||||
"analysis",
|
||||
"design",
|
||||
"guided",
|
||||
"interactive"
|
||||
],
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.3.0",
|
||||
"status": "stable",
|
||||
"kicad_version": "6.0"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import pcbnew
|
||||
import wx
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Try to import eeschema for schematic support
|
||||
try:
|
||||
import eeschema
|
||||
EESCHEMA_AVAILABLE = True
|
||||
except ImportError:
|
||||
EESCHEMA_AVAILABLE = False
|
||||
|
||||
# Add plugin directory to sys.path for imports
|
||||
plugin_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
if plugin_dir not in sys.path:
|
||||
sys.path.insert(0, plugin_dir)
|
||||
|
||||
class KicAIAssistant(pcbnew.ActionPlugin):
|
||||
"""
|
||||
KIC-AI Assistant Plugin voor KiCad
|
||||
AI-powered PCB design assistant met Ollama integratie
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "KIC-AI Assistant"
|
||||
self.category = "AI Tools"
|
||||
self.description = "AI assistant for PCB and Schematic design with Ollama"
|
||||
self.pcbnew_icon_support = hasattr(self, "show_toolbar_button")
|
||||
self.show_toolbar_button = True
|
||||
self.icon_file_name = os.path.join(os.path.dirname(__file__), "robot_icon.png")
|
||||
self.dark_icon_file_name = os.path.join(os.path.dirname(__file__), "robot_icon.png")
|
||||
|
||||
def defaults(self):
|
||||
pass # Niet meer nodig met __init__ implementatie
|
||||
|
||||
def Run(self):
|
||||
"""Start the AI Assistant dialog"""
|
||||
try:
|
||||
# Import de dialog class
|
||||
from ai_dialog import AIAssistantDialog
|
||||
|
||||
# Determine context - check if we're in PCB or Schematic editor
|
||||
context_type = "pcb" # Default to PCB
|
||||
|
||||
# Better context detection
|
||||
try:
|
||||
# Check if we have a board loaded and it has a valid filename
|
||||
board = pcbnew.GetBoard()
|
||||
if board and board.GetFileName():
|
||||
# We have a PCB board loaded
|
||||
footprints = list(board.GetFootprints())
|
||||
|
||||
if len(footprints) == 0:
|
||||
# No components on PCB - ask user what they want to analyze
|
||||
dlg = wx.MessageDialog(
|
||||
None,
|
||||
"No components found on PCB.\n\nWhat would you like to analyze?\n\n"
|
||||
"• Schematic/Circuit: Review component values, connections, and circuit design\n"
|
||||
"• PCB Layout: Analyze board layout, placement, and routing\n\n"
|
||||
"Note: Both modes use data from the loaded KiCad project.",
|
||||
"KIC-AI Context Selection",
|
||||
wx.YES_NO | wx.ICON_QUESTION
|
||||
)
|
||||
dlg.SetYesNoLabels("&Schematic/Circuit", "&PCB Layout")
|
||||
result = dlg.ShowModal()
|
||||
dlg.Destroy()
|
||||
|
||||
context_type = "schematic" if result == wx.ID_YES else "pcb"
|
||||
else:
|
||||
# PCB has components - ask what to focus on
|
||||
dlg = wx.MessageDialog(
|
||||
None,
|
||||
"What would you like to analyze?\n\n"
|
||||
"• Schematic/Circuit: Review component values, connections, and circuit design\n"
|
||||
"• PCB Layout: Analyze component placement, routing, and board layout\n\n"
|
||||
"Note: Both modes use data from the current KiCad project.",
|
||||
"KIC-AI Analysis Mode",
|
||||
wx.YES_NO | wx.ICON_QUESTION
|
||||
)
|
||||
dlg.SetYesNoLabels("&Schematic/Circuit", "&PCB Layout")
|
||||
result = dlg.ShowModal()
|
||||
dlg.Destroy()
|
||||
|
||||
context_type = "schematic" if result == wx.ID_YES else "pcb"
|
||||
else:
|
||||
# No board loaded - inform user
|
||||
wx.MessageBox(
|
||||
"No KiCad project loaded.\n\n"
|
||||
"Please open a KiCad project first:\n"
|
||||
"1. Open your .kicad_pcb file in PCB Editor\n"
|
||||
"2. Click the KIC-AI robot icon in the toolbar\n\n"
|
||||
"The plugin will analyze both schematic and PCB data from the project.",
|
||||
"KIC-AI: No Project Loaded",
|
||||
wx.OK | wx.ICON_INFORMATION
|
||||
)
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
# Fallback to PCB mode
|
||||
context_type = "pcb"
|
||||
|
||||
# Create and show dialog with detected context
|
||||
dialog = AIAssistantDialog(None, context_type=context_type)
|
||||
dialog.Show()
|
||||
|
||||
except ImportError as e:
|
||||
wx.MessageBox(
|
||||
f"Cannot load AI dialog:\n{str(e)}\n\nPlease check plugin installation.",
|
||||
"KIC-AI Error",
|
||||
wx.OK | wx.ICON_ERROR
|
||||
)
|
||||
except Exception as e:
|
||||
wx.MessageBox(
|
||||
f"KIC-AI error:\n{str(e)}",
|
||||
"KIC-AI Error",
|
||||
wx.OK | wx.ICON_ERROR
|
||||
)
|
||||
|
||||
# Registreer de plugin
|
||||
KicAIAssistant().register()
|
||||
@@ -0,0 +1,618 @@
|
||||
import wx
|
||||
import pcbnew
|
||||
import threading
|
||||
import json
|
||||
|
||||
try:
|
||||
import requests
|
||||
REQUESTS_AVAILABLE = True
|
||||
except ImportError:
|
||||
REQUESTS_AVAILABLE = False
|
||||
|
||||
class AIAssistantDialog(wx.Frame):
|
||||
"""AI Assistant Dialog voor PCB en Schematic design hulp met 3 interactie modi"""
|
||||
|
||||
def __init__(self, parent, context_type="pcb"):
|
||||
# Set title based on context
|
||||
title = "KIC-AI Assistant - PCB" if context_type == "pcb" else "KIC-AI Assistant - Schematic"
|
||||
super().__init__(parent, title=title, size=(850, 650))
|
||||
|
||||
self.context_type = context_type # "pcb" or "schematic"
|
||||
|
||||
# AI Interaction modes
|
||||
self.ANALYSIS_MODE = "analysis" # Safe analysis and suggestions
|
||||
self.ADVISORY_MODE = "advisory" # Step-by-step guidance with confirmation
|
||||
self.ASSISTANT_MODE = "assistant" # Interactive recommendations (future: with actions)
|
||||
|
||||
self.interaction_mode = self.ANALYSIS_MODE # Default to safest mode
|
||||
|
||||
# Icon instellen (optioneel)
|
||||
self.SetIcon(wx.Icon())
|
||||
|
||||
# Chat history voor context
|
||||
self.conversation_history = []
|
||||
|
||||
# UI opzetten
|
||||
self.init_ui()
|
||||
|
||||
# Centreer op scherm
|
||||
self.CenterOnScreen()
|
||||
|
||||
# Welcome message based on context
|
||||
if context_type == "schematic":
|
||||
welcome_msg = ("Welcome to KIC-AI Assistant - Schematic Mode! 📋⚡\n\n"
|
||||
"I can help you with:\n"
|
||||
"• Schematic analysis and review\n"
|
||||
"• Circuit design advice\n"
|
||||
"• Component selection guidance\n"
|
||||
"• Net connectivity analysis\n"
|
||||
"• Symbol and annotation review\n\n"
|
||||
"� Interaction Modes:\n"
|
||||
"• Analysis: Safe recommendations only\n"
|
||||
"• Advisory: Step-by-step guidance\n"
|
||||
"• Assistant: Interactive help (future automation)\n\n"
|
||||
"�💡 I remember our conversation!\n"
|
||||
"Ask me about your circuit design!")
|
||||
else:
|
||||
welcome_msg = ("Welcome to KIC-AI Assistant - PCB Mode! 🔧🖥️\n\n"
|
||||
"I can help you with:\n"
|
||||
"• PCB layout analysis and advice\n"
|
||||
"• Component placement optimization\n"
|
||||
"• Routing suggestions\n"
|
||||
"• Design rule checking tips\n"
|
||||
"• Manufacturing considerations\n\n"
|
||||
"🔧 Interaction Modes:\n"
|
||||
"• Analysis: Safe recommendations only\n"
|
||||
"• Advisory: Step-by-step guidance\n"
|
||||
"• Assistant: Interactive help (future automation)\n\n"
|
||||
"💡 I remember our conversation!\n"
|
||||
"Ask me about your PCB design!")
|
||||
|
||||
self.add_message("🤖 KIC-AI", welcome_msg)
|
||||
|
||||
def init_ui(self):
|
||||
"""Initialiseer de user interface"""
|
||||
panel = wx.Panel(self)
|
||||
|
||||
# Main sizer
|
||||
main_sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
|
||||
# Mode selector
|
||||
mode_sizer = wx.BoxSizer(wx.HORIZONTAL)
|
||||
mode_label = wx.StaticText(panel, label="AI Interaction Mode:")
|
||||
mode_label.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
|
||||
|
||||
self.mode_choice = wx.Choice(panel, choices=[
|
||||
"🔍 Analysis Mode (Safe)",
|
||||
"📋 Advisory Mode (Guided)",
|
||||
"🤖 Assistant Mode (Interactive)"
|
||||
])
|
||||
self.mode_choice.SetSelection(0) # Default to Analysis mode
|
||||
|
||||
mode_help = wx.Button(panel, label="?", size=(30, -1))
|
||||
mode_help.SetToolTip("Click for mode explanations")
|
||||
|
||||
mode_sizer.Add(mode_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)
|
||||
mode_sizer.Add(self.mode_choice, 1, wx.EXPAND | wx.RIGHT, 5)
|
||||
mode_sizer.Add(mode_help, 0, wx.ALIGN_CENTER_VERTICAL)
|
||||
|
||||
main_sizer.Add(mode_sizer, 0, wx.EXPAND | wx.ALL, 10)
|
||||
|
||||
# Chat area
|
||||
self.chat_ctrl = wx.TextCtrl(
|
||||
panel,
|
||||
style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_WORDWRAP
|
||||
)
|
||||
self.chat_ctrl.SetFont(wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
|
||||
|
||||
# Input area
|
||||
input_sizer = wx.BoxSizer(wx.HORIZONTAL)
|
||||
|
||||
self.input_ctrl = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER)
|
||||
self.input_ctrl.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
|
||||
self.input_ctrl.SetHint("Type your question here...")
|
||||
|
||||
# Buttons
|
||||
self.send_btn = wx.Button(panel, label="Send")
|
||||
analyze_label = "Analyze Schematic" if self.context_type == "schematic" else "Analyze PCB"
|
||||
self.analyze_btn = wx.Button(panel, label=analyze_label)
|
||||
self.clear_btn = wx.Button(panel, label="Clear Chat")
|
||||
self.context_btn = wx.Button(panel, label="Show Context")
|
||||
|
||||
# Input layout
|
||||
input_sizer.Add(self.input_ctrl, 1, wx.EXPAND | wx.RIGHT, 5)
|
||||
input_sizer.Add(self.send_btn, 0, wx.RIGHT, 5)
|
||||
input_sizer.Add(self.analyze_btn, 0, wx.RIGHT, 5)
|
||||
input_sizer.Add(self.clear_btn, 0, wx.RIGHT, 5)
|
||||
input_sizer.Add(self.context_btn, 0)
|
||||
|
||||
# Status bar
|
||||
self.status_text = wx.StaticText(panel, label="Ready")
|
||||
self.status_text.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_NORMAL))
|
||||
|
||||
# Main layout
|
||||
main_sizer.Add(self.chat_ctrl, 1, wx.EXPAND | wx.ALL, 10)
|
||||
main_sizer.Add(input_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
|
||||
main_sizer.Add(self.status_text, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
|
||||
|
||||
panel.SetSizer(main_sizer)
|
||||
|
||||
# Events
|
||||
self.bind_events()
|
||||
|
||||
def bind_events(self):
|
||||
"""Bind UI events"""
|
||||
self.send_btn.Bind(wx.EVT_BUTTON, self.on_send)
|
||||
self.analyze_btn.Bind(wx.EVT_BUTTON, self.on_analyze)
|
||||
self.clear_btn.Bind(wx.EVT_BUTTON, self.on_clear)
|
||||
self.context_btn.Bind(wx.EVT_BUTTON, self.on_show_context)
|
||||
self.mode_choice.Bind(wx.EVT_CHOICE, self.on_mode_change)
|
||||
self.input_ctrl.Bind(wx.EVT_TEXT_ENTER, self.on_send)
|
||||
self.Bind(wx.EVT_CLOSE, self.on_close)
|
||||
|
||||
# Mode help button (find it in the parent)
|
||||
for child in self.GetChildren():
|
||||
for subchild in child.GetChildren():
|
||||
if isinstance(subchild, wx.Button) and subchild.GetLabel() == "?":
|
||||
subchild.Bind(wx.EVT_BUTTON, self.on_mode_help)
|
||||
break
|
||||
|
||||
def add_message(self, sender, message):
|
||||
"""Add message to chat"""
|
||||
timestamp = wx.DateTime.Now().Format("%H:%M")
|
||||
formatted_msg = f"[{timestamp}] {sender}:\n{message}\n\n"
|
||||
self.chat_ctrl.AppendText(formatted_msg)
|
||||
|
||||
def set_status(self, status):
|
||||
"""Update status tekst"""
|
||||
self.status_text.SetLabel(status)
|
||||
|
||||
def on_send(self, event):
|
||||
"""Send user message"""
|
||||
message = self.input_ctrl.GetValue().strip()
|
||||
if not message:
|
||||
return
|
||||
|
||||
# Add message
|
||||
self.add_message("🟢 You", message)
|
||||
self.input_ctrl.Clear()
|
||||
|
||||
# Send to AI
|
||||
self.process_user_message(message)
|
||||
|
||||
def on_analyze(self, event):
|
||||
"""Analyze current PCB"""
|
||||
self.set_status("Analyzing...")
|
||||
self.analyze_btn.Enable(False)
|
||||
|
||||
# Start analyse in thread
|
||||
thread = threading.Thread(target=self.analyze_pcb)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_clear(self, event):
|
||||
"""Clear chat history"""
|
||||
self.chat_ctrl.Clear()
|
||||
self.conversation_history.clear() # Wis ook conversatie geschiedenis
|
||||
self.add_message("🤖 KIC-AI", "Chat cleared. How can I help you?")
|
||||
|
||||
def on_mode_change(self, event):
|
||||
"""Handle AI interaction mode change"""
|
||||
selection = self.mode_choice.GetSelection()
|
||||
|
||||
if selection == 0:
|
||||
self.interaction_mode = self.ANALYSIS_MODE
|
||||
mode_name = "Analysis Mode"
|
||||
description = "Safe analysis and recommendations only"
|
||||
elif selection == 1:
|
||||
self.interaction_mode = self.ADVISORY_MODE
|
||||
mode_name = "Advisory Mode"
|
||||
description = "Step-by-step guidance with user confirmation"
|
||||
elif selection == 2:
|
||||
self.interaction_mode = self.ASSISTANT_MODE
|
||||
mode_name = "Assistant Mode"
|
||||
description = "Interactive recommendations and future automation"
|
||||
|
||||
self.add_message("⚙️ System", f"Switched to {mode_name}: {description}")
|
||||
self.set_status(f"Mode: {mode_name}")
|
||||
|
||||
def on_mode_help(self, event):
|
||||
"""Show mode explanations"""
|
||||
help_text = """🔍 Analysis Mode (Safe):
|
||||
• Analyzes your design and provides recommendations
|
||||
• No modifications to your project
|
||||
• Safe for all users and projects
|
||||
|
||||
📋 Advisory Mode (Guided):
|
||||
• Provides step-by-step instructions
|
||||
• Asks for confirmation before suggesting changes
|
||||
• Guides you through design improvements
|
||||
|
||||
🤖 Assistant Mode (Interactive):
|
||||
• Interactive design recommendations
|
||||
• Future: Semi-automatic design assistance
|
||||
• Advanced features for experienced users
|
||||
|
||||
Choose the mode that fits your experience level and comfort with AI assistance."""
|
||||
|
||||
self.add_message("ℹ️ Mode Help", help_text)
|
||||
|
||||
def on_show_context(self, event):
|
||||
"""Toon huidige conversatie context"""
|
||||
if not self.conversation_history:
|
||||
self.add_message("ℹ️ Context", "No conversation history yet.")
|
||||
return
|
||||
|
||||
context_info = f"📝 Memory: {len(self.conversation_history)//2} exchanges remembered\n\n"
|
||||
|
||||
# Show last 4 messages (2 exchanges)
|
||||
recent_history = self.conversation_history[-4:] if len(self.conversation_history) > 4 else self.conversation_history
|
||||
|
||||
for entry in recent_history:
|
||||
role_emoji = "🟢" if entry['role'] == "User" else "🤖"
|
||||
content = entry['content'][:150] + "..." if len(entry['content']) > 150 else entry['content']
|
||||
context_info += f"{role_emoji} {content}\n\n"
|
||||
|
||||
if len(self.conversation_history) > 4:
|
||||
context_info += f"(+ {len(self.conversation_history)//2 - 2} older exchanges in memory)"
|
||||
|
||||
self.add_message("ℹ️ Context", context_info)
|
||||
|
||||
def on_close(self, event):
|
||||
"""Sluit dialog"""
|
||||
self.Destroy()
|
||||
|
||||
def analyze_pcb(self):
|
||||
"""Analyze current design in background thread"""
|
||||
try:
|
||||
if self.context_type == "schematic":
|
||||
# Analyze schematic
|
||||
analysis = self.collect_schematic_info()
|
||||
analysis_title = "📋 Schematic Analysis"
|
||||
ai_prompt = f"Analyze this schematic design and provide circuit advice:\n\n{analysis}"
|
||||
else:
|
||||
# Analyze PCB
|
||||
board = pcbnew.GetBoard()
|
||||
if not board:
|
||||
wx.CallAfter(self.add_message, "❌ Error", "No PCB loaded")
|
||||
return
|
||||
|
||||
analysis = self.collect_pcb_info(board)
|
||||
analysis_title = "📊 PCB Analysis"
|
||||
ai_prompt = f"Analyze this PCB and provide design advice:\n\n{analysis}"
|
||||
|
||||
# Toon analyse
|
||||
wx.CallAfter(self.add_message, analysis_title, analysis)
|
||||
|
||||
# Stuur naar AI voor advies
|
||||
self.send_to_ai(ai_prompt, is_analysis=True)
|
||||
|
||||
except Exception as e:
|
||||
wx.CallAfter(self.add_message, "❌ Error", f"Analysis error: {str(e)}")
|
||||
finally:
|
||||
wx.CallAfter(self.analyze_btn.Enable, True)
|
||||
wx.CallAfter(self.set_status, "Ready")
|
||||
|
||||
def collect_pcb_info(self, board):
|
||||
"""Collect PCB information with specific component details"""
|
||||
info = []
|
||||
|
||||
# Board info
|
||||
title = board.GetTitleBlock().GetTitle()
|
||||
info.append(f"PCB: {title if title else 'Unknown'}")
|
||||
|
||||
# Afmetingen
|
||||
bbox = board.GetBoardEdgesBoundingBox()
|
||||
width_mm = bbox.GetWidth() / 1000000.0
|
||||
height_mm = bbox.GetHeight() / 1000000.0
|
||||
info.append(f"Dimensions: {width_mm:.1f} x {height_mm:.1f} mm")
|
||||
|
||||
# Componenten - GEDETAILLEERDE LIJST
|
||||
footprints = list(board.GetFootprints())
|
||||
info.append(f"Components: {len(footprints)}")
|
||||
|
||||
if footprints:
|
||||
info.append("\n=== COMPONENT DETAILS ===")
|
||||
|
||||
# Sorteer componenten op referentie
|
||||
sorted_footprints = sorted(footprints, key=lambda fp: fp.GetReference())
|
||||
|
||||
for fp in sorted_footprints:
|
||||
ref = fp.GetReference()
|
||||
value = fp.GetValue()
|
||||
footprint = fp.GetFPID().GetLibItemName()
|
||||
|
||||
# Positie
|
||||
pos = fp.GetPosition()
|
||||
x_mm = pos.x / 1000000.0
|
||||
y_mm = pos.y / 1000000.0
|
||||
|
||||
# Rotatie
|
||||
rotation = fp.GetOrientation().AsDegrees()
|
||||
|
||||
# Layer (bovenkant/onderkant)
|
||||
layer = "Top" if fp.IsFlipped() == False else "Bottom"
|
||||
|
||||
info.append(f"{ref}: {value}")
|
||||
info.append(f" Footprint: {footprint}")
|
||||
info.append(f" Position: ({x_mm:.1f}, {y_mm:.1f}) mm")
|
||||
info.append(f" Rotation: {rotation:.0f}°, Layer: {layer}")
|
||||
|
||||
# Pads info
|
||||
pads = list(fp.Pads())
|
||||
if pads:
|
||||
info.append(f" Pads: {len(pads)}")
|
||||
|
||||
info.append("") # Lege regel tussen componenten
|
||||
|
||||
# Nets met details
|
||||
nets = board.GetNetInfo()
|
||||
net_count = nets.GetNetCount()
|
||||
info.append(f"\n=== NETS ({net_count}) ===")
|
||||
|
||||
# Toon belangrijke nets
|
||||
for net_code in range(min(10, net_count)): # Eerste 10 nets
|
||||
net = nets.GetNetItem(net_code)
|
||||
if net:
|
||||
net_name = net.GetNetname()
|
||||
if net_name and net_name != "":
|
||||
info.append(f"Net {net_code}: {net_name}")
|
||||
|
||||
# Tracks
|
||||
tracks = list(board.GetTracks())
|
||||
info.append(f"\nTracks: {len(tracks)}")
|
||||
|
||||
# Layers
|
||||
layer_count = board.GetCopperLayerCount()
|
||||
info.append(f"Copper layers: {layer_count}")
|
||||
|
||||
return "\n".join(info)
|
||||
|
||||
def collect_schematic_info(self):
|
||||
"""Collect schematic information for analysis"""
|
||||
info = []
|
||||
|
||||
try:
|
||||
# Try to get schematic information via PCB board
|
||||
# (KiCad stores schematic refs in PCB)
|
||||
board = pcbnew.GetBoard()
|
||||
if not board:
|
||||
info.append("No board available for schematic analysis")
|
||||
return "\n".join(info)
|
||||
|
||||
# Board/Project info
|
||||
title = board.GetTitleBlock().GetTitle()
|
||||
info.append(f"Project: {title if title else 'Unknown'}")
|
||||
|
||||
# Get footprints (which represent schematic symbols)
|
||||
footprints = list(board.GetFootprints())
|
||||
info.append(f"Components: {len(footprints)}")
|
||||
|
||||
if footprints:
|
||||
info.append("\n=== SCHEMATIC COMPONENTS ===")
|
||||
|
||||
# Group by component type
|
||||
components_by_type = {}
|
||||
|
||||
for fp in footprints:
|
||||
ref = fp.GetReference()
|
||||
value = fp.GetValue()
|
||||
footprint = fp.GetFPID().GetLibItemName()
|
||||
|
||||
# Get component type from reference
|
||||
comp_type = ref[0] if ref else "?"
|
||||
|
||||
if comp_type not in components_by_type:
|
||||
components_by_type[comp_type] = []
|
||||
|
||||
components_by_type[comp_type].append({
|
||||
'ref': ref,
|
||||
'value': value,
|
||||
'footprint': footprint
|
||||
})
|
||||
|
||||
# Show components grouped by type
|
||||
for comp_type in sorted(components_by_type.keys()):
|
||||
components = components_by_type[comp_type]
|
||||
info.append(f"\n{comp_type}-type components ({len(components)}):")
|
||||
|
||||
for comp in sorted(components, key=lambda x: x['ref']):
|
||||
info.append(f" {comp['ref']}: {comp['value']} ({comp['footprint']})")
|
||||
|
||||
# Nets (connections between components)
|
||||
nets = board.GetNetInfo()
|
||||
net_count = nets.GetNetCount()
|
||||
info.append(f"\n=== CONNECTIONS ({net_count} nets) ===")
|
||||
|
||||
# Show important nets
|
||||
important_nets = []
|
||||
for net_code in range(min(15, net_count)):
|
||||
net = nets.GetNetItem(net_code)
|
||||
if net:
|
||||
net_name = net.GetNetname()
|
||||
if net_name and net_name != "":
|
||||
important_nets.append(net_name)
|
||||
|
||||
if important_nets:
|
||||
info.append("Key nets:")
|
||||
for net_name in important_nets:
|
||||
info.append(f" • {net_name}")
|
||||
|
||||
info.append(f"\nTotal design complexity: {len(footprints)} components, {net_count} connections")
|
||||
|
||||
except Exception as e:
|
||||
info.append(f"Schematic analysis error: {str(e)}")
|
||||
info.append("Note: Full schematic analysis requires KiCad eeschema integration")
|
||||
|
||||
return "\n".join(info)
|
||||
|
||||
def process_user_message(self, message):
|
||||
"""Process user message"""
|
||||
self.set_status("AI thinking...")
|
||||
self.send_btn.Enable(False)
|
||||
|
||||
# Start AI processing in thread
|
||||
thread = threading.Thread(target=self.send_to_ai, args=(message,))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def send_to_ai(self, message, is_analysis=False):
|
||||
"""Send message to AI (Ollama) with design context"""
|
||||
if not REQUESTS_AVAILABLE:
|
||||
wx.CallAfter(self.add_message, "❌ Error", "Requests module not available")
|
||||
wx.CallAfter(self.send_btn.Enable, True)
|
||||
wx.CallAfter(self.set_status, "Ready")
|
||||
return
|
||||
|
||||
try:
|
||||
# Ollama API endpoint
|
||||
url = "http://localhost:11434/api/generate"
|
||||
|
||||
# Build simple conversation context
|
||||
conversation_context = ""
|
||||
if self.conversation_history:
|
||||
# Include last 4 exchanges (8 messages) for context
|
||||
recent_messages = self.conversation_history[-8:]
|
||||
conversation_context = "\n\nRecent conversation:\n"
|
||||
for msg in recent_messages:
|
||||
conversation_context += f"{msg['role']}: {msg['content'][:200]}...\n"
|
||||
conversation_context += "\n"
|
||||
|
||||
# Get current design context for user questions
|
||||
design_context = ""
|
||||
if not is_analysis:
|
||||
try:
|
||||
if self.context_type == "schematic":
|
||||
design_context = f"\n\nCURRENT SCHEMATIC CONTEXT:\n{self.collect_schematic_info()}\n"
|
||||
else:
|
||||
board = pcbnew.GetBoard()
|
||||
if board:
|
||||
design_context = f"\n\nCURRENT PCB CONTEXT:\n{self.collect_pcb_info(board)}\n"
|
||||
except:
|
||||
pass # No design available
|
||||
|
||||
# Prepare system prompt based on context and interaction mode
|
||||
mode_instructions = self.get_mode_instructions()
|
||||
|
||||
if is_analysis:
|
||||
if self.context_type == "schematic":
|
||||
system_prompt = ("You are an expert electronic circuit designer and schematic review specialist. "
|
||||
"Analyze the provided schematic data thoroughly and provide specific, practical advice. "
|
||||
"Look at component types, values, connections, and circuit topology. "
|
||||
"Focus on circuit functionality, component selection, and design best practices. "
|
||||
f"{mode_instructions} "
|
||||
"Reference previous conversation if relevant.")
|
||||
else:
|
||||
system_prompt = ("You are an expert PCB design engineer. Analyze the provided PCB data thoroughly and provide specific, practical advice. "
|
||||
"Look at individual components, their values, positions, and relationships. "
|
||||
f"{mode_instructions} "
|
||||
"Reference previous conversation if relevant.")
|
||||
else:
|
||||
if self.context_type == "schematic":
|
||||
system_prompt = ("You are a helpful schematic design assistant with access to the current schematic design. "
|
||||
"When users ask about specific components, circuits, or connections, reference the actual schematic data provided. "
|
||||
"Give specific answers about component values, connections, and circuit topology when possible. "
|
||||
"Focus on circuit functionality, component selection, and electrical design principles. "
|
||||
f"{mode_instructions} "
|
||||
"Remember our conversation and build upon previous topics when relevant.")
|
||||
else:
|
||||
system_prompt = ("You are a helpful PCB design assistant with access to the current PCB design. "
|
||||
"When users ask about specific components (like resistors, capacitors, ICs), look up the actual component details from the PCB context provided. "
|
||||
"Give specific answers referencing actual component values, positions, and designators when possible. "
|
||||
"If asked about a specific component (e.g., 'R1', 'check this resistor'), find that component in the PCB data and provide detailed information about it. "
|
||||
f"{mode_instructions} "
|
||||
"Remember our conversation and build upon previous topics when relevant.")
|
||||
|
||||
# Build final prompt with design context
|
||||
final_prompt = system_prompt + conversation_context + design_context + f"\nUser question: {message}\n\nPlease provide a specific, helpful response based on the actual design data when applicable:"
|
||||
|
||||
# API request
|
||||
data = {
|
||||
"model": "llama3.2:3b",
|
||||
"prompt": final_prompt,
|
||||
"stream": False,
|
||||
"options": {
|
||||
"temperature": 0.6,
|
||||
"top_p": 0.9,
|
||||
"num_ctx": 4096, # Verhoogd voor meer context
|
||||
"repeat_penalty": 1.1
|
||||
}
|
||||
}
|
||||
|
||||
response = requests.post(url, json=data, timeout=60) # Langere timeout
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
ai_response = result.get('response', 'No response received').strip()
|
||||
|
||||
# Add to conversation history
|
||||
self.conversation_history.append({"role": "User", "content": message})
|
||||
self.conversation_history.append({"role": "Assistant", "content": ai_response})
|
||||
|
||||
# Keep only last 12 messages (6 exchanges)
|
||||
if len(self.conversation_history) > 12:
|
||||
self.conversation_history = self.conversation_history[-12:]
|
||||
|
||||
wx.CallAfter(self.add_message, "🤖 KIC-AI", ai_response)
|
||||
else:
|
||||
wx.CallAfter(self.add_message, "❌ Error", f"AI server error: {response.status_code}")
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
wx.CallAfter(self.add_message, "❌ Error",
|
||||
"Cannot connect to Ollama.\n"
|
||||
"Start Ollama server:\n"
|
||||
" ollama serve\n"
|
||||
" ollama run llama3.2:3b")
|
||||
except requests.exceptions.Timeout:
|
||||
wx.CallAfter(self.add_message, "❌ Error", "AI timeout - please try again")
|
||||
except Exception as e:
|
||||
wx.CallAfter(self.add_message, "❌ Error", f"AI error: {str(e)}")
|
||||
finally:
|
||||
wx.CallAfter(self.send_btn.Enable, True)
|
||||
wx.CallAfter(self.set_status, "Ready")
|
||||
|
||||
def get_mode_instructions(self):
|
||||
"""Get instructions based on current interaction mode"""
|
||||
if self.interaction_mode == self.ANALYSIS_MODE:
|
||||
return ("ANALYSIS MODE: Provide only analysis and recommendations. "
|
||||
"Do not suggest any direct modifications to the design. "
|
||||
"Focus on observations and general advice.")
|
||||
|
||||
elif self.interaction_mode == self.ADVISORY_MODE:
|
||||
return ("ADVISORY MODE: Provide step-by-step instructions when suggesting changes. "
|
||||
"Always ask for user confirmation before proceeding with multi-step processes. "
|
||||
"Format suggestions as clear actionable steps with safety warnings when needed. "
|
||||
"Example: 'To remove R14: 1) First select the component 2) Press Delete 3) Update the netlist. Would you like me to guide you through this?'")
|
||||
|
||||
elif self.interaction_mode == self.ASSISTANT_MODE:
|
||||
return ("ASSISTANT MODE: Provide interactive design assistance. "
|
||||
"You can suggest specific actions and modifications. "
|
||||
"When appropriate, indicate what changes could be made automatically in the future. "
|
||||
"Be proactive in offering to help with implementation.")
|
||||
|
||||
return ""
|
||||
|
||||
def process_user_message(self, message):
|
||||
"""Process user message with mode-specific handling"""
|
||||
self.send_btn.Enable(False)
|
||||
self.set_status("Processing...")
|
||||
|
||||
# Check for mode-specific commands
|
||||
if self.interaction_mode == self.ADVISORY_MODE:
|
||||
if any(word in message.lower() for word in ['remove', 'delete', 'change', 'modify', 'update']):
|
||||
# Add advisory warning
|
||||
self.add_message("⚠️ Advisory",
|
||||
"I'll provide step-by-step guidance for this modification. "
|
||||
"Please confirm each step before proceeding.")
|
||||
|
||||
elif self.interaction_mode == self.ASSISTANT_MODE:
|
||||
if any(word in message.lower() for word in ['remove', 'delete', 'change', 'modify']):
|
||||
# Add assistant note
|
||||
self.add_message("🤖 Assistant",
|
||||
"I'll provide interactive guidance. In future versions, "
|
||||
"I may be able to help automate some of these tasks.")
|
||||
|
||||
# Start AI processing in thread
|
||||
thread = threading.Thread(target=self.send_to_ai, args=(message,))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 194 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.2 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
Reference in New Issue
Block a user