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.

fix(params): coerce numeric assistant params from string to number (#8386)

Akarshan Biswas679091782fb5
diff --git a/web-app/src/containers/dynamicControllerSetting/index.tsx b/web-app/src/containers/dynamicControllerSetting/index.tsx
index ed1720531..15b9f3bed 100644
--- a/web-app/src/containers/dynamicControllerSetting/index.tsx
+++ b/web-app/src/containers/dynamicControllerSetting/index.tsx
@@ -64,6 +64,12 @@ function renderControl(
onChange: DynamicControllerProps['onChange']
) {
if (controllerType === 'input') {
+ const isNumeric =
+ controllerProps.type === 'number' ||
+ typeof controllerProps.value === 'number' ||
+ controllerProps.min !== undefined ||
+ controllerProps.max !== undefined ||
+ controllerProps.step !== undefined
return (
<InputControl
type={controllerProps.type}
@@ -78,7 +84,13 @@ function renderControl(
min={controllerProps.min}
max={controllerProps.max}
step={controllerProps.step}
- onChange={(newValue) => onChange(newValue)}
+ onChange={(newValue) => {
+ if (!isNumeric || typeof newValue !== 'string') return onChange(newValue)
+ const trimmed = newValue.trim()
+ if (trimmed === '' || trimmed === '-') return onChange(trimmed)
+ const n = Number(trimmed)
+ onChange(Number.isNaN(n) ? newValue : n)
+ }}
/>
)
} else if (controllerType === 'checkbox') {
diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.ts
index 6e5437765..88d5073c9 100644
--- a/web-app/src/lib/__tests__/model-factory.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.test.ts
@@ -327,6 +327,30 @@ describe('createCustomFetch — max_tokens coercion', () => {
)
expect(sent.max_tokens).toBe(-1)
})
+
+ it('coerces string numeric params (text input) back to numbers', async () => {
+ const sent = await captureSentBody(
+ { max_output_tokens: '2048', dry_penalty_last_n: '-1' },
+ true,
+ { messages: [] }
+ )
+ expect(sent.max_tokens).toBe(2048)
+ expect(sent.dry_penalty_last_n).toBe(-1)
+ })
+
+ it('coerces string "0" so the max_tokens=-1 rule still fires', async () => {
+ const sent = await captureSentBody({ max_output_tokens: '0' }, true, {
+ messages: [],
+ })
+ expect(sent.max_tokens).toBe(-1)
+ })
+
+ it('leaves non-numeric string params untouched', async () => {
+ const sent = await captureSentBody({ max_output_tokens: '' }, false, {
+ messages: [],
+ })
+ expect(sent.max_tokens).toBe('')
+ })
})
describe('createCustomFetch — llamacpp 500 handling', () => {
diff --git a/web-app/src/lib/__tests__/toolCallRepair.test.ts b/web-app/src/lib/__tests__/toolCallRepair.test.ts
new file mode 100644
index 000000000..6323f8441
--- /dev/null
+++ b/web-app/src/lib/__tests__/toolCallRepair.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect } from 'vitest'
+import {
+ sanitizeInvalidJsonEscapes,
+ repairToolArgs,
+} from '../toolCallRepair'
+
+describe('sanitizeInvalidJsonEscapes', () => {
+ it('re-escapes a Windows drive path with all-literal backslashes', () => {
+ const raw = '{"path":"C:\\Users\\name\\file.txt"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:\\Users\\name\\file.txt',
+ })
+ })
+
+ it('handles Program Files and Windows system folders', () => {
+ const raw = '{"path":"C:\\Program Files\\Windows\\notepad.exe"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:\\Program Files\\Windows\\notepad.exe',
+ })
+ })
+
+ it('re-escapes segments starting with JSON escape letters', () => {
+ const raw = '{"path":"C:\\temp\\new\\report.txt"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:\\temp\\new\\report.txt',
+ })
+ })
+
+ it('preserves genuine unicode escapes', () => {
+ const raw = '{"path":"C:\\u0041\\dir"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:A\\dir',
+ })
+ })
+
+ it('treats \\u not followed by hex as a literal backslash', () => {
+ const raw = '{"path":"C:\\users\\bob"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:\\users\\bob',
+ })
+ })
+
+ it('handles a trailing directory-separator backslash', () => {
+ const raw = '{"path":"C:\\Users\\"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: 'C:\\Users\\',
+ })
+ })
+
+ it('handles UNC paths (leading double backslash)', () => {
+ const raw = '{"path":"\\\\server\\share\\file"}'
+ expect(JSON.parse(sanitizeInvalidJsonEscapes(raw))).toEqual({
+ path: '\\\\server\\share\\file',
+ })
+ })
+
+ it('leaves content outside string literals untouched', () => {
+ const raw = '{"n":42,"ok":true}'
+ expect(sanitizeInvalidJsonEscapes(raw)).toBe(raw)
+ })
+})
+
+describe('repairToolArgs', () => {
+ it('parses a broken Windows path', () => {
+ expect(repairToolArgs('{"path":"D:\\repos\\jan\\file"}')).toEqual({
+ path: 'D:\\repos\\jan\\file',
+ })
+ })
+
+ it('returns valid JSON untouched, preserving intended escapes', () => {
+ const raw = '{"text":"line1\\nline2\\ttab","q":"say \\"hi\\""}'
+ expect(repairToolArgs(raw)).toEqual({
+ text: 'line1\nline2\ttab',
+ q: 'say "hi"',
+ })
+ })
+
+ it('parses plain valid JSON', () => {
+ expect(repairToolArgs('{"n":42}')).toEqual({ n: 42 })
+ })
+
+ it('returns null when unrepairable', () => {
+ expect(repairToolArgs('{not json at all')).toBeNull()
+ })
+
+ it('returns null for non-object JSON', () => {
+ expect(repairToolArgs('"just a string"')).toBeNull()
+ })
+
+ it('returns null for array JSON', () => {
+ expect(repairToolArgs('[1,2,3]')).toBeNull()
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 5780e3cca..027a433f5 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -9,7 +9,9 @@ import {
type Tool,
type LanguageModelUsage,
jsonSchema,
+ InvalidToolInputError,
} from 'ai'
+import { repairToolArgs } from './toolCallRepair'
import { useServiceStore } from '@/hooks/useServiceHub'
import { useToolAvailable } from '@/hooks/useToolAvailable'
import { ModelFactory } from './model-factory'
@@ -1110,6 +1112,15 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
toolChoice: shouldEnableTools ? 'auto' : undefined,
system: effectiveSystem,
...(maxOutputTokens !== undefined ? { maxTokens: maxOutputTokens } : {}),
+ experimental_repairToolCall: async ({ toolCall, error }) => {
+ // Windows paths (`C:\Users\...`) contain invalid JSON escapes that make
+ // the SDK's argument parse fail. Re-escape lone backslashes and retry
+ // so the tool receives the intended path instead of looping on failure.
+ if (!InvalidToolInputError.isInstance(error)) return null
+ const repaired = repairToolArgs(toolCall.input)
+ if (!repaired) return null
+ return { ...toolCall, input: JSON.stringify(repaired) }
+ },
})
let tokensPerSecond = 0
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 635aa67c7..4368606e0 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -347,6 +347,17 @@ export function createCustomFetch(
keepLlamacppOnly = false,
onLlamacppServerError?: () => void
): typeof globalThis.fetch {
+ // Params entered via a text input arrive as strings (see InputControl).
+ // Providers reject a string where a number is required, so coerce back to a
+ // number when the param's predefined default is numeric.
+ const coerceNumericParam = (key: string, value: unknown): unknown => {
+ if (typeof value !== 'string') return value
+ const def = paramsSettings[key]
+ if (!def || typeof def.value !== 'number' || value.trim() === '') return value
+ const n = Number(value)
+ return Number.isNaN(n) ? value : n
+ }
+
const buildBody = (
rawBody: Record<string, unknown>,
includeOurParams: boolean
@@ -361,7 +372,7 @@ export function createCustomFetch(
if (CLIENT_SIDE_PARAM_KEYS.has(key)) continue
if (!keepLlamacppOnly && LLAMACPP_ONLY_PARAM_KEYS.has(key)) continue
const targetKey = key === 'max_output_tokens' ? 'max_tokens' : key
- normalised[targetKey] = value
+ normalised[targetKey] = coerceNumericParam(key, value)
}
const merged = { ...rawBody, ...normalised }
if (keepLlamacppOnly && merged.stream === true) {
diff --git a/web-app/src/lib/toolCallRepair.ts b/web-app/src/lib/toolCallRepair.ts
new file mode 100644
index 000000000..2607ba283
--- /dev/null
+++ b/web-app/src/lib/toolCallRepair.ts
@@ -0,0 +1,60 @@
+const HEX = /[0-9a-fA-F]/
+
+/**
+ * Re-escapes backslashes inside JSON string literals as literal path
+ * separators. Intended for tool-call arguments that FAILED to parse: smaller
+ * local models emit Windows paths like `C:\Users\name\file.txt` verbatim, where
+ * `\U`, `\n`, `\f`, ... are treated as (invalid or unintended) JSON escapes and
+ * the path is corrupted or dropped. Every backslash is doubled except a genuine
+ * `\uXXXX` unicode escape, which is preserved. Do not run this on already-valid
+ * JSON (see `repairToolArgs`, which parses first).
+ */
+export function sanitizeInvalidJsonEscapes(raw: string): string {
+ let out = ''
+ let inString = false
+ for (let i = 0; i < raw.length; i++) {
+ const ch = raw[i]
+ if (!inString) {
+ if (ch === '"') inString = true
+ out += ch
+ continue
+ }
+ if (ch === '\\') {
+ const isUnicode =
+ raw[i + 1] === 'u' &&
+ HEX.test(raw[i + 2] ?? '') &&
+ HEX.test(raw[i + 3] ?? '') &&
+ HEX.test(raw[i + 4] ?? '') &&
+ HEX.test(raw[i + 5] ?? '')
+ if (isUnicode) {
+ out += raw.slice(i, i + 6)
+ i += 5
+ } else {
+ out += '\\\\'
+ }
+ continue
+ }
+ if (ch === '"') inString = false
+ out += ch
+ }
+ return out
+}
+
+/**
+ * Parses tool-call argument JSON, repairing malformed backslash escapes (the
+ * common Windows-path failure) only when a plain parse fails. Returns the parsed
+ * object, or null if it still cannot be parsed as an object.
+ */
+export function repairToolArgs(raw: string): Record<string, unknown> | null {
+ for (const candidate of [raw, sanitizeInvalidJsonEscapes(raw)]) {
+ try {
+ const parsed = JSON.parse(candidate)
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return parsed
+ }
+ } catch {
+ // try next candidate
+ }
+ }
+ return null
+}