Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(llamacpp): per-model chat template kwargs (#8441)

Akarshan Biswas84a98bf4a6ca
diff --git a/core/src/browser/extensions/engines/AIEngine.ts b/core/src/browser/extensions/engines/AIEngine.ts
index dd2735d7c..d47d6de58 100644
--- a/core/src/browser/extensions/engines/AIEngine.ts
+++ b/core/src/browser/extensions/engines/AIEngine.ts
@@ -175,9 +175,20 @@ export interface modelInfo {
// True if the model was imported from a user-supplied local file
// (path lives outside the provider's managed models directory).
imported?: boolean
+ // Chat-template kwargs the model's embedded jinja template accepts
+ // (e.g. `preserve_thinking`), detected from the GGUF at import/list time.
+ template_kwargs?: TemplateKwarg[]
[key: string]: any
}
+export type TemplateKwargType = 'boolean' | 'number' | 'string'
+
+export interface TemplateKwarg {
+ name: string
+ type: TemplateKwargType
+ default: boolean | number | string
+}
+
// 1. /list
export type listResult = modelInfo[]
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index cc43082d6..260e0228f 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -259,15 +259,6 @@
"value": false
}
},
- {
- "key": "strip_reasoning_from_context",
- "title": "Strip reasoning from context",
- "description": "Remove prior turns' thinking/reasoning content before resending history. Improves KV-cache reuse across turns, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning.",
- "controllerType": "checkbox",
- "controllerProps": {
- "value": false
- }
- },
{
"key": "cache_type_k",
"title": "KV Cache K Type",
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 731fd7040..f5101baca 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -50,6 +50,7 @@ import {
mergeEmbedResponses,
detectEmbeddingFromGgufMeta,
detectMtpLayersFromGgufMeta,
+ detectTemplateKwargsFromChatTemplate,
getDefaultEmbeddingModelId,
setDefaultEmbeddingModelId,
type EmbedBatchResult,
@@ -70,6 +71,7 @@ import {
LlamacppConfig,
DownloadItem,
ModelConfig,
+ TemplateKwarg,
EmbeddingResponse,
ModelProps,
DeviceList,
@@ -85,6 +87,7 @@ import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
const EMBEDDING_CHECK_VERSION = 3
const MTP_CHECK_VERSION = 1
+const TEMPLATE_KWARGS_CHECK_VERSION = 1
// Upstream build that added the `GET /models?reload=1` diff/reconcile path
// (llama.cpp #21848). At/above this, a preset change can be hot-applied without
@@ -1867,6 +1870,10 @@ export default class llamacpp_extension extends AIEngine {
const isEmbedding = await this.resolveEmbeddingConfig(modelId, modelConfig)
await this.resolveMtpLayersConfig(modelId, modelConfig)
+ const templateKwargs = await this.resolveTemplateKwargsConfig(
+ modelId,
+ modelConfig
+ )
return {
id: modelId,
@@ -1876,6 +1883,7 @@ export default class llamacpp_extension extends AIEngine {
port: 0, // port is not known until the model is loaded
sizeBytes: modelConfig.size_bytes ?? 0,
embedding: isEmbedding,
+ template_kwargs: templateKwargs,
} as modelInfo
}
@@ -1999,6 +2007,64 @@ export default class llamacpp_extension extends AIEngine {
return mtpLayers
}
+ /**
+ * Detect which chat-template kwargs (e.g. `preserve_thinking`) a model's
+ * embedded jinja template accepts, caching the result in model.yml. Migrates
+ * pre-existing models lazily the first time list() sees a stale check version.
+ */
+ private async resolveTemplateKwargsConfig(
+ modelId: string,
+ modelConfig: ModelConfig
+ ): Promise<TemplateKwarg[]> {
+ const cfg = modelConfig as ModelConfig & {
+ template_kwargs?: TemplateKwarg[]
+ template_kwargs_check_v?: number
+ }
+ if (
+ Array.isArray(cfg.template_kwargs) &&
+ cfg.template_kwargs_check_v === TEMPLATE_KWARGS_CHECK_VERSION
+ ) {
+ return cfg.template_kwargs
+ }
+
+ let kwargs: TemplateKwarg[] = []
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullModelPath = await joinPath([
+ janDataFolderPath,
+ modelConfig.model_path,
+ ])
+ if (await fs.existsSync(fullModelPath)) {
+ const metadata = await readGgufMetadata(fullModelPath)
+ kwargs = detectTemplateKwargsFromChatTemplate(
+ metadata.metadata?.['tokenizer.chat_template']
+ )
+ }
+ } catch (e) {
+ logger.warn(`Failed to check template kwargs for ${modelId}`, e)
+ return cfg.template_kwargs ?? []
+ }
+
+ try {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ cfg.template_kwargs = kwargs
+ cfg.template_kwargs_check_v = TEMPLATE_KWARGS_CHECK_VERSION
+ await invoke<void>('write_yaml', {
+ data: cfg,
+ savePath: configPath,
+ })
+ } catch (e) {
+ logger.warn(`Failed to persist template kwargs for ${modelId}`, e)
+ }
+
+ return kwargs
+ }
+
// Implement the required LocalProvider interface methods
override async list(): Promise<modelInfo[]> {
const modelsDir = await joinPath([await this.getProviderPath(), 'models'])
@@ -2062,6 +2128,10 @@ export default class llamacpp_extension extends AIEngine {
modelId,
modelConfig
)
+ const templateKwargs = await this.resolveTemplateKwargsConfig(
+ modelId,
+ modelConfig
+ )
const capabilities: string[] = []
if (modelConfig.mmproj_path) {
@@ -2089,6 +2159,7 @@ export default class llamacpp_extension extends AIEngine {
embedding: isEmbedding,
imported: isAbsolute,
capabilities: capabilities.length > 0 ? capabilities : undefined,
+ template_kwargs: templateKwargs,
} as modelInfo
modelInfos.push(modelInfo)
} catch (err) {
@@ -2577,6 +2648,7 @@ export default class llamacpp_extension extends AIEngine {
const fullModelPath = await joinPath([janDataFolderPath, modelPath])
let isEmbedding = false
let mtpLayers = 0
+ let templateKwargs: TemplateKwarg[] = []
let resolvedName: string | undefined
try {
@@ -2590,6 +2662,9 @@ export default class llamacpp_extension extends AIEngine {
isEmbedding = true
}
mtpLayers = detectMtpLayersFromGgufMeta(modelMetadata.metadata)
+ templateKwargs = detectTemplateKwargsFromChatTemplate(
+ modelMetadata.metadata?.['tokenizer.chat_template']
+ )
const rawName = modelMetadata.metadata?.['general.name']
if (typeof rawName === 'string') {
@@ -2655,6 +2730,8 @@ export default class llamacpp_extension extends AIEngine {
embedding_check_v: EMBEDDING_CHECK_VERSION,
mtp_layers: mtpLayers,
mtp_check_v: MTP_CHECK_VERSION,
+ template_kwargs: templateKwargs,
+ template_kwargs_check_v: TEMPLATE_KWARGS_CHECK_VERSION,
// A separate draft gguf is downloaded only to be used — enable MTP by
// default. Embedded-MTP models keep MTP opt-in (no flag written here).
...(mtpModelPath ? { mtp_model_path: mtpModelPath, mtp: true } : {}),
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index 8615399b7..ca55f6be0 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -144,6 +144,7 @@ describe('llamacpp_extension', () => {
embedding: false,
imported: false,
capabilities: undefined,
+ template_kwargs: [],
}
])
})
diff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.ts
index ce043f31d..4f79a94e2 100644
--- a/extensions/llamacpp-extension/src/util.test.ts
+++ b/extensions/llamacpp-extension/src/util.test.ts
@@ -3,6 +3,7 @@ import { logger } from '@janhq/core'
import {
buildEmbedBatches,
detectMtpLayersFromGgufMeta,
+ detectTemplateKwargsFromChatTemplate,
estimateTokensFromText,
getProxyConfig,
truncateToTokenBudget,
@@ -626,3 +627,49 @@ describe('detectMtpLayersFromGgufMeta', () => {
).toBe(2)
})
})
+
+describe('detectTemplateKwargsFromChatTemplate', () => {
+ it('returns [] for missing or empty templates', () => {
+ expect(detectTemplateKwargsFromChatTemplate(undefined)).toEqual([])
+ expect(detectTemplateKwargsFromChatTemplate('')).toEqual([])
+ expect(detectTemplateKwargsFromChatTemplate(123)).toEqual([])
+ })
+
+ it('detects the self-defaulting set idiom and infers types', () => {
+ const tpl = [
+ "{%- set enable_thinking = enable_thinking | default(false) -%}",
+ "{%- set preserve_thinking = preserve_thinking | default(false) -%}",
+ "{%- set reasoning_effort = reasoning_effort | default('medium') -%}",
+ "{%- set max_turns = max_turns | default(8) -%}",
+ ].join('\n')
+ expect(detectTemplateKwargsFromChatTemplate(tpl)).toEqual([
+ { name: 'preserve_thinking', type: 'boolean', default: false },
+ { name: 'reasoning_effort', type: 'string', default: 'medium' },
+ { name: 'max_turns', type: 'number', default: 8 },
+ ])
+ })
+
+ it('excludes enable_thinking (owned by the reasoning control)', () => {
+ const tpl = '{%- set enable_thinking = enable_thinking | default(true) -%}'
+ expect(detectTemplateKwargsFromChatTemplate(tpl)).toEqual([])
+ })
+
+ it('deduplicates repeated kwargs and ignores non-self-defaulting sets', () => {
+ const tpl = [
+ '{%- set preserve_thinking = preserve_thinking | default(false) -%}',
+ '{%- set preserve_thinking = preserve_thinking | default(false) -%}',
+ '{%- set ns = namespace(x=1) -%}',
+ '{%- set role = message.role -%}',
+ ].join('\n')
+ expect(detectTemplateKwargsFromChatTemplate(tpl)).toEqual([
+ { name: 'preserve_thinking', type: 'boolean', default: false },
+ ])
+ })
+
+ it('handles the {% %} form without the dash', () => {
+ const tpl = '{% set add_notes = add_notes | default(true) %}'
+ expect(detectTemplateKwargsFromChatTemplate(tpl)).toEqual([
+ { name: 'add_notes', type: 'boolean', default: true },
+ ])
+ })
+})
diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.ts
index 007352f46..684ed1ec3 100644
--- a/extensions/llamacpp-extension/src/util.ts
+++ b/extensions/llamacpp-extension/src/util.ts
@@ -1,4 +1,8 @@
import { logger } from '@janhq/core'
+import type {
+ TemplateKwarg,
+ TemplateKwargType,
+} from '@janhq/tauri-plugin-llamacpp-api'
import { getBackendSetting, setBackendSetting } from './backend-settings'
// File path utilities
@@ -228,6 +232,52 @@ export function detectMtpLayersFromGgufMeta(
return 0
}
+const TEMPLATE_KWARG_RE =
+ /\{%-?\s*set\s+([A-Za-z_]\w*)\s*=\s*\1\s*\|\s*default\(\s*([^)]*?)\s*\)/g
+
+function parseJinjaDefault(raw: string): {
+ type: TemplateKwargType
+ value: boolean | number | string
+} {
+ const trimmed = raw.trim()
+ if (trimmed === 'true' || trimmed === 'false') {
+ return { type: 'boolean', value: trimmed === 'true' }
+ }
+ const quoted = trimmed.match(/^(['"])(.*)\1$/)
+ if (quoted) {
+ return { type: 'string', value: quoted[2] }
+ }
+ const n = Number(trimmed)
+ if (trimmed.length > 0 && Number.isFinite(n)) {
+ return { type: 'number', value: n }
+ }
+ return { type: 'string', value: trimmed }
+}
+
+/**
+ * Extract chat-template kwargs a GGUF's embedded jinja template accepts. Matches
+ * the self-defaulting idiom `{%- set X = X | default(<v>) -%}`, from which the
+ * kwarg's control type is inferred. `enable_thinking` is owned by the reasoning
+ * control and is intentionally excluded from the generic list.
+ */
+export function detectTemplateKwargsFromChatTemplate(
+ template: unknown
+): TemplateKwarg[] {
+ if (typeof template !== 'string' || template.length === 0) return []
+ const seen = new Set<string>()
+ const out: TemplateKwarg[] = []
+ const re = new RegExp(TEMPLATE_KWARG_RE.source, 'g')
+ let m: RegExpExecArray | null
+ while ((m = re.exec(template)) !== null) {
+ const name = m[1]
+ if (name === 'enable_thinking' || seen.has(name)) continue
+ seen.add(name)
+ const { type, value } = parseJinjaDefault(m[2])
+ out.push({ name, type, default: value })
+ }
+ return out
+}
+
export function estimateTokensFromText(text: string, charsPerToken = DEFAULT_CHARS_PER_TOKEN): number {
return Math.max(1, Math.ceil(text.length / Math.max(charsPerToken, 1)))
}
diff --git a/extensions/mlx-extension/settings.json b/extensions/mlx-extension/settings.json
index 6b9c5d05b..b330668a3 100644
--- a/extensions/mlx-extension/settings.json
+++ b/extensions/mlx-extension/settings.json
@@ -5,12 +5,5 @@
"description": "Automatically unload other models when loading a new one",
"controllerType": "checkbox",
"controllerProps": { "value": true }
- },
- {
- "key": "strip_reasoning_from_context",
- "title": "Strip reasoning from context",
- "description": "Remove prior turns' thinking/reasoning content before resending history. Improves KV-cache reuse across turns, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning.",
- "controllerType": "checkbox",
- "controllerProps": { "value": true }
}
]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index 3143dacfb..f41d128af 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -111,6 +111,16 @@ export interface ModelConfig {
mmproj_sha256?: string
mmproj_size_bytes?: number
embedding?: boolean
+ template_kwargs?: TemplateKwarg[]
+ template_kwargs_check_v?: number
+}
+
+export type TemplateKwargType = 'boolean' | 'number' | 'string'
+
+export interface TemplateKwarg {
+ name: string
+ type: TemplateKwargType
+ default: boolean | number | string
}
export interface EmbeddingResponse {
diff --git a/web-app/src/containers/ChatTemplateKwargs.tsx b/web-app/src/containers/ChatTemplateKwargs.tsx
new file mode 100644
index 000000000..a5e31680e
--- /dev/null
+++ b/web-app/src/containers/ChatTemplateKwargs.tsx
@@ -0,0 +1,180 @@
+import { useState } from 'react'
+import { IconPlus, IconTrash } from '@tabler/icons-react'
+
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Switch } from '@/components/ui/switch'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+type KwargValue = boolean | number | string
+type KwargBag = Record<string, KwargValue>
+
+function coerceRawValue(raw: string): KwargValue {
+ const trimmed = raw.trim()
+ if (trimmed === 'true' || trimmed === 'false') return trimmed === 'true'
+ const n = Number(trimmed)
+ if (trimmed.length > 0 && Number.isFinite(n)) return n
+ return raw
+}
+
+function readBag(model: Model): KwargBag {
+ const raw: unknown =
+ model.settings?.chat_template_kwargs?.controller_props?.value
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
+ return { ...(raw as KwargBag) }
+}
+
+export function ChatTemplateKwargs({
+ model,
+ onChange,
+}: {
+ model: Model
+ onChange: (value: KwargBag) => void
+}) {
+ const { t } = useTranslation()
+ const detected = model.template_kwargs ?? []
+ const [adding, setAdding] = useState(false)
+ const [newKey, setNewKey] = useState('')
+ const [newValue, setNewValue] = useState('')
+
+ if (detected.length === 0) return null
+
+ const bag = readBag(model)
+ const detectedNames = new Set(detected.map((k) => k.name))
+ const customEntries = Object.entries(bag).filter(([k]) => !detectedNames.has(k))
+
+ const setValue = (name: string, value: KwargValue) => {
+ onChange({ ...bag, [name]: value })
+ }
+ const removeValue = (name: string) => {
+ const next = { ...bag }
+ delete next[name]
+ onChange(next)
+ }
+ const addCustom = () => {
+ const key = newKey.trim()
+ if (!key || key in bag || detectedNames.has(key)) return
+ onChange({ ...bag, [key]: coerceRawValue(newValue) })
+ setNewKey('')
+ setNewValue('')
+ setAdding(false)
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1">
+ <div className="font-medium">
+ {t('common:modelSettings.templateKwargs.section')}
+ </div>
+ <p className="text-muted-foreground leading-normal text-xs">
+ {t('common:modelSettings.templateKwargs.description')}
+ </p>
+ </div>
+
+ {detected.map((kwarg) => {
+ const current = bag[kwarg.name] ?? kwarg.default
+ return (
+ <div
+ key={kwarg.name}
+ className="flex items-center justify-between gap-8"
+ >
+ <span className="font-medium truncate" title={kwarg.name}>
+ {kwarg.name}
+ </span>
+ {kwarg.type === 'boolean' ? (
+ <Switch
+ checked={current === true}
+ onCheckedChange={(v) => setValue(kwarg.name, v)}
+ />
+ ) : (
+ <Input
+ type={kwarg.type === 'number' ? 'number' : 'text'}
+ className="w-40"
+ value={String(current)}
+ onChange={(e) =>
+ setValue(
+ kwarg.name,
+ kwarg.type === 'number'
+ ? Number(e.target.value)
+ : e.target.value
+ )
+ }
+ />
+ )}
+ </div>
+ )
+ })}
+
+ {customEntries.map(([key, value]) => (
+ <div key={key} className="flex items-center gap-2">
+ <span className="font-medium truncate flex-1" title={key}>
+ {key}
+ </span>
+ <Input
+ className="w-40"
+ value={String(value)}
+ onChange={(e) => setValue(key, coerceRawValue(e.target.value))}
+ />
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => removeValue(key)}
+ title={t('common:modelSettings.templateKwargs.remove')}
+ >
+ <IconTrash size={16} className="text-muted-foreground" />
+ </Button>
+ </div>
+ ))}
+
+ {adding ? (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Input
+ className="flex-1"
+ placeholder={t(
+ 'common:modelSettings.templateKwargs.keyPlaceholder'
+ )}
+ value={newKey}
+ onChange={(e) => setNewKey(e.target.value)}
+ />
+ <Input
+ className="flex-1"
+ placeholder={t(
+ 'common:modelSettings.templateKwargs.valuePlaceholder'
+ )}
+ value={newValue}
+ onChange={(e) => setNewValue(e.target.value)}
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <Button variant="link" size="sm" onClick={addCustom}>
+ {t('common:modelSettings.templateKwargs.add')}
+ </Button>
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={() => {
+ setAdding(false)
+ setNewKey('')
+ setNewValue('')
+ }}
+ >
+ {t('common:modelSettings.templateKwargs.cancel')}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <Button
+ variant="link"
+ size="sm"
+ className="px-0"
+ onClick={() => setAdding(true)}
+ >
+ <IconPlus size={14} className="mr-1" />
+ {t('common:modelSettings.templateKwargs.addCustom')}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index 63f418761..6a7f30290 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -15,6 +15,7 @@ import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'
import { SamplerDefaults } from '@/containers/SamplerDefaults'
+import { ChatTemplateKwargs } from '@/containers/ChatTemplateKwargs'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useServiceHub } from '@/hooks/useServiceHub'
import { cn, getModelDisplayName } from '@/lib/utils'
@@ -202,6 +203,37 @@ export function ModelSetting({
}
}
+ // Chat-template kwargs are a per-request concern (sent as chat_template_kwargs),
+ // not a router preset arg — persist to the store only, like `reasoning`.
+ const handleTemplateKwargsChange = (
+ value: Record<string, boolean | number | string>
+ ) => {
+ if (!provider) return
+ const modelIndex = provider.models.findIndex((m) => m.id === model.id)
+ if (modelIndex === -1) return
+ const existing = model.settings?.chat_template_kwargs
+ const updatedModel = {
+ ...model,
+ settings: {
+ ...model.settings,
+ chat_template_kwargs: {
+ key: 'chat_template_kwargs',
+ title: 'Chat template options',
+ description: '',
+ controller_type: 'object',
+ ...(existing ?? {}),
+ controller_props: {
+ ...(existing?.controller_props ?? {}),
+ value,
+ },
+ },
+ },
+ } as unknown as Model
+ const updatedModels = [...provider.models]
+ updatedModels[modelIndex] = updatedModel
+ updateProvider(provider.provider, { models: updatedModels })
+ }
+
const handleEngineSettingChange = (
key: string,
value: string | boolean | number
@@ -247,6 +279,12 @@ export function ModelSetting({
{provider.provider === 'llamacpp' && (
<MtpPanel modelId={model.id} provider={provider} />
)}
+ {provider.provider === 'llamacpp' && model.embedding !== true && (
+ <ChatTemplateKwargs
+ model={model}
+ onChange={handleTemplateKwargsChange}
+ />
+ )}
{(provider.provider === 'llamacpp' || provider.provider === 'mlx') &&
model.embedding !== true && (
<SamplerDefaults
@@ -283,6 +321,8 @@ export function ModelSetting({
return Object.entries(model.settings || {})
.reduce<[string, unknown][]>((acc, entry) => {
if (entry[0] === 'reasoning') return acc
+ // Rendered by the dedicated ChatTemplateKwargs section above.
+ if (entry[0] === 'chat_template_kwargs') return acc
// Removed in v15 migration; defend against any pre-migration
// localStorage state that still carries the orphan entry.
if (entry[0] === 'auto_increase_ctx_len') return acc
diff --git a/web-app/src/hooks/useGeneralSetting.ts b/web-app/src/hooks/useGeneralSetting.ts
index 322a0a013..e5cf3456f 100644
--- a/web-app/src/hooks/useGeneralSetting.ts
+++ b/web-app/src/hooks/useGeneralSetting.ts
@@ -11,11 +11,13 @@ type GeneralSettingState = {
spellCheckChatInput: boolean
tokenCounterCompact: boolean
autoUpdateCheck: boolean
+ stripReasoningFromContext: boolean
huggingfaceToken?: string
setHuggingfaceToken: (token: string) => void
setSpellCheckChatInput: (value: boolean) => void
setTokenCounterCompact: (value: boolean) => void
setAutoUpdateCheck: (value: boolean) => void
+ setStripReasoningFromContext: (value: boolean) => void
setCurrentLanguage: (value: Language) => void
}
@@ -26,10 +28,13 @@ export const useGeneralSetting = create<GeneralSettingState>()(
spellCheckChatInput: true,
tokenCounterCompact: true,
autoUpdateCheck: true,
+ stripReasoningFromContext: false,
huggingfaceToken: undefined,
setSpellCheckChatInput: (value) => set({ spellCheckChatInput: value }),
setTokenCounterCompact: (value) => set({ tokenCounterCompact: value }),
setAutoUpdateCheck: (value) => set({ autoUpdateCheck: value }),
+ setStripReasoningFromContext: (value) =>
+ set({ stripReasoningFromContext: value }),
setCurrentLanguage: (value) => set({ currentLanguage: value }),
setHuggingfaceToken: (token) => {
set({ huggingfaceToken: token })
@@ -74,6 +79,7 @@ export const useGeneralSetting = create<GeneralSettingState>()(
spellCheckChatInput: state.spellCheckChatInput,
tokenCounterCompact: state.tokenCounterCompact,
autoUpdateCheck: state.autoUpdateCheck,
+ stripReasoningFromContext: state.stripReasoningFromContext,
}),
}
)
diff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
index 53a424784..a53e22285 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
@@ -391,6 +391,60 @@ describe('buildLlamacppReasoningParams', () => {
expect(JSON.stringify(value)).toMatch(/^(true|false)$/)
}
})
+
+ it('merges user kwargs with reasoning into one chat_template_kwargs object', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'on', {
+ preserve_thinking: true,
+ })
+ expect(params).toEqual({
+ chat_template_kwargs: { preserve_thinking: true, enable_thinking: true },
+ })
+ })
+
+ it('emits user kwargs even when reasoning is auto (no enable_thinking)', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'auto', {
+ preserve_thinking: false,
+ reasoning_effort: 'high',
+ max_turns: 4,
+ })
+ expect(params).toEqual({
+ chat_template_kwargs: {
+ preserve_thinking: false,
+ reasoning_effort: 'high',
+ max_turns: 4,
+ },
+ })
+ })
+
+ it('lets the reasoning control win over a user-supplied enable_thinking', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'off', {
+ enable_thinking: true,
+ })
+ expect(params).toEqual({
+ chat_template_kwargs: { enable_thinking: false },
+ })
+ })
+
+ it('drops non-primitive user kwarg values', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'auto', {
+ good: true,
+ bad: { nested: 1 } as unknown as boolean,
+ })
+ expect(params).toEqual({
+ chat_template_kwargs: { good: true },
+ })
+ })
+
+ it('returns {} for llamacpp when there are no kwargs at all', () => {
+ expect(buildLlamacppReasoningParams('llamacpp', 'auto', {})).toEqual({})
+ expect(buildLlamacppReasoningParams('llamacpp', 'auto')).toEqual({})
+ })
+
+ it('ignores user kwargs for non-llamacpp providers', () => {
+ expect(
+ buildLlamacppReasoningParams('openai', 'on', { preserve_thinking: true })
+ ).toEqual({})
+ })
})
describe('coalesceMessagesForAlternation', () => {
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 9ec4c27da..55710bb76 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -125,6 +125,29 @@ function extractModelSamplingDefaults(
return out
}
+/**
+ * Per-model chat-template kwargs the user set in the model settings sidebar,
+ * stored as an object under `settings.chat_template_kwargs`. Only primitive
+ * values are forwarded; `enable_thinking` is owned by the reasoning control
+ * and is dropped here.
+ */
+function extractModelTemplateKwargs(
+ model: Model | null | undefined
+): Record<string, boolean | number | string> {
+ const raw: unknown =
+ model?.settings?.chat_template_kwargs?.controller_props?.value
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
+ const out: Record<string, boolean | number | string> = {}
+ for (const [key, value] of Object.entries(raw)) {
+ if (key === 'enable_thinking') continue
+ const t = typeof value
+ if (t === 'boolean' || t === 'number' || t === 'string') {
+ out[key] = value as boolean | number | string
+ }
+ }
+ return out
+}
+
/**
* `thinking_budget_tokens` is stored as a symbolic level (low/medium/high/
* xhigh/unlimited), not a frozen absolute count — llama.cpp's --fit can pick
@@ -526,24 +549,41 @@ export function normalizeToolInputSchema(
}
/** Text from the most recent user message (for MCP server routing). */
+type ChatTemplateKwargs = Record<string, boolean | number | string>
+
/**
- * Build the per-request reasoning kwargs for llama-server's chat completions
- * endpoint. The server parses `chat_template_kwargs.enable_thinking` via
- * `json_value(...).dump()` (server-common.cpp:1056-1069) and rejects values
- * that serialize to a quoted JSON string — so this must emit a JSON boolean
- * (`true` / `false`), never the strings `"true"` / `"false"`. 'auto' omits
- * the kwarg entirely so the server falls back to its --reasoning-budget
- * default. The function is a no-op for non-llamacpp providers.
+ * Build the per-request `chat_template_kwargs` for llama-server's chat
+ * completions endpoint, merging the reasoning toggle with any user-set
+ * per-model template kwargs (e.g. `preserve_thinking`) into one object. The
+ * server parses each value via `json_value(...).dump()`
+ * (server-common.cpp:1056-1069) and rejects values that serialize to a quoted
+ * JSON string where a boolean/number is expected — so this emits real JSON
+ * types, never the strings `"true"` / `"false"`. Reasoning 'auto'/undefined
+ * omits `enable_thinking` so the server falls back to its --reasoning-budget
+ * default; `enable_thinking` from the reasoning control always wins over a
+ * user-supplied value. The function is a no-op for non-llamacpp providers.
*/
export function buildLlamacppReasoningParams(
providerName: string | null | undefined,
- reasoning: 'auto' | 'on' | 'off' | undefined
-): { chat_template_kwargs?: { enable_thinking: boolean } } {
+ reasoning: 'auto' | 'on' | 'off' | undefined,
+ userKwargs?: ChatTemplateKwargs | null
+): { chat_template_kwargs?: ChatTemplateKwargs } {
if (providerName !== 'llamacpp') return {}
- if (reasoning !== 'on' && reasoning !== 'off') return {}
- return {
- chat_template_kwargs: { enable_thinking: reasoning === 'on' },
+ const kwargs: ChatTemplateKwargs = {}
+ if (userKwargs && typeof userKwargs === 'object') {
+ for (const [key, value] of Object.entries(userKwargs)) {
+ if (key === 'enable_thinking') continue
+ const t = typeof value
+ if (t === 'boolean' || t === 'number' || t === 'string') {
+ kwargs[key] = value
+ }
+ }
+ }
+ if (reasoning === 'on' || reasoning === 'off') {
+ kwargs.enable_thinking = reasoning === 'on'
}
+ if (Object.keys(kwargs).length === 0) return {}
+ return { chat_template_kwargs: kwargs }
}
function extractLatestUserText(messages: UIMessage[]): string {
@@ -942,7 +982,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
| 'auto'
| 'on'
| 'off'
- | undefined
+ | undefined,
+ extractModelTemplateKwargs(selectedModel)
)
if (providerId === 'llamacpp') {
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 1ce3c3858..07ef003ed 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -75,6 +75,7 @@ import {
getProviderApiType,
} from '@/lib/providerCaps'
import { useAppState } from '@/hooks/useAppState'
+import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'
/**
@@ -597,13 +598,9 @@ export function stripAssistantReasoningInBody(
}
}
-/** Reads the per-provider "Strip reasoning from context" checkbox; defaults to false. */
-function shouldStripReasoningFromContext(provider?: ProviderObject): boolean {
- const setting = provider?.settings?.find(
- (s) => s.key === 'strip_reasoning_from_context'
- )
- const value = setting?.controller_props?.value
- return typeof value === 'boolean' ? value : false
+/** Reads the global "Strip reasoning from context" toggle; defaults to false. */
+function shouldStripReasoningFromContext(): boolean {
+ return useGeneralSetting.getState().stripReasoningFromContext === true
}
/** Wraps `inner` to strip reasoning fields from assistant messages before send. */
@@ -930,7 +927,7 @@ export class ModelFactory {
onLlamacppServerError,
true
)
- if (shouldStripReasoningFromContext(provider)) {
+ if (shouldStripReasoningFromContext()) {
customFetch = withAssistantReasoningStripped(customFetch)
}
@@ -1004,7 +1001,7 @@ export class ModelFactory {
undefined,
true
)
- if (shouldStripReasoningFromContext(provider)) {
+ if (shouldStripReasoningFromContext()) {
baseCustomFetch = withAssistantReasoningStripped(baseCustomFetch)
}
const customFetch: typeof globalThis.fetch = async (
@@ -1288,7 +1285,9 @@ export class ModelFactory {
)
: createCustomFetch(getRuntimeFetch(), parameters, false, undefined, true)
- if (provider.provider === 'groq') {
+ // Groq's API rejects assistant `reasoning` fields, so it always strips
+ // regardless of the toggle; other providers honor the global setting.
+ if (provider.provider === 'groq' || shouldStripReasoningFromContext()) {
fetchImpl = withAssistantReasoningStripped(fetchImpl)
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 1653243cf..f86a4dce9 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -261,6 +261,16 @@
"nMinDescription": "Minimum number of tokens to draft per step. Default 0.",
"pMin": "Min draft probability",
"pMinDescription": "Minimum probability for greedy drafting (0–1). Default 0.75."
+ },
+ "templateKwargs": {
+ "section": "Chat template options",
+ "description": "Extra options this model's chat template accepts. Sent as chat_template_kwargs on each request; leave a value at its default to let the template decide.",
+ "addCustom": "Add custom option",
+ "keyPlaceholder": "name",
+ "valuePlaceholder": "value",
+ "add": "Add",
+ "cancel": "Cancel",
+ "remove": "Remove"
}
},
"dialogs": {
diff --git a/web-app/src/locales/en/provider.json b/web-app/src/locales/en/provider.json
index e5489fb08..77596c6b0 100644
--- a/web-app/src/locales/en/provider.json
+++ b/web-app/src/locales/en/provider.json
@@ -10,5 +10,8 @@
"baseUrlPlaceholderAnthropic": "https://api.anthropic.com/v1",
"apiKeyLabel": "API key",
"apiKeyPlaceholder": "Paste your API key",
- "invalidBaseUrl": "Base URL must be a valid http(s) URL"
+ "invalidBaseUrl": "Base URL must be a valid http(s) URL",
+ "globalSettings": "Global settings",
+ "stripReasoning": "Strip reasoning from context",
+ "stripReasoningDesc": "Remove prior turns' thinking/reasoning content before resending history, across all providers. Improves KV-cache reuse for local models, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning."
}
diff --git a/web-app/src/routes/settings/providers/__tests__/index.test.tsx b/web-app/src/routes/settings/providers/__tests__/index.test.tsx
index 9a6450952..3f57d6e54 100644
--- a/web-app/src/routes/settings/providers/__tests__/index.test.tsx
+++ b/web-app/src/routes/settings/providers/__tests__/index.test.tsx
@@ -159,8 +159,8 @@ describe('Providers Settings Route', () => {
const Component = ProvidersRoute.component as React.ComponentType
render(<Component />)
- expect(screen.getByTestId('card')).toBeInTheDocument()
- expect(screen.getByTestId('card-header')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
+ expect(screen.getAllByTestId('card-header').length).toBeGreaterThan(0)
})
it('should render list of providers', () => {
@@ -168,7 +168,7 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
it('should render provider avatars', () => {
@@ -176,7 +176,7 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
it('should render provider titles', () => {
@@ -184,7 +184,7 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
it('should render provider switches', () => {
@@ -192,7 +192,7 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
it('should render add provider dialog', () => {
@@ -227,7 +227,7 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
it('should handle add provider button click', () => {
@@ -303,6 +303,6 @@ describe('Providers Settings Route', () => {
render(<Component />)
// With empty providers array, should still render the page structure
- expect(screen.getByTestId('card')).toBeInTheDocument()
+ expect(screen.getAllByTestId('card').length).toBeGreaterThan(0)
})
})
diff --git a/web-app/src/routes/settings/providers/index.tsx b/web-app/src/routes/settings/providers/index.tsx
index c9ef77341..6a04d31f0 100644
--- a/web-app/src/routes/settings/providers/index.tsx
+++ b/web-app/src/routes/settings/providers/index.tsx
@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'
import { Card, CardItem } from '@/containers/Card'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useModelProvider } from '@/hooks/useModelProvider'
+import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { useNavigate } from '@tanstack/react-router'
import { IconCirclePlus, IconSettings } from '@tabler/icons-react'
import { cn, getProviderTitle } from '@/lib/utils'
@@ -30,6 +31,12 @@ function ModelProviders() {
const { t } = useTranslation()
const serviceHub = useServiceHub()
const { providers, addProvider, updateProvider } = useModelProvider()
+ const stripReasoningFromContext = useGeneralSetting(
+ (s) => s.stripReasoningFromContext
+ )
+ const setStripReasoningFromContext = useGeneralSetting(
+ (s) => s.setStripReasoningFromContext
+ )
const navigate = useNavigate()
const createProvider = useCallback(
@@ -100,6 +107,28 @@ function ModelProviders() {
<SettingsMenu />
<div className="p-4 pt-0 w-full h-[calc(100%-32px)] overflow-y-auto">
<div className="flex flex-col justify-between gap-4 gap-y-3 w-full">
+ {/* Global settings */}
+ <Card
+ header={
+ <div className="flex items-center justify-between w-full mb-6">
+ <span className="font-medium text-base font-studio text-foreground">
+ {t('provider:globalSettings')}
+ </span>
+ </div>
+ }
+ >
+ <CardItem
+ title={t('provider:stripReasoning')}
+ description={t('provider:stripReasoningDesc')}
+ className="items-center flex-row gap-y-2"
+ actions={
+ <Switch
+ checked={stripReasoningFromContext}
+ onCheckedChange={setStripReasoningFromContext}
+ />
+ }
+ />
+ </Card>
{/* Model Providers */}
<Card
header={
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index f449d6d86..fd2b25c15 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -107,6 +107,8 @@ export class TauriProvidersService extends DefaultProvidersService {
capabilities,
embedding: model.embedding, // Preserve embedding flag for filtering in UI
imported: (model as { imported?: boolean }).imported,
+ template_kwargs: (model as { template_kwargs?: TemplateKwarg[] })
+ .template_kwargs,
provider: providerName,
settings: Object.values(modelSettings).reduce(
(acc, setting) => {
diff --git a/web-app/src/types/modelProviders.d.ts b/web-app/src/types/modelProviders.d.ts
index ef53270cc..1be1945e9 100644
--- a/web-app/src/types/modelProviders.d.ts
+++ b/web-app/src/types/modelProviders.d.ts
@@ -24,6 +24,16 @@ type ProviderSetting = {
controller_props: ControllerProps
}
+/**
+ * A chat-template kwarg the model's embedded jinja template accepts,
+ * detected from the GGUF (e.g. `preserve_thinking`).
+ */
+type TemplateKwarg = {
+ name: string
+ type: 'boolean' | 'number' | 'string'
+ default: boolean | number | string
+}
+
/**
* The model object structure
*/
@@ -36,6 +46,8 @@ type Model = {
description?: string
format?: string
capabilities?: string[]
+ /** Chat-template kwargs the model's template accepts (llamacpp only). */
+ template_kwargs?: TemplateKwarg[]
settings?: Record<string, ProviderSetting>
/** Whether this model is an embedding model (e.g., BERT-based) */
embedding?: boolean