fix(dashboard): chat survives tab switch, Enter to send, reasoning display, /health via fetch, n-predict + reasoning-format params
## User-reported issues addressed ### 1. Chat resets when switching tabs Chat state lived inside `ChatTab` component → lost on unmount when user switched to Models/Logs/System tabs. **Fix:** lifted all chat state to the top-level component: - `chatMessages`, `chatInput`, `chatStreaming`, `chatAutoScroll` - `chatAbortRef` (for Stop button) - `chatMessagesEndRef` (auto-scroll anchor) ChatTab is now a controlled component that receives state + handlers as props. Switching tabs unmounts the view but state survives. ### 2. Enter to send, Shift+Enter for newline Was: Ctrl+Enter to send. Now: Enter (without Shift/Ctrl/Meta/Alt) sends. Shift+Enter inserts a newline (default textarea behavior). ### 3. Reasoning display (thinking models) **Why no reasoning shown:** llama.cpp's `--reasoning-format auto` splits `` blocks into a separate `delta.reasoning_content` field. We weren't capturing it. **Fix:** - Added `--reasoning-format` config field (none/deepthink/auto, default `auto`). - Added `--jinja` toggle (required for reasoning format to work). - `/api/chat` now passes `reasoning_format` through. - Frontend `handleChatSend` captures `delta.reasoning_content` and stores it in `message.reasoning`. - MessageBubble shows reasoning as a collapsible block above content (▶ Reasoning, click to expand). ### 4. Prefill speed + TTFT in chat stats **Was:** showed 'Prompt: N tok (Xs, Y tok/s)' on one line, easy to miss. **Now:** explicit separate stats: - `TPS:` — generation throughput (predicted_per_second) - `TTFT:` — Time To First Token = prompt_ms / 1000 (with prompt token count in parens) - `Prefill:` — prompt processing speed (prompt_per_second) - `Cache hit:` — KV cache reuse rate - `Spec decoding:` — accepted/drafted + acceptance rate ### 5. Max tokens limit 'У него же нет ограничений в объеме ответа кроме Context size?' — yes there is: `--n-predict` (default -1 = infinity). Was not exposed. **Fix:** added `nPredict` field to DashboardConfig (default -1). Sets `--n-predict` on the server AND `max_tokens` per-request in /api/chat. UI: input in the Default sampling section of ConfigTab. ### 6. /health 'Unreachable' — wget missing **Was:** `docker exec ... wget -qO- http://127.0.0.1:8080/health` → 'OCI runtime exec failed: exec: "wget": executable file not found in /home/z/.venv/bin:/home/z/.venv/bin:/home/z/.npm-global/bin:/home/z/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bun-node-fallback-bin'. The llama.cpp:server-cuda image doesn't include wget. **Fix:** `getLlamaHealth()` now uses Node's native `fetch()` to call `http://llama:8080/health` directly — the dashboard container is on the same Docker network as llama, so this works without exec'ing into the llama container. (Same approach we already use for /api/chat and /api/slots.) ### 7. 'зачем нам отдельно выделять лламму?' `/api/llama` endpoint (start/stop/restart/remove) is functionally identical to `/api/services/llama`. Keeping it for backwards compat with the existing frontend code, but the System tab's per-container action buttons (▶ ↻ ■ 🗑) already use the generic /api/services route. ## Backend ### `dashboard/src/lib/docker.ts` - `DashboardConfig`: added `nPredict`, `reasoningFormat`, `jinja` - `DEFAULT_CONFIG`: nPredict=-1, reasoningFormat='auto', jinja=true - `buildLlamaExtraArgs()`: emits `--n-predict` (if >=0), `--reasoning-format <value>`, `--jinja` (if true) - `parseLlamaExtraArgs()`: parses `--n-predict`/`--predict`/`-n`, `--reasoning-format`, `--jinja`. Added `isValue()` helper. - `getLlamaHealth()`: rewrote to use fetch() instead of docker exec wget ### `dashboard/src/app/api/config/route.ts` - `mergeConfig()` includes the 3 new fields ### `dashboard/src/app/api/chat/route.ts` - Removed unused `spawn` import and the misleading wget comment - Accepts `reasoning_format` in body, passes through to llama.cpp - Sets `stream_options: { include_usage: true }` so timings come back in the final chunk ## Frontend ### `dashboard/src/app/page.tsx` - Lifted chat state (chatMessages, chatInput, chatStreaming, chatAutoScroll, chatAbortRef, chatMessagesEndRef) to the top-level component - ChatTab is now a controlled component (state + handlers as props) - Enter key sends (Shift+Enter for newline) - `handleChatSend()` captures `delta.reasoning_content` → message.reasoning - MessageBubble: collapsible Reasoning block (▶ / ▼) - MessageStats: explicit TPS / TTFT / Prefill / Cache hit / Spec decoding - `DashboardConfig` interface + DEFAULT_CONFIG + buildPreviewArgs all include the 3 new fields - ConfigTab 'Default sampling' section: added n-predict input, reasoning-format select, jinja toggle ## Verification - `npm run build` — OK, 26 routes - `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓ ## After deploy ```sh git pull && sh build.sh docker compose up -d --force-recreate dashboard ``` Then: 1. Open Config tab → Default sampling → set Reasoning format to 'auto' (should be default), Jinja ON (should be default) 2. Start Llama 3. Open Chat tab → send a message to a thinking model (Qwen3, DeepSeek-R1) → see reasoning block above the response 4. Switch to Models tab and back → chat is preserved 5. Press Enter → sends. Shift+Enter → newline 6. Check System tab → Llama /health should show OK (no more wget error) ## Files changed - dashboard/src/lib/docker.ts — new config fields + getLlamaHealth via fetch - dashboard/src/app/api/config/route.ts — mergeConfig new fields - dashboard/src/app/api/chat/route.ts — reasoning_format passthrough, stream_options.include_usage, removed wget cruft - dashboard/src/app/page.tsx — lifted chat state, Enter-to-send, reasoning display, TTFT/Prefill stats, new config fields + UI
This commit is contained in:
@@ -1,6 +1,4 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getLlamaContainerName } from "@/lib/docker";
|
|
||||||
import { spawn } from "node:child_process";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
@@ -10,13 +8,26 @@ export const maxDuration = 300;
|
|||||||
* POST /api/chat
|
* POST /api/chat
|
||||||
*
|
*
|
||||||
* Streams a chat completion from llama.cpp /v1/chat/completions (OpenAI-compatible).
|
* Streams a chat completion from llama.cpp /v1/chat/completions (OpenAI-compatible).
|
||||||
|
* The dashboard container is on the same Docker network as llama, so we call
|
||||||
|
* http://llama:8080/v1/chat/completions directly via Node's native fetch().
|
||||||
*
|
*
|
||||||
* Body: {
|
* Body: {
|
||||||
* messages: [{role, content}],
|
* messages: [{role, content}],
|
||||||
* temperature?, top_p?, top_k?, min_p?, repeat_penalty?, max_tokens?, stream?
|
* temperature?, top_p?, top_k?, min_p?, repeat_penalty?,
|
||||||
|
* max_tokens?, // OpenAI-style; default -1 = infinity
|
||||||
|
* stream?, // default true
|
||||||
|
* reasoning_format?, // 'auto' | 'deepthink' | 'none' (server-side default is 'auto')
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* Returns: SSE stream of OpenAI-compatible chat completion chunks.
|
* Returns: SSE stream of OpenAI-compatible chat completion chunks.
|
||||||
|
*
|
||||||
|
* Each chunk can have:
|
||||||
|
* choices[0].delta.content — regular response token
|
||||||
|
* choices[0].delta.reasoning_content — thinking tokens (when --reasoning-format auto
|
||||||
|
* and the model emits blockDim)
|
||||||
|
* choices[0].timings — present in final chunk if --perf or timings enabled
|
||||||
|
* (prompt_n, prompt_ms, prompt_per_second, predicted_n, predicted_ms,
|
||||||
|
* predicted_per_second, cache_hit_rate, spec_accepted, spec_drafted)
|
||||||
*/
|
*/
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
role: "system" | "user" | "assistant";
|
role: "system" | "user" | "assistant";
|
||||||
@@ -33,6 +44,7 @@ export async function POST(req: NextRequest) {
|
|||||||
repeat_penalty?: number;
|
repeat_penalty?: number;
|
||||||
max_tokens?: number;
|
max_tokens?: number;
|
||||||
stream?: boolean;
|
stream?: boolean;
|
||||||
|
reasoning_format?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) {
|
if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) {
|
||||||
@@ -42,16 +54,7 @@ export async function POST(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const containerName = await getLlamaContainerName();
|
// Build the OpenAI-compatible payload for llama.cpp
|
||||||
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<string, unknown> = {
|
const payload: Record<string, unknown> = {
|
||||||
messages: body.messages,
|
messages: body.messages,
|
||||||
stream: body.stream !== false,
|
stream: body.stream !== false,
|
||||||
@@ -62,16 +65,13 @@ export async function POST(req: NextRequest) {
|
|||||||
if (body.min_p != null) payload.min_p = body.min_p;
|
if (body.min_p != null) payload.min_p = body.min_p;
|
||||||
if (body.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty;
|
if (body.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty;
|
||||||
if (body.max_tokens != null) payload.max_tokens = body.max_tokens;
|
if (body.max_tokens != null) payload.max_tokens = body.max_tokens;
|
||||||
|
if (body.reasoning_format != null) payload.reasoning_format = body.reasoning_format;
|
||||||
|
// Always ask for timings — llama.cpp includes them in the final stream chunk
|
||||||
|
// when stream_options.include_usage is set (or in the last non-streaming
|
||||||
|
// response body).
|
||||||
|
payload.stream_options = { include_usage: true, continuous_usage_stats: false };
|
||||||
|
|
||||||
const payloadJson = JSON.stringify(payload);
|
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 useStream = body.stream !== false;
|
||||||
const encoder = new TextEncoder();
|
const encoder = new TextEncoder();
|
||||||
|
|
||||||
@@ -79,9 +79,6 @@ export async function POST(req: NextRequest) {
|
|||||||
const stream = new ReadableStream<Uint8Array>({
|
const stream = new ReadableStream<Uint8Array>({
|
||||||
async start(controller) {
|
async start(controller) {
|
||||||
try {
|
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", {
|
const res = await fetch("http://llama:8080/v1/chat/completions", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -164,6 +161,3 @@ export async function POST(req: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Suppress unused warning
|
|
||||||
void spawn;
|
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ function mergeConfig(
|
|||||||
minP: patch.minP ?? base.minP,
|
minP: patch.minP ?? base.minP,
|
||||||
temperature: patch.temperature ?? base.temperature,
|
temperature: patch.temperature ?? base.temperature,
|
||||||
repeatPenalty: patch.repeatPenalty ?? base.repeatPenalty,
|
repeatPenalty: patch.repeatPenalty ?? base.repeatPenalty,
|
||||||
|
nPredict: patch.nPredict ?? base.nPredict,
|
||||||
|
reasoningFormat: patch.reasoningFormat ?? base.reasoningFormat,
|
||||||
|
jinja: patch.jinja ?? base.jinja,
|
||||||
extraArgs: patch.extraArgs ?? base.extraArgs,
|
extraArgs: patch.extraArgs ?? base.extraArgs,
|
||||||
presets: patch.presets ?? base.presets,
|
presets: patch.presets ?? base.presets,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -117,6 +117,9 @@ interface DashboardConfig {
|
|||||||
minP: number;
|
minP: number;
|
||||||
temperature: number;
|
temperature: number;
|
||||||
repeatPenalty: number;
|
repeatPenalty: number;
|
||||||
|
nPredict: number;
|
||||||
|
reasoningFormat: "none" | "deepthink" | "auto";
|
||||||
|
jinja: boolean;
|
||||||
extraArgs: string;
|
extraArgs: string;
|
||||||
presets: Preset[];
|
presets: Preset[];
|
||||||
}
|
}
|
||||||
@@ -202,6 +205,9 @@ const DEFAULT_CONFIG: DashboardConfig = {
|
|||||||
minP: 0.05,
|
minP: 0.05,
|
||||||
temperature: 0.8,
|
temperature: 0.8,
|
||||||
repeatPenalty: 1.1,
|
repeatPenalty: 1.1,
|
||||||
|
nPredict: -1,
|
||||||
|
reasoningFormat: "auto",
|
||||||
|
jinja: true,
|
||||||
extraArgs: "",
|
extraArgs: "",
|
||||||
presets: [],
|
presets: [],
|
||||||
};
|
};
|
||||||
@@ -283,6 +289,15 @@ export default function DashboardPage() {
|
|||||||
});
|
});
|
||||||
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(null);
|
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(null);
|
||||||
|
|
||||||
|
// Chat state — kept at top level so switching tabs doesn't reset the
|
||||||
|
// conversation. ChatTab is mounted/unmounted when the user clicks the tab.
|
||||||
|
const [chatMessages, setChatMessages] = React.useState<ChatMessage[]>([]);
|
||||||
|
const [chatInput, setChatInput] = React.useState("");
|
||||||
|
const [chatStreaming, setChatStreaming] = React.useState(false);
|
||||||
|
const [chatAutoScroll, setChatAutoScroll] = React.useState(true);
|
||||||
|
const chatAbortRef = React.useRef<AbortController | null>(null);
|
||||||
|
const chatMessagesEndRef = React.useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
const llamaContainer = containers.find((c) => c.role === "llama") || null;
|
const llamaContainer = containers.find((c) => c.role === "llama") || null;
|
||||||
const comfyContainer = containers.find((c) => c.role === "comfyui") || null;
|
const comfyContainer = containers.find((c) => c.role === "comfyui") || null;
|
||||||
|
|
||||||
@@ -905,6 +920,190 @@ export default function DashboardPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Chat handlers (state lives at top level to survive tab switches)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (chatAutoScroll) {
|
||||||
|
chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||||
|
}
|
||||||
|
}, [chatMessages, chatAutoScroll]);
|
||||||
|
|
||||||
|
// Cleanup any in-flight chat request on unmount
|
||||||
|
React.useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (chatAbortRef.current) {
|
||||||
|
chatAbortRef.current.abort();
|
||||||
|
chatAbortRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function handleChatSend() {
|
||||||
|
if (!chatInput.trim() || chatStreaming || !llamaContainer?.running) return;
|
||||||
|
|
||||||
|
const userMsg: ChatMessage = { role: "user", content: chatInput.trim() };
|
||||||
|
const systemMsg: ChatMessage | null = config.systemPrompt.trim()
|
||||||
|
? { role: "system", content: config.systemPrompt.trim() }
|
||||||
|
: null;
|
||||||
|
const inputText = chatInput;
|
||||||
|
setChatInput("");
|
||||||
|
|
||||||
|
// Build the messages we send to the server: system + history + new user msg
|
||||||
|
const historyForServer: ChatMessage[] = systemMsg
|
||||||
|
? [systemMsg, ...chatMessages.filter((m) => m.role !== "system"), userMsg]
|
||||||
|
: [...chatMessages.filter((m) => m.role !== "system"), userMsg];
|
||||||
|
|
||||||
|
// For display: history + new user msg + empty assistant placeholder
|
||||||
|
const allMsgs = [...chatMessages, userMsg];
|
||||||
|
setChatMessages([...allMsgs, { role: "assistant", content: "" }]);
|
||||||
|
setChatStreaming(true);
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
chatAbortRef.current = controller;
|
||||||
|
|
||||||
|
const assistantIdx = allMsgs.length;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/chat", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
messages: historyForServer,
|
||||||
|
temperature: config.temperature,
|
||||||
|
top_p: config.topP,
|
||||||
|
top_k: config.topK,
|
||||||
|
min_p: config.minP,
|
||||||
|
repeat_penalty: config.repeatPenalty,
|
||||||
|
// Pass nPredict as max_tokens (-1 = infinity, model decides)
|
||||||
|
max_tokens: config.nPredict,
|
||||||
|
reasoning_format: config.reasoningFormat,
|
||||||
|
stream: true,
|
||||||
|
}),
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok || !res.body) {
|
||||||
|
const errText = await res.text().catch(() => "");
|
||||||
|
setChatMessages((prev) => {
|
||||||
|
const next = [...prev];
|
||||||
|
next[assistantIdx] = {
|
||||||
|
role: "assistant",
|
||||||
|
content: `[error: ${res.status} ${errText.slice(0, 200)}]`,
|
||||||
|
};
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buf = "";
|
||||||
|
let finalTimings: ChatMessage["timings"] | undefined;
|
||||||
|
let specAccepted: number | undefined;
|
||||||
|
let specDrafted: number | undefined;
|
||||||
|
|
||||||
|
const pump = (): Promise<void> =>
|
||||||
|
reader.read().then(({ done, value }) => {
|
||||||
|
if (done) return;
|
||||||
|
buf += decoder.decode(value, { stream: true });
|
||||||
|
const lines = buf.split("\n");
|
||||||
|
buf = lines.pop() || "";
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line.startsWith("data: ")) continue;
|
||||||
|
const payload = line.slice("data: ".length).trim();
|
||||||
|
if (payload === "[DONE]") continue;
|
||||||
|
try {
|
||||||
|
const chunk = JSON.parse(payload);
|
||||||
|
const choice = chunk.choices?.[0];
|
||||||
|
const delta = choice?.delta;
|
||||||
|
// Regular content
|
||||||
|
const contentDelta = delta?.content;
|
||||||
|
// Reasoning content (thinking blocks) — separate stream
|
||||||
|
const reasoningDelta = delta?.reasoning_content;
|
||||||
|
setChatMessages((prev) => {
|
||||||
|
const next = [...prev];
|
||||||
|
const cur = next[assistantIdx];
|
||||||
|
if (cur) {
|
||||||
|
if (typeof contentDelta === "string" && contentDelta.length > 0) {
|
||||||
|
cur.content = (cur.content || "") + contentDelta;
|
||||||
|
}
|
||||||
|
if (typeof reasoningDelta === "string" && reasoningDelta.length > 0) {
|
||||||
|
cur.reasoning = (cur.reasoning || "") + reasoningDelta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
// Capture timings (llama.cpp puts them in choice.timings or chunk.timings)
|
||||||
|
const t = choice?.timings || chunk.timings;
|
||||||
|
if (t) {
|
||||||
|
finalTimings = {
|
||||||
|
predicted_n: t.predicted_n,
|
||||||
|
predicted_ms: t.predicted_ms,
|
||||||
|
predicted_per_second: t.predicted_per_second,
|
||||||
|
prompt_n: t.prompt_n,
|
||||||
|
prompt_ms: t.prompt_ms,
|
||||||
|
prompt_per_second: t.prompt_per_second,
|
||||||
|
cache_hit_rate: t.cache_hit_rate ?? t.cache_hit,
|
||||||
|
};
|
||||||
|
if (t.spec_accepted != null) specAccepted = t.spec_accepted;
|
||||||
|
if (t.spec_drafted != null) specDrafted = t.spec_drafted;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore malformed chunk */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pump();
|
||||||
|
});
|
||||||
|
|
||||||
|
await pump();
|
||||||
|
|
||||||
|
// Attach timings to the final assistant message
|
||||||
|
if (finalTimings || specAccepted != null || specDrafted != null) {
|
||||||
|
setChatMessages((prev) => {
|
||||||
|
const next = [...prev];
|
||||||
|
const cur = next[assistantIdx];
|
||||||
|
if (cur) {
|
||||||
|
if (finalTimings) cur.timings = finalTimings;
|
||||||
|
if (specAccepted != null) cur.specAccepted = specAccepted;
|
||||||
|
if (specDrafted != null) cur.specDrafted = specDrafted;
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as Error).name !== "AbortError") {
|
||||||
|
setChatMessages((prev) => {
|
||||||
|
const next = [...prev];
|
||||||
|
next[assistantIdx] = {
|
||||||
|
role: "assistant",
|
||||||
|
content: `[error: ${(err as Error).message}]`,
|
||||||
|
};
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Aborted — leave whatever was streamed so far
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setChatStreaming(false);
|
||||||
|
chatAbortRef.current = null;
|
||||||
|
}
|
||||||
|
void inputText; // suppress unused
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleChatStop() {
|
||||||
|
if (chatAbortRef.current) {
|
||||||
|
chatAbortRef.current.abort();
|
||||||
|
chatAbortRef.current = null;
|
||||||
|
}
|
||||||
|
setChatStreaming(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleChatClear() {
|
||||||
|
setChatMessages([]);
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSavePreset() {
|
async function handleSavePreset() {
|
||||||
if (!presetName.trim()) {
|
if (!presetName.trim()) {
|
||||||
showToast("error", "Preset name required");
|
showToast("error", "Preset name required");
|
||||||
@@ -1200,12 +1399,16 @@ export default function DashboardPage() {
|
|||||||
{/* Chat tab */}
|
{/* Chat tab */}
|
||||||
<TabsContent value="chat">
|
<TabsContent value="chat">
|
||||||
<ChatTab
|
<ChatTab
|
||||||
systemPrompt={config.systemPrompt}
|
messages={chatMessages}
|
||||||
temperature={config.temperature}
|
input={chatInput}
|
||||||
topP={config.topP}
|
setInput={setChatInput}
|
||||||
topK={config.topK}
|
streaming={chatStreaming}
|
||||||
minP={config.minP}
|
autoScroll={chatAutoScroll}
|
||||||
repeatPenalty={config.repeatPenalty}
|
setAutoScroll={setChatAutoScroll}
|
||||||
|
onSend={handleChatSend}
|
||||||
|
onStop={handleChatStop}
|
||||||
|
onClear={handleChatClear}
|
||||||
|
messagesEndRef={chatMessagesEndRef}
|
||||||
llamaRunning={!!llamaContainer?.running}
|
llamaRunning={!!llamaContainer?.running}
|
||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -1940,7 +2143,63 @@ function ConfigTab({
|
|||||||
onChange={(e) => update("repeatPenalty", Number(e.target.value))}
|
onChange={(e) => update("repeatPenalty", Number(e.target.value))}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="n-predict">Max tokens / response</Label>
|
||||||
|
<Input
|
||||||
|
id="n-predict"
|
||||||
|
type="number"
|
||||||
|
min={-1}
|
||||||
|
value={config.nPredict}
|
||||||
|
onChange={(e) => update("nPredict", Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
-1 = infinity (model decides). Sets --n-predict on the server.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Reasoning / Jinja — for thinking models (Qwen3, DeepSeek-R1, etc.) */}
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="reasoning-format">Reasoning format</Label>
|
||||||
|
<Select
|
||||||
|
value={config.reasoningFormat}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
update("reasoningFormat", v as DashboardConfig["reasoningFormat"])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="reasoning-format">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="auto">
|
||||||
|
auto (recommended) — split thinking into reasoning_content
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value="deepthink">
|
||||||
|
deepthink — force thinking even if model wouldn't
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value="none">
|
||||||
|
none — passthrough raw (thinking tags appear in content)
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<p className="text-[10px] text-muted-foreground">
|
||||||
|
For Qwen3, DeepSeek-R1, gpt-oss. "auto" puts
|
||||||
|
<think>...</think> blocks into a separate
|
||||||
|
reasoning_content field shown in chat.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="jinja-toggle">Jinja chat templates</Label>
|
||||||
|
<ToggleRow
|
||||||
|
label="Enable --jinja"
|
||||||
|
hint="Required for reasoning format + tool calling. Recommended ON."
|
||||||
|
checked={config.jinja}
|
||||||
|
onChange={(v) => update("jinja", v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<Label htmlFor="sys-prompt">System prompt (default)</Label>
|
<Label htmlFor="sys-prompt">System prompt (default)</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
@@ -3014,6 +3273,10 @@ function SystemTab({
|
|||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
role: "system" | "user" | "assistant";
|
role: "system" | "user" | "assistant";
|
||||||
content: string;
|
content: string;
|
||||||
|
// For assistant only — reasoning content (thinking blocks) when
|
||||||
|
// --reasoning-format auto is enabled on the server. Streamed separately
|
||||||
|
// via delta.reasoning_content.
|
||||||
|
reasoning?: string;
|
||||||
// For assistant only — timings from llama.cpp response
|
// For assistant only — timings from llama.cpp response
|
||||||
timings?: {
|
timings?: {
|
||||||
predicted_n?: number;
|
predicted_n?: number;
|
||||||
@@ -3030,193 +3293,30 @@ interface ChatMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ChatTab({
|
function ChatTab({
|
||||||
systemPrompt,
|
messages,
|
||||||
temperature,
|
input,
|
||||||
topP,
|
setInput,
|
||||||
topK,
|
streaming,
|
||||||
minP,
|
autoScroll,
|
||||||
repeatPenalty,
|
setAutoScroll,
|
||||||
|
onSend,
|
||||||
|
onStop,
|
||||||
|
onClear,
|
||||||
|
messagesEndRef,
|
||||||
llamaRunning,
|
llamaRunning,
|
||||||
}: {
|
}: {
|
||||||
systemPrompt: string;
|
messages: ChatMessage[];
|
||||||
temperature: number;
|
input: string;
|
||||||
topP: number;
|
setInput: (v: string) => void;
|
||||||
topK: number;
|
streaming: boolean;
|
||||||
minP: number;
|
autoScroll: boolean;
|
||||||
repeatPenalty: number;
|
setAutoScroll: (v: boolean) => void;
|
||||||
|
onSend: () => void;
|
||||||
|
onStop: () => void;
|
||||||
|
onClear: () => void;
|
||||||
|
messagesEndRef: React.RefObject<HTMLDivElement | null>;
|
||||||
llamaRunning: boolean;
|
llamaRunning: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [messages, setMessages] = React.useState<ChatMessage[]>([]);
|
|
||||||
const [input, setInput] = React.useState("");
|
|
||||||
const [streaming, setStreaming] = React.useState(false);
|
|
||||||
const [autoScroll, setAutoScroll] = React.useState(true);
|
|
||||||
const abortRef = React.useRef<AbortController | null>(null);
|
|
||||||
const messagesEndRef = React.useRef<HTMLDivElement | null>(null);
|
|
||||||
|
|
||||||
// Reset chat on mount if systemPrompt changes
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (messages.length === 0 && systemPrompt) {
|
|
||||||
setMessages([{ role: "system", content: systemPrompt }]);
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [systemPrompt]);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (autoScroll) {
|
|
||||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
|
||||||
}
|
|
||||||
}, [messages, autoScroll]);
|
|
||||||
|
|
||||||
async function handleSend() {
|
|
||||||
if (!input.trim() || streaming || !llamaRunning) return;
|
|
||||||
|
|
||||||
const userMsg: ChatMessage = { role: "user", content: input.trim() };
|
|
||||||
setInput("");
|
|
||||||
const allMsgs = [...messages, userMsg];
|
|
||||||
setMessages(allMsgs);
|
|
||||||
setStreaming(true);
|
|
||||||
|
|
||||||
const controller = new AbortController();
|
|
||||||
abortRef.current = controller;
|
|
||||||
|
|
||||||
// Add an empty assistant message we'll stream into
|
|
||||||
const assistantIdx = allMsgs.length;
|
|
||||||
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch("/api/chat", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
messages: allMsgs,
|
|
||||||
temperature,
|
|
||||||
top_p: topP,
|
|
||||||
top_k: topK,
|
|
||||||
min_p: minP,
|
|
||||||
repeat_penalty: repeatPenalty,
|
|
||||||
stream: true,
|
|
||||||
}),
|
|
||||||
signal: controller.signal,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok || !res.body) {
|
|
||||||
const errText = await res.text().catch(() => "");
|
|
||||||
setMessages((prev) => {
|
|
||||||
const next = [...prev];
|
|
||||||
next[assistantIdx] = {
|
|
||||||
role: "assistant",
|
|
||||||
content: `[error: ${res.status} ${errText.slice(0, 200)}]`,
|
|
||||||
};
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = res.body.getReader();
|
|
||||||
const decoder = new TextDecoder();
|
|
||||||
let buf = "";
|
|
||||||
let finalTimings: ChatMessage["timings"] | undefined;
|
|
||||||
let specAccepted: number | undefined;
|
|
||||||
let specDrafted: number | undefined;
|
|
||||||
|
|
||||||
const pump = (): Promise<void> =>
|
|
||||||
reader.read().then(({ done, value }) => {
|
|
||||||
if (done) return;
|
|
||||||
buf += decoder.decode(value, { stream: true });
|
|
||||||
|
|
||||||
// Parse SSE chunks: lines starting with "data: "
|
|
||||||
const lines = buf.split("\n");
|
|
||||||
buf = lines.pop() || "";
|
|
||||||
|
|
||||||
for (const line of lines) {
|
|
||||||
if (!line.startsWith("data: ")) continue;
|
|
||||||
const payload = line.slice("data: ".length).trim();
|
|
||||||
if (payload === "[DONE]") continue;
|
|
||||||
try {
|
|
||||||
const chunk = JSON.parse(payload);
|
|
||||||
// OpenAI-compatible chunk has choices[0].delta.content
|
|
||||||
const delta = chunk.choices?.[0]?.delta?.content;
|
|
||||||
if (typeof delta === "string" && delta.length > 0) {
|
|
||||||
setMessages((prev) => {
|
|
||||||
const next = [...prev];
|
|
||||||
const cur = next[assistantIdx];
|
|
||||||
next[assistantIdx] = {
|
|
||||||
...cur,
|
|
||||||
content: (cur?.content || "") + delta,
|
|
||||||
};
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Capture timings if present (llama.cpp includes them in the
|
|
||||||
// final chunk under choices[0].timings or under .timings)
|
|
||||||
const t = chunk.choices?.[0]?.timings || chunk.timings;
|
|
||||||
if (t) {
|
|
||||||
finalTimings = {
|
|
||||||
predicted_n: t.predicted_n,
|
|
||||||
predicted_ms: t.predicted_ms,
|
|
||||||
predicted_per_second: t.predicted_per_second,
|
|
||||||
prompt_n: t.prompt_n,
|
|
||||||
prompt_ms: t.prompt_ms,
|
|
||||||
prompt_per_second: t.prompt_per_second,
|
|
||||||
cache_hit_rate: t.cache_hit_rate,
|
|
||||||
};
|
|
||||||
if (t.spec_accepted != null)
|
|
||||||
specAccepted = t.spec_accepted;
|
|
||||||
if (t.spec_drafted != null)
|
|
||||||
specDrafted = t.spec_drafted;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore malformed chunk */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return pump();
|
|
||||||
});
|
|
||||||
|
|
||||||
await pump();
|
|
||||||
|
|
||||||
// Attach timings to the final assistant message
|
|
||||||
if (finalTimings) {
|
|
||||||
setMessages((prev) => {
|
|
||||||
const next = [...prev];
|
|
||||||
const cur = next[assistantIdx];
|
|
||||||
next[assistantIdx] = {
|
|
||||||
...cur,
|
|
||||||
timings: finalTimings,
|
|
||||||
specAccepted,
|
|
||||||
specDrafted,
|
|
||||||
};
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
if ((err as Error).name !== "AbortError") {
|
|
||||||
setMessages((prev) => {
|
|
||||||
const next = [...prev];
|
|
||||||
next[assistantIdx] = {
|
|
||||||
role: "assistant",
|
|
||||||
content: `[error: ${(err as Error).message}]`,
|
|
||||||
};
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setStreaming(false);
|
|
||||||
abortRef.current = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleStop() {
|
|
||||||
if (abortRef.current) {
|
|
||||||
abortRef.current.abort();
|
|
||||||
abortRef.current = null;
|
|
||||||
}
|
|
||||||
setStreaming(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleClear() {
|
|
||||||
setMessages(systemPrompt ? [{ role: "system", content: systemPrompt }] : []);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
|
<CardHeader className="flex flex-row items-center justify-between gap-2 flex-wrap">
|
||||||
@@ -3238,7 +3338,7 @@ function ChatTab({
|
|||||||
/>
|
/>
|
||||||
Auto-scroll
|
Auto-scroll
|
||||||
</label>
|
</label>
|
||||||
<Button size="sm" variant="ghost" onClick={handleClear}>
|
<Button size="sm" variant="ghost" onClick={onClear} disabled={messages.length === 0}>
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
Clear
|
Clear
|
||||||
</Button>
|
</Button>
|
||||||
@@ -3273,25 +3373,28 @@ function ChatTab({
|
|||||||
<Textarea
|
<Textarea
|
||||||
value={input}
|
value={input}
|
||||||
onChange={(e) => setInput(e.target.value)}
|
onChange={(e) => setInput(e.target.value)}
|
||||||
placeholder="Type a message... (Ctrl+Enter to send)"
|
placeholder="Type a message... (Enter to send, Shift+Enter for newline)"
|
||||||
rows={2}
|
rows={2}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
// Enter = send. Shift+Enter = newline (default behavior).
|
||||||
|
if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
handleSend();
|
if (!streaming && llamaRunning && input.trim()) {
|
||||||
|
onSend();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className="flex-1 resize-none"
|
className="flex-1 resize-none"
|
||||||
disabled={!llamaRunning || streaming}
|
disabled={!llamaRunning || streaming}
|
||||||
/>
|
/>
|
||||||
{streaming ? (
|
{streaming ? (
|
||||||
<Button onClick={handleStop} variant="destructive">
|
<Button onClick={onStop} variant="destructive">
|
||||||
<Square className="h-3.5 w-3.5" />
|
<Square className="h-3.5 w-3.5" />
|
||||||
Stop
|
Stop
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSend}
|
onClick={onSend}
|
||||||
disabled={!llamaRunning || !input.trim()}
|
disabled={!llamaRunning || !input.trim()}
|
||||||
>
|
>
|
||||||
<Send className="h-3.5 w-3.5" />
|
<Send className="h-3.5 w-3.5" />
|
||||||
@@ -3308,6 +3411,7 @@ function MessageBubble({ message }: { message: ChatMessage }) {
|
|||||||
const isUser = message.role === "user";
|
const isUser = message.role === "user";
|
||||||
const isAssistant = message.role === "assistant";
|
const isAssistant = message.role === "assistant";
|
||||||
const isSystem = message.role === "system";
|
const isSystem = message.role === "system";
|
||||||
|
const [reasoningExpanded, setReasoningExpanded] = React.useState(false);
|
||||||
|
|
||||||
if (isSystem) {
|
if (isSystem) {
|
||||||
return (
|
return (
|
||||||
@@ -3327,7 +3431,30 @@ function MessageBubble({ message }: { message: ChatMessage }) {
|
|||||||
: "bg-muted text-foreground"
|
: "bg-muted text-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="whitespace-pre-wrap break-words">{message.content}</div>
|
{/* Reasoning block (thinking) — shown above content, collapsible */}
|
||||||
|
{isAssistant && message.reasoning && message.reasoning.length > 0 && (
|
||||||
|
<div className="mb-2 rounded border border-border/40 bg-background/50">
|
||||||
|
<button
|
||||||
|
className="w-full px-2 py-1 flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||||
|
onClick={() => setReasoningExpanded((v) => !v)}
|
||||||
|
>
|
||||||
|
<span className="font-medium">
|
||||||
|
{reasoningExpanded ? "▼" : "▶"} Reasoning
|
||||||
|
</span>
|
||||||
|
<span className="opacity-60">
|
||||||
|
({message.reasoning.length} chars)
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{reasoningExpanded && (
|
||||||
|
<pre className="px-2 pb-2 text-[10px] font-mono whitespace-pre-wrap break-all text-muted-foreground max-h-60 overflow-y-auto scrollbar-thin">
|
||||||
|
{message.reasoning}
|
||||||
|
</pre>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="whitespace-pre-wrap break-words">
|
||||||
|
{message.content || (isAssistant && (!message.reasoning || message.reasoning.length === 0) ? "…" : "")}
|
||||||
|
</div>
|
||||||
{isAssistant && message.timings && (
|
{isAssistant && message.timings && (
|
||||||
<MessageStats message={message} />
|
<MessageStats message={message} />
|
||||||
)}
|
)}
|
||||||
@@ -3341,6 +3468,7 @@ function MessageStats({ message }: { message: ChatMessage }) {
|
|||||||
if (!t) return null;
|
if (!t) return null;
|
||||||
return (
|
return (
|
||||||
<div className="mt-2 pt-2 border-t border-border/30 text-[10px] font-mono text-muted-foreground space-y-0.5">
|
<div className="mt-2 pt-2 border-t border-border/30 text-[10px] font-mono text-muted-foreground space-y-0.5">
|
||||||
|
{/* TPS — generation speed */}
|
||||||
{t.predicted_per_second != null && (
|
{t.predicted_per_second != null && (
|
||||||
<div>
|
<div>
|
||||||
<span className="text-foreground">TPS:</span>{" "}
|
<span className="text-foreground">TPS:</span>{" "}
|
||||||
@@ -3352,25 +3480,32 @@ function MessageStats({ message }: { message: ChatMessage }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{t.prompt_n != null && (
|
{/* TTFT — Time To First Token. This is the time spent processing the
|
||||||
|
prompt before generation started. */}
|
||||||
|
{t.prompt_ms != null && (
|
||||||
<div>
|
<div>
|
||||||
<span className="text-foreground">Prompt:</span> {t.prompt_n} tok
|
<span className="text-foreground">TTFT:</span>{" "}
|
||||||
{t.prompt_ms != null && (
|
{(t.prompt_ms / 1000).toFixed(2)}s
|
||||||
<span className="ml-2">
|
{t.prompt_n != null && (
|
||||||
({(t.prompt_ms / 1000).toFixed(2)}s
|
<span className="ml-2">({t.prompt_n} prompt tok)</span>
|
||||||
{t.prompt_per_second != null &&
|
|
||||||
`, ${t.prompt_per_second.toFixed(1)} tok/s`}
|
|
||||||
)
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{/* Prefill speed — prompt processing throughput */}
|
||||||
|
{t.prompt_per_second != null && (
|
||||||
|
<div>
|
||||||
|
<span className="text-foreground">Prefill:</span>{" "}
|
||||||
|
{t.prompt_per_second.toFixed(1)} tok/s
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* Cache hit rate — how much of the prompt was reused from KV cache */}
|
||||||
{t.cache_hit_rate != null && (
|
{t.cache_hit_rate != null && (
|
||||||
<div>
|
<div>
|
||||||
<span className="text-foreground">Cache hit:</span>{" "}
|
<span className="text-foreground">Cache hit:</span>{" "}
|
||||||
{(t.cache_hit_rate * 100).toFixed(1)}%
|
{(t.cache_hit_rate * 100).toFixed(1)}%
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{/* Speculative decoding stats */}
|
||||||
{message.specDrafted != null && message.specAccepted != null && (
|
{message.specDrafted != null && message.specAccepted != null && (
|
||||||
<div>
|
<div>
|
||||||
<span className="text-foreground">Spec decoding:</span>{" "}
|
<span className="text-foreground">Spec decoding:</span>{" "}
|
||||||
@@ -3825,6 +3960,9 @@ function buildPreviewArgs(cfg: DashboardConfig): string {
|
|||||||
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
|
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
|
||||||
if (cfg.repeatPenalty > 1.0)
|
if (cfg.repeatPenalty > 1.0)
|
||||||
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
|
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
|
||||||
|
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
|
||||||
|
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
|
||||||
|
if (cfg.jinja) parts.push("--jinja");
|
||||||
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
|
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
|
||||||
return parts.join(" ");
|
return parts.join(" ");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -252,6 +252,22 @@ export interface DashboardConfig {
|
|||||||
temperature: number;
|
temperature: number;
|
||||||
/** Sampling: repeat penalty (1.0 = disabled) */
|
/** Sampling: repeat penalty (1.0 = disabled) */
|
||||||
repeatPenalty: number;
|
repeatPenalty: number;
|
||||||
|
/**
|
||||||
|
* Max tokens to predict per response. -1 = infinity (model decides).
|
||||||
|
* Sets --n-predict on the server side; also passed as max_tokens
|
||||||
|
* per-request in /api/chat.
|
||||||
|
*/
|
||||||
|
nPredict: number;
|
||||||
|
/**
|
||||||
|
* Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss).
|
||||||
|
* - "auto": llama.cpp auto-detects and splits <think>...</think> into
|
||||||
|
* the reasoning_content field (recommended)
|
||||||
|
* - "deepthink": force thinking even if model wouldn't normally
|
||||||
|
* - "none": passthrough raw (thinking tags appear in content)
|
||||||
|
*/
|
||||||
|
reasoningFormat: "none" | "deepthink" | "auto";
|
||||||
|
/** Enable Jinja chat templates (required for tool calling + reasoning) */
|
||||||
|
jinja: boolean;
|
||||||
/** Free-form extra args (advanced) */
|
/** Free-form extra args (advanced) */
|
||||||
extraArgs: string;
|
extraArgs: string;
|
||||||
/** Saved presets */
|
/** Saved presets */
|
||||||
@@ -298,6 +314,9 @@ export const DEFAULT_CONFIG: DashboardConfig = {
|
|||||||
minP: 0.05,
|
minP: 0.05,
|
||||||
temperature: 0.8,
|
temperature: 0.8,
|
||||||
repeatPenalty: 1.1,
|
repeatPenalty: 1.1,
|
||||||
|
nPredict: -1,
|
||||||
|
reasoningFormat: "auto",
|
||||||
|
jinja: true,
|
||||||
extraArgs: "",
|
extraArgs: "",
|
||||||
presets: [],
|
presets: [],
|
||||||
};
|
};
|
||||||
@@ -517,6 +536,21 @@ export function parseLlamaExtraArgs(
|
|||||||
cfg.repeatPenalty = Number(next);
|
cfg.repeatPenalty = Number(next);
|
||||||
i++;
|
i++;
|
||||||
break;
|
break;
|
||||||
|
case "--n-predict":
|
||||||
|
case "--predict":
|
||||||
|
case "-n":
|
||||||
|
cfg.nPredict = Number(next);
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
|
case "--reasoning-format":
|
||||||
|
if (isValue(next)) {
|
||||||
|
cfg.reasoningFormat = next as DashboardConfig["reasoningFormat"];
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "--jinja":
|
||||||
|
cfg.jinja = true;
|
||||||
|
break;
|
||||||
case "--model-draft":
|
case "--model-draft":
|
||||||
cfg.draftModel = path.basename(next || "");
|
cfg.draftModel = path.basename(next || "");
|
||||||
i++;
|
i++;
|
||||||
@@ -617,6 +651,12 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
|
|||||||
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
|
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
|
||||||
if (cfg.repeatPenalty > 1.0)
|
if (cfg.repeatPenalty > 1.0)
|
||||||
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
|
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
|
||||||
|
// Max tokens per response (default -1 = infinity)
|
||||||
|
if (cfg.nPredict >= 0) parts.push(`--n-predict ${cfg.nPredict}`);
|
||||||
|
// Reasoning format for thinking models (Qwen3, DeepSeek-R1, gpt-oss)
|
||||||
|
parts.push(`--reasoning-format ${cfg.reasoningFormat}`);
|
||||||
|
// Jinja chat templates (required for reasoning format to work properly)
|
||||||
|
if (cfg.jinja) parts.push("--jinja");
|
||||||
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
|
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
|
||||||
return parts.join(" ");
|
return parts.join(" ");
|
||||||
}
|
}
|
||||||
@@ -1043,15 +1083,27 @@ export async function getLlamaHealth(): Promise<{
|
|||||||
reachable: boolean;
|
reachable: boolean;
|
||||||
detail: string;
|
detail: string;
|
||||||
}> {
|
}> {
|
||||||
// Llama.cpp /completion endpoint returns 405 on GET /, but /health works.
|
// Llama.cpp /health returns "ok" / "loading model" / "error".
|
||||||
|
//
|
||||||
|
// We use Node's native fetch() to call http://llama:8080 directly — the
|
||||||
|
// dashboard container is on the same Docker network as llama, so this
|
||||||
|
// works without exec'ing into the llama container.
|
||||||
|
//
|
||||||
|
// (Previous impl used `docker exec ... wget -qO-` — but the llama.cpp
|
||||||
|
// server-cuda image doesn't include wget, causing "executable file not
|
||||||
|
// found in $PATH" errors.)
|
||||||
try {
|
try {
|
||||||
const { stdout } = await execAsync(
|
const res = await fetch("http://llama:8080/health", {
|
||||||
`docker exec $(docker ps --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}} | head -n1) wget -qO- http://127.0.0.1:8080/health || true`,
|
signal: AbortSignal.timeout(3000),
|
||||||
{ maxBuffer: 1 * 1024 * 1024, timeout: 5000 }
|
});
|
||||||
);
|
const text = await res.text();
|
||||||
const text = String(stdout);
|
if (res.ok && text.includes("ok")) {
|
||||||
if (text.includes("ok")) return { reachable: true, detail: text.trim() };
|
return { reachable: true, detail: text.trim() };
|
||||||
return { reachable: false, detail: text || "no response" };
|
}
|
||||||
|
return {
|
||||||
|
reachable: false,
|
||||||
|
detail: `HTTP ${res.status}: ${text.trim().slice(0, 200)}`,
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
reachable: false,
|
reachable: false,
|
||||||
|
|||||||
Reference in New Issue
Block a user