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(chat): stop capping answers at 1024 tokens and surface truncation

jakeaturnera013eb6394a8
diff --git a/admin/app/controllers/ollama_controller.ts b/admin/app/controllers/ollama_controller.ts
index f0feca4f..d0dce83b 100644
--- a/admin/app/controllers/ollama_controller.ts
+++ b/admin/app/controllers/ollama_controller.ts
@@ -225,6 +225,8 @@ export default class OllamaController {
const abortController = new AbortController()
response.response.on('close', () => abortController.abort())
let fullContent = ''
+ let doneReason: string | undefined
+ let completionTokens: number | undefined
try {
const stream = await this.ollamaService.chatStream({
...ollamaRequest,
@@ -242,8 +244,10 @@ export default class OllamaController {
fullContent += chunk.message.content
}
if (chunk.usage) {
+ completionTokens = chunk.usage.completionTokens
this._recordUsage(reqData.model, trace, chunk.usage)
}
+ if (chunk.done_reason) doneReason = chunk.done_reason
response.response.write(`data: ${JSON.stringify(chunk)}\n\n`)
}
} catch (err) {
@@ -255,6 +259,9 @@ export default class OllamaController {
normalizedImages.length > 0 && modelCapabilities.vision === 'unknown'
throw err
}
+ if (doneReason === 'length') {
+ this._logLengthStop(reqData.model, numCtx, numPredict, completionTokens)
+ }
// Trailing citation event, written before end(). It carries no `message`
// key, which is how the client tells it apart from Ollama's own chunks.
if (sources.length > 0) {
@@ -301,6 +308,9 @@ export default class OllamaController {
if (result?.usage) {
this._recordUsage(reqData.model, trace, result.usage)
}
+ if (result?.done_reason === 'length') {
+ this._logLengthStop(reqData.model, numCtx, numPredict, result.usage?.completionTokens)
+ }
if (sessionId && result?.message?.content) {
await this.chatService.addMessage(sessionId, 'assistant', result.message.content, sources)
@@ -335,6 +345,23 @@ export default class OllamaController {
}
}
+ /**
+ * A reply that hit the generation cap reaches the user cut off. The client
+ * shows that from done_reason; this puts it in the admin log with the numbers
+ * needed to tell a small window from a cap that is set too low (#1342).
+ */
+ private _logLengthStop(
+ model: string,
+ numCtx: number | undefined,
+ numPredict: number | undefined,
+ completionTokens: number | undefined
+ ): void {
+ logger.info(
+ `[OllamaController] ${model} stopped at the length limit: ` +
+ `${completionTokens ?? '?'} tokens generated, num_predict=${numPredict ?? 'unset'}, num_ctx=${numCtx ?? 'unset'}`
+ )
+ }
+
/**
* Close the loop on token accounting.
*
diff --git a/admin/app/services/ollama_service.ts b/admin/app/services/ollama_service.ts
index eeec1298..f17b1bd2 100644
--- a/admin/app/services/ollama_service.ts
+++ b/admin/app/services/ollama_service.ts
@@ -106,6 +106,12 @@ export type NomadChatResponse = {
* than feed a JSON fragment to a parser written for prose.
*/
structured?: boolean
+ /**
+ * Why generation stopped, in Ollama's vocabulary: 'stop' for a natural end,
+ * 'length' when num_predict / max_tokens cut it off. Snake case because this
+ * object goes to API clients as-is and that is the field name they know.
+ */
+ done_reason?: string
}
export type NomadChatStreamChunk = {
@@ -113,6 +119,8 @@ export type NomadChatStreamChunk = {
done: boolean
// Present only on the final chunk of a stream.
usage?: NomadChatUsage
+ // Present only on the chunk that ends generation. See NomadChatResponse.
+ done_reason?: string
}
type ChatInput = {
@@ -690,6 +698,7 @@ export class OllamaService {
// 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,
+ ...(response.done_reason ? { done_reason: response.done_reason } : {}),
usage: {
promptTokens: response.prompt_eval_count,
completionTokens: response.eval_count,
@@ -726,6 +735,7 @@ export class OllamaService {
// so the response is unconstrained prose and the caller's string parser is
// still the correct way to recover it.
structured: false,
+ ...(choice.finish_reason ? { done_reason: choice.finish_reason } : {}),
usage: {
promptTokens: response.usage?.prompt_tokens,
completionTokens: response.usage?.completion_tokens,
@@ -785,6 +795,7 @@ export class OllamaService {
done: chunk.done === true,
...(chunk.done
? {
+ ...(chunk.done_reason ? { done_reason: chunk.done_reason } : {}),
usage: {
promptTokens: chunk.prompt_eval_count,
completionTokens: chunk.eval_count,
@@ -843,12 +854,15 @@ export class OllamaService {
const nativeThinking: string = (delta as any)?.thinking ?? (delta as any)?.reasoning ?? ''
const split = splitter.push(delta?.content ?? '')
+ const finishReason = chunk.choices[0]?.finish_reason
yield {
message: {
content: split.content,
thinking: nativeThinking + split.thinking,
},
- done: chunk.choices[0]?.finish_reason !== null && chunk.choices[0]?.finish_reason !== undefined,
+ done: finishReason !== null && finishReason !== undefined,
+ // OpenAI's finish_reason uses the same 'stop' / 'length' values.
+ ...(finishReason ? { done_reason: finishReason } : {}),
}
}
diff --git a/admin/app/utils/context_budget.ts b/admin/app/utils/context_budget.ts
index 1df2023e..41ef3ed4 100644
--- a/admin/app/utils/context_budget.ts
+++ b/admin/app/utils/context_budget.ts
@@ -15,7 +15,9 @@
* record what happened so the eval harness can see it.
*
* Allocation order, most protected first:
- * 1. Response reserve — tokens held back for the answer itself.
+ * 1. Response reserve — a floor held back for the answer itself. The actual
+ * generation cap is whatever the window has left once
+ * the prompt is assembled, which is usually far more.
* 2. Fixed blocks — system prompts and the current question. Never dropped.
* 3. Retrieved context — whole chunks, best-first, until its share is spent.
* 4. History — whole turns, newest-first, into whatever remains.
@@ -86,19 +88,37 @@ export type BudgetTrace = {
historyElided: boolean
queryTruncated: boolean
ragPlacement: RagPlacement
+ numPredict: number
}
export type BudgetResult = {
messages: BudgetMessage[]
trace: BudgetTrace
- /** What to send as num_predict, so generation can't run past the window. */
+ /**
+ * What to send as num_predict: the space the window actually has left after
+ * the prompt, less a margin for estimator error. Never below the reserve.
+ */
numPredict: number
}
-/** Ceiling on tokens reserved for the answer. */
-export const MAX_RESPONSE_RESERVE = 1024
+/**
+ * Ceiling on tokens reserved for the answer.
+ *
+ * This only bounds how much prompt space is held back; it is not the
+ * generation cap. It used to double as one, which pinned every answer at 1024
+ * tokens regardless of window size and cut long answers off mid-sentence
+ * (#1342).
+ */
+export const MAX_RESPONSE_RESERVE = 8192
/** Share of the window reserved for the answer when that is smaller. */
export const RESPONSE_RESERVE_FRACTION = 0.25
+/**
+ * Headroom left between the estimated prompt and the end of the window when
+ * sizing num_predict. The estimator is calibrated per model but still only an
+ * estimate; undershooting here means llama.cpp context-shifts mid-answer.
+ */
+export const NUM_PREDICT_SAFETY_FRACTION = 0.05
+export const NUM_PREDICT_SAFETY_MIN = 64
/** Share of the remaining budget the retrieved context may claim. */
export const DEFAULT_RAG_SHARE = 0.35
@@ -268,9 +288,17 @@ export function planPrompt(inputs: BudgetInputs): BudgetResult {
const estimatedPromptTokens = cost(messages)
+ // The planner already kept the prompt within `contextWindow - responseReserve`,
+ // so the reserve floor can never push generation past the window.
+ const safetyMargin = Math.max(
+ NUM_PREDICT_SAFETY_MIN,
+ Math.ceil(estimatedPromptTokens * NUM_PREDICT_SAFETY_FRACTION)
+ )
+ const numPredict = Math.max(responseReserve, contextWindow - estimatedPromptTokens - safetyMargin)
+
return {
messages,
- numPredict: responseReserve,
+ numPredict,
trace: {
contextWindow,
responseReserve,
@@ -287,6 +315,7 @@ export function planPrompt(inputs: BudgetInputs): BudgetResult {
historyElided,
queryTruncated,
ragPlacement: placement,
+ numPredict,
},
}
}
diff --git a/admin/inertia/components/chat/ChatInterface.tsx b/admin/inertia/components/chat/ChatInterface.tsx
index b9c665a1..2663ec78 100644
--- a/admin/inertia/components/chat/ChatInterface.tsx
+++ b/admin/inertia/components/chat/ChatInterface.tsx
@@ -20,6 +20,11 @@ interface ChatInterfaceProps {
chatSuggestionsLoading?: boolean
}
+// Sent as an ordinary turn, so it goes through retrieval, budgeting and
+// persistence like any other message. The cut-off answer is the newest turn in
+// history, which the budget keeps first.
+const CONTINUE_PROMPT = 'Continue exactly where you left off. Do not repeat what you already wrote.'
+
const MAX_VISION_IMAGES = 4
const MAX_VISION_IMAGE_BYTES = 8 * 1024 * 1024
const SUPPORTED_VISION_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
@@ -198,7 +203,7 @@ export default function ChatInterface({
</div>
) : (
<>
- {messages.map((message) => (
+ {messages.map((message, idx) => (
<div
key={message.id}
className={classNames(
@@ -207,7 +212,14 @@ export default function ChatInterface({
)}
>
{message.role === 'assistant' && <ChatAssistantAvatar />}
- <ChatMessageBubble message={message} />
+ <ChatMessageBubble
+ message={message}
+ onContinue={
+ idx === messages.length - 1 && !isLoading
+ ? () => onSendMessage(CONTINUE_PROMPT, [])
+ : undefined
+ }
+ />
</div>
))}
{/* Loading/thinking indicator */}
diff --git a/admin/inertia/components/chat/ChatMessageBubble.tsx b/admin/inertia/components/chat/ChatMessageBubble.tsx
index 0df7ca87..b9eacc28 100644
--- a/admin/inertia/components/chat/ChatMessageBubble.tsx
+++ b/admin/inertia/components/chat/ChatMessageBubble.tsx
@@ -5,9 +5,11 @@ import { ChatMessage } from '../../../types/chat'
export interface ChatMessageBubbleProps {
message: ChatMessage
+ // Offered on the latest answer when it was cut off at the length limit.
+ onContinue?: () => void
}
-export default function ChatMessageBubble({ message }: ChatMessageBubbleProps) {
+export default function ChatMessageBubble({ message, onContinue }: ChatMessageBubbleProps) {
return (
<div
className={classNames(
@@ -114,6 +116,20 @@ export default function ChatMessageBubble({ message }: ChatMessageBubbleProps) {
<span className="inline-block w-2 h-4 ml-1 bg-current animate-pulse" />
)}
</div>
+ {message.role === 'assistant' && message.truncated && !message.isStreaming && (
+ <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-border-subtle pt-2 text-xs text-text-secondary">
+ <span>This answer hit the length limit and was cut off.</span>
+ {onContinue && (
+ <button
+ type="button"
+ onClick={onContinue}
+ className="rounded border border-border-default px-2 py-0.5 font-medium text-desert-green hover:bg-surface-primary focus:outline-none focus:ring-2 focus:ring-desert-green"
+ >
+ Continue
+ </button>
+ )}
+ </div>
+ )}
{message.role === 'assistant' && message.sources && message.sources.length > 0 && (
<div className="mt-3 border-t border-border-subtle pt-2 text-xs text-text-primary">
<div className="mb-1 font-medium">Sources</div>
diff --git a/admin/inertia/components/chat/index.tsx b/admin/inertia/components/chat/index.tsx
index f8c31aa0..9484af2d 100644
--- a/admin/inertia/components/chat/index.tsx
+++ b/admin/inertia/components/chat/index.tsx
@@ -213,6 +213,7 @@ export default function Chat({
role: 'assistant',
content: data.message?.content || 'Sorry, I could not generate a response.',
timestamp: new Date(),
+ truncated: data.done_reason === 'length',
}
setMessages((prev) => [...prev, assistantMessage])
@@ -513,6 +514,12 @@ export default function Chat({
setMessages((prev) =>
prev.map((m) => (m.id === assistantMsgId ? { ...m, sources } : m))
)
+ },
+ (reason) => {
+ if (reason !== 'length') return
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantMsgId ? { ...m, truncated: true } : m))
+ )
}
)
} catch (error: any) {
diff --git a/admin/inertia/lib/api.ts b/admin/inertia/lib/api.ts
index 4c617cea..8284e14d 100644
--- a/admin/inertia/lib/api.ts
+++ b/admin/inertia/lib/api.ts
@@ -362,7 +362,8 @@ class API {
chatRequest: OllamaChatRequestWithImages,
onChunk: (content: string, thinking: string, done: boolean) => void,
signal?: AbortSignal,
- onSources?: (sources: ChatSource[]) => void
+ onSources?: (sources: ChatSource[]) => void,
+ onDoneReason?: (reason: string) => void
): Promise<void> {
// Axios doesn't support ReadableStream in browser, so need to use fetch
const serialized = serializeChatRequest({ ...chatRequest, stream: true })
@@ -408,6 +409,12 @@ class API {
continue
}
+ // Only the chunk that ends generation carries it; 'length' means the
+ // answer was cut off rather than finished (#1342).
+ if (data.done_reason) {
+ onDoneReason?.(data.done_reason)
+ }
+
onChunk(
data.message?.content ?? '',
data.message?.thinking ?? '',
diff --git a/admin/tests/unit/context_budget.spec.ts b/admin/tests/unit/context_budget.spec.ts
index bc939bf3..24ba1ea6 100644
--- a/admin/tests/unit/context_budget.spec.ts
+++ b/admin/tests/unit/context_budget.spec.ts
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict'
import {
ELISION_MARKER,
HISTORY_EVICTION_BLOCK,
+ MAX_RESPONSE_RESERVE,
groupIntoTurns,
planPrompt,
type BudgetChunk,
@@ -80,11 +81,43 @@ test('never exceeds the prompt budget', () => {
assert.ok(result.trace.turnsDropped > 0)
})
-test('reserves room for the response and reports it as numPredict', () => {
+test('reserves room for the response out of the prompt budget', () => {
const result = planPrompt(makeInputs({ contextWindow: 4096 }))
- assert.equal(result.trace.responseReserve, result.numPredict)
assert.equal(result.trace.promptBudget, 4096 - result.trace.responseReserve)
- assert.ok(result.numPredict > 0)
+ assert.ok(result.numPredict >= result.trace.responseReserve)
+ assert.equal(result.trace.numPredict, result.numPredict)
+})
+
+test('numPredict scales with the window instead of pinning at 1024 (#1342)', () => {
+ const result = planPrompt(makeInputs({ contextWindow: 65536 }))
+ assert.ok(result.numPredict > 60000, `numPredict ${result.numPredict} should use the free window`)
+ assert.ok(
+ result.trace.estimatedPromptTokens + result.numPredict <= 65536,
+ 'prompt plus answer must still fit the window'
+ )
+})
+
+test('numPredict never runs past the window, even with a full prompt', () => {
+ for (const contextWindow of [4096, 8192, 32768]) {
+ const result = planPrompt(makeInputs({ history: history(400), contextWindow }))
+ assert.ok(result.numPredict >= result.trace.responseReserve)
+ assert.ok(
+ result.trace.estimatedPromptTokens + result.numPredict <= contextWindow,
+ `window ${contextWindow}: ${result.trace.estimatedPromptTokens} + ${result.numPredict} overflows`
+ )
+ }
+})
+
+test('the response reserve is capped so large windows keep their prompt space', () => {
+ const result = planPrompt(makeInputs({ contextWindow: 131072 }))
+ assert.equal(result.trace.responseReserve, MAX_RESPONSE_RESERVE)
+})
+
+test('an explicit response reserve is still honoured as the floor', () => {
+ const result = planPrompt(makeInputs({ contextWindow: 8192, responseReserve: 500 }))
+ assert.equal(result.trace.responseReserve, 500)
+ assert.equal(result.trace.promptBudget, 8192 - 500)
+ assert.ok(result.numPredict >= 500)
})
test('system blocks and the current question are never dropped', () => {
diff --git a/admin/tests/unit/ollama_done_reason.spec.ts b/admin/tests/unit/ollama_done_reason.spec.ts
new file mode 100644
index 00000000..c62898ea
--- /dev/null
+++ b/admin/tests/unit/ollama_done_reason.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * The stop reason has to survive chunk normalization (#1342).
+ *
+ * Both transports used to rebuild each chunk as {message, done, usage}, which
+ * dropped Ollama's done_reason and OpenAI's finish_reason. A reply cut off by
+ * num_predict then looked exactly like one that finished.
+ *
+ * A Japa spec: OllamaService imports the Adonis logger at module scope. Run with
+ * `node ace test unit`.
+ */
+import assert from 'node:assert/strict'
+import { test } from '@japa/runner'
+import { OllamaService } from '../../app/services/ollama_service.js'
+
+async function collect<T>(iterable: AsyncIterable<T>): Promise<T[]> {
+ const out: T[] = []
+ for await (const item of iterable) out.push(item)
+ return out
+}
+
+function fakeNativeIterator(chunks: any[]) {
+ return {
+ abort() {},
+ async *[Symbol.asyncIterator]() {
+ yield* chunks
+ },
+ }
+}
+
+function serviceWithNative(chunks: any[], response?: any) {
+ const service = new OllamaService() as any
+ service.ollama = {
+ chat: async (req: { stream: boolean }) => (req.stream ? fakeNativeIterator(chunks) : response),
+ }
+ return service
+}
+
+function serviceWithCompat(chunks: any[], response?: any) {
+ const service = new OllamaService() as any
+ service.openai = {
+ chat: {
+ completions: {
+ create: async (params: { stream: boolean }) =>
+ params.stream
+ ? (async function* () {
+ yield* chunks
+ })()
+ : response,
+ },
+ },
+ }
+ return service
+}
+
+const request = { model: 'm', messages: [{ role: 'user', content: 'hi' }], numPredict: 16 }
+
+test('native stream forwards done_reason on the final chunk', async () => {
+ const service = serviceWithNative([
+ { message: { content: 'Alternate Between' }, done: false },
+ { message: { content: ' Annuals' }, done: true, done_reason: 'length', eval_count: 16 },
+ ])
+ const chunks = await collect<any>(await service._chatStreamNative(request))
+ assert.equal(chunks[0].done_reason, undefined)
+ assert.equal(chunks.at(-1).done, true)
+ assert.equal(chunks.at(-1).done_reason, 'length')
+ assert.equal(chunks.at(-1).usage.completionTokens, 16)
+})
+
+test('compat stream maps finish_reason to done_reason', async () => {
+ const service = serviceWithCompat([
+ { choices: [{ delta: { content: 'egg' }, finish_reason: null }] },
+ { choices: [{ delta: { content: '' }, finish_reason: 'length' }] },
+ { choices: [], usage: { prompt_tokens: 10, completion_tokens: 16 } },
+ ])
+ const chunks = await collect<any>(await service._chatStreamCompat(request))
+ assert.equal(chunks[0].done_reason, undefined)
+ assert.equal(chunks[1].done, true)
+ assert.equal(chunks[1].done_reason, 'length')
+})
+
+test('non-streaming native and compat responses carry done_reason', async () => {
+ const native = serviceWithNative([], {
+ model: 'm',
+ message: { content: 'cut' },
+ done: true,
+ done_reason: 'length',
+ })
+ assert.equal((await native._chatNative(request)).done_reason, 'length')
+
+ const compat = serviceWithCompat([], {
+ model: 'm',
+ choices: [{ message: { content: 'done' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1 },
+ })
+ assert.equal((await compat._chatCompat(request)).done_reason, 'stop')
+})
diff --git a/admin/types/chat.ts b/admin/types/chat.ts
index d05dc646..782361bb 100644
--- a/admin/types/chat.ts
+++ b/admin/types/chat.ts
@@ -20,6 +20,8 @@ export interface ChatMessage {
isThinking?: boolean
thinkingDuration?: number
sources?: ChatSource[]
+ // Generation stopped at the length limit, so the answer ends mid-thought.
+ truncated?: boolean
}
export interface ChatImageAttachment {
diff --git a/admin/types/ollama.ts b/admin/types/ollama.ts
index 66fc03e1..07b0d412 100644
--- a/admin/types/ollama.ts
+++ b/admin/types/ollama.ts
@@ -66,6 +66,8 @@ export type NomadChatResponse = {
message: { content: string; thinking?: string }
done: boolean
model: string
+ // 'length' means the answer hit the generation cap and was cut off (#1342).
+ done_reason?: string
}
/**