File size: 2,217 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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,
  };
}