Spendplane Global
Provided by Spendit Agent

Multi-cloud LLM orchestration patterns and best practices

How do I route v0 traffic to Llama-3?
# Multi-Cloud LLM Orchestration Patterns and Best Practices ## Executive Summary Multi-cloud LLM orchestration is the architectural strategy of distributing large language model workloads across multiple cloud providers to optimize for cost, latency, reliability, compliance, and vendor diversification. **Why it matters now:** | Factor | Impact on LLM Workflows | |--------|-------------------------| | **Cost Arbitrage** | 40-60% price variance between providers for equivalent models | | **Latency Optimization** | Regional inference can reduce latency by 150-200ms | | **Resilience** | Eliminates single-cloud outage risk affecting AI services | | **Compliance** | Enables data residency requirements (GDPR, sovereign cloud) | --- ## Table of Contents 1. [Core Architectural Patterns](#core-architectural-patterns) 2. [Cross-Cloud Communication Patterns](#cross-cloud-communication-patterns) 3. [Cost Optimization Strategies](#cost-optimization-strategies) 4. [Resilience and Fault Tolerance Patterns](#resilience-and-fault-tolerance-patterns) 5. [Security and Compliance Patterns](#security-and-compliance-patterns) 6. [Performance Optimization Patterns](#performance-optimization-patterns) 7. [Best Practices Summary](#best-practices-summary) --- ## 1. Core Architectural Patterns ### Pattern 1: Provider-Agnostic Router Layer **Architecture Diagram** ``` ┌─────────────────────────────────────────────────────────────┐ │ APPLICATION LAYER │ └──────────────────────────┬──────────────────────────────────┘ │ ┌─────────────────▼──────────────────┐ │ MULTI-CLOUD ORCHESTRATOR │ │ ┌─────────────────────────────┐ │ │ │ INTELLIGENT ROUTER │ │ │ │ • Model Selection Engine │ │ │ │ • Cost Calculator │ │ │ │ • Latency Predictor │ │ │ └──────────────┬──────────────┘ │ │ │ │ │ ┌────────────┴────────────┐ │ │ ▼ ▼ │ │ ┌─────────┐ ┌─────────┐ │ │ │Fallback │ │ Load │ │ │ │ Handler │ │ Balancer│ │ │ └─────────┘ └─────────┘ │ └──────────────────┬─────────────────┘ │ ┌───────────────────┼───────────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ AWS Bedrock│ │ Azure OpenAI │ │ GCP Vertex │ │ (us-east)│ │ (eu-west) │ │ (ap-south)│ └──────────┘ └──────────┘ └──────────┘ ``` **Implementation Pattern** ```python from enum import Enum from dataclasses import dataclass import asyncio from typing import List, Dict, Optional import logging class RoutingStrategy(Enum): COST_OPTIMIZED = "cost" LATENCY_OPTIMIZED = "latency" RELIABILITY_FIRST = "reliability" HYBRID = "hybrid" @dataclass class ModelEndpoint: provider: str # 'aws', 'azure', 'gcp' model_id: str region: str cost_per_1k_tokens: float base_latency_ms: int health_score: float = 1.0 current_load: float = 0.0 class MultiCloudLLMOrchestrator: def __init__(self): self.endpoints: List[ModelEndpoint] = [] self.circuit_breakers: Dict[str, CircuitBreaker] = {} async def route_request( self, prompt: str, strategy: RoutingStrategy = RoutingStrategy.HYBRID, context: Optional[Dict] = None ) -> Dict: """Intelligent request routing with fallback mechanism""" candidates = await self._select_candidates(strategy, context) for endpoint in candidates: try: # Check circuit breaker state cb_key = f"{endpoint.provider}:{endpoint.region}" if not self.circuit_breakers[cb_key].is_available(): continue response = await self._execute_with_retry( endpoint, prompt, max_retries=2 ) # Record metrics for adaptive learning await self._record_execution_metrics(endpoint, response) return response except Exception as e: logging.error(f"Endpoint {endpoint.provider} failed: {e}") continue raise RuntimeError("All endpoints unavailable") async def _select_candidates( self, strategy: RoutingStrategy, context: Dict ) -> List[ModelEndpoint]: """Select and rank endpoints based on routing strategy""" if strategy == RoutingStrategy.COST_OPTIMIZED: return sorted(self.endpoints, key=lambda e: e.cost_per_1k_tokens) elif strategy == RoutingStrategy.LATENCY_OPTIMIZED: # Calculate effective latency with current load factor def calc_latency(e): return e.base_latency_ms * (1 + e.current_load * 0.5) return sorted(self.endpoints, key=calc_latency) elif strategy == RoutingStrategy.RELIABILITY_FIRST: return sorted( self.endpoints, key=lambda e: -e.health_score ) # Hybrid: Multi-factor weighted scoring else: def hybrid_score(e): cost_weight = 0.3 latency_weight = 0.4 reliability_weight = 0.3 normalized_cost = 1 / (e.cost_per_1k_tokens + 0.01) * 1000 normalized_latency = max(0, 100 - e.base_latency_ms) / 100 return ( cost_weight * normalized_cost + latency_weight * normalized_latency + reliability_weight * e.health_score ) return sorted(self.endpoints, key=hybrid_score, reverse=True) ``` ### Pattern 2: Federated Model Registry with Smart Caching **Architecture Overview** This pattern implements a distributed model registry that maintains metadata about available LLMs across clouds while caching common responses to reduce costs and latency. **Implementation** ```python from redis.asyncio import Redis import json import hashlib import time from typing import AsyncIterator class FederatedModelRegistry: def __init__(self, redis_url: str): self.redis = Redis.from_url(redis_url) self.model_cache_ttl = 3600 # 1 hour async def register_model(self, model_config: Dict): """Register a model endpoint across clouds""" key = f"model:{model_config['provider']}:{model_config['model_id']}" config_data = { **model_config, 'registered_at': time.time(), 'health_check_endpoint': model_config.get('health_endpoint'), 'capabilities': model_config.get('capabilities', []), # e.g., ['text', 'image', 'embedding'] } await self.redis.hset(key, mapping=config_data) async def find_optimal_model( self, requirements: Dict, user_region: str = None ) -> Optional[Dict]: """Find best model matching functional and non-functional requirements""" # Build Redis query based on requirements supported_providers = set() if 'capabilities' in requirements: for cap in requirements['capabilities']: key_pattern = f"model:*:{cap}" async for key in self.redis.scan_iter(key_pattern): provider_model = key.decode().split(':')[1:3] supported_providers.add(tuple(provider_model)) # Score candidates candidates = [] async for key in supported_providers: model_data = await self.redis.hgetall(f"model:{key[0]}:{key[1]}") score = self._calculate_model_score(model_data, requirements, user_region) if score > 0: candidates.append((score, json.loads(json.dumps(model_data)))) candidates.sort(reverse=True) return candidates[0][1] if candidates else None def _calculate_model_score(self, model_data, requirements, user_region) -> float: """Multi-factor scoring algorithm""" score = 100.0 # Region proximity bonus (up to +30 points) if user_region and model_data.get('region') == user_region: score += 30 # Cost penalty max_cost = requirements.get('max_cost_per_1k', float('inf')) current_cost = float(model_data.get('cost_per_1k_tokens', 0)) if current_cost > max_cost: return -1 # Disqualify else: cost_factor = max(0, 20 * (1 - current_cost/max_cost)) score += cost_factor # Capability match bonus required_caps = set(requirements.get('capabilities', [])) available_caps = set(model_data.get('capabilities', [])) if required_caps.issubset(available_caps): score += 15 return max(0, min(200, score)) class ResponseCache: """Intelligent response caching with semantic similarity detection""" def __init__(self, redis_client: Redis): self.redis = redis_client self.cache_key_prefix = "llm_response:" async def get_cached_response( self, prompt: str, model_id: str, tolerance: float = 0.85 ) -> Optional[Dict]: """Check cache with semantic similarity fallback""" # Exact match first exact_key = f"{self.cache_key_prefix}{model_id}:{hashlib.sha256(prompt.encode()).hexdigest()}" cached = await self.redis.get(exact_key) if cached: return json.loads(cached.decode()) # Semantic similarity search for near-duplicates similar_keys = await self._find_similar_prompts(prompt, tolerance) for key in similar_keys[:3]: # Check top 3 similar prompts cached_response = await self.redis.get(key) if cached_response: return { 'response': json.loads(cached_response.decode()), 'cache_hit_type': 'semantic_similarity', 'similarity_score': float(similar_keys[key]) } return None async def _find_similar_prompts(self, prompt: str, tolerance: float) -> Dict[str, float]: """Use Redis vector search for semantic similarity""" # In production, use Redis Stack with RedisAI or external embedding service # This is a simplified placeholder return {} async def cache_response( self, prompt: str, response: Dict, model_id: str, ttl: int = 3600 ): """Store response with metadata""" key = f"{self.cache_key_prefix}{model_id}:{hashlib.sha256(prompt.encode()).hexdigest()}" cache_data = { 'response': response, 'prompt_hash': hashlib.sha256(prompt.encode()).hexdigest(), 'timestamp': time.time(), 'ttl_remaining': ttl, 'hit_count': 0 } await self.redis.setex(key, ttl, json.dumps(cache_data)) ``` ### Pattern 3: Circuit Breaker with Progressive Fallback Ladder **Architecture Overview** Progressive fallback ensures graceful degradation when primary endpoints fail. The system attempts requests across multiple tiers, each with increasing latency tolerance and decreasing quality expectations. ```python import asyncio from collections import defaultdict from datetime import datetime, timedelta class AdaptiveCircuitBreaker: def __init__( self, failure_threshold: int = 5, success_threshold: int = 3, timeout_seconds: int = 60, half_open_requests: int = 2 ): self.failure_threshold = failure_threshold self.success_threshold = success_threshold self.timeout_seconds = timeout_seconds self.half_open_requests = half_open_requests # State tracking per endpoint self.state: Dict[str, str] = defaultdict(lambda: "CLOSED") # CLOSED, OPEN, HALF_OPEN self.failure_count: Dict[str, int] = defaultdict(int) self.last_failure_time: Dict[str, datetime] = {} def is_available(self, endpoint_id: str) -> bool: """Check if endpoint can accept traffic""" current_state = self.state[endpoint_id] if current_state == "CLOSED": return True elif current_state == "OPEN": # Check if timeout has elapsed last_failure = self.last_failure_time.get(endpoint_id) if last_failure and (datetime.now() - last_failure).seconds > self.timeout_seconds: self._transition_to_half_open(endpoint_id) return True return False else: # HALF_OPEN return True def record_success(self, endpoint_id: str): """Record successful request""" if self.state[endpoint_id] == "HALF_OPEN": self.failure_count[endpoint_id] = max(0, self.failure_count[endpoint_id] - 1) if self.failure_count[endpoint_id] <= (self.failure_threshold - self.success_threshold): self._transition_to_closed(endpoint_id) def record_failure(self, endpoint_id: str): """Record failed request""" self.failure_count[endpoint_id] += 1 self.last_failure_time[endpoint_id] = datetime.now() if self.state[endpoint_id] == "HALF_OPEN": self._transition_to_open(endpoint_id) elif self.failure_count[endpoint_id] >= self.failure_threshold: self._transition_to_open(endpoint_id) def _transition_to_open(self, endpoint_id: str): self.state[endpoint_id] = "OPEN" logging.warning(f"Circuit breaker OPEN for {endpoint_id}") def _transition_to_half_open(self, endpoint_id: str): self.state[endpoint_id] = "HALF_OPEN" logging.info(f"Circuit breaker HALF_OPEN for {endpoint_id}, testing with limited traffic") def _transition_to_closed(self, endpoint_id: str): self.failure_count[endpoint_id] = 0 self.state[endpoint_id] = "CLOSED" logging.info(f"Circuit breaker CLOSED for {endpoint_id}") class ProgressiveFallbackLadder: """Multi-tier fallback strategy""" def __init__(self, orchestrator: MultiCloudLLMOrchestrator): self.orchestrator = orchestrator self.circuit_breaker = AdaptiveCircuitBreaker() # Define fallback tiers with priority and cost considerations self.fallback_tiers = [ { 'tier': 1, 'name': 'Primary High-Performance', 'providers': ['aws', 'azure'], 'models': ['anthropic.claude-3-5-sonnet', 'gpt-4o'], 'max_latency_ms': 2000, }, { 'tier': 2, 'name': 'Cost-Optimized Secondary', 'providers': ['aws', 'gcp'], 'models': ['anthropic.claude-3-haiku', 'gemini-1.5-flash'], 'max_latency_ms': 4000, }, { 'tier': 3, 'name': 'Fallback Budget Tier', 'providers': ['all'], 'models': ['mistral-small', 'llama3-8b-instruct'], 'max_latency_ms': 8000, } ] async def execute_with_fallback( self, prompt: str, required_capabilities: List[str] = None ) -> Dict: """Execute request through progressive fallback ladder""" errors = [] for tier_config in self.fallback_tiers: # Filter models by capabilities if specified available_models = tier_config['models'] # Try each model in tier for model_id in available_models: endpoint_key = f"tier{tier_config['tier']}:{model_id}" if not self.circuit_breaker.is_available(endpoint_key): continue try: response = await asyncio.wait_for( self._execute_single_attempt(prompt, model_id), timeout=tier_config['max_latency_ms'] / 1000 ) self.circuit_breaker.record_success(endpoint_key) return { 'response': response, 'tier_used': tier_config['tier'], 'model_used': model_id, 'fallback_depth': 0 if tier_config['tier'] == 1 else tier_config['tier'] - 1 } except asyncio.TimeoutError as e: errors.append(f"Tier {tier_config['tier']} timeout for {model_id}") self.circuit_breaker.record_failure(endpoint_key) continue except Exception as e: errors.append(f"Tier {tier_config['tier']} error for {model_id}: {str(e)}") self.circuit_breaker.record_failure(endpoint_key) continue raise RuntimeError( f"All fallback tiers exhausted. Errors: {'; '.join(errors)}" ) Pattern 4: Cross-Cloud Load Balancing with Dynamic Weighting **Architecture Overview** ``` ┌─────────────────────────────────────────────────────────────────┐ │ DYNAMIC LOAD BALANCER │ │ │ │ ┌─────────────┬─────────────┬─────────────┬───────────────┐ │ │ │ AWS │ Azure │ GCP │ Others │ │ │ │ Bedrock │ OpenAI │ Vertex AI │ │ │ │ │ │ │ │ │ │ │ │ Weight: 40% │ Weight: 35% │ Weight: 20% │ Weight: 5% │ │ │ │ Health: 98% │ Health: 99% │ Health: 95% │ Health: 97% │ │ │ │ Latency: 45ms│Latency: 52ms│Latency: 60ms│Latency: 120ms│ │ │ └─────────────┴─────────────┴─────────────┴───────────────┘ │ │ │ │ ┌───────────────────────────────────────────────────────────┐ │ │ │ ADAPTIVE WEIGHTING ENGINE │ │ │ │ • Real-time latency monitoring │ │ │ │ • Cost per token tracking │ │ │ │ • Error rate calculation │ │ │ │ • Predictive scaling │ │ │ └───────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` **Implementation** ```python from dataclasses import dataclass, field import statistics from collections import deque import numpy as np @dataclass class ProviderMetrics: provider_id: str recent_latencies: deque = field(default_factory=lambda: deque(maxlen=100)) recent_costs: deque = field(default_factory=lambda: deque(maxlen=100)) recent_errors: deque = field(default_factory=lambda: deque(maxlen=100)) total_requests: int = 0 def update(self, latency_ms: float, cost_usd: float, success: bool): self.recent_latencies.append(latency_ms) self.recent_costs.append(cost_usd) self.recent_errors.append(1 if not success else 0) self.total_requests += 1 def get_average_latency(self) -> float: return statistics.mean(self.recent_latencies) if self.recent_latencies else 500.0 def get_error_rate(self) -> float: if not self.recent_errors: return 0.0 return sum(self.recent_errors[-10:]) / min(10, len(self.recent_errors)) def get_cost_per_1k_tokens(self, tokens: int) -> float: if tokens == 0 or not self.recent_costs: return 0.0 recent_cost = sum(self.recent_costs[-10:]) recent_tokens = max(1, tokens * min(10, len(self.recent_costs))) return (recent_cost / recent_tokens) * 1000 class AdaptiveLoadBalancer: def __init__(self): self.provider_metrics: Dict[str, ProviderMetrics] = {} self.base_weights: Dict[str, float] = { 'aws': 0.40, 'azure': 0.35, 'gcp': 0.20, 'others': 0.05 } def record_request( self, provider_id: str, latency_ms: float, cost_usd: float, tokens: int, success: bool ): if provider_id not in self.provider_metrics: self.provider_metrics[provider_id] = ProviderMetrics(provider_id) self.provider_metrics[provider_id].update(latency_ms, cost_usd, success) def calculate_adaptive_weights(self) -> Dict[str, float]: """Calculate weights based on real-time performance metrics""" scores: Dict[str, float] = {} for provider_id, metrics in self.provider_metrics.items(): # Calculate composite score (higher is better) # Latency score (inverse relationship, normalized to 0-100) avg_latency = metrics.get_average_latency() latency_score = max(0, min(100, 150 - avg_latency)) # Error rate penalty (convert error rate to score) error_rate = metrics.get_error_rate() reliability_score = max(0, 100 - (error_rate * 200)) # Cost efficiency score cost_per_1k = metrics.get_cost_per_1k_tokens(1000) base_cost = 5.0 # Reference cost per 1K tokens in cents cost_score = max(0, min(100, (base_cost / max(cost_per_1k, 0.01)) * 100)) # Weighted composite score weights = { 'latency': 0.35, 'reliability': 0.40, 'cost': 0.25 } total_score = ( weights['latency'] * latency_score + weights['reliability'] * reliability_score + weights['cost'] * cost_score ) # Apply base weight as multiplier base_weight = self.base_weights.get(provider_id, 0.1) scores[provider_id] = total_score * base_weight # Normalize to sum of 1.0 total = max(sum(scores.values()), 0.001) normalized_weights = {k: v / total for k, v in scores.items()} return normalized_weights def select_provider(self, request_context: Dict = None) -> str: """Weighted random selection with context awareness""" weights = self.calculate_adaptive_weights() # Sort providers by weight sorted_providers = sorted(weights.keys(), key=lambda k: weights[k], reverse=True) # Use weighted selection (can add request-specific adjustments here) import random return np.random.choice(sorted_providers, p=[weights[p] for p in sorted_providers]) ``` --- ## 2. Cross-Cloud Communication Patterns ### Pattern 5: Request Chaining Across Providers **Use Case:** Using one provider's strengths for specific tasks while orchestrating across multiple providers. ```python class CrossCloudRequestChainer: """Orchestrates multi-step workflows across different cloud providers""" def __init__(self, orchestrator: MultiCloudLLMOrchestrator): self.orchestrator = orchestrator async def execute_chained_workflow( self, workflow_config: Dict, input_data: str ) -> Dict: """Execute a multi-step workflow with provider-specific optimizations""" results = {} intermediate_outputs = {'input': input_data} for step_idx, step in enumerate(workflow_config['steps']): # Determine optimal provider for this step type provider_selector = self._select_provider_for_step(step) try: # Construct prompt with context from previous steps contextualized_prompt = await self._build_contextualized_prompt( step, intermediate_outputs, workflow_config.get('context_window', {}) ) # Execute step with provider-specific parameters step_result = await self.orchestrator.route_request( prompt=contextualized_prompt, strategy=provider_selector.strategy, context={'step_id': step_idx} ) results[f'step_{step_idx}'] = { 'output': step_result.get('content'), 'provider': provider_selector.provider, 'model': step.get('preferred_model'), 'latency_ms': step_result.get('usage', {}).get('total_time_ms', 0) } # Store for next step context output_key = step.get('output_variable', f'step_{step_idx}_output') intermediate_outputs[output_key] = step_result.get('content') except Exception as e: logging.error(f"Step {step_idx} failed: {e}") if workflow_config.get('fail_fast'): raise continue # Final aggregation step if configured aggregator = workflow_config.get('aggregator') if aggregator: final_result = await self._execute_aggregation( aggregator, results, intermediate_outputs ) return {'final_output': final_result, 'steps_executed': len(results)} return { 'step_results': list(results.values()), 'intermediate_outputs': intermediate_outputs, 'total_steps': len(workflow_config['steps']) } Pattern 6: Distributed Context Window Management **Challenge:** Managing context windows across multiple model calls when total content exceeds single-model limits. ```python from typing import List, Optional import math class DistributedContextManager: """Manages distributed context processing across models with varying window sizes""" def __init__(self): # Model capabilities database self.model_capabilities = { 'claude-3-5-sonnet': {'max_tokens': 200000, 'optimal_chunk_size': 180000}, 'gpt-4o': {'max_tokens': 128000, 'optimal_chunk_size': 115000}, 'gemini-1.5-pro': {'max_tokens': 2000000, 'optimal_chunk_size': 1800000}, 'mistral-large': {'max_tokens': 128000, 'optimal_chunk_size': 115000}, } async def process_large_context( self, content: str, system_prompt: str, orchestrator: MultiCloudLLMOrchestrator, strategy: str = 'smart_distribution' ) -> Dict: """Process large documents by intelligently distributing across models""" total_tokens = len(content) // 4 # Rough token estimation if strategy == 'single_model': return await self._find_largest_window_and_process( content, system_prompt, orchestrator ) elif strategy == 'smart_distribution': return await self._intelligent_chunking_strategy( content, system_prompt, total_tokens, orchestrator ) async def _intelligent_chunking_strategy( self, content: str, system_prompt: str, total_tokens: int, orchestrator: MultiCloudLLMOrchestrator ) -> Dict: """Intelligently distribute large context processing""" # Check if single model can handle it available_models = [m for m in self.model_capabilities.values()] max_capacity = max(m['max_tokens'] for m in available_models) if total_tokens < max_capacity * 0.9: # Use largest window model, but stay within optimal range return await self._find_largest_window_and_process( content, system_prompt, orchestrator ) # Need chunking - determine strategy based on content type num_chunks = math.ceil(total_tokens / 180000) # Target ~180K per chunk chunks = self._create_overlapping_chunks( content, target_size=180000 * 4, # Convert tokens to chars approx overlap_size=5000 * 4 # 5K token overlap for context continuity ) results = [] chunk_metadata = [] for i, chunk in enumerate(chunks): result = await orchestrator.route_request( prompt=f""" <system>{system_prompt}</system> This is part {i+1} of {len(chunks)} chunks. {'Previous context summarized here' if i > 0 else 'First chunk.'} Content: {chunk[:5000]}...[truncated for display] Provide analysis focusing on this section, noting any connections to broader themes. """, strategy=RoutingStrategy.COST_OPTIMIZED ) results.append(result) chunk_metadata.append({ 'chunk_id': i, 'start_pos': ..., # Calculate actual positions 'end_pos': ..., 'token_count': len(chunk) // 4 }) # Aggregate results with a summary pass aggregated_summary = await self._aggregate_chunk_results( chunk_metadata, results, system_prompt, orchestrator ) return { 'aggregated_output': aggregated_summary, 'chunk_count': len(chunks), 'processing_strategy': 'distributed_with_overlap', 'metadata': chunk_metadata } --- ## 3. Cost Optimization Strategies ### Strategy 1: Real-Time Provider Selection Based on Token Economics ```python class TokenEconomicsOptimizer: """Optimizes cost through intelligent provider/model selection""" def __init__(self): self.price_database = { # Format: (input_price_per_1k, output_price_per_1k) in USD 'aws:anthropic.claude-3-5-sonnet': (0.03, 0.15), 'aws:anthropic.claude-3-haiku': (0.0025, 0.0125), 'azure:gpt-4o': (0.005, 0.015), 'azure:gpt-4o-mini': (0.0015, 0.006), 'gcp:gemini-1.5-pro': (0.0035, 0.0105), 'gcp:gemini-1.5-flash': (0.00075, 0.0015), } def calculate_optimal_configuration( self, estimated_input_tokens: int, estimated_output_tokens: int, latency_requirement_ms: int = None, quality_tier: str = 'balanced' # budget, balanced, premium ) -> Dict: """Find most cost-effective configuration meeting requirements""" candidates = [] for provider_model, prices in self.price_database.items(): input_price, output_price = prices total_cost = ( (estimated_input_tokens / 1000) * input_price + (estimated_output_tokens / 1000) * output_price ) # Apply quality tier filters if quality_tier == 'budget': if 'sonnet' in provider_model or '-4o' in provider_model: continue elif quality_tier == 'premium': if 'mini' in provider_model or 'flash' in provider_model or 'haiku' in provider_model: continue candidates.append({ 'provider_model': provider_model, 'total_cost_usd': total_cost, 'input_tokens': estimated_input_tokens, 'output_tokens': estimated_output_tokens }) # Sort by cost and return best option candidates.sort(key=lambda x: x['total_cost_usd']) if not candidates: raise ValueError("No configuration meets requirements") return { **candidates[0], 'cost_savings_vs_premium': self._calculate_savings(candidates), 'recommendation_reasoning': self._generate_recommendation_reasoning(candidates[0]) } ### Strategy 2: Predictive Caching Based on Query Patterns ```python class PredictiveCacheWarmer: """Pre-caches responses for predictable query patterns""" def __init__(self): self.pattern_database = [] # Learned patterns self.cache_hit_history = defaultdict(list) async def learn_query_pattern(self, prompt_template: str, metadata: Dict): """Learn recurring query patterns from traffic analysis""" pattern_hash = hashlib.sha256(prompt_template.encode()).hexdigest()[:16] existing_pattern = next( (p for p in self.pattern_database if p['hash'] == pattern_hash), None ) if existing_pattern: existing_pattern['frequency'] += 1 existing_pattern['last_seen'] = datetime.now() else: self.pattern_database.append({ 'hash': pattern_hash, 'template': prompt_template[:500], 'frequency': 1, 'first_seen': datetime.now(), 'last_seen': datetime.now(), 'avg_tokens': metadata.get('token_count', 100) }) async def generate_warming_schedule(self) -> List[Dict]: """Generate cache warming schedule based on learned patterns""" # Sort by frequency and recency prioritized_patterns = sorted( self.pattern_database, key=lambda p: (p['frequency'] * 1000 - days_since_last_seen), reverse=True ) # Generate warming tasks for top patterns warming_tasks = [] for pattern in prioritized_patterns[:50]: # Top 50 patterns if pattern['frequency'] > 5: # Only warm frequently used patterns warming_tasks.append({ 'pattern_hash': pattern['hash'], 'priority': 'HIGH' if pattern['frequency'] > 50 else 'MEDIUM', 'estimated_tokens': pattern['avg_tokens'], 'last_accessed': pattern['last_seen'].isoformat() }) return warming_tasks --- ## 4. Resilience and Fault Tolerance Patterns ### Pattern: Multi-Level Retry with Exponential Backoff and Provider Switching ```python class IntelligentRetryManager: """Advanced retry logic with provider switching on repeated failures""" def __init__(self): self.max_retries = 3 self.base_delay_seconds = 1.0 self.max_delay_seconds = 60.0 self.provider_failures: Dict[str, int] = defaultdict(int) async def execute_with_smart_retry( self, request_func: Callable, context: Dict ) -> Any: """Execute with exponential backoff and intelligent provider switching""" attempt = 0 last_exception = None while attempt < self.max_retries: try: # Check if we should switch provider current_provider = context.get('provider') if current_provider and self.provider_failures[current_provider] >= 2: new_provider = await self._select_alternative_provider(current_provider) context['provider'] = new_provider logging.info(f"Switching from {current_provider} to {new_provider}") result = await request_func(context) # Clear failure count on success if current_provider: self.provider_failures[current_provider] = max(0, self.provider_failures[current_provider] - 1) return {'success': True, 'result': result} except Exception as e: last_exception = e if context.get('provider'): self.provider_failures[context['provider']] += 1 attempt += 1 if attempt < self.max_retries: # Calculate exponential backoff with jitter delay = min( self.base_delay_seconds * (2 ** (attempt - 1)) + random.uniform(0, 1), self.max_delay_seconds ) logging.warning(f"Retry {attempt}/{self.max_retries} in {delay:.2f}s") await asyncio.sleep(delay) return {'success': False, 'error': str(last_exception)} ### Pattern: Health Check Orchestration Across Clouds ```python class CrossCloudHealthMonitor: """Distributed health monitoring for all provider endpoints""" def __init__(self): self.health_cache: Dict[str, Dict] = {} self.cache_ttl_seconds = 30 async def execute_health_check(self, endpoint_config: Dict) -> Dict: """Execute comprehensive health check""" checks = { 'endpoint_reachable': False, 'api_responsive': False, 'latency_acceptable': False, 'rate_limit_available': True, 'model_available': False, } try: # 1. Basic connectivity check start_time = time.time() # Provider-specific health endpoints if endpoint_config['provider'] == 'aws':
?
AI

Did this help? Spendplane AI continuously learns from search interactions to refine the Engineering Manual.

Spendplane Meta-Docs / Trace ID: multi-cloud-llm-orchestration-patterns-and-best-practices-en