Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /als-apg_osprey /src /osprey /models /providers /base.py
| """Base Provider Interface for AI Model Access.""" | |
| import os | |
| from abc import ABC, abstractmethod | |
| from typing import Any | |
| class BaseProvider(ABC): | |
| """Abstract base class for AI model providers. | |
| All provider implementations must inherit from this class and implement | |
| the two core methods: execute_completion and check_health. | |
| **Metadata as Class Attributes** (SINGLE SOURCE OF TRUTH): | |
| Subclasses define provider metadata as class attributes. The registry | |
| introspects these attributes after loading the class, avoiding duplication | |
| between ProviderRegistration and the class itself. This follows the same | |
| pattern as capabilities and context classes in the framework. | |
| Metadata Attributes (define on subclass): | |
| name: Provider identifier (e.g., "anthropic", "openai") | |
| description: User-friendly description (e.g., "Anthropic (Claude models)") | |
| requires_api_key: Whether provider requires API key for authentication | |
| requires_base_url: Whether provider requires custom base URL | |
| requires_model_id: Whether provider requires model ID specification | |
| supports_proxy: Whether provider supports HTTP proxy configuration | |
| default_base_url: Default API endpoint URL if applicable | |
| base_url_env_var: Name of an env var that, when set, overrides every | |
| other base_url source (explicit argument, config, default) for this | |
| provider — the runtime lever for redirecting an already-deployed | |
| system at a different gateway without a rebuild. None disables the | |
| override (the default; providers opt in explicitly so the name | |
| never collides with an env var another layer owns, e.g. | |
| ANTHROPIC_BASE_URL). | |
| default_model_id: Default model recommended for general use (used in templates) | |
| health_check_model_id: Cheapest/fastest model for health checks | |
| available_models: List of available model IDs for this provider | |
| api_key_url: URL where users can obtain an API key (e.g., "https://console.anthropic.com/") | |
| api_key_instructions: Step-by-step instructions for obtaining an API key | |
| api_key_note: Additional notes or requirements (e.g., "Requires affiliation") | |
| LiteLLM Integration Attributes: | |
| litellm_prefix: LiteLLM provider prefix (e.g., "anthropic", "gemini"). If None, | |
| uses the provider name. Set to empty string "" if no prefix needed. | |
| is_openai_compatible: True if this provider uses an OpenAI-compatible API | |
| endpoint with custom base_url (e.g., CBORG, Stanford, ARGO, vLLM). | |
| When True, LiteLLM routes via "openai/{model}" with api_base parameter. | |
| supports_native_structured_output: True=native json_schema, False=prompt fallback, None=auto-detect | |
| This interface ensures consistent provider behavior across the framework | |
| while allowing provider-specific implementations. | |
| """ | |
| # Metadata - subclasses MUST override these class attributes | |
| name: str = NotImplemented # Provider identifier (e.g., "anthropic") | |
| description: str = ( | |
| NotImplemented # User-friendly description (e.g., "Anthropic (Claude models)") | |
| ) | |
| requires_api_key: bool = NotImplemented | |
| requires_base_url: bool = NotImplemented | |
| requires_model_id: bool = NotImplemented | |
| supports_proxy: bool = NotImplemented | |
| default_base_url: str | None = None | |
| base_url_env_var: str | None = None # Env var overriding all base_url sources (opt-in) | |
| # Whether a missing base_url resolves to default_base_url. Opt-in: for most | |
| # providers litellm derives the endpoint from the model prefix, and forcing a | |
| # default would redirect them. A provider turns this on when a config that | |
| # omits base_url means "the default I declare" — openai-compatible routes | |
| # (which would otherwise fall through to api.openai.com) and local servers on | |
| # a well-known port. Declaring a default_base_url without this flag makes that | |
| # default unreachable through get_chat_completion, which rejects the call for a | |
| # missing base_url before any adapter body runs. | |
| apply_default_base_url_fallback: bool = False | |
| default_model_id: str | None = None # Default model for templates/general use | |
| health_check_model_id: str | None = None # Cheapest model for health checks | |
| available_models: list[str] = [] # List of available models for this provider | |
| # API key acquisition information (for CLI help and documentation) | |
| api_key_url: str | None = None # URL where users can obtain an API key | |
| api_key_instructions: list[str] = [] # Step-by-step instructions for obtaining the key | |
| api_key_note: str | None = None # Additional notes or requirements | |
| # LiteLLM integration configuration | |
| # These attributes allow providers to declare their LiteLLM routing behavior, | |
| # eliminating hardcoded provider checks in the adapter layer. | |
| litellm_prefix: str | None = None # LiteLLM prefix (e.g., "anthropic", "gemini") | |
| is_openai_compatible: bool = False # True for OpenAI-compatible endpoints (CBORG, etc.) | |
| # The gateway kind fronting this provider, when it is a proxy rather than a | |
| # model vendor. "litellm" makes every request carry the acting identity for | |
| # spend attribution (see models/spend_attribution.py); None sends nothing. | |
| gateway: str | None = None | |
| # Structured output routing: | |
| # True -> send response_format json_schema (native constrained decoding) | |
| # False -> use OSPREY's prompt-based JSON fallback | |
| # None -> defer to litellm.supports_response_schema() (auto-detect) | |
| supports_native_structured_output: bool | None = None | |
| def effective_base_url(cls, base_url: str | None) -> str | None: | |
| """Resolve the base_url actually used: env override > caller value > default. | |
| Lives on the base class because two callers must agree on the answer: the | |
| adapter that finally calls the endpoint, and whatever validates | |
| :attr:`requires_base_url` before it. When only the adapter knew this rule, | |
| a provider carrying a perfectly good :attr:`default_base_url` still failed | |
| validation for "missing" base_url, and the default it declared was | |
| unreachable — visible only once the env override was removed. | |
| Args: | |
| base_url: The caller's value, usually from deployment config. May be | |
| ``None``. | |
| Returns: | |
| The URL this provider will use, or ``None`` when it has no source for | |
| one — which is the only case a ``requires_base_url`` provider should | |
| be rejected for. | |
| """ | |
| if cls.base_url_env_var: | |
| override = os.environ.get(cls.base_url_env_var) | |
| if override: | |
| return override | |
| if cls.apply_default_base_url_fallback: | |
| return base_url or cls.default_base_url | |
| return base_url | |
| def require_effective_base_url(cls, base_url: str | None) -> str: | |
| """Same resolution as :meth:`effective_base_url`, but never ``None``. | |
| For adapters that build a request URL in their own body: they need a | |
| ``str``, and the rule they must apply is the one | |
| :meth:`effective_base_url` implements. A local | |
| ``base_url or self.default_base_url`` looks equivalent and is not — it | |
| skips the env override, and it disagrees with the ``requires_base_url`` | |
| check in :mod:`osprey.models.completion`, which then rejects the call | |
| before the adapter body ever runs. | |
| Args: | |
| base_url: The caller's value, usually from deployment config. May be | |
| ``None``. | |
| Returns: | |
| The URL this provider will call. | |
| Raises: | |
| ValueError: When no source supplies one — the same condition | |
| :func:`osprey.models.completion.get_chat_completion` rejects, | |
| reported with the same wording. | |
| """ | |
| resolved = cls.effective_base_url(base_url) | |
| if not resolved: | |
| raise ValueError(f"Base URL required for {cls.name}") | |
| return resolved | |
| def execute_completion( | |
| self, | |
| message: str, | |
| model_id: str, | |
| api_key: str | None, | |
| base_url: str | None, | |
| max_tokens: int = 1024, | |
| temperature: float = 0.0, | |
| thinking: dict | None = None, | |
| system_prompt: str | None = None, | |
| output_format: Any | None = None, | |
| **kwargs, | |
| ) -> str | Any: | |
| """Execute a direct chat completion. | |
| :param message: User message to send | |
| :param model_id: Model identifier | |
| :param api_key: API authentication key | |
| :param base_url: Custom API endpoint URL | |
| :param max_tokens: Maximum tokens to generate | |
| :param temperature: Sampling temperature | |
| :param thinking: Extended thinking configuration (if supported) | |
| :param system_prompt: System prompt (if supported) | |
| :param output_format: Structured output format (Pydantic model or TypedDict) | |
| :param kwargs: Additional provider-specific arguments | |
| :return: Model response text or structured output | |
| """ | |
| pass | |
| def check_health( | |
| self, | |
| api_key: str | None, | |
| base_url: str | None, | |
| timeout: float = 5.0, | |
| model_id: str | None = None, | |
| ) -> tuple[bool, str]: | |
| """Test provider connectivity and authentication. | |
| Makes a minimal API call to verify the API key works. For paid providers, | |
| uses the cheapest available model with minimal tokens (~$0.0001 per check). | |
| :param api_key: API authentication key | |
| :param base_url: Custom API endpoint URL | |
| :param timeout: Request timeout in seconds | |
| :param model_id: Optional model ID to test with (uses cheapest if not provided) | |
| :return: (success, message) tuple | |
| """ | |
| pass | |
Xet Storage Details
- Size:
- 9.99 kB
- Xet hash:
- 90c6a158a9c04f7140edcfca8558b58a51ca1f2cbdc2fafcc0f47177bd393dfb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.