diff --git a/dashboard/src/app/api/chat/route.ts b/dashboard/src/app/api/chat/route.ts new file mode 100644 index 0000000..9439665 --- /dev/null +++ b/dashboard/src/app/api/chat/route.ts @@ -0,0 +1,169 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getLlamaContainerName } from "@/lib/docker"; +import { spawn } from "node:child_process"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; +export const maxDuration = 300; + +/** + * POST /api/chat + * + * Streams a chat completion from llama.cpp /v1/chat/completions (OpenAI-compatible). + * + * Body: { + * messages: [{role, content}], + * temperature?, top_p?, top_k?, min_p?, repeat_penalty?, max_tokens?, stream? + * } + * + * Returns: SSE stream of OpenAI-compatible chat completion chunks. + */ +interface ChatMessage { + role: "system" | "user" | "assistant"; + content: string; +} + +export async function POST(req: NextRequest) { + const body = (await req.json()) as { + messages: ChatMessage[]; + temperature?: number; + top_p?: number; + top_k?: number; + min_p?: number; + repeat_penalty?: number; + max_tokens?: number; + stream?: boolean; + }; + + if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) { + return NextResponse.json( + { ok: false, error: "messages array is required" }, + { status: 400 } + ); + } + + const containerName = await getLlamaContainerName(); + if (!containerName) { + return NextResponse.json( + { ok: false, error: "llama container not running" }, + { status: 503 } + ); + } + + // Build the request payload for llama.cpp /v1/chat/completions endpoint. + // llama.cpp supports OpenAI-compatible API. + const payload: Record = { + messages: body.messages, + stream: body.stream !== false, + }; + if (body.temperature != null) payload.temperature = body.temperature; + if (body.top_p != null) payload.top_p = body.top_p; + if (body.top_k != null) payload.top_k = body.top_k; + if (body.min_p != null) payload.min_p = body.min_p; + if (body.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty; + if (body.max_tokens != null) payload.max_tokens = body.max_tokens; + + const payloadJson = JSON.stringify(payload); + + // Build the docker exec command to send the request to llama.cpp inside + // the container. We use `docker exec ... wget` because we can't reach + // the container's port from the dashboard directly (different network + // namespace). Actually — the dashboard IS on the same Docker network, + // so we can just fetch http://llama:8080/v1/chat/completions directly. + // But wget is more reliable for streaming. + + const useStream = body.stream !== false; + const encoder = new TextEncoder(); + + if (useStream) { + const stream = new ReadableStream({ + async start(controller) { + try { + // Use Node's fetch (available in Node 18+) to call llama.cpp + // directly over the Docker network. The dashboard container is + // on the same network as llama, so http://llama:8080 works. + const res = await fetch("http://llama:8080/v1/chat/completions", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: payloadJson, + signal: req.signal, + }); + + if (!res.ok || !res.body) { + const text = await res.text().catch(() => ""); + controller.enqueue( + encoder.encode( + `data: ${JSON.stringify({ + error: `llama returned ${res.status}: ${text.slice(0, 500)}`, + })}\n\n` + ) + ); + controller.close(); + return; + } + + // Pipe the response through — llama.cpp /v1/chat/completions with + // stream=true returns SSE chunks (data: {...}\n\n). + const reader = res.body.getReader(); + const pump = (): Promise => + reader.read().then(({ done, value }) => { + if (done) { + controller.enqueue(encoder.encode("data: [DONE]\n\n")); + controller.close(); + return; + } + controller.enqueue(value); + return pump(); + }); + await pump(); + } catch (err) { + try { + controller.enqueue( + encoder.encode( + `data: ${JSON.stringify({ + error: (err as Error).message, + })}\n\n` + ) + ); + controller.close(); + } catch { + /* already closed */ + } + } + }, + }); + + return new Response(stream, { + headers: { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + }, + }); + } else { + // Non-streaming — return JSON + try { + const res = await fetch("http://llama:8080/v1/chat/completions", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: payloadJson, + }); + const text = await res.text(); + return new Response(text, { + status: res.status, + headers: { "Content-Type": "application/json" }, + }); + } catch (err) { + return NextResponse.json( + { ok: false, error: (err as Error).message }, + { status: 500 } + ); + } + } +} + +// Suppress unused warning +void spawn; diff --git a/dashboard/src/app/api/config/route.ts b/dashboard/src/app/api/config/route.ts index 4c09d89..cc147a3 100644 --- a/dashboard/src/app/api/config/route.ts +++ b/dashboard/src/app/api/config/route.ts @@ -10,6 +10,53 @@ import { export const dynamic = "force-dynamic"; export const runtime = "nodejs"; +/** + * Merge a Partial into a full DashboardConfig. All known + * fields are copied; missing fields keep their existing values. + */ +function mergeConfig( + base: DashboardConfig, + patch: Partial | undefined +): DashboardConfig { + if (!patch) return base; + return { + model: patch.model ?? base.model, + ctxSize: patch.ctxSize ?? base.ctxSize, + parallel: patch.parallel ?? base.parallel, + nGpuLayers: patch.nGpuLayers ?? base.nGpuLayers, + threads: patch.threads ?? base.threads, + draftModel: patch.draftModel ?? base.draftModel, + specType: patch.specType ?? base.specType, + specDraftNMax: patch.specDraftNMax ?? base.specDraftNMax, + batchSize: patch.batchSize ?? base.batchSize, + ubatchSize: patch.ubatchSize ?? base.ubatchSize, + contextOverflow: patch.contextOverflow ?? base.contextOverflow, + cacheTypeK: patch.cacheTypeK ?? base.cacheTypeK, + cacheTypeV: patch.cacheTypeV ?? base.cacheTypeV, + defragThold: patch.defragThold ?? base.defragThold, + flashAttn: patch.flashAttn ?? base.flashAttn, + noMmap: patch.noMmap ?? base.noMmap, + mlock: patch.mlock ?? base.mlock, + contBatching: patch.contBatching ?? base.contBatching, + embeddings: patch.embeddings ?? base.embeddings, + metrics: patch.metrics ?? base.metrics, + ropeFreqScale: patch.ropeFreqScale ?? base.ropeFreqScale, + ropeScale: patch.ropeScale ?? base.ropeScale, + yarnExtFactor: patch.yarnExtFactor ?? base.yarnExtFactor, + yarnAttnFactor: patch.yarnAttnFactor ?? base.yarnAttnFactor, + yarnBetaFast: patch.yarnBetaFast ?? base.yarnBetaFast, + yarnBetaSlow: patch.yarnBetaSlow ?? base.yarnBetaSlow, + systemPrompt: patch.systemPrompt ?? base.systemPrompt, + topK: patch.topK ?? base.topK, + topP: patch.topP ?? base.topP, + minP: patch.minP ?? base.minP, + temperature: patch.temperature ?? base.temperature, + repeatPenalty: patch.repeatPenalty ?? base.repeatPenalty, + extraArgs: patch.extraArgs ?? base.extraArgs, + presets: patch.presets ?? base.presets, + }; +} + export async function GET() { const config = await loadConfig(); return NextResponse.json({ config, defaults: DEFAULT_CONFIG }); @@ -18,23 +65,7 @@ export async function GET() { export async function PUT(req: NextRequest) { const body = (await req.json()) as Partial; const current = await loadConfig(); - - // Merge: keep existing presets unless explicitly overwritten - const next: DashboardConfig = { - model: body.model ?? current.model, - ctxSize: body.ctxSize ?? current.ctxSize, - parallel: body.parallel ?? current.parallel, - nGpuLayers: body.nGpuLayers ?? current.nGpuLayers, - threads: body.threads ?? current.threads, - draftModel: body.draftModel ?? current.draftModel, - specType: body.specType ?? current.specType, - specDraftNMax: body.specDraftNMax ?? current.specDraftNMax, - batchSize: body.batchSize ?? current.batchSize, - contextOverflow: body.contextOverflow ?? current.contextOverflow, - extraArgs: body.extraArgs ?? current.extraArgs, - presets: body.presets ?? current.presets, - }; - + const next = mergeConfig(current, body); await saveConfig(next); return NextResponse.json({ config: next }); } @@ -46,9 +77,17 @@ export async function POST(req: NextRequest) { action: "save-preset" | "delete-preset" | "load-preset" | "reset"; name?: string; id?: string; + config?: Partial; }; const current = await loadConfig(); + // If the caller passed a `config` in the body, merge it into `current` + // before performing the action. This is critical for `save-preset`: if the + // user has edited the form but not clicked "Apply" yet, the persisted + // config.json still has the old values, and saving a preset would snapshot + // the OLD config — not what's currently in the UI. + const effective = mergeConfig(current, body.config); + if (body.action === "save-preset") { if (!body.name) { return NextResponse.json( @@ -59,12 +98,15 @@ export async function POST(req: NextRequest) { const preset: Preset = { id: `preset-${Date.now()}`, name: body.name, - config: stripPresets(current), + config: stripPresets(effective), createdAt: new Date().toISOString(), }; const next: DashboardConfig = { - ...current, - presets: [...current.presets.filter((p) => p.name !== body.name), preset], + ...effective, + presets: [ + ...effective.presets.filter((p) => p.name !== body.name), + preset, + ], }; await saveConfig(next); return NextResponse.json({ config: next }); diff --git a/dashboard/src/app/api/metrics/route.ts b/dashboard/src/app/api/metrics/route.ts new file mode 100644 index 0000000..3ca2a88 --- /dev/null +++ b/dashboard/src/app/api/metrics/route.ts @@ -0,0 +1,45 @@ +import { NextResponse } from "next/server"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * GET /api/metrics + * + * Proxies llama.cpp's /metrics (Prometheus) endpoint. The dashboard container + * is on the same Docker network as llama, so http://llama:8080/metrics works. + * + * Returns plain text (Prometheus exposition format). + */ +export async function GET() { + try { + const res = await fetch("http://llama:8080/metrics", { + cache: "no-store", + signal: AbortSignal.timeout(5000), + }); + if (!res.ok) { + return NextResponse.json( + { + ok: false, + error: `llama returned ${res.status}`, + raw: await res.text().catch(() => ""), + }, + { status: res.status } + ); + } + const text = await res.text(); + // Return as plain text — the frontend can render it as
+    return new Response(text, {
+      headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" },
+    });
+  } catch (err) {
+    return NextResponse.json(
+      {
+        ok: false,
+        error: (err as Error).message,
+        hint: "llama container must be running and started with --metrics flag",
+      },
+      { status: 503 }
+    );
+  }
+}
diff --git a/dashboard/src/app/api/slots/route.ts b/dashboard/src/app/api/slots/route.ts
new file mode 100644
index 0000000..2d25ca1
--- /dev/null
+++ b/dashboard/src/app/api/slots/route.ts
@@ -0,0 +1,51 @@
+import { NextResponse } from "next/server";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * GET /api/slots
+ *
+ * Returns llama.cpp slot status from /slots endpoint. Each slot is one
+ * parallel processing unit (controlled by --parallel). Includes:
+ *   - id: slot id (0-indexed)
+ *   - is_processing: bool
+ *   - prompt: current prompt tokens
+ *   - n_ctx: context size
+ *   - n_past: tokens processed so far
+ *   - n_eval: total tokens generated in this slot
+ *   - timings: { prompt_n, prompt_ms, prompt_per_token, prompt_per_second,
+ *                predicted_n, predicted_ms, predicted_per_token,
+ *                predicted_per_second }
+ *
+ * From these we can compute TPS (predicted_per_second), TTFT (prompt_ms),
+ * cache-hit ratio, etc.
+ */
+export async function GET() {
+  try {
+    const res = await fetch("http://llama:8080/slots", {
+      cache: "no-store",
+      signal: AbortSignal.timeout(5000),
+    });
+    if (!res.ok) {
+      return NextResponse.json(
+        {
+          ok: false,
+          error: `llama returned ${res.status}`,
+        },
+        { status: res.status }
+      );
+    }
+    const data = await res.json();
+    return NextResponse.json({ ok: true, slots: data });
+  } catch (err) {
+    return NextResponse.json(
+      {
+        ok: false,
+        error: (err as Error).message,
+        slots: [],
+      },
+      { status: 503 }
+    );
+  }
+}
diff --git a/dashboard/src/app/icon.svg b/dashboard/src/app/icon.svg
new file mode 100644
index 0000000..b49695e
--- /dev/null
+++ b/dashboard/src/app/icon.svg
@@ -0,0 +1,27 @@
+
+  
+    
+      
+      
+    
+  
+  
+  
+  
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+  
+
diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx
index 2ee0127..4aa11a1 100644
--- a/dashboard/src/app/page.tsx
+++ b/dashboard/src/app/page.tsx
@@ -5,14 +5,17 @@ import {
   Activity,
   Cpu,
   CpuIcon,
+  Gauge,
   HardDrive,
   Layers,
+  MessageSquare,
   Moon,
   Play,
   Power,
   RefreshCw,
   RotateCw,
   Save,
+  Send,
   Settings2,
   Square,
   Sun,
@@ -90,7 +93,29 @@ interface DashboardConfig {
   specType: "none" | "draft-mtp" | "draft-llama";
   specDraftNMax: number;
   batchSize: number;
+  ubatchSize: number;
   contextOverflow: "none" | "shift" | "evict";
+  cacheTypeK: "f16" | "f32" | "q8_0" | "q4_0";
+  cacheTypeV: "f16" | "f32" | "q8_0" | "q4_0";
+  defragThold: number;
+  flashAttn: boolean;
+  noMmap: boolean;
+  mlock: boolean;
+  contBatching: boolean;
+  embeddings: boolean;
+  metrics: boolean;
+  ropeFreqScale: number;
+  ropeScale: number;
+  yarnExtFactor: number;
+  yarnAttnFactor: number;
+  yarnBetaFast: number;
+  yarnBetaSlow: number;
+  systemPrompt: string;
+  topK: number;
+  topP: number;
+  minP: number;
+  temperature: number;
+  repeatPenalty: number;
   extraArgs: string;
   presets: Preset[];
 }
@@ -126,7 +151,29 @@ const DEFAULT_CONFIG: DashboardConfig = {
   specType: "none",
   specDraftNMax: 4,
   batchSize: 512,
+  ubatchSize: 512,
   contextOverflow: "none",
+  cacheTypeK: "f16",
+  cacheTypeV: "f16",
+  defragThold: 0.1,
+  flashAttn: true,
+  noMmap: false,
+  mlock: false,
+  contBatching: true,
+  embeddings: false,
+  metrics: false,
+  ropeFreqScale: 1.0,
+  ropeScale: 1.0,
+  yarnExtFactor: 1.0,
+  yarnAttnFactor: 1.0,
+  yarnBetaFast: 32.0,
+  yarnBetaSlow: 1.0,
+  systemPrompt: "",
+  topK: 40,
+  topP: 0.95,
+  minP: 0.05,
+  temperature: 0.8,
+  repeatPenalty: 1.1,
   extraArgs: "",
   presets: [],
 };
@@ -607,7 +654,13 @@ export default function DashboardPage() {
       const res = await fetch("/api/config", {
         method: "POST",
         headers: { "Content-Type": "application/json" },
-        body: JSON.stringify({ action: "save-preset", name: presetName.trim() }),
+        // Send current config so the preset snapshots what's actually in
+        // the form right now — not what was last persisted to config.json.
+        body: JSON.stringify({
+          action: "save-preset",
+          name: presetName.trim(),
+          config,
+        }),
       });
       const data = await res.json();
       if (data.config) {
@@ -829,11 +882,19 @@ export default function DashboardPage() {
 
         {/* Tabs */}
         
-          
+          
             
               
               Config
             
+            
+              
+              Chat
+            
+            
+              
+              Perf
+            
             
               
               Models
@@ -875,6 +936,24 @@ export default function DashboardPage() {
             />
           
 
+          {/* Chat tab */}
+          
+            
+          
+
+          {/* Perf tab */}
+          
+            
+          
+
           {/* Models tab */}
           
             
             
           
+          
+ + update("ubatchSize", Number(e.target.value))} + /> +
+ + + {/* KV cache */} +
+
+ KV cache +

+ Quantize KV cache to save VRAM. q8_0 ≈ 50% memory, q4_0 ≈ 25% + (slight quality drop). +

+
+
+
+ + +
+
+ + +
+
+ + update("defragThold", Number(e.target.value))} + /> +
+
+
+ + {/* Performance flags */} +
+
+ Performance flags +
+
+ update("flashAttn", v)} + /> + update("contBatching", v)} + /> + update("noMmap", v)} + /> + update("mlock", v)} + /> + update("embeddings", v)} + /> + update("metrics", v)} + /> +
+
+ + {/* RoPE / YaRN */} +
+
+ RoPE / YaRN context extension +

+ For extending context beyond the model's training length. + Leave at defaults unless you know what you're doing. +

+
+
+
+ + update("ropeScale", Number(e.target.value))} + /> +
+
+ + update("ropeFreqScale", Number(e.target.value))} + /> +
+
+ + update("yarnExtFactor", Number(e.target.value))} + /> +
+
+ + update("yarnAttnFactor", Number(e.target.value))} + /> +
+
+ + update("yarnBetaFast", Number(e.target.value))} + /> +
+
+ + update("yarnBetaSlow", Number(e.target.value))} + /> +
+
+
+ + {/* Sampling defaults */} +
+
+ Default sampling +

+ Applied as defaults to /completion & /v1/chat/completions requests + (can be overridden per-request). +

+
+
+
+ + update("temperature", Number(e.target.value))} + /> +
+
+ + update("topK", Number(e.target.value))} + /> +
+
+ + update("topP", Number(e.target.value))} + /> +
+
+ + update("minP", Number(e.target.value))} + /> +
+
+ + update("repeatPenalty", Number(e.target.value))} + /> +
+
+
+ +