Source code for smarter.apps.provider.management.commands.initialize_providers

"""Initialize 3rd party providers."""

from collections.abc import Callable
from http import HTTPStatus
from pathlib import Path
from typing import Optional
from urllib.parse import urljoin

import requests
from django.core.files.base import ContentFile
from django.utils import timezone

from smarter.apps.account.models import UserProfile
from smarter.apps.account.utils import smarter_cached_objects
from smarter.apps.provider.const import (
    BUILTIN_PROVIDER_API_KEY_SECRET_NAMES,
    GOOGLE_MAPS_API_KEY_SECRET_NAME,
    GOOGLE_SERVICE_ACCOUNT_SECRET_NAME,
)
from smarter.apps.provider.models import Provider, ProviderModel, ProviderStatus
from smarter.apps.secret.models import Secret
from smarter.common.conf import smarter_settings
from smarter.common.conf.env import is_missing_value
from smarter.common.helpers.console_helpers import SmarterFormattedText
from smarter.lib import json, logging
from smarter.lib.django.management.base import SmarterCommand
from smarter.lib.django.models.utils import assign_changed_fields
from smarter.lib.typing import SmarterDictType

logger = logging.getSmarterLogger(__name__)

HERE = Path(__file__).resolve().parent

ANTHROPIC_VERSION = "2023-06-01"
"""The Anthropic API version that the models api requires, in its anthropic-version header."""


[docs] def bearer_auth_headers(api_key: str) -> dict[str, str]: """ The headers that authenticate to an OpenAI compatible models api. :param api_key: the provider's api key. :returns: an Authorization header with the key as a Bearer token. """ return {"Authorization": f"Bearer {api_key}"}
[docs] def anthropic_auth_headers(api_key: str) -> dict[str, str]: """ The headers that authenticate to Anthropic's models api, which rejects a request without anthropic-version. :param api_key: the Anthropic api key. :returns: the x-api-key and anthropic-version headers. """ return {"x-api-key": api_key, "anthropic-version": ANTHROPIC_VERSION}
[docs] def googleai_auth_headers(api_key: str) -> dict[str, str]: """ The headers that authenticate to the Gemini api, which treats a Bearer token as an OAuth 2 token. :param api_key: the Gemini api key. :returns: the x-goog-api-key header. """ return {"x-goog-api-key": api_key}
[docs] class Command(SmarterCommand): """ Django manage.py initialize_providers.py command. Used to create/update the principal Providers that are preloaded on all platforms. Creates/updates the API key Secret, the Provider, and the ProviderModels for each provider. The following providers are initialized: - Anthropic - Cohere - Fireworks - Google Service Account - Google AI - Google Maps - Meta AI - Mistral - OpenAI - TogetherIA This is called indirectly by initialize_platform and runs during automated deployment. """ user_profile: UserProfile missing_api_keys: list[tuple[str, str, str]] """The API keys that are not set: their environment variable, what they are used for, and where to get one."""
[docs] def initialize_google_service_account(self): """ Initialize Google service account credentials. A Google service account is a special identity that allows an application, rather than a person, to securely authenticate with Google APIs and services. It uses cryptographic credentials to prove its identity and obtain temporary access tokens without requiring a user to log in. The service account can only perform the actions that have been explicitly granted to it through Google Cloud IAM permissions. Example service account JSON structure:: service_account_json = { "type": "service_account", "project_id": "smarter-sh", "private_key_id": "65fc3e5bd38b1234567890676f6d6abcdefghijk", "private_key": "PRIVATE-KEY-DATA", "client_email": "smarter-gemini-initializer@smarter-sh.iam.gserviceaccount.com", "client_id": "104887368144732193269", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/smarter-gemini-initializer%40smarter-sh.iam.gserviceaccount.com", "universe_domain": "googleapis.com" } service_account_b64 = base64.b64encode(json.dumps(service_account_json).encode("utf-8")).decode("ascii") print(service_account_b64) """ # the Secret holds the service account's json, which initialize_bootstrap_secrets creates (issue #1099). secret, value = self.admin_secret(GOOGLE_SERVICE_ACCOUNT_SECRET_NAME) if secret is None: self.missing_api_key( GOOGLE_SERVICE_ACCOUNT_SECRET_NAME, "Google service account credentials, for Google Cloud bearer tokens: the service account's json", "https://console.cloud.google.com/iam-admin/serviceaccounts", ) return try: # parsed only to validate it: get_google_service_account_bearer_token() parses it when it is used. json.loads(str(value)) except json.JSONDecodeError as e: logger.error("The Secret %s is not a service account's json: %s", GOOGLE_SERVICE_ACCOUNT_SECRET_NAME, e) logger.error( "See https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts?supportedpurview=project" )
[docs] def admin_secret(self, name: str) -> tuple[Optional[Secret], Optional[str]]: """ Return the Smarter admin's Secret of a name, and its value, if it exists and isn't empty. :param name: The Secret's name, e.g. ``openai_api_key``. :returns: The Secret and its value, or (None, None). """ secret = Secret.objects.filter(name=name, user_profile=self.user_profile).first() if secret is None: return None, None value = secret.get_secret(update_last_accessed=False) if value is None or is_missing_value(value): return None, None return secret, value
[docs] def initialize_generic_provider( self, api_key_secret_name: str, name: str, provider_configuration: SmarterDictType, logo_filename: str, provider_api_url: str, auth_headers: Callable[[str], dict[str, str]] = bearer_auth_headers, models_params: Optional[dict[str, str]] = None, ): """ Initialize a provider and its models. - create/update api key secret - create/update provider - create/update provider models :param auth_headers: returns the headers that authenticate to the provider's models api, given its key. :param models_params: query parameters for the models api, e.g. a page size. """ def _initialize_provider_models(provider: Provider, bearer_token: str, default_model: str): """ Initialize models by fetching them from the provider's models api end point. OpenAI compatible apis, and Anthropic's, list models in ``data``, with an ``id``. The Gemini api lists them in ``models``, with a ``name`` such as ``models/gemini-2.5-flash``. Example response:: { "object": "list", "data": [ { "id": "gpt-4-0613", "object": "model", "created": 1686588896, "owned_by": "openai" } ] } """ log_prefix = f"_initialize_provider_models({provider.name}):" end_point = "models" if not provider.base_url: self.stdout.write(self.style.ERROR(f"{log_prefix} Provider has no base url to fetch its models from.")) return url = urljoin(provider.base_url, end_point) headers = auth_headers(bearer_token) def _initialize_provider_model(provider: Provider, model_name: str, is_default: bool = False) -> bool: """Initialize a single provider model, and return whether it was saved.""" try: # a new model starts active, and its verification, which saving it queues, decides # whether it stays so. An existing model keeps the is_active its last verification set. defaults = {"description": f"{model_name} model for {provider.name}.", "is_default": is_default} # an unchanged model is not saved again: there are hundreds, and every deploy runs this. provider_model = ProviderModel.objects.filter(provider=provider, name=model_name).first() if provider_model is None: ProviderModel.objects.create(provider=provider, name=model_name, **defaults, is_active=True) elif assign_changed_fields(provider_model, defaults): provider_model.save() return True # pylint: disable=broad-except except Exception as e: self.stdout.write( self.style.ERROR(f"{log_prefix} Failed to initialize provider model {model_name}. Error: {e}") ) return False try: self.stdout.write(f"{log_prefix} Fetching provider models from {url}") response = requests.get(url, headers=headers, params=models_params, timeout=10) except requests.RequestException as e: logger.error( "failed to fetch the %s provider's models: %s", name, e, ) self.stdout.write(self.style.ERROR(f"{log_prefix} Failed to fetch provider models. Error: {e}")) return if response.status_code == HTTPStatus.NOT_FOUND: self.stdout.write( self.style.WARNING(f"{log_prefix} Provider models endpoint not found for this provider: {url}") ) return if response.status_code != HTTPStatus.OK: try: error_message = response.json().get("error", {}).get("message", response.text) # pylint: disable=broad-except except Exception: error_message = response.text # an error, not only command output: the command still succeeds, so without a logged ERROR an # expired key or a suspended account is easy to miss. logger.error( "failed to fetch the %s provider's models from %s: %s %s", name, url, response.status_code, error_message, ) self.stdout.write( self.style.ERROR( f"{log_prefix} Failed to fetch provider models. {url} Response {response.status_code}: {error_message}" ) ) return # some providers (e.g. Together AI) return a bare list rather than {"object": "list", "data": [...]} response_json = response.json() if isinstance(response_json, list): models = response_json else: models = response_json.get("data") if not models: models = response_json.get("models") if not models: models = [] if len(models) == 0: self.stdout.write(self.style.WARNING(f"{log_prefix} No provider models found.")) return self.stdout.write(f"{log_prefix} Found {len(models)} provider models.") initialized = 0 for model in models: model_name = model.get("id") or model.get("name", "").removeprefix("models/") if not model_name: continue # the Gemini api also lists models that cannot chat: embedding, video and question # answering models, and Live models that only stream over a WebSocket. Their # supportedGenerationMethods lack generateContent, which chat completions need. generation_methods = model.get("supportedGenerationMethods") if generation_methods is not None and "generateContent" not in generation_methods: self.stdout.write( f"{log_prefix} Skipping {model_name}, which does not support chat completions: {generation_methods}" ) continue if _initialize_provider_model( provider=provider, model_name=model_name, is_default=model_name == default_model ): initialized += 1 self.stdout.write( self.style.SUCCESS( f"{log_prefix} initialized {initialized} of the {len(models)} provider models successfully." ) ) self.echo_banner(name) logger.info("initializing the %s provider", name) if self.user_profile is None: self.stdout.write(self.style.ERROR(f"initialize_{name}: User profile is not set.")) return COMMON_DEFAULTS = { "user_profile": self.user_profile, "contact_email": smarter_settings.platform_email_admin, "support_email": smarter_settings.platform_branding_support_email, "tos_accepted_by": self.user_profile.user, } # a new built-in provider starts verified and active. An existing one keeps the status that its # last verification, or an admin who deprecated, flagged or suspended it, set: every deploy runs # this command, and must not re-enable a provider that failed verification. # when the emails were verified, and the terms accepted: when the provider was created. Setting # them on every deploy changed every provider's row on every deploy. CREATE_DEFAULTS = { "contact_email_verified": timezone.now(), "support_email_verified": timezone.now(), "tos_accepted_at": timezone.now(), "status": ProviderStatus.VERIFIED, "is_active": True, "is_verified": True, "is_deprecated": False, "is_flagged": False, "is_suspended": False, } # a missing key does not stop the provider from being created: the built-in LLMClients # and Proxies that use it must be applied. Its prompts fail, with instructions, until a key is set. # the key's only source is its Smarter Secret, which initialize_bootstrap_secrets creates (issue #1099). secret, api_key = self.admin_secret(api_key_secret_name) if secret is None: self.missing_api_key(api_key_secret_name, f"the {name} Provider", provider_api_url) try: defaults = { **COMMON_DEFAULTS, **provider_configuration, # without a key, an API key Secret that was set otherwise, e.g. in the web console, is kept. **({"api_key": secret} if secret else {}), # the platform-wide default provider, e.g. for prompts that do not name one "is_default": name == smarter_settings.llm_default_provider, } # an unchanged provider is not saved again: every deploy runs this command, and each save # sends post_save and invalidates the provider's caches. provider = Provider.objects.filter(name=name).first() if provider is None: provider = Provider.objects.create(name=name, **defaults, **CREATE_DEFAULTS) elif assign_changed_fields(provider, defaults): provider.save() # pylint: disable=broad-except except Exception as e: self.stdout.write(self.style.ERROR(f"initialize_{name}: Failed to create/update provider. Error: {e}")) return logo_path = HERE / "data" / "logos" / name / logo_filename with open(logo_path, "rb") as logo_file: logo = logo_file.read() if not self.has_logo(provider, logo): provider.logo.save(logo_filename, ContentFile(logo), save=True) if secret is None or api_key is None: # the models cannot be listed without a key, so only the default model is created. defaults = { "description": f"{provider_configuration['default_model']} model for {provider.name}.", "is_default": True, } ProviderModel.objects.update_or_create( provider=provider, name=provider_configuration["default_model"], defaults=defaults, create_defaults={**defaults, "is_active": True}, ) return _initialize_provider_models( provider=provider, bearer_token=api_key, default_model=provider_configuration["default_model"], )
[docs] def initialize_anthropic(self): """Initialize Anthropic provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["anthropic"] NAME = "anthropic" DEFAULT_MODEL = "claude-sonnet-4-6" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Anthropic provides advanced AI models and APIs.", "base_url": "https://api.anthropic.com/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "chat/completions", "website_url": "https://www.anthropic.com/", "terms_of_service_url": "https://privacy.claude.com/en/articles/9190861-terms-of-service-updates/", "privacy_policy_url": "https://privacy.claude.com/en/", "docs_url": "https://platform.claude.com/docs/en/api/overview", }, logo_filename="anthropic-logo.svg", provider_api_url="https://platform.claude.com/docs/en/api/overview", auth_headers=anthropic_auth_headers, # the models api returns 20 models per page by default. models_params={"limit": "1000"}, )
[docs] def initialize_cohere(self): """Initialize Cohere provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["cohere"] NAME = "cohere" DEFAULT_MODEL = "command-a-03-2025" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Cohere provides advanced AI models and APIs.", "base_url": "https://api.cohere.ai/compatibility/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "chat/completions", "website_url": "https://www.cohere.com/", "terms_of_service_url": "https://www.cohere.com/terms-of-service", "privacy_policy_url": "https://www.cohere.com/privacy", "docs_url": "https://platform.cohere.com/docs/en/api/overview", }, logo_filename="cohere-logo.svg", provider_api_url="https://platform.cohere.com/docs/en/api/overview", )
[docs] def initialize_fireworks(self): """Initialize Fireworks provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["fireworks"] NAME = "fireworks" DEFAULT_MODEL = "accounts/fireworks/models/gpt-oss-120b" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Fireworks provides advanced AI models and APIs.", "base_url": "https://api.fireworks.ai/inference/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "chat/completions", "website_url": "https://www.fireworks.ai/", "terms_of_service_url": "https://fireworks.ai/terms-of-service", "privacy_policy_url": "https://fireworks.ai/privacy-policy", "docs_url": "https://docs.fireworks.com/docs/en/api/overview", }, logo_filename="fireworks-logo.svg", provider_api_url="https://app.fireworks.ai/settings/users/api-keys", )
[docs] def initialize_googleai(self): """Initialize Google AI provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["googleai"] NAME = "googleai" DEFAULT_MODEL = "gemini-flash-latest" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Google AI provides a range of AI and machine learning services.", "base_url": "https://generativelanguage.googleapis.com/v1beta/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "prompt/completions", "website_url": "https://ai.google.com/", "terms_of_service_url": "https://cloud.google.com/terms/", "privacy_policy_url": "https://policies.google.com/privacy", "docs_url": "https://developers.generativeai.google/learn/api", }, logo_filename="google-ai.png", provider_api_url="https://aistudio.google.com/app/apikey", auth_headers=googleai_auth_headers, # the models api returns 50 models per page by default. models_params={"pageSize": "1000"}, )
[docs] def initialize_google_maps(self): """Report whether the Google Maps API key's Secret, which the weather extension uses, exists.""" secret, _ = self.admin_secret(GOOGLE_MAPS_API_KEY_SECRET_NAME) if secret is None: self.missing_api_key( GOOGLE_MAPS_API_KEY_SECRET_NAME, "the weather extension", "https://developers.google.com/maps/documentation/geocoding/get-api-key", )
[docs] def initialize_metaai(self): """Initialize Meta AI provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["metaai"] NAME = "metaai" DEFAULT_MODEL = "muse-spark-1.3-contributor" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Meta AI provides a range of AI and machine learning services.", "base_url": "https://api.meta.ai/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "responses", "website_url": "https://ai.meta.com/", "terms_of_service_url": "https://ai.meta.com/terms/", "privacy_policy_url": "https://ai.meta.com/privacy/", "docs_url": "https://ai.meta.com/docs/", }, logo_filename="Meta_lockup_mono_white_RGB.svg", provider_api_url="https://llama.developer.meta.com/", )
[docs] def initialize_mistral(self): """Initialize Mistral provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["mistral"] NAME = "mistral" DEFAULT_MODEL = "mistral-medium-latest" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "Mistral AI provides a range of AI and machine learning services.", "user_profile": self.user_profile, "base_url": "https://api.mistral.ai/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "conversations", "website_url": "https://mistral.ai/", "terms_of_service_url": "https://legal.mistral.ai/terms/", "privacy_policy_url": "https://legal.mistral.ai/terms/privacy-policy/", "docs_url": "https://docs.mistral.ai/", }, logo_filename="mistral-logo.svg", provider_api_url="https://admin.mistral.ai/organization/api-keys", )
[docs] def initialize_openai(self): """Initialize OpenAI provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["openai"] NAME = "openai" DEFAULT_MODEL = "gpt-6-luna" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "OpenAI provides advanced AI models and APIs.", "base_url": "https://api.openai.com/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "prompt/completions", "website_url": "https://www.openai.com/", "terms_of_service_url": "https://openai.com/policies/terms-of-use/", "privacy_policy_url": "https://openai.com/policies/privacy-policy/", "docs_url": "https://developers.openai.com/api/reference/overview", }, logo_filename="OpenAI-white-monoblossom.png", provider_api_url="https://platform.openai.com/api-keys", )
[docs] def initialize_togetheria(self): """Initialize TogetherAI provider and its models.""" API_KEY_SECRET_NAME = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES["togetherai"] NAME = "togetherai" DEFAULT_MODEL = "openai/gpt-oss-120b" self.initialize_generic_provider( api_key_secret_name=API_KEY_SECRET_NAME, name=NAME, provider_configuration={ "description": "TogetherAI provides advanced AI models and APIs.", "base_url": "https://api.together.xyz/v1/", "default_model": DEFAULT_MODEL, "connectivity_test_path": "chat/completions", "website_url": "https://www.together.ai/", "terms_of_service_url": "https://www.together.ai/terms-of-service/", "privacy_policy_url": "https://docs.together.ai/docs/privacy-and-security", "docs_url": "https://docs.together.ai/", }, logo_filename="together-logo.svg", provider_api_url="https://platform.together.ai/api-keys", )
[docs] def missing_api_key(self, secret_name: str, used_for: str, url: str): """ Record an API key whose Smarter Secret doesn't exist, for the summary that :meth:`handle` logs. :param secret_name: The Secret's name, e.g. ``openai_api_key``. :param used_for: What the key is used for. :param url: Where to get the key. """ self.missing_api_keys.append((secret_name, used_for, url)) self.stdout.write(self.style.WARNING(f"The Secret {secret_name} does not exist. It is used for {used_for}."))
[docs] def log_missing_api_keys(self): """Log one banner that lists the API keys that are not set, and how to set them.""" if not self.missing_api_keys: return lines = [ "The platform runs without them, but the features that use them fail, with an error, until they are set.", "", ] for secret_name, used_for, url in self.missing_api_keys: lines += [f" {secret_name}", f" for {used_for}", f" get one at {url}"] lines += [ "", "Each is a Smarter Secret of the Smarter admin's. Set it in the web console or with smarter apply, or add", "it to the platform's bootstrap secrets, from which the init Job creates it: the Helm chart's", "bootstrapSecrets, or, locally, a file of that name in bootstrap-secrets/ (make bootstrap-secrets).", ] logger.error( SmarterFormattedText.banner( f"[API KEYS NOT SET] {len(self.missing_api_keys)} API key Secrets do not exist:", *lines ) )
[docs] def echo_banner(self, name: str): """Echo a banner to the console.""" self.stdout.write(self.style.SUCCESS("-" * 40)) self.stdout.write(self.style.SUCCESS(f"Initializing {name} provider...")) self.stdout.write(self.style.SUCCESS("-" * 40))
[docs] def handle(self, *args, **options): """Initialize all built-in providers.""" self.handle_begin() self.missing_api_keys = [] try: self.user_profile = smarter_cached_objects.smarter_admin_user_profile self.initialize_anthropic() self.initialize_cohere() self.initialize_fireworks() self.initialize_google_service_account() self.initialize_googleai() self.initialize_google_maps() self.initialize_metaai() self.initialize_mistral() self.initialize_openai() self.initialize_togetheria() # pylint: disable=broad-except except Exception as exc: self.handle_completed_failure(msg=f"initialize_providers: Error initializing providers: {exc}") return self.log_missing_api_keys() self.handle_completed_success()