provider-config-panel.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. 'use client';
  2. import { useState, useCallback, useEffect } from 'react';
  3. import { Button } from '@/components/ui/button';
  4. import { Input } from '@/components/ui/input';
  5. import { Label } from '@/components/ui/label';
  6. import { Checkbox } from '@/components/ui/checkbox';
  7. import {
  8. AlertDialog,
  9. AlertDialogAction,
  10. AlertDialogCancel,
  11. AlertDialogContent,
  12. AlertDialogDescription,
  13. AlertDialogFooter,
  14. AlertDialogHeader,
  15. AlertDialogTitle,
  16. } from '@/components/ui/alert-dialog';
  17. import {
  18. Loader2,
  19. CheckCircle2,
  20. XCircle,
  21. Eye,
  22. EyeOff,
  23. RotateCcw,
  24. Plus,
  25. Zap,
  26. Settings2,
  27. Trash2,
  28. Sparkles,
  29. Wrench,
  30. FileText,
  31. Send,
  32. } from 'lucide-react';
  33. import { useI18n } from '@/lib/hooks/use-i18n';
  34. import type { ProviderConfig } from '@/lib/ai/providers';
  35. import type { ProvidersConfig } from '@/lib/types/settings';
  36. import { formatContextWindow } from './utils';
  37. import { cn } from '@/lib/utils';
  38. interface ProviderConfigPanelProps {
  39. provider: ProviderConfig;
  40. initialApiKey: string;
  41. initialBaseUrl: string;
  42. initialRequiresApiKey: boolean;
  43. providersConfig: ProvidersConfig;
  44. onConfigChange: (apiKey: string, baseUrl: string, requiresApiKey: boolean) => void;
  45. onSave: () => void; // Auto-save on blur
  46. onEditModel: (index: number) => void;
  47. onDeleteModel: (index: number) => void;
  48. onAddModel: () => void;
  49. onResetToDefault?: () => void; // Reset provider to default configuration
  50. isBuiltIn: boolean; // To determine if reset button should be shown
  51. }
  52. export function ProviderConfigPanel({
  53. provider,
  54. initialApiKey,
  55. initialBaseUrl,
  56. initialRequiresApiKey,
  57. providersConfig,
  58. onConfigChange,
  59. onSave,
  60. onEditModel,
  61. onDeleteModel,
  62. onAddModel,
  63. onResetToDefault,
  64. isBuiltIn,
  65. }: ProviderConfigPanelProps) {
  66. const { t } = useI18n();
  67. // Local state for this provider
  68. const [apiKey, setApiKey] = useState(initialApiKey);
  69. const [baseUrl, setBaseUrl] = useState(initialBaseUrl);
  70. const [requiresApiKey, setRequiresApiKey] = useState(initialRequiresApiKey);
  71. const [showApiKey, setShowApiKey] = useState(false);
  72. const [testStatus, setTestStatus] = useState<'idle' | 'testing' | 'success' | 'error'>('idle');
  73. const [testMessage, setTestMessage] = useState('');
  74. const [showResetDialog, setShowResetDialog] = useState(false);
  75. // Update local state when provider changes or initial values change
  76. useEffect(() => {
  77. // eslint-disable-next-line react-hooks/set-state-in-effect -- Sync local state from props on provider change
  78. setApiKey(initialApiKey);
  79. setBaseUrl(initialBaseUrl);
  80. setRequiresApiKey(initialRequiresApiKey);
  81. setTestStatus('idle');
  82. setTestMessage('');
  83. }, [provider.id, initialApiKey, initialBaseUrl, initialRequiresApiKey]);
  84. // Notify parent of changes
  85. const handleApiKeyChange = (key: string) => {
  86. setApiKey(key);
  87. onConfigChange(key, baseUrl, requiresApiKey);
  88. };
  89. const handleBaseUrlChange = (url: string) => {
  90. setBaseUrl(url);
  91. onConfigChange(apiKey, url, requiresApiKey);
  92. };
  93. const handleRequiresApiKeyChange = (requires: boolean) => {
  94. setRequiresApiKey(requires);
  95. onConfigChange(apiKey, baseUrl, requires);
  96. };
  97. const handleTestApi = useCallback(async () => {
  98. setTestStatus('testing');
  99. setTestMessage('');
  100. const availableModels = providersConfig[provider.id]?.models || [];
  101. if (availableModels.length === 0) {
  102. setTestStatus('error');
  103. setTestMessage(t('settings.noModelsAvailable') || 'No models available for testing');
  104. return;
  105. }
  106. const testModelId = availableModels[0].id;
  107. try {
  108. const response = await fetch('/api/verify-model', {
  109. method: 'POST',
  110. headers: { 'Content-Type': 'application/json' },
  111. body: JSON.stringify({
  112. apiKey,
  113. baseUrl,
  114. model: `${provider.id}:${testModelId}`,
  115. providerType: provider.type,
  116. requiresApiKey: requiresApiKey,
  117. }),
  118. });
  119. const data = await response.json();
  120. if (data.success) {
  121. setTestStatus('success');
  122. setTestMessage(t('settings.connectionSuccess'));
  123. } else {
  124. setTestStatus('error');
  125. setTestMessage(data.error || t('settings.connectionFailed'));
  126. }
  127. } catch (_error) {
  128. setTestStatus('error');
  129. setTestMessage(t('settings.connectionFailed'));
  130. }
  131. }, [apiKey, baseUrl, provider.id, provider.type, requiresApiKey, providersConfig, t]);
  132. const models = providersConfig[provider.id]?.models || [];
  133. const isServerConfigured = providersConfig[provider.id]?.isServerConfigured;
  134. return (
  135. <div className="space-y-6 max-w-3xl">
  136. {/* Server-configured notice */}
  137. {isServerConfigured && (
  138. <div className="rounded-lg border border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30 p-3 text-sm text-blue-700 dark:text-blue-300">
  139. {t('settings.serverConfiguredNotice')}
  140. </div>
  141. )}
  142. {/* API Key */}
  143. <div className="space-y-2">
  144. <Label>{t('settings.apiSecret')}</Label>
  145. <div className="flex gap-2">
  146. <div className="relative flex-1">
  147. <Input
  148. name={`llm-api-key-${provider.id}`}
  149. type={showApiKey ? 'text' : 'password'}
  150. autoComplete="new-password"
  151. autoCapitalize="none"
  152. autoCorrect="off"
  153. spellCheck={false}
  154. placeholder={isServerConfigured ? t('settings.optionalOverride') : 'sk-...'}
  155. value={apiKey}
  156. onChange={(e) => handleApiKeyChange(e.target.value)}
  157. onBlur={onSave}
  158. disabled={!requiresApiKey && !isServerConfigured}
  159. className="h-8 pr-8"
  160. />
  161. <button
  162. type="button"
  163. onClick={() => setShowApiKey(!showApiKey)}
  164. className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
  165. disabled={!requiresApiKey}
  166. >
  167. {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
  168. </button>
  169. </div>
  170. <Button
  171. variant="outline"
  172. size="sm"
  173. onClick={handleTestApi}
  174. disabled={
  175. testStatus === 'testing' || (requiresApiKey && !apiKey && !isServerConfigured)
  176. }
  177. className="gap-1.5"
  178. >
  179. {testStatus === 'testing' ? (
  180. <Loader2 className="h-3.5 w-3.5 animate-spin" />
  181. ) : (
  182. <>
  183. <Zap className="h-3.5 w-3.5" />
  184. {t('settings.testConnection')}
  185. </>
  186. )}
  187. </Button>
  188. </div>
  189. {testMessage && (
  190. <div
  191. className={cn(
  192. 'rounded-lg p-3 text-sm overflow-hidden',
  193. testStatus === 'success' && 'bg-green-50 text-green-700 border border-green-200',
  194. testStatus === 'error' && 'bg-red-50 text-red-700 border border-red-200',
  195. )}
  196. >
  197. <div className="flex items-start gap-2 min-w-0">
  198. {testStatus === 'success' && <CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0" />}
  199. {testStatus === 'error' && <XCircle className="h-4 w-4 mt-0.5 shrink-0" />}
  200. <p className="flex-1 min-w-0 break-all">{testMessage}</p>
  201. </div>
  202. </div>
  203. )}
  204. <div className="flex items-center space-x-2">
  205. <Checkbox
  206. id={`requires-api-key-${provider.id}`}
  207. checked={requiresApiKey}
  208. onCheckedChange={(checked) => {
  209. handleRequiresApiKeyChange(checked as boolean);
  210. onSave();
  211. }}
  212. />
  213. <label
  214. htmlFor={`requires-api-key-${provider.id}`}
  215. className="text-sm cursor-pointer text-muted-foreground"
  216. >
  217. {t('settings.requiresApiKey')}
  218. </label>
  219. </div>
  220. </div>
  221. {/* API Host */}
  222. <div className="space-y-2">
  223. <Label>{t('settings.apiHost')}</Label>
  224. <Input
  225. name={`llm-base-url-${provider.id}`}
  226. type="url"
  227. autoComplete="off"
  228. autoCapitalize="none"
  229. autoCorrect="off"
  230. spellCheck={false}
  231. placeholder={provider.defaultBaseUrl || 'https://api.example.com/v1'}
  232. value={baseUrl}
  233. onChange={(e) => handleBaseUrlChange(e.target.value)}
  234. onBlur={onSave}
  235. className="h-8"
  236. />
  237. {(() => {
  238. const effectiveBaseUrl = baseUrl || provider.defaultBaseUrl || '';
  239. if (!effectiveBaseUrl) return null;
  240. // Generate endpoint path based on provider type
  241. let endpointPath = '';
  242. switch (provider.type) {
  243. case 'openai':
  244. endpointPath = '/chat/completions';
  245. break;
  246. case 'anthropic':
  247. endpointPath = '/messages';
  248. break;
  249. case 'google':
  250. endpointPath = '/models/[model]';
  251. break;
  252. default:
  253. endpointPath = '';
  254. }
  255. const fullUrl = effectiveBaseUrl + endpointPath;
  256. return (
  257. <p className="text-xs text-muted-foreground break-all">
  258. {t('settings.requestUrl')}: {fullUrl}
  259. </p>
  260. );
  261. })()}
  262. </div>
  263. {/* Models - No selection state, just list for management */}
  264. <div className="space-y-3">
  265. <div className="flex items-center justify-between flex-wrap gap-2">
  266. <Label className="text-base">{t('settings.models')}</Label>
  267. <div className="flex items-center gap-2 flex-wrap">
  268. {isBuiltIn && onResetToDefault && (
  269. <Button
  270. variant="outline"
  271. size="sm"
  272. onClick={() => setShowResetDialog(true)}
  273. className="gap-1.5"
  274. >
  275. <RotateCcw className="h-3.5 w-3.5" />
  276. {t('settings.reset')}
  277. </Button>
  278. )}
  279. <Button variant="outline" size="sm" onClick={onAddModel} className="gap-1.5">
  280. <Plus className="h-3.5 w-3.5" />
  281. {t('settings.addNewModel')}
  282. </Button>
  283. </div>
  284. </div>
  285. <p className="text-xs text-muted-foreground">{t('settings.modelsManagementDescription')}</p>
  286. <div className="space-y-1.5">
  287. {models.map((model, index) => {
  288. return (
  289. <div
  290. key={model.id}
  291. className="flex items-center justify-between p-3 rounded-lg border border-border/50 bg-card"
  292. >
  293. <div className="flex-1">
  294. <div className="font-mono text-sm font-medium mb-1.5">{model.name}</div>
  295. <div className="flex items-center gap-2 text-xs text-muted-foreground">
  296. {/* Capabilities */}
  297. <div className="flex items-center gap-1">
  298. {model.capabilities?.vision && (
  299. <div title={t('settings.capabilities.vision')}>
  300. <Sparkles className="h-3 w-3" />
  301. </div>
  302. )}
  303. {model.capabilities?.tools && (
  304. <div title={t('settings.capabilities.tools')}>
  305. <Wrench className="h-3 w-3" />
  306. </div>
  307. )}
  308. {model.capabilities?.streaming && (
  309. <div title={t('settings.capabilities.streaming')}>
  310. <Zap className="h-3 w-3" />
  311. </div>
  312. )}
  313. </div>
  314. {/* Context Window */}
  315. {model.contextWindow && (
  316. <span className="flex items-center gap-0.5">
  317. <FileText className="h-3 w-3" />
  318. <span className="text-[10px]">
  319. {formatContextWindow(model.contextWindow)}
  320. </span>
  321. </span>
  322. )}
  323. {/* Output Window */}
  324. {model.outputWindow && (
  325. <span className="flex items-center gap-0.5">
  326. <Send className="h-3 w-3" />
  327. <span className="text-[10px]">
  328. {formatContextWindow(model.outputWindow)}
  329. </span>
  330. </span>
  331. )}
  332. </div>
  333. </div>
  334. {/* Edit/Delete Buttons */}
  335. <div className="flex items-center gap-1">
  336. <Button
  337. variant="outline"
  338. size="sm"
  339. className="h-8 px-2"
  340. onClick={() => onEditModel(index)}
  341. title={t('settings.editModel')}
  342. >
  343. <Settings2 className="h-3.5 w-3.5" />
  344. </Button>
  345. <Button
  346. variant="outline"
  347. size="sm"
  348. className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
  349. onClick={() => onDeleteModel(index)}
  350. title={t('settings.deleteModel')}
  351. >
  352. <Trash2 className="h-3.5 w-3.5" />
  353. </Button>
  354. </div>
  355. </div>
  356. );
  357. })}
  358. </div>
  359. </div>
  360. {/* Reset Confirmation Dialog */}
  361. <AlertDialog open={showResetDialog} onOpenChange={setShowResetDialog}>
  362. <AlertDialogContent>
  363. <AlertDialogHeader>
  364. <AlertDialogTitle>{t('settings.resetToDefault')}</AlertDialogTitle>
  365. <AlertDialogDescription>{t('settings.resetConfirmDescription')}</AlertDialogDescription>
  366. </AlertDialogHeader>
  367. <AlertDialogFooter>
  368. <AlertDialogCancel>{t('settings.cancelEdit')}</AlertDialogCancel>
  369. <AlertDialogAction
  370. onClick={() => {
  371. setShowResetDialog(false);
  372. onResetToDefault?.();
  373. }}
  374. >
  375. {t('settings.confirmReset')}
  376. </AlertDialogAction>
  377. </AlertDialogFooter>
  378. </AlertDialogContent>
  379. </AlertDialog>
  380. </div>
  381. );
  382. }