Skip to content

Agent Zero AI framework

refactor(_model_config): extract reusable model-field component, split store into mixins, unify API key lifecycle

keyboardstaff9ff4133d7de9
diff --git a/plugins/_model_config/webui/api-keys-mixin.js b/plugins/_model_config/webui/api-keys-mixin.js
new file mode 100644
index 000000000..04a3cad08
--- /dev/null
+++ b/plugins/_model_config/webui/api-keys-mixin.js
@@ -0,0 +1,161 @@
+const API_BASE = "/plugins/_model_config";
+
+export const apiKeysState = {
+ apiKeyStatus: {},
+ apiKeyValues: {},
+ apiKeyDirty: {},
+ allProviders: [],
+};
+
+export const apiKeysMethods = {
+ _setProviderHasKey(provider, hasKey) {
+ if (!provider) return;
+ this.apiKeyStatus = { ...this.apiKeyStatus, [provider]: !!hasKey };
+ const normalized = provider.toLowerCase();
+ this.allProviders = (this.allProviders || []).map((item) =>
+ item.value?.toLowerCase() === normalized ? { ...item, has_key: !!hasKey } : item
+ );
+ },
+
+ _ensureApiKeySlot(provider) {
+ if (!provider) return;
+ if (!(provider in this.apiKeyValues)) {
+ this.apiKeyValues = { ...this.apiKeyValues, [provider]: '' };
+ }
+ if (!(provider in this.apiKeyDirty)) {
+ this.apiKeyDirty = { ...this.apiKeyDirty, [provider]: false };
+ }
+ },
+
+ _setApiKeyDirty(provider, isDirty) {
+ if (!provider) return;
+ this._ensureApiKeySlot(provider);
+ this.apiKeyDirty = { ...this.apiKeyDirty, [provider]: !!isDirty };
+ },
+
+ touchApiKey(provider) {
+ this._setApiKeyDirty(provider, true);
+ },
+
+ async refreshApiKeyStatus() {
+ await this.ensureLoaded();
+ const res = await fetchApi(`${API_BASE}/api_keys`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'get' })
+ });
+ const data = await res.json();
+ const keys = data.keys || {};
+
+ const nextStatus = { ...this.apiKeyStatus };
+ const nextValues = { ...this.apiKeyValues };
+ const nextDirty = { ...this.apiKeyDirty };
+
+ for (const provider of this.allProviders) {
+ const entry = keys[provider.value] || {};
+ const hasKey = !!entry.has_key;
+ nextStatus[provider.value] = hasKey;
+ provider.has_key = hasKey;
+ if (!(provider.value in nextDirty)) {
+ nextDirty[provider.value] = false;
+ }
+ if (!hasKey && !nextDirty[provider.value]) {
+ nextValues[provider.value] = '';
+ }
+ }
+
+ this.apiKeyStatus = nextStatus;
+ this.apiKeyValues = nextValues;
+ this.apiKeyDirty = nextDirty;
+ this.allProviders = [...this.allProviders];
+ return keys;
+ },
+
+ resetApiKeyDrafts() {
+ const nextValues = {};
+ const nextDirty = {};
+ for (const provider of this.allProviders || []) {
+ if (!provider?.value) continue;
+ nextValues[provider.value] = '';
+ nextDirty[provider.value] = false;
+ }
+ this.apiKeyValues = nextValues;
+ this.apiKeyDirty = nextDirty;
+ },
+
+ async saveApiKeys(updates) {
+ const normalized = {};
+ for (const [provider, value] of Object.entries(updates || {})) {
+ if (!provider || typeof value !== 'string') continue;
+ normalized[provider] = value.trim() ? value : '';
+ }
+
+ if (Object.keys(normalized).length === 0) {
+ return { ok: true };
+ }
+
+ const res = await fetchApi(`${API_BASE}/api_keys`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'set', keys: normalized })
+ });
+ const data = await res.json();
+ if (!data?.ok) {
+ throw new Error(data?.error || 'Failed to save API keys.');
+ }
+
+ const nextValues = { ...this.apiKeyValues };
+ const nextDirty = { ...this.apiKeyDirty };
+ for (const [provider, value] of Object.entries(normalized)) {
+ nextValues[provider] = value;
+ nextDirty[provider] = false;
+ this._setProviderHasKey(provider, !!value.trim());
+ }
+ this.apiKeyValues = nextValues;
+ this.apiKeyDirty = nextDirty;
+ return data;
+ },
+
+ async saveApiKey(provider, value) {
+ return this.saveApiKeys({ [provider]: value });
+ },
+
+ saveApiKeyIfSet(provider) {
+ if (provider in this.apiKeyValues) {
+ return this.saveApiKey(provider, this.apiKeyValues[provider] || '');
+ }
+ },
+
+ async revealApiKey(provider) {
+ const res = await fetchApi(`${API_BASE}/api_keys`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'reveal', provider })
+ });
+ const data = await res.json();
+ if (!data?.ok) {
+ throw new Error(data?.error || 'Failed to load API key.');
+ }
+ const value = data.value || '';
+ if (provider) {
+ this._ensureApiKeySlot(provider);
+ this.apiKeyValues = { ...this.apiKeyValues, [provider]: value };
+ this._setApiKeyDirty(provider, false);
+ this._setProviderHasKey(provider, !!value.trim());
+ }
+ return value;
+ },
+
+ async persistApiKeysForConfig(config) {
+ const updates = {};
+ const seen = new Set();
+ for (const section of this.MODEL_SECTIONS) {
+ const provider = config?.[section.key]?.provider;
+ if (!provider || seen.has(provider) || !this.apiKeyDirty[provider]) continue;
+ seen.add(provider);
+ const value = this.apiKeyValues[provider];
+ updates[provider] = typeof value === 'string' ? value : '';
+ }
+ return this.saveApiKeys(updates);
+ },
+};
diff --git a/plugins/_model_config/webui/api-keys.html b/plugins/_model_config/webui/api-keys.html
index 6a01e2877..09f9c2769 100644
--- a/plugins/_model_config/webui/api-keys.html
+++ b/plugins/_model_config/webui/api-keys.html
@@ -11,35 +11,22 @@
<div x-data>
<template x-if="$store.modelConfig">
<div x-data="{
- keys: {},
- originalKeys: {},
- touched: {},
loading: true,
saving: false,
error: '',
get hasChanges() {
- return Object.keys(this.touched).some((provider) => this.touched[provider]);
+ const dirty = $store.modelConfig.apiKeyDirty;
+ return Object.keys(dirty).some((p) => dirty[p]);
},
async init() {
await $store.modelConfig.ensureLoaded();
$store.modelConfig.resetApiKeyDrafts();
await $store.modelConfig.refreshApiKeyStatus();
- $store.modelConfig.allProviders.forEach((provider) => {
- this.keys[provider.value] = '';
- this.originalKeys[provider.value] = '';
- this.touched[provider.value] = false;
- });
this.loading = false;
},
- markChanged(provider) {
- this.touched[provider] = this.keys[provider] !== this.originalKeys[provider];
- },
async reveal(provider) {
try {
- const value = await $store.modelConfig.revealApiKey(provider);
- this.keys[provider] = value || '';
- this.originalKeys[provider] = value || '';
- this.touched[provider] = false;
+ await $store.modelConfig.revealApiKey(provider);
} catch (e) {
this.error = e?.message || 'Failed to reveal API key.';
}
@@ -49,9 +36,11 @@
this.error = '';
try {
const updates = {};
- for (const provider of Object.keys(this.touched)) {
- if (!this.touched[provider]) continue;
- updates[provider] = this.keys[provider] || '';
+ const dirty = $store.modelConfig.apiKeyDirty;
+ const values = $store.modelConfig.apiKeyValues;
+ for (const provider of Object.keys(dirty)) {
+ if (!dirty[provider]) continue;
+ updates[provider] = values[provider] || '';
}
await $store.modelConfig.saveApiKeys(updates);
await $store.modelConfig.refreshApiKeyStatus();
@@ -89,15 +78,15 @@
</div>
<div class="field-control" style="position:relative;" x-data="{ showKey: false }">
<input :type="showKey ? 'text' : 'password'"
- x-model="keys[provider.value]"
+ x-model="$store.modelConfig.apiKeyValues[provider.value]"
:placeholder="provider.has_key ? '••••••••••••' : ''"
autocomplete="off"
- @input="markChanged(provider.value)"
+ @input="$store.modelConfig.touchApiKey(provider.value)"
style="padding-right:32px;" />
<span class="material-symbols-outlined eye-toggle"
@click="
showKey = !showKey;
- if (showKey && !keys[provider.value] && provider.has_key) {
+ if (showKey && !$store.modelConfig.apiKeyValues[provider.value] && provider.has_key) {
reveal(provider.value);
}
"
diff --git a/plugins/_model_config/webui/config.html b/plugins/_model_config/webui/config.html
index 40753cc40..4c25faf5b 100644
--- a/plugins/_model_config/webui/config.html
+++ b/plugins/_model_config/webui/config.html
@@ -13,242 +13,18 @@
$store.modelConfig.resetApiKeyDrafts();
await $store.modelConfig.refreshApiKeyStatus();
$store.modelConfig.initConfigFields(config);
- $store.modelConfig.installPluginSettingsSaveHook(context, config);
- const _origReset = context.resetToDefault.bind(context);
- context.resetToDefault = async () => {
- const before = context.settings;
- await _origReset();
- if (context.settings !== before) {
- await $store.modelConfig.resetGlobalPresets();
- }
- };
+ $store.modelConfig.installSettingsHooks(context, config);
">
<template x-if="config && $store.modelConfig._loaded">
<div class="model-config-sections">
<!-- Model Sections (Main, Utility, Embedding) -->
<template x-for="section in $store.modelConfig.MODEL_SECTIONS" :key="section.key">
- <div class="model-section">
+ <div class="model-section"
+ x-data="{ model: config[section.key], modelType: section.key.replace('_model', ''), providers: $store.modelConfig.getProviders(section.key), searchType: $store.modelConfig.getSearchType(section.key), apiKeyMode: 'store' }">
<div class="section-title" x-text="section.title"></div>
<div class="section-description" x-text="section.desc"></div>
-
- <!-- Provider -->
- <div class="field">
- <div class="field-label">
- <div class="field-title">Provider</div>
- <div class="field-description">LLM service provider for this model slot.</div>
- </div>
- <div class="field-control">
- <select x-model="config[section.key].provider"
- x-effect="$nextTick(() => { if ($store.modelConfig.getProviders(section.key).length) $el.value = config[section.key].provider })">
- <template x-for="p in $store.modelConfig.getProviders(section.key)" :key="p.value">
- <option :value="p.value" x-text="p.label"></option>
- </template>
- </select>
- </div>
- </div>
-
- <!-- Model name + search -->
- <div class="field">
- <div class="field-label">
- <div class="field-title">Model name</div>
- <div class="field-description">Model identifier. Click the search icon to browse available models.</div>
- </div>
- <div class="field-control" style="position:relative;"
- x-data="{ results: [], open: false, searching: false,
- doSearch() { this.searching = true; $store.modelConfig.searchModels(config[section.key].provider, config[section.key].name, $store.modelConfig.getSearchType(section.key), config[section.key].api_base).then(r => { this.results = r; this.open = true; }).finally(() => this.searching = false); },
- grouped() { return $store.modelConfig.groupResults(this.results, config[section.key].name); }
- }"
- @click.outside="open = false">
- <input type="text" x-model="config[section.key].name" style="padding-right:32px;"
- @keydown.enter.prevent="doSearch()" />
- <span class="model-search-btn"
- @click="if (!searching) doSearch()"
- title="Search available models">
- <span class="material-symbols-outlined" :style="searching && 'opacity:0'">search</span>
- <span class="material-symbols-outlined model-search-spinner" :style="!searching && 'opacity:0'">progress_activity</span>
- </span>
- <div class="model-search-results" x-show="open && results.length > 0" x-transition.opacity>
- <template x-for="m in grouped().matched" :key="'m_'+m">
- <div class="model-search-item matched" @click="config[section.key].name = m; open = false;" x-text="m"></div>
- </template>
- <div class="model-search-separator" x-show="grouped().matched.length > 0 && grouped().rest.length > 0"></div>
- <template x-for="m in grouped().rest" :key="'r_'+m">
- <div class="model-search-item" @click="config[section.key].name = m; open = false;" x-text="m"></div>
- </template>
- </div>
- <div class="model-search-results" x-show="open && results.length === 0 && !searching">
- <div class="model-search-item disabled">No models found</div>
- </div>
- </div>
- </div>
-
- <!-- API key + eye toggle -->
- <div class="field">
- <div class="field-label">
- <div class="field-title">API key</div>
- <div class="field-description">Authentication key for this provider. Shared across all model slots using the same provider.</div>
- </div>
- <div class="field-control" style="position:relative;" x-data="{ showKey: false }">
- <input :type="showKey ? 'text' : 'password'"
- x-model="$store.modelConfig.apiKeyValues[config[section.key].provider]"
- :placeholder="$store.modelConfig.apiKeyStatus[config[section.key].provider] ? '&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;' : ''"
- autocomplete="off"
- @input="$store.modelConfig.touchApiKey(config[section.key].provider)"
- style="padding-right:32px;" />
- <span class="material-symbols-outlined eye-toggle"
- @click="
- showKey = !showKey;
- const prov = config[section.key].provider;
- if (showKey && !$store.modelConfig.apiKeyValues[prov] && $store.modelConfig.apiKeyStatus[prov]) {
- $store.modelConfig.revealApiKey(prov).then(v => { if (v) $store.modelConfig.apiKeyValues[prov] = v; });
- }
- "
- x-text="showKey ? 'visibility' : 'visibility_off'"></span>
- </div>
- </div>
-
- <!-- API base URL -->
- <div class="field">
- <div class="field-label">
- <div class="field-title">API base URL</div>
- <div class="field-description">
- Custom endpoint URL. Leave empty to use the provider's default.
- </div>
- </div>
- <div class="field-control">
- <input type="text" x-model="config[section.key].api_base" />
- </div>
- </div>
-
- <!-- Context length -->
- <template x-if="section.key !== 'embedding_model'">
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context length</div>
- <div class="field-description">
- Maximum number of tokens in the context window. System prompt, chat history, RAG and response all count towards this limit.
- </div>
- </div>
- <div class="field-control">
- <input type="number" x-model.number="config[section.key].ctx_length" />
- </div>
- </div>
- </template>
-
- <!-- Context history -->
- <template x-if="section.key === 'chat_model'">
- <div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context window space for chat history</div>
- <div class="field-description">
- Portion of context window dedicated to chat history visible to the agent. Smaller size will result in shorter and more summarized history.
- </div>
- </div>
- <div class="field-control">
- <input type="range" min="0.01" max="1" step="0.01" x-model.number="config.chat_model.ctx_history" />
- <span class="range-value" x-text="config.chat_model.ctx_history"></span>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Supports Vision</div>
- <div class="field-description">
- Models capable of Vision can for example natively see the content of image attachments.
- </div>
- </div>
- <div class="field-control">
- <label class="toggle">
- <input type="checkbox" x-model="config.chat_model.vision" />
- <span class="toggler"></span>
- </label>
- </div>
- </div>
- <template x-if="config.chat_model.vision">
- <div class="field">
- <div class="field-label">
- <div class="field-title">Max embeds</div>
- <div class="field-description">
- Maximum number of embedded images used by the chat model. Set to 0 for unlimited.
- </div>
- </div>
- <div class="field-control">
- <input type="number" min="0" x-model.number="config.chat_model.max_embeds" x-init="if (!config.chat_model.max_embeds) config.chat_model.max_embeds = 10" />
- </div>
- </div>
- </template>
- </div>
- </template>
-
- <!-- Context input slider -->
- <template x-if="section.key === 'utility_model'">
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context window space for utility model input</div>
- <div class="field-description">Portion of context window used for utility model input messages.</div>
- </div>
- <div class="field-control">
- <input type="range" min="0.01" max="1" step="0.01" x-model.number="config.utility_model.ctx_input" />
- <span class="range-value" x-text="config.utility_model.ctx_input"></span>
- </div>
- </div>
- </template>
-
- <!-- Rate limits -->
- <div class="field">
- <div class="field-label">
- <div class="field-title">Requests per minute limit</div>
- <div class="field-description">
- Limits the number of requests per minute. Waits if the limit is exceeded. Set to 0 to disable.
- </div>
- </div>
- <div class="field-control">
- <input type="number" x-model.number="config[section.key].rl_requests" />
- </div>
- </div>
-
- <div class="field">
- <div class="field-label">
- <div class="field-title">Input tokens per minute limit</div>
- <div class="field-description">
- Limits the number of input tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.
- </div>
- </div>
- <div class="field-control">
- <input type="number" x-model.number="config[section.key].rl_input" />
- </div>
- </div>
-
- <template x-if="section.key !== 'embedding_model'">
- <div class="field">
- <div class="field-label">
- <div class="field-title">Output tokens per minute limit</div>
- <div class="field-description">
- Limits the number of output tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.
- </div>
- </div>
- <div class="field-control">
- <input type="number" x-model.number="config[section.key].rl_output" />
- </div>
- </div>
- </template>
-
- <!-- Additional parameters -->
- <div class="field field-full">
- <div class="field-label">
- <div class="field-title">Additional parameters</div>
- <div class="field-description">
- Any other parameters supported by <a href='https://docs.litellm.ai/docs/set_keys' target='_blank'>LiteLLM</a>. Format is KEY=VALUE on individual lines. Value can be JSON objects; unquoted is treated as object/number, quoted as string.
- </div>
- </div>
- <div class="field-control">
- <textarea x-model="config[section.key]._kwargs_text"
- @change="config[section.key].kwargs = $store.modelConfig.textToKwargs(config[section.key]._kwargs_text)"></textarea>
- </div>
- </div>
-
-
+ <x-component path="/plugins/_model_config/webui/model-field.html"></x-component>
</div>
</template>
@@ -302,91 +78,7 @@
font-size: 0.78rem;
gap: 4px;
}
- .eye-toggle {
- position: absolute;
- right: 8px;
- top: 50%;
- transform: translateY(-50%);
- font-size: 18px;
- cursor: pointer;
- user-select: none;
- opacity: 0.6;
- z-index: 1;
- }
- .eye-toggle:hover {
- opacity: 1;
- }
- /* Model search */
- .model-search-btn {
- position: absolute;
- right: 8px;
- top: 50%;
- transform: translateY(-50%);
- width: 20px;
- height: 20px;
- display: grid;
- place-items: center;
- cursor: pointer;
- user-select: none;
- opacity: 0.6;
- z-index: 1;
- }
- .model-search-btn:hover {
- opacity: 1;
- }
- .model-search-btn > span {
- grid-area: 1 / 1;
- font-size: 18px;
- transition: opacity 0.15s;
- }
- .model-search-spinner {
- animation: spin 0.8s linear infinite;
- }
- @keyframes spin {
- from { transform: rotate(0deg); }
- to { transform: rotate(360deg); }
- }
- .model-search-results {
- position: absolute;
- top: calc(100% + 4px);
- left: 0;
- right: 0;
- max-height: 200px;
- overflow-y: auto;
- background: var(--color-input);
- border: 1px solid var(--color-border);
- border-radius: 6px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
- z-index: 50;
- padding: 4px;
- }
- .model-search-item {
- padding: 5px 8px;
- font-size: 0.8rem;
- border-radius: 4px;
- cursor: pointer;
- word-break: break-all;
- }
- .model-search-item:hover {
- background: var(--color-background-hover, rgba(255,255,255,0.06));
- }
- .model-search-item.disabled {
- opacity: 0.4;
- cursor: default;
- font-style: italic;
- }
- .model-search-item.matched {
- font-weight: 500;
- }
- .model-search-separator {
- height: 1px;
- margin: 4px 8px;
- background: var(--color-border);
- opacity: 0.5;
- }
- .model-search-item.disabled:hover {
- background: transparent;
- }
+
</style>
</body>
</html>
diff --git a/plugins/_model_config/webui/main.html b/plugins/_model_config/webui/main.html
index 4fafd1fa7..46c853323 100644
--- a/plugins/_model_config/webui/main.html
+++ b/plugins/_model_config/webui/main.html
@@ -46,270 +46,13 @@
</div>
<div class="preset-subheader">Main Model</div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Provider</div>
- <div class="field-description">LLM service provider for this preset's main model.</div>
- </div>
- <div class="field-control">
- <select x-model="preset.chat.provider"
- x-effect="$nextTick(() => { if ($store.modelConfig.chatProviders.length) $el.value = preset.chat.provider })">
- <option value="">&#x2014; select &#x2014;</option>
- <template x-for="p in $store.modelConfig.chatProviders" :key="p.value">
- <option :value="p.value" x-text="p.label"></option>
- </template>
- </select>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Model name</div>
- <div class="field-description">Model identifier. Click the search icon to browse available models.</div>
- </div>
- <div class="field-control" style="position:relative;"
- x-data="{ results: [], open: false, searching: false,
- doSearch() { this.searching = true; $store.modelConfig.searchModels(preset.chat.provider, preset.chat.name, 'chat', preset.chat.api_base).then(r => { this.results = r; this.open = true; }).finally(() => this.searching = false); },
- grouped() { return $store.modelConfig.groupResults(this.results, preset.chat.name); }
- }"
- @click.outside="open = false">
- <input type="text" x-model="preset.chat.name" style="padding-right:32px;"
- @keydown.enter.prevent="doSearch()" />
- <span class="model-search-btn"
- @click="if (!searching) doSearch()"
- title="Search available models">
- <span class="material-symbols-outlined" :style="searching && 'opacity:0'">search</span>
- <span class="material-symbols-outlined model-search-spinner" :style="!searching && 'opacity:0'">progress_activity</span>
- </span>
- <div class="model-search-results" x-show="open && results.length > 0" x-transition.opacity>
- <template x-for="m in grouped().matched" :key="'m_'+m">
- <div class="model-search-item matched" @click="preset.chat.name = m; open = false;" x-text="m"></div>
- </template>
- <div class="model-search-separator" x-show="grouped().matched.length > 0 && grouped().rest.length > 0"></div>
- <template x-for="m in grouped().rest" :key="'r_'+m">
- <div class="model-search-item" @click="preset.chat.name = m; open = false;" x-text="m"></div>
- </template>
- </div>
- <div class="model-search-results" x-show="open && results.length === 0 && !searching">
- <div class="model-search-item disabled">No models found</div>
- </div>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">API key</div>
- <div class="field-description">Authentication key for this provider. Shared across all model slots using the same provider.</div>
- </div>
- <div class="field-control" style="position:relative;" x-data="{ showKey: false, _revealed: '' }">
- <input :type="showKey ? 'text' : 'password'" x-model="preset.chat.api_key" autocomplete="off"
- :placeholder="$store.modelConfig.apiKeyStatus[preset.chat.provider] ? '&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;' : ''"
- style="padding-right:32px;" />
- <span class="material-symbols-outlined eye-toggle"
- @click="
- showKey = !showKey;
- if (showKey && !preset.chat.api_key && $store.modelConfig.apiKeyStatus[preset.chat.provider]) {
- $store.modelConfig.revealApiKey(preset.chat.provider).then(v => { if (v) { preset.chat.api_key = v; _revealed = v; } });
- }
- if (!showKey && _revealed && preset.chat.api_key === _revealed) {
- preset.chat.api_key = ''; _revealed = '';
- }
- "
- x-text="showKey ? 'visibility' : 'visibility_off'"></span>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">API base URL</div>
- <div class="field-description">Custom endpoint URL. Leave empty for the provider's default.</div>
- </div>
- <div class="field-control"><input type="text" x-model="preset.chat.api_base" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context length</div>
- <div class="field-description">Maximum number of tokens in the context window. System prompt, chat history, RAG and response all count towards this limit.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.chat.ctx_length" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context window space for chat history</div>
- <div class="field-description">Portion of context window dedicated to chat history visible to the agent. Smaller size will result in shorter and more summarized history.</div>
- </div>
- <div class="field-control">
- <input type="range" min="0.01" max="1" step="0.01" x-model.number="preset.chat.ctx_history" />
- <span class="range-value" x-text="preset.chat.ctx_history || ''"></span>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Supports Vision</div>
- <div class="field-description">Models capable of Vision can for example natively see the content of image attachments.</div>
- </div>
- <div class="field-control">
- <label class="toggle">
- <input type="checkbox" x-model="preset.chat.vision" />
- <span class="toggler"></span>
- </label>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Requests per minute limit</div>
- <div class="field-description">Limits the number of requests per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.chat.rl_requests" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Input tokens per minute limit</div>
- <div class="field-description">Limits the number of input tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.chat.rl_input" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Output tokens per minute limit</div>
- <div class="field-description">Limits the number of output tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.chat.rl_output" /></div>
- </div>
- <div class="field field-full">
- <div class="field-label">
- <div class="field-title">Additional parameters</div>
- <div class="field-description">Any other parameters supported by <a href='https://docs.litellm.ai/docs/set_keys' target='_blank'>LiteLLM</a>. Format is KEY=VALUE on individual lines. Value can be JSON objects; unquoted is treated as object/number, quoted as string.</div>
- </div>
- <div class="field-control">
- <textarea x-model="preset.chat._kwargs_text"
- @change="preset.chat.kwargs = $store.modelConfig.textToKwargs(preset.chat._kwargs_text)"></textarea>
- </div>
+ <div x-data="{ model: preset.chat, modelType: 'chat', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'inline' }">
+ <x-component path="/plugins/_model_config/webui/model-field.html"></x-component>
</div>
<div class="preset-subheader">Utility Model <span style="opacity:0.5; font-size:0.75rem;">(optional &#x2014; falls back to the configured Utility Model)</span></div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Provider</div>
- <div class="field-description">Leave empty to use the configured Utility Model provider.</div>
- </div>
- <div class="field-control">
- <select x-model="preset.utility.provider"
- x-effect="$nextTick(() => { if ($store.modelConfig.chatProviders.length) $el.value = preset.utility.provider })">
- <option value="">&#x2014; select &#x2014;</option>
- <template x-for="p in $store.modelConfig.chatProviders" :key="p.value">
- <option :value="p.value" x-text="p.label"></option>
- </template>
- </select>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Model name</div>
- <div class="field-description">Leave empty to use the configured Utility Model.</div>
- </div>
- <div class="field-control" style="position:relative;"
- x-data="{ results: [], open: false, searching: false,
- doSearch() { this.searching = true; $store.modelConfig.searchModels(preset.utility.provider || preset.chat.provider, preset.utility.name, 'chat', preset.utility.api_base || preset.chat.api_base).then(r => { this.results = r; this.open = true; }).finally(() => this.searching = false); },
- grouped() { return $store.modelConfig.groupResults(this.results, preset.utility.name); }
- }"
- @click.outside="open = false">
- <input type="text" x-model="preset.utility.name" style="padding-right:32px;"
- @keydown.enter.prevent="doSearch()" />
- <span class="model-search-btn"
- @click="if (!searching) doSearch()"
- title="Search available models">
- <span class="material-symbols-outlined" :style="searching && 'opacity:0'">search</span>
- <span class="material-symbols-outlined model-search-spinner" :style="!searching && 'opacity:0'">progress_activity</span>
- </span>
- <div class="model-search-results" x-show="open && results.length > 0" x-transition.opacity>
- <template x-for="m in grouped().matched" :key="'m_'+m">
- <div class="model-search-item matched" @click="preset.utility.name = m; open = false;" x-text="m"></div>
- </template>
- <div class="model-search-separator" x-show="grouped().matched.length > 0 && grouped().rest.length > 0"></div>
- <template x-for="m in grouped().rest" :key="'r_'+m">
- <div class="model-search-item" @click="preset.utility.name = m; open = false;" x-text="m"></div>
- </template>
- </div>
- <div class="model-search-results" x-show="open && results.length === 0 && !searching">
- <div class="model-search-item disabled">No models found</div>
- </div>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">API key</div>
- <div class="field-description">Authentication key for this provider. Shared across all model slots using the same provider.</div>
- </div>
- <div class="field-control" style="position:relative;" x-data="{ showKey: false, _revealed: '' }">
- <input :type="showKey ? 'text' : 'password'" x-model="preset.utility.api_key" autocomplete="off"
- :placeholder="$store.modelConfig.apiKeyStatus[preset.utility.provider || preset.chat.provider] ? '&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;' : ''"
- style="padding-right:32px;" />
- <span class="material-symbols-outlined eye-toggle"
- @click="
- const prov = preset.utility.provider || preset.chat.provider;
- showKey = !showKey;
- if (showKey && !preset.utility.api_key && $store.modelConfig.apiKeyStatus[prov]) {
- $store.modelConfig.revealApiKey(prov).then(v => { if (v) { preset.utility.api_key = v; _revealed = v; } });
- }
- if (!showKey && _revealed && preset.utility.api_key === _revealed) {
- preset.utility.api_key = ''; _revealed = '';
- }
- "
- x-text="showKey ? 'visibility' : 'visibility_off'"></span>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">API base URL</div>
- <div class="field-description">Custom endpoint URL. Leave empty for the provider's default.</div>
- </div>
- <div class="field-control"><input type="text" x-model="preset.utility.api_base" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context length</div>
- <div class="field-description">Maximum number of tokens in the context window. System prompt, chat history, RAG and response all count towards this limit.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.utility.ctx_length" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Context window space for utility input</div>
- <div class="field-description">Portion of context window used for utility model input messages.</div>
- </div>
- <div class="field-control">
- <input type="range" min="0.01" max="1" step="0.01" x-model.number="preset.utility.ctx_input" />
- <span class="range-value" x-text="preset.utility.ctx_input || ''"></span>
- </div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Requests per minute limit</div>
- <div class="field-description">Limits the number of requests per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.utility.rl_requests" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Input tokens per minute limit</div>
- <div class="field-description">Limits the number of input tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.utility.rl_input" /></div>
- </div>
- <div class="field">
- <div class="field-label">
- <div class="field-title">Output tokens per minute limit</div>
- <div class="field-description">Limits the number of output tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
- </div>
- <div class="field-control"><input type="number" x-model.number="preset.utility.rl_output" /></div>
- </div>
- <div class="field field-full">
- <div class="field-label">
- <div class="field-title">Additional parameters</div>
- <div class="field-description">Any other parameters supported by <a href='https://docs.litellm.ai/docs/set_keys' target='_blank'>LiteLLM</a>. Format is KEY=VALUE on individual lines. Value can be JSON objects; unquoted is treated as object/number, quoted as string.</div>
- </div>
- <div class="field-control">
- <textarea x-model="preset.utility._kwargs_text"
- @change="preset.utility.kwargs = $store.modelConfig.textToKwargs(preset.utility._kwargs_text)"></textarea>
- </div>
+ <div x-data="{ model: preset.utility, modelType: 'utility', providers: $store.modelConfig.chatProviders, searchType: 'chat', apiKeyMode: 'inline', providerFallback: preset.chat.provider, apiBaseFallback: preset.chat.api_base }">
+ <x-component path="/plugins/_model_config/webui/model-field.html"></x-component>
</div>
</div>
</div>
@@ -418,88 +161,7 @@
align-items: center;
margin-top: 4px;
}
- .eye-toggle {
- position: absolute;
- right: 8px;
- top: 50%;
- transform: translateY(-50%);
- font-size: 18px;
- cursor: pointer;
- user-select: none;
- opacity: 0.6;
- z-index: 1;
- }
- .eye-toggle:hover {
- opacity: 1;
- }
- /* Model search */
- .model-search-btn {
- position: absolute;
- right: 8px;
- top: 50%;
- transform: translateY(-50%);
- width: 20px;
- height: 20px;
- display: grid;
- place-items: center;
- cursor: pointer;
- user-select: none;
- opacity: 0.6;
- z-index: 1;
- }
- .model-search-btn:hover {
- opacity: 1;
- }
- .model-search-btn > span {
- grid-area: 1 / 1;
- font-size: 18px;
- transition: opacity 0.15s;
- }
- .model-search-spinner {
- animation: spin 0.8s linear infinite;
- }
- @keyframes spin {
- from { transform: rotate(0deg); }
- to { transform: rotate(360deg); }
- }
- .model-search-results {
- position: absolute;
- top: calc(100% + 4px);
- left: 0;
- right: 0;
- max-height: 200px;
- overflow-y: auto;
- background: var(--color-input);
- border: 1px solid var(--color-border);
- border-radius: 6px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
- z-index: 50;
- padding: 4px;
- }
- .model-search-item {
- padding: 5px 8px;
- font-size: 0.8rem;
- border-radius: 4px;
- cursor: pointer;
- word-break: break-all;
- }
- .model-search-item:hover {
- background: var(--color-background-hover, rgba(255,255,255,0.06));
- }
- .model-search-item.disabled {
- opacity: 0.4;
- cursor: default;
- font-style: italic;
- }
- .model-search-item.matched {
- font-weight: 500;
- }
- .model-search-separator {
- height: 1px;
- margin: 4px 8px;
- background: var(--color-border);
- opacity: 0.5;
- }
+
</style>
</body>
</html>
diff --git a/plugins/_model_config/webui/model-config-store.js b/plugins/_model_config/webui/model-config-store.js
index 1256c4896..b4a3ed0e4 100644
--- a/plugins/_model_config/webui/model-config-store.js
+++ b/plugins/_model_config/webui/model-config-store.js
@@ -1,5 +1,7 @@
import { createStore } from "/js/AlpineStore.js";
import { store as pluginSettingsStore } from "/components/plugins/plugin-settings-store.js";
+import { apiKeysState, apiKeysMethods } from "/plugins/_model_config/webui/api-keys-mixin.js";
+import { switcherState, switcherMethods } from "/plugins/_model_config/webui/switcher-mixin.js";
export const MODEL_SECTIONS = [
@@ -48,61 +50,36 @@ export function textToHeaders(text) {
const API_BASE = "/plugins/_model_config";
export const store = createStore("modelConfig", {
- // Shared state
+ // Core state
chatProviders: [],
embeddingProviders: [],
- apiKeyStatus: {},
- apiKeyValues: {},
- apiKeyDirty: {},
- allProviders: [],
_loaded: false,
+ // API Keys state (from mixin)
+ ...apiKeysState,
+
// Global presets state
globalPresets: [],
_presetsLoaded: false,
- // Settings include summary state
+ // Model summary state
modelsSummary: [],
modelsSummaryLoading: false,
_modelsSummaryLoaded: false,
_modelsSummaryPromise: null,
- // Switcher state
- switcherAllowed: false,
- switcherOverride: null,
- switcherPresets: [],
- switcherLoading: true,
+ // Switcher state (from mixin)
+ ...switcherState,
init() {},
- _setProviderHasKey(provider, hasKey) {
- if (!provider) return;
- this.apiKeyStatus = { ...this.apiKeyStatus, [provider]: !!hasKey };
- const normalized = provider.toLowerCase();
- this.allProviders = (this.allProviders || []).map((item) =>
- item.value?.toLowerCase() === normalized ? { ...item, has_key: !!hasKey } : item
- );
- },
-
- _ensureApiKeySlot(provider) {
- if (!provider) return;
- if (!(provider in this.apiKeyValues)) {
- this.apiKeyValues = { ...this.apiKeyValues, [provider]: '' };
- }
- if (!(provider in this.apiKeyDirty)) {
- this.apiKeyDirty = { ...this.apiKeyDirty, [provider]: false };
- }
- },
+ // ── API Keys methods (from mixin) ──
+ ...apiKeysMethods,
- _setApiKeyDirty(provider, isDirty) {
- if (!provider) return;
- this._ensureApiKeySlot(provider);
- this.apiKeyDirty = { ...this.apiKeyDirty, [provider]: !!isDirty };
- },
+ // ── Switcher methods (from mixin) ──
+ ...switcherMethods,
- touchApiKey(provider) {
- this._setApiKeyDirty(provider, true);
- },
+ // ── Core methods ──
_normalizePresets(rawPresets) {
return (rawPresets || []).map(p => ({
@@ -143,52 +120,6 @@ export const store = createStore("modelConfig", {
this._loaded = true;
},
- async refreshApiKeyStatus() {
- await this.ensureLoaded();
- const res = await fetchApi(`${API_BASE}/api_keys`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'get' })
- });
- const data = await res.json();
- const keys = data.keys || {};
-
- const nextStatus = { ...this.apiKeyStatus };
- const nextValues = { ...this.apiKeyValues };
- const nextDirty = { ...this.apiKeyDirty };
-
- for (const provider of this.allProviders) {
- const entry = keys[provider.value] || {};
- const hasKey = !!entry.has_key;
- nextStatus[provider.value] = hasKey;
- provider.has_key = hasKey;
- if (!(provider.value in nextDirty)) {
- nextDirty[provider.value] = false;
- }
- if (!hasKey && !nextDirty[provider.value]) {
- nextValues[provider.value] = '';
- }
- }
-
- this.apiKeyStatus = nextStatus;
- this.apiKeyValues = nextValues;
- this.apiKeyDirty = nextDirty;
- this.allProviders = [...this.allProviders];
- return keys;
- },
-
- resetApiKeyDrafts() {
- const nextValues = {};
- const nextDirty = {};
- for (const provider of this.allProviders || []) {
- if (!provider?.value) continue;
- nextValues[provider.value] = '';
- nextDirty[provider.value] = false;
- }
- this.apiKeyValues = nextValues;
- this.apiKeyDirty = nextDirty;
- },
-
async _fetchConfigData() {
const res = await fetchApi(`${API_BASE}/model_config_get`, {
method: 'POST',
@@ -265,85 +196,14 @@ export const store = createStore("modelConfig", {
}
},
- // API Key operations
- async saveApiKeys(updates) {
- const normalized = {};
- for (const [provider, value] of Object.entries(updates || {})) {
- if (!provider || typeof value !== 'string') continue;
- normalized[provider] = value.trim() ? value : '';
- }
-
- if (Object.keys(normalized).length === 0) {
- return { ok: true };
- }
-
- const res = await fetchApi(`${API_BASE}/api_keys`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'set', keys: normalized })
- });
- const data = await res.json();
- if (!data?.ok) {
- throw new Error(data?.error || 'Failed to save API keys.');
- }
-
- const nextValues = { ...this.apiKeyValues };
- const nextDirty = { ...this.apiKeyDirty };
- for (const [provider, value] of Object.entries(normalized)) {
- nextValues[provider] = value;
- nextDirty[provider] = false;
- this._setProviderHasKey(provider, !!value.trim());
- }
- this.apiKeyValues = nextValues;
- this.apiKeyDirty = nextDirty;
- return data;
- },
-
- async saveApiKey(provider, value) {
- return this.saveApiKeys({ [provider]: value });
- },
-
- saveApiKeyIfSet(provider) {
- if (provider in this.apiKeyValues) {
- return this.saveApiKey(provider, this.apiKeyValues[provider] || '');
- }
- },
-
- async revealApiKey(provider) {
- const res = await fetchApi(`${API_BASE}/api_keys`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'reveal', provider })
- });
- const data = await res.json();
- if (!data?.ok) {
- throw new Error(data?.error || 'Failed to load API key.');
- }
- const value = data.value || '';
- if (provider) {
- this._ensureApiKeySlot(provider);
- this.apiKeyValues = { ...this.apiKeyValues, [provider]: value };
- this._setApiKeyDirty(provider, false);
- this._setProviderHasKey(provider, !!value.trim());
- }
- return value;
- },
-
- async persistApiKeysForConfig(config) {
- const updates = {};
- const seen = new Set();
- for (const section of this.MODEL_SECTIONS) {
- const provider = config?.[section.key]?.provider;
- if (!provider || seen.has(provider) || !this.apiKeyDirty[provider]) continue;
- seen.add(provider);
- const value = this.apiKeyValues[provider];
- updates[provider] = typeof value === 'string' ? value : '';
- }
- return this.saveApiKeys(updates);
- },
+ /**
+ * Install save and reset hooks on the plugin settings context.
+ * - Save: persists dirty API keys before the normal config save.
+ * - Reset: reloads global presets when settings are reset to defaults.
+ */
+ installSettingsHooks(context, config) {
+ if (!context || context.__modelConfigHooksInstalled) return;
- installPluginSettingsSaveHook(context, config) {
- if (!context || context.__modelConfigSaveHookInstalled) return;
const originalSave = context.save.bind(context);
context.save = async () => {
context.error = null;
@@ -355,7 +215,17 @@ export const store = createStore("modelConfig", {
}
await originalSave();
};
- context.__modelConfigSaveHookInstalled = true;
+
+ const originalReset = context.resetToDefault.bind(context);
+ context.resetToDefault = async () => {
+ const before = context.settings;
+ await originalReset();
+ if (context.settings !== before) {
+ await this.resetGlobalPresets();
+ }
+ };
+
+ context.__modelConfigHooksInstalled = true;
},
// Model search
@@ -395,68 +265,6 @@ export const store = createStore("modelConfig", {
return { matched, rest };
},
- // Model Switcher
- async loadSwitcherState(contextId) {
- const result = { allowed: false, presets: [], override: null };
- try {
- await this.loadGlobalPresets();
- result.presets = this.globalPresets.filter(p => p.name);
- if (contextId) {
- const overRes = await fetchApi(`${API_BASE}/model_override`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ action: "get", context_id: contextId }),
- });
- const overData = await overRes.json();
- result.allowed = !!overData.allowed;
- result.override = overData.override || null;
- }
- } catch (e) {
- console.error("Model switcher load failed:", e);
- }
- return result;
- },
-
- async setPresetOverride(contextId, presetName) {
- try {
- const res = await fetchApi(`${API_BASE}/model_override`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ action: "set_preset", context_id: contextId, preset_name: presetName }),
- });
- return !!(await res.json()).ok;
- } catch (e) {
- console.error("Failed to set preset override:", e);
- return false;
- }
- },
-
- async clearOverride(contextId) {
- try {
- const res = await fetchApi(`${API_BASE}/model_override`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ action: "clear", context_id: contextId }),
- });
- return !!(await res.json()).ok;
- } catch (e) {
- console.error("Failed to clear override:", e);
- return false;
- }
- },
-
- getPresetLabel(preset) {
- return preset?.name || "Unnamed";
- },
-
- getPresetSummary(preset) {
- if (!preset) return "";
- const parts = [];
- if (preset.chat?.name) parts.push(preset.chat.name);
- if (preset.utility?.name) parts.push(preset.utility.name);
- return parts.join(" / ");
- },
-
// Model summary for agent-settings page
async loadModelsSummary() {
const data = await this._fetchConfigData();
@@ -524,54 +332,6 @@ export const store = createStore("modelConfig", {
}
},
- // Switcher high-level methods
- async refreshSwitcher(contextId) {
- this.switcherLoading = true;
- try {
- const state = await this.loadSwitcherState(contextId);
- this.switcherAllowed = state.allowed;
- this.switcherPresets = state.presets;
- this.switcherOverride = state.override;
- } catch (e) {
- console.error('Model switcher refresh failed:', e);
- } finally {
- this.switcherLoading = false;
- }
- },
-
- async selectPresetSwitch(contextId, presetName) {
- const ok = await this.setPresetOverride(contextId, presetName);
- if (ok) this.switcherOverride = { preset_name: presetName };
- return ok;
- },
-
- async clearOverrideSwitch(contextId) {
- const ok = await this.clearOverride(contextId);
- if (ok) this.switcherOverride = null;
- return ok;
- },
-
- getSwitcherLabel() {
- const o = this.switcherOverride;
- if (!o) return 'Default LLM';
- return o.preset_name || o.name || o.provider || 'Custom';
- },
-
- getActivePreset() {
- const o = this.switcherOverride;
- if (!o || !o.preset_name) return null;
- return this.switcherPresets.find(p => p.name === o.preset_name) || null;
- },
-
- getActiveModels() {
- const preset = this.getActivePreset();
- if (!preset) return { main: null, utility: null };
- return {
- main: preset.chat?.name ? { provider: preset.chat.provider, name: preset.chat.name } : null,
- utility: preset.utility?.name ? { provider: preset.utility.provider, name: preset.utility.name } : null,
- };
- },
-
// Text conversion utilities (accessible from templates via $store.modelConfig)
textToKwargs,
textToHeaders,
diff --git a/plugins/_model_config/webui/model-field.html b/plugins/_model_config/webui/model-field.html
new file mode 100644
index 000000000..2186d49f6
--- /dev/null
+++ b/plugins/_model_config/webui/model-field.html
@@ -0,0 +1,338 @@
+<html>
+<head>
+ <script type="module">
+ import { store } from "/plugins/_model_config/webui/model-config-store.js";
+ </script>
+</head>
+
+<body>
+ <!--
+ Reusable model configuration field set.
+ Parent x-data scope must provide:
+ model — reactive object with provider, name, api_key, api_base, ctx_length, ctx_history, ctx_input, vision, max_embeds, rl_requests, rl_input, rl_output, kwargs, _kwargs_text
+ modelType — 'chat' | 'utility' | 'embedding'
+ providers — array of { value, label }
+ searchType — 'chat' | 'embedding'
+ apiKeyMode — 'store' (config.html: key lives in $store.modelConfig.apiKeyValues) | 'inline' (preset: key lives in model.api_key)
+ Optional:
+ providerFallback — fallback provider string for search/API key status (e.g. preset.chat.provider for utility slot)
+ apiBaseFallback — fallback api_base string for search (e.g. preset.chat.api_base for utility slot)
+ -->
+ <div x-data="{ get _prov() { return model.provider || (typeof providerFallback !== 'undefined' ? providerFallback : ''); }, get _apiBase() { return model.api_base || (typeof apiBaseFallback !== 'undefined' ? apiBaseFallback : ''); } }">
+ <!-- Provider -->
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Provider</div>
+ <div class="field-description">LLM service provider for this model slot.</div>
+ </div>
+ <div class="field-control">
+ <select x-model="model.provider"
+ x-effect="$nextTick(() => { if (providers.length) $el.value = model.provider })">
+ <template x-for="p in providers" :key="p.value">
+ <option :value="p.value" x-text="p.label"></option>
+ </template>
+ </select>
+ </div>
+ </div>
+
+ <!-- Model name + search -->
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Model name</div>
+ <div class="field-description">Model identifier. Click the search icon to browse available models.</div>
+ </div>
+ <div class="field-control" style="position:relative;"
+ x-data="{ results: [], open: false, searching: false,
+ doSearch() { this.searching = true; $store.modelConfig.searchModels(_prov, model.name, searchType, _apiBase).then(r => { this.results = r; this.open = true; }).finally(() => this.searching = false); },
+ grouped() { return $store.modelConfig.groupResults(this.results, model.name); }
+ }"
+ @click.outside="open = false">
+ <input type="text" x-model="model.name" style="padding-right:32px;"
+ @keydown.enter.prevent="doSearch()" />
+ <span class="model-search-btn"
+ @click="if (!searching) doSearch()"
+ title="Search available models">
+ <span class="material-symbols-outlined" :style="searching && 'opacity:0'">search</span>
+ <span class="material-symbols-outlined model-search-spinner" :style="!searching && 'opacity:0'">progress_activity</span>
+ </span>
+ <div class="model-search-results" x-show="open && results.length > 0" x-transition.opacity>
+ <template x-for="m in grouped().matched" :key="'m_'+m">
+ <div class="model-search-item matched" @click="model.name = m; open = false;" x-text="m"></div>
+ </template>
+ <div class="model-search-separator" x-show="grouped().matched.length > 0 && grouped().rest.length > 0"></div>
+ <template x-for="m in grouped().rest" :key="'r_'+m">
+ <div class="model-search-item" @click="model.name = m; open = false;" x-text="m"></div>
+ </template>
+ </div>
+ <div class="model-search-results" x-show="open && results.length === 0 && !searching">
+ <div class="model-search-item disabled">No models found</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- API key (store mode: config.html) -->
+ <template x-if="apiKeyMode === 'store'">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">API key</div>
+ <div class="field-description">Authentication key for this provider. Shared across all model slots using the same provider.</div>
+ </div>
+ <div class="field-control" style="position:relative;" x-data="{ showKey: false }">
+ <input :type="showKey ? 'text' : 'password'"
+ x-model="$store.modelConfig.apiKeyValues[model.provider]"
+ :placeholder="$store.modelConfig.apiKeyStatus[model.provider] ? '&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;' : ''"
+ autocomplete="off"
+ @input="$store.modelConfig.touchApiKey(model.provider)"
+ style="padding-right:32px;" />
+ <span class="material-symbols-outlined eye-toggle"
+ @click="
+ showKey = !showKey;
+ const prov = model.provider;
+ if (showKey && !$store.modelConfig.apiKeyValues[prov] && $store.modelConfig.apiKeyStatus[prov]) {
+ $store.modelConfig.revealApiKey(prov).then(v => { if (v) $store.modelConfig.apiKeyValues[prov] = v; });
+ }
+ "
+ x-text="showKey ? 'visibility' : 'visibility_off'"></span>
+ </div>
+ </div>
+ </template>
+
+ <!-- API key (inline mode: presets) -->
+ <template x-if="apiKeyMode === 'inline'">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">API key</div>
+ <div class="field-description">Authentication key for this provider. Shared across all model slots using the same provider.</div>
+ </div>
+ <div class="field-control" style="position:relative;" x-data="{ showKey: false, _revealed: '' }">
+ <input :type="showKey ? 'text' : 'password'" x-model="model.api_key" autocomplete="off"
+ :placeholder="$store.modelConfig.apiKeyStatus[_prov] ? '&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;' : ''"
+ style="padding-right:32px;" />
+ <span class="material-symbols-outlined eye-toggle"
+ @click="
+ showKey = !showKey;
+ if (showKey && !model.api_key && $store.modelConfig.apiKeyStatus[_prov]) {
+ $store.modelConfig.revealApiKey(_prov).then(v => { if (v) { model.api_key = v; _revealed = v; } });
+ }
+ if (!showKey && _revealed && model.api_key === _revealed) {
+ model.api_key = ''; _revealed = '';
+ }
+ "
+ x-text="showKey ? 'visibility' : 'visibility_off'"></span>
+ </div>
+ </div>
+ </template>
+
+ <!-- API base URL -->
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">API base URL</div>
+ <div class="field-description">Custom endpoint URL. Leave empty to use the provider's default.</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="model.api_base" />
+ </div>
+ </div>
+
+ <!-- Context length (not for embedding) -->
+ <template x-if="modelType !== 'embedding'">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Context length</div>
+ <div class="field-description">Maximum number of tokens in the context window. System prompt, chat history, RAG and response all count towards this limit.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="model.ctx_length" />
+ </div>
+ </div>
+ </template>
+
+ <!-- Chat-specific: ctx_history, vision, max_embeds -->
+ <template x-if="modelType === 'chat'">
+ <div>
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Context window space for chat history</div>
+ <div class="field-description">Portion of context window dedicated to chat history visible to the agent. Smaller size will result in shorter and more summarized history.</div>
+ </div>
+ <div class="field-control">
+ <input type="range" min="0.01" max="1" step="0.01" x-model.number="model.ctx_history" />
+ <span class="range-value" x-text="model.ctx_history"></span>
+ </div>
+ </div>
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Supports Vision</div>
+ <div class="field-description">Models capable of Vision can for example natively see the content of image attachments.</div>
+ </div>
+ <div class="field-control">
+ <label class="toggle">
+ <input type="checkbox" x-model="model.vision" />
+ <span class="toggler"></span>
+ </label>
+ </div>
+ </div>
+ <template x-if="model.vision">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Max embeds</div>
+ <div class="field-description">Maximum number of embedded images used by the chat model. Set to 0 for unlimited.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" min="0" x-model.number="model.max_embeds" x-init="if (!model.max_embeds) model.max_embeds = 10" />
+ </div>
+ </div>
+ </template>
+ </div>
+ </template>
+
+ <!-- Utility-specific: ctx_input slider -->
+ <template x-if="modelType === 'utility'">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Context window space for utility model input</div>
+ <div class="field-description">Portion of context window used for utility model input messages.</div>
+ </div>
+ <div class="field-control">
+ <input type="range" min="0.01" max="1" step="0.01" x-model.number="model.ctx_input" />
+ <span class="range-value" x-text="model.ctx_input"></span>
+ </div>
+ </div>
+ </template>
+
+ <!-- Rate limits -->
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Requests per minute limit</div>
+ <div class="field-description">Limits the number of requests per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="model.rl_requests" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Input tokens per minute limit</div>
+ <div class="field-description">Limits the number of input tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="model.rl_input" />
+ </div>
+ </div>
+
+ <template x-if="modelType !== 'embedding'">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Output tokens per minute limit</div>
+ <div class="field-description">Limits the number of output tokens per minute. Waits if the limit is exceeded. Set to 0 to disable.</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="model.rl_output" />
+ </div>
+ </div>
+ </template>
+
+ <!-- Additional parameters -->
+ <div class="field field-full">
+ <div class="field-label">
+ <div class="field-title">Additional parameters</div>
+ <div class="field-description">
+ Any other parameters supported by <a href='https://docs.litellm.ai/docs/set_keys' target='_blank'>LiteLLM</a>. Format is KEY=VALUE on individual lines. Value can be JSON objects; unquoted is treated as object/number, quoted as string.
+ </div>
+ </div>
+ <div class="field-control">
+ <textarea x-model="model._kwargs_text"
+ @change="model.kwargs = $store.modelConfig.textToKwargs(model._kwargs_text)"></textarea>
+ </div>
+ </div>
+ </div>
+
+<style>
+ .eye-toggle {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ font-size: 18px;
+ cursor: pointer;
+ user-select: none;
+ opacity: 0.6;
+ z-index: 1;
+ }
+ .eye-toggle:hover {
+ opacity: 1;
+ }
+ .model-search-btn {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ width: 20px;
+ height: 20px;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ user-select: none;
+ opacity: 0.6;
+ z-index: 1;
+ }
+ .model-search-btn:hover {
+ opacity: 1;
+ }
+ .model-search-btn > span {
+ grid-area: 1 / 1;
+ font-size: 18px;
+ transition: opacity 0.15s;
+ }
+ .model-search-spinner {
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ .model-search-results {
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ right: 0;
+ max-height: 200px;
+ overflow-y: auto;
+ background: var(--color-input);
+ border: 1px solid var(--color-border);
+ border-radius: 6px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
+ z-index: 50;
+ padding: 4px;
+ }
+ .model-search-item {
+ padding: 5px 8px;
+ font-size: 0.8rem;
+ border-radius: 4px;
+ cursor: pointer;
+ word-break: break-all;
+ }
+ .model-search-item:hover {
+ background: var(--color-background-hover, rgba(255,255,255,0.06));
+ }
+ .model-search-item.disabled {
+ opacity: 0.4;
+ cursor: default;
+ font-style: italic;
+ }
+ .model-search-item.matched {
+ font-weight: 500;
+ }
+ .model-search-separator {
+ height: 1px;
+ margin: 4px 8px;
+ background: var(--color-border);
+ opacity: 0.5;
+ }
+ .model-search-item.disabled:hover {
+ background: transparent;
+ }
+</style>
+</body>
+</html>
diff --git a/plugins/_model_config/webui/switcher-mixin.js b/plugins/_model_config/webui/switcher-mixin.js
new file mode 100644
index 000000000..c614d35bf
--- /dev/null
+++ b/plugins/_model_config/webui/switcher-mixin.js
@@ -0,0 +1,118 @@
+const API_BASE = "/plugins/_model_config";
+
+export const switcherState = {
+ switcherAllowed: false,
+ switcherOverride: null,
+ switcherPresets: [],
+ switcherLoading: true,
+};
+
+export const switcherMethods = {
+ async loadSwitcherState(contextId) {
+ const result = { allowed: false, presets: [], override: null };
+ try {
+ await this.loadGlobalPresets();
+ result.presets = this.globalPresets.filter(p => p.name);
+ if (contextId) {
+ const overRes = await fetchApi(`${API_BASE}/model_override`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "get", context_id: contextId }),
+ });
+ const overData = await overRes.json();
+ result.allowed = !!overData.allowed;
+ result.override = overData.override || null;
+ }
+ } catch (e) {
+ console.error("Model switcher load failed:", e);
+ }
+ return result;
+ },
+
+ async setPresetOverride(contextId, presetName) {
+ try {
+ const res = await fetchApi(`${API_BASE}/model_override`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "set_preset", context_id: contextId, preset_name: presetName }),
+ });
+ return !!(await res.json()).ok;
+ } catch (e) {
+ console.error("Failed to set preset override:", e);
+ return false;
+ }
+ },
+
+ async clearOverride(contextId) {
+ try {
+ const res = await fetchApi(`${API_BASE}/model_override`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "clear", context_id: contextId }),
+ });
+ return !!(await res.json()).ok;
+ } catch (e) {
+ console.error("Failed to clear override:", e);
+ return false;
+ }
+ },
+
+ getPresetLabel(preset) {
+ return preset?.name || "Unnamed";
+ },
+
+ getPresetSummary(preset) {
+ if (!preset) return "";
+ const parts = [];
+ if (preset.chat?.name) parts.push(preset.chat.name);
+ if (preset.utility?.name) parts.push(preset.utility.name);
+ return parts.join(" / ");
+ },
+
+ async refreshSwitcher(contextId) {
+ this.switcherLoading = true;
+ try {
+ const state = await this.loadSwitcherState(contextId);
+ this.switcherAllowed = state.allowed;
+ this.switcherPresets = state.presets;
+ this.switcherOverride = state.override;
+ } catch (e) {
+ console.error('Model switcher refresh failed:', e);
+ } finally {
+ this.switcherLoading = false;
+ }
+ },
+
+ async selectPresetSwitch(contextId, presetName) {
+ const ok = await this.setPresetOverride(contextId, presetName);
+ if (ok) this.switcherOverride = { preset_name: presetName };
+ return ok;
+ },
+
+ async clearOverrideSwitch(contextId) {
+ const ok = await this.clearOverride(contextId);
+ if (ok) this.switcherOverride = null;
+ return ok;
+ },
+
+ getSwitcherLabel() {
+ const o = this.switcherOverride;
+ if (!o) return 'Default LLM';
+ return o.preset_name || o.name || o.provider || 'Custom';
+ },
+
+ getActivePreset() {
+ const o = this.switcherOverride;
+ if (!o || !o.preset_name) return null;
+ return this.switcherPresets.find(p => p.name === o.preset_name) || null;
+ },
+
+ getActiveModels() {
+ const preset = this.getActivePreset();
+ if (!preset) return { main: null, utility: null };
+ return {
+ main: preset.chat?.name ? { provider: preset.chat.provider, name: preset.chat.name } : null,
+ utility: preset.utility?.name ? { provider: preset.utility.provider, name: preset.utility.name } : null,
+ };
+ },
+};