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:
1 parent
66e6a8c4f7
commit
ea1f18cc74
32 files changed
+2478
-183
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import "server-only";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiKeys } from "@/lib/db/schema";
|
||||
|
||||
export class ApiKeyError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "conflict",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
|
||||
export const ApiKeyBody = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
key: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(16, "at least 16 characters")
|
||||
.max(256)
|
||||
.regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
|
||||
.refine((k) => !k.includes(","), "no commas")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
|
||||
|
||||
/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
|
||||
const mask = (key: string) => `…${key.slice(-4)}`;
|
||||
|
||||
export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
|
||||
|
||||
export async function listApiKeys(): Promise<ApiKeyRow[]> {
|
||||
const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
|
||||
return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
|
||||
}
|
||||
|
||||
/** Returns the full key once, so the user can copy it. */
|
||||
export async function createApiKey(input: z.infer<typeof ApiKeyBody>) {
|
||||
const key = input.key ?? generateApiKey();
|
||||
const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
|
||||
if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
|
||||
const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
|
||||
return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
|
||||
}
|
||||
|
||||
export async function deleteApiKey(id: string) {
|
||||
const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
|
||||
if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
|
||||
}
|
||||
|
||||
/** All key values (for runtime containers and Kaname's own requests to them). */
|
||||
export async function apiKeyValues(): Promise<string[]> {
|
||||
return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
|
||||
}
|
||||
|
||||
/** One key's value, for "show key" in Settings. */
|
||||
export async function revealApiKey(id: string): Promise<string> {
|
||||
const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
|
||||
if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
|
||||
return row.key;
|
||||
}
|
||||
@@ -451,6 +451,8 @@ export type DeploymentOptions = {
|
||||
flashAttn?: "auto" | "on" | "off" | null;
|
||||
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
|
||||
webui?: boolean | null;
|
||||
/** Only accept requests with one of the API keys from Settings → API keys. */
|
||||
requireApiKey?: boolean | null;
|
||||
/** vLLM */
|
||||
dtype?: string | null;
|
||||
maxNumSeqs?: number | null;
|
||||
@@ -510,3 +512,14 @@ export const deploymentLogs = sqliteTable(
|
||||
},
|
||||
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
|
||||
);
|
||||
|
||||
/**
|
||||
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
|
||||
* hands them to the runtime container; never logged or written into a stored command line.
|
||||
*/
|
||||
export const apiKeys = sqliteTable("api_keys", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
key: text("key").notNull().unique(),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { buildCommand, renderCommand } from "./deploy-command";
|
||||
import { buildCommand, redactCommand, renderCommand } from "./deploy-command";
|
||||
|
||||
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
|
||||
|
||||
@@ -65,4 +65,22 @@ describe("buildCommand", () => {
|
||||
assert.ok(!args().includes("--no-webui") && !args(true).includes("--no-webui"));
|
||||
assert.ok(args(false).includes("--no-webui"));
|
||||
});
|
||||
|
||||
it("passes API keys via the environment and redacts them", () => {
|
||||
const base = { model: { repoId: "a/b", localPath: "a/b" }, runtime: { env: {}, extraArgs: [] } };
|
||||
const opts = { modelFile: "m.gguf", contextSize: 2048, requireApiKey: true, extraArgs: [] };
|
||||
const llama = buildCommand({ ...base, engine: "llama.cpp", options: opts, apiKeys: ["sk-one-1234567890", "sk-two-1234567890"] });
|
||||
assert.equal(llama.env.LLAMA_API_KEY, "sk-one-1234567890,sk-two-1234567890");
|
||||
assert.ok(!llama.args.join(" ").includes("sk-"));
|
||||
const shown = renderCommand("img", redactCommand(llama, ["sk-one-1234567890", "sk-two-1234567890"]));
|
||||
assert.ok(!shown.includes("sk-") && shown.includes("<api-key>,<api-key>"));
|
||||
|
||||
const one = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["sk-one-1234567890"] });
|
||||
assert.equal(one.env.VLLM_API_KEY, "sk-one-1234567890");
|
||||
const two = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["k1-1234567890123456", "k2-1234567890123456"] });
|
||||
assert.deepEqual(two.args.slice(two.args.indexOf("--api-key"), two.args.indexOf("--api-key") + 3), ["--api-key", "k1-1234567890123456", "k2-1234567890123456"]);
|
||||
|
||||
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
|
||||
assert.equal(off.env.LLAMA_API_KEY, undefined);
|
||||
});
|
||||
});
|
||||
@@ -14,8 +14,13 @@ export type CommandInput = {
|
||||
options: DeploymentOptions;
|
||||
model: { repoId: string; localPath: string };
|
||||
runtime: { env: Record<string, string>; extraArgs: string[] };
|
||||
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
|
||||
apiKeys?: string[];
|
||||
};
|
||||
|
||||
/** Stands in for key values in everything Kaname shows or stores. */
|
||||
export const API_KEY_PLACEHOLDER = "<api-key>";
|
||||
|
||||
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
|
||||
|
||||
const inModels = (localPath: string, file?: string | null) =>
|
||||
@@ -34,8 +39,9 @@ function withoutFlag(args: string[], flag: string): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function buildCommand({ engine, options: o, model, runtime }: CommandInput): ContainerCommand {
|
||||
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
|
||||
const port = ENGINE_PORT[engine];
|
||||
const keys = o.requireApiKey ? apiKeys : [];
|
||||
if (engine === "llama.cpp") {
|
||||
// The image's entrypoint is llama-server, so these are its arguments.
|
||||
const args = [
|
||||
@@ -63,12 +69,16 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
|
||||
...runtime.extraArgs,
|
||||
...o.extraArgs,
|
||||
];
|
||||
return { args, env: { ...runtime.env }, port };
|
||||
// Via the environment, not the command line; several keys as one comma-separated list.
|
||||
const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) };
|
||||
return { args, env, port };
|
||||
}
|
||||
|
||||
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
|
||||
const env = { ...runtime.env };
|
||||
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
|
||||
// VLLM_API_KEY holds a single key; more than one needs --api-key.
|
||||
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
|
||||
const args = [
|
||||
inModels(model.localPath, o.modelFile || null),
|
||||
"--host",
|
||||
@@ -79,6 +89,7 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
|
||||
model.repoId,
|
||||
...num("--max-model-len", o.contextSize),
|
||||
...num("--max-num-seqs", o.maxNumSeqs),
|
||||
...(keys.length > 1 ? ["--api-key", ...keys] : []),
|
||||
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
|
||||
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
|
||||
...str("--dtype", o.dtype),
|
||||
@@ -87,6 +98,12 @@ export function buildCommand({ engine, options: o, model, runtime }: CommandInpu
|
||||
return { args, env, port };
|
||||
}
|
||||
|
||||
/** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */
|
||||
export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand {
|
||||
const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v);
|
||||
return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) };
|
||||
}
|
||||
|
||||
/** Shell-style rendering for display ("docker run … image args"). */
|
||||
export function renderCommand(image: string, cmd: ContainerCommand): string {
|
||||
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
||||
|
||||
+48
-1
@@ -2,8 +2,9 @@ import "server-only";
|
||||
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
|
||||
import { apiKeys, deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
|
||||
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
export class DeploymentError extends Error {
|
||||
constructor(
|
||||
@@ -35,6 +36,7 @@ export const DeploymentBody = z.object({
|
||||
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
|
||||
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
|
||||
webui: z.boolean().nullable().optional(),
|
||||
requireApiKey: z.boolean().nullable().optional(),
|
||||
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
|
||||
maxNumSeqs: int(1, 1024).nullable().optional(),
|
||||
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
|
||||
@@ -92,6 +94,9 @@ async function validate(input: DeploymentInput, selfId?: string): Promise<Deploy
|
||||
} else {
|
||||
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null });
|
||||
}
|
||||
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
|
||||
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
|
||||
}
|
||||
if (input.hostPort) {
|
||||
const clash = await db().query.deployments.findFirst({
|
||||
columns: { name: true },
|
||||
@@ -236,3 +241,45 @@ export async function deploymentsUsing(by: { modelId?: string; runtimeId?: strin
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export type ModelDeployment = { id: string; name: string; state: DeploymentRow["state"]; desiredState: DeploymentRow["desiredState"]; runtimeName: string };
|
||||
|
||||
/** Deployments per model id (for links from the library and model pages). */
|
||||
export async function deploymentsByModel(): Promise<Map<string, ModelDeployment[]>> {
|
||||
const rows = await db()
|
||||
.select({
|
||||
modelId: deployments.modelId,
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
state: deployments.state,
|
||||
desiredState: deployments.desiredState,
|
||||
runtimeName: runtimes.name,
|
||||
})
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(isNull(deployments.deleteRequestedAt))
|
||||
.orderBy(asc(deployments.name));
|
||||
const out = new Map<string, ModelDeployment[]>();
|
||||
for (const { modelId, ...d } of rows) out.set(modelId, [...(out.get(modelId) ?? []), d]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Form defaults for "Deploy" from the library: the first runtime with a pulled image that can serve the model. */
|
||||
export async function deployPreset(modelId: string) {
|
||||
const model = (await listDeployableModels()).find((m) => m.id === modelId);
|
||||
if (!model) return null;
|
||||
const rts = await db().select({ id: runtimes.id, engine: runtimes.engine }).from(runtimes).where(eq(runtimes.imageState, "present")).orderBy(asc(runtimes.createdAt));
|
||||
const runtime = rts.find((r) => servableBy(model.candidates, r.engine));
|
||||
if (!runtime) return null;
|
||||
const gguf = runtime.engine === "llama.cpp" ? model.candidates.gguf[0] : undefined;
|
||||
const quant = gguf ? quantGroup(gguf.path) : null;
|
||||
return {
|
||||
name: `${model.repoId.split("/")[1]}${quant ? ` ${quant}` : ""}`,
|
||||
runtimeId: runtime.id,
|
||||
modelId: model.id,
|
||||
options: { modelFile: gguf?.path ?? "", mmproj: gguf ? (model.candidates.mmproj[0]?.path ?? null) : null, contextSize: 4096, extraArgs: [] },
|
||||
cpus: null,
|
||||
memoryMb: null,
|
||||
hostPort: null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { argsToRows, rowsToArgs } from "./extra-args";
|
||||
|
||||
describe("extra args rows", () => {
|
||||
it("pairs flags with their values", () => {
|
||||
const tokens = ["--temp", "0.7", "--no-mmap", "--dtype=bfloat16", "--seed", "-1", "positional"];
|
||||
const rows = argsToRows(tokens);
|
||||
assert.deepEqual(rows, [
|
||||
{ flag: "--temp", value: "0.7" },
|
||||
{ flag: "--no-mmap", value: "" },
|
||||
{ flag: "--dtype=bfloat16", value: "" },
|
||||
{ flag: "--seed", value: "-1" },
|
||||
{ flag: "", value: "positional" },
|
||||
]);
|
||||
assert.deepEqual(rowsToArgs(rows), tokens);
|
||||
});
|
||||
|
||||
it("drops empty rows and trims", () => {
|
||||
assert.deepEqual(rowsToArgs([{ flag: " --top-k ", value: " 40 " }, { flag: "", value: "" }]), ["--top-k", "40"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// Extra command-line arguments as editable flag/value rows. Pure; shared by the runtime and
|
||||
// deployment forms. The stored form stays a token list (one argv entry per item).
|
||||
|
||||
export type ArgRow = { flag: string; value: string };
|
||||
|
||||
const isFlag = (t: string) => t.startsWith("-") && !/^-\d/.test(t);
|
||||
|
||||
/** Tokens → rows: a flag takes the following non-flag token as its value. */
|
||||
export function argsToRows(tokens: string[]): ArgRow[] {
|
||||
const rows: ArgRow[] = [];
|
||||
for (const t of tokens) {
|
||||
const last = rows.at(-1);
|
||||
// "--flag=value" stays one token, so it is shown (and passed) exactly as written.
|
||||
if (!isFlag(t) && last && last.flag && !last.value && !last.flag.includes("=")) last.value = t;
|
||||
else if (isFlag(t)) rows.push({ flag: t, value: "" });
|
||||
else rows.push({ flag: "", value: t });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Rows → tokens, skipping empty rows. */
|
||||
export function rowsToArgs(rows: ArgRow[]): string[] {
|
||||
return rows.flatMap((r) => [r.flag.trim(), r.value.trim()].filter(Boolean));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
|
||||
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
@@ -52,6 +53,9 @@ export async function listLibrary() {
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
|
||||
|
||||
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
|
||||
const deployableIds = new Set(deployable.map((m) => m.id));
|
||||
|
||||
return rows.map(({ updateDiff, ...r }) => ({
|
||||
...r,
|
||||
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
|
||||
@@ -61,6 +65,8 @@ export async function listLibrary() {
|
||||
hubTags: r.hubTags ?? [],
|
||||
quants: [...(quants.get(r.id) ?? [])].sort(),
|
||||
tags: tagsByModel.get(r.id) ?? [],
|
||||
deployable: deployableIds.has(r.id),
|
||||
deployments: byModel.get(r.id) ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user