Note 17 / LLM / Backend / NestJS
When the model stops at max_tokens and your app saves the half answer: handling finish_reason length
Chat answers ended mid-sentence and reports lost blocks with no error. The cause was ignoring finish_reason. What I treat as complete, how truncation reaches the client, and what is still unfinished.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- October 2026, AI Note Taker (NestJS, OpenRouter, Postgres)
- Stack
- NestJS, OpenRouter (OpenAI-style chat completions, SSE streaming), Zod, Jest
- Reading
- 6 min, 1,218 words
While testing the meeting-notes app I hit two symptoms. A long chat answer in the meeting-notes app stopped in the middle of a sentence and looked finished. A generated meeting report was missing a block, and nothing in the screen or the API response said it was incomplete. Both outputs had been saved and shown as normal results.
Neither was a crash. The provider had answered “I stopped because you set a limit”, and my code had not read that part of the response.
The field that says why generation stopped
A chat completion carries a reason it stopped. OpenAI’s API reference describes finish_reason as “stop if the model hit a natural stop point or a provided stop sequence, length if the maximum number of tokens specified in the request was reached, content_filter if content was omitted due to a flag from our content filters”, plus tool_calls when the model calls a tool. Gemini’s equivalent is finishReason with the values STOP (“natural stop point of the model or provided stop sequence”) and MAX_TOKENS (“the maximum number of tokens as specified in the request was reached”), along with a long list of safety and policy values such as SAFETY, RECITATION and BLOCKLIST. The backend talks to models through OpenRouter, which returns the OpenAI shape, so the field I read is choices[0].finish_reason.
The point is that HTTP 200 and a non-empty content do not mean the answer is complete. A truncated answer is a successful response.
Where my code lost it
Streaming made it easy to miss. The chat path reads server-sent events and yields each text delta. The last frames carry usage, and the frame with finish_reason arrives in the stream but contains no text. The old loop only looked at deltas, so the stream ended, the full text was assembled and saved, and the reason was never inspected.
The structured path (JSON for report blocks) had a related, more confusing failure. Models with a thinking phase spend part of max_tokens on reasoning. When the cap is reached the JSON is cut off in the middle, JSON.parse fails, and the error says “invalid JSON”. Reading that message, the natural move is to fix the prompt. A comment in the provider code records three failed reports on 14 August 2026 that were all this: the fix was the output limit, not the prompt. In another case the thinking tokens consumed the whole budget and content came back empty with length, which my code reported as “model returned empty”.
So the first rule in the provider is order of checks: read finish_reason before the empty check and before the parse.
const finish = response.choices?.[0]?.finish_reason ?? null;
if (finish === "length") {
throw new Error(
`cut off at max_tokens=${limit}, got ${text.length} chars; ` +
"the cap includes the model's reasoning tokens"
);
}
if (!text.trim()) throw new Error(`empty output (finish_reason=${finish})`);
The message names the limit that was hit. It does not include any of the model’s output, because on this app the output is the content of someone’s meeting and these error strings end up in logs and a failure-reason column.
What counts as complete
For free-text chat I use the narrow definition: complete means the provider said stop, and nothing else.
const isComplete = (finishReason: string | null) =>
finishReason?.toLowerCase() === "stop";
length is the case I started with, but the same predicate catches content_filter, an error reason, and the one I find the most useful: null. If the stream ends without any finish frame, the connection may have been cut by a proxy or a mobile network, and “no reason given” must not be read as “finished”. The client gets a stable reason: max_tokens for length, stream_ended for null, and the provider’s own string for the rest.
This predicate is only right because this chat call has no tools. If you pass tools, tool_calls is a normal stop in OpenAI’s scheme, and treating it as incomplete would be wrong. The set of acceptable reasons belongs to each call site, so keep it next to the call.
How the client finds out
The chat endpoint streams events to the app. When the stream ends and the reason is not stop, the server sends a truncated event with the reason before the final event, logs a warning with the length and reason (not the text), and the final done event also carries truncated: true for a client that only reads the last event. I raised the answer ceiling to 8,192 tokens so ordinary long answers are not cut in the first place; at that size a length stop is an extreme case, but it is reported, not silent.
There is a second, quieter use. Chat first rewrites a follow-up question into a standalone one before retrieval. If that rewrite itself stops on anything but stop, I use the user’s original question and log it, because a rewritten question that ends mid-clause retrieves the wrong passages.
For reports, one block that fails (cut off, schema mismatch, timeout) now retries on its own, up to 2 more times, instead of rerunning the whole report, which is dozens of high-tier calls. If a block is still missing after the retries, the report is saved with what exists, and the missing blocks are written to a gaps record that the note detail API returns. A report with no blocks at all throws, so the job is retried instead of storing an empty headline.
What I checked, and what I did not
According to my lessons log (BL-251), the Jest specs for the OpenRouter provider, the report service, the chat scenarios and the number-check for generated artifacts pass, and the sweep git grep -n "finish_reason" -- src showed every LLM call in the backend going through the completeness helper at that commit. That commit is deployed and the health endpoint reports it.
Two gaps remain, and the log entry says so. The mobile app does not display the truncated flag yet, so a truncated answer is reported by the server but not yet explained to the user. And the flag is not saved on the message row, because the table has no column for it and the migration is not written; reopening the conversation later shows the answer without the marker. I have no count of how often length actually occurs at the 8,192 limit in production, so I cannot say how much the change helps in practice.
Rules I took from it
Read the finish reason on every call, including the one that “always returns a few lines”. Decide per call which reasons are complete. Treat a missing reason as incomplete. Put the check before your emptiness and parse checks so the error names the real cause. Return partial results with an explicit marker rather than a thrown error when the user can still use what exists, and keep the marker in storage, not only in the response.
Documentation checked
- OpenAI chat completions reference: wording for
finish_reasonquoted above. - Gemini generate content reference:
FinishReasonvaluesSTOPandMAX_TOKENSas quoted. - How OpenRouter counts reasoning tokens against
max_tokensis from the behaviour I saw and from the comments in my own provider code; I did not re-read OpenRouter’s documentation page while writing this.