Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 模型增加别名配置

cycong_169371ca32994
diff --git a/docs/en/Configuration.md b/docs/en/Configuration.md
index 8aabff02b6..081c73b8cc 100644
--- a/docs/en/Configuration.md
+++ b/docs/en/Configuration.md
@@ -36,6 +36,43 @@ These can be changed in the web app; values are written back to `.env` or config
**Note**: After saving, the backend restarts to load new settings. Model fields (`api_base`, `api_key`, `model`, `model_provider`) are required.
+### Multi-model management and aliases
+
+The **model list** block in the Configuration panel supports maintaining multiple models simultaneously. Fields for each model entry:
+
+| Field | Required | Description |
+|-------|----------|-------------|
+| `model_name` | Yes | API-level model identifier (e.g. `gpt-4o`, `deepseek-chat`) |
+| `alias` | No | Display name / switch identifier; defaults to `model_name` if left empty |
+| `api_base` | Yes | API base URL for this model |
+| `api_key` | Yes | API key for this model |
+| `model_provider` | Yes | Provider (e.g. `OpenAI`, `DeepSeek`) |
+| `temperature` | No | Sampling temperature, default `0.95` |
+
+**`alias` rules**:
+- If left blank, the stored value is automatically set to `model_name`.
+- Must be globally unique across all configured models: cannot match another model's `alias` or `model_name`.
+- When switching models (web dropdown / CLI `\model <name>`), either `alias` or `model_name` can be used as the identifier.
+
+Multi-model configuration is saved to the `models.defaults` list in `config.yaml`. Example:
+
+```yaml
+models:
+ defaults:
+ - alias: my-gpt # display name; used for switching in both UI and CLI
+ model_client_config:
+ api_base: https://api.openai.com/v1
+ api_key: ${API_KEY}
+ model_name: gpt-4o
+ client_provider: OpenAI
+ timeout: 1800
+ verify_ssl: false
+ model_config_obj:
+ temperature: 0.95
+```
+
+The first entry in the list is the default model; use the UI to drag-reorder or click "Set as default" to change it.
+
## 2. Not configurable in the web UI
Edit **`config/config.yaml`** or **`.env`** directly; there is no UI for these.
diff --git "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md" "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
index 956bc54805..0d2cb2af2e 100644
--- "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
+++ "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
@@ -36,6 +36,43 @@ JiuwenClaw 的配置来源包括:`config/config.yaml`、`.env` 环境变量、
**说明**:保存后后端会重启以加载新配置。模型配置(`api_base`、`api_key`、`model`、`model_provider`)为必填项。
+### 多模型管理与别名
+
+配置面板的**模型列表**区块支持同时维护多个模型。每个模型条目的字段:
+
+| 字段 | 是否必填 | 说明 |
+|------|---------|------|
+| `model_name` | 必填 | 模型在 API 层的名称(如 `gpt-4o`、`deepseek-chat`) |
+| `alias` | 选填 | 显示名称 / 切换标识符;不填时自动取 `model_name` 的值 |
+| `api_base` | 必填 | 该模型的 API 地址 |
+| `api_key` | 必填 | 该模型的 API 密钥 |
+| `model_provider` | 必填 | 提供商(如 `OpenAI`、`DeepSeek`) |
+| `temperature` | 选填 | 采样温度,默认 `0.95` |
+
+**`alias` 规则**:
+- 留空时存储时自动赋值为 `model_name`;
+- 在所有已配置模型中必须全局唯一:不能与其他模型的 `alias` 或 `model_name` 相同;
+- 切换模型时(Web 下拉 / CLI `\model <name>`)可用 `alias` 或 `model_name` 作为标识符。
+
+多模型配置保存后写入 `config.yaml` 的 `models.defaults` 列表,示例:
+
+```yaml
+models:
+ defaults:
+ - alias: my-gpt # 显示名称,UI 和 CLI 均以此标识切换
+ model_client_config:
+ api_base: https://api.openai.com/v1
+ api_key: ${API_KEY}
+ model_name: gpt-4o
+ client_provider: OpenAI
+ timeout: 1800
+ verify_ssl: false
+ model_config_obj:
+ temperature: 0.95
+```
+
+列表首位为默认使用的模型;可在 UI 中拖拽排序或点击"设为默认"调整首位。
+
## 二、前端不可配置
以下配置需通过**直接编辑 `config/config.yaml`** 或 **`.env`** 修改,无 Web 界面。
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
index 6676fd6ea8..404e8cbd91 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
@@ -1292,6 +1292,8 @@ class JiuWenClawDeepAdapter:
temperature=mco.get("temperature", 0.95),
)
mcc_fields = {k: v for k, v in mcc.items() if k != "model_name"}
+ if not mcc_fields.get("client_provider"):
+ mcc_fields["client_provider"] = "OpenAI"
return Model(model_client_config=ModelClientConfig(**mcc_fields), model_config=m_config)
def _build_model_cache_from_defaults(self, config: dict) -> None:
@@ -1323,6 +1325,10 @@ class JiuWenClawDeepAdapter:
if entry.get("is_default") is True:
self._model_cache[model_name] = self._model_cache[cache_key]
+ alias = entry.get("alias", "")
+ if alias and alias != model_name and alias not in self._model_cache:
+ self._model_cache[alias] = self._model_cache[cache_key]
+
def _build_model_cache_legacy(self, config: dict) -> None:
"""回退到旧格式(models.default / react 段)构建单条目缓存。"""
default_model_config = config.get("models", {}).get("default", {})
@@ -1372,7 +1378,7 @@ class JiuWenClawDeepAdapter:
return self._model
def _resolve_model_for_request(self, request: AgentRequest) -> Model:
- """根据请求中的 model_name 参数查找对应模型,未匹配则回退默认模型。
+ """根据请求中的 model_name 参数查找对应模型(支持别名),未匹配则回退默认模型。
支持两种格式:
- 纯 model_name:查找 is_default=true 的条目
@@ -2882,17 +2888,35 @@ class JiuWenClawDeepAdapter:
exc,
)
- def _has_valid_model_config(self) -> bool:
+ def _has_valid_model_config(self, requested_model_name: str = "") -> bool:
"""检查是否有有效的模型配置。
- 优先用已解析的 self._model,其次从 config.yaml 重新解析。
- 与 _create_model 同源,不独立读取环境变量。
+ 优先检查请求中实际要用的模型(requested_model_name),其次检查默认模型,
+ 最后从 config.yaml 重新解析。与 _create_model 同源,不独立读取环境变量。
"""
+ def _mcc_obj_looks_usable(mcc_obj: Any) -> bool:
+ if not isinstance(mcc_obj, ModelClientConfig):
+ return False
+ return _mcc_looks_usable({
+ "api_key": mcc_obj.api_key,
+ "api_base": getattr(mcc_obj, "api_base", None),
+ })
+
+ # 优先检查请求中指定的模型(如用户在 UI 切换了模型)
+ if requested_model_name and requested_model_name in self._model_cache:
+ m = self._model_cache[requested_model_name]
+ if _mcc_obj_looks_usable(getattr(m, "model_client_config", None)):
+ return True
+
+ # 检查默认模型
if self._model is not None:
- mcc = getattr(self._model, "model_client_config", None)
- if isinstance(mcc, ModelClientConfig):
- if _mcc_looks_usable({"api_key": mcc.api_key, "api_base": getattr(mcc, "api_base", None)}):
- return True
+ if _mcc_obj_looks_usable(getattr(self._model, "model_client_config", None)):
+ return True
+
+ # 回退:检查 cache 中是否有任意一个有效模型
+ for m in self._model_cache.values():
+ if _mcc_obj_looks_usable(getattr(m, "model_client_config", None)):
+ return True
try:
mcc = get_config().get("models", {}).get("default", {}).get("model_client_config", {})
@@ -3616,7 +3640,8 @@ class JiuWenClawDeepAdapter:
if self._instance is None:
raise RuntimeError("JiuWenClawDeepAdapter 未初始化,请先调用 create_instance()")
- if not self._has_valid_model_config():
+ _req_model = (request.params.get("model_name") or "") if isinstance(request.params, dict) else ""
+ if not self._has_valid_model_config(_req_model):
return AgentResponse(
request_id=request.request_id,
channel_id=request.channel_id,
@@ -3714,7 +3739,8 @@ class JiuWenClawDeepAdapter:
if self._instance is None:
raise RuntimeError("JiuWenClawDeepAdapter 未初始化,请先调用 create_instance()")
- if not self._has_valid_model_config():
+ _req_model = (request.params.get("model_name") or "") if isinstance(request.params, dict) else ""
+ if not self._has_valid_model_config(_req_model):
yield AgentResponseChunk(
request_id=request.request_id,
channel_id=request.channel_id,
diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.py
index 76fad10aca..80af3b812d 100644
--- a/jiuwenclaw/app_web_handlers.py
+++ b/jiuwenclaw/app_web_handlers.py
@@ -70,6 +70,12 @@ def _entry_model_name(entry: dict) -> str:
return _resolve_env_var_str(raw)
+def _entry_alias(entry: dict) -> str:
+ """从模型配置条目中提取并解析 alias。alias 为空时返回空字符串。"""
+ raw = entry.get("alias", "")
+ return _resolve_env_var_str(raw) if raw else ""
+
+
# 仅满足 Channel 构造所需,不入队、不路由;仅用 channel_manager + message_handler 做入站/出站
class _DummyBus:
async def publish_user_messages(self, msg): # noqa: ANN001, ARG002
@@ -706,6 +712,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
"model_provider": mcc.get("client_provider", ""),
"temperature": mco.get("temperature", 0.95),
"is_default": is_default,
+ "alias": entry.get("alias", ""),
})
# active_model 为列表首位的模型(主对话默认)
active_model = result[0]["model_name"] if result else ""
@@ -744,6 +751,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
target_index = int(target_index)
except (ValueError, TypeError):
target_index = None
+ alias = str(params.get("alias") or "").strip()
available_model_providers = [p.value for p in ProviderType]
if model_provider and model_provider not in available_model_providers:
@@ -753,6 +761,31 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
code="BAD_REQUEST",
)
return
+ _existing = _get_raw_model_list()
+ if alias:
+ for chk_idx, entry in enumerate(_existing):
+ # 跳过正在编辑的条目本身(按 index 精准定位,避免误报自身冲突)
+ if target_index is not None and chk_idx == target_index:
+ continue
+ ea = _entry_alias(entry)
+ emn = _entry_model_name(entry)
+ if ea == alias:
+ # 同 model_name 组内换位(如设为主对话默认时列表重排),不视为冲突
+ if emn == model_name:
+ continue
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{alias}' is already used by model '{emn}'",
+ code="BAD_REQUEST",
+ )
+ return
+ if emn == alias:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{alias}' conflicts with model name '{emn}'",
+ code="BAD_REQUEST",
+ )
+ return
if api_key:
from jiuwenclaw.extensions.registry import ExtensionRegistry
@@ -774,40 +807,50 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
},
"is_default": is_default,
}
+ new_entry["alias"] = alias
try:
models = _get_raw_model_list()
action = "created"
- if original_model_name and original_model_name != model_name:
- models = [m for m in models if _entry_model_name(m) != original_model_name]
- action = "renamed"
- if is_default:
- for i, entry in enumerate(models):
- if _entry_model_name(entry) == model_name:
- entry["is_default"] = False
-
- if target_index is not None:
- found = False
- for i, entry in enumerate(models):
- if i == target_index:
- models[i] = new_entry
- found = True
- if action != "renamed":
- action = "updated"
- break
- if not found:
- models.append(new_entry)
- else:
- for i, entry in enumerate(models):
- if _entry_model_name(entry) == model_name and not entry.get("is_default", False):
- models[i] = new_entry
- if action != "renamed":
- action = "updated"
- break
+ if original_model_name and original_model_name != model_name:
+ # 重命名场景:model_name 发生变化,优先用 target_index 精准定位
+ if target_index is not None and 0 <= target_index < len(models):
+ models[target_index] = new_entry
+ action = "renamed"
else:
+ renamed = False
+ for i, entry in enumerate(models):
+ if _entry_model_name(entry) == original_model_name:
+ models[i] = new_entry
+ renamed = True
+ break
+ if renamed:
+ action = "renamed"
+ else:
+ models.append(new_entry)
+ else:
+ if is_default:
+ for i, entry in enumerate(models):
+ if _entry_model_name(entry) == model_name:
+ entry["is_default"] = False
+
+ if target_index is not None and 0 <= target_index < len(models):
+ models[target_index] = new_entry
+ action = "updated"
+ elif target_index is not None and target_index >= len(models):
+ # index 越界 = 新增条目(前端追加到列表末尾时会出现此情况)
models.append(new_entry)
+ else:
+ updated = False
+ for i, entry in enumerate(models):
+ if _entry_model_name(entry) == model_name:
+ models[i] = new_entry
+ updated = True
+ break
+ if not updated:
+ models.append(new_entry)
from jiuwenclaw.config import _infer_is_default
models = _infer_is_default(models)
@@ -871,15 +914,20 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
removed_name = _entry_model_name(removed)
new_models = models[:target_index] + models[target_index + 1:]
else:
- new_models = [m for m in models if _entry_model_name(m) != model_name]
- removed_name = model_name
- if len(new_models) == len(models):
+ removed_idx = None
+ for i, entry in enumerate(models):
+ if _entry_model_name(entry) == model_name:
+ removed_idx = i
+ break
+ if removed_idx is None:
await channel.send_response(
ws, req_id, ok=False,
error=f"Model '{model_name}' not found",
code="NOT_FOUND",
)
return
+ removed_name = _entry_model_name(models[removed_idx])
+ new_models = models[:removed_idx] + models[removed_idx + 1:]
# 删除后若同 model_name 组内无 is_default=true,自动将第一个设为默认
from jiuwenclaw.config import _infer_is_default
diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.py
index 27827db661..6d1e6f4995 100644
--- a/jiuwenclaw/channel/cli_channel.py
+++ b/jiuwenclaw/channel/cli_channel.py
@@ -893,6 +893,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
"timeout": "timeout",
"verify_ssl": "verify_ssl",
"ssl_cert": "ssl_cert",
+ "alias": "alias",
}
# target 可能是 "model=gpt-5" 形式(前端把第一个 key=value 当作 name 参数解析)
if "=" in target:
@@ -916,28 +917,62 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
client_cfg["model_name"] = target
effective_name = client_cfg["model_name"]
+ # alias 为顶层字段,从 client_cfg 中提取;提前计算最终值确保唯一性校验基于实际存储值
+ entry_alias = client_cfg.pop("alias", None)
+ effective_alias = str(entry_alias).strip() if entry_alias else ""
+
new_entry = {
"model_client_config": client_cfg,
"model_config_obj": model_cfg_obj,
}
+ new_entry["alias"] = effective_alias
try:
_raw = get_config_raw()
_raw_defs = (_raw.get("models") or {}).get("defaults")
if isinstance(_raw_defs, list):
- # 重名校验
- existing_names = [
- resolve_env_vars(str((e.get("model_client_config") or {}).get("model_name", "")))
- for e in _raw_defs if isinstance(e, dict)
- ]
- if effective_name in existing_names:
- await channel.send_response(
- ws, req_id, ok=False,
- error=f"Model '{effective_name}' already exists.",
- )
- return
+ # alias 唯一性校验(仅在 alias 非空时执行)
+ if effective_alias:
+ for _e in _raw_defs:
+ if not isinstance(_e, dict):
+ continue
+ _emn = resolve_env_vars(str((_e.get("model_client_config") or {}).get("model_name", "")))
+ _ea = resolve_env_vars(str(_e.get("alias", "")))
+ # 别名不能和其他模型的别名重复
+ if _ea == effective_alias:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{effective_alias}' is already used by model '{_emn}'",
+ )
+ return
+ # 别名不能和其他模型的 model_name 冲突
+ if _emn == effective_alias:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{effective_alias}' conflicts with model name '{_emn}'",
+ )
+ return
_raw_defs.append(new_entry)
update_default_models_in_config(_raw_defs)
else:
+ # 旧格式:通过 get_default_models 枚举现有模型,补做 alias 唯一性校验
+ if effective_alias:
+ for _e in get_default_models():
+ if not isinstance(_e, dict):
+ continue
+ _emn = resolve_env_vars(str((_e.get("model_client_config") or {}).get("model_name", "")))
+ _ea = resolve_env_vars(str(_e.get("alias", "")))
+ if _ea == effective_alias:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{effective_alias}' is already used by model '{_emn}'",
+ )
+ return
+ if _emn == effective_alias:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Alias '{effective_alias}' conflicts with model name '{_emn}'",
+ )
+ return
add_or_update_model_in_config(target, new_entry)
logger.info(
"[cli command.model] 新增模型: name=%s, "
@@ -986,7 +1021,17 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
_defs = (_raw.get("models") or {}).get("defaults")
if isinstance(_defs, list) and _defs:
_first_name = resolve_env_vars(str((_defs[0].get("model_client_config") or {}).get("model_name", "")))
- payload["current"] = _first_name or os.getenv("MODEL_NAME", "unknown")
+ _first_alias = resolve_env_vars(str(_defs[0].get("alias", ""))) if _defs[0].get("alias") else ""
+ payload["current"] = _first_alias or _first_name or os.getenv("MODEL_NAME", "unknown")
+ payload["current_model_name"] = _first_name or os.getenv("MODEL_NAME", "unknown")
+ payload["models"] = [
+ {
+ "name": resolve_env_vars(str(e.get("alias", ""))) or
+ resolve_env_vars(str((e.get("model_client_config") or {}).get("model_name", ""))),
+ "model_name": resolve_env_vars(str((e.get("model_client_config") or {}).get("model_name", ""))),
+ }
+ for e in _defs if isinstance(e, dict)
+ ]
else:
payload["current"] = os.getenv("MODEL_NAME", "unknown")
await channel.send_response(ws, req_id, ok=True, payload=payload)
@@ -994,19 +1039,41 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
target = str(model_name).strip()
logger.info("[cli command.model] 切换模型: target=%s", target)
- if target not in get_model_names():
+ _raw_defs_check = (get_config_raw().get("models") or {}).get("defaults") or []
+ _valid_names: set[str] = set()
+ for _e in _raw_defs_check:
+ if isinstance(_e, dict):
+ _mn = resolve_env_vars(str((_e.get("model_client_config") or {}).get("model_name", "")))
+ _al = resolve_env_vars(str(_e.get("alias", ""))) if _e.get("alias") else ""
+ if _mn:
+ _valid_names.add(_mn)
+ if _al:
+ _valid_names.add(_al)
+ if not _valid_names:
+ _valid_names = set(get_model_names())
+ if target not in _valid_names:
logger.warning(
"[cli command.model] 模型不存在: %s, 可用: %s",
target,
get_model_names(),
)
+ _avail_parts = []
+ for _e in _raw_defs_check:
+ if not isinstance(_e, dict):
+ continue
+ _mn = resolve_env_vars(str((_e.get("model_client_config") or {}).get("model_name", "")))
+ _al = resolve_env_vars(str(_e.get("alias", ""))) if _e.get("alias") else ""
+ if _al and _mn and _al != _mn:
+ _avail_parts.append(f"{_al} ({_mn})")
+ elif _mn:
+ _avail_parts.append(_mn)
await channel.send_response(
ws,
req_id,
ok=False,
error=(
f"Model '{target}' not found. "
- f"Available: {', '.join(get_model_names())}"
+ f"Available: {', '.join(_avail_parts) or ', '.join(get_model_names())}"
),
)
return
@@ -1015,16 +1082,17 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
_raw_defaults = (_raw_cfg.get("models") or {}).get("defaults")
if isinstance(_raw_defaults, list):
_target_entry = None
- _other_entries = []
- for _e in _raw_defaults:
+ _target_idx = None
+ for _i, _e in enumerate(_raw_defaults):
if not isinstance(_e, dict):
- _other_entries.append(_e)
continue
_ename = resolve_env_vars(str((_e.get("model_client_config") or {}).get("model_name", "")))
- if _ename == target:
+ _ealias = resolve_env_vars(str(_e.get("alias", ""))) if _e.get("alias") else ""
+ if _ename == target or _ealias == target:
_target_entry = _e
- else:
- _other_entries.append(_e)
+ _target_idx = _i
+ break # 取第一个匹配
+ _other_entries = [_e for _i, _e in enumerate(_raw_defaults) if _i != _target_idx]
if _target_entry is None:
await channel.send_response(ws, req_id, ok=False, error=f"Model '{target}' config not found")
return
@@ -1047,9 +1115,11 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
await _cb
except Exception as _e2:
logger.warning("[cli model.switch] on_config_saved failed: %s", _e2)
- logger.info("[cli command.model] 切换完成(新格式): current=%s", target)
+ _target_model_name = resolve_env_vars(
+ str((_target_entry.get("model_client_config") or {}).get("model_name", target)))
+ logger.info("[cli command.model] 切换完成(新格式): current=%s", _target_model_name)
await channel.send_response(ws, req_id, ok=True, payload={
- "current": target,
+ "current": _target_model_name,
"requested": target,
"type": "switched",
"applied": True,
@@ -1247,6 +1317,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
"api_key": mcc.get("api_key", ""),
"model_provider": mcc.get("client_provider", ""),
"temperature": mco.get("temperature", 0.95),
+ "alias": entry.get("alias", ""),
})
active_model = result[0]["model_name"] if result else ""
await channel.send_response(ws, req_id, ok=True, payload={
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/model.ts b/jiuwenclaw/cli/src/core/commands/builtins/model.ts
index d831647f14..4bc59b1f5d 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/model.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/model.ts
@@ -106,11 +106,16 @@ export function createModelCommand(): SlashCommand {
ctx.addItem(addInfo(ctx.sessionId, "No switchable models in list", "m"));
return;
}
+ const modelsMeta = payload.models ?? [];
const items = selectable.map((m, i) => {
const isCurrent = m === current;
+ const meta = modelsMeta.find((x) => x.name === m);
+ const displayName = meta?.model_name && meta.model_name !== m
+ ? `${m} (${meta.model_name})`
+ : m;
return {
label: String(i + 1),
- value: `${m}${isCurrent ? " (current)" : ""}`,
+ value: `${displayName}${isCurrent ? " (current)" : ""}`,
};
});
ctx.addItem(
@@ -143,10 +148,10 @@ export function createModelCommand(): SlashCommand {
const isSwitch = !!payload.requested;
if (isSwitch) {
- ctx.setModel(payload.requested ?? payload.current ?? "");
+ ctx.setModel(payload.current ?? payload.requested ?? "");
}
const title = isSwitch
- ? `Switched to: ${payload.requested}`
+ ? `Switched to: ${payload.current ?? payload.requested}`
: "Model Configuration";
const icon = isSwitch ? "m" : "c";
@@ -154,7 +159,7 @@ export function createModelCommand(): SlashCommand {
addInfo(
ctx.sessionId,
payload.requested
- ? `Switched model config to: ${payload.requested}`
+ ? `Switched model config to: ${payload.current ?? payload.requested}`
: `Current model: ${payload.current ?? "unknown"}`,
icon,
{
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
index 6f68660e69..7389262a34 100644
--- a/jiuwenclaw/cli/src/ui/app-screen.ts
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -1006,10 +1006,15 @@ export class AppScreen implements Component, Focusable {
return;
}
+ const modelsMeta = payload.models ?? [];
const items = selectable.map((m, i) => {
const isCurrent = m === current;
+ const meta = modelsMeta.find((x) => x.name === m);
+ const displayName = (meta?.model_name && meta.model_name !== m)
+ ? `${m} (${meta.model_name})`
+ : m;
return {
- label: `${i + 1}. ${m}${isCurrent ? " (current)" : ""}`,
+ label: `${i + 1}. ${displayName}${isCurrent ? " (current)" : ""}`,
value: m,
};
});
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index b9c6c6f8e5..ae31fe770a 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -688,7 +688,7 @@ def get_default_models(config: dict[str, Any] | None = None) -> list[dict[str, A
"""获取默认模型列表,兼容新旧格式。
优先级:models.defaults(列表) > models.default(单对象) > 环境变量回退
- 返回的 api_key 已解密。
+ 返回的 api_key 已解密。每个条目可能含顶层 alias 字段。
"""
if config is None:
config = get_config()
@@ -703,7 +703,8 @@ def get_default_models(config: dict[str, Any] | None = None) -> list[dict[str, A
return _decrypt_model_entries([models["default"]])
# 回退:从环境变量构造(env var 已在 resolve_env_vars 中解密)
- return [{
+ alias = os.getenv("MODEL_ALIAS", "")
+ entry: dict[str, Any] = {
"model_client_config": {
"api_base": os.getenv("API_BASE", ""),
"api_key": os.getenv("API_KEY", ""),
@@ -714,7 +715,10 @@ def get_default_models(config: dict[str, Any] | None = None) -> list[dict[str, A
"verify_ssl": False,
},
"model_config_obj": {"temperature": 0.95},
- }]
+ }
+ if alias:
+ entry["alias"] = alias
+ return [entry]
def update_default_models_in_config(models_list: list[dict[str, Any]]) -> None:
@@ -1193,10 +1197,14 @@ def get_model_names() -> list[str]:
for entry in defaults_list:
if not isinstance(entry, dict):
continue
- name = (entry.get("model_client_config") or {}).get("model_name", "")
- if name and name not in seen:
- seen.add(name)
- names.append(resolve_env_vars(str(name)))
+ model_name = (entry.get("model_client_config") or {}).get("model_name", "")
+ alias = entry.get("alias", "")
+ resolved_alias = resolve_env_vars(str(alias)) if alias else ""
+ resolved_name = resolve_env_vars(str(model_name)) if model_name else ""
+ display = resolved_alias or resolved_name
+ if display and display not in seen:
+ seen.add(display)
+ names.append(display)
return names
skip = {"default", "defaults"}
return [k for k, v in models.items() if isinstance(v, dict) and k not in skip]
@@ -1238,6 +1246,13 @@ def get_model_config(name: str, index: int | None = None) -> dict[str, Any] | No
if resolve_env_vars(str(entry_name)) == name:
matches.append((i, entry))
if not matches:
+ # 按 alias 查找(alias 全局唯一,index 无意义)
+ for entry in defaults_list:
+ if not isinstance(entry, dict):
+ continue
+ alias = entry.get("alias", "")
+ if alias and resolve_env_vars(str(alias)) == name:
+ return entry
return models.get(name) if name in models else None
if index is not None:
for pos, entry in matches:
diff --git a/jiuwenclaw/web/src/App.tsx b/jiuwenclaw/web/src/App.tsx
index 57c9911466..7eb9974ab5 100644
--- a/jiuwenclaw/web/src/App.tsx
+++ b/jiuwenclaw/web/src/App.tsx
@@ -388,7 +388,7 @@ function AppContent() {
}
// 同步获取多模型列表
try {
- const resp = await request<{ models: Array<{ model_name: string; api_base: string; api_key: string; model_provider: string; temperature?: number }>; active_model: string }>('models.list');
+ const resp = await request<{ models: Array<{ model_name: string; api_base: string; api_key: string; model_provider: string; temperature?: number; alias?: string }>; active_model: string }>('models.list');
if (resp?.models) {
setAvailableModels(resp.models, resp.active_model);
}
diff --git a/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css b/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css
index c9a10789fa..d91c2f011a 100644
--- a/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css
+++ b/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css
@@ -259,7 +259,7 @@
border-radius: var(--radius-md, 6px);
background: var(--bg);
color: var(--text);
- max-width: 140px;
+ max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
diff --git a/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx b/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx
index c4b2b273b1..1e054021bc 100644
--- a/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx
+++ b/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx
@@ -455,10 +455,10 @@ function ModelSelector() {
if (chatAvailableModels.length === 1) {
return (
<span
- className="text-xs text-text-muted px-2 truncate max-w-[140px]"
+ className="text-xs text-text-muted px-2 truncate max-w-[200px]"
title={chatAvailableModels[0].model_name}
>
- {chatAvailableModels[0].model_name}
+ {chatAvailableModels[0].alias || chatAvailableModels[0].model_name}
</span>
);
}
@@ -471,9 +471,9 @@ function ModelSelector() {
className="chat-model-selector"
data-testid="chat-model-selector"
>
- {chatAvailableModels.map((m) => (
- <option key={m.model_name} value={m.model_name}>
- {m.model_name}
+ {chatAvailableModels.map((m, idx) => (
+ <option key={`${m.model_name}-${idx}`} value={m.alias || m.model_name}>
+ {m.alias ? `${m.alias} (${m.model_name})` : m.model_name}
</option>
))}
</select>
diff --git a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx b/jiuwenclaw/web/src/components/ConfigPanel/index.tsx
index 29970e7278..dcc3b6f677 100644
--- a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/ConfigPanel/index.tsx
@@ -726,6 +726,19 @@ function MultiModelSection({
};
const updateModel = (idx: number, field: keyof ModelEntry, value: string) => {
+ if (field === "alias") {
+ const alias = value.trim();
+ if (alias) {
+ const conflict = models.find((m, i) => i !== idx && ((m.alias || "") === alias || m.model_name === alias));
+ if (conflict) {
+ setLocalError(`Alias '${alias}' is already used by model '${conflict.model_name}'`);
+ } else {
+ setLocalError(null);
+ }
+ } else {
+ setLocalError(null);
+ }
+ }
const copy = [...models];
copy[idx] = { ...copy[idx], [field]: value };
onModelsChange(copy);
@@ -777,37 +790,24 @@ function MultiModelSection({
if (sameNameCount <= 1) return;
const copy = [...models];
const newDefault = !copy[idx].is_default;
- copy[idx] = { ...copy[idx], is_default: newDefault };
-
- // 找到主对话默认所在的 index(列表首位)
- const primaryDefaultName = copy[0].model_name;
if (newDefault) {
- // 设为组内默认时,同组其他条目取消默认
+ // 设为组内默认:同组其他条目取消默认,不重排列表顺序
for (let i = 0; i < copy.length; i++) {
- if (i !== idx && copy[i].model_name === model.model_name) {
- copy[i] = { ...copy[i], is_default: false };
+ if (copy[i].model_name === model.model_name) {
+ copy[i] = { ...copy[i], is_default: i === idx };
}
}
- // 如果切换的组是主对话默认所在组,则新的组内默认自动成为主对话默认
- if (model.model_name === primaryDefaultName) {
- const [newPrimary] = copy.splice(idx, 1);
- copy.unshift(newPrimary);
- }
} else {
- // 取消默认时,同组第一个其他条目自动成为默认
+ // 取消默认:同组第一个其他条目自动成为默认
+ copy[idx] = { ...copy[idx], is_default: false };
const fallbackIdx = copy.findIndex((m, i) => i !== idx && m.model_name === model.model_name);
if (fallbackIdx >= 0) {
copy[fallbackIdx] = { ...copy[fallbackIdx], is_default: true };
- // 如果取消的组是主对话默认所在组,则新的组内默认自动成为主对话默认
- if (model.model_name === primaryDefaultName) {
- const [newPrimary] = copy.splice(fallbackIdx, 1);
- copy.unshift(newPrimary);
- }
}
}
onModelsChange(copy);
- setExpandedIdx(null);
+ // 不收起面板,让用户看到变化后的状态
};
const handleAddNew = () => {
@@ -817,6 +817,14 @@ function MultiModelSection({
setLocalError(t("config.modelList.apiKeyRequired"));
return;
}
+ const alias = newModel.alias?.trim() ?? "";
+ if (alias) {
+ const conflict = models.find((m) => (m.alias || "") === alias || m.model_name === alias);
+ if (conflict) {
+ setLocalError(`Alias '${alias}' is already used by model '${conflict.model_name}'`);
+ return;
+ }
+ }
setLocalError(null);
// 新增条目:同名组已有条目时 is_default=false,否则 is_default=true
const sameNameExists = models.some((m) => m.model_name === name);
@@ -824,7 +832,7 @@ function MultiModelSection({
onModelsChange([...models, entry]);
setExpandedIdx(models.length); // 自动展开新增的条目
setAddingNew(false);
- setNewModel({ model_name: "", api_base: "", api_key: "", model_provider: "OpenAI" });
+ setNewModel({ model_name: "", api_base: "", api_key: "", model_provider: "OpenAI", alias: "" });
};
return (
@@ -868,13 +876,13 @@ function MultiModelSection({
: model.model_name;
return (
<div key={idx} className="rounded-lg border border-border bg-secondary/20">
- <div className="flex items-center justify-between px-3 py-2">
+ <div className="flex items-center justify-between px-3 py-2 gap-2">
<button
type="button"
className="flex items-center gap-2 text-sm font-medium text-text truncate flex-1 text-left"
onClick={() => setExpandedIdx(isExpanded ? null : idx)}
>
- <svg className={`w-3 h-3 transition-transform ${isExpanded ? "rotate-90" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
+ <svg className={`w-3 h-3 transition-transform shrink-0 ${isExpanded ? "rotate-90" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
</svg>
<span className="truncate">{displayName || t("config.modelList.untitled")}</span>
@@ -899,7 +907,7 @@ function MultiModelSection({
</span>
)}
</button>
- <div className="flex items-center gap-1 ml-2">
+ <div className="flex items-center gap-1.5 shrink-0">
{!isPrimaryDefault && (
<button
type="button"
@@ -929,7 +937,7 @@ function MultiModelSection({
</div>
{isExpanded && (
<div className="border-t border-border px-3 py-2 space-y-2">
- {(["model_name", "api_base", "api_key", "model_provider"] as const).map((field) => (
+ {(["model_name", "alias", "api_base", "api_key", "model_provider"] as const).map((field) => (
<div key={field} className="flex items-center gap-2 text-xs">
<label className="w-28 text-text-muted shrink-0">
{field}{field === "api_key" && <span className="text-danger ml-0.5">*</span>}
@@ -976,7 +984,7 @@ function MultiModelSection({
{addingNew ? (
<div className="rounded-lg border border-accent/40 bg-accent/5 px-3 py-2 space-y-2">
- {(["model_name", "api_base", "api_key", "model_provider"] as const).map((field) => (
+ {(["model_name", "alias", "api_base", "api_key", "model_provider"] as const).map((field) => (
<div key={field} className="flex items-center gap-2 text-xs">
<label className="w-28 text-text-muted shrink-0">
{field}{field === "api_key" && <span className="text-danger ml-0.5">*</span>}
@@ -993,7 +1001,7 @@ function MultiModelSection({
) : (
<input
type={field === "api_key" ? "password" : "text"}
- value={newModel[field]}
+ value={newModel[field] ?? ""}
onChange={(e) => setNewModel((p) => ({ ...p, [field]: e.target.value }))}
className="flex-1 rounded border border-border bg-bg px-2 py-1 text-text text-xs"
placeholder={field === "model_name" ? "e.g. gpt-4o" : field === "api_key" ? t("config.modelList.apiKeyPlaceholder") : ""}
@@ -1893,7 +1901,7 @@ export function ConfigPanel({
}, [normalizedConfig]);
useEffect(() => {
- setDraftModels(storeAvailableModels.map((m) => ({ ...m })));
+ setDraftModels(storeAvailableModels.map((m) => ({ ...m, alias: m.alias || "" })));
}, [storeAvailableModels]);
const agentsFromConfig = useMemo<AgentEntry[]>(() => {
@@ -2012,7 +2020,9 @@ export function ConfigPanel({
const om = storeAvailableModels[i];
if (!om) return true;
return dm.model_name !== om.model_name || dm.api_base !== om.api_base
- || dm.api_key !== om.api_key || dm.model_provider !== om.model_provider;
+ || dm.api_key !== om.api_key || dm.model_provider !== om.model_provider
+ || (dm.alias ?? "") !== (om.alias ?? "")
+ || dm.is_default !== om.is_default;
});
}, [draftModels, storeAvailableModels]);
@@ -2038,7 +2048,7 @@ export function ConfigPanel({
const handleCancel = () => {
if (!hasChanges) return;
setDraftValues(normalizedConfig);
- setDraftModels(storeAvailableModels.map((m) => ({ ...m })));
+ setDraftModels(storeAvailableModels.map((m) => ({ ...m, alias: m.alias || "" })));
setDraftAgents(agentsFromConfig);
setDraftTeams(teamsFromConfig);
setAgentsTeamsEdited(false);
@@ -2056,6 +2066,21 @@ export function ConfigPanel({
setError(t('config.modelList.apiKeyRequired'));
return;
}
+ // alias 唯一性校验
+ const aliasSeen = new Map<string, string>();
+ for (const m of draftModels) {
+ const a = (m.alias || "").trim();
+ if (!a) continue;
+ if (aliasSeen.has(a)) {
+ setError(`Alias '${a}' is used by multiple models`);
+ return;
+ }
+ aliasSeen.set(a, m.model_name);
+ if (draftModels.some((other) => other !== m && other.model_name === a)) {
+ setError(`Alias '${a}' conflicts with model name '${a}'`);
+ return;
+ }
+ }
setSaving(true);
setError(null);
try {
@@ -2067,9 +2092,7 @@ export function ConfigPanel({
const isRename = removedNames.length === 1 && addedNames.length === 1
&& draftModels.length === storeAvailableModels.length;
- // 保存非模型配置(视频/音频/embed/第三方等)
- await onSaveConfig(draftValues);
- // 保存多模型变更
+ // 先保存多模型变更——若此步骤失败,后续成功弹窗不会弹出
if (hasModelChanges) {
if (isRename && onModelSave) {
// 改名场景:先原子性处理改名,再处理其他模型的字段变更
@@ -2085,7 +2108,7 @@ export function ConfigPanel({
const original = storeAvailableModels.find((m) => m.model_name === other.model_name);
const isChanged = original && (
other.api_base !== original.api_base || other.api_key !== original.api_key
- || other.model_provider !== original.model_provider
+ || other.model_provider !== original.model_provider || other.alias !== original.alias
|| other.is_default !== original.is_default
);
if (isChanged) {
@@ -2097,11 +2120,27 @@ export function ConfigPanel({
for (let i = 0; i < draftModels.length; i++) {
const dm = draftModels[i];
if (!dm.model_name) continue;
- const original = storeAvailableModels.find((m) => m.model_name === dm.model_name);
- const isNew = !originalNames.has(dm.model_name);
+ // 用 alias 作为身份标识匹配原始条目,避免重排后位置错位
+ const dmAlias = (dm.alias || "").trim();
+ let origIdx: number;
+ if (dmAlias) {
+ origIdx = storeAvailableModels.findIndex((m) => (m.alias || "").trim() === dmAlias);
+ } else {
+ // 无 alias:按 model_name 且同样无 alias 的条目匹配,找不到再按位置
+ const byName = storeAvailableModels.findIndex(
+ (m) => !(m.alias || "").trim() && m.model_name === dm.model_name
+ );
+ origIdx = byName >= 0 ? byName : i;
+ }
+ const original = origIdx >= 0 ? storeAvailableModels[origIdx] : storeAvailableModels[i];
+ const positionChanged = origIdx >= 0 && origIdx !== i;
+ // i >= storeAvailableModels.length 时是新增条目;alias 找不到对应原始条目也视为新增
+ const isNew = origIdx < 0 && (i >= storeAvailableModels.length || !originalNames.has(dm.model_name));
const isChanged = original && (
+ positionChanged ||
dm.api_base !== original.api_base || dm.api_key !== original.api_key
|| dm.model_provider !== original.model_provider
+ || (dm.alias ?? "") !== (original.alias ?? "")
|| dm.is_default !== original.is_default
);
if ((isNew || isChanged) && onModelSave) {
@@ -2146,6 +2185,8 @@ export function ConfigPanel({
});
setAgentsTeamsEdited(false);
}
+ // 模型保存全部成功后,再保存非模型配置(视频/音频/embed/第三方等)并触发成功弹窗
+ await onSaveConfig(draftValues);
} catch (saveError) {
const message = saveError instanceof Error ? saveError.message : t('config.errors.saveFailed');
setError(message);
diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.json
index af623b4dbf..31f6f1996e 100644
--- a/jiuwenclaw/web/src/i18n/locales/en.json
+++ b/jiuwenclaw/web/src/i18n/locales/en.json
@@ -459,7 +459,9 @@
"isDefault": "Group Default",
"onlyOneInGroup": "Only one in group, auto-default",
"apiKeyRequired": "API Key is required, please fill it in before saving",
- "apiKeyPlaceholder": "Local models don't need an API Key — enter any value, e.g. sk-1234"
+ "apiKeyPlaceholder": "Local models don't need an API Key — enter any value, e.g. sk-1234",
+ "alias": "Alias",
+ "aliasPlaceholder": "Optional, defaults to empty"
},
"agentList": {
"addAgent": "Add Agent",
diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.json
index 205c5983a5..c9edabef5f 100644
--- a/jiuwenclaw/web/src/i18n/locales/zh.json
+++ b/jiuwenclaw/web/src/i18n/locales/zh.json
@@ -458,7 +458,9 @@
"isDefault": "组内默认",
"onlyOneInGroup": "同模型名仅一个,自动默认",
"apiKeyRequired": "API Key 为必填项,请填写后再保存",
- "apiKeyPlaceholder": "本地模型无需 API Key 可随意填写,如 sk-1234"
+ "apiKeyPlaceholder": "本地模型无需 API Key 可随意填写,如 sk-1234",
+ "alias": "别名",
+ "aliasPlaceholder": "选填,默认为空"
},
"agentList": {
"addAgent": "添加Agent",
diff --git a/jiuwenclaw/web/src/stores/sessionStore.ts b/jiuwenclaw/web/src/stores/sessionStore.ts
index 699f193bdd..2443c75f82 100644
--- a/jiuwenclaw/web/src/stores/sessionStore.ts
+++ b/jiuwenclaw/web/src/stores/sessionStore.ts
@@ -402,11 +402,11 @@ export const useSessionStore = create<SessionState>((set) => ({
setAvailableModels: (models, activeModel) => {
set(() => {
const chatModels = models.filter((m) => m.is_default !== false);
- const chatNames = chatModels.map((m) => m.model_name);
- // 优先使用后端返回的 activeModel(默认模型),其次取 chatAvailableModels 第一个
- const selected = (activeModel && chatNames.includes(activeModel))
- ? activeModel
- : chatNames[0] || null;
+ // 优先使用后端返回的 activeModel(默认模型),其次取第一个;有别名时存别名
+ const matchedModel = activeModel ? chatModels.find((m) => m.model_name === activeModel) : null;
+ const selected = matchedModel
+ ? (matchedModel.alias || matchedModel.model_name)
+ : (chatModels[0] ? (chatModels[0].alias || chatModels[0].model_name) : null);
if (selected) {
try { localStorage.setItem(MODEL_STORAGE_KEY, selected); } catch { /* noop */ }
}
diff --git a/jiuwenclaw/web/src/types/index.ts b/jiuwenclaw/web/src/types/index.ts
index bdb125e397..d0c89c4918 100644
--- a/jiuwenclaw/web/src/types/index.ts
+++ b/jiuwenclaw/web/src/types/index.ts
@@ -38,6 +38,8 @@ export interface ModelEntry {
temperature?: number;
/** 同 model_name 组内的默认勾选标识 */
is_default?: boolean;
+ /** 可选别名,用于快捷切换模型(如 "mimo" → "xiaomi/mimo-v2-omni") */
+ alias?: string;
/** 用于原子性重命名操作,指定原模型名 */
original_model_name?: string;
}