diff --git a/dashboard/src/app/api/chat/route.ts b/dashboard/src/app/api/chat/route.ts index 9439665..5f2162b 100644 --- a/dashboard/src/app/api/chat/route.ts +++ b/dashboard/src/app/api/chat/route.ts @@ -1,6 +1,4 @@ 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"; @@ -10,13 +8,26 @@ export const maxDuration = 300; * POST /api/chat * * 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: { * 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. + * + * 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 { role: "system" | "user" | "assistant"; @@ -33,6 +44,7 @@ export async function POST(req: NextRequest) { repeat_penalty?: number; max_tokens?: number; stream?: boolean; + reasoning_format?: string; }; 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(); - 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. + // Build the OpenAI-compatible payload for llama.cpp const payload: Record = { messages: body.messages, 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.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty; 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); - - // 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(); @@ -79,9 +79,6 @@ export async function POST(req: NextRequest) { 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: { @@ -164,6 +161,3 @@ export async function POST(req: NextRequest) { } } } - -// Suppress unused warning -void spawn; diff --git a/dashboard/src/app/api/config/route.ts b/dashboard/src/app/api/config/route.ts index cc147a3..891b4a4 100644 --- a/dashboard/src/app/api/config/route.ts +++ b/dashboard/src/app/api/config/route.ts @@ -52,6 +52,9 @@ function mergeConfig( minP: patch.minP ?? base.minP, temperature: patch.temperature ?? base.temperature, 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, presets: patch.presets ?? base.presets, }; diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx index a56d635..421cf7d 100644 --- a/dashboard/src/app/page.tsx +++ b/dashboard/src/app/page.tsx @@ -117,6 +117,9 @@ interface DashboardConfig { minP: number; temperature: number; repeatPenalty: number; + nPredict: number; + reasoningFormat: "none" | "deepthink" | "auto"; + jinja: boolean; extraArgs: string; presets: Preset[]; } @@ -202,6 +205,9 @@ const DEFAULT_CONFIG: DashboardConfig = { minP: 0.05, temperature: 0.8, repeatPenalty: 1.1, + nPredict: -1, + reasoningFormat: "auto", + jinja: true, extraArgs: "", presets: [], }; @@ -283,6 +289,15 @@ export default function DashboardPage() { }); const [urlPreview, setUrlPreview] = React.useState(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([]); + const [chatInput, setChatInput] = React.useState(""); + const [chatStreaming, setChatStreaming] = React.useState(false); + const [chatAutoScroll, setChatAutoScroll] = React.useState(true); + const chatAbortRef = React.useRef(null); + const chatMessagesEndRef = React.useRef(null); + const llamaContainer = containers.find((c) => c.role === "llama") || 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 => + 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() { if (!presetName.trim()) { showToast("error", "Preset name required"); @@ -1200,12 +1399,16 @@ export default function DashboardPage() { {/* Chat tab */} @@ -1940,7 +2143,63 @@ function ConfigTab({ onChange={(e) => update("repeatPenalty", Number(e.target.value))} /> +
+ + update("nPredict", Number(e.target.value))} + /> +

+ -1 = infinity (model decides). Sets --n-predict on the server. +

+
+ + {/* Reasoning / Jinja — for thinking models (Qwen3, DeepSeek-R1, etc.) */} +
+
+ + +

+ For Qwen3, DeepSeek-R1, gpt-oss. "auto" puts + <think>...</think> blocks into a separate + reasoning_content field shown in chat. +

+
+
+ + update("jinja", v)} + /> +
+
+