Skip to content

Repository files navigation

🧪 Error Explainer

Author: Avishek Devnath
Email:avishekdevnath@gmail.com

Python 3.10+License: MITPyPIDownloadsVersionStatusMaintenance

AI-powered error analysis and explanation tool for multiple programming languages.

Explain error logs from Python, JavaScript, TypeScript, C++, and Java using Google's Gemini AI directly from your terminal. Get instant, intelligent explanations and fix suggestions for any programming error.

Built with ❤️ by Avishek Devnath

✨ Features

  • 🤖 AI-Powered Explanations: Uses Google Gemini 1.5 Flash for intelligent error analysis
  • 🔍 Offline Rule-Based Analysis: Works without AI - instant explanations for common errors
  • 🌐 Multi-Language Support: Python, JavaScript, TypeScript, C++, Java
  • 📁 Multiple Input Methods: Read from files, stdin, or paste interactively
  • 💾 Save & Search: Store explanations and search through your error history
  • 🎨 Rich Output: Beautiful terminal formatting with progress indicators
  • 🔍 Smart Parsing: Intelligent traceback and error detection across languages
  • 📊 Markdown Export: Export explanations in markdown format
  • Fast & Lightweight: Quick analysis with minimal dependencies
  • 🌐 Works Offline: No internet connection required for rule-based mode
  • 🔄 Real-time Monitoring: Watch running processes for live error detection
  • 🐍 Python API: Programmatic access for integration with your tools
  • 🔧 Multi-Model Support: Switch between different AI providers
  • 🎯 Language Auto-Detection: Automatically identifies programming language from error logs

🚀 Quick Start

Installation

For Users:

pip install xerror

For Developers:

# Clone the repository
git clone https://github.com/xerror/xerror.git
cd xerror
# Install in development mode
pip install -e .

Setup API Key

  1. Get your Google Gemini API key from Google AI Studio
  2. Set the environment variable:
export GOOGLE_API_KEY=your-api-key-here

Or create a .env file in your project directory:

GOOGLE_API_KEY=your-api-key-here

Basic Usage

# Explain error from file (AI mode - requires API key)
xerror error.log
# Explain error offline (no API key required)
xerror error.log --offline
# Paste error interactively
xerror --paste
# Paste error offline
xerror --paste --offline
# Pipe error from stdin
xerror < error.log
# Save explanation to history
xerror error.log --save
# Output in markdown format
xerror error.log --markdown

🌐 Supported Languages

LanguageError DetectionAI ExplanationRule-BasedExamplesStatus
PythonNameError, TypeError, ImportError🟢 Production Ready
JavaScriptTypeError, ReferenceError, SyntaxError🟢 Production Ready
TypeScriptTS2322, TS2339, TS2307🟢 Production Ready
C++Compilation errors, runtime errors🟢 Production Ready
JavaNullPointerException, ClassNotFoundException🟢 Production Ready

📖 Usage Examples

1. Multi-Language Error Analysis

# Python error
xerror python_error.log
# JavaScript error
xerror javascript_error.log
# TypeScript error
xerror typescript_error.log
# C++ error
xerror cpp_error.log
# Java error
xerror java_error.log

2. Language Detection

# Auto-detect language from error
xerror detect "NameError: name 'x' is not defined"
xerror detect "TypeError: Cannot read property 'length' of undefined"
xerror detect "TS2322: Type 'string' is not assignable to type 'number'"
xerror detect "error: 'cout' was not declared in this scope"
xerror detect "Exception in thread \"main\" java.lang.NullPointerException"

3. Real-time Process Monitoring

# Watch a running process for errors
xerror watch "python my_script.py"# Watch with custom command
xerror watch "npm start"# Watch in background mode
xerror watch "python long_running_script.py" --background

4. Python API Examples

importxerror# Basic error explanationresult=xerror.explain_error("NameError: name 'x' is not defined")
print(result['explanation'])
# Language detectionlanguage=xerror.detect_language("TypeError: Cannot read property 'length' of undefined")
print(f"Detected language: {language}")
# Parse error detailserror_info=xerror.parse_error("TS2322: Type 'string' is not assignable to type 'number'")
print(f"Error type: {error_info.error_type}")
print(f"Language: {error_info.language}")
# Quick explanation (rule-based only)explanation=xerror.quick_explain("TypeError: can only concatenate str (not 'int') to str")
print(explanation)
# Automatic error handlingwithxerror.auto_explain_exceptions():
undefined_variable# This will be automatically explained# Function decorator@xerror.explain_function_errors()defmy_function():
returnundefined_variable

5. Error Examples by Language

Python Errors

# NameErrorNameError: name'x'isnotdefined# TypeErrorTypeError: canonlyconcatenatestr (not'int') tostr# ImportErrorImportError: Nomodulenamed'requests'# IndentationErrorIndentationError: expectedanindentedblock# AttributeErrorAttributeError: 'list'objecthasnoattribute'append'# ValueErrorValueError: invalidliteralforint() withbase10: 'abc'

JavaScript Errors

// TypeError
TypeError: Cannotreadproperty'length'ofundefined// ReferenceError
ReferenceError: xisnotdefined// SyntaxError
SyntaxError: Unexpectedtoken'{'// RangeError
RangeError: Maximumcallstacksizeexceeded// URIError
URIError: URImalformed

TypeScript Errors

// TS2322: Type assignment error
TS2322: Type'string'isnotassignabletotype'number'// TS2339: Property does not exist
TS2339: Property'length'doesnotexistontype'number'// TS2307: Module not found
TS2307: Cannotfind module './Component'// TS2345: Argument type mismatch
TS2345: Argumentoftype'string'isnotassignabletoparameteroftype'number'// TS2531: Object is possibly null
TS2531: Objectispossibly'null'

C++ Errors

// Compilation error
error: 'cout' was not declared in this scope
// Syntax error
error: expected ';' before '}' token
// Missing include
error: 'vector' was not declared in this scope
// Linker error
undefined reference to 'main'// Runtime error
Segmentation fault (core dumped)

Java Errors

// NullPointerExceptionExceptioninthread"main"java.lang.NullPointerException// Compilation errorerror: cannotfindsymbol: variablex// Class not foundjava.lang.ClassNotFoundException: com.example.MyClass// ArrayIndexOutOfBoundsExceptionjava.lang.ArrayIndexOutOfBoundsException: Index5outofboundsforlength3// NumberFormatExceptionjava.lang.NumberFormatException: Forinputstring: "abc"

🐍 Python API Reference

Core Functions

FunctionDescriptionReturnsExample
explain_error(error_text)Full AI-powered error explanationDict with explanation, confidence, methodexplain_error("NameError: name 'x' is not defined")
quick_explain(error_text)Fast rule-based explanationString explanationquick_explain("TypeError: can only concatenate str (not 'int') to str")
detect_language(error_text)Detect programming languageLanguage enumdetect_language("TypeError: Cannot read property 'length' of undefined")
parse_error(error_text)Parse error detailsErrorInfo objectparse_error("TS2322: Type 'string' is not assignable to type 'number'")
get_supported_languages()Get list of supported languagesList of Language enumsget_supported_languages()

Context Managers

Context ManagerDescriptionExample
auto_explain_exceptions()Automatically explain any exceptionswith auto_explain_exceptions(): ...
watch_process(command)Monitor a running process for errorswith watch_process("python script.py"): ...

Decorators

DecoratorDescriptionExample
explain_function_errors()Automatically explain errors in decorated function@explain_function_errors()

See API Documentation for complete API reference.

🧪 Testing

Running Tests

# Run all tests
python -m pytest
# Run specific test categories
python -m pytest test_multi_language.py
python -m pytest test_api_proper.py
python -m pytest test_watcher.py
python -m pytest test_multi_model.py
# Run with coverage
python -m pytest --cov=xerror
# Run with verbose output
python -m pytest -v
# Run tests in parallel
python -m pytest -n auto

Test Coverage

ComponentTest FilesCoverageStatus
Core Language Detectiontest_multi_language.py✅ 100%🟢 Complete
Python APItest_api_proper.py✅ 100%🟢 Complete
Real-time Monitoringtest_watcher.py✅ 100%🟢 Complete
Multi-Model Supporttest_multi_model.py✅ 100%🟢 Complete
Error Parsingtest_parser.py✅ 100%🟢 Complete
Rule-Based Explainertest_rule_based.py✅ 100%🟢 Complete

Test Examples

# Test language detection
python test_multi_language.py
# Test API functionality
python test_api_proper.py
# Test watcher functionality
python test_watcher.py
# Test multi-model support
python test_multi_model.py

🔧 Advanced Usage

AI Mode vs Offline Mode

FeatureAI ModeOffline Mode
API Key Required✅ Yes❌ No
Internet Connection✅ Yes❌ No
Response Time2-5 secondsInstant
Explanation QualityHigh (contextual)Good (rule-based)
CoverageAll errorsCommon errors
CostAPI usageFree
Best ForComplex/unique errorsCommon errors, offline use
# AI mode (requires API key)
xerror error.log
# Offline mode (no API key needed)
xerror error.log --offline

Multi-Model Support

ModelProviderStatusFeaturesCost
Gemini 1.5 FlashGoogle✅ ActiveFast, cost-effectiveLow
Gemini 1.5 ProGoogle⚠️ LimitedHigher quality, slowerMedium
OpenAI GPT-4OpenAI🔧 OptionalHigh quality, paidHigh
Ollama LocalLocal🔧 OptionalOffline, customizableFree

Custom Configuration

# Use custom API key for this session
xerror error.log --api-key your-custom-key
# Use different AI model
xerror error.log --model gemini-1.5-pro
# Set custom log directoryexport ERROR_EXPLAINER_LOG_DIR=/custom/path
xerror error.log --save
# Set default modelexport DEFAULT_MODEL=gemini-1.5-flash

Search with Filters

# Search by error type
xerror search "NameError"# Search by language
xerror search "python"# Search by keyword
xerror search "undefined"# Search by filename
xerror search "views.py"# Limit search results
xerror search "error" --limit 5
# Search with date range
xerror search "error" --since "2024-01-01" --until "2024-12-31"

🚨 Troubleshooting

Common Issues

IssueSolutionStatus
API Key ErrorSet GOOGLE_API_KEY environment variable✅ Fixed
Language Not DetectedUse --offline mode or check error format✅ Fixed
Slow ResponseUse offline mode or check internet connection✅ Fixed
Import ErrorInstall with pip install xerror✅ Fixed
Permission DeniedCheck file permissions or use --offline✅ Fixed

Error Messages

# If you see: "No API key found"export GOOGLE_API_KEY=your-api-key-here
# If you see: "Language not detected"
xerror error.log --offline
# If you see: "Import error"
pip install --upgrade xerror
# If you see: "Permission denied"
chmod +r error.log

Performance Tips

  • Use --offline mode for faster responses
  • Save explanations with --save to avoid re-analyzing
  • Use specific error messages rather than full logs
  • Set up your API key in .env file for convenience

📁 Supported File Formats

FormatExtensionDescriptionExample
Log files.logStandard log fileserror.log
Text files.txtPlain text fileserror.txt
Python files.pyPython source filesscript.py
Error files.errorDedicated error fileserror.error
Any text*Any text-based fileoutput

🏗️ Project Structure

xerror/
├── xerror/
│ ├── __init__.py # Package initialization
│ ├── cli.py # Command line interface
│ ├── config.py # Configuration management
│ ├── explainer.py # AI explanation engine
│ ├── parser.py # Error parsing logic
│ ├── rule_based_explainer.py # Offline rule-based analysis
│ ├── api.py # Python API functions
│ ├── watcher.py # Real-time process monitoring
│ ├── models.py # Multi-model support
│ ├── language_parsers.py # Multi-language parsing
│ └── utils.py # Utility functions
├── examples/
│ ├── error_sample.log # Python error example
│ ├── javascript_error.log # JavaScript error example
│ ├── typescript_error.log # TypeScript error example
│ ├── cpp_error.log # C++ error example
│ ├── java_error.log # Java error example
│ └── api_usage_examples.py # API usage examples
├── setup.py # Package setup
├── requirements.txt # Dependencies
├── env.example # Environment template
├── README.md # This file
└── API_DOCUMENTATION.md # API documentation

🔮 Roadmap

FeatureStatusPriorityETADescription
VSCode Extension🔧 In ProgressHighQ4 2024IDE integration with real-time error detection
GitHub Actions CI🔧 In ProgressMediumQ4 2024Automated testing and deployment
Desktop Notifications📋 PlannedMediumQ1 2025Get notified of critical errors
More Languages (Go, Rust)📋 PlannedLowQ2 2025Extended language support
Web Interface📋 PlannedLowQ3 2025Browser-based error analysis
Mobile App📋 PlannedLowQ4 2025iOS/Android error analysis

🛠️ Development

Local Development Setup

# Clone the repository
git clone https://github.com/xerror/xerror.git
cd xerror
# Install in development mode
pip install -e .# Install development dependencies
pip install -r requirements.txt
# Set up environment
cp env.example .env
# Edit .env with your API keys

Development Commands

# Run tests
python -m pytest
# Run linting
flake8 xerror/
# Format code
black xerror/
# Type checking
mypy xerror/
# Build package
python setup.py sdist bdist_wheel
# Install from local build
pip install dist/xerror-0.1.0.tar.gz
# Run security checks
bandit -r xerror/

Contributing Guidelines

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Run tests: python -m pytest
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

📋 Requirements

ComponentVersionRequiredNotes
Python3.10+✅ YesCore requirement
Google Gemini APILatest⚠️ For AI modeFree tier available
Internet Connection-⚠️ For AI modeNot needed for offline mode
Click8.1.0+✅ YesCLI framework
Rich13.0.0+✅ YesTerminal formatting

🤝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Areas

AreaDescriptionPriorityStatus
Language SupportAdd new programming languagesHigh🔧 In Progress
Error PatternsImprove error detection patternsHigh🔧 In Progress
AI ModelsAdd support for new AI providersMedium📋 Planned
PerformanceOptimize parsing and analysis speedMedium📋 Planned
DocumentationImprove docs and examplesLow✅ Complete

How to Contribute

  1. Report Bugs: Use GitHub Issues
  2. Request Features: Use GitHub Discussions
  3. Submit Code: Follow the contributing guidelines above
  4. Improve Docs: Submit PRs for documentation improvements

📄 License

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

🙏 Acknowledgments

👨‍💻 Author

Avishek Devnath

📞 Support

ChannelLinkResponse TimeBest For
📧 Emailavishekdevnath@gmail.com24-48 hoursPersonal support, feature requests
🐛 IssuesGitHub Issues1-3 daysBug reports, technical issues
📖 DocumentationGitHub WikiInstantHow-to guides, tutorials
💬 DiscussionsGitHub Discussions1-2 daysGeneral questions, community help

Made with ❤️ by Avishek Devnath for developers everywhere

About

AI-powered error analysis and explanation tool for multiple programming languages. Explain error logs from Python, JavaScript, TypeScript, C++, and Java using Google's Gemini AI directly from your terminal. Get instant, intelligent explanations and fix suggestions for any programming error.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages