"use client"; import * as React from "react"; import { Loader2Icon, PlugZapIcon, PlusIcon, RefreshCwIcon, RotateCcwIcon, SaveIcon, StarIcon, Trash2Icon, ZapIcon, } from "lucide-react"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Separator } from "@/components/ui/separator"; import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"; import { Switch } from "@/components/ui/switch"; import { api } from "@/lib/api"; import type { LLMPoolMember, LLMPoolStatus, LLMProfile } from "@/lib/types"; import { cn } from "@/lib/utils"; // 思考开关(thinking.type)与思考强度(reasoning_effort)是两个【互相独立】的字段, // 各自单独设置——有些接口没有 thinking 字段、只靠强度参数就能激活思考,故需解耦。 // 存库空字符串 = 该字段【不发送】;Radix Select 不接受空 value,故 UI 用 "none" // 哨兵表示不发送,存取时与 "" 互转(NONE / fromStore / toStore)。 const NONE = "none"; const fromStore = (v?: string) => (v ? v : NONE); const toStore = (v: string) => (v === NONE ? "" : v); const THINKING_TYPES: { value: string; label: string }[] = [ { value: NONE, label: "不发送(默认)" }, { value: "disabled", label: "关闭" }, { value: "enabled", label: "开启" }, ]; const EFFORT_LEVELS: { value: string; label: string }[] = [ { value: NONE, label: "不发送(默认)" }, { value: "low", label: "low" }, { value: "medium", label: "medium" }, { value: "high", label: "high" }, { value: "xhigh", label: "xhigh" }, { value: "max", label: "max" }, ]; function cooldownText(secs: number) { if (secs <= 0) return ""; if (secs < 60) return `${secs}s`; return `${Math.ceil(secs / 60)}min`; } // 一个配置在卡片上显示的「是否正常」。没填 Key 的配置根本发不出请求,比熔断更该先说; // 其余状态来自轮询的熔断记录(轮询关着时不会产生新记录,此时「正常」= 没有已知故障)。 type Health = { label: string; cls: string; hint?: string }; function healthOf(p: LLMProfile, m?: LLMPoolMember): Health { if (!p.api_key_hint) { return { label: "未配置 Key", cls: "border-muted-foreground/40 text-muted-foreground", hint: "未填 API Key,无法调用", }; } if (m?.state === "tripped") { return { label: m.cooldown_secs > 0 ? `已熔断 · ${cooldownText(m.cooldown_secs)}` : "已熔断", cls: "border-destructive/50 text-destructive", hint: m.last_error, }; } if (m?.state === "degraded") { return { label: `异常 · 失败 ${m.fails} 次`, cls: "border-amber-500/50 text-amber-600 dark:text-amber-400", hint: m.last_error, }; } return { label: "正常", cls: "border-emerald-500/50 text-emerald-600 dark:text-emerald-400" }; } // ───────────────────────────────────────────────────────────────────────────── // 轮询配置抽屉 // ───────────────────────────────────────────────────────────────────────────── function PoolSheet({ open, onOpenChange, pool, onReload, }: { open: boolean; onOpenChange: (o: boolean) => void; pool: LLMPoolStatus | null; onReload: () => Promise; }) { const [busy, setBusy] = React.useState(false); // 冷却倒计时是后端算出的剩余秒数——抽屉开着且有配置不正常时才定时拉,让它走起来。 React.useEffect(() => { if (!open || !pool?.enabled || !pool.chain.some((m) => m.state !== "ok")) return; const t = setInterval(() => void onReload(), 10_000); return () => clearInterval(t); }, [open, pool, onReload]); async function toggle(patch: { llm_pool_enabled?: boolean; llm_pool_bind_fallback?: boolean }) { if (busy) return; setBusy(true); try { await api.setSettings(patch); await onReload(); if (patch.llm_pool_enabled !== undefined) { toast.success(patch.llm_pool_enabled ? "已开启 LLM 轮询" : "已关闭 LLM 轮询"); } else { toast.success("已更新兜底设置"); } } catch (e) { toast.error(`设置失败:${(e as Error).message}`); } finally { setBusy(false); } } async function recover(id?: string) { try { await api.resetLLMPool(id); await onReload(); toast.success(id ? "已恢复该配置" : "已恢复全部配置"); } catch (e) { toast.error(`恢复失败:${(e as Error).message}`); } } const enabled = pool?.enabled ?? false; const chain = pool?.chain ?? []; // 参与轮询的成员(排除被标记「不参与轮询」的),顺序即后端实际的尝试顺序。 const inChain = chain.filter((m) => m.active || !m.excluded); const tripped = chain.filter((m) => m.state === "tripped"); return ( LLM 轮询 · 故障转移 开启后,未指定模型的 Agent 在当前配置不可用(余额不足 / Key 失效 / 限流 / 服务异常)时自动切到下一个配置。

默认关闭。关闭时始终只用激活配置,失败即失败。

void toggle({ llm_pool_enabled: v })} aria-label="LLM 轮询开关" />
{enabled && ( <>

默认关闭:Agent 或任务指定了某个配置就只用它,失败即失败(不会悄悄换成别的模型)。 开启后,指定的配置失败时也会回落到下面的轮询链。

void toggle({ llm_pool_bind_fallback: v })} aria-label="绑定配置失败兜底开关" />
{tripped.length > 0 && ( )}
{inChain.length < 2 && (

当前只有 {inChain.length} 个可用配置,轮询不会生效——至少需要 2 个已填 API Key 且参与轮询的配置。

)} {chain.map((m) => { const excluded = m.excluded && !m.active; const order = excluded ? null : inChain.findIndex((x) => x.profile_id === m.profile_id) + 1; return (
{order ?? "—"} {m.name} {m.active && ( 激活 )} {excluded && 不参与轮询}
{m.state === "tripped" && m.cooldown_secs > 0 && ( 冷却 {cooldownText(m.cooldown_secs)} )} {m.state === "degraded" && ( 连续失败 {m.fails} 次 )} {m.state !== "ok" && ( )}
{m.model} {!m.active && 优先级 {m.priority}}
{m.last_error && (

{m.last_error}

)}
); })} {chain.length === 0 && (
暂无配置
)}
激活配置恒为第 1 顺位,其余按优先级从高到低(在各配置里设置)。某个配置失败后进入冷却 (60s → 5min → 30min),冷却期内被跳过,恢复后自动切回。上下文窗口装不下当前请求的配置会被跳过。 指定了模型的 Agent 与任务默认不参与轮询。
)}
); } // ───────────────────────────────────────────────────────────────────────────── // 模型配置抽屉(新建 / 编辑共用同一套表单) // ───────────────────────────────────────────────────────────────────────────── function ProfileSheet({ profile, open, onOpenChange, onSaved, }: { profile: LLMProfile | null; // null = 新建 open: boolean; onOpenChange: (o: boolean) => void; onSaved: (id: string) => void; }) { const isNew = !profile; const [name, setName] = React.useState(""); const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses">("anthropic"); const [model, setModel] = React.useState(""); const [baseUrl, setBaseUrl] = React.useState(""); const [proxy, setProxy] = React.useState(""); const [apiKey, setApiKey] = React.useState(""); const [keyHint, setKeyHint] = React.useState(""); const [rps, setRps] = React.useState("0"); const [rpm, setRpm] = React.useState("0"); const [cw, setCw] = React.useState("0"); // 上下文窗口(K tokens);0=默认200K const [thinkingType, setThinkingType] = React.useState(NONE); const [effort, setEffort] = React.useState(NONE); const [priority, setPriority] = React.useState("0"); // 轮询顺位;越大越先 const [poolExclude, setPoolExclude] = React.useState(false); const [streaming, setStreaming] = React.useState(true); // true=流式(默认);false=非流式 const [testing, setTesting] = React.useState(false); const [saving, setSaving] = React.useState(false); const [models, setModels] = React.useState([]); const [loadingModels, setLoadingModels] = React.useState(false); const [modelsOpen, setModelsOpen] = React.useState(false); // 每次打开时从传入的 profile 灌一遍表单(新建则重置为默认值)。抽屉关掉再打开 // 就是一次干净的开始,不会留下上一个配置的残影。 React.useEffect(() => { if (!open) return; setName(profile?.name ?? ""); setFormat( profile?.format === "openai" || profile?.format === "openai-responses" ? profile.format : "anthropic", ); setModel(profile?.model ?? ""); setBaseUrl(profile?.base_url ?? ""); setProxy(profile?.proxy ?? ""); setRps(String(profile?.rate_per_second ?? 0)); setRpm(String(profile?.rate_per_minute ?? 0)); setCw(String(profile?.context_window_k ?? 0)); setThinkingType(fromStore(profile?.thinking_type)); setEffort(fromStore(profile?.reasoning_effort)); setPriority(String(profile?.priority ?? 0)); setPoolExclude(profile?.pool_exclude ?? false); setStreaming(profile?.streaming ?? true); setApiKey(""); setKeyHint(profile?.api_key_hint ?? ""); setModels([]); setModelsOpen(false); }, [open, profile]); const profileId = profile ? Number(profile.id) : undefined; async function loadModels() { if (loadingModels) return; setLoadingModels(true); setModels([]); try { const r = await api.fetchLLMModels(format, baseUrl, apiKey, proxy, profileId); if (r.ok && r.models && r.models.length > 0) { setModels(r.models); setModelsOpen(true); toast.success(`已加载 ${r.models.length} 个模型`); } else { toast.error(`加载模型失败:${r.error ?? "未获取到模型"}`); } } catch (e) { toast.error(`加载模型出错:${(e as Error).message}`); } finally { setLoadingModels(false); } } async function testConnection() { if (testing) return; setTesting(true); try { // 用配置实际会跑的思考参数来测,这样不支持该字段的模型在这里就失败, // 而不是等到跑任务时才炸。传 profile id:Key 输入框留空时用已存的 Key。 const r = await api.testLLM( format, model, baseUrl, apiKey, proxy, toStore(thinkingType), toStore(effort), profileId, streaming, ); // 回复内容一并展示:看得见模型确实说了话,才算和会话里跑通是一回事。 if (r.ok) toast.success(`连接成功 · ${r.latency_ms ?? "?"}ms · ${r.model ?? model}`, { description: r.reply ? `回复:${r.reply}` : undefined, }); else toast.error(`连接失败:${r.error ?? "未知"}`); } catch (e) { toast.error(`测试出错:${(e as Error).message}`); } finally { setTesting(false); } } async function save() { if (!name.trim() || !model.trim()) { toast.error("请填写名称与模型"); return; } if (saving) return; setSaving(true); try { const { id } = await api.saveLLMProfile({ ...(profile ? { id: Number(profile.id) } : {}), name: name.trim(), format, model: model.trim(), base_url: baseUrl.trim(), proxy: proxy.trim(), api_key: apiKey, rate_per_second: Number(rps) || 0, rate_per_minute: Number(rpm) || 0, context_window_k: Number(cw) || 0, thinking_type: toStore(thinkingType), reasoning_effort: toStore(effort), priority: Number(priority) || 0, pool_exclude: poolExclude, streaming, }); if (isNew) toast.success(`已新建:${name.trim()}(在卡片上「设为激活」以启用)`); else toast.success(profile?.is_default ? "已保存,激活配置即时生效,无需重启" : "已保存"); onSaved(String(id)); onOpenChange(false); } catch (e) { toast.error(`保存失败:${(e as Error).message}`); } finally { setSaving(false); } } return ( {isNew ? "新建模型配置" : `编辑:${profile?.name}`} {profile?.is_default && ( 激活中 )} {isNew ? "新建后不会自动激活,请在卡片上「设为激活」以启用。" : "修改后点击保存;激活配置保存后对全部 Agent 立即生效。"}
setName(e.target.value)} />
setModel(e.target.value)} /> {/* modal: 这个 Popover 的内容被 portal 到 ,在 Sheet 的滚动锁之外, 不加 modal 时列表能渲染却滚不动。modal 让它自己持有最上层滚动锁。 */} {models.length > 0 && ( {models.map((m) => ( ))} )}
setBaseUrl(e.target.value)} />
setProxy(e.target.value)} />

仅 LLM 出站请求走此代理,支持 http/https/socks5,可带账号密码(如 socks5://user:pass@host:port,密码含特殊字符需 URL 编码);留空表示不使用代理(直连)。

setApiKey(e.target.value)} />
setRps(e.target.value)} />
setRpm(e.target.value)} />
setCw(e.target.value)} placeholder="200" />

限速 0 = 不限,全 Agent 共享。上下文窗口单位 K(千 token),0 = 默认 200K,上限 1000(即 1M);设太高会导致压缩不触发。

数字越大越先被选中;激活配置恒为第 1 顺位,与本值无关。相同优先级的配置会轮流打头,天然分摊额度。

setPriority(e.target.value)} />

开启后不会被当作故障转移目标(仍可被 Agent / 任务显式指定使用)。 适合「只给某个 Agent 专用、不希望别人失败时烧掉」的昂贵配置。

开启(默认)走流式 SSE,有运行中实时进度与实时 token 计数。 关闭则走真·非流式(stream:false, 一次性返回完整响应)——可绕开部分网关糟糕的 SSE 实现(空帧 / 思考字段丢帧), 代价是失去运行中的实时进度。

控制是否发送 thinking 字段。不发送=不带该字段(兼容 MiniMax 等不支持 的模型);关闭=发 disabled;开启=发 enabled。与下面的强度互相独立。

独立的强度档位(OpenAI reasoning_effort / Anthropic output_config.effort)。 有些接口没有 thinking 字段、只靠强度即可激活思考,故可单独设置、不发送思考开关。

); } // ───────────────────────────────────────────────────────────────────────────── export default function LLMPage() { const [profiles, setProfiles] = React.useState([]); const [pool, setPool] = React.useState(null); const [poolOpen, setPoolOpen] = React.useState(false); // 抽屉的开关和内容分开存:关闭时 editing 保持不变,否则关闭动画期间标题会从 // 「编辑 X」闪成「新建」。editing = null 表示新建。 const [editOpen, setEditOpen] = React.useState(false); const [editing, setEditing] = React.useState(null); const openEditor = React.useCallback((p: LLMProfile | null) => { setEditing(p); setEditOpen(true); }, []); const loadPool = React.useCallback(async () => { try { setPool(await api.llmPool()); } catch { /* ignore */ } }, []); const load = React.useCallback(async () => { try { setProfiles(await api.llmProfiles()); } catch { /* ignore */ } await loadPool(); }, [loadPool]); React.useEffect(() => { void load(); }, [load]); // 卡片上的健康徽章按 profile id 取轮询状态。 const health = React.useMemo(() => { const m = new Map(); for (const c of pool?.chain ?? []) m.set(c.profile_id, c); return m; }, [pool]); async function activate(id: string, name: string) { try { await api.activateLLMProfile(id); toast.success(`已激活:${name}`); await load(); } catch (e) { toast.error(`激活失败:${(e as Error).message}`); } } async function remove(p: LLMProfile) { if (p.is_default) { toast.error("无法删除当前激活的配置"); return; } try { await api.deleteLLMProfile(p.id); toast.success(`已删除:${p.name}`); await load(); } catch (e) { toast.error(`删除失败:${(e as Error).message}`); } } const poolOn = pool?.enabled ?? false; return (

LLM

全 Agent 共享的格式 / 模型 / 限速配置。点击卡片编辑,星标为当前激活配置。

{profiles.map((p) => { const h = healthOf(p, health.get(p.id)); return ( // biome-ignore lint/a11y/useSemanticElements: 卡片内含自己的操作按钮,用原生
); })} {profiles.length === 0 && (
还没有模型配置,点击右上角「新建」创建第一个。
)}
void load()} /> ); }