Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

complete mutual exclusive fields implementation

Forhad Hosainf39839adcc84
diff --git a/packages/app/src/builder-ui/components/GenAILLM.class.ts b/packages/app/src/builder-ui/components/GenAILLM.class.ts
index 91b98a04..7e9a23c7 100644
--- a/packages/app/src/builder-ui/components/GenAILLM.class.ts
+++ b/packages/app/src/builder-ui/components/GenAILLM.class.ts
@@ -42,6 +42,7 @@ export class GenAILLM extends Component {
private modelOptions: string[];
private modelParams: Record<string, any>;
private defaultModel: string;
+ private anthropicModels: string[];
private anthropicThinkingModels: string[];
private openaiReasoningModels: string[];
private groqReasoningModels: string[];
@@ -61,6 +62,10 @@ export class GenAILLM extends Component {
this.defaultModel = LLMFormController.getDefaultModel(modelOptions);
+ // Get all Anthropic models using 'text' feature (all LLM models support text)
+ this.anthropicModels = LLMRegistry.getModelsByFeatures('text', 'anthropic').map(
+ (m) => m.entryId,
+ );
this.anthropicThinkingModels = LLMRegistry.getSortedModelsByFeatures({
features: 'reasoning',
providers: 'anthropic',
@@ -307,6 +312,7 @@ export class GenAILLM extends Component {
maxFrequencyPenalty: modelParams?.maxFrequencyPenalty,
maxPresencePenalty: modelParams?.maxPresencePenalty,
+ minTemperature: modelParams?.minTemperature,
minTopP: modelParams?.minTopP,
minTopK: modelParams?.minTopK,
@@ -325,6 +331,7 @@ export class GenAILLM extends Component {
allowedCompletionTokens,
allowedWebSearchContextTokens,
allowedReasoningTokens,
+ minTemperature,
maxTemperature,
maxStopSequences,
maxTopP,
@@ -551,12 +558,12 @@ export class GenAILLM extends Component {
temperature: {
type: 'range',
label: 'Temperature',
- min: 0,
+ min: minTemperature,
max: maxTemperature,
value: defaultTemperature,
step: 0.01,
- validate: `min=0 max=${maxTemperature}`,
- validateMessage: `Allowed range 0 to ${maxTemperature}`,
+ validate: `min=${minTemperature} max=${maxTemperature}`,
+ validateMessage: `Allowed range ${minTemperature} to ${maxTemperature}`,
attributes: {
'data-supported-models':
'OpenAI,Anthropic,GoogleAI,Groq,xAI,TogetherAI,VertexAI,Bedrock,Perplexity,cohere,Ollama',
@@ -566,12 +573,17 @@ export class GenAILLM extends Component {
...this.gptO3andO4Models,
...this.gptSearchModels,
].join(','),
- // Temperature and Top P are mutually exclusive sampling parameters
- // Setting one will reset the other to its default value
+ // Anthropic API requires only temperature OR top_p (mutually exclusive).
+ // We use llmParams.anthropic.minTemperature instead of minTemperature because:
+ // - minTemperature is dynamic and depends on the currently selected model at form generation time
+ // - This attribute is set once when the form is created (via JSON.stringify)
+ // - Since this feature is Anthropic-specific, we need Anthropic's "not set" value (-0.01)
'data-mutually-exclusive': JSON.stringify({
- group: 'sampling-params',
- with: 'Top P',
- reason: 'The selected model supports either Temperature or Top P',
+ group: 'anthropic-temperature-topp',
+ models: this.anthropicModels,
+ reset: llmParams.anthropic.minTemperature,
+ reason:
+ 'Anthropic models support either Temperature or Top P at a time. Setting Temperature will clear Top P.',
}),
},
section: 'Advanced',
@@ -639,12 +651,17 @@ export class GenAILLM extends Component {
//...this.anthropicThinkingModels,
...this.groqReasoningModels,
].join(','),
- // Temperature and Top P are mutually exclusive sampling parameters
- // Setting one will reset the other to its default value
+ // Anthropic API requires only temperature OR top_p (mutually exclusive).
+ // We use llmParams.anthropic.minTopP instead of minTopP because:
+ // - minTopP is dynamic and depends on the currently selected model at form generation time
+ // - This attribute is set once when the form is created (via JSON.stringify)
+ // - Since this feature is Anthropic-specific, we need Anthropic's "not set" value (-0.01)
'data-mutually-exclusive': JSON.stringify({
- group: 'sampling-params',
- with: 'Temperature',
- reason: 'The selected model supports either Temperature or Top P',
+ group: 'anthropic-temperature-topp',
+ models: this.anthropicModels,
+ reset: llmParams.anthropic.minTopP,
+ reason:
+ 'Anthropic models support either Temperature or Top P at a time. Setting Top P will clear Temperature.',
}),
},
section: 'Advanced',
@@ -664,7 +681,7 @@ export class GenAILLM extends Component {
attributes: {
'data-supported-models':
'GoogleAI,VertexAI,Anthropic,TogetherAI,Perplexity,cohere,Ollama,xAI,Groq',
- 'data-excluded-models': this.anthropicThinkingModels.join(','),
+ //'data-excluded-models': this.anthropicThinkingModels.join(','),
},
section: 'Advanced',
help: 'Restrict generation to the top K most likely words to reduce randomness.',
diff --git a/packages/app/src/builder-ui/helpers/LLMFormController.helper.ts b/packages/app/src/builder-ui/helpers/LLMFormController.helper.ts
index 9fc1e209..40969214 100644
--- a/packages/app/src/builder-ui/helpers/LLMFormController.helper.ts
+++ b/packages/app/src/builder-ui/helpers/LLMFormController.helper.ts
@@ -1,6 +1,10 @@
import { LLMRegistry } from '../../shared/services/LLMRegistry.service';
import llmParams from '../params/LLM.params.json';
import { generateModelCapabilityBadges, generateModelStatusBadges } from '../ui/badges';
+import {
+ updateInactiveEffectState,
+ updateMutualExclusiveHintsVisibility,
+} from '../ui/form/mutually-exclusive-fields';
import { createSpinner } from '../utils/general.utils';
declare var $;
@@ -70,6 +74,7 @@ export class LLMFormController {
const {
defaultTemperature,
+ minTemperature,
maxTemperature,
defaultTopP,
minTopP,
@@ -87,7 +92,7 @@ export class LLMFormController {
this.updateField({
formElm,
fieldElm: temperatureField,
- minValue: 0,
+ minValue: minTemperature,
maxValue: maxTemperature,
defaultValue: defaultTemperature,
});
@@ -148,6 +153,10 @@ export class LLMFormController {
presencePenaltyField
.closest('.form-group')
.setAttribute('data-hint-text', hint.presencePenalty);
+
+ // Update mutual exclusive hints visibility based on the selected model
+ // Hints are only shown for models in the whitelist (e.g., Anthropic models)
+ updateMutualExclusiveHintsVisibility(formElm as HTMLFormElement);
}
// * N:B Need to invoke this function with .bind(this), .call(this) or .apply(this) to get the correct context
@@ -435,15 +444,67 @@ export class LLMFormController {
}
}
+ /**
+ * Updates a field's validation rules and value when switching between LLM models.
+ *
+ * This method handles two main scenarios:
+ * 1. **Standard fields**: Clamps values to new min/max range
+ * 2. **Mutually exclusive fields**: Resets to provider-specific defaults when applicable
+ *
+ * ## Mutually Exclusive Fields
+ *
+ * Some fields are mutually exclusive for certain providers (e.g., Anthropic's
+ * temperature and top_p). These fields are marked with `data-mutually-exclusive`
+ * attribute containing configuration:
+ *
+ * ```json
+ * {
+ * "group": "sampling-params",
+ * "models": ["claude-3-opus", "claude-3-sonnet"],
+ * "reset": -0.01,
+ * "reason": "..."
+ * }
+ * ```
+ *
+ * When switching models, if the new model is in the field's whitelist and the
+ * current value doesn't match the reset value, the field is reset to maintain
+ * proper mutual exclusivity.
+ *
+ * ### Example: OpenAI → Anthropic
+ * - OpenAI uses Top P = 1 (both temperature and top_p can be set)
+ * - Anthropic requires Top P = -0.01 (only temperature OR top_p)
+ * - When switching to Claude, Top P resets from 1 to -0.01 ("not set")
+ *
+ * @param formElm - Parent form element for context
+ * @param fieldElm - Input element to update
+ * @param minValue - New minimum value for the field
+ * @param maxValue - New maximum value for the field
+ * @param defaultValue - Default value for the new model
+ */
private static updateField({ formElm, fieldElm, minValue, maxValue, defaultValue }) {
const currentValue = parseFloat(fieldElm.value);
+ let newValue = currentValue;
- if (currentValue > maxValue) {
- fieldElm.value = maxValue;
+ // First, check for mutually exclusive field configuration
+ const shouldResetForMutualExclusivity = this.shouldResetMutuallyExclusiveField(
+ fieldElm,
+ formElm,
+ currentValue,
+ defaultValue,
+ );
+
+ if (shouldResetForMutualExclusivity) {
+ // Reset to the configured reset value (e.g., -0.01 for Anthropic)
+ newValue = defaultValue;
+ } else if (currentValue > maxValue) {
+ // Clamp to maximum if current value exceeds new range
+ newValue = maxValue;
} else if (currentValue < minValue) {
- fieldElm.value = minValue;
+ // Clamp to minimum if current value is below new range
+ newValue = minValue;
}
+ // Update validation rules to reflect new model's constraints
this.replaceValidationRules({
fieldElm,
attribute: 'min',
@@ -456,6 +517,78 @@ export class LLMFormController {
targetValue: maxValue,
inputType: 'range',
});
- this.setRangeInputValue(formElm, fieldElm.id, fieldElm.value || defaultValue);
+
+ // Apply the new value to both range and number inputs
+ this.setRangeInputValue(formElm, fieldElm.id, newValue);
+
+ // Update visual state (blur effect for negative/"not set" values)
+ updateInactiveEffectState(fieldElm);
+ }
+
+ /**
+ * Determines if a field should be reset based on mutually exclusive configuration.
+ *
+ * A field should be reset when:
+ * 1. It has a `data-mutually-exclusive` attribute
+ * 2. The current model is in the field's whitelist
+ * 3. The current value is not already the reset value (avoid unnecessary resets)
+ *
+ * @param fieldElm - The field element to check
+ * @param formElm - Parent form element (to get current model)
+ * @param currentValue - Current numeric value of the field
+ * @param resetValue - The value to reset to (from provider config)
+ * @returns true if field should be reset to resetValue
+ */
+ private static shouldResetMutuallyExclusiveField(
+ fieldElm: HTMLElement,
+ formElm: HTMLElement,
+ currentValue: number,
+ resetValue: number,
+ ): boolean {
+ // Check if field has mutually exclusive configuration
+ const mutualExclusiveAttr = fieldElm.getAttribute('data-mutually-exclusive');
+ if (!mutualExclusiveAttr) {
+ return false; // Not a mutually exclusive field
+ }
+
+ try {
+ const config = JSON.parse(mutualExclusiveAttr);
+
+ // Get the current model from the form
+ const modelSelector = formElm.querySelector('#model') as HTMLSelectElement;
+ if (!modelSelector) {
+ return false; // Can't determine model, skip reset
+ }
+
+ const currentModel = modelSelector.value?.toLowerCase();
+ if (!currentModel) {
+ return false;
+ }
+
+ // Check if current model is in the whitelist
+ const whitelistedModels = config.models || [];
+ const isModelApplicable =
+ whitelistedModels.length === 0 || // Empty whitelist = apply to all models
+ whitelistedModels.some((model: string) => model.toLowerCase() === currentModel);
+
+ if (!isModelApplicable) {
+ return false; // Model not in whitelist, don't reset
+ }
+
+ // Use the reset value from config if specified, otherwise use resetValue parameter
+ const targetResetValue = config.reset !== undefined ? config.reset : resetValue;
+
+ // Only reset if current value is different from target reset value
+ // This avoids unnecessary resets when value is already correct
+ // Use small epsilon for floating point comparison
+ const epsilon = 0.0001;
+ const isDifferent = Math.abs(currentValue - targetResetValue) > epsilon;
+
+ return isDifferent;
+ } catch (error) {
+ // If config parsing fails, don't reset (fail gracefully)
+ console.warn('Failed to parse data-mutually-exclusive config:', error);
+ return false;
+ }
}
}
diff --git a/packages/app/src/builder-ui/params/LLM.params.json b/packages/app/src/builder-ui/params/LLM.params.json
index 9d9c3021..809d3e0f 100644
--- a/packages/app/src/builder-ui/params/LLM.params.json
+++ b/packages/app/src/builder-ui/params/LLM.params.json
@@ -1,6 +1,7 @@
{
"default": {
"defaultTemperature": 1,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -29,6 +30,7 @@
},
"openai": {
"defaultTemperature": 1,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -57,6 +59,7 @@
},
"cohere": {
"defaultTemperature": 0.75,
+ "minTemperature": 0,
"maxTemperature": 5,
"minMaxTokens": 4,
"defaultMaxTokens": 100,
@@ -85,6 +88,7 @@
},
"togetherai": {
"defaultTemperature": 0.7,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -112,13 +116,15 @@
}
},
"anthropic": {
+ "_note": "minTemperature/minTopP are -0.01 to represent 'not set'. Anthropic requires only temperature OR top_p (mutually exclusive). Backend excludes values < 0.",
"defaultTemperature": 1,
+ "minTemperature": -0.01,
"maxTemperature": 1,
"minMaxTokens": 2048,
"defaultMaxTokens": 8192,
"defaultThinkingTokens": 4096,
- "defaultTopP": 0,
- "minTopP": 0,
+ "defaultTopP": -0.01,
+ "minTopP": -0.01,
"maxTopP": 1,
"defaultTopK": 0,
"minTopK": 0,
@@ -141,6 +147,7 @@
},
"googleai": {
"defaultTemperature": 0.9,
+ "minTemperature": 0,
"maxTemperature": 1,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -169,6 +176,7 @@
},
"groq": {
"defaultTemperature": 0.2,
+ "minTemperature": 0,
"maxTemperature": 1,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -197,6 +205,7 @@
},
"bedrock": {
"defaultTemperature": 1,
+ "minTemperature": 0,
"maxTemperature": 1,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -225,6 +234,7 @@
},
"vertexai": {
"defaultTemperature": 0.9,
+ "minTemperature": 0,
"maxTemperature": 1,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -253,6 +263,7 @@
},
"perplexity": {
"defaultTemperature": 0.2,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -281,6 +292,7 @@
},
"xai": {
"defaultTemperature": 0.2,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 4,
"defaultMaxTokens": 8192,
@@ -309,6 +321,7 @@
},
"ollama": {
"defaultTemperature": 0.8,
+ "minTemperature": 0,
"maxTemperature": 2,
"minMaxTokens": 1,
"defaultMaxTokens": 128,
diff --git a/packages/app/src/builder-ui/ui/form/createFormField.ts b/packages/app/src/builder-ui/ui/form/createFormField.ts
index ae41dd63..b4761524 100644
--- a/packages/app/src/builder-ui/ui/form/createFormField.ts
+++ b/packages/app/src/builder-ui/ui/form/createFormField.ts
@@ -597,46 +597,18 @@ export default function createFormField(entry, displayType = 'block', entryIndex
window['__FIELD_TEMPLATE_VARIABLES__'][entry?.name] = variables;
}
- // Register mutually exclusive fields
- // When a field has data-mutually-exclusive attribute, it will be part of a group
- // where only one field can have a non-default value at a time
- // Format: { group: string, with?: string, reason?: string }
- const mutuallyExclusiveAttr = attributes['data-mutually-exclusive'];
- if (mutuallyExclusiveAttr) {
- // Parse the config object from the attribute
- let exclusiveConfig: { group: string; with?: string; reason?: string };
- try {
- exclusiveConfig = JSON.parse(mutuallyExclusiveAttr);
- } catch {
- // Fallback for legacy string format (just the group name)
- exclusiveConfig = { group: mutuallyExclusiveAttr };
- }
-
- const { group, with: exclusiveWithFields, reason: exclusiveReason } = exclusiveConfig;
-
- // Use the actual input element (eventTarget) for registration
- // Store the default value from the entry for proper reset behavior
- registerMutuallyExclusiveField(eventTarget, group, entry.value);
-
- // Add a hint to indicate mutual exclusivity
- let hintMessage: string;
- if (exclusiveWithFields && exclusiveReason) {
- hintMessage = `${exclusiveReason}. Changing this will reset ${exclusiveWithFields} to 0.`;
- } else if (exclusiveWithFields) {
- hintMessage = `Mutually exclusive with ${exclusiveWithFields}. Changing this will reset it to 0.`;
- } else {
- hintMessage = 'Only one field in this group can have a value at a time.';
- }
-
- const mutualExclusiveHint = document.createElement('div');
- mutualExclusiveHint.className =
- 'mutual-exclusive-hint text-xs text-amber-500 mx-2';
- mutualExclusiveHint.textContent = hintMessage;
- // Store hint reference on the field element for later updates
- (eventTarget as any)._mutualExclusiveHint = mutualExclusiveHint;
- // Will be appended to div later (after the field is fully constructed)
+ // Setup mutually exclusive field registration and hint (if applicable)
+ const mutuallyExclusiveResult = setupMutuallyExclusiveField(
+ eventTarget,
+ div,
+ attributes,
+ entry.value,
+ );
+
+ // Store hint reference if present (will be appended to div later)
+ if (mutuallyExclusiveResult.hint) {
div.setAttribute('data-has-mutual-exclusive-hint', 'true');
- (div as any)._mutualExclusiveHint = mutualExclusiveHint;
+ (div as any)._mutualExclusiveHint = mutuallyExclusiveResult.hint;
}
// Real-time validation - only clear error when field becomes valid
@@ -1586,3 +1558,101 @@ function configureSelectMultiple(
*/
return actualSelect;
}
+
+/**
+ * Configuration interface for mutually exclusive fields
+ */
+interface MutuallyExclusiveConfig {
+ group: string;
+ reason?: string;
+ reset?: number;
+ models?: string[];
+}
+
+/**
+ * Result interface for mutually exclusive field setup
+ */
+interface MutuallyExclusiveResult {
+ hint: HTMLElement | null;
+}
+
+/**
+ * Sets up mutually exclusive field registration and hint creation.
+ *
+ * This function extracts the mutually exclusive field logic from createFormField
+ * to improve code organization and maintainability.
+ *
+ * ## What it does:
+ * 1. Parses the `data-mutually-exclusive` attribute configuration
+ * 2. Registers the field with the mutually exclusive system
+ * 3. Creates a hint element explaining the mutual exclusivity
+ * 4. Configures visibility based on model whitelist
+ *
+ * ## Example configuration:
+ * ```json
+ * {
+ * "group": "anthropic-temperature-topp",
+ * "models": ["claude-3-opus", "claude-3-sonnet"],
+ * "reset": -0.01,
+ * "reason": "Anthropic models support either Temperature or Top P at a time."
+ * }
+ * ```
+ *
+ * @param fieldElement - The input element to register (e.g., HTMLInputElement)
+ * @param containerDiv - The form-group container div
+ * @param attributes - Field attributes containing data-mutually-exclusive config
+ * @param defaultValue - The default value for this field (for reset behavior)
+ * @returns Object containing the hint element (null if not a mutually exclusive field)
+ */
+function setupMutuallyExclusiveField(
+ fieldElement: HTMLElement,
+ containerDiv: HTMLElement,
+ attributes: Record<string, any>,
+ defaultValue: any,
+): MutuallyExclusiveResult {
+ const mutuallyExclusiveAttr = attributes['data-mutually-exclusive'];
+
+ // Not a mutually exclusive field - return early
+ if (!mutuallyExclusiveAttr) {
+ return { hint: null };
+ }
+
+ // Parse the configuration object from the attribute
+ let config: MutuallyExclusiveConfig;
+ try {
+ config = JSON.parse(mutuallyExclusiveAttr);
+ } catch {
+ // Fallback for legacy string format (just the group name)
+ config = { group: mutuallyExclusiveAttr };
+ }
+
+ const { group, reason, reset: resetValue, models: whitelistedModels } = config;
+
+ // Register the field with the mutually exclusive system
+ // This enables automatic reset behavior when another field in the group is changed
+ registerMutuallyExclusiveField(fieldElement, group, defaultValue);
+
+ // Create hint message explaining the mutual exclusivity
+ const hintMessage = reason || 'Only one field in this group can have a value at a time.';
+
+ // Create the hint element
+ const mutualExclusiveHint = document.createElement('div');
+ mutualExclusiveHint.className = 'mutual-exclusive-hint text-xs text-amber-500 mx-2';
+ mutualExclusiveHint.textContent = hintMessage;
+
+ // Configure model-specific visibility
+ // The hint should only be visible when the current model is in the whitelist
+ if (whitelistedModels && Array.isArray(whitelistedModels) && whitelistedModels.length > 0) {
+ mutualExclusiveHint.setAttribute(
+ 'data-mutual-exclusive-models',
+ JSON.stringify(whitelistedModels.map((m) => m.toLowerCase())),
+ );
+ // Initially hide - will be shown by updateMutualExclusiveHintsVisibility when appropriate
+ mutualExclusiveHint.style.display = 'none';
+ }
+
+ // Store hint reference on the field element for later access
+ (fieldElement as any)._mutualExclusiveHint = mutualExclusiveHint;
+
+ return { hint: mutualExclusiveHint };
+}
diff --git a/packages/app/src/builder-ui/ui/form/index.ts b/packages/app/src/builder-ui/ui/form/index.ts
index 9ddad7cd..d0af1111 100644
--- a/packages/app/src/builder-ui/ui/form/index.ts
+++ b/packages/app/src/builder-ui/ui/form/index.ts
@@ -2,7 +2,3 @@ export * from './form';
export { default as createFormField } from './createFormField';
export * from './misc';
export { smythValidator } from './smyth-validator';
-export {
- normalizeMutuallyExclusiveValue,
- normalizeMutuallyExclusiveParams,
-} from './mutually-exclusive-fields';
diff --git a/packages/app/src/builder-ui/ui/form/mutually-exclusive-fields.ts b/packages/app/src/builder-ui/ui/form/mutually-exclusive-fields.ts
index 9de00216..84103111 100644
--- a/packages/app/src/builder-ui/ui/form/mutually-exclusive-fields.ts
+++ b/packages/app/src/builder-ui/ui/form/mutually-exclusive-fields.ts
@@ -12,8 +12,10 @@
*
* Config object properties:
* - group: string (required) - The group name for mutual exclusivity
- * - with: string (optional) - Display name of the related field(s) for the hint message
- * - reason: string (optional) - Explanation of why the fields are mutually exclusive
+ * - models: string[] (optional) - Whitelist of model IDs for which mutual exclusivity applies.
+ * If omitted or empty, applies to all models. The form must have a #model selector.
+ * - reset: number (optional) - The value to reset to (e.g., -0.01 for Anthropic's "not set")
+ * - reason: string (required) - User-friendly explanation shown as hint (should include why and what happens)
*
* Example in field definition:
* ```typescript
@@ -23,8 +25,9 @@
* attributes: {
* 'data-mutually-exclusive': JSON.stringify({
* group: 'sampling-params',
- * with: 'Top P',
- * reason: 'The selected model supports either Temperature or Top P',
+ * models: ['claude-3-opus', 'claude-3-sonnet'],
+ * reset: -0.01,
+ * reason: 'Anthropic models support either Temperature or Top P at a time. Setting Temperature will clear Top P.',
* }),
* // ... other attributes
* },
@@ -35,44 +38,29 @@
* attributes: {
* 'data-mutually-exclusive': JSON.stringify({
* group: 'sampling-params',
- * with: 'Temperature',
- * reason: 'The selected model supports either Temperature or Top P',
+ * models: ['claude-3-opus', 'claude-3-sonnet'],
+ * reset: -0.01,
+ * reason: 'Anthropic models support either Temperature or Top P at a time. Setting Top P will clear Temperature.',
* }),
* // ... other attributes
* },
* },
* ```
*
- * When temperature is changed from its default, topP will be reset to -1, and vice versa.
- * A hint message will be displayed below each field explaining the mutual exclusivity.
- *
- * ## Data Serialization
- * **IMPORTANT**: Before sending form data to the backend API, you must normalize the values
- * to convert -1 sentinel values to undefined:
- *
- * ```typescript
- * import { normalizeMutuallyExclusiveParams } from './form';
- *
- * // When collecting form data:
- * const formData = {
- * temperature: 0.7,
- * topP: -1, // This was reset by mutual exclusivity
- * maxTokens: 1000
- * };
- *
- * // Normalize before sending to backend:
- * const normalizedData = normalizeMutuallyExclusiveParams(formData);
- * // Result: { temperature: 0.7, topP: undefined, maxTokens: 1000 }
- *
- * // The backend will then exclude undefined values automatically:
- * // if (params?.topP !== undefined) body.top_p = params.topP;
- * ```
- *
- * This approach keeps the backend simple - no changes needed to parameter handling!
+ * When temperature is changed, topP will be reset to its reset value (e.g., -0.01), and vice versa.
+ * A hint message is displayed below each field explaining the mutual exclusivity.
+ * Fields with negative/reset values appear dimmed until the user hovers over them.
*/
declare var Metro: any;
+/**
+ * CSS class applied to form-group when field is reset due to mutual exclusivity.
+ * This creates a dimmed visual effect indicating the field is inactive.
+ * The effect is removed on hover/focus, allowing the user to activate the field.
+ */
+const MUTUAL_EXCLUSIVE_INACTIVE_CLASS = 'mutual-exclusive-inactive';
+
/**
* Registry to track mutually exclusive field groups within forms
* Key: form element
@@ -86,73 +74,9 @@ const formGroupRegistry = new WeakMap<HTMLFormElement, Map<string, Set<HTMLEleme
*/
let isResetting = false;
-/**
- * Get the default value for a field element based on its type
- */
-function getFieldDefaultValue(fieldElement: HTMLElement): string | number | boolean {
- const defaultValueAttr = fieldElement.getAttribute('data-default-value');
- if (defaultValueAttr !== null) {
- // Try to parse as JSON for complex types, otherwise use as string
- try {
- return JSON.parse(defaultValueAttr);
- } catch {
- return defaultValueAttr;
- }
- }
-
- // Fallback defaults based on field type
- const fieldType = fieldElement.getAttribute('type') || fieldElement.tagName.toLowerCase();
-
- switch (fieldType) {
- case 'checkbox':
- return false;
- case 'number':
- case 'range':
- return parseFloat(fieldElement.getAttribute('min') || '0');
- case 'select':
- case 'select-one':
- const firstOption = (fieldElement as HTMLSelectElement).options?.[0];
- return firstOption?.value || '';
- default:
- return '';
- }
-}
-
-/**
- * Get the current value of a field element
- */
-function getFieldValue(fieldElement: HTMLElement): string | number | boolean {
- const tagName = fieldElement.tagName.toLowerCase();
-
- if (tagName === 'input') {
- const inputElement = fieldElement as HTMLInputElement;
- const inputType = inputElement.type;
-
- switch (inputType) {
- case 'checkbox':
- return inputElement.checked;
- case 'number':
- case 'range':
- return parseFloat(inputElement.value) || 0;
- default:
- return inputElement.value;
- }
- }
-
- if (tagName === 'select') {
- return (fieldElement as HTMLSelectElement).value;
- }
-
- if (tagName === 'textarea') {
- return (fieldElement as HTMLTextAreaElement).value;
- }
-
- return '';
-}
-
/**
* Get the empty/cleared value for a field based on its type
- * - Numbers: -1 for mutually exclusive fields (to distinguish from valid 0 values), or min value otherwise
+ * - Numbers: Uses the 'reset' value from mutual exclusive config, or -1 as fallback, or min value for non-exclusive fields
* - Strings: ''
* - Booleans: false
* - Select: first option value
@@ -167,10 +91,18 @@ function getEmptyValue(fieldElement: HTMLElement): string | number | boolean {
return false;
case 'number':
case 'range':
- // For mutually exclusive numeric fields, use -1 as sentinel value
- // This allows distinguishing "unset" from valid 0 values in backend
- const hasMutualExclusive = fieldElement.getAttribute('data-mutually-exclusive');
- if (hasMutualExclusive) {
+ // For mutually exclusive numeric fields, use the reset value from config
+ const mutualExclusiveAttr = fieldElement.getAttribute('data-mutually-exclusive');
+ if (mutualExclusiveAttr) {
+ try {
+ const config = JSON.parse(mutualExclusiveAttr);
+ // Use the reset value from config if provided, otherwise fallback to -1
+ if (config.reset !== undefined) {
+ return config.reset;
+ }
+ } catch {
+ // Ignore parse errors
+ }
return -1;
}
// For non-mutually-exclusive fields, use the min value (typically 0)
@@ -238,6 +170,9 @@ function clearField(fieldElement: HTMLElement): void {
(fieldElement as HTMLTextAreaElement).value = '';
}
+ // Apply visual inactive effect to the form-group container
+ applyInactiveEffect(fieldElement);
+
// Note: We intentionally do NOT dispatch events here to avoid infinite loops
// The visual update is sufficient for the reset behavior
}
@@ -258,18 +193,143 @@ function updateRangeCompanion(rangeInput: HTMLInputElement): void {
}
/**
- * Check if a field's current value differs from its default value
+ * Check if a field has a negative value (representing "not set")
*/
-function hasNonDefaultValue(fieldElement: HTMLElement): boolean {
- const currentValue = getFieldValue(fieldElement);
- const defaultValue = getFieldDefaultValue(fieldElement);
+export function hasNegativeValue(fieldElement: HTMLElement): boolean {
+ const tagName = fieldElement.tagName.toLowerCase();
+ if (tagName === 'input') {
+ const inputType = (fieldElement as HTMLInputElement).type;
+ if (inputType === 'number' || inputType === 'range') {
+ const value = parseFloat((fieldElement as HTMLInputElement).value);
+ return value < 0;
+ }
+ }
+ return false;
+}
- // Handle floating point comparison for numbers
- if (typeof currentValue === 'number' && typeof defaultValue === 'number') {
- return Math.abs(currentValue - defaultValue) > 0.0001;
+/**
+ * Apply visual inactive effect to a field's form-group container.
+ * Adds dimmed styling and sets up hover/focus listeners to temporarily show the field.
+ * The field stays inactive (blurred) as long as it has a negative value.
+ */
+export function applyInactiveEffect(fieldElement: HTMLElement): void {
+ const formGroup = fieldElement.closest('.form-group');
+ if (!formGroup) return;
+
+ // Add the inactive class for visual dimming
+ formGroup.classList.add(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+
+ // Set up listeners for hover behavior
+ // Store references to allow cleanup
+ if (!(fieldElement as any)._inactiveEffectListeners) {
+ const onMouseEnter = () => {
+ // Temporarily remove inactive effect on hover
+ formGroup.classList.remove(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+ };
+
+ const onMouseLeave = () => {
+ // Re-apply inactive effect if field still has negative value
+ if (hasNegativeValue(fieldElement)) {
+ formGroup.classList.add(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+ }
+ };
+
+ const onFocus = () => {
+ // Temporarily remove inactive effect on focus
+ formGroup.classList.remove(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+ };
+
+ const onBlur = () => {
+ // Re-apply inactive effect if field still has negative value
+ if (hasNegativeValue(fieldElement)) {
+ formGroup.classList.add(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+ }
+ };
+
+ // Listen on the form-group for hover (covers label, input, etc.)
+ formGroup.addEventListener('mouseenter', onMouseEnter);
+ formGroup.addEventListener('mouseleave', onMouseLeave);
+ // Also listen for focus/blur on the field itself
+ fieldElement.addEventListener('focus', onFocus);
+ fieldElement.addEventListener('blur', onBlur);
+
+ // Store references for cleanup
+ (fieldElement as any)._inactiveEffectListeners = {
+ formGroup,
+ onMouseEnter,
+ onMouseLeave,
+ onFocus,
+ onBlur,
+ };
+ }
+}
+
+/**
+ * Remove the visual inactive effect from a field's form-group container.
+ * Called when the field becomes active (gets a valid non-negative value).
+ */
+export function removeInactiveEffect(fieldElement: HTMLElement): void {
+ const formGroup = fieldElement.closest('.form-group');
+ if (formGroup) {
+ formGroup.classList.remove(MUTUAL_EXCLUSIVE_INACTIVE_CLASS);
+ }
+
+ // Clean up all listeners
+ const listeners = (fieldElement as any)._inactiveEffectListeners;
+ if (listeners) {
+ listeners.formGroup.removeEventListener('mouseenter', listeners.onMouseEnter);
+ listeners.formGroup.removeEventListener('mouseleave', listeners.onMouseLeave);
+ fieldElement.removeEventListener('focus', listeners.onFocus);
+ fieldElement.removeEventListener('blur', listeners.onBlur);
+ delete (fieldElement as any)._inactiveEffectListeners;
+ }
+}
+
+/**
+ * Update the visual state of a field based on its current value.
+ * If the field has a negative value, apply the inactive effect.
+ * If the field has a non-negative value, remove the inactive effect.
+ * Call this after programmatically changing a field's value.
+ */
+export function updateInactiveEffectState(fieldElement: HTMLElement): void {
+ if (hasNegativeValue(fieldElement)) {
+ applyInactiveEffect(fieldElement);
+ } else {
+ removeInactiveEffect(fieldElement);
}
+}
+
+/**
+ * Check if the current model matches the models whitelist in the mutual exclusive config.
+ * Returns true if mutual exclusivity should be applied.
+ */
+function isModelInWhitelist(fieldElement: HTMLElement, form: HTMLFormElement): boolean {
+ const mutualExclusiveAttr = fieldElement.getAttribute('data-mutually-exclusive');
+ if (!mutualExclusiveAttr) return true; // No config, apply to all
+
+ try {
+ const config = JSON.parse(mutualExclusiveAttr);
+ const whitelistedModels = config.models;
+
+ // If no models specified, apply to all models
+ if (!whitelistedModels || !Array.isArray(whitelistedModels) || whitelistedModels.length === 0) {
+ return true;
+ }
- return currentValue !== defaultValue;
+ // Get the current model from the form's model selector
+ const modelSelector = form.querySelector('#model') as HTMLSelectElement;
+ if (!modelSelector) return true; // No model selector found, apply to all
+
+ const currentModel = modelSelector.value?.toLowerCase();
+ if (!currentModel) return true;
+
+ // Check if current model is in the whitelist (case-insensitive)
+ return whitelistedModels.some(
+ (model: string) => model.toLowerCase() === currentModel,
+ );
+ } catch {
+ return true; // On error, apply to all
+ }
}
/**
@@ -283,22 +343,30 @@ function handleFieldChange(
// Prevent re-entry during reset operations
if (isResetting) return;
+ // Check if mutual exclusivity applies to the current model
+ if (!isModelInWhitelist(changedField, form)) return;
+
const groupRegistry = formGroupRegistry.get(form);
if (!groupRegistry) return;
const groupFields = groupRegistry.get(groupName);
if (!groupFields) return;
- // Only reset other fields if this field has a non-default value
- if (!hasNonDefaultValue(changedField)) return;
+ // Check if the changed field now has a non-negative value (user is activating it)
+ // If the field still has a negative value, don't reset other fields
+ if (hasNegativeValue(changedField)) return;
+
+ // Remove inactive effect from the field being changed (it's now active)
+ removeInactiveEffect(changedField);
// Set flag to prevent re-entry
isResetting = true;
try {
- // Reset all other fields in the group to their defaults
+ // Reset all other fields in the group to their empty/reset values
+ // This clears other fields regardless of their current value
groupFields.forEach((field) => {
- if (field !== changedField && hasNonDefaultValue(field)) {
+ if (field !== changedField) {
clearField(field);
}
});
@@ -383,157 +451,48 @@ function registerFieldWithForm(
// Store handler reference for potential cleanup
(fieldElement as any)._mutuallyExclusiveHandler = changeHandler;
-}
-/**
- * Unregister a field from its mutually exclusive group
- * Call this when a field is removed from the DOM
- */
-export function unregisterMutuallyExclusiveField(fieldElement: HTMLElement): void {
- const form = fieldElement.closest('form') as HTMLFormElement;
- if (!form) return;
-
- const groupRegistry = formGroupRegistry.get(form);
- if (!groupRegistry) return;
-
- const groupName = fieldElement.getAttribute('data-mutually-exclusive');
- if (!groupName) return;
-
- const groupFields = groupRegistry.get(groupName);
- if (groupFields) {
- groupFields.delete(fieldElement);
-
- // Clean up empty groups
- if (groupFields.size === 0) {
- groupRegistry.delete(groupName);
- }
+ // Apply blur effect on initial load if field already has a negative value
+ // This handles cases where saved configuration has a "not set" value
+ if (hasNegativeValue(fieldElement)) {
+ applyInactiveEffect(fieldElement);
}
-
- // Remove event listeners
- const handler = (fieldElement as any)._mutuallyExclusiveHandler;
- if (handler) {
- fieldElement.removeEventListener('input', handler);
- delete (fieldElement as any)._mutuallyExclusiveHandler;
- }
-}
-
-/**
- * Get all fields in a mutually exclusive group within a form
- */
-export function getMutuallyExclusiveGroup(
- form: HTMLFormElement,
- groupName: string,
-): HTMLElement[] {
- const groupRegistry = formGroupRegistry.get(form);
- if (!groupRegistry) return [];
-
- const groupFields = groupRegistry.get(groupName);
- if (!groupFields) return [];
-
- return Array.from(groupFields);
}
/**
- * Reset all fields in a mutually exclusive group to their defaults
+ * Update the visibility of mutual exclusive hint messages based on the current model.
+ * Hints with a `data-mutual-exclusive-models` attribute are only shown when the
+ * current model is in the whitelist.
+ *
+ * Call this function when the model selection changes to ensure hints are only
+ * visible for models that support mutual exclusivity (e.g., Anthropic models).
+ *
+ * @param form The form element containing the hints and model selector
*/
-export function resetMutuallyExclusiveGroup(
- form: HTMLFormElement,
- groupName: string,
-): void {
- isResetting = true;
- try {
- const fields = getMutuallyExclusiveGroup(form, groupName);
- fields.forEach((field) => clearField(field));
- } finally {
- isResetting = false;
- }
-}
+export function updateMutualExclusiveHintsVisibility(form: HTMLFormElement): void {
+ // Get the current model from the form's model selector
+ const modelSelector = form.querySelector('#model') as HTMLSelectElement;
+ if (!modelSelector) return;
-/**
- * Check if any field in a mutually exclusive group has a non-default value
- */
-export function hasGroupNonDefaultValue(
- form: HTMLFormElement,
- groupName: string,
-): boolean {
- const fields = getMutuallyExclusiveGroup(form, groupName);
- return fields.some((field) => hasNonDefaultValue(field));
-}
+ const currentModel = modelSelector.value?.toLowerCase();
+ if (!currentModel) return;
-/**
- * Get the field in a group that currently has a non-default value
- * Returns null if all fields have default values
- */
-export function getActiveFieldInGroup(
- form: HTMLFormElement,
- groupName: string,
-): HTMLElement | null {
- const fields = getMutuallyExclusiveGroup(form, groupName);
- return fields.find((field) => hasNonDefaultValue(field)) || null;
-}
+ // Find all hints with model whitelist
+ const hints = form.querySelectorAll('.mutual-exclusive-hint[data-mutual-exclusive-models]');
-/**
- * Normalize a field value for serialization/API submission
- * Converts -1 sentinel values to undefined for mutually exclusive numeric fields
- *
- * @param value The raw field value
- * @param fieldElement Optional field element to check if it has mutually exclusive behavior
- * @returns The normalized value (undefined if it's a -1 sentinel, otherwise the original value)
- */
-export function normalizeMutuallyExclusiveValue(
- value: any,
- fieldElement?: HTMLElement,
-): any {
- // If value is exactly -1 and field has mutually exclusive attribute, return undefined
- if (value === -1 || value === '-1') {
- if (fieldElement) {
- const hasMutualExclusive = fieldElement.getAttribute('data-mutually-exclusive');
- if (hasMutualExclusive) {
- return undefined;
- }
- } else {
- // If no field element provided, assume -1 should be treated as undefined
- // This is safe because -1 is our sentinel value for "unset"
- return undefined;
- }
- }
-
- return value;
-}
+ hints.forEach((hint: HTMLElement) => {
+ const modelsAttr = hint.getAttribute('data-mutual-exclusive-models');
+ if (!modelsAttr) return;
-/**
- * Normalize an object of field values, converting -1 sentinel values to undefined
- * This should be called before sending data to the backend API
- *
- * @param data Object containing field names and values
- * @param form Optional form element to check field attributes
- * @returns Normalized object with -1 values converted to undefined
- *
- * @example
- * const formData = { temperature: 0.7, topP: -1, maxTokens: 1000 };
- * const normalized = normalizeMutuallyExclusiveParams(formData);
- * // Result: { temperature: 0.7, topP: undefined, maxTokens: 1000 }
- */
-export function normalizeMutuallyExclusiveParams(
- data: Record<string, any>,
- form?: HTMLFormElement,
-): Record<string, any> {
- const normalized: Record<string, any> = {};
-
- for (const [key, value] of Object.entries(data)) {
- let fieldElement: HTMLElement | null = null;
-
- // Try to find the field element if form is provided
- if (form) {
- // Try common field selectors
- fieldElement =
- form.querySelector(`#${key}`) ||
- form.querySelector(`[name="${key}"]`) ||
- null;
+ try {
+ const whitelistedModels: string[] = JSON.parse(modelsAttr);
+ const shouldShow = whitelistedModels.some(
+ (model) => model.toLowerCase() === currentModel,
+ );
+ hint.style.display = shouldShow ? '' : 'none';
+ } catch {
+ // On parse error, hide the hint
+ hint.style.display = 'none';
}
-
- normalized[key] = normalizeMutuallyExclusiveValue(value, fieldElement || undefined);
- }
-
- return normalized;
+ });
}
diff --git a/packages/app/static/css/smyth-form.css b/packages/app/static/css/smyth-form.css
index 7e139395..5fcf5f94 100644
--- a/packages/app/static/css/smyth-form.css
+++ b/packages/app/static/css/smyth-form.css
@@ -497,3 +497,26 @@ button.inner-link:hover {
box-shadow: 0 0 0 2px #c3e6cb;
}
/* #endregion JSON Field Synchronizer */
+
+/* #region Mutually Exclusive Fields */
+/**
+ * Visual feedback for fields reset due to mutual exclusivity.
+ * When a field is reset (e.g., Temperature resets Top P for Anthropic),
+ * the inactive field appears dimmed until the user hovers over it.
+ */
+.form-group.mutual-exclusive-inactive {
+ opacity: 0.5;
+ transition: opacity 0.2s ease;
+}
+
+.form-group.mutual-exclusive-inactive:hover {
+ opacity: 1;
+}
+
+/* Ensure input elements inside also get proper cursor */
+.form-group.mutual-exclusive-inactive input,
+.form-group.mutual-exclusive-inactive select,
+.form-group.mutual-exclusive-inactive textarea {
+ cursor: pointer;
+}
+/* #endregion Mutually Exclusive Fields */