Spaces:
Running
Running
| import { useState, useEffect } from "react"; | |
| import { getDefaultModel, getModelById } from "@/lib/models"; | |
| import { useToast } from "@/hooks/use-toast"; | |
| const MODEL_PREFERENCE_KEY = "agentgraph_model_preference"; | |
| export function useModelPreferences() { | |
| const [selectedModel, setSelectedModel] = useState<string>(getDefaultModel()); | |
| const [isLoading, setIsLoading] = useState(true); | |
| const { toast } = useToast(); | |
| // Load saved preference on mount | |
| useEffect(() => { | |
| try { | |
| const savedModel = localStorage.getItem(MODEL_PREFERENCE_KEY); | |
| if (savedModel && getModelById(savedModel)) { | |
| setSelectedModel(savedModel); | |
| } | |
| } catch (error) { | |
| console.warn("Failed to load model preference from localStorage:", error); | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }, []); | |
| // Save preference to localStorage | |
| const updateModelPreference = (modelId: string) => { | |
| try { | |
| // Validate model exists | |
| const modelConfig = getModelById(modelId); | |
| if (!modelConfig) { | |
| console.warn(`Invalid model ID: ${modelId}`); | |
| toast({ | |
| title: "Model Selection Failed", | |
| description: "The selected model is not available.", | |
| variant: "destructive", | |
| }); | |
| return; | |
| } | |
| const previousModel = selectedModel; | |
| setSelectedModel(modelId); | |
| localStorage.setItem(MODEL_PREFERENCE_KEY, modelId); | |
| // Show success notification only if model actually changed | |
| if (previousModel !== modelId) { | |
| toast({ | |
| title: "Model Updated", | |
| description: `Successfully switched to ${modelConfig.name}. This will be used for all new graph generations.`, | |
| variant: "success", | |
| }); | |
| } | |
| } catch (error) { | |
| console.error("Failed to save model preference to localStorage:", error); | |
| toast({ | |
| title: "Model Selection Failed", | |
| description: "Failed to save your model preference. Please try again.", | |
| variant: "destructive", | |
| }); | |
| } | |
| }; | |
| // Get current model config | |
| const currentModelConfig = getModelById(selectedModel); | |
| return { | |
| selectedModel, | |
| currentModelConfig, | |
| updateModelPreference, | |
| isLoading, | |
| }; | |
| } | |