Agent Zero AI framework
Report invalid model parameter JSON before saving
Alessandro0af7390b7c6f
diff --git a/plugins/_model_config/AGENTS.md b/plugins/_model_config/AGENTS.mdindex 05fbc623a..0047327d3 100644--- a/plugins/_model_config/AGENTS.md+++ b/plugins/_model_config/AGENTS.md@@ -53,6 +53,7 @@- Venice migration applies chat-only kwargs to chat slots and removes them from embedding slots without discarding embedding-specific kwargs.- On every startup after migration, short-circuit when `usr/plugins/_model_config/presets.yaml` exists. Only a missing collection may fetch `agent0ai/a0-presets`; parse remote and plugin-local fallback YAML through the same validator, strip secrets before persistence, and persist `mode_presets_fallback.yaml` when download or validation fails.- Model-name catalogs open below the input from either a field click or the embedded magnifier.+- Additional parameter drafts retain plain-string compatibility but reject malformed JSON-shaped values and invalid KEY=VALUE lines with a standard notification. Reparse every preset slot before saving presets or API keys; invalid drafts stay editable and never silently save stale kwargs.## Work Guidancediff --git a/plugins/_model_config/webui/model-config-store.js b/plugins/_model_config/webui/model-config-store.jsindex 74c723132..624135c90 100644--- a/plugins/_model_config/webui/model-config-store.js+++ b/plugins/_model_config/webui/model-config-store.js@@ -22,15 +22,23 @@ export function kwargsToText(obj) {export function textToKwargs(text) {const d = {};- (text || '').split('\n').forEach(l => {+ (text || '').split('\n').forEach((l, line) => {l = l.trim();if (!l || l.startsWith('#')) return;const i = l.indexOf('=');if (i > 0) {const key = l.substring(0, i).trim();let val = l.substring(i + 1).trim();- try { val = JSON.parse(val); } catch {}+ try {+ val = JSON.parse(val);+ } catch {+ if (['{', '[', '"'].includes(val[0]) || ['True', 'False', 'None'].includes(val)) {+ throw new Error(`Additional parameters line ${line + 1}: invalid JSON for ${key}. JSON uses lowercase true, false, and null; quote strings.`);+ }+ }d[key] = val;+ } else {+ throw new Error(`Additional parameters line ${line + 1}: use KEY=VALUE.`);}});return d;@@ -407,10 +415,15 @@ export const store = createStore("modelConfig", {return false;}try {+ for (const preset of this.presets) {+ for (const key of ['chat', 'vision', 'utility', 'embedding']) {+ const slot = preset[key];+ if (typeof slot?._kwargs_text === 'string') slot.kwargs = textToKwargs(slot._kwargs_text);+ }+ }await store.persistAllDirtyApiKeys();} catch (e) {- console.error('Failed to save API keys:', e);- globalThis.justToast?.(e?.message || 'Failed to save API keys.', 'error');+ globalThis.justToast?.(e?.message || 'Failed to save preset settings.', 'error');return false;}if (!await store.saveGlobalPresets(this.presets)) return false;@@ -889,6 +902,14 @@ export const store = createStore("modelConfig", {}},+ updateModelKwargs(model) {+ try {+ model.kwargs = textToKwargs(model._kwargs_text);+ } catch (e) {+ globalThis.justToast?.(e.message, 'error');+ }+ },+// 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.htmlindex a5b3ac92b..f16cd9526 100644--- a/plugins/_model_config/webui/model-field.html+++ b/plugins/_model_config/webui/model-field.html@@ -324,12 +324,12 @@<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.+ 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. Values can be JSON objects, arrays, numbers, lowercase true/false/null, or text. Quote strings to keep values such as "true" as text.</div></div><div class="field-control"><textarea x-model="model._kwargs_text"- @change="model.kwargs = $store.modelConfig.textToKwargs(model._kwargs_text)"></textarea>+ @change="$store.modelConfig.updateModelKwargs(model)"></textarea></div></div>diff --git a/tests/test_model_parameter_text.py b/tests/test_model_parameter_text.pynew file mode 100644index 000000000..b00327cd8--- /dev/null+++ b/tests/test_model_parameter_text.py@@ -0,0 +1,58 @@+import base64+from pathlib import Path+import re+import shutil+import subprocess++import pytest++[email protected](not shutil.which("node"), reason="node is required")+def test_parameter_parsing_and_save_validation():+ source = (Path(__file__).parents[1] / "plugins/_model_config/webui/model-config-store.js").read_text()+ source = re.sub(r"^import .*?;\n", "", source, flags=re.MULTILINE)+ source = """+const createStore = (_name, value) => value;+const apiKeysState = {}, apiKeysMethods = {}, switcherState = {}, switcherMethods = {};+""" + source+ module_url = "data:text/javascript;base64," + base64.b64encode(source.encode()).decode()+ script = r'''+import assert from 'node:assert/strict';+const { textToKwargs, kwargsToText, store } = await import(MODULE_URL);+const values = { plain: 'hello', literal: 'true', flag: true, off: false, nothing: null,+ number: 0.2, object: { list: [1, false] }, empty: '' };+assert.deepEqual(textToKwargs(kwargsToText(values)), values);+assert.deepEqual(textToKwargs('# comment\n\nplain=hello\nurl=https://example.test/?a=b'),+ {plain: 'hello', url: 'https://example.test/?a=b'});+for (const value of ['{"enabled":True}', '[1,]', '"unfinished', 'True', 'False', 'None']) {+ assert.throws(() => textToKwargs('param=' + value), /line 1: invalid JSON for param/);+}+assert.throws(() => textToKwargs('# comment\nbroken'), /line 2: use KEY=VALUE/);+let saves = 0, keySaves = 0, saved;+const notifications = [];+globalThis.justToast = (message, type) => notifications.push({message, type});+const draft = {kwargs: {old: true}, _kwargs_text: 'param={"enabled":True}'};+store.updateModelKwargs(draft);+assert.deepEqual(draft.kwargs, {old: true});+assert.match(notifications.at(-1).message, /invalid JSON/);+draft._kwargs_text = 'param={"enabled":true}';+store.updateModelKwargs(draft);+assert.deepEqual(draft.kwargs, {param: {enabled: true}});+store.persistAllDirtyApiKeys = async () => { keySaves++; };+store.saveGlobalPresets = async presets => { saves++; saved = structuredClone(presets); return true; };+for (const slot of ['chat', 'vision', 'utility', 'embedding']) {+ store.globalPresets = [{name: 'Test', [slot]: {provider: 'test', name: 'test',+ kwargs: {old: true}, _kwargs_text: 'param={"enabled":True}'}}];+ const editor = store.createPresetEditor('Test');+ const before = [saves, keySaves];+ assert.equal(await editor.savePresets(), false);+ assert.deepEqual([saves, keySaves], before);+ assert.match(notifications.at(-1).message, /invalid JSON/);+ assert.equal(notifications.at(-1).type, 'error');+ assert.equal(editor.selectedPreset[slot]._kwargs_text, 'param={"enabled":True}');+ editor.selectedPreset[slot]._kwargs_text = 'param={"enabled":true}';+ assert.equal(await editor.savePresets(), true);+ assert.deepEqual(saved[0][slot].kwargs, {param: {enabled: true}});+}+'''.replace("MODULE_URL", repr(module_url))+ subprocess.run(["node", "--input-type=module", "-e", script], check=True)