Skip to content

Project NOMAD is an offline-first knowledge and education server. Wikipedia, thousands of books, courses, maps, and optional local AI, all running on hardware you own with no internet required.

TypeScript

fix(AI): tell a broken grammar apart from a backend that never had one

jakeaturner06941e71c508
diff --git a/admin/app/services/chat_service.ts b/admin/app/services/chat_service.ts
index 7a44f68d..7cc46cf2 100644
--- a/admin/app/services/chat_service.ts
+++ b/admin/app/services/chat_service.ts
@@ -11,11 +11,18 @@ import { resolveTasksModel } from '../utils/tasks_model.js'
import {
SUGGESTIONS_SCHEMA,
TITLE_SCHEMA,
- parseStructured,
pickSuggestions,
pickTitle,
+ resolveStructured,
} from '../utils/structured_output.js'
+/** Sidebar width, near enough. Applied once, to whichever candidate title won. */
+const TITLE_MAX_LENGTH = 57
+
+function truncateTitle(value: string): string {
+ return value.length > TITLE_MAX_LENGTH ? value.slice(0, TITLE_MAX_LENGTH) + '...' : value
+}
+
@inject()
export class ChatService {
constructor(private ollamaService: OllamaService) {}
@@ -108,12 +115,22 @@ export class ChatService {
if (response && response.message && response.message.content) {
const content = response.message.content.trim()
- const structured = parseStructured(content, pickSuggestions)
- if (structured) {
- return structured.map((s) => toTitleCase(s))
+ const structured = resolveStructured(content, pickSuggestions, response.structured === true)
+ if (structured.ok) {
+ return structured.value.map((s) => toTitleCase(s))
+ }
+ if (structured.reason === 'constrained-parse-failed') {
+ // The grammar was applied and the model broke it anyway, so what came back
+ // is a broken JSON object rather than prose. Splitting that on commas would
+ // surface `{"suggestions": ["How Do I` as a chip. No chips is the better
+ // failure — they are decorative, and the empty state is already designed.
+ logger.warn(
+ `[ChatService] Model "${model}" broke the suggestion grammar; returning no suggestions`
+ )
+ return []
}
logger.warn(
- `[ChatService] Model "${model}" returned unparseable suggestion JSON; falling back to text parsing`
+ `[ChatService] Model "${model}" returned no suggestion JSON; falling back to text parsing`
)
// Handle both comma-separated and newline-separated formats
@@ -317,18 +334,43 @@ export class ChatService {
})
const content = response?.message?.content?.trim() ?? ''
- // The schema path and the text path share the same truncation: "under 50
- // characters" is a request the model can ignore either way.
- let title = parseStructured(content, pickTitle) ?? content
- title = title.slice(0, 57) + (title.length > 57 ? '...' : '')
+ const structured = resolveStructured(content, pickTitle, response?.structured === true)
+
+ let title: string
+ if (!content) {
+ // Nothing left once reasoning was split out. Checked before the grammar branch
+ // so the log says what actually happened rather than blaming the schema.
+ logger.warn(
+ `[ChatService] Model "${titleModel}" returned no usable title text; using the user message`
+ )
+ title = userMessage
+ } else if (structured.ok) {
+ title = structured.value
+ } else if (structured.reason === 'constrained-parse-failed') {
+ // A truncated object would otherwise be stored verbatim, leaving `{"title": ...`
+ // in the sidebar. The user's own words are a worse title than the model's but a
+ // far better one than a JSON fragment.
+ logger.warn(
+ `[ChatService] Model "${titleModel}" broke the title grammar; using the user message`
+ )
+ title = userMessage
+ } else {
+ // Unconstrained backend: the response is meant to be the bare title.
+ title = content
+ }
+
if (!title) {
- // Nothing left once reasoning was split out — fall back to the user's own words.
+ // An unconstrained response that was pure punctuation or whitespace.
logger.warn(
`[ChatService] Model "${titleModel}" returned no usable title text; using the user message`
)
- title = userMessage.slice(0, 57) + (userMessage.length > 57 ? '...' : '')
+ title = userMessage
}
+ // Applied once, to whichever string won: "under 50 characters" is a request the
+ // model can ignore on the schema path and the text path alike.
+ title = truncateTitle(title)
+
await this.updateSession(sessionId, { title })
logger.info(`[ChatService] Generated title for session ${sessionId}: "${title}"`)
} catch (error) {
@@ -337,8 +379,7 @@ export class ChatService {
)
// Fall back to truncated user message
try {
- const fallbackTitle = userMessage.slice(0, 57) + (userMessage.length > 57 ? '...' : '')
- await this.updateSession(sessionId, { title: fallbackTitle })
+ await this.updateSession(sessionId, { title: truncateTitle(userMessage) })
} catch {
// Silently fail - session keeps "New Chat" title
}
diff --git a/admin/app/services/ollama_service.ts b/admin/app/services/ollama_service.ts
index 512ae4a3..9f15c207 100644
--- a/admin/app/services/ollama_service.ts
+++ b/admin/app/services/ollama_service.ts
@@ -81,6 +81,17 @@ export type NomadChatResponse = {
done: boolean
model: string
usage?: NomadChatUsage
+ /**
+ * Whether the decoder was grammar-constrained for this request — `format` was
+ * requested AND the request went out over the native transport that honours it.
+ *
+ * This is what lets a caller tell its two failure modes apart. False means the
+ * model was free to answer in prose and a string parser is the right recovery;
+ * true means unparseable output is the model breaking its own grammar (a
+ * truncated object, in practice) and the caller must take its safe path rather
+ * than feed a JSON fragment to a parser written for prose.
+ */
+ structured?: boolean
}
export type NomadChatStreamChunk = {
@@ -542,6 +553,9 @@ export class OllamaService {
},
done: true,
model: response.model,
+ // The grammar reached the model only if a caller asked for one; this is the
+ // native transport, so requesting it is the same as applying it.
+ structured: chatRequest.format !== undefined,
usage: {
promptTokens: response.prompt_eval_count,
completionTokens: response.eval_count,
@@ -574,6 +588,10 @@ export class OllamaService {
},
done: true,
model: response.model,
+ // `format` is dropped on this transport whether or not the caller sent one,
+ // so the response is unconstrained prose and the caller's string parser is
+ // still the correct way to recover it.
+ structured: false,
usage: {
promptTokens: response.usage?.prompt_tokens,
completionTokens: response.usage?.completion_tokens,
diff --git a/admin/app/services/rag_pipeline_service.ts b/admin/app/services/rag_pipeline_service.ts
index 264ff767..6707b44a 100644
--- a/admin/app/services/rag_pipeline_service.ts
+++ b/admin/app/services/rag_pipeline_service.ts
@@ -19,7 +19,7 @@ import { planPrompt } from '../utils/context_budget.js'
import { estimateMessagesTokens } from '../utils/token_estimate.js'
import { resolveTasksModel } from '../utils/tasks_model.js'
import { buildContextBlock, getContextLimitsForModel } from '../utils/rag_prompt.js'
-import { QUERIES_SCHEMA, parseStructured, pickQueries } from '../utils/structured_output.js'
+import { QUERIES_SCHEMA, pickQueries, resolveStructured } from '../utils/structured_output.js'
/**
* Everything that happens between "a user sent a message" and "a payload goes
@@ -286,9 +286,21 @@ export class RagPipelineService {
})
const raw = response.message.content.trim()
- // Falls back to the raw text on any parse failure — on a non-native backend the
- // grammar was never applied, so the old bare-string behaviour is still correct.
- const rewrittenQuery = parseStructured(raw, pickQueries)?.[0] ?? raw
+ const structured = resolveStructured(raw, pickQueries, response.structured === true)
+ if (!structured.ok && structured.reason === 'constrained-parse-failed') {
+ // The grammar was applied and the output still didn't parse, which here means a
+ // rewrite truncated mid-object by QUERY_REWRITE_MAX_TOKENS. `raw` is a JSON
+ // fragment: embedding it would send the brace and the schema key to Qdrant as
+ // if they were the question. Losing the rewrite for this turn is the cheaper
+ // failure, so take the same path as a rewrite that produced nothing at all.
+ logger.warn(
+ `[RAG] Model "${rewriteModel}" broke the query grammar; falling back to the user message`
+ )
+ return { query: lastUserMessage?.content ?? null, didRewrite: false }
+ }
+ // Unconstrained backends never had the grammar applied, so the raw text is the
+ // rewrite and the old bare-string behaviour is still correct.
+ const rewrittenQuery = structured.ok ? structured.value[0] : raw
// Empty means the response was reasoning and nothing else (or was truncated
// mid-thought). Embedding an empty string would search the corpus for nothing
// and quietly poison retrieval for the rest of the conversation, so fall back
diff --git a/admin/app/utils/structured_output.ts b/admin/app/utils/structured_output.ts
index e129dbed..139db6cc 100644
--- a/admin/app/utils/structured_output.ts
+++ b/admin/app/utils/structured_output.ts
@@ -94,6 +94,43 @@ export function parseStructured<T>(raw: string, pick: (value: any) => T | null):
}
}
+/**
+ * The two ways a structured call can fail to yield a value.
+ *
+ * `unconstrained` — no grammar reached the model (a non-native backend, or a call
+ * that never asked for one). The response is prose by design and the caller's
+ * legacy string parser is the correct recovery.
+ *
+ * `constrained-parse-failed` — the grammar *was* applied and the output still did
+ * not yield a value. In practice that means a truncated object: the model hit its
+ * token cap mid-JSON. Feeding that to a parser written for prose is what produces
+ * `{"title": ...` in the sidebar or a JSON blob in the embedded query, so the
+ * caller must take its safe path instead.
+ */
+export type StructuredResult<T> =
+ | { ok: true; value: T }
+ | { ok: false; reason: 'constrained-parse-failed' | 'unconstrained' }
+
+/**
+ * `parseStructured` plus the reason it failed, so callers branch on what actually
+ * happened rather than sniffing the raw text for braces.
+ *
+ * `constrained` is `NomadChatResponse.structured` — whether the decoder was really
+ * grammar-constrained for the request, which only the transport knows.
+ *
+ * Total, like `parseStructured`: a picker that throws is a failed parse, not an
+ * exception on the chat critical path.
+ */
+export function resolveStructured<T>(
+ raw: string,
+ pick: (value: any) => T | null,
+ constrained: boolean
+): StructuredResult<T> {
+ const value = parseStructured(raw, pick)
+ if (value !== null) return { ok: true, value }
+ return { ok: false, reason: constrained ? 'constrained-parse-failed' : 'unconstrained' }
+}
+
/** Non-empty trimmed string, or null. */
function cleanString(value: unknown): string | null {
if (typeof value !== 'string') return null
diff --git a/admin/tests/unit/structured_output.spec.ts b/admin/tests/unit/structured_output.spec.ts
index 392476ed..13ff6bea 100644
--- a/admin/tests/unit/structured_output.spec.ts
+++ b/admin/tests/unit/structured_output.spec.ts
@@ -20,6 +20,7 @@ import {
pickQueries,
pickSuggestions,
pickTitle,
+ resolveStructured,
} from '../../app/utils/structured_output.js'
// --- parseStructured: extraction ---------------------------------------------
@@ -144,6 +145,77 @@ test('queries: an empty array is null so the raw message is used', () => {
assert.equal(parseStructured('{"queries": []}', pickQueries), null)
})
+// --- resolveStructured -------------------------------------------------------
+//
+// The reason is what each caller branches on, and the two failure reasons lead to
+// opposite behaviour: one runs the legacy prose parser, the other refuses to. A
+// wrong reason is the bug Copilot found on #1259, so both directions are pinned.
+
+test('resolve: a parsed value carries no reason', () => {
+ assert.deepEqual(resolveStructured('{"title": "Water Purification"}', pickTitle, true), {
+ ok: true,
+ value: 'Water Purification',
+ })
+})
+
+test('resolve: constrained + malformed JSON is the model breaking its own grammar', () => {
+ // Truncated mid-object by a token cap. The caller must NOT parse this as prose.
+ assert.deepEqual(resolveStructured('{"title": "unterminated', pickTitle, true), {
+ ok: false,
+ reason: 'constrained-parse-failed',
+ })
+})
+
+test('resolve: unconstrained + malformed JSON leaves the legacy parser in charge', () => {
+ assert.deepEqual(resolveStructured('{"title": "unterminated', pickTitle, false), {
+ ok: false,
+ reason: 'unconstrained',
+ })
+})
+
+test('resolve: unconstrained + plain prose is the normal compat-backend response', () => {
+ assert.deepEqual(resolveStructured('Water Purification Basics', pickTitle, false), {
+ ok: false,
+ reason: 'unconstrained',
+ })
+})
+
+test('resolve: constrained + a picker rejection is still a grammar failure', () => {
+ // `{"suggestions": []}` is valid JSON and valid against nothing useful — minItems
+ // was supposed to prevent it. Parsing the braces as prose would still be wrong.
+ assert.deepEqual(resolveStructured('{"suggestions": []}', pickSuggestions, true), {
+ ok: false,
+ reason: 'constrained-parse-failed',
+ })
+})
+
+test('resolve: constrained + an empty response fails rather than returning a value', () => {
+ assert.deepEqual(resolveStructured('', pickQueries, true), {
+ ok: false,
+ reason: 'constrained-parse-failed',
+ })
+})
+
+test('resolve: a throwing picker is a failed parse, not an exception', () => {
+ // Same critical-path guarantee as parseStructured — the rewrite runs every turn.
+ assert.deepEqual(
+ resolveStructured(
+ '{"title": "x"}',
+ () => {
+ throw new Error('boom')
+ },
+ true
+ ),
+ { ok: false, reason: 'constrained-parse-failed' }
+ )
+})
+
+test('resolve: queries keeps the whole array so [0] is the retrieval query', () => {
+ const result = resolveStructured('{"queries": ["a", "b"]}', pickQueries, true)
+ assert.equal(result.ok, true)
+ assert.deepEqual(result.ok && result.value, ['a', 'b'])
+})
+
// --- schemas -----------------------------------------------------------------
test('every schema marks its key required and forbids extra properties', () => {