|
| 1 | +""" |
| 2 | +Provider factory with automatic fallback. |
| 3 | +
|
| 4 | +Resolution order: |
| 5 | + 1. CUA_PROVIDER env var (required) |
| 6 | + 2. CUA_FALLBACK_PROVIDERS env var (optional, comma-separated) |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import os |
| 12 | +from dataclasses import dataclass |
| 13 | +from typing import Protocol |
| 14 | + |
| 15 | +from kernel import Kernel |
| 16 | + |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class TaskOptions: |
| 20 | + query: str |
| 21 | + kernel: Kernel |
| 22 | + session_id: str |
| 23 | + viewport_width: int = 1280 |
| 24 | + viewport_height: int = 800 |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class TaskResult: |
| 29 | + result: str |
| 30 | + provider: str |
| 31 | + |
| 32 | + |
| 33 | +class CuaProvider(Protocol): |
| 34 | + @property |
| 35 | + def name(self) -> str: ... |
| 36 | + def is_configured(self) -> bool: ... |
| 37 | + async def run_task(self, options: TaskOptions) -> TaskResult: ... |
| 38 | + |
| 39 | + |
| 40 | +def _build_provider(name: str) -> CuaProvider | None: |
| 41 | + if name == "anthropic": |
| 42 | + from .anthropic import AnthropicProvider |
| 43 | + return AnthropicProvider() |
| 44 | + if name == "openai": |
| 45 | + from .openai import OpenAIProvider |
| 46 | + return OpenAIProvider() |
| 47 | + if name == "gemini": |
| 48 | + from .gemini import GeminiProvider |
| 49 | + return GeminiProvider() |
| 50 | + return None |
| 51 | + |
| 52 | + |
| 53 | +def resolve_providers() -> list[CuaProvider]: |
| 54 | + """Build the ordered list of providers to try.""" |
| 55 | + primary = os.environ.get("CUA_PROVIDER", "").strip().lower() |
| 56 | + fallbacks = [ |
| 57 | + s.strip().lower() |
| 58 | + for s in os.environ.get("CUA_FALLBACK_PROVIDERS", "").split(",") |
| 59 | + if s.strip() |
| 60 | + ] |
| 61 | + |
| 62 | + order = ([primary] if primary else []) + fallbacks |
| 63 | + |
| 64 | + seen: set[str] = set() |
| 65 | + providers: list[CuaProvider] = [] |
| 66 | + |
| 67 | + for name in order: |
| 68 | + if name in seen: |
| 69 | + continue |
| 70 | + seen.add(name) |
| 71 | + |
| 72 | + provider = _build_provider(name) |
| 73 | + if provider is None: |
| 74 | + print(f'Warning: Unknown provider "{name}", skipping.') |
| 75 | + continue |
| 76 | + if not provider.is_configured(): |
| 77 | + print(f'Warning: Provider "{name}" missing API key, skipping.') |
| 78 | + continue |
| 79 | + providers.append(provider) |
| 80 | + |
| 81 | + if not providers: |
| 82 | + raise RuntimeError( |
| 83 | + "No CUA provider is configured. " |
| 84 | + "Set CUA_PROVIDER to one of: anthropic, openai, gemini, " |
| 85 | + "and provide the matching API key." |
| 86 | + ) |
| 87 | + |
| 88 | + return providers |
| 89 | + |
| 90 | + |
| 91 | +async def run_with_fallback( |
| 92 | + providers: list[CuaProvider], |
| 93 | + options: TaskOptions, |
| 94 | +) -> TaskResult: |
| 95 | + """Run a CUA task, trying each provider in order until one succeeds.""" |
| 96 | + errors: list[tuple[str, Exception]] = [] |
| 97 | + |
| 98 | + for provider in providers: |
| 99 | + try: |
| 100 | + print(f"Attempting provider: {provider.name}") |
| 101 | + return await provider.run_task(options) |
| 102 | + except Exception as exc: |
| 103 | + print(f'Provider "{provider.name}" failed: {exc}') |
| 104 | + errors.append((provider.name, exc)) |
| 105 | + |
| 106 | + summary = "\n".join(f" {name}: {exc}" for name, exc in errors) |
| 107 | + raise RuntimeError(f"All providers failed:\n{summary}") |
0 commit comments