"use client"; import {useEffect, useState} from "react"; import {Loader2} from "lucide-react"; import {Button} from "@/components/ui/button"; interface AIConfig { apiKey: string; baseUrl: string; model: string; } const defaultAIConfig: AIConfig = { apiKey: "", baseUrl: "https://api.openai.com/v1", model: "gpt-3.5-turbo", }; export default function AISettingsPage() { const [config, setConfig] = useState(defaultAIConfig); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [testing, setTesting] = useState(false); const [testResult, setTestResult] = useState<"success" | "error" | null>(null); // 加载配置 useEffect(() => { fetch("/api/config") .then((res) => res.json()) .then((result) => { if (result.success && result.data) { setConfig({ apiKey: result.data.ai?.apiKey || defaultAIConfig.apiKey, baseUrl: result.data.ai?.baseUrl || defaultAIConfig.baseUrl, model: result.data.ai?.model || defaultAIConfig.model, }); } }) .catch(console.error) .finally(() => setLoading(false)); }, []); // 保存配置 const handleSave = async () => { setSaving(true); try { const response = await fetch("/api/config", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ai: config}), }); const result = await response.json(); if (result.success) { setTestResult("success"); setTimeout(() => setTestResult(null), 3000); } else { setTestResult("error"); } } catch (error) { console.error("Failed to save config:", error); setTestResult("error"); } finally { setSaving(false); } }; // 测试 AI 连接 const handleTestAI = async () => { if (!config.apiKey) return; // 先保存配置 await handleSave(); setTesting(true); setTestResult(null); try { const response = await fetch(`/api/ai/translate?word=${encodeURIComponent("早餐")}`); const result = await response.json(); if (result.english) { setTestResult("success"); } else { setTestResult("error"); } } catch { setTestResult("error"); } finally { setTesting(false); } }; if (loading) { return (

大模型设置

配置 AI 翻译服务

); } return (

大模型设置

配置 AI 翻译服务

{testResult === "success" && ( 配置成功! )} {testResult === "error" && ( 配置失败,请检查 API Key )}
setConfig({...config, apiKey: e.target.value})} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder="sk-..." />
setConfig({...config, baseUrl: e.target.value})} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder="https://api.openai.com/v1" />
setConfig({...config, model: e.target.value})} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" placeholder="gpt-3.5-turbo" />
); }