Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(model): add OpenAI Chat and Responses API selection (#1937)
qbc7fded2535d81
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex aba7c2729..069bade70 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -10,6 +10,7 @@ export interface ChatModelConfig {type: string;credential_id: string;model: string;+ model_class: string;parameters: Record<string, unknown>;}@@ -818,6 +819,7 @@ export interface ScheduleListResponse {export interface ModelCard {type: 'chat_model';+ model_class: string;name: string;label: string;status: 'active' | 'deprecated' | 'sunset';diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsxindex 7b849c7a5..1afbb8761 100644--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx@@ -310,11 +310,17 @@ export function ModelParametersPopover({[values, onChange],);- const handleSelectFallback = (type: string, credentialId: string, model: string) => {+ const handleSelectFallback = (+ type: string,+ credentialId: string,+ model: string,+ modelClass: string,+ ) => {onFallbackChange?.({type,credential_id: credentialId,model,+ model_class: modelClass,parameters: {},});};@@ -329,6 +335,17 @@ export function ModelParametersPopover({.map(([type, items]) => [type, items.filter((i) => i.models.length > 0)] as const).filter(([, usable]) => usable.length > 0);const hasFallbackOptions = fallbackGroups.length > 0;+ // Legacy configs use the first matching implementation, as the backend does.+ const selectedFallbackCard = selectedFallbackModel+ ? groups[selectedFallbackModel.type]+ ?.find(({ credential }) => credential.id === selectedFallbackModel.credential_id)+ ?.models.find(+ (m) =>+ m.name === selectedFallbackModel.model &&+ (!selectedFallbackModel.model_class ||+ m.model_class === selectedFallbackModel.model_class),+ )+ : undefined;return (<DropdownMenu>@@ -351,7 +368,9 @@ export function ModelParametersPopover({<span className="truncate">{selectedFallbackModel? t('model-parameters.fallbackLabelWithModel', {- model: selectedFallbackModel.model,+ model:+ selectedFallbackCard?.label ??+ selectedFallbackModel.model,}): t('model-parameters.fallbackLabel')}</span>@@ -372,11 +391,10 @@ export function ModelParametersPopover({models.map((m) => {const isSelected =selectedFallbackModel?.credential_id ===- credential.id &&- selectedFallbackModel?.model === m.name;+ credential.id && m === selectedFallbackCard;return (<DropdownMenuCheckboxItem- key={`${credential.id}-${m.name}`}+ key={`${credential.id}-${m.model_class}:${m.name}`}checked={isSelected}onCheckedChange={(checked) => {if (checked) {@@ -384,6 +402,7 @@ export function ModelParametersPopover({type,credential.id,m.name,+ m.model_class,);} else {onFallbackChange(null);@@ -407,13 +426,12 @@ export function ModelParametersPopover({usable[0].models,): usable.map(({ credential, models }) => {- const hasSelected = models.some(- (m) =>- selectedFallbackModel?.credential_id ===- credential.id &&- selectedFallbackModel?.model ===- m.name,- );+ const hasSelected =+ selectedFallbackModel?.credential_id ===+ credential.id &&+ models.some(+ (m) => m === selectedFallbackCard,+ );return (<DropdownMenuSub key={credential.id}><DropdownMenuSubTrigger>diff --git a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx b/examples/web_ui/frontend/src/components/select/LlmSelect.tsxindex 97815064a..e392ab9b0 100644--- a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx+++ b/examples/web_ui/frontend/src/components/select/LlmSelect.tsx@@ -58,15 +58,38 @@ export function LlmSelect({.filter(([, usable]) => usable.length > 0);const hasOptions = groupEntries.length > 0;- const handleSelect = (type: string, credentialId: string, model: string) => {- onChange?.({ type, credential_id: credentialId, model, parameters: {} });+ const handleSelect = (+ type: string,+ credentialId: string,+ model: string,+ modelClass: string,+ ) => {+ onChange?.({+ type,+ credential_id: credentialId,+ model,+ model_class: modelClass,+ parameters: {},+ });};- const displayLabel = value?.model- ? value.model- : loading- ? t('llm-select.loading')- : (placeholder ?? t('llm-select.placeholder'));+ const displayLabel = (() => {+ if (!value?.model) {+ return loading ? t('llm-select.loading') : (placeholder ?? t('llm-select.placeholder'));+ }+ const items = groups[value.type];+ if (items) {+ for (const { models } of items) {+ const card = models.find(+ (m) =>+ m.name === value.model &&+ (!value.model_class || m.model_class === value.model_class),+ );+ if (card) return card.label;+ }+ }+ return value.model;+ })();return (<DropdownMenu>@@ -99,16 +122,17 @@ export function LlmSelect({{isSingle? usable[0].models.map((m) => (<DropdownMenuItem- key={m.name}+ key={`${m.model_class}:${m.name}`}onSelect={() =>handleSelect(type,usable[0].credential.id,m.name,+ m.model_class,)}>- {m.name}+ {m.label}</DropdownMenuItem>)): usable.map(({ credential, models }) => (@@ -120,12 +144,13 @@ export function LlmSelect({<DropdownMenuSubContent className="max-h-60 overflow-y-auto">{models.map((m) => (<DropdownMenuItem- key={m.name}+ key={`${m.model_class}:${m.name}`}onSelect={() =>handleSelect(type,credential.id,m.name,+ m.model_class,)}>diff --git a/examples/web_ui/frontend/src/pages/channel/channel-form.tsx b/examples/web_ui/frontend/src/pages/channel/channel-form.tsxindex 3b0251948..9b56f27db 100644--- a/examples/web_ui/frontend/src/pages/channel/channel-form.tsx+++ b/examples/web_ui/frontend/src/pages/channel/channel-form.tsx@@ -201,15 +201,25 @@ export function ChannelForm({ value, onChange, agents, channelTypes, mode }: Pro}, [t, typeSchema]);const selectedModelCard = React.useMemo(() => {- if (!value.chatModelConfig) return null;- const items = groups[value.chatModelConfig.type];+ const config = value.chatModelConfig;+ if (!config) return null;+ const items = groups[config.type];if (!items) return null;for (const { models } of items) {- const card = models.find((m) => m.name === value.chatModelConfig!.model);+ const card = models.find(+ (m) =>+ m.name === config.model &&+ (!config.model_class || m.model_class === config.model_class),+ );if (card) return card;}return null;- }, [groups, value.chatModelConfig?.type, value.chatModelConfig?.model]);+ }, [+ groups,+ value.chatModelConfig?.type,+ value.chatModelConfig?.model,+ value.chatModelConfig?.model_class,+ ]);return (<FieldGroup className="[&>[data-orientation=horizontal]>:last-child]:w-48">diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsxindex 6314a991b..3fae74978 100644--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx@@ -535,11 +535,15 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatViewconst items = groups[selectedModel.type];if (!items) return null;for (const { models } of items) {- const card = models.find((m) => m.name === selectedModel.model);+ const card = models.find(+ (m) =>+ m.name === selectedModel.model &&+ (!selectedModel.model_class || m.model_class === selectedModel.model_class),+ );if (card) return card;}return null;- }, [groups, selectedModel?.type, selectedModel?.model]);+ }, [groups, selectedModel?.type, selectedModel?.model, selectedModel?.model_class]);const selectedRealtimeModelCard = useMemo(() => {if (!selectedRealtimeModel) return null;@@ -571,14 +575,13 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatViewconst items = groups[firstType];if (!items || items.length === 0) return null;const firstItem = items[0];- const firstModel = (firstItem.models as { name?: string; id?: string }[])[0];+ const firstModel = firstItem.models[0];if (!firstModel) return null;- const modelName = firstModel.name ?? firstModel.id ?? null;- if (!modelName) return null;return {type: firstType,credential_id: firstItem.credential.id,- model: modelName,+ model: firstModel.name,+ model_class: firstModel.model_class,parameters: {},};};diff --git a/examples/web_ui/frontend/src/pages/credential/index.tsx b/examples/web_ui/frontend/src/pages/credential/index.tsxindex 0dcfe8038..01a27f9dc 100644--- a/examples/web_ui/frontend/src/pages/credential/index.tsx+++ b/examples/web_ui/frontend/src/pages/credential/index.tsx@@ -176,7 +176,7 @@ function ModelTable({ models, variant }: ModelTableProps) {const context = chat?.context_size ?? embed?.context_size;return (<TableRow- key={model.name}+ key={chat ? `${chat.model_class}:${chat.name}` : model.name}className="border-border hover:bg-row-hover"><TableCell className="px-4 py-2.5 text-[12.5px] text-foreground">diff --git a/src/agentscope/app/_router/_model.py b/src/agentscope/app/_router/_model.pyindex b42943100..338a74686 100644--- a/src/agentscope/app/_router/_model.py+++ b/src/agentscope/app/_router/_model.py@@ -36,5 +36,5 @@ async def list_models(detail=f"Provider '{body.provider}' not found.",)- models = credential_cls.get_chat_model_class().list_models()+ models = credential_cls.list_models()return ListModelsResponse(models=models, total=len(models))diff --git a/src/agentscope/app/_service/_model.py b/src/agentscope/app/_service/_model.pyindex 1f5fc6b12..666b47602 100644--- a/src/agentscope/app/_service/_model.py+++ b/src/agentscope/app/_service/_model.py@@ -39,6 +39,8 @@ async def get_model(`HTTPException`:404 when the credential is neither owned by ``user_id`` norshared to them.+ `ValueError`:+ If the credential does not support the explicit model class."""credential_record = await access.resolve_credential(user_id,@@ -46,7 +48,18 @@ async def get_model()credential = CredentialFactory.from_dict(credential_record.data)- model_cls = credential.get_chat_model_class()+ if config.model_class:+ for model_cls in credential.get_chat_model_classes():+ if getattr(model_cls, "type", "") == config.model_class:+ break+ else:+ raise ValueError(+ f"Chat model class {config.model_class!r} is not available "+ f"for credential {config.credential_id!r}.",+ )+ else:+ model_cls = credential.get_chat_model_class()+parameters = (model_cls.Parameters(**config.parameters)if config.parametersdiff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex 29b502469..2d414a408 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -120,6 +120,10 @@ class ChatModelConfig(BaseModel):model: str"""The model name."""+ model_class: str = ""+ """The model implementation class type (e.g. ``openai_chat``,+ ``openai_response``). Empty string means use default resolution."""+parameters: dict"""The model parameters."""diff --git a/src/agentscope/credential/_base.py b/src/agentscope/credential/_base.pyindex 7ec8f8e69..223c3fc92 100644--- a/src/agentscope/credential/_base.py+++ b/src/agentscope/credential/_base.py@@ -42,6 +42,21 @@ class CredentialBase(BaseModel):f"{cls.__name__} must implement ``get_chat_model_class``.",)+ @classmethod+ def get_chat_model_classes(cls) -> list[Type["ChatModelBase"]]:+ """Return all chat model classes supported by this credential.++ Providers that expose multiple API surfaces (e.g. OpenAI Chat+ Completions vs Responses API) should override this to return all+ applicable classes. The default returns a single-element list from+ :meth:`get_chat_model_class`.++ Returns:+ `list[Type[ChatModelBase]]`:+ The chat model classes.+ """+ return [cls.get_chat_model_class()]+@classmethoddef get_tts_model_classes(cls) -> list[Type["TTSModelBase"]]:"""Return the TTS model classes supported by this credential.@@ -102,15 +117,17 @@ class CredentialBase(BaseModel):@classmethoddef list_models(cls) -> list["ModelCard"]:"""List the candidate chat models that are available under this- credential. The default implementation delegates to the- :meth:`ChatModelBase.list_models` of the class returned by- :meth:`get_chat_model_class`.+ credential. Merges model cards from all classes returned by+ :meth:`get_chat_model_classes`.Returns:`list[ModelCard]`:A list of candidate models described by their model cards."""- return cls.get_chat_model_class().list_models()+ cards: list["ModelCard"] = []+ for model_cls in cls.get_chat_model_classes():+ cards.extend(model_cls.list_models())+ return cards@classmethoddef get_embedding_model_class(cls) -> Type["EmbeddingModelBase"] | None:diff --git a/src/agentscope/credential/_openai.py b/src/agentscope/credential/_openai.pyindex 2f5cea3f9..4b7fdd2f3 100644--- a/src/agentscope/credential/_openai.py+++ b/src/agentscope/credential/_openai.py@@ -51,6 +51,16 @@ class OpenAICredential(CredentialBase):return OpenAIChatModel+ @classmethod+ def get_chat_model_classes(cls) -> list[Type["ChatModelBase"]]:+ """Return both APIs unless the legacy getter selects a custom model."""+ from ..model import OpenAIChatModel, OpenAIResponseModel++ model_cls = cls.get_chat_model_class()+ if model_cls is not OpenAIChatModel:+ return [model_cls]+ return [OpenAIChatModel, OpenAIResponseModel]+@classmethoddef get_embedding_model_class(cls) -> Type["EmbeddingModelBase"]:"""Return the OpenAIEmbeddingModel class."""diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.pyindex d4782b2a5..2a61e247d 100644--- a/src/agentscope/model/_base.py+++ b/src/agentscope/model/_base.py@@ -160,6 +160,7 @@ class ChatModelBase:yaml_files = list(yaml_dir.glob("*.yaml"))# Load each YAML file and create ModelCard+ model_class_type = getattr(cls, "type", "")model_cards = []for yaml_file in yaml_files:try:@@ -167,6 +168,7 @@ class ChatModelBase:yaml_path=str(yaml_file),parameter_class=cls.Parameters,)+ card.model_class = model_class_typemodel_cards.append(card)except Exception as e:# Log error but continue with other filesdiff --git a/src/agentscope/model/_model_card.py b/src/agentscope/model/_model_card.pyindex 282e5c9ad..66e4abeeb 100644--- a/src/agentscope/model/_model_card.py+++ b/src/agentscope/model/_model_card.py@@ -14,6 +14,13 @@ class ModelCard(BaseModel):type: Literal["chat_model"] = "chat_model""""The model card type."""+ model_class: str = Field(+ default="",+ description="The model implementation class type (e.g. openai_chat).",+ )+ """Discriminator identifying which ChatModelBase subclass owns this card.+ Set automatically by :meth:`ChatModelBase.list_models`."""+name: str = Field(description="The name of the model")"""The model name."""diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yamlindex 06ccd7125..4f93670fc 100644--- a/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml@@ -1,5 +1,5 @@name: gpt-4.1-mini-label: GPT-4.1 Mini+label: GPT-4.1 Mini (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yamlindex fd81fce7b..a4929c77a 100644--- a/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml@@ -1,5 +1,5 @@name: gpt-4.1-nano-label: GPT-4.1 Nano+label: GPT-4.1 Nano (Responses API)status: deprecateddeprecated_at: "2026-10-23T00:00:00"diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1.yamlindex 37d4ba47e..f40fff012 100644--- a/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml@@ -1,5 +1,5 @@name: gpt-4.1-label: GPT-4.1+label: GPT-4.1 (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml b/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yamlindex e808f59bf..acb479bd3 100644--- a/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml@@ -1,5 +1,5 @@name: gpt-4o-mini-label: GPT-4o Mini+label: GPT-4o Mini (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-4o.yaml b/src/agentscope/model/_openai_response/_models/gpt-4o.yamlindex 419735bbd..8b733cf37 100644--- a/src/agentscope/model/_openai_response/_models/gpt-4o.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-4o.yaml@@ -1,5 +1,5 @@name: gpt-4o-label: GPT-4o+label: GPT-4o (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.5.yamlindex 3d1edf00a..b87b31d6e 100644--- a/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml@@ -1,5 +1,5 @@name: gpt-5.5-label: GPT-5.5+label: GPT-5.5 (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yamlindex 9f6fd13e5..b8d037b44 100644--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml@@ -1,5 +1,5 @@name: gpt-5.6-luna-label: GPT-5.6 Luna+label: GPT-5.6 Luna (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yamlindex ebeb0b576..f49f6ffe1 100644--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml@@ -1,5 +1,5 @@name: gpt-5.6-sol-label: GPT-5.6 Sol+label: GPT-5.6 Sol (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yamlindex 4440e7e3e..75206b344 100644--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml@@ -1,5 +1,5 @@name: gpt-5.6-terra-label: GPT-5.6 Terra+label: GPT-5.6 Terra (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-6-astra.yaml b/src/agentscope/model/_openai_response/_models/gpt-6-astra.yamlindex d929531c0..fca384cfa 100644--- a/src/agentscope/model/_openai_response/_models/gpt-6-astra.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-6-astra.yaml@@ -1,5 +1,5 @@name: gpt-6-astra-label: GPT-6 Astra+label: GPT-6 Astra (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-6-luna.yaml b/src/agentscope/model/_openai_response/_models/gpt-6-luna.yamlindex 4d85f2904..a7f99c091 100644--- a/src/agentscope/model/_openai_response/_models/gpt-6-luna.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-6-luna.yaml@@ -1,6 +1,6 @@# Source: https://developers.openai.com/api/docs/models/gpt-6-lunaname: gpt-6-luna-label: GPT-6 Luna+label: GPT-6 Luna (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-6-sol.yaml b/src/agentscope/model/_openai_response/_models/gpt-6-sol.yamlindex 32fa00cfc..698809574 100644--- a/src/agentscope/model/_openai_response/_models/gpt-6-sol.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-6-sol.yaml@@ -1,6 +1,6 @@# Source: https://developers.openai.com/api/docs/models/gpt-6-solname: gpt-6-sol-label: GPT-6 Sol+label: GPT-6 Sol (Responses API)status: activeinput_types:diff --git a/src/agentscope/model/_openai_response/_models/gpt-6.1-sol.yaml b/src/agentscope/model/_openai_response/_models/gpt-6.1-sol.yamlindex 7bdc0ceda..61d576724 100644--- a/src/agentscope/model/_openai_response/_models/gpt-6.1-sol.yaml+++ b/src/agentscope/model/_openai_response/_models/gpt-6.1-sol.yaml@@ -1,6 +1,6 @@# Source: https://developers.openai.com/api/docs/models/gpt-6.1-solname: gpt-6.1-sol-label: GPT-6.1 Sol+label: GPT-6.1 Sol (Responses API)status: activeinput_types:diff --git a/tests/service_model_test.py b/tests/service_model_test.pyindex 443d1d684..0f935095d 100644--- a/tests/service_model_test.py+++ b/tests/service_model_test.py@@ -2,14 +2,154 @@"""Unit tests for :func:`get_model` — the chat model factory."""from types import SimpleNamespacefrom unittest import IsolatedAsyncioTestCase-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchfrom agentscope.app._service._model import get_modelfrom agentscope.app.storage import ChatModelConfig+from agentscope.credential import CredentialFactory, OpenAICredential+from agentscope.model import OpenAIChatModel, OpenAIResponseModel_CREDENTIAL = {"type": "deepseek_credential", "api_key": "test"}+class _CustomOpenAIChatModel(OpenAIChatModel):+ """A custom adapter selected through the legacy credential getter."""+++class _CustomOpenAICredential(OpenAICredential):+ """An existing credential extension using the single-class getter."""++ @classmethod+ def get_chat_model_class(cls) -> type[OpenAIChatModel]:+ return _CustomOpenAIChatModel+++class OpenAICredentialModelTest(IsolatedAsyncioTestCase):+ """Check model resolution for built-in and extended credentials."""++ def test_default_models(self) -> None:+ """Standard credentials continue to expose both API surfaces."""+ self.assertListEqual(+ OpenAICredential.get_chat_model_classes(),+ [OpenAIChatModel, OpenAIResponseModel],+ )++ def test_legacy_model_override(self) -> None:+ """A legacy override keeps its model without adding other APIs."""+ for model_cls in (_CustomOpenAIChatModel, OpenAIResponseModel):+ with self.subTest(model=model_cls.__name__):+ with patch.object(+ _CustomOpenAICredential,+ "get_chat_model_class",+ return_value=model_cls,+ ):+ self.assertListEqual(+ _CustomOpenAICredential.get_chat_model_classes(),+ [model_cls],+ )++ async def test_factory_uses_legacy_model_override(self) -> None:+ """Saved configs without model_class still use the custom adapter."""+ access = MagicMock(+ resolve_credential=AsyncMock(+ return_value=SimpleNamespace(data={}),+ ),+ )+ credential = _CustomOpenAICredential(api_key="test")+ with patch.object(+ CredentialFactory,+ "from_dict",+ return_value=credential,+ ), patch.object(+ _CustomOpenAICredential,+ "get_chat_model_classes",+ return_value=[OpenAIResponseModel, _CustomOpenAIChatModel],+ ) as get_classes:+ model = await get_model(+ "user-1",+ ChatModelConfig(+ type="openai_credential",+ credential_id="cred-1",+ model="custom-model",+ parameters={"max_tokens": 123},+ ),+ access,+ )+ try:+ get_classes.assert_not_called()+ self.assertEqual(+ (type(model), model.model, model.parameters.max_tokens),+ (_CustomOpenAIChatModel, "custom-model", 123),+ )+ finally:+ await model.client.close()++ async def test_explicit_model_class(self) -> None:+ """Explicit classes select the API for built-in and custom names."""+ access = MagicMock(+ resolve_credential=AsyncMock(+ return_value=SimpleNamespace(+ data={"type": "openai_credential", "api_key": "test"},+ ),+ ),+ )+ for model_cls in (OpenAIChatModel, OpenAIResponseModel):+ for name in ("gpt-4o", "custom-deployment"):+ with self.subTest(model_class=model_cls.type, model=name):+ model = await get_model(+ "user-1",+ ChatModelConfig(+ type="openai_credential",+ credential_id="cred-1",+ model=name,+ model_class=model_cls.type,+ parameters={"max_tokens": 123},+ ),+ access,+ )+ try:+ self.assertEqual(+ (+ type(model),+ model.model,+ model.parameters.max_tokens,+ ),+ (model_cls, name, 123),+ )+ finally:+ await model.client.close()++ async def test_unsupported_model_class_raises(self) -> None:+ """Invalid or foreign adapter types cannot silently fall back."""+ access = MagicMock(+ resolve_credential=AsyncMock(+ return_value=SimpleNamespace(+ data={"type": "openai_credential", "api_key": "test"},+ ),+ ),+ )+ for model_class in ("unknown", "deepseek_chat"):+ with self.subTest(model_class=model_class):+ with self.assertRaises(ValueError) as raised:+ model = await get_model(+ "user-1",+ ChatModelConfig(+ type="openai_credential",+ credential_id="cred-1",+ model="gpt-4o",+ model_class=model_class,+ parameters={},+ ),+ access,+ )+ await model.client.close()+ self.assertEqual(+ str(raised.exception),+ f"Chat model class {model_class!r} is not available "+ "for credential 'cred-1'.",+ )++class GetModelContextSizeTest(IsolatedAsyncioTestCase):"""The factory must forward the model card's ``context_size``."""diff --git a/tests/session_auto_naming_test.py b/tests/session_auto_naming_test.pyindex 0a941a0dd..051eae3aa 100644--- a/tests/session_auto_naming_test.py+++ b/tests/session_auto_naming_test.py@@ -57,19 +57,33 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):redis = fakeredis.aioredis.FakeRedis(decode_responses=True)class _Storage(RedisStorage):+ def __init__(self) -> None:+ """Initialize the storage with no active test client."""+ super().__init__()+ self._client = None+async def __aenter__(self) -> Any:+ """Attach the shared fake Redis client."""self._client = redisreturn selfasync def aclose(self) -> None:+ """Detach the client without closing the shared fake Redis."""self._client = Noneclass _Bus(RedisMessageBus):+ def __init__(self) -> None:+ """Initialize the bus with no active test client."""+ super().__init__()+ self._client = None+async def __aenter__(self) -> Any:+ """Attach the shared fake Redis client."""self._client = redisreturn selfasync def aclose(self) -> None:+ """Detach the client without closing the shared fake Redis."""self._client = Noneapp = create_app(@@ -343,6 +357,7 @@ class AutoNameSessionTest(IsolatedAsyncioTestCase):"type": "test","credential_id": "credential-1","model": "test-model",+ "model_class": "","parameters": {},},"fallback_chat_model_config": None,