Deployments: API keys, deploy from the library, reorganized form

- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 12:28:25 +02:00
1 parent 66e6a8c4f7
commit ea1f18cc74
32 files changed
+2478 -183

No files matched your search

+44 -1
View File
@@ -9,6 +9,8 @@ import {
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
@@ -17,12 +19,14 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
@@ -97,13 +101,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs] = await Promise.all([
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
@@ -143,6 +151,15 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
@@ -287,6 +304,32 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
@@ -3,7 +3,7 @@
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useEffect, useRef, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
@@ -21,6 +21,7 @@ import {
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
@@ -67,15 +68,9 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
// The browser's host name (null while rendering on the server, so hydration matches).
const hostname = useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
const hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
// llama-server's built-in chat UI, served at / on the same port.
const webUi = d.engine === "llama.cpp" && d.options.webui !== false && d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
@@ -218,6 +213,16 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
+195 -111
View File
@@ -1,19 +1,23 @@
"use client";
import { BoxesIcon, CheckIcon, CpuIcon, SearchIcon } from "lucide-react";
import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { ArgsEditor } from "@/components/args-editor";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
@@ -42,8 +46,6 @@ export type FormInitial = {
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
const selectClass =
"h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
@@ -63,10 +65,41 @@ function Section({ step, title, description, children }: { step: number; title:
);
}
function Field({ label, hint, children, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string }) {
/** A titled block of related options inside the launch options card. */
function Group({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={htmlFor}>{label}</Label>
<div className="grid gap-3 border-t pt-5 first:border-t-0 first:pt-0 md:grid-cols-[11rem_1fr] md:gap-6">
<div className="flex flex-col gap-0.5">
<h3 className="text-sm font-medium">{title}</h3>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
<div className="grid content-start gap-4 sm:grid-cols-2">{children}</div>
</div>
);
}
/** `flag`: the command-line flag the field sets, shown next to the label. */
function Field({
label,
flag,
hint,
children,
htmlFor,
wide,
}: {
label: string;
flag?: string;
hint?: React.ReactNode;
children: React.ReactNode;
htmlFor?: string;
wide?: boolean;
}) {
return (
<div className={cn("flex flex-col gap-1.5", wide && "sm:col-span-2")}>
<div className="flex items-baseline justify-between gap-2">
<Label htmlFor={htmlFor}>{label}</Label>
{flag && <code className="font-mono text-[11px] text-muted-foreground">{flag}</code>}
</div>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
@@ -78,11 +111,13 @@ export function DeploymentForm({
runtimes,
models,
host,
apiKeyCount,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
initial?: FormInitial;
}) {
const router = useRouter();
@@ -109,12 +144,13 @@ export function DeploymentForm({
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [webui, setWebui] = useState(o?.webui !== false);
const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey);
const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
const [dtype, setDtype] = useState(o?.dtype ?? "");
const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
const [extraArgs, setExtraArgs] = useState((o?.extraArgs ?? []).join("\n"));
const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? []));
const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
@@ -144,13 +180,11 @@ export function DeploymentForm({
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
webui: engine === "llama.cpp" ? webui : null,
requireApiKey,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: extraArgs
.split("\n")
.map((a) => a.trim())
.filter(Boolean),
extraArgs: rowsToArgs(argRows),
};
const fileBytes = model
@@ -163,7 +197,13 @@ export function DeploymentForm({
const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model ? renderCommand(runtime.image, buildCommand({ engine, options, model, runtime: { env: runtime.env, extraArgs: runtime.extraArgs } })) : null;
runtime && model ? renderCommand(runtime.image, buildCommand({
engine,
options,
model,
runtime: { env: runtime.env, extraArgs: runtime.extraArgs },
apiKeys: Array.from({ length: apiKeyCount }, () => API_KEY_PLACEHOLDER),
})) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
@@ -302,7 +342,7 @@ export function DeploymentForm({
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file">
<Field label="Model file" flag="-m">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
@@ -315,21 +355,22 @@ export function DeploymentForm({
))}
</div>
</Field>
<Field label="Vision (mmproj)" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<select value={mmproj} onChange={(e) => setMmproj(e.target.value)} className={selectClass} disabled={model.candidates.mmproj.length === 0}>
<Field label="Vision (mmproj)" flag="--mmproj" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<NativeSelect value={mmproj} onChange={(e) => setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</select>
</NativeSelect>
</Field>
<Field
label="Speculative decoding"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "MTP heads use --spec-type draft-mtp."}
flag="-md"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "Faster generation with an MTP head or draft model."}
>
<select value={draftFile} onChange={(e) => setDraftFile(e.target.value)} className={selectClass} disabled={model.candidates.drafts.length === 0}>
<NativeSelect value={draftFile} onChange={(e) => setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
@@ -337,7 +378,7 @@ export function DeploymentForm({
{d.path} ({formatBytes(d.size)})
</option>
))}
</select>
</NativeSelect>
</Field>
</div>
)}
@@ -358,106 +399,152 @@ export function DeploymentForm({
{runtime && model && (
<Section step={3} title="Launch options" description="Empty fields use the engine's defaults.">
<div className="grid gap-4 md:grid-cols-3">
<Group title="General" description="Name and how to reach the server.">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="Context size (tokens)" htmlFor="d-ctx" hint={engine === "vllm" ? "--max-model-len" : "-c"}>
<div className="flex gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-24" />
<div className="flex flex-wrap gap-1">
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c >= 1024 ? `${c / 1024}k` : c}
</Button>
))}
</div>
<Field label="Host port" htmlFor="d-port" hint={`Publishes container port ${ENGINE_PORT[engine]}; empty: only reachable inside Docker.`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={requireApiKey} onCheckedChange={(v) => setRequireApiKey(v === true)} className="mt-0.5" disabled={apiKeyCount === 0 && !requireApiKey} />
<span className="flex flex-col gap-0.5">
<span>Require an API key</span>
<span className="text-xs text-muted-foreground">
{apiKeyCount === 0 ? (
<>
No keys yet.{" "}
<Link href="/settings/api-keys" className="underline">
Add one in Settings
</Link>
.
</>
) : (
<>
Accepts any of the {apiKeyCount} key{apiKeyCount === 1 ? "" : "s"} from{" "}
<Link href="/settings/api-keys" className="underline">
Settings → API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.{engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
</>
)}
</span>
</span>
</label>
{engine === "llama.cpp" && (
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={webui} onCheckedChange={(v) => setWebui(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Serve the llama.cpp web UI</span>
<span className="text-xs text-muted-foreground">
{webui
? hostPort
? `Opens at http://<server>:${hostPort}/ (no login on that port).`
: "Set a host port to open it."
: "Off: passes --no-webui; the API keeps working."}
</span>
</span>
</label>
)}
</Group>
<Group title="Context" description="How much text the model sees and how many requests run at once.">
<Field label="Context size (tokens)" flag={engine === "vllm" ? "--max-model-len" : "-c"} htmlFor="d-ctx" wide>
<div className="flex flex-wrap items-center gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-28" />
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c / 1024}k
</Button>
))}
</div>
</Field>
<Field
label={engine === "vllm" ? "Max concurrent sequences" : "Parallel slots"}
htmlFor="d-par"
hint={engine === "vllm" ? "--max-num-seqs" : "-np; the context is shared between slots"}
>
{engine === "vllm" ? (
{engine === "vllm" ? (
<Field label="Max concurrent sequences" flag="--max-num-seqs" htmlFor="d-par">
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
) : (
</Field>
) : (
<Field label="Parallel slots" flag="-np" htmlFor="d-par" hint="The context is split between slots.">
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
)}
</Field>
</div>
</Field>
)}
</Group>
{engine === "llama.cpp" ? (
<div className="grid gap-4 md:grid-cols-4">
<Field label="Threads" htmlFor="d-thr" hint={host?.cpus ? `-t / -tb; host has ${host.cpus}` : "-t / -tb"}>
<Group title="Performance" description="CPU threads and prompt processing.">
<Field label="Threads" flag="-t / -tb" htmlFor="d-thr" hint={host?.cpus ? `Host has ${host.cpus} threads.` : undefined}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="KV cache K / V" hint="-ctk / -ctv; q8_0 halves the KV memory">
<div className="flex gap-1.5">
{[
[cacheTypeK, setCacheTypeK],
[cacheTypeV, setCacheTypeV],
].map(([value, set], i) => (
<select key={i} value={value as string} onChange={(e) => (set as (v: string) => void)(e.target.value)} className={selectClass}>
<option value="">default</option>
{KV_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
))}
</div>
</Field>
<Field label="Flash attention" hint="-fa">
<select value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)} className={selectClass}>
<option value="">default (auto)</option>
<Field label="Flash attention" flag="-fa" htmlFor="d-fa">
<NativeSelect id="d-fa" value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)}>
<option value="">auto</option>
<option value="on">on</option>
<option value="off">off</option>
</select>
</NativeSelect>
</Field>
<Field label="Web UI" hint={webui ? (hostPort ? `Opens at http://<server>:${hostPort}/` : "Needs a host port to open it (below).") : "--no-webui"}>
<select value={webui ? "on" : "off"} onChange={(e) => setWebui(e.target.value === "on")} className={selectClass}>
<option value="on">on</option>
<option value="off">off</option>
</select>
<Field label="Batch size" flag="-b" htmlFor="d-b">
<Input id="d-b" value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" />
</Field>
<Field label="Batch / micro-batch" hint="-b / -ub">
<div className="flex gap-1.5">
<Input value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" aria-label="Batch size" />
<Input value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" aria-label="Micro-batch size" />
</div>
<Field label="Micro-batch size" flag="-ub" htmlFor="d-ub">
<Input id="d-ub" value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" />
</Field>
</div>
</Group>
) : (
<div className="grid gap-4 md:grid-cols-3">
<Group title="Performance" description="vLLM binds its CPU threads itself; limit cores under Resources.">
<Field
label="Data type"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster than bfloat16." : "--dtype; overrides the runtime's default"}
flag="--dtype"
htmlFor="d-dtype"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster." : "Overrides the runtime's default."}
>
<select value={dtype} onChange={(e) => setDtype(e.target.value)} className={selectClass}>
<NativeSelect id="d-dtype" value={dtype} onChange={(e) => setDtype(e.target.value)}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</select>
</NativeSelect>
</Field>
<Field label="KV cache (GiB)" htmlFor="d-kv" hint="VLLM_CPU_KVCACHE_SPACE">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
<Field label="Threads" hint="vLLM binds OpenMP threads itself (VLLM_CPU_OMP_THREADS_BIND); limit CPUs below instead.">
<Input value="auto" disabled />
</Field>
</div>
</Group>
)}
<div className="grid gap-4 md:grid-cols-3">
<Field label="CPU limit (cores)" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus})` : "Empty: no limit"}>
<Group title="KV cache" description="Memory for the context of running requests.">
{engine === "llama.cpp" ? (
<>
<Field label="K type" flag="-ctk" htmlFor="d-ctk" hint="q8_0 halves the memory.">
<NativeSelect id="d-ctk" value={cacheTypeK} onChange={(e) => setCacheTypeK(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
<Field label="V type" flag="-ctv" htmlFor="d-ctv">
<NativeSelect id="d-ctv" value={cacheTypeV} onChange={(e) => setCacheTypeV(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
</>
) : (
<Field label="KV cache size (GiB)" flag="VLLM_CPU_KVCACHE_SPACE" htmlFor="d-kv" hint="Reserved up front; must fit in the memory limit.">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
)}
</Group>
<Group title="Resources" description="Container limits.">
<Field label="CPU cores" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus}).` : "Empty: no limit."}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory limit (MiB)"
label="Memory (MiB)"
htmlFor="d-mem"
hint={
<>
@@ -481,35 +568,32 @@ export function DeploymentForm({
inputMode="numeric"
/>
</Field>
<Field label="Publish on host port" htmlFor="d-port" hint={`Optional: reach the API at http://<server>:<port>/v1 (container port ${ENGINE_PORT[engine]}).`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
</div>
</Group>
<Field label="Extra arguments" htmlFor="d-args" hint="One per line, appended after the runtime's own extra arguments.">
<textarea
id="d-args"
value={extraArgs}
onChange={(e) => setExtraArgs(e.target.value)}
spellCheck={false}
className="min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30"
placeholder={engine === "vllm" ? "--enforce-eager" : "--temp\n0.7"}
/>
</Field>
<Group
title="Extra arguments"
description={`Any other ${engine === "vllm" ? "vllm serve" : "llama-server"} flag. Added after the runtime's own arguments.`}
>
<div className="sm:col-span-2">
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--enforce-eager", value: "value (optional)" } : { flag: "--temp", value: "0.7" }} />
</div>
</Group>
</Section>
)}
{runtime && model && (
<Section step={4} title="Command" description="What Kaname runs, including the runtime's environment and arguments.">
{preview && (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<Label className="flex items-center gap-1.5">
<CpuIcon className="size-4 text-muted-foreground" />
Command
</Label>
<div className="relative">
<pre className="overflow-x-auto rounded-lg bg-muted/60 py-2.5 pr-12 pl-3 font-mono text-xs break-all whitespace-pre-wrap">
<TerminalIcon className="mr-1.5 inline size-3.5 align-[-2px] text-muted-foreground" />
{preview}
</pre>
<div className="absolute top-1.5 right-1.5">
<CopyButton value={preview} label="Copy command" />
</div>
<pre className="overflow-x-auto rounded-lg bg-muted/60 px-3 py-2 font-mono text-xs whitespace-pre-wrap break-all">{preview}</pre>
</div>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()}>
Cancel
+23 -13
View File
@@ -1,11 +1,12 @@
"use client";
import { PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
@@ -23,6 +24,7 @@ const isActive = (r: Row) => r.desiredState === "running" || r.state === "starti
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const hostname = useHostname();
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
@@ -77,17 +79,25 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
<span className="flex items-center gap-1.5">
{r.state === "running" && webUiUrl(r, hostname) && (
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
<ExternalLinkIcon />
Web UI
</a>
)}
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</span>
</div>
</Card>
);
+5 -3
View File
@@ -1,14 +1,16 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost }> {
const [runtimes, models, docker] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo()]);
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
apiKeyCount: keys.length,
};
}
+6 -3
View File
@@ -1,16 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
export default async function NewDeploymentPage() {
const data = await formData();
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} />
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+36 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
@@ -10,7 +10,7 @@ import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -19,6 +19,7 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -180,6 +181,9 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -195,6 +199,23 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
@@ -236,6 +257,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
);
})}
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { BoxesIcon, DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
@@ -6,6 +6,7 @@ const SECTIONS = [
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
@@ -1,11 +1,13 @@
"use client";
import { useState } from "react";
import { ArgsEditor } from "@/components/args-editor";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
@@ -34,7 +36,7 @@ export function RuntimeForm({
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argsText, setArgsText] = useState((initial.extraArgs ?? []).join("\n"));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
@@ -51,7 +53,7 @@ export function RuntimeForm({
image,
description,
env: parseEnvLines(envText),
extraArgs: argsText.split("\n"),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
@@ -117,31 +119,22 @@ export function RuntimeForm({
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-args">Extra arguments</Label>
<textarea
id="rt-args"
value={argsText}
onChange={(e) => setArgsText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"--dtype=bfloat16"}
/>
<p className="text-xs text-muted-foreground">One per line, appended to the generated command.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Extra arguments</Label>
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
<p className="text-xs text-muted-foreground">Added to every deployment&apos;s command; a deployment can override them.</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
+29
View File
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** The key's value ("show key" in Settings). */
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Remove a key; running deployments keep accepting it until they restart. */
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteApiKey(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** Keys without their values (only the last characters). */
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
/** Add a key (generated when `key` is missing); the response carries the full key once. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+5 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { apiKeyValues } from "@/lib/api-keys";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
@@ -21,9 +22,11 @@ export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
// Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
@@ -31,6 +34,7 @@ export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
+7
View File
@@ -127,4 +127,11 @@
html {
@apply font-sans;
}
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
.dark {
color-scheme: dark;
}
option {
@apply bg-popover text-popover-foreground;
}
}