/** * Site › Settings › AI (RFC-0016 §2, DESIGN.md §2y): the switch for in-editor AI, the model * (recommended models first, then the account's Workers AI catalogue), the daily cap with today's * use, and — under "AI Gateway and other providers" — a gateway id and a `provider/model` that runs * through it. Words come from the lazy `aiSettings` namespace, loaded with the settings route. */ import { formatNumber } from "@cloudhal/messages/format"; import { Badge, Banner, Button, Collapsible, Combobox, Input, Meter, SkeletonLine, Switch, Text, } from "@cloudhal/ui"; import { ArrowClockwise, Sparkle, WarningCircle } from "@phosphor-icons/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect, useMemo, useState } from "react"; import { useI18n } from "../i18n/index.tsx"; import { type AiPickerModel, type AiSettings, ApiRequestError, api } from "../lib/api.ts"; import { apiErrorText } from "../lib/api-errors.ts"; import { SettingRow, SettingsSection } from "./Settings.tsx"; import { useToast } from "./Toast.ts"; import { useGate } from "./useMe.ts"; export const AI_SETTINGS_SECTION = "ai"; const WORKERS_AI_MODEL = /^@(cf|hf)\/[A-Za-z0-9._-]+\/[A-Za-z0-9._:-]+$/; const PROVIDER_MODEL = /^[a-z0-9][a-z0-9-]{0,40}\/[A-Za-z0-9._:/-]{1,120}$/; const GATEWAY_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; const MAX_LIMIT = 10_000; const isConflict = (e: unknown) => e instanceof ApiRequestError && e.status === 409; interface ModelOption { value: string; label: string; model: AiPickerModel; } interface Form { enabled: boolean; /** The Workers AI model chosen in the picker. */ model: string; /** `provider/model` through the gateway; when set, it is the model used. */ provider: string; gateway: string; limit: string; } const formOf = (s: AiSettings): Form => ({ enabled: s.enabled, model: WORKERS_AI_MODEL.test(s.model) ? s.model : "", provider: WORKERS_AI_MODEL.test(s.model) ? "" : s.model, gateway: s.gateway ?? "", limit: String(s.dailyLimit), }); export function AiSettingsSection({ siteId }: { siteId: string }) { const { t, locale } = useI18n("aiSettings"); const a = "aiSettings" as const; const qc = useQueryClient(); const toast = useToast(); const gate = useGate("ai.settings"); const key = ["ai", siteId, "settings"] as const; const settings = useQuery({ queryKey: key, queryFn: () => api.ai.settings(siteId) }); const transport = settings.data?.transport; const picker = useQuery({ queryKey: ["ai", siteId, "models"], queryFn: () => api.ai.models(siteId), enabled: gate.allowed && transport !== undefined && transport !== "none", staleTime: 10 * 60 * 1000, retry: false, }); const saved = settings.data?.settings; const [form, setForm] = useState