import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Switch } from '@/components/ui/switch' import { Textarea } from '@/components/ui/textarea' import { useNostr } from '@/providers/NostrProvider' import { DEFAULT_MODEL, fetchModels, TAnthropicModel } from '@/services/llm.service' import storage, { dispatchSettingsChanged } from '@/services/local-storage.service' import { TLlmConfig } from '@/types' import { LoaderCircle } from 'lucide-react' import { useCallback, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' const DEFAULT_CONFIG: TLlmConfig = { apiKey: '', model: '', systemPrompt: '', autoRewrite: false } export default function LlmSetting() { const { t } = useTranslation() const { pubkey } = useNostr() const [config, setConfig] = useState(DEFAULT_CONFIG) const [models, setModels] = useState([]) const [loadingModels, setLoadingModels] = useState(false) useEffect(() => { if (pubkey) { setConfig(storage.getLlmConfig(pubkey) ?? DEFAULT_CONFIG) } }, [pubkey]) // Fetch models when API key changes useEffect(() => { if (!config.apiKey || config.apiKey.length < 10) { setModels([]) return } let cancelled = false const timer = setTimeout(async () => { setLoadingModels(true) try { const result = await fetchModels(config.apiKey) if (!cancelled) setModels(result) } catch (err) { console.error('[LLM] Failed to fetch models:', err) if (!cancelled) setModels([]) } finally { if (!cancelled) setLoadingModels(false) } }, 500) // debounce while typing the key return () => { cancelled = true clearTimeout(timer) } }, [config.apiKey]) const save = useCallback( (updated: TLlmConfig) => { setConfig(updated) if (pubkey) { storage.setLlmConfig(pubkey, updated) dispatchSettingsChanged() } }, [pubkey] ) const selectedModel = config.model || DEFAULT_MODEL return (
save({ ...config, apiKey: e.target.value })} />
{loadingModels ? (
{t('Loading models...')}
) : models.length > 0 ? ( ) : (
{config.apiKey ? t('Enter a valid API key to load models') : t('Enter API key first')}
)}