File size: 14,957 Bytes
f5754e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import React, { useState, useEffect } from 'react';

interface Settings {
  default_llm_provider: string;
  embedding_provider: string;
  openai_api_key: string;
  openai_model: string;
  anthropic_api_key: string;
  anthropic_model: string;
  google_api_key: string;
  gemini_model: string;
  ollama_base_url: string;
  ollama_model: string;
  ollama_embedding_model: string;
  huggingface_api_key: string;
  huggingface_model: string;
  huggingface_embedding_model: string;
}

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api';

const SettingsView: React.FC = () => {
  const [settings, setSettings] = useState<Settings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [ollamaModels, setOllamaModels] = useState<string[]>([]);
  const [hfModels, setHfModels] = useState<string[]>([]);

  // State for tracking if custom input is shown
  const [showCustom, setShowCustom] = useState<Record<string, boolean>>({});

  useEffect(() => {
    fetchSettings();
    fetchHfModels();
  }, []);

  useEffect(() => {
    if (settings?.ollama_base_url) {
      fetchOllamaModels(settings.ollama_base_url);
    }
  }, [settings?.ollama_base_url]);

  const fetchOllamaModels = async (baseUrl: string) => {
    try {
      const res = await fetch(`${API_BASE}/system/ollama/models?base_url=${encodeURIComponent(baseUrl)}`);
      if (res.ok) {
        const data = await res.json();
        setOllamaModels(data.models || []);
      }
    } catch (e) {
      console.error(e);
    }
  };

  const fetchHfModels = async () => {
    try {
      const res = await fetch(`${API_BASE}/system/huggingface/models`);
      if (res.ok) {
        const data = await res.json();
        setHfModels(data.models || []);
      }
    } catch (e) {
      console.error(e);
    }
  };

  const fetchSettings = async () => {
    try {
      const response = await fetch(`${API_BASE}/system/settings`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      if (!response.ok) throw new Error('Failed to fetch settings');
      const data = await response.json();
      // Replace nulls with empty strings for input values
      const sanitizedData = Object.keys(data).reduce((acc, key) => {
        acc[key as keyof Settings] = data[key] || '';
        return acc;
      }, {} as Settings);
      setSettings(sanitizedData);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    if (settings) {
      if (value === '__custom__') {
        setShowCustom({ ...showCustom, [name]: true });
        setSettings({ ...settings, [name]: '' });
      } else {
        setSettings({ ...settings, [name]: value });
      }
    }
  };

  const renderDropdownOrInput = (name: keyof Settings, options: string[], placeholder: string = "") => {
    // Always include the current value in the options so the select doesn't break
    const currentValue = settings?.[name] as string;
    const finalOptions = [...options];
    if (currentValue && !finalOptions.includes(currentValue)) {
      finalOptions.unshift(currentValue);
    }

    const isCustom = showCustom[name];
    
    if (isCustom) {
      return (
        <div style={{ display: 'flex', gap: '0.5rem' }}>
          <input 
            type="text" 
            name={name} 
            value={currentValue || ''} 
            onChange={handleChange}
            placeholder={placeholder}
            style={{ padding: '0.5rem', border: '1px solid #ccc', flex: 1 }}
          />
          <button 
            type="button" 
            onClick={() => {
              setShowCustom({ ...showCustom, [name]: false });
              setSettings({ ...settings!, [name]: finalOptions[0] || '' });
            }}
            style={{ padding: '0.5rem', background: '#eee', border: '1px solid #ccc', cursor: 'pointer' }}
          >
            Cancel
          </button>
        </div>
      );
    }

    return (
      <select 
        name={name} 
        value={currentValue || ''} 
        onChange={handleChange}
        style={{ padding: '0.5rem', border: '1px solid #ccc' }}
      >
        <option value="" disabled>Select a model...</option>
        {finalOptions.map(m => <option key={m} value={m}>{m}</option>)}
        <option value="__custom__">-- Type custom model --</option>
      </select>
    );
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSuccess(null);

    try {
      const response = await fetch(`${API_BASE}/system/settings`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(settings)
      });
      
      if (!response.ok) throw new Error('Failed to save settings');
      
      setSuccess('Settings updated successfully!');
      setTimeout(() => setSuccess(null), 3000);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <div style={{ padding: '2rem' }}>Loading settings...</div>;

  return (
    <div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto', fontFamily: 'var(--font-sans)' }}>
      <h1 style={{ fontSize: '1.5rem', marginBottom: '1.5rem', borderBottom: '2px solid #000', paddingBottom: '0.5rem' }}>SYSTEM SETTINGS</h1>
      
      {error && <div style={{ background: '#fee', color: '#c00', padding: '1rem', marginBottom: '1rem', border: '1px solid #c00' }}>{error}</div>}
      {success && <div style={{ background: '#efe', color: '#090', padding: '1rem', marginBottom: '1rem', border: '1px solid #090' }}>{success}</div>}

      <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
        
        {/* Global Providers */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd', background: '#fcfcfc' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>Global Providers</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Default LLM Provider</label>
              <select 
                name="default_llm_provider" 
                value={settings?.default_llm_provider} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              >
                <option value="ollama">Ollama</option>
                <option value="openai">OpenAI</option>
                <option value="anthropic">Anthropic</option>
                <option value="gemini">Gemini</option>
                <option value="huggingface">Hugging Face</option>
              </select>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Embedding Provider</label>
              <select 
                name="embedding_provider" 
                value={settings?.embedding_provider} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              >
                <option value="ollama">Ollama</option>
                <option value="openai">OpenAI</option>
                <option value="huggingface">Hugging Face</option>
              </select>
            </div>
          </div>
        </div>

        {/* Hugging Face Settings */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>Hugging Face</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>API Token</label>
              <input 
                type="password" 
                name="huggingface_api_key" 
                value={settings?.huggingface_api_key} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
                placeholder="hf_..."
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>LLM Model</label>
              {renderDropdownOrInput('huggingface_model', hfModels, 'meta-llama/Meta-Llama-3-8B-Instruct')}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Embedding Model</label>
              {renderDropdownOrInput('huggingface_embedding_model', hfModels, 'BAAI/bge-large-en-v1.5')}
            </div>
          </div>
        </div>

        {/* Gemini Settings */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>Google Gemini</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Google API Key</label>
              <input 
                type="password" 
                name="google_api_key" 
                value={settings?.google_api_key} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Model</label>
              <input 
                type="text" 
                name="gemini_model" 
                value={settings?.gemini_model} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
          </div>
        </div>

        {/* Ollama Settings */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>Ollama</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', gridColumn: 'span 2' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Base URL</label>
              <input 
                type="text" 
                name="ollama_base_url" 
                value={settings?.ollama_base_url} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>LLM Model</label>
              {renderDropdownOrInput('ollama_model', ollamaModels, 'llama3')}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Embedding Model</label>
              {renderDropdownOrInput('ollama_embedding_model', ollamaModels, 'nomic-embed-text')}
            </div>
          </div>
        </div>

        {/* OpenAI Settings */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>OpenAI</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>API Key</label>
              <input 
                type="password" 
                name="openai_api_key" 
                value={settings?.openai_api_key} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Model</label>
              <input 
                type="text" 
                name="openai_model" 
                value={settings?.openai_model} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
          </div>
        </div>

        {/* Anthropic Settings */}
        <div style={{ padding: '1.5rem', border: '1px solid #ddd' }}>
          <h2 style={{ fontSize: '1.1rem', marginBottom: '1rem' }}>Anthropic</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>API Key</label>
              <input 
                type="password" 
                name="anthropic_api_key" 
                value={settings?.anthropic_api_key} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <label style={{ fontWeight: 600, fontSize: '0.85rem' }}>Model</label>
              <input 
                type="text" 
                name="anthropic_model" 
                value={settings?.anthropic_model} 
                onChange={handleChange}
                style={{ padding: '0.5rem', border: '1px solid #ccc' }}
              />
            </div>
          </div>
        </div>

        <button 
          type="submit" 
          disabled={saving}
          style={{ 
            padding: '0.75rem', 
            background: '#000', 
            color: '#fff', 
            fontWeight: 'bold', 
            border: 'none', 
            cursor: saving ? 'not-allowed' : 'pointer',
            opacity: saving ? 0.7 : 1,
            marginTop: '1rem'
          }}
        >
          {saving ? 'SAVING...' : 'SAVE SETTINGS'}
        </button>
      </form>
    </div>
  );
};

export default SettingsView;