The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): DeepSeek R1 and its distills get no system message (C69)
purplefa52dd72727d
diff --git a/src/api/providers/normalize-system.ts b/src/api/providers/normalize-system.tsindex 520d8730..a6ccbd1f 100644--- a/src/api/providers/normalize-system.ts+++ b/src/api/providers/normalize-system.ts@@ -37,6 +37,7 @@*/import { buildHermesToolResult, buildHermesToolCall } from '../hermes-tool-calling'+import { foldSystemForR1 } from '../../lib/r1-system-prompt'/** The shape this works on. Deliberately looser than ChatMessage so the same* function serves the wire types of all providers. */@@ -148,6 +149,12 @@ export interface TemplateContract {toolRole: 'native' | 'text'/** Enforce strict user/assistant alternation behind the system message. */alternate: boolean+ /**+ * The model the request goes to. C69: a DeepSeek R1 style model gets its+ * system message folded into the first user turn (lib/r1-system-prompt.ts).+ * Without it, or for any other model, nothing changes.+ */+ model?: string}/** The minimal turn used when two same-role turns cannot be merged. */@@ -336,7 +343,7 @@ export function userTurnFirst<T extends RoledMessage>(messages: T[]): T[] {/*** The whole contract, in the order the rules depend on each other: system- * first (round 1), then the tool channel, then the merge of same role turns,+ * first (round 1), the R1 fold (C69), then the tool channel, then the merge of same role turns,* then alternation, because turning* a tool result into a user turn is what creates most of the consecutive* user turns alternation then has to merge.@@ -350,6 +357,8 @@ export function applyTemplateContract<T extends ContractMessage>(contract: TemplateContract,): T[] {let out = userTurnFirst(normalizeSystemMessages(messages))+ // C69: before the merge and alternation, which tidy up after it.+ out = foldSystemForR1(contract.model, out)if (contract.toolRole === 'text') out = toolRoleAsText(out)out = mergeSameRoleTurns(out)if (contract.alternate) out = alternateRoles(out)diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 149c2e26..740281e3 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -143,6 +143,7 @@ export class OllamaProvider implements ProviderClient {const ollamaMessages = applyTemplateContract(messages, {toolRole: 'text',alternate: true,+ model,}).map(m => {const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.images?.length) msg.images = m.images.map(img => img.data)@@ -314,6 +315,7 @@ export class OllamaProvider implements ProviderClient {const ollamaMessages = applyTemplateContract(messages, {toolRole: tools.length > 0 ? 'native' : 'text',alternate: tools.length === 0,+ model,}).map(m => {const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.tool_calls) msg.tool_calls = m.tool_callsdiff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex a639a380..f4f6c53d 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -567,11 +567,12 @@ export class OpenAIProvider implements ProviderClient {* this template has no branch for. That is exactly the payload the* counter-check killed the built-in engine with.*/- private templateContract(messages: ChatMessage[], nativeTools: boolean): ChatMessage[] {+ private templateContract(messages: ChatMessage[], nativeTools: boolean, model: string): ChatMessage[] {const rendersTemplate = this.isLanBackend && !nativeToolsreturn applyTemplateContract(messages, {toolRole: rendersTemplate ? 'text' : 'native',alternate: rendersTemplate,+ model,})}@@ -1049,7 +1050,7 @@ export class OpenAIProvider implements ProviderClient {// render the model's own Jinja template, which raises "System message// must be at the beginning" on anything else and kills the whole turn// before a byte streams. See providers/normalize-system.ts.- messages: this.templateContract(messages, (options?.tools?.length ?? 0) > 0).map(m => this.toOpenAIMessage(m)),+ messages: this.templateContract(messages, (options?.tools?.length ?? 0) > 0, model).map(m => this.toOpenAIMessage(m)),stream: true,}@@ -1303,7 +1304,7 @@ export class OpenAIProvider implements ProviderClient {const body: OpenAIChatRequest = {model,// Bug B3: same invariant as chatStream, see providers/normalize-system.ts.- messages: this.templateContract(messages, tools.length > 0).map(m => this.toOpenAIMessage(m)),+ messages: this.templateContract(messages, tools.length > 0, model).map(m => this.toOpenAIMessage(m)),stream: false,}diff --git a/src/lib/__tests__/r1-system-prompt.test.ts b/src/lib/__tests__/r1-system-prompt.test.tsnew file mode 100644index 00000000..856ed2c1--- /dev/null+++ b/src/lib/__tests__/r1-system-prompt.test.ts@@ -0,0 +1,225 @@+/**+ * C69 (3.1.0): DeepSeek R1 and its distills get no system message.+ *+ * Discord: deepseek-r1:14b on Ollama answered "hi" with pages of thinking+ * about LU's system prompt. DeepSeek's model card: no system prompt, all+ * instructions in the user prompt. See lib/r1-system-prompt.ts.+ *+ * Run: npx vitest run src/lib/__tests__/r1-system-prompt.test.ts+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { isR1StyleModel, foldSystemForR1, withoutLuLines } from '../r1-system-prompt'+import { applyTemplateContract } from '../../api/providers/normalize-system'+import { buildChatSystemPrompt, withHouseConduct, CHAT_BASE_SYSTEM_PROMPT, HOUSE_RULES } from '../system-prompt'+import type { ChatMessage, ProviderConfig } from '../../api/providers/types'+import type { OpenAIChatRequest } from '../../api/providers/openai-provider'+import type { OllamaChatRequest } from '../../api/providers/ollama-provider'++describe('which models count as R1', () => {+ it.each([+ 'deepseek-r1:14b',+ 'deepseek-r1:8b',+ 'deepseek-r1',+ 'deepseek-r1:671b',+ 'huihui_ai/deepseek-r1-abliterated:8b',+ 'hf.co/bartowski/DeepSeek-R1-Distill-Qwen-14B-GGUF:Q4_K_M',+ 'hf.co/unsloth/DeepSeek-R1-0528-Qwen3-8B-GGUF:Q4_K_M',+ // LU Engine: the GGUF file name, with or without the extension.+ 'DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf',+ 'DeepSeek-R1-Distill-Qwen-7B-Q4_K_M',+ 'deepseek_r1_distill_qwen_1.5b',+ 'R1-Distill-Qwen-7B-abliterated.Q4_K_M.gguf',+ // Cloud catalogues.+ 'deepseek/deepseek-r1-0528',+ 'deepseek/deepseek-r1-distill-llama-70b',+ 'deepseek-ai/DeepSeek-R1',+ 'perplexity/r1-1776',+ ])('%s is R1', (name) => {+ expect(isR1StyleModel(name)).toBe(true)+ })++ it.each([+ 'deepseek-v3', 'deepseek-chat', 'deepseek-reasoner', 'deepseek-coder-v2:16b',+ 'deepseek-v2.5', 'qwen3:8b', 'gemma3:4b', 'command-r:35b', 'command-r7b',+ 'llama3.1:8b', 'deepseek-r10', 'mistral-small', '', undefined, null,+ ])('%s is not', (name) => {+ expect(isR1StyleModel(name as string)).toBe(false)+ })+})++describe('the fold', () => {+ const chat = (system: string): ChatMessage[] => [+ { role: 'system', content: system },+ { role: 'user', content: 'hi' },+ ]++ it('the plain LU prompt is left out entirely: "hi" goes out as "hi"', () => {+ const out = foldSystemForR1('deepseek-r1:14b', chat(buildChatSystemPrompt({})))+ expect(out).toEqual([{ role: 'user', content: 'hi' }])+ })++ it('a persona is kept, fenced, in front of the first user message, without the house lines', () => {+ const persona = 'You are Captain Mira, a gruff starship pilot. Stay in character.'+ const system = buildChatSystemPrompt({ systemPrompt: persona, personaEnabled: true })+ expect(system).toContain(HOUSE_RULES)+ const out = foldSystemForR1('deepseek-r1:14b', chat(system))+ expect(out).toHaveLength(1)+ expect(out[0].role).toBe('user')+ expect(out[0].content).toBe(`<instructions>\n${persona}\n</instructions>\n\nhi`)+ })++ it('an agent role and its tool catalogue survive the fold', () => {+ const agent = withHouseConduct('You are a coding agent.\n\n<tools>\n[{"name":"file_read"}]\n</tools>')+ const out = foldSystemForR1('deepseek-r1:8b', chat(agent))+ expect(out[0].content).toContain('You are a coding agent.')+ expect(out[0].content).toContain('"name":"file_read"')+ expect(out[0].content).not.toContain(HOUSE_RULES)+ })++ it('it lands in the FIRST user turn of a longer chat, the rest stays by reference', () => {+ const msgs: ChatMessage[] = [+ { role: 'system', content: 'Persona P.' },+ { role: 'user', content: 'one' },+ { role: 'assistant', content: 'a' },+ { role: 'user', content: 'two' },+ ]+ const out = foldSystemForR1('deepseek-r1:14b', msgs)+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'user'])+ expect(out[0].content).toBe('<instructions>\nPersona P.\n</instructions>\n\none')+ expect(out[1]).toBe(msgs[2])+ expect(out[2]).toBe(msgs[3])+ })++ it('images on the first user turn ride along', () => {+ const msgs: ChatMessage[] = [+ { role: 'system', content: 'Persona P.' },+ { role: 'user', content: 'what is this', images: [{ data: 'AAA', mimeType: 'image/png' }] },+ ]+ const out = foldSystemForR1('deepseek-r1:14b', msgs)+ expect(out[0].images).toEqual([{ data: 'AAA', mimeType: 'image/png' }])+ })++ it('a system message with no user turn becomes the user turn', () => {+ const out = foldSystemForR1('deepseek-r1:14b', [{ role: 'system', content: 'Summarise X.' }])+ expect(out).toEqual([{ role: 'user', content: '<instructions>\nSummarise X.\n</instructions>' }])+ })++ it('withoutLuLines strips only LU lines', () => {+ expect(withoutLuLines(CHAT_BASE_SYSTEM_PROMPT)).toBe('')+ expect(withoutLuLines(`Mine.\n\n${HOUSE_RULES}`)).toBe('Mine.')+ expect(withoutLuLines('Mine only.')).toBe('Mine only.')+ })++ it('NEGATIVE CONTROL: every other model gets the same array back, by reference', () => {+ const msgs = chat(buildChatSystemPrompt({}))+ for (const m of ['qwen3:8b', 'deepseek-v3', 'gemma3:4b', 'Llama-3.1-8B-Q4_K_M.gguf']) {+ expect(foldSystemForR1(m, msgs)).toBe(msgs)+ expect(applyTemplateContract(msgs, { toolRole: 'text', alternate: true, model: m })).toBe(msgs)+ }+ expect(applyTemplateContract(msgs, { toolRole: 'text', alternate: true })).toBe(msgs)+ })++ it('through the whole contract, a greeting-first character chat still alternates', () => {+ // A character card opens with an assistant greeting. userTurnFirst puts a+ // bridge user line in front; the persona folds into that one.+ const msgs: ChatMessage[] = [+ { role: 'system', content: buildChatSystemPrompt({ systemPrompt: 'Card text.', personaEnabled: true }) },+ { role: 'assistant', content: 'Greetings, traveller.' },+ { role: 'user', content: 'hi' },+ ]+ const out = applyTemplateContract(msgs, { toolRole: 'text', alternate: true, model: 'deepseek-r1:14b' })+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'user'])+ expect(out[0].content).toContain('Card text.')+ expect(out.some((m) => m.role === 'system')).toBe(false)+ })+})++// ── On the wire ────────────────────────────────────────────────++type CapturedInit = { body?: string }++const backendMock = (capture: (url: string, init: CapturedInit) => Response) => ({+ isTauri: () => false,+ localFetch: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),+ localFetchStream: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,+ backendCall: vi.fn(),+ isPrivateOrLanHost: () => true,+ isDirectFetchAllowed: () => false,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+})++afterEach(() => {+ vi.doUnmock('../../api/backend')+ vi.doUnmock('../../api/builtin-ensure')+ vi.resetModules()+})++const HI: ChatMessage[] = [+ { role: 'system', content: CHAT_BASE_SYSTEM_PROMPT },+ { role: 'user', content: 'hi' },+]++async function viaOllama(model: string): Promise<OllamaChatRequest> {+ vi.resetModules()+ const captures: OllamaChatRequest[] = []+ vi.doMock('../../api/backend', () =>+ backendMock((url, init) => {+ if (url.endsWith('/chat')) captures.push(JSON.parse(init.body ?? '{}'))+ return new Response('{"message":{"content":"ok"},"done":true}\n')+ }),+ )+ const { OllamaProvider } = await import('../../api/providers/ollama-provider')+ const p = new OllamaProvider({ id: 'ollama', name: 'Ollama', enabled: true, baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true })+ for await (const chunk of p.chatStream(model, HI)) { void chunk }+ expect(captures).toHaveLength(1)+ return captures[0]+}++async function viaEngine(model: string): Promise<OpenAIChatRequest> {+ vi.resetModules()+ let sent: OpenAIChatRequest | null = null+ vi.doMock('../../api/backend', () =>+ backendMock((url, init) => {+ if (url.includes('/chat/completions')) {+ sent = JSON.parse(init.body ?? '{}')+ return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { headers: { 'Content-Type': 'application/json' } })+ }+ return new Response('{}', { status: 404 })+ }),+ )+ vi.doMock('../../api/builtin-ensure', () => ({+ ensureBuiltinEngineAlive: vi.fn(),+ explainDeadEngine: (e: unknown) => e,+ isManagedBuiltinSlot: () => true,+ }))+ const { OpenAIProvider } = await import('../../api/providers/openai-provider')+ const cfg: ProviderConfig = { id: 'openai', name: 'LU Engine', enabled: true, apiKey: '', baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true }+ await new OpenAIProvider(cfg).chatWithTools(model, HI, [])+ if (!sent) throw new Error('no /chat/completions request was captured')+ return sent+}++describe('the request that leaves', () => {+ it('Ollama deepseek-r1:14b: no system message, "hi" is "hi"', async () => {+ const body = await viaOllama('deepseek-r1:14b')+ expect(body.messages).toEqual([{ role: 'user', content: 'hi' }])+ })++ it('NEGATIVE CONTROL: Ollama qwen3:8b keeps its system message', async () => {+ const body = await viaOllama('qwen3:8b')+ expect(body.messages[0]).toEqual({ role: 'system', content: CHAT_BASE_SYSTEM_PROMPT })+ })++ it('LU Engine with an R1 distill GGUF: no system message', async () => {+ const sent = await viaEngine('DeepSeek-R1-Distill-Qwen-14B-Q4_K_M')+ expect(sent.messages.some((m) => m.role === 'system')).toBe(false)+ expect(sent.messages[0]).toMatchObject({ role: 'user', content: 'hi' })+ })++ it('NEGATIVE CONTROL: LU Engine with another GGUF keeps it', async () => {+ const sent = await viaEngine('Qwen3-8B-Q4_K_M')+ expect(sent.messages[0]).toMatchObject({ role: 'system', content: CHAT_BASE_SYSTEM_PROMPT })+ })+})diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.tsindex c516c7e4..c941e6aa 100644--- a/src/lib/ollama-stream-tools.ts+++ b/src/lib/ollama-stream-tools.ts@@ -71,6 +71,7 @@ export async function streamOllamaChatWithTools(const ollamaMessages = applyTemplateContract(messages, {toolRole: 'native',alternate: false,+ model: modelId,}).map((m): OllamaRequestMessage => {const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.tool_calls) msg.tool_calls = m.tool_callsdiff --git a/src/lib/r1-system-prompt.ts b/src/lib/r1-system-prompt.tsnew file mode 100644index 00000000..4fa1983f--- /dev/null+++ b/src/lib/r1-system-prompt.ts@@ -0,0 +1,92 @@+/**+ * C69 (3.1.0): DeepSeek R1 and its distills get no system message.+ *+ * Discord, deepseek-r1:14b on Ollama: a plain "hi" got pages of thinking+ * ABOUT LU's system prompt ("so I want to figure out how to solve this+ * problem where a model is supposed to be running solely for the user…")+ * and no answer. R1 was trained without system prompts, and DeepSeek's own+ * model card says to leave the system prompt out and put every instruction+ * into the user prompt. The distills (R1-Distill-Qwen, R1-Distill-Llama, the+ * Ollama `deepseek-r1:*` tags) inherit that.+ *+ * So, for these models only, on the wire only:+ * * LU's own lines (the chat base role and the house rules from+ * lib/system-prompt.ts) are left out. They are what the model chewed on,+ * and they are not the user's words.+ * * Whatever else the system message carried (a persona, an agent role, a+ * tool catalog, memory, a character card) is folded into the FIRST user+ * message, fenced off so the model reads it as setup and not as the+ * question. The first and not the latest user turn: that is where+ * DeepSeek puts it, and it keeps the prefix of a long chat stable.+ * * The store keeps the transcript as written; nothing on screen changes.+ *+ * Every other model gets the very same array back (by reference), so their+ * requests stay byte for byte what they were.+ */++import { CHAT_BASE_ROLE, CHAT_BASE_SYSTEM_PROMPT, HOUSE_CONDUCT, HOUSE_RULES, HOUSE_SCOPE } from './system-prompt'++/**+ * R1 itself and the models built from it, under the names Ollama, Hugging+ * Face, a GGUF file in the LU Engine and the cloud catalogues give them:+ *+ * deepseek-r1:14b · huihui_ai/deepseek-r1-abliterated:8b+ * hf.co/bartowski/DeepSeek-R1-Distill-Qwen-14B-GGUF:Q4_K_M+ * DeepSeek-R1-Distill-Llama-8B-Q4_K_M(.gguf) · deepseek/deepseek-r1-0528+ * deepseek-r1-distill-llama-70b · R1-Distill-Qwen-7B · r1-1776+ *+ * Not DeepSeek V3, Coder, V2.5 or the `deepseek-chat` API, and not a name+ * that only happens to hold the letters "r1" (command-r, r10, …).+ */+export function isR1StyleModel(model: string | null | undefined): boolean {+ if (!model) return false+ const n = model.toLowerCase().replace(/[\s_.]+/g, '-')+ return /deepseek-?r1(?![0-9a-z])/.test(n)+ || /(^|[^a-z0-9])r1-distill(?![a-z])/.test(n)+ || /(^|[^a-z0-9])r1-1776(?![0-9])/.test(n)+}++/** LU's own lines, longest first so a whole block goes before its parts. */+const LU_LINES = [CHAT_BASE_SYSTEM_PROMPT, HOUSE_RULES, HOUSE_CONDUCT, HOUSE_SCOPE, CHAT_BASE_ROLE]++/** The system text without LU's own lines. Empty when that was all of it. */+export function withoutLuLines(system: string): string {+ let out = system+ for (const line of LU_LINES) out = out.split(line).join('')+ return out.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim()+}++const OPEN = '<instructions>'+const CLOSE = '</instructions>'++interface Roled {+ role: string+ content?: unknown+}++/**+ * Move the leading system message of `messages` into the first user turn,+ * for an R1 style `model`. Expects the contract's shape: at most one system+ * message, at index 0 (normalize-system.ts runs first).+ */+export function foldSystemForR1<T extends Roled>(model: string | null | undefined, messages: T[]): T[] {+ if (!isR1StyleModel(model) || messages[0]?.role !== 'system') return messages+ const system = typeof messages[0].content === 'string' ? messages[0].content : ''+ const rest = messages.slice(1)+ const kept = withoutLuLines(system)+ if (!kept) return rest++ const block = `${OPEN}\n${kept}\n${CLOSE}`+ const first = rest.findIndex((m) => m?.role === 'user')+ if (first < 0) return [{ role: 'user', content: block } as unknown as T, ...rest]+ const target = rest[first]+ const text = typeof target.content === 'string' ? target.content : null+ if (text === null) {+ // Not plain text (never the case on today's wire): the setup goes in a+ // turn of its own in front, which merging cannot reach.+ return [...rest.slice(0, first), { role: 'user', content: block } as unknown as T, ...rest.slice(first)]+ }+ const out = rest.slice()+ out[first] = { ...target, content: text ? `${block}\n\n${text}` : block }+ return out+}