[PR #7486] [MERGED] fix(llm): retry strict-template role alternation errors with merged turns #7755

Closed
opened 2026-10-24 04:07:12 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/7486
Author: @SpicyMarinara
Created: 10/12/2026
Status: ✅ Merged
Merged: 10/12/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/7457-custom-alternate-roles-retry


📝 Commits (3)

  • eae3aca fix(llm): retry strict-template role alternation errors with merged turns
  • 2499fde fix(llm): narrow the previous turn before merging for tsc
  • a0790ef fix(llm): retry llama.cpp's two-assistant prefill rejection and log the retried prompt

📊 Changes

3 files changed (+290 additions, -43 deletions)

View changed files

📝 docs/TROUBLESHOOTING.md (+1 -0)
📝 packages/server/src/services/llm/providers/openai.provider.ts (+115 -43)
📝 scripts/regressions/provider-compat.regression.ts (+174 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #7457

Why this change

  • Local models with a strict Mistral-family chat template (for example Rocinante on llama.cpp) reject any request with two messages in a row from the same role. llama.cpp answers HTTP 400 "conversation roles must alternate user/assistant/...". Several flows send that shape after the prompt is assembled: Professor Mari's repair rounds, continue/swipe with an Assistant Prefill, and impersonate. So the user got a raw parser error instead of a reply.
  • Only the Anthropic provider merged same-role turns. The OpenAI-compatible path (Custom connections, and the bundled Local Model that delegates to it) sent them through unchanged.

What changed

  • Nothing that worked before stops working. A request the endpoint accepts is sent exactly as before, in one request.
  • When an OpenAI-compatible endpoint rejects a Chat Completions request with a "roles must alternate" error, or with llama.cpp's own "Cannot have 2 or more assistant messages at the end of the list." (its prefill check runs before any template, so continue/swipe with an Assistant Prefill hits it on every llama.cpp model), Marinara retries it once with the messages reshaped for a strict template:
    • the leading system messages are joined into one;
    • later system messages join the user turn around them;
    • back-to-back messages from the same role are joined with a blank line, with images kept in order as content parts;
    • a [Start] user turn goes before an opening assistant greeting (the same placeholder the Anthropic provider uses);
    • tool results and assistant tool calls are never merged.
  • This covers normal generation, continue/swipe prefill, impersonate, agents and Professor Mari, since they all go through chat() / chatComplete().
  • If the retry is rejected the same way, or nothing could be merged, the error now ends with a plain next step: set Post-Processing Messages to Single User Message, or serve the model with a less strict chat template.
  • The two Chat Completions call sites share one postChatCompletions helper instead of repeating the fetch-and-throw code.
  • With UI debug mode or DEBUG_AGENTS on, the retried messages are logged at the visible level, so the debug log shows the prompt the model actually received.
  • On the Mistral API, the filter that drops Mistral's repeat of an Assistant Prefill now uses the prefix actually sent, so a merged prefill is not echoed back into the reply after a retry.
  • The match is on the error text, not the provider kind, so OpenRouter, Arli and other OpenAI-compatible hosts that serve strict templates get the same retry.
  • Troubleshooting guide: one new bullet under Connection and generation errors. Translation follow-up: #7485.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Notes (agent-run commands):

Head a0790ef70 (validated after the review fixes):

  • pnpm install --frozen-lockfile --prefer-offline and pnpm build:shared: OK.
  • pnpm check: exit 0.
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/provider-compat.regression.ts: PASSED. The #7457 block runs a fake OpenAI-compatible server that follows llama.cpp's order. It runs the prefill check first, which returns "Cannot have 2 or more assistant messages at the end of the list." for two trailing assistant messages. Then it runs the Mistral v3 Tekken alternation check and returns llama.cpp's real 400 body. The block covers:
    • a non-streaming retry (system + system, greeting first, mid-chat system, image parts, history ending on assistant + prefill, which first hits the two-assistant check);
    • a streaming impersonate-style retry run with debugMode: true at warn, which asserts the retried messages are logged;
    • a Mistral API retry, where the merged prefix that Mistral repeats is dropped from the reply;
    • a retry that fails again (exactly two requests, tool turns never merged, actionable error);
    • an accepting endpoint, which receives the original messages in one request.
  • Each fix proven by reverting it alone, with the regression failing every time:
    • PR-head provider (2499fded5): Custom OpenAI-compatible endpoint error 400: Cannot have 2 or more assistant messages at the end of the list.
    • with only the trigger fix: debug mode logs the retried messages fails;
    • with the trigger and log fixes but the old echo filter: the Mistral reply is 'Previous reply.\n\nPrefillmerged' instead of 'merged'.
  • node ./scripts/run-regressions.mjs --filter mistral-reasoning-output and --filter generation-parameter-relevance: PASSED (they cover normalizeMistralRequest, which changed).
  • coderabbit review --agent --committed --base-commit 9fd6e0900 (merge-base with staging) on a0790ef70: completed, 0 findings in the 3 reviewed files. The first two attempts were rate limited, and the third ran. GitHub CodeRabbit was also rate limited on this push.
  • GitHub review threads: three CodeRabbit threads were answered and resolved. Two were fixed (debug log of the retried prompt, Mistral echo filter built from the final request). One was declined, with the reason given in its thread (keep the alternation hint only when the shown error is an alternation error).

Manual verification notes

  • Serve a strict Mistral-template model with llama.cpp (for example Rocinante-X-12B-v1b-Q5_K_M.gguf with no chat-template-file, so its built-in Tekken template applies) and add it as a Custom (OAI-Compatible) connection.
  • In a roleplay chat, set an Assistant Prefill, then use Continue on the last AI message. Verify a reply streams instead of a 400 toast, and the server log shows one "retrying once with consecutive same-role messages merged" warning.
  • Repeat the Continue + Assistant Prefill step with a llama.cpp model that has a lenient template (for example a ChatML model). Before this fix, llama.cpp's "Cannot have 2 or more assistant messages at the end of the list." 400 appeared even with lenient templates. Verify a reply streams.
  • Turn on debug mode in the UI, keep the server's default log level, and trigger a retry. Verify the server log shows "[debug/openai] role-alternation retry messages" with the merged messages.
  • Use Impersonate in the same chat. Verify it generates instead of failing.
  • Ask Professor Mari something that triggers a protocol or verification repair round on the same connection. Verify she answers instead of "Professor Mari could not answer right now. Custom OpenAI-compatible endpoint error 400".
  • Switch to a hosted provider that accepts back-to-back roles (for example OpenRouter with a non-Mistral model). Verify replies are unchanged and no retry warning is logged.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

Docs: docs/TROUBLESHOOTING.md gains one bullet. Translation follow-up: #7485. No CHANGELOG edit, per the 2026-10-12 release-notes policy.

UI evidence (if applicable)

No UI changes. The only user-visible text is the server error message.

Summary by CodeRabbit

  • Bug Fixes
    • Improved compatibility with models that require alternating user and assistant messages. When such a request fails, Marinara adjusts the message sequence and retries once; if the error persists, it provides a relevant troubleshooting hint.
  • Documentation
    • Added guidance for resolving persistent chat-template errors, including how to configure message post-processing or choose a less restrictive model template.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/7486 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/12/2026 **Status:** ✅ Merged **Merged:** 10/12/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/7457-custom-alternate-roles-retry` --- ### 📝 Commits (3) - [`eae3aca`](https://github.com/Pasta-Devs/Marinara-Engine/commit/eae3aca829febc48428c6c854bb45bc5c2f85b16) fix(llm): retry strict-template role alternation errors with merged turns - [`2499fde`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2499fded57c723f4a42e415e6c53ba451e36c32f) fix(llm): narrow the previous turn before merging for tsc - [`a0790ef`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a0790ef701a0d50f1daf8de8480d2066359fef38) fix(llm): retry llama.cpp's two-assistant prefill rejection and log the retried prompt ### 📊 Changes **3 files changed** (+290 additions, -43 deletions) <details> <summary>View changed files</summary> 📝 `docs/TROUBLESHOOTING.md` (+1 -0) 📝 `packages/server/src/services/llm/providers/openai.provider.ts` (+115 -43) 📝 `scripts/regressions/provider-compat.regression.ts` (+174 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. ## Linked issue Closes #7457 ## Why this change - Local models with a strict Mistral-family chat template (for example Rocinante on llama.cpp) reject any request with two messages in a row from the same role. llama.cpp answers HTTP 400 "conversation roles must alternate user/assistant/...". Several flows send that shape after the prompt is assembled: Professor Mari's repair rounds, continue/swipe with an Assistant Prefill, and impersonate. So the user got a raw parser error instead of a reply. - Only the Anthropic provider merged same-role turns. The OpenAI-compatible path (Custom connections, and the bundled Local Model that delegates to it) sent them through unchanged. ## What changed - Nothing that worked before stops working. A request the endpoint accepts is sent exactly as before, in one request. - When an OpenAI-compatible endpoint rejects a Chat Completions request with a "roles must alternate" error, or with llama.cpp's own "Cannot have 2 or more assistant messages at the end of the list." (its prefill check runs before any template, so continue/swipe with an Assistant Prefill hits it on every llama.cpp model), Marinara retries it **once** with the messages reshaped for a strict template: - the leading system messages are joined into one; - later system messages join the user turn around them; - back-to-back messages from the same role are joined with a blank line, with images kept in order as content parts; - a `[Start]` user turn goes before an opening assistant greeting (the same placeholder the Anthropic provider uses); - tool results and assistant tool calls are never merged. - This covers normal generation, continue/swipe prefill, impersonate, agents and Professor Mari, since they all go through `chat()` / `chatComplete()`. - If the retry is rejected the same way, or nothing could be merged, the error now ends with a plain next step: set **Post-Processing Messages** to **Single User Message**, or serve the model with a less strict chat template. - The two Chat Completions call sites share one `postChatCompletions` helper instead of repeating the fetch-and-throw code. - With UI debug mode or `DEBUG_AGENTS` on, the retried messages are logged at the visible level, so the debug log shows the prompt the model actually received. - On the Mistral API, the filter that drops Mistral's repeat of an Assistant Prefill now uses the prefix actually sent, so a merged prefill is not echoed back into the reply after a retry. - The match is on the error text, not the provider kind, so OpenRouter, Arli and other OpenAI-compatible hosts that serve strict templates get the same retry. - Troubleshooting guide: one new bullet under **Connection and generation errors**. Translation follow-up: #7485. ## Validation - [ ] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed `CONTRIBUTING.md` Notes (agent-run commands): Head `a0790ef70` (validated after the review fixes): - `pnpm install --frozen-lockfile --prefer-offline` and `pnpm build:shared`: OK. - `pnpm check`: exit 0. - `node ./scripts/run-regressions.mjs --filter scripts/regressions/provider-compat.regression.ts`: PASSED. The #7457 block runs a fake OpenAI-compatible server that follows llama.cpp's order. It runs the prefill check first, which returns "Cannot have 2 or more assistant messages at the end of the list." for two trailing assistant messages. Then it runs the Mistral v3 Tekken alternation check and returns llama.cpp's real 400 body. The block covers: - a non-streaming retry (system + system, greeting first, mid-chat system, image parts, history ending on assistant + prefill, which first hits the two-assistant check); - a streaming impersonate-style retry run with `debugMode: true` at `warn`, which asserts the retried messages are logged; - a Mistral API retry, where the merged prefix that Mistral repeats is dropped from the reply; - a retry that fails again (exactly two requests, tool turns never merged, actionable error); - an accepting endpoint, which receives the original messages in one request. - Each fix proven by reverting it alone, with the regression failing every time: - PR-head provider (`2499fded5`): `Custom OpenAI-compatible endpoint error 400: Cannot have 2 or more assistant messages at the end of the list.` - with only the trigger fix: `debug mode logs the retried messages` fails; - with the trigger and log fixes but the old echo filter: the Mistral reply is `'Previous reply.\n\nPrefillmerged'` instead of `'merged'`. - `node ./scripts/run-regressions.mjs --filter mistral-reasoning-output` and `--filter generation-parameter-relevance`: PASSED (they cover `normalizeMistralRequest`, which changed). - `coderabbit review --agent --committed --base-commit 9fd6e0900` (merge-base with staging) on `a0790ef70`: completed, 0 findings in the 3 reviewed files. The first two attempts were rate limited, and the third ran. GitHub CodeRabbit was also rate limited on this push. - GitHub review threads: three CodeRabbit threads were answered and resolved. Two were fixed (debug log of the retried prompt, Mistral echo filter built from the final request). One was declined, with the reason given in its thread (keep the alternation hint only when the shown error is an alternation error). ### Manual verification notes - [ ] Serve a strict Mistral-template model with llama.cpp (for example `Rocinante-X-12B-v1b-Q5_K_M.gguf` with no `chat-template-file`, so its built-in Tekken template applies) and add it as a **Custom (OAI-Compatible)** connection. - [ ] In a roleplay chat, set an **Assistant Prefill**, then use **Continue** on the last AI message. Verify a reply streams instead of a 400 toast, and the server log shows one "retrying once with consecutive same-role messages merged" warning. - [ ] Repeat the **Continue** + **Assistant Prefill** step with a llama.cpp model that has a lenient template (for example a ChatML model). Before this fix, llama.cpp's "Cannot have 2 or more assistant messages at the end of the list." 400 appeared even with lenient templates. Verify a reply streams. - [ ] Turn on debug mode in the UI, keep the server's default log level, and trigger a retry. Verify the server log shows "[debug/openai] role-alternation retry messages" with the merged messages. - [ ] Use **Impersonate** in the same chat. Verify it generates instead of failing. - [ ] Ask Professor Mari something that triggers a protocol or verification repair round on the same connection. Verify she answers instead of "Professor Mari could not answer right now. Custom OpenAI-compatible endpoint error 400". - [ ] Switch to a hosted provider that accepts back-to-back roles (for example OpenRouter with a non-Mistral model). Verify replies are unchanged and no retry warning is logged. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) Docs: `docs/TROUBLESHOOTING.md` gains one bullet. Translation follow-up: #7485. No CHANGELOG edit, per the 2026-10-12 release-notes policy. ## UI evidence (if applicable) No UI changes. The only user-visible text is the server error message. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved compatibility with models that require alternating user and assistant messages. When such a request fails, Marinara adjusts the message sequence and retries once; if the error persists, it provides a relevant troubleshooting hint. * **Documentation** * Added guidance for resolving persistent chat-template errors, including how to configure message post-processing or choose a less restrictive model template. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-24 04:07:12 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#7755
No description provided.