Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,38 +1,68 @@
from typing import cast
from typing_extensions import TypedDict

from core.app.app_config.entities import EasyUIBasedAppConfig
from core.app.entities.app_invoke_entities import ModelConfigWithCredentialsEntity
from core.entities.model_entities import ModelStatus
from core.entities.provider_configuration import bind_model_route
from core.entities.provider_configuration import ProviderModelBundle, bind_model_route
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from core.plugin.impl.model_runtime_factory import create_plugin_provider_manager
from graphon.model_runtime.entities.llm_entities import LLMMode
from graphon.model_runtime.entities.model_entities import ModelPropertyKey, ModelType
from graphon.model_runtime.model_providers.base.large_language_model import LargeLanguageModel


class ProviderCredentials(TypedDict):
"""The custom (BYOK) provider credentials the converter only checks for presence.

Production-owned shape: tests import this instead of re-declaring an ad hoc dict.
"""

api_key: str


class CompletionParameters(TypedDict, total=False, extra_items=object):
"""The completion parameters the converter splits into ``parameters`` and ``stop``.

``stop`` is peeled off into ``ModelConfigEntity.stop`` before the rest is forwarded to the
model runtime; provider-specific parameters pass through unchanged (``extra_items``).
Production-owned shape: tests import this instead of re-declaring an ad hoc dict.
"""

temperature: float
max_tokens: int
stop: list[str]


class ModelConfigConverter:
@classmethod
def convert(cls, app_config: EasyUIBasedAppConfig) -> ModelConfigWithCredentialsEntity:
def convert(
cls,
app_config: EasyUIBasedAppConfig,
*,
provider_model_bundle: ProviderModelBundle | None = None,
) -> ModelConfigWithCredentialsEntity:
"""
Convert app model config to an entity with credentials and status from the same model route.
:param app_config: app config
:param provider_model_bundle: already resolved provider model bundle; when omitted the bundle is
resolved from the tenant's provider configuration (the production path)
:raises ProviderTokenNotInitError: provider token not init error
:return: app orchestration config entity
"""
model_config = app_config.model

provider_manager = create_plugin_provider_manager(tenant_id=app_config.tenant_id)
provider_model_bundle = provider_manager.get_provider_model_bundle(
tenant_id=app_config.tenant_id, provider=model_config.provider, model_type=ModelType.LLM
)
if provider_model_bundle is None:
provider_manager = create_plugin_provider_manager(tenant_id=app_config.tenant_id)
provider_model_bundle = provider_manager.get_provider_model_bundle(
tenant_id=app_config.tenant_id, provider=model_config.provider, model_type=ModelType.LLM
)
provider_model_bundle = bind_model_route(provider_model_bundle, model_config.model)

provider_name = provider_model_bundle.configuration.provider.provider
model_name = model_config.model

# ``get_model_schema`` is declared on the ``AIModel`` base class, so the bundle's model type
# instance already carries the right type; no downcast to ``LargeLanguageModel`` is needed.
model_type_instance = provider_model_bundle.model_type_instance
model_type_instance = cast(LargeLanguageModel, model_type_instance)

# check model credentials
model_credentials = provider_model_bundle.configuration.get_current_credentials(
Expand Down
81 changes: 74 additions & 7 deletions api/core/entities/provider_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from collections import defaultdict
from collections.abc import Iterator, Sequence
from json import JSONDecodeError
from typing import Any, override
from typing import Any, Self, override

from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validator
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, ValidationInfo, model_validator
from sqlalchemy import String, func, literal, select
from sqlalchemy.orm import Session
from sqlalchemy.sql.elements import BindParameter
Expand Down Expand Up @@ -63,6 +63,35 @@
original_provider_configurate_methods: dict[str, list[ConfigurateMethod]] = {}


class ProviderConfigurateMethodsRegistry:
"""Keep the first provider configurate-method snapshot for each provider ID.

Production validation uses the module registry to preserve the existing catalog-level snapshot,
while callers can supply an isolated registry through Pydantic validation context.
"""

def __init__(self, methods_by_provider: dict[str, list[ConfigurateMethod]] | None = None) -> None:
"""Use ``methods_by_provider`` as backing storage, or create a fresh isolated mapping.

Preconditions: supplied entries map provider IDs to their original configurate methods.
Postconditions: the registry keeps the mapping by reference so production can preserve its
module-level storage and tests can own a fresh mapping.
"""
self.methods_by_provider: dict[str, list[ConfigurateMethod]] = (
methods_by_provider if methods_by_provider is not None else {}
)

def register_initial_methods(self, *, provider_id: str, methods: Sequence[ConfigurateMethod]) -> None:
"""Record the first method snapshot for ``provider_id`` without replacing it.

Preconditions: ``methods`` is the provider's original configure-method sequence.
Postconditions: the mapping contains a copy of that sequence only if this provider has not
already been registered; later tenant/request configurations cannot overwrite the snapshot.
"""
if provider_id not in self.methods_by_provider:
self.methods_by_provider[provider_id] = list(methods)


def _model_type_db_values(model_type: ModelType) -> tuple[str, ...]:
"""Return DB values that may represent ``model_type`` after pre-1.15 upgrades.

Expand Down Expand Up @@ -143,6 +172,11 @@ class ProviderConfiguration(BaseModel):
lookups instead of refetching the full provider catalog from the runtime on
every request-scoped lookup.

Original configurate methods are snapshotted per instance before schema
normalization. Their first provider-level snapshot is retained in the
production registry by default; explicit validation context can supply an
isolated registry without changing the Pydantic fields or schema.

TODO: lots of logic in a BaseModel entity should be separated, the exceptions should be classified
"""

Expand All @@ -161,14 +195,47 @@ class ProviderConfiguration(BaseModel):
_original_provider_configurate_methods: tuple[ConfigurateMethod, ...] = PrivateAttr(default_factory=tuple)
_policy_checked_credential_ids: set[str] = PrivateAttr(default_factory=set)

@classmethod
def model_validate_with_configurate_methods_registry(
cls,
*,
registry: ProviderConfigurateMethodsRegistry,
tenant_id: str,
provider: ProviderEntity,
preferred_provider_type: ProviderType,
using_provider_type: ProviderType,
system_configuration: SystemConfiguration,
custom_configuration: CustomConfiguration,
model_settings: list[ModelSettings],
) -> Self:
"""Validate the configuration fields with a caller-owned snapshot registry."""
return cls.model_validate(
{
"tenant_id": tenant_id,
"provider": provider,
"preferred_provider_type": preferred_provider_type,
"using_provider_type": using_provider_type,
"system_configuration": system_configuration,
"custom_configuration": custom_configuration,
"model_settings": model_settings,
},
context=registry,
)

@model_validator(mode="after")
def _(self):
def _record_original_provider_configurate_methods(self, info: ValidationInfo) -> Self:
"""Snapshot provider methods per instance and register the provider's first global snapshot.

The configuration's snapshot is taken before normalization. A registry supplied as
validation context receives the first snapshot for each provider; otherwise the module
registry retains the existing production behavior.
"""
self._original_provider_configurate_methods = tuple(self.provider.configurate_methods)

if self.provider.provider not in original_provider_configurate_methods:
original_provider_configurate_methods[self.provider.provider] = []
for configurate_method in self.provider.configurate_methods:
original_provider_configurate_methods[self.provider.provider].append(configurate_method)
registry = info.context
if not isinstance(registry, ProviderConfigurateMethodsRegistry):
registry = ProviderConfigurateMethodsRegistry(original_provider_configurate_methods)
registry.register_initial_methods(provider_id=self.provider.provider, methods=self.provider.configurate_methods)

if list(self._original_provider_configurate_methods) == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
if (
Expand Down
Loading