[Bug] Unintended regressions for open-weights models and OOM crashes in recent parsing refactor (40b091a)
Hey @will-lamerton ! I'm back in the loop after some time off. First off, thank you for everything you do here - awesome new features and amazing work cleaning up the codebase. The new Bridge layer and streaming UI components are fantastic additions, and I completely understand the drive to simplify the parsing logic.
However, I think there may exist some level of misunderstanding on the intended redundancies introduced in the v2 parsers 3-layer system. From the perspective of external API endpoint users, having multiple JSON/XML parsers running alongside the Vercel AI SDK looks like unnecessary double-parsing. Easy assumption to make - I know as well as anyone, unraveling the v2 logic is entirely unpleasant (and downright inconvenient!).
That being said, your willingness to maintain that system has made Nanocoder the only publicly available project capable of running ANY local model (not an exaggeration) with near immunity to hallucination across JSON, XML, and even the complete absence of tool-call post-training in some cases. I've also been working on an additional parser for deepseek proprietary DSML tool structures to make this statement universal.
-- If at any point you realize I have fundamentally missed the point, please disregard and show me to the nearest directory. I acknowledge that I am still catching up while I chase down the cause for this sudden onset of erratic model performance..
So then, after testing the latest commit, my primary workhorses (GLM, Kimi, Qwen ) have largely lost their ability to chain thoughts, execute tools reliably, and now trigger JavaScript heap out of memory (OOM) fatal crashes. I dug into the changes to see what is happening and want to share a technical breakdown of why those redundant v2 layers were actually load-bearing walls.
The General Idea: When using Anthropic or OpenAI, their backend infrastructure acts as a massive janitor. Claude natively outputs XML with
Here's what I found:
- Native Tooling Mode (toolsDisabled = false)
The loop now uses a conditional check (or user setting, same result): if the model supports native tools, it skips the text parser entirely and assumes the text stream is perfectly clean conversational text.
over
"Ghost Echo": Many models suffer from some level of api bleed. They trigger the native tool API but simultaneously print the raw JSON payload to the text stream. Skipping the parser bypasses our deduplication logic, meaning raw JSON is now printed directly to the user's UI.
Type unSafety: normalizeLLMResponse was designed to ensure that any arbitrary object returned by a hallucinating model was safely coerced into a string. Because this step is bypassed, we can see fatal runtime crashes (like split is not a function).
- The XML Fallback Mode (toolsDisabled = true)
If we tell the system to expect XML, it now only parses for XML.
Missing JSON Fallback: Open-weights models are heavily fine-tuned on JSON. Even when prompted for XML, models frequently panic under complex reasoning and output a markdown-wrapped JSON block instead. In the v2 architecture, the unified parser caught this JSON fallback and executed the tool. Now, the system ignores it, treats the JSON as plain text, and the agent stalls out.
Loss of JSON Self-Correction: Because the JSON parsing utilities were removed, the system no longer detects syntactically broken JSON tool attempts. The self-correction loop never fires for JSON hallucinations, leaving the agent waiting indefinitely for user intervention.
Loss of Async Middleware & Type Safety: By deleting tool-processor.ts, the XML fallback processing is thrown directly into the conversation loop as a synchronous call (parseToolCalls(fullContent)). This bypasses the async normalizeLLMResponse middleware pipeline. Without that isolated layer, the XML fallback path no longer benefits from the universal type coercion (ensureString) and metadata generation that kept the legacy system stable and crash-free.
- Infinite Recursion - Memory Leak (OOM Crash) When the system does catch a malformed XML tool call, it aborts the turn and recursively prompts the model to self-correct. However, the recursive call to processAssistantResponse explicitly resets the iteration counter (emptyTurnCount: 0).
Because there is no cap on malformed retries (unlike empty turns), a model that repeatedly fails to format its XML enters an infinite, unthrottled async loop. It rapidly appends messages to the state array until Node.js exhausts its heap memory (~1.4GB) and hard-crashes.
Summary & Proposal This refactor beautifully optimizes the loop for perfect API compliance, but removes the multi-layer defense-in-depth required for raw open-weights AI inference. These models require their text streams to be sanitized, stripped of reasoning tags, and checked for hallucinations unconditionally.
I would very much like to collaborate on a way forward - is there a middle ground where we can keep the excellent new bridge layer, streaming, and some level of refactoring, but restore the universal parser, type safety,JSON fallback, and implement a strict cap on malformed retries to fix the OOM crashes?
I'm open to being wrong, so let me know your thoughts!
[P.S. I'm currently training a 71B param model specifically for nanocoder (many many thousands of long-context session traces)... so the parsing system IS of existential importance to me for what that's worth...]
Hey @cleyesode - welcome back! Genuinely appreciate the issue. You clearly went and read the diff carefully, and most of what you've called out is true. Let me walk through what I agree with, where I'd move the framing to, and a path forward that I think gets us where you want without rolling back the cleanup.
What you got right
I went back through 40b091a against main with your analysis open. Verified findings:
<think>tag leak on the native path - confirmed.stripThinkTags()only runs insideparseToolCalls(), andconversation-loop.tsxonly invokes that on thetoolsDisabled === truebranch. On the native pathcleanedContent = fullContentverbatim, and any<think>tokens that hit thetext-deltastream (rather thanreasoning-delta) leak straight into the assistant message and into history. More on the AI SDK side of this below.- Ghost Echo - confirmed. The deleted
tool-processor.tsranXMLToolCallParser.removeToolCallsFromContent()and the deletedjson-parser.tshad its analog. On the native path today, neither runs. A model that double-emits will display the JSON payload in the UI and re-feed it next turn. - JSON fallback when XML expected - confirmed.
parseToolCalls()is XML-only now. The "panicked into a fenced JSON block" failure mode is silently treated as plain text and the agent stalls. Self-correction never fires. - OOM / unbounded malformed-XML retries - confirmed. In
conversation-loop.tsxonly the empty-response branch (line 751) incrementsemptyTurnCount; the malformed-XML branch (line 297) and the unknown-tool branch (line 487) both reset to0. Each malformed iteration appends two messages viaMessageBuilder. There is no cap. A model stuck producing bad XML will inflate the message array until Node OOMs. That's just a bug. normalizeLLMResponsemiddleware loss - confirmed it's no longer in any production code path (still exported, still has a spec, but nothing calls it). I'd push back on this being a high-impact regression in practice —result.textfrom the AI SDK is always a string, and the XML-fallback path still callsensureStringinsideparseToolCalls. So the safety net is partially preserved where it matters most. But you're right that the universal coercion layer is gone.
On the AI SDK and <think> tags specifically
You called this out and I want to be precise about it because I think there's a common misconception. The Vercel AI SDK does not auto-strip <think> from text. There's an extractReasoningMiddleware (docs) that does exactly what you'd want - extracts tag-bracketed content and exposes it as reasoning instead of leaking into text - but it requires explicit opt-in via wrapLanguageModel. We don't wrap anywhere right now.
So what actually happens depends on the provider's protocol:
- Provider emits reasoning via the protocol (Anthropic, OpenAI Responses API for o-series, newer Ollama with thinking support, etc.) → SDK fires
reasoning-deltaevents → clean separation, our reasoning UI works, no leak. - Provider just streams
<think>as plain text (most generic OpenAI-compat endpoints serving GLM/Kimi/Qwen, including older Ollama and llama.cpp setups) -> tokens go totext-delta-> land infullText-> becomecleanedContenton the native path -> leak into UI and history.
So you're right about the population of models this hurts, and the fact that "Anthropic's backend acts as middleware" is exactly the asymmetry. Wrapping the model with extractReasoningMiddleware({ tagName: 'think' }) would close this for native-path models without needing to re-add the parser layer for it specifically.
Where I'd nudge the framing
The "load-bearing walls" frame had me wanting a rollback. I don't think we need one - every regression you raised has a tight fix that preserves the single-parse-site / toolsDisabled cleanup. Roughly:
| Regression | Fix | Size |
|---|---|---|
<think> leak |
Wrap the model with extractReasoningMiddleware({ tagName: 'think' }) in the client factory. Belt-and-braces: also call stripThinkTags() on fullContent before assigning cleanedContent. |
~5–10 lines |
| Ghost Echo | When toolCalls.length > 0 on the native path, run a small dedup pass over cleanedContent to strip JSON-tool-call-shaped substrings whose name matches an emitted call. Or simpler: always run XMLToolCallParser.removeToolCallsFromContent (it's idempotent if no XML present). |
~10 lines |
| JSON fallback in XML mode | Add a JSON-parse branch inside parseToolCalls that fires when XMLToolCallParser.hasToolCalls is false and content looks like a fenced JSON block. Don't need to restore the whole 267-line json-parser.ts — a 30–40 line subset covers the panicked-JSON case. |
~40 lines |
| OOM cap | Add malformedRetryCount?: number next to emptyTurnCount, increment only on the malformed-XML branch, gate at a MAX_MALFORMED_RETRIES = 2 constant, reset on any productive branch. Mirror the existing test in conversation-loop.spec.ts:377. |
~15 lines + 1 const + 1 test |
That's a few dozen lines total. v3 architecture stays intact, defense-in-depth comes back where it actually mattered, and we don't reintroduce the double-parse confusion the refactor was trying to kill.
Other things worth considering while we're here
experimental_repairToolCall- for native-path malformed arguments (different failure than your malformed-XML case), the SDK has built-in repair we're not using. Worth wiring up as a complementary defense. Caveat: there's an open SDK bug (vercel/ai#8240) where it doesn't fire on validation errors, so I wouldn't lean on it as primary.- DSML for DeepSeek - the parser you mentioned working on, I'd love to see what shape that takes. If it slots into the
parseToolCallsflow as another branch (try XML -> try JSON -> try DSML -> malformed), that'd compose nicely with the surgical fixes above. Want to share a sketch when you have one? - Test coverage gap - we have
conversation-loop.spec.tscovering the empty-turn cap but nothing for malformed-retry capping. I'd want a regression test landing in the same PR as the OOM fix.
Concrete next steps
I've taken the OOM cap myself - that one shouldn't sit. Happy to coordinate on the others if you want to grab any:
- OOM cap + regression test - I've patched this in
ebf45ed. <think>middleware + belt-and-braces strip - happy to take or hand off.- Ghost Echo dedup on native path - open.
- JSON fallback inside
parseToolCalls- this is the one closest to your ongoing parser work; if you want it, it's yours. Otherwise I'll get to it after 1.
If you'd rather group some of these into one PR rather than four or, if I've misinterrepted what you've said or you just think differently let me know :)
And yeah, the 71B for nanocoder thing sounds awesome - I can't wait to hear more about this. Genuinely glad you're back in the loop.
Hey @will-lamerton,
This response is exactly why I enjoy contributing to this project. Thank you for taking the time to address these concerns so quickly, and for jumping on the OOM cap right away. I completely agree with your framing - we definitely don't need a rollback, apologies for the jump-scare! Your proposed fixes appear to cleanly restore many of the defenses required for local models without the legacy bloat.
Good point on extractReasoningMiddleware, I was unaware Vercel had opt-in wrapper - I should probably brush up on these stardards; using that alongside stripThinkTags() fallback is the perfect native-feeling solution.
I can take Ghost Echo dedup and JSON fallback inside parseToolCalls and group them into a single PR. I'll condense the JSON fallback to specifically target panicked failures. I can wrap both of these in the next 2 - 3 days, some travel at the moment. But don't let me keep you waiting - feel free to complete if you happen to be there already. I'll push DSML branch separately.
I thought this might also be a good time to have you correct me on the overall path forward - here are my thoughts on toolsDisabled branching logic for open-weight models - some of these items have already been addressed - as recapped by GLM-4.7-Flash:
Current Capabilities Pipeline
| Core Capability / Defense | Native Path (toolsDisabled=false) |
XML Fallback (toolsDisabled=true) |
|---|---|---|
| Leverages Model's Native Fine-Tuning | ✅ Yes (Via Backend Jinja Templates) | ❌ No (Forces zero-shot text prompt) |
| Supports SDK Reasoning Streams | ✅ Yes | ❌ No |
Protects Context from <think> Leaks |
❌ No (Bypasses stripping) | ✅ Yes |
| Prevents "Ghost Echo" UI Bleed | ❌ No (Bypasses deduplication) | ✅ Yes |
| Catches XML Text Hallucinations | ❌ No (Bypasses parser) | ✅ Yes |
| Catches JSON Text Hallucinations | ❌ No (Bypasses parser) | ❌ No (json-parser removed) |
| Self-Corrects Broken JSON Syntax | ❌ No | ❌ No (Reclassified as valid) |
- Native path completely bypasses
parseToolCalls, it has no defense-in-depth against text-stream hallucinations. - XML path is currently missing the JSON safety nets required for models that panic under complex prompts.
- Looking into
experimental_repairToolCallas suggested, this seems to trip for Zod validation within the nativetool_callsarray, does not account for Ghost Echoes and markdown text-stream hallucinations of model ignoring native or dumping to content block.
Which brings us to the low hanging fruit:
Items Needing Attention
Native Path (toolsDisabled=false) |
XML Fallback (toolsDisabled=true) |
|---|---|
1. Belt-and-braces <think> stripping: Need to unconditionally strip <think> from the raw text stream to protect context history from generic endpoints. |
1. JSON Fallback Parser: Restore a targeted subset of the JSON parser to catch open-weights models that "panic" and output markdown JSON instead of XML. |
2. Un-gate parseToolCalls: Must run the parser even on the native path so the existing deduplication logic can actually catch and strip Ghost Echoes. |
2. JSON Runtime Trust: Restore JSON.parse validation to safely distinguish between broken tool calls and valid conversational JSON. |
3. The "Not an Echo" Safety Net: If the SDK returns 0 native tools, we still need to check the parsed text to see if the model hallucinated a tool call entirely in markdown. |
Which brings us to the paradox:
The Architectural Overlap: Final Product is Two Systems with Near Identical Function
While I am perfectly happy to submit PRs patching both of these pathways, I wanted to point out an interesting architectural reality we are accelerating toward.
When we force an open-weights model (which is heavily fine-tuned on JSON or custom tokens) to use the XML Fallback path, we are fighting its latent weights. This frequently causes "Format Collapse," where the model spits out a mix of XML and its native tokens. To fix the XML path, we have to rebuild the JSON safety nets. To fix the Native path, we have to un-gate the text parsers to catch Ghost Echoes and <think> leaks.
If we project this forward and apply all the fixes from Table 2, here is what the architecture will look like:
Table 3: The Post-Fix Reality
| Core Capability / Defense | Native Path (Fixed) | XML Fallback (Fixed) |
|---|---|---|
| Successfully Executes Tools | ✅ Yes (Via SDK + Parsers) | ✅ Yes (Via Parsers) |
| Leverages Model's Native Fine-Tuning | ✅ Yes (Via Backend Jinja Templates) | ❌ No (Architecturally blocked) |
| Supports SDK Reasoning Streams | ✅ Yes | ❌ No (Architecturally blocked) |
Protects Context from <think> Leaks |
✅ Yes | ✅ Yes |
| Prevents "Ghost Echo" UI Bleed | ✅ Yes | ✅ Yes |
| Catches XML Text Hallucinations | ✅ Yes | ✅ Yes |
| Catches JSON Text Hallucinations | ✅ Yes | ✅ Yes |
| Self-Corrects Broken JSON Syntax | ✅ Yes | ✅ Yes |
As you can see, by the time we finish patching both pathways to survive local models, we will have built the exact same defensive parsing system twice, achieving the exact same tool execution. Worse, the XML Fallback path still falls short because it fundamentally blocks the backend from using its native Jinja templates and reasoning streams. The fortified Native path does literally everything.
In the future, it might be worth considering dropping the toolsDisabled dichotomy entirely. The most robust approach for local AI is a single unified pipeline: Always send native tool schemas (so the backend can map them to the model's native training), and Always run the text stream through the defensive parsers to clean up the mess.
I'll get to work on the Ghost Echo and JSON fallback soon. Let me know if I'm looking at the disableTools pathways from the wrong angle - thanks!
@cleyesode - no apology required haha, the depth was the right call. Take whatever travel time you need; the OOM cap is in main as of ebf45ed so that major issue is stopped. Ghost Echo + JSON fallback as one PR works great. I'll grab <think> middleware + belt-and-braces strip in parallel so we don't block on each other, then merge in whatever order they land. DSML as its own branch makes sense.
On experimental_repairToolCall - your read matches mine. It operates inside the native tool-call structure (Zod schema validation, argument repair) and is blind to anything in the text stream. It's complementary at best, not a substitute for defensive parsing. Worth keeping in mind for the malformed-arguments case but not the load-bearing piece.
On the architectural argument:
This is the part of your reply I want to engage with properly, because I think you're mostly right and it's worth saying so explicitly - but with one structural caveat that changes the conclusion slightly.
You're correct that after the four targeted fixes land, the two paths converge to near-identical defensive surface area, and the XML fallback path is strictly worse on the things it gives up (Jinja templates, reasoning streams). Your Table 3 is a fair projection.
The caveat: toolsDisabled isn't only a defensive-parsing dichotomy. It's also doing two other jobs that don't go away when the parsers converge:
isToolSupportErrorretry (chat-handler.ts:366). Some providers/endpoints actively reject requests that includetoolswhen the model can't handle them - they throw before the model even runs. The current path catches this, retries withskipTools: true, and the request succeeds. Removing the gate entirely re-introduces these hard errors.- System prompt content. On the XML-fallback path, the system prompt is augmented upstream (in
useChatHandler) with full XML tool definitions. On the native path it isn't, because the SDK ships schemas natively. If we unify and always send native schemas, what does the model see in the system prompt for the rare case where the backend silently ignores native tools and the model falls back to writing text? Right now the XML defs in the prompt give it scaffolding. Without them, hallucinated tool calls go up. disableToolModelscurated list. This is a user/operator-facing config that lets people opt specific models out of native tools when they know the backend is broken. Useful escape hatch even in a unified world.
So the unified architecture you're sketching - "always send native schemas, always run defensive parsers" — is directionally right for the common case, but it doesn't fully replace toolsDisabled. What it might replace is the automatic gating of parseToolCalls. That's the actual defect in the current architecture: parsing being conditional on which path we're on, rather than being a universal pipeline stage.
What I think the post-fix architecture should look like:
Three things, ordered by cost:
Cheap and obviously right (the four fixes already on the table):
- Run
parseToolCalls(or its component pieces -stripThinkTags, dedup, JSON fallback) unconditionally on the text stream regardless oftoolsDisabled - Combine native
tool_calls+ parsed text-stream tool calls - Cap retries on every recursion site (already done for malformed XML)
This converges the defensive layer to a single pipeline. After this, toolsDisabled only controls what gets sent upstream (native schemas vs. XML in prompt) and the recovery path on isToolSupportError.
Worth evaluating after we have data:
- Whether
disableToolModelsis still pulling its weight. If our defensive parsers are catching the open-weights failure modes well, the curated list shrinks. If it stays useful, keep it as an explicit operator escape hatch. - Whether
disableTools=trueinagents.config.jsonshould be deprecated in favor of "send native schemas, always parse text." Probably yes for most users, but I'd want to test against the Ollama / llama.cpp / vLLM populations before pulling it.
Bigger conversation:
- Whether to drop
toolsDisabledfrom the response shape entirely. Once parsing is unconditional, the flag stops carrying useful runtime information. But that's a public-ish type change and I'd rather do it after we've shipped the fixes and run them in anger for a couple weeks.
So: I think your unified-pipeline instinct is right, and the path there is the four targeted fixes you and I are already working on. The fixes are the convergence. After they land, the dichotomy becomes thin enough that we can have the "do we drop it?" conversation with real evidence rather than projections.
On Jinja templates specifically:
Worth saying out loud because I don't think we've named it: you're right that the XML fallback path is fighting the model's training. Qwen, GLM, Kimi, DeepSeek all have specific tool-call formatting baked into their chat templates - when we send tools natively, Ollama/vLLM substitute them into that template and the model's fine-tuning kicks in. When we stuff tool definitions as plain text in a system prompt, that machinery is bypassed. That's a real cost, and one of the better arguments for getting toolsDisabled=true off the default path for models that can handle native tools.
The 71B you're training is going to have its own opinions about formatting. If you have a sense of what tool-call shape it'll prefer (native JSON, native XML, DSML, something custom), share it earlier rather than later - the fixes we're landing now should accommodate it cleanly, but I'd rather adapt the schema once than retrofit it.
Plan:
~- I'll take <think> middleware + strip fallback asap.~ - fixed in 65de8fd
~- You'll take Ghost Echo dedup + targeted JSON fallback in parseToolCalls, no rush, ping me when it's up.~ - fixed in 83f0db9
- DSML as its own branch, queue it after the above land so we're not stacking conflicting parser changes.
Sound good? And, separately, really glad you're approaching this collaboratively rather than as a "this is broken" haha. The framing here is exactly the kind of contribution that makes the project better.
I'll update this issue as things land :)
Sound good?
Sounds great! More detail from my side coming soon...
Hey! Just to let you know I spent some time fixing up the JSON tool fallback along with a bunch of other strengthening features - hope you don't mind but an additional piece of the puzzle needed to be done so I thought I would push it through after checking your branch :)
Most excellent - I'll be in touch more regularly starting soon, schedule has been difficult to predict lately. Thank you again for handling as you do - I'll review this week and PR if there is anything still to be contributed from my side.
Looking to the future, I dropped our hybrid-XML format and shifted training to play nicely with ai sdk, so disregard the previous concern (although these recent fortifications are still excellent for off-the-shelf open-weights jinjas, so nothing wasted). No training time lost really, still in CPT at the moment. More info to come later over the iterations - feel free to ping [email protected] (unpublished) if you have any input or particular workflows you would like to see hardcoded.