-
Notifications
You must be signed in to change notification settings - Fork 0
Session 4: Build Intelligence, Security & Cloud layers (6 prototypes) #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
blackboxprogramming
wants to merge
1
commit into
main
Choose a base branch
from
claude/continue-building-M810l
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # AI Provider Failover Chain | ||
|
|
||
| > **Route to intelligence. If one path fails, take another.** | ||
|
|
||
| The failover chain ensures requests always reach an AI provider by cascading through a priority-ordered list of providers with health tracking, circuit breaking, and automatic recovery. | ||
|
|
||
| ## Architecture | ||
|
|
||
| ``` | ||
| [Request] --> [Failover Router] | ||
| | | ||
| ├── 1. Claude (primary) | ||
| | ├── healthy? --> route here | ||
| | └── failing? --> circuit open, skip | ||
| | | ||
| ├── 2. GPT (secondary) | ||
| | ├── healthy? --> route here | ||
| | └── failing? --> circuit open, skip | ||
| | | ||
| ├── 3. Llama (local/tertiary) | ||
| | ├── healthy? --> route here | ||
| | └── failing? --> circuit open, skip | ||
| | | ||
| └── 4. All down --> queue + retry | ||
| ``` | ||
|
|
||
| ## Features | ||
|
|
||
| - **Priority-based routing** - Tries providers in order of preference | ||
| - **Circuit breaker** - Opens after N failures, half-opens after cooldown | ||
| - **Health checks** - Periodic pings to track provider status | ||
| - **Latency tracking** - Records response times per provider | ||
| - **Retry with backoff** - Exponential backoff on transient failures | ||
| - **Request queuing** - Queues requests when all providers are down | ||
| - **Provider scoring** - Weighted scoring based on latency, reliability, cost | ||
|
|
||
| ## Files | ||
|
|
||
| | File | Purpose | | ||
| |------|---------| | ||
| | `provider.py` | Provider abstraction and health tracking | | ||
| | `circuit_breaker.py` | Circuit breaker pattern implementation | | ||
| | `failover_router.py` | Core routing logic with failover | | ||
| | `config.py` | Provider configuration and defaults | | ||
|
|
||
| ## Usage | ||
|
|
||
| ```python | ||
| from failover_router import FailoverRouter | ||
| from config import DEFAULT_PROVIDERS | ||
|
|
||
| router = FailoverRouter(DEFAULT_PROVIDERS) | ||
| response = await router.route(prompt="What is BlackRoad?", max_tokens=500) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| *Intelligence is already out there. We just need reliable paths to reach it.* |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| """ | ||
| Circuit Breaker Pattern | ||
| Prevents cascading failures by tracking error rates and temporarily | ||
| disabling unhealthy providers. | ||
|
|
||
| States: | ||
| CLOSED -> Normal operation, requests flow through | ||
| OPEN -> Provider failing, requests blocked | ||
| HALF_OPEN -> Testing if provider recovered | ||
| """ | ||
|
|
||
| import time | ||
| from enum import Enum | ||
| from dataclasses import dataclass, field | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class CircuitState(Enum): | ||
| CLOSED = "closed" # Healthy - requests flow | ||
| OPEN = "open" # Failing - requests blocked | ||
| HALF_OPEN = "half_open" # Testing recovery | ||
|
|
||
|
|
||
| @dataclass | ||
| class CircuitStats: | ||
| """Tracks circuit breaker statistics.""" | ||
| total_requests: int = 0 | ||
| successful_requests: int = 0 | ||
| failed_requests: int = 0 | ||
| consecutive_failures: int = 0 | ||
| consecutive_successes: int = 0 | ||
| last_failure_time: Optional[float] = None | ||
| last_success_time: Optional[float] = None | ||
| state_changes: int = 0 | ||
| total_open_time: float = 0.0 | ||
| last_state_change: Optional[float] = None | ||
|
|
||
|
|
||
| class CircuitBreaker: | ||
| """ | ||
| Circuit breaker for an AI provider. | ||
|
|
||
| CLOSED: All good. Count failures. | ||
| OPEN: Too many failures. Block requests. Wait for recovery timeout. | ||
| HALF_OPEN: Recovery timeout passed. Allow limited test requests. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| name: str, | ||
| failure_threshold: int = 3, | ||
| recovery_timeout: float = 60.0, | ||
| half_open_max_calls: int = 1, | ||
| ): | ||
| self.name = name | ||
| self.failure_threshold = failure_threshold | ||
| self.recovery_timeout = recovery_timeout | ||
| self.half_open_max_calls = half_open_max_calls | ||
|
|
||
| self._state = CircuitState.CLOSED | ||
| self._half_open_calls = 0 | ||
| self._opened_at: Optional[float] = None | ||
| self.stats = CircuitStats() | ||
|
|
||
| @property | ||
| def state(self) -> CircuitState: | ||
| """Get current state, auto-transitioning OPEN -> HALF_OPEN if cooldown passed.""" | ||
| if self._state == CircuitState.OPEN and self._opened_at: | ||
| elapsed = time.time() - self._opened_at | ||
| if elapsed >= self.recovery_timeout: | ||
| self._transition(CircuitState.HALF_OPEN) | ||
| return self._state | ||
|
|
||
| @property | ||
| def is_available(self) -> bool: | ||
| """Can we send a request through this circuit?""" | ||
| state = self.state | ||
| if state == CircuitState.CLOSED: | ||
| return True | ||
| if state == CircuitState.HALF_OPEN: | ||
| return self._half_open_calls < self.half_open_max_calls | ||
| return False # OPEN | ||
|
|
||
| def record_success(self, latency: float = 0.0) -> None: | ||
| """Record a successful request.""" | ||
| self.stats.total_requests += 1 | ||
| self.stats.successful_requests += 1 | ||
| self.stats.consecutive_successes += 1 | ||
| self.stats.consecutive_failures = 0 | ||
| self.stats.last_success_time = time.time() | ||
|
|
||
| if self._state == CircuitState.HALF_OPEN: | ||
| # Recovery confirmed - close the circuit | ||
| self._transition(CircuitState.CLOSED) | ||
|
|
||
| def record_failure(self, error: Optional[str] = None) -> None: | ||
| """Record a failed request.""" | ||
| now = time.time() | ||
| self.stats.total_requests += 1 | ||
| self.stats.failed_requests += 1 | ||
| self.stats.consecutive_failures += 1 | ||
| self.stats.consecutive_successes = 0 | ||
| self.stats.last_failure_time = now | ||
|
|
||
| if self._state == CircuitState.HALF_OPEN: | ||
| # Recovery failed - reopen | ||
| self._transition(CircuitState.OPEN) | ||
| elif self._state == CircuitState.CLOSED: | ||
| if self.stats.consecutive_failures >= self.failure_threshold: | ||
| self._transition(CircuitState.OPEN) | ||
|
|
||
| def reset(self) -> None: | ||
| """Manually reset circuit to closed state.""" | ||
| self._transition(CircuitState.CLOSED) | ||
| self.stats.consecutive_failures = 0 | ||
| self.stats.consecutive_successes = 0 | ||
|
|
||
| def _transition(self, new_state: CircuitState) -> None: | ||
| """Transition to a new state.""" | ||
| now = time.time() | ||
| old_state = self._state | ||
|
|
||
| if old_state == CircuitState.OPEN and self._opened_at: | ||
| self.stats.total_open_time += now - self._opened_at | ||
|
|
||
| self._state = new_state | ||
| self.stats.state_changes += 1 | ||
| self.stats.last_state_change = now | ||
|
|
||
| if new_state == CircuitState.OPEN: | ||
| self._opened_at = now | ||
| self._half_open_calls = 0 | ||
| elif new_state == CircuitState.HALF_OPEN: | ||
| self._half_open_calls = 0 | ||
| elif new_state == CircuitState.CLOSED: | ||
| self._opened_at = None | ||
| self._half_open_calls = 0 | ||
| self.stats.consecutive_failures = 0 | ||
|
|
||
| def to_dict(self) -> dict: | ||
| """Serialize state for monitoring.""" | ||
| return { | ||
| "name": self.name, | ||
| "state": self.state.value, | ||
| "consecutive_failures": self.stats.consecutive_failures, | ||
| "total_requests": self.stats.total_requests, | ||
| "success_rate": ( | ||
| self.stats.successful_requests / self.stats.total_requests | ||
| if self.stats.total_requests > 0 | ||
| else 1.0 | ||
| ), | ||
| "total_open_time": round(self.stats.total_open_time, 2), | ||
| "is_available": self.is_available, | ||
| } | ||
|
|
||
| def __repr__(self) -> str: | ||
| return ( | ||
| f"CircuitBreaker({self.name}, state={self.state.value}, " | ||
| f"failures={self.stats.consecutive_failures}/{self.failure_threshold})" | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The is_available property checks _half_open_calls in HALF_OPEN state but doesn't increment this counter. The counter should be incremented when a request is made in HALF_OPEN state, but there's no mechanism to do this. This means multiple concurrent requests could all pass the is_available check and exceed the half_open_max_calls limit. Consider implementing a method to track when a request starts in HALF_OPEN state or using atomic operations for thread safety.