Repository navigation
Releases: brouwerict/open_router_fixed
Release list
OpenRouter Fixed - Release v1.2.6
OpenRouter Fixed - Release v1.2.6
🎯 Feature Release: Improved API Error Handling & Automatic Retries
This release dramatically improves error handling with specific, actionable error messages and automatic retry logic for transient API failures.
✨ What's New
Intelligent Error Handling (Major Improvement)
Before: Generic unhelpful error messages
Error talking to API
After: Specific, actionable error messages with provider context
Provider 'Chutes' is temporarily at capacity. Please try again in a few minutes or select a different model.
Automatic Retry Logic (New Feature)
The integration now automatically retries transient API errors:
| Error Type | Max Retries | Retry Delays | Total Wait |
|---|---|---|---|
| 503 Service Unavailable | 2 | 5s, 10s | Up to 15s |
| 429 Rate Limit | 2 | 10s, 20s | Up to 30s |
Benefits:
- ✅ Handles temporary provider capacity issues automatically
- ✅ Reduces failed requests during high load periods
- ✅ No user intervention needed for transient failures
- ✅ Detailed logging shows retry progress
Example log output:
Provider 'Chutes' temporarily unavailable (attempt 1/3). Retrying in 5s...
Provider 'Chutes' temporarily unavailable (attempt 2/3). Retrying in 10s...
🔧 Specific Error Types Handled
1. 503 Service Unavailable
What it means: Provider (e.g., Chutes) has no available GPU instances
Old behavior: Generic error, immediate failure
New behavior:
- Automatically retries 2 times (5s, 10s delays)
- Extracts provider name from error metadata
- Final error if retries fail:
Provider 'Chutes' is temporarily at capacity. Please try again in a few minutes or select a different model.
2. 429 Rate Limit
What it means: Too many requests to provider's API
Old behavior: Generic error, immediate failure
New behavior:
- Automatically retries 2 times (10s, 20s delays)
- Parses rate limit details from upstream
- Final error if retries fail:
Rate limit exceeded: mistralai/mistral-small-3.2-24b-instruct:free is temporarily rate-limited upstream. Please retry shortly, or add your own key to accumulate your rate limits: https://openrouter.ai/settings/integrations. Please wait before retrying or upgrade to a paid plan.
3. 404 Image Input Not Supported
What it means: Model doesn't support vision/image inputs
Old behavior: Generic BadRequestError
New behavior:
- Detects "no endpoints found that support image input"
- Clear error message:
Model deepseek/deepseek-chat does not support images. Please configure a vision-capable model (e.g., gpt-4-vision-preview, claude-3-haiku, gemini-pro-vision).
4. Other HTTP Errors
New behavior: Extracts status code and error details
API error (404): [specific error message]
API error (500): Internal server error
📋 Technical Details
Error Response Parsing (entity.py)
The integration now extracts rich error metadata:
# Extracts from error.response.json():
{
"error": {
"message": "Provider returned error",
"code": 503,
"metadata": {
"provider_name": "Chutes", # ← Used in error messages
"raw": "{...}" # ← Additional context
}
}
}Exception Hierarchy
New exception handling order (most specific to most generic):
- openai.BadRequestError → Vision/image errors, malformed requests
- openai.APIStatusError → HTTP status codes (503, 429, 404, etc.)
- openai.OpenAIError → Generic fallback (network, auth, etc.)
Code Changes
entity.py:464-567
- Added
import asynciofor retry delays - Nested retry loop (max 2 retries for transient errors)
- Status code specific handling (503, 429, 404)
- Provider metadata extraction
- Exponential backoff delays
- Detailed logging at each step
✅ Result
- ✅ Better UX: Users see clear, actionable error messages
- ✅ Automatic recovery: Transient errors often resolve without user action
- ✅ Better debugging: Logs show which provider failed and why
- ✅ Graceful degradation: Permanent errors still fail fast with clear messages
🆙 Upgrade Instructions
From v1.2.5 or earlier:
- Update via HACS or manually
- Restart Home Assistant
- Monitor logs - you'll see new retry messages during temporary outages
No configuration changes required - fully backward compatible.
What to Expect
During normal operation: No visible changes, requests work as before
During provider issues: You'll see new log messages:
WARNING: Provider 'Chutes' temporarily unavailable (attempt 1/3). Retrying in 5s...
WARNING: Provider 'Chutes' temporarily unavailable (attempt 2/3). Retrying in 10s...
INFO: Request succeeded after 1 retry
If retries fail: Clear error message instead of generic "Error talking to API"
🧪 Tested With
- Home Assistant 2024.1+
- Python 3.11, 3.12, 3.13
- OpenAI library 2.0.0+
- python-open-router 0.3.1+
Tested error scenarios:
- ✅ 503 Chutes capacity issues (DeepSeek models under load)
- ✅ 429 Rate limits on free tier models
- ✅ 404 Image input not supported errors
- ✅ Network timeouts and connection errors
📦 Commits in This Release
1a30a2c- feat: improved API error handling with retry logic
🔗 Links
- Repository: https://github.com/brouwerict/open_router_fixed
- Issues: https://github.com/brouwerict/open_router_fixed/issues
- Previous Release: v1.2.5
📝 Notes
This release focuses on resilience and user experience during API errors. All features from v1.2.5 remain unchanged:
- AI Task entity support
- Camera snapshot analysis
- Vision model compatibility
- Structured JSON responses
- Lazy import pattern (from v1.2.4)
- OpenAI library v2.x support (from v1.2.5)
Performance Impact
Minimal - Retries only occur during actual failures:
- Normal requests: 0 overhead
- Single transient error: +5-10s recovery time (vs immediate failure)
- Persistent errors: +15-30s before final failure (better UX than instant failure)
Cost Impact
None - Retries for 503/429 don't consume API credits (request never reached model)
Recommendation: All users should upgrade for better reliability during provider capacity issues and clearer error messages.
OpenRouter Fixed - Release v1.2.5
OpenRouter Fixed - Release v1.2.5
🔧 Dependency Fix Release: OpenAI Library v2.x Support
This release fixes a critical import error when using OpenAI library version 2.0.0 or higher.
🐛 What's Fixed
ImportError: NotGivenOr Type Not Found (Critical)
Problem: Home Assistant failed to load the integration with this error:
ImportError: cannot import name 'NotGivenOr' from 'openai._types' (/usr/local/lib/python3.13/site-packages/openai/_types.py)
Root Cause:
- OpenAI library v2.0.0 (released September 2024) removed the internal type
NotGivenOrfromopenai._types - Previous version constraint was
openai>=1.99.5,<2.0.0 - Home Assistant's dependency resolution installed v2.x despite the constraint, causing the import to fail
Solution: Updated OpenAI library requirement to officially support v2.x:
Changes
manifest.json
// Before
"requirements": ["openai>=1.99.5,<2.0.0", "python-open-router>=0.3.1"]
// After
"requirements": ["openai>=2.0.0", "python-open-router>=0.3.1"]✅ Result
- ✅ Integration loads successfully with OpenAI library v2.0.0+
- ✅ Future-proof for latest OpenAI features
- ✅ All functionality preserved - no breaking changes
- ✅ Existing code already compatible via TYPE_CHECKING guards
🔍 Technical Details
Why This Works
The integration code was already compatible with OpenAI v2.x:
-
Type-only imports: All OpenAI types are imported in
TYPE_CHECKINGblocks (not executed at runtime)if TYPE_CHECKING: from openai.types.chat import ChatCompletionMessage
-
Runtime import guards: All runtime imports use try/except for version compatibility
try: from openai.types.shared_params import ResponseFormatJSONSchema except ImportError: ResponseFormatJSONSchema = dict # Fallback
-
No use of removed types: The integration never used
NotGivenOrin its code
OpenAI v2.0.0 Breaking Changes
For reference, key changes in OpenAI library v2.0.0:
- Removed
NotGivenOrinternal type - Changed
ResponseFunctionToolCallOutputItem.outputtype signature - Introduced
Omittabletype as replacement pattern
None of these affect this integration's functionality.
📦 Version Support
| Component | Version Required |
|---|---|
| Home Assistant | 2024.1+ |
| Python | 3.11, 3.12, 3.13 |
| OpenAI library | 2.0.0+ (latest: 2.8.0) |
| python-open-router | 0.3.1+ |
🔄 Upgrade Instructions
From v1.2.4 or earlier:
- Update via HACS or manually
- Restart Home Assistant
- Verify integration loads without errors
No configuration changes required - fully backward compatible.
🧪 Tested With
- Home Assistant Core 2024.1+
- Python 3.13 on WSL2
- OpenAI library 2.0.0 - 2.8.0
- python-open-router 0.3.1
📦 Commits in This Release
6f749b6- feat: upgrade to openai library v2.x
🔗 Links
- Repository: https://github.com/brouwerict/open_router_fixed
- Issues: https://github.com/brouwerict/open_router_fixed/issues
- Previous Release: v1.2.4
📝 Notes
This is a dependency fix focused on OpenAI library compatibility. All features from v1.2.4 remain unchanged:
- AI Task entity support
- Camera snapshot analysis
- Vision model compatibility
- Structured JSON responses
- Lazy import pattern (from v1.2.4)
Recommendation: All users should upgrade to ensure compatibility with current OpenAI library versions.
V1.2.4 🐛 Bug Fix: Event Loop Blocking Resolved
🐛 Bug Fix: Event Loop Blocking Resolved
Fixes critical Home Assistant stability issue where the integration blocked the event loop during initialization.
What's Fixed
Event Loop Blocking Warning ✅
- Deferred heavy library imports (
openai,python-open-router) to async functions - Eliminated blocking import warnings in Home Assistant logs
- Improved startup performance and system stability
Technical Changes
__init__.py: Moved openai imports toasync_setup_entry()entity.py: All openai types underTYPE_CHECKING, runtime imports in functionsconfig_flow.py: python_open_router imports deferred to async methods
Upgrade Notes
- ✅ Fully backward compatible - no configuration changes needed
- ✅ All features from v1.2.3 preserved
- ✅ Faster Home Assistant startup
- ✅ No more blocking warnings
Installation
Update via HACS or manually, then restart Home Assistant.
Full release notes:
RELEASE_NOTES_v1.2.4.md
Recommendation: All users should upgrade to eliminate event loop blocking and improve HA stability.
## Version 1.2.2 - Camera Snapshot & AI Task Integration Fixed
OpenRouter Fixed - Release Notes
Version 1.2.2 - Camera Snapshot & AI Task Integration Fixed
This release provides a fully functional OpenRouter integration for Home Assistant with comprehensive AI Task support and camera snapshot analysis capabilities. This custom component resolves multiple compatibility issues present in the original Home Assistant OpenRouter integration.
🎯 Primary Purpose
This integration enables Home Assistant users to:
- Use OpenRouter AI models for AI Task entity operations
- Analyze camera snapshots with vision-capable models (Claude, GPT-4V, Qwen-VL)
- Process structured JSON responses for automation workflows
- Integrate with Home Assistant's native AI Task service
🔧 Key Fixes & Improvements
1. OpenAI Library Compatibility (Critical Fix)
Problem: Original integration fails with different OpenAI library versions due to import incompatibilities.
Solution: Added comprehensive import compatibility layer across multiple files:
# Enhanced compatibility in entity.py
try:
from openai.types.chat import ChatCompletionFunctionToolParam
from openai.types.shared_params import ResponseFormatJSONSchema
from openai.types.shared_params.response_format_json_schema import JSONSchema
except ImportError:
# Fallback implementations with TypedDict
ChatCompletionFunctionToolParam = Dict[str, Any]
# ... additional fallbacksFiles Modified: entity.py, ai_task.py, __init__.py
2. AI Task Entity Support (New Feature)
Problem: Original integration lacks AI Task entity support, preventing use with Home Assistant's AI Task service.
Solution: Complete AI Task entity implementation:
- Created
ai_task.pywith fullAITaskEntitysupport - Added attachment processing for camera snapshots
- Implemented structured JSON response handling
- Added support for
ai_task.generate_dataservice calls
Files Added: ai_task.py (entirely new)
Files Modified: manifest.json, __init__.py, strings.json
3. Camera Snapshot & Attachment Processing (Major Feature)
Problem: No support for processing camera images or file attachments with AI models.
Solution: Comprehensive attachment handling system:
# Multi-format attachment support
content_attrs = ['content', 'data', 'binary_data', 'bytes', 'file_content', 'image_data', 'payload']
for attr in content_attrs:
if hasattr(attachment, attr):
image_content = getattr(attachment, attr)
break
# File path fallback support
if hasattr(attachment, 'file_path') and attachment.file_path:
with open(attachment.file_path, 'rb') as f:
image_content = f.read()Supported Attachment Sources:
- Direct camera streams (
media-source://camera/camera_name) - File paths (
/config/www/snapshot.jpg) - Base64 encoded images
- Binary data objects
4. Model Availability & Selection (Enhancement)
Problem: Limited model selection and filtering preventing access to vision-capable models.
Solution: Removed restrictive model filtering:
# config_flow.py - Removed structured output requirement
# OLD: Only models with structured output support
# NEW: All available OpenRouter models accessibleResult: Access to 200+ OpenRouter models including:
- Claude 3.5 Sonnet, Claude 3 Haiku
- GPT-4o, GPT-4o-mini
- Qwen2.5-VL-72B (free vision model)
- Gemini Pro Vision
- And many more...
5. JSON Response Processing (Reliability Fix)
Problem: Inconsistent JSON parsing causing automation failures.
Solution: Robust JSON handling with graceful fallbacks:
try:
data = json_loads(text)
_LOGGER.debug("Successfully parsed structured response")
except JSONDecodeError as err:
_LOGGER.error("Failed to parse JSON response: %s", text[:500])
# Return raw text instead of crashing
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=text,
)6. UI Translations & Strings (Bug Fix)
Problem: Missing UI strings causing empty button labels in configuration.
Solution: Complete translation support:
Files Added:
strings.json- English UI stringstranslations/en.json- Translation mappings
Fixed UI Elements:
- "Add AI Task" button labels
- Configuration descriptions
- Error messages
📋 Complete File Modifications
Files Modified from Original
| File | Changes | Purpose |
|---|---|---|
manifest.json |
Domain name, version, flexible OpenAI requirements | HACS compatibility |
__init__.py |
AI Task platform loading, error handling | Service integration |
entity.py |
OpenAI imports, attachment processing, vision support | Core functionality |
config_flow.py |
Model filtering removal, enhanced model loading | Model selection |
Files Added (New)
| File | Purpose |
|---|---|
ai_task.py |
Complete AI Task entity implementation |
strings.json |
UI text definitions |
translations/en.json |
English translations |
Configuration Files
| File | Purpose |
|---|---|
vehicle_detection_WORKING.yaml |
Example automation with camera snapshot |
vehicle_check_OPTIMIZED.yaml |
Optimized vehicle detection workflow |
dev_tools_CORRECT.yaml |
Developer Tools service call examples |
🚀 Usage Examples
Basic AI Task Service Call
service: ai_task.generate_data
data:
entity_id: ai_task.anthropic_claude_3_haiku
task_name: "Image Analysis"
instructions: "Analyze this image and return JSON with vehicle count"
attachments:
media_content_id: media-source://camera/front_door
media_content_type: image/jpeg
response_variable: resultCamera Snapshot Analysis
# Complete automation example included in release
alias: "Vehicle Detection with Camera"
trigger:
- trigger: state
entity_id: binary_sensor.motion_detected
action:
- service: ai_task.generate_data
data:
entity_id: ai_task.qwen_qwen2_5_vl_72b_instruct # Free model!
task_name: "Vehicle Detection"
instructions: |
Count vehicles in this driveway image.
Return JSON: {"cars": 0, "motorcycles": 0}
attachments:
media_content_id: media-source://camera/driveway
media_content_type: image/jpeg
response_variable: vehicle_data🔄 Migration from Original Integration
Automatic Migration
- Configuration entries are preserved
- Existing conversations continue to work
- Model selections remain intact
New Capabilities Available
- AI Task entities appear in entity registry
- Camera snapshot analysis in automations
- Structured JSON responses
- Enhanced model selection
🧪 Tested Configurations
Models Tested
- ✅ Claude 3 Haiku (fast, cost-effective)
- ✅ Claude 3.5 Sonnet (high accuracy)
- ✅ GPT-4o-mini (OpenAI vision)
- ✅ Qwen2.5-VL-72B (free, excellent performance)
Attachment Types Tested
- ✅ Live camera streams
- ✅ Static image files
- ✅ Home Assistant camera snapshots
- ✅ Media source URLs
Integration Points Tested
- ✅ Developer Tools > Services
- ✅ Automation YAML workflows
- ✅ Template sensors
- ✅ Script integrations
🔍 Technical Deep Dive
Core Architecture Changes
- Modular Import System: Handles OpenAI library version differences gracefully
- Attachment Pipeline: Processes multiple input formats with fallback mechanisms
- AI Task Bridge: Connects OpenRouter models to Home Assistant AI Task framework
- Error Recovery: Comprehensive error handling prevents integration crashes
Performance Optimizations
- Lazy Loading: Models load on-demand to reduce startup time
- Caching: Configuration and model data cached for faster access
- Async Processing: All AI calls use async/await patterns
- Memory Management: Efficient image processing with cleanup
📊 Cost Optimization
Model Cost Comparison (per 1000 calls)
- Claude 3 Haiku: ~$0.61
- GPT-4o-mini: ~$0.42
- Qwen2.5-VL-72B: $0.00 ⭐ (Free!)
Recommended Setup
For production use with camera analysis:
entity_id: ai_task.qwen_qwen2_5_vl_72b_instruct
# 72B parameter model with vision capabilities - completely free!🛠️ Installation & Setup
HACS Installation
- Add custom repository:
https://github.com/brouwerict/open_router_fixed - Install via HACS
- Restart Home Assistant
- Configure via Settings > Integrations
Manual Installation
- Copy
custom_components/openrouter_fixed/to your HA config - Restart Home Assistant
- Add integration via UI
Configuration
- Add OpenRouter API key
- Select AI models for conversation and/or AI Task
- Configure camera entities (if using vision features)
🆕 What's New in This Release
Version 1.2.2
- ✅ Complete AI Task entity support
- ✅ Camera snapshot processing
- ✅ Qwen2.5-VL model support (free tier)
- ✅ Enhanced error handling
- ✅ Performance optimizations
Breaking Changes
- None - fully backward compatible
Deprecations
- None - all existing functionality preserved
🤝 Contributing
Found an issue or want to contribute?
- Repository: https://github.com/brouwerict/open_router_fixed
- Issues: Report bugs and feature requests
- Pull Requests: Contributions welcome
📄 License
Same as Home Assistant core: Apache 2.0
**This integration transforms OpenRouter from a simple conversation tool into a powerful AI Task processor with vision capabilities, enabling advanced home automation scenarios with camera analysis and structured...
🚀 OpenRouter Fixed v1.2.1 - Major Update with Vision Support
🚀 OpenRouter Fixed v1.2.0 - Major Update with Vision Support
🚀 OpenRouter Fixed v1.1.6- Major Update with Vision Support
🚀 OpenRouter Fixed v1.1.5 - Major Update with Vision Support
🚀 OpenRouter Fixed v1.1.4 - Major Update with Vision Support
🚀 OpenRouter Fixed v1.1.3 - Major Update with Vision Support
🔧 Critical Hotfix v1.1.3 - OpenAI Import Compatibility Fixed all remaining OpenAI library import issues: - ChatCompletionMessageFunctionToolCallParam fallback - Tool calls creation compatibility - Runtime error handling for all type imports This should resolve all import errors preventing integration startup.