mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't … #1417
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1417
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @kolacheee on GitHub (Jun 22, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2792
Summary
Tool calls do not work for OpenAI-compatible backends whose model emits a non-native tool-call format in 2.0.0. This is not limited to the bundled llama.cpp sidecar — it also affects Custom (OAI-Compatible) connections pointed at llama.cpp, LM Studio, and KoboldCPP, and remote models that free-text their tool calls such as GLM 5 / 5.1 / 5.2 and DeepSeek v4 (via Custom OAI / OpenRouter / Zhipu / DeepSeek) — all confirmed via user reports + code, including a controlled test at temperature 0 in a fresh chat that still fails (so it is a format/parsing problem, not sampling or context). The underlying defect is that the OpenAI-compatible provider has no textual tool-call fallback, so any backend that returns its tool call as the model's trained/free-text format (instead of native
tool_callsJSON) has the call leaked into the chat as text — and, on the Professor Mari path, can spiral into a visible repeat-loop of the reasoning preamble (see fix 4/5).Symptoms by path:
toolcalltoken wrapper or atool_codeblock) instead of executing and rendering as a tool pill. Occasionally — when the model happens to emit exactly the JSON shape Mari asks for — it works and renders a pill, which makes the bug look intermittent.This is a regression: the same Gemma + llama.cpp setup tool-calls fine in SillyTavern/Cline (which parse llama.cpp's native textual tool-call format), and worked in 1.6.1, which had neither of the two gating mechanisms introduced in the 2.0 cycle.
Symptom & UX impact
mari_db-triggering request prints the model's internal tool-call token as a normal assistant message. No tool runs, no data comes back.Steps to reproduce
Bundled sidecar:
enableNativeToolCalls: false).mari_db). Observed: the model's tool-call token leaks as a normal Mari message; no pill, no tool result. (Occasionally a request where the model emits exactly{"tool_calls":[{"name":"…","arguments":{…}}]}renders correctly as a pill.)Custom (OAI-Compatible) connection — llama.cpp / LM Studio / KoboldCPP:
llama-server(started without--jinja+ a tool template), LM Studio, or KoboldCPP. (Setting "treat as local endpoint" routes Mari through the JSON protocol; either way the native path has no textual fallback.)<|tool_call>…,<tool_code>…, or malformed JSON); no pill, no tool result, no error.Root cause (file:line trace)
Two distinct, mutually reinforcing failures — both reachable by Custom local connections, not just the sidecar.
A. Professor Mari workspace path: brittle JSON-only tool-call parser (the leak)
MARI_SYSTEM_PROMPTis hardcoded atpackages/server/src/services/professor-mari/workspace-agent.service.ts:215.The JSON-only protocol is gated on a local flag, not on "is sidecar":
treatAsLocalEndpointis a real per-connection flag (packages/server/src/db/schema/connections.ts:66, default"false") that users enable for Custom local endpoints. So a Custom OAI connection with "treat as local" on routes through the samerunJsonToolProtocol(workspace-agent.service.ts:1119-1129) as the sidecar.runJsonToolProtocolinjectsjsonToolProtocolInstruction(:515-531) asking the model to emit{"tool_calls":[{"name":…,"arguments":{}}]}, then parses withparseJsonToolProtocolCalls(:565), which is brittle:extractJsonToolPayload(:533-554) only accepts the whole trimmed string as JSON, a fenced```jsonblock, or the substring between the first{and last}.rawJsonToolCalls(:556-563) only recognizestool_calls/toolCalls/calls/tool_call/toolCall, or a top-levelname.llama.cpp / LM Studio / Kobold GGUFs emit their trained format instead (a piped
toolcalltoken wrapper, atool_codeblock, or function-call XML). The first-to-last-brace slice yields an object whose only key is e.g.command: it JSON-parses but has noname/tool_calls, so the parser returns[], and:The raw text is then rendered/persisted via
pushTextDelta(:1131). No fallback recognizes textual/native-token formats.B. Main assistant / agents path: OAI-compatible provider only assembles native
tool_calls(no textual fallback)packages/server/src/services/llm/providers/openai.provider.ts:1219—normalizeToolCalls(choice?.message?.tool_calls)only.openai.provider.ts:1333-1377— assembles only fromdelta.tool_calls.contentfor a textual tool call (<|tool_call>…<tool_call|>,<tool_code>, fenced```json, or bare top-level JSON). So for any OAI-compatible local backend returning its tool call as content,toolCallsis empty and the call leaks as text. This is provider-wide and applies to every Custom OAI connection, not just the sidecar.Sidecar-only gate (why sidecar throws but Custom leaks):
SIDECAR_DEFAULT_CONFIG.enableNativeToolCallsisfalse—packages/shared/src/types/sidecar.ts:293.buildLlamaArgsonly appends--jinja(which makes the bundledllama-serverexpose OpenAI-compatible tool calls) when that flag is on —packages/server/src/services/sidecar/sidecar-launch-plan.ts:35-38.assertToolCallsAvailablethrows when tools are requested with the flag off —packages/server/src/services/llm/providers/local-sidecar.provider.ts:39-43. This is sidecar-only. A Custom connection has no such gate, so it does not error — it silently leaks (matches the Custom-connection reports).Per-backend nuance:
llama-server) only exposes nativetool_callswhen launched with--jinjaand a chat template matching the model's tool format. A user's own server (Custom connection) usually isn't started that way → textual leak.Why this is a regression from 1.6.1
Both gating mechanisms are new in the 2.0 cycle: the native-tool gate +
--jinjaplumbing (commitc29ed255, #2646) and therunJsonToolProtocol/extractJsonToolPayload/shouldUseJsonToolProtocolscaffolding (commitcaca4e0d). 1.6.1 had neither. The same setups that tool-call fine in Cline/SillyTavern (which parse the native textual format) now leak (Mari + Custom) or throw (sidecar agents). The "works at exact JSON, repeats at low temp" symptom is consistent: when the model complies with the requested JSON it parses; when it falls back to its trained format the call is returned as content with no result fed back, so the loop re-asks and repeats the malformed call.Suggested fix
(1) Primary — a tolerant textual tool-call fallback, homed in the OpenAI-compatible provider so it covers ALL local OAI backends.
Add a shared parser that, when native
tool_callsis empty butcontentcontains a recognizable tool call, parses it and surfaces it as atoolCallsresult. Wire it into the OAI provider's tool-call assembly (openai.provider.ts:1219non-streaming and:1333-1377streaming) and share it with Mari'srunJsonToolProtocol(workspace-agent.service.ts:603). Recognize, in order:tool_callsJSON (current behavior),toolcalltoken form (<|tool_call>… optionalcall:prefix, tool name, optional brace object …<tool_call|>),tool_codeblocks,```jsonblocks,name+arguments/toolobjects,<tool_call>…</tool_call>/<tool_call>…</arg_value>wrappers (tolerant of mismatched close tags) around a command-style payload — e.g. DeepSeek/GLM emit<tool_call>mari db tables</arg_value>; map the leading token to the matching tool (mari_db) and the remainder to its args ({command: "tables"}/{args: "db tables"}),parsing arguments leniently and matching captured names against the known tool set. Only return raw text when no known tool name matches (so plain prose is unaffected). Sketch:
(2) Secondary — stop the bundled sidecar agent path being dead on arrival.
Replace the hard throw at
local-sidecar.provider.ts:39-43with auto-passing--jinjawhen a request carries tools (or defaultenableNativeToolCallstotrue,sidecar.ts:293), paired with the tolerant parser above so non-conforming models degrade gracefully rather than throwing.(3) Alignment.
Prefer native jinja tool calls for templated models (what Cline/ST use), reserving the custom JSON protocol for backends with no working template — always paired with the tolerant fallback so trained-format output is recognized regardless of connection type.
(4) Force greedy/low sampling for the Mari JSON-protocol tool turn (fixes the GLM/remote repeat-loop).
runJsonToolProtocolruns the tool-call generation at the user's RP temperature —provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false })(workspace-agent.service.ts:602) — with no override. At high temp (e.g. GLM @ 0.8) the model free-texts its reasoning preamble and degenerates into a repeat loop ("Let me find Portia's character and any linked lorebooks." ×N) instead of committing to the tool JSON. Overridetemperature: 0(andtopP: 1) for that single tool-protocol generation, mirroring how the local-sidecar provider already forces greedy sampling for structured output. This applies to remote OAI models too (GLM / DeepSeek via Custom OAI / OpenRouter / Zhipu), not just local backends. Caveat (confirmed by a temp-0 + fresh-chat test): this is necessary but not sufficient — DeepSeek/GLM still emit their trained<tool_call>…</arg_value>format at temp 0, so fix (1) [tolerant parser] and preferring native tool-calling for capable providers are the load-bearing fixes; (4) only improves format compliance at the margin.(5) Add a repeat / no-progress guard.
When a tool turn yields no parseable tool call (or the model repeats the same preamble), stop and surface an error / fall back rather than letting it spiral into the visible repeat loop. This bounds the degeneration even for models whose output the tolerant parser still cannot recognize.
Alternatives considered: tightening the Mari prompt (rejected — does not control what the model emits; leak persists on trained-format fallback); only flipping
enableNativeToolCalls(rejected as sole fix — does not help Custom connections or models whose native output differs from strict OpenAI JSON, and leaves the OAI provider with no textual fallback).Affected files
packages/server/src/services/llm/providers/openai.provider.ts(:1219,:1333-1377) — primary home for the textual fallback (covers Custom OAI connections + sidecar + agents)packages/server/src/services/professor-mari/workspace-agent.service.ts(:215,:511-513,:515-531,:533-563,:565-584,:586-606,:1119-1131)packages/server/src/services/llm/providers/local-sidecar.provider.ts(:31-43)packages/server/src/services/sidecar/sidecar-launch-plan.ts(:35-38)packages/shared/src/types/sidecar.ts(:293)packages/server/src/db/schema/connections.ts(:66—treatAsLocalEndpoint)Validation
pnpm checkpasses (TypeScript + ESLint).<|tool_call>token form, (b) atool_codeblock, (c) a fenced```jsonblock — each asserting exactly one tool call is produced.--jinja): tool calls execute (pill + result), not leaked text.AI-investigated against released 2.0.0 (
main); verify before fixing. Scope expanded from the original (sidecar-only) framing after a user reported the same failure on Custom connections to llama.cpp / LM Studio / KoboldCPP.@kolacheee commented on GitHub (Jun 22, 2026):
Why Custom connections are affected too
There are two code paths, and Custom local connections fall into both failure modes:
1. Professor Mari path — the JSON-only protocol gates on a local flag, not on "is sidecar".
packages/server/src/services/professor-mari/workspace-agent.service.ts:512treatAsLocalEndpointis a real per-connection flag (packages/server/src/db/schema/connections.ts:66, default"false") that users set for Custom local endpoints. So a Custom OAI connection with "treat as local" on routes throughrunJsonToolProtocoland the same brittle parser (extractJsonToolPayload/rawJsonToolCalls,:533-563) that only accepts{"tool_calls":[…]}-shaped JSON. llama.cpp / Kobold / LM Studio emitting their trained textual format (<|tool_call>token,tool_codeblock, function-call XML) → parser returns[]→ raw text is returned unchanged (:603-605) and rendered as a Mari message. Identical leak to the sidecar.treatAsLocalEndpointis off, Mari instead uses the native path below — which has the same gap. Either way it leaks.2. Main assistant / agents path — the OAI-compatible provider only assembles native
tool_calls, with no textual fallback.packages/server/src/services/llm/providers/openai.provider.ts:1219—normalizeToolCalls(choice?.message?.tool_calls)only.openai.provider.ts:1333-1377— assembles only fromdelta.tool_calls.contentfor a textual tool call (<|tool_call>…<tool_call|>,<tool_code>, fenced```json, or bare top-level JSON). So for any OAI-compatible local backend that returns its tool call as content instead of nativetool_calls,toolCallsis empty and the call leaks into the chat.assertToolCallsAvailablethrowing "native tool calls are disabled",local-sidecar.provider.ts:39-43) does not apply to Custom connections — they have no such gate, so they don't error, they just silently leak. That matches this report exactly.Per-backend nuance
llama-server) only exposes OpenAI-style nativetool_callswhen launched with--jinjaand a chat template that matches the model's tool format. A user's ownllama-server(Custom connection) usually isn't started that way, so it returns the model's trained textual format → leaks.tool_callsenvelope) → leaks.This is why "encourage raw JSON" sometimes works (the model happens to emit the exact shape the parser accepts) and lower temperature makes the repeat-loop worse (stronger adherence to the trained textual format).
Fix — same shape, broader home
The fix from the original write-up still applies, but it should live where it covers all OAI-compatible connections, not just the sidecar/Mari:
openai.provider.tsnon-streaming:1219and streaming:1333-1377): when nativetool_callsis empty butcontentcontains a recognizable tool call, parse it and surface it as atoolCallsresult instead of as text. Recognize the common forms: the<|tool_call>…<tool_call|>token wrapper,<tool_code>…</tool_code>, a fenced```jsonblock, and a bare top-level JSON object withname/arguments(ortool_calls/tool_call). Share this parser with Mari'srunJsonToolProtocolso both paths use one implementation.--jinja/enableNativeToolCalls) as the preferred route, but the fallback above is what makes Custom llama.cpp/LM Studio/Kobold connections work without per-user server reconfiguration.Suggested scope/title update: this is broader than "sidecar" — it's "local OpenAI-compatible tool calls leak as text (sidecar + Custom llama.cpp/LM Studio/KoboldCPP) because the OAI provider has no textual tool-call fallback."
AI-investigated against the released 2.0.0 (
main) tree; please verify the traces before fixing.@lyrakat commented on GitHub (Jun 22, 2026):
Issue isn't limited to professor mari, nor is it limited to local sidecar. It also affects tool calls in conversations using a local model on the OpenAPI compatible connection (koboldcpp / gemma4 26b)
@lyrakat commented on GitHub (Jun 22, 2026):
Because this issue is related to my work on custom tools for ME I've been poking around it alongside Claude (opus 4.8) and in regards to the issue it also had this to say:
As for the "twp ways to handle it" I don't think force non-streaming is a good approach, as unless I'm mistaken this would break tool calls in thinking (user message > think > tool call > think more with results > tool call > etc > final reply), though I could be wrong about that.
I am not sure if this is valuable feedback entirely so sorry for that. It's a little over my head.
Also fwiw, my setup is koboldcpp with --jinja and --jinjatools, the most up to date jinja template, gemma4 26b
@kolacheee commented on GitHub (Jun 22, 2026):
@lyrakat Thank you for your feedback! The ticket has been updated to reflect the true scope of the issue. Marinara will decide how best to tackle this bug.
@kolacheee commented on GitHub (Jun 22, 2026):
GLM is the same defect, triggered remotely
Professor Mari on GLM (e.g. GLM 5.2 @ temp 0.8) gets stuck repeating its reasoning preamble — "Let me find Portia's character and any linked lorebooks." over and over — instead of executing the tool:
runJsonToolProtocol(workspace-agent.service.ts:586-606) injects the "emit{tool_calls:[…]}JSON" instruction, does one generation, then parses withparseJsonToolProtocolCalls(:565-583), which requires an exactname+ known-tool JSON shape.tool_calls). The parser finds nothing → returns the raw text → no tool result is fed back → the model re-asks / degenerates into the visible repeat loop.This is the same "works at exact JSON, fails on the model's free-text format" pattern already described here. The expanded scope of this issue ("any OAI-compatible backend whose model emits a non-native tool format") already covers GLM, whether reached via a Custom OAI connection, OpenRouter, or Zhipu's API.
Why some GLM users work and others don't (it is NOT the model version)
Reporters confirm GLM 5, 5.1 and 5.2 all behave the same, so it is not a model-version problem. Two config/runtime variables decide the outcome:
tool_callscome back. If the GLM connection/proxy returns proper OpenAItool_callsand Mari uses the native path → works. If GLM free-texts the call (or the connection routes through the JSON protocol) → the no-fallback parser fails.runJsonToolProtocolruns the tool-call turn at the user's temperature —provider.chatComplete(fallbackMessages, { ...baseOptions, stream: false })at:602— with no greedy/low-temp override. At temp 0.8 the model is far more likely to free-text and fall into a repetition loop. (Contrast: the local-sidecar provider forcestemperature: 0for structured output; the Mari JSON protocol does not.)Two fix additions (now folded into the issue body)
On top of the tolerant textual fallback parser already proposed:
runJsonToolProtocol(:602), overridetemperature: 0(andtopP: 1) for that single generation so the model commits to the tool JSON instead of free-texting at the user's RP temperature.AI-investigated against the released 2.0.0 (
main) tree; verify before fixing.@SpicyMarinara commented on GitHub (Jun 22, 2026):
Addressed in PR #2790 / commit acab1fba: OpenAI-compatible tool requests now use non-streaming completion when tools are present, parse textual tool-call fallbacks, and local sidecar no longer hard-fails when native llama.cpp tool calls are disabled.
@kolacheee commented on GitHub (Jun 22, 2026):
New test data (DeepSeek 4 + GLM, temp 0, fresh chat)
A user re-ran with controlled conditions: temperature 0 and a brand-new chat (to rule out sampling and context pollution). Tool calls still fail to format, on both GLM and DeepSeek v4 Pro. The models emit their trained tool-call format as text, e.g.:
Two important takeaways:
1. It is purely a FORMAT/PARSING problem — not sampling. Since temp 0 + a fresh chat still fail, the earlier "force greedy sampling" fix (item 4) is necessary but not sufficient: these models simply don't speak the requested JSON protocol regardless of temperature. The tolerant fallback parser (fix 1) is the load-bearing fix.
2. The emitted format is currently 100% unparseable. The protocol asks for
{"tool_calls":[{"name":…,"arguments":{}}]}(workspace-agent.service.ts:523-525), andextractJsonToolPayload(:533-554) only looks for JSON — the whole string as JSON, a fenced```jsonblock, or the substring between the first{and last}. The DeepSeek/GLM output<tool_call>mari db tables</arg_value>contains no{or}at all, so there are zero JSON candidates →extractJsonToolPayloadreturnsnull→parseJsonToolProtocolCallsreturns[]→ the raw text is returned and shown. (GLM then degenerates into the agree/repeat loop; DeepSeek "at least created the agent on text" — both fail to produce a tool call.)Note the shape: an XML-ish
<tool_call>…</arg_value>wrapper (often with mismatched open/close tags) around a command-style invocation (mari db tables), not a JSON args object. The parser needs to handle both the wrapper and the non-JSON payload.Refined fix priority
Prefer NATIVE tool calling for providers/models that support it (now the top priority for remote models). DeepSeek and GLM via their OpenAI-compatible APIs return proper native
tool_callswhen the request carriestoolsand the model's chat template is used. The Mari path forces the custom JSON-text protocol whenevershouldUseJsonToolProtocolis true (isLocalSidecarConnection || treatAsLocalEndpoint,:512), which bypasses native tool calling and fights the model's training. For remote OAI providers that support native tools, route through nativetool_callsinstead of the JSON-text protocol — that alone should fix DeepSeek/GLM.Make the tolerant fallback parser handle this XML/command format, not just JSON: recognize
<tool_call>…</tool_call>/<tool_call>…</arg_value>wrappers (tolerant of mismatched close tags), and map a command-style payload (mari db tables) to the matching tool + args (e.g.mari_dbwith{command: "tables"}/{args: "db tables"}), matching the leading token against the known tool set. This is the safety net for any backend that can't do native tools.Item 4 (force temp 0/greedy) stays, but as a minor compliance aid only — this test shows it does not fix the format mismatch on its own.
This keeps the throughline: the bug is the missing tolerant parsing + over-eager routing through a JSON-text protocol that many capable models (Gemma, GLM, DeepSeek, local llama.cpp/LM Studio/Kobold) won't follow.
AI-investigated against the released 2.0.0 (
main) tree; verify before fixing.@lyrakat commented on GitHub (Jun 23, 2026):
This still seems to happen in 2.0.2
[GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't …to [GH-ISSUE #2792] [Issue]: OpenAI-compatible tool calls leak as raw text / repeat-loop on models that emit a non-native format (sidecar + Custom llama.cpp/LM Studio/KoboldCPP + remote GLM/DeepSeek) — no textual tool-call fallback; Mari & agents can't …