The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: MoA aggregator merges adjacent same-role messages only for destinations that reject them
teknium140778c74e27d
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 89d3357c119..f1a9d4541af 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1701,6 +1701,7 @@ _FALLBACK_REASON_LABELS = {FailoverReason.provider_policy_blocked: "provider policy blocked the request",FailoverReason.content_policy_blocked: "content policy blocked the request",FailoverReason.format_error: "request format rejected",+ FailoverReason.role_alternation: "adjacent same-role messages rejected",FailoverReason.invalid_encrypted_content: "encrypted reasoning state rejected",FailoverReason.multimodal_tool_content_unsupported: "multimodal tool content unsupported",FailoverReason.thinking_signature: "thinking signature rejected",diff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex 29bb23bee01..d6b0088d32f 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -50,6 +50,7 @@ class FailoverReason(enum.Enum):provider_policy_blocked = "provider_policy_blocked" # Aggregator account data/privacy policy excluded the only endpointcontent_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — don't retry unchangedformat_error = "format_error" # 400 bad request — abort or strip + retry+ role_alternation = "role_alternation" # Strict chat template rejected adjacent same-role messages — merge them for this destination and retryinvalid_encrypted_content = "invalid_encrypted_content" # Responses replay blob rejected — strip replay state and retrymultimodal_tool_content_unsupported = "multimodal_tool_content_unsupported" # Provider rejected list-type content in tool messages (e.g. Xiaomi MiMo) — downgrade to text and retryreasoning_mandatory = "reasoning_mandatory" # Route rejects reasoning: {enabled: false} — send the disable no more this session and retry@@ -277,6 +278,19 @@ _INVALID_MESSAGE_BODY_PATTERNS = ("messages: at least one message is required", _NO_USER_QUERY_SIGNAL,)+# Strict-alternation chat templates (llama.cpp / vLLM Jinja templates, Mistral, some+# OpenRouter routes) 400 when two adjacent messages share a role. Deterministic for the+# request shape, and the only bad thing is the adjacency, so the caller that produced it+# (the MoA aggregator appends ``user(guidance)`` after ``user(task)`` on iteration 1 —+# #112358) merges the pair for THAT destination and retries once. Checked before the+# request-validation table: the body usually also carries ``invalid_request_error``.+_ROLE_ALTERNATION_PATTERNS = (+ "roles must alternate", "role must alternate", "must alternate between",+ "consecutive user messages", "consecutive messages with the same role",+ "consecutive messages of the same role", "same role in a row", "multiple user messages in a row",+ "adjacent messages with the same role",+)+# Proxy-side rejection of the model's own tool-call JSON (Ollama "invalid tool call arguments",# OpenRouter-wrapped "function_call arguments"). Checked before the generic 400 validation and# overflow heuristics: on a large session the bare message would otherwise read as overflow.@@ -428,6 +442,9 @@ _V_OVERLOADED, _V_SERVER_ERROR, _V_TIMEOUT, _V_UNKNOWN = map(_v, (_R.overloaded,_V_IMAGE_TOO_LARGE, _V_IMAGE_CORRUPT = _v(_R.image_too_large), _v(_R.image_corrupt)_V_MULTIMODAL, _V_INVALID_ENCRYPTED = _v(_R.multimodal_tool_content_unsupported), _v(_R.invalid_encrypted_content)_V_REASONING_MANDATORY = _v(_R.reasoning_mandatory, should_compress=False, should_fallback=False)+# Same recovery hints as format_error: consumers without a merge-and-retry step (the main loop+# already merges adjacent users before the call) keep aborting to the fallback chain.+_V_ROLE_ALTERNATION = _v(_R.role_alternation, **_ABORT_FALLBACK)# The MODEL emitted unparseable tool-call JSON and the proxy (Ollama, OpenRouter) rejected it: no# other provider can fix that output, so falling back only replays the same broken turn 4-5 times# (20-60s per occurrence, #12770). Abort this call; the loop's argument repair handles the retry.@@ -524,7 +541,8 @@ _400_TAIL_RULES = _OVERFLOW_AS_5XX_RULES + (# Status-less message path, head (before usage-limit disambiguation)._MESSAGE_HEAD_RULES = ((_MEMORY_CEILING_PATTERNS, _V_OVERLOADED),- (_PAYLOAD_TOO_LARGE_PATTERNS, _V_PAYLOAD_TOO_LARGE)) + _IMAGE_TOOL_RULES+ (_PAYLOAD_TOO_LARGE_PATTERNS, _V_PAYLOAD_TOO_LARGE),+ (_ROLE_ALTERNATION_PATTERNS, _V_ROLE_ALTERNATION)) + _IMAGE_TOOL_RULES# Status-less tail. Overload before rate_limit/billing so "overloaded" backs off# instead of rotating; policy block before model_not_found; timeout/connection@@ -966,6 +984,8 @@ def _classify_400(c: _Ctx) -> Verdict:return _V_SERVER_ERRORif any(p in msg for p in _MALFORMED_TOOL_ARGS_PATTERNS):return _V_MALFORMED_TOOL_ARGS+ if any(p in msg for p in _ROLE_ALTERNATION_PATTERNS):+ return _V_ROLE_ALTERNATION# Before overflow: GPT-5's "Unsupported parameter: 'max_tokens'" contains it.if any(p in msg for p in _400_VALIDATION_PATTERNS) or code in _400_VALIDATION_CODES:return _V_FORMAT_ERRORdiff --git a/agent/moa_alternation.py b/agent/moa_alternation.pynew file mode 100644index 00000000000..4e94608b8c2--- /dev/null+++ b/agent/moa_alternation.py@@ -0,0 +1,64 @@+"""Reactive same-role merge for the MoA aggregator request (#112358, last atom).++The aggregator request deliberately ends ``user(task), user(guidance)`` on iteration 1 of a+turn: the guidance is its own trailing message so every earlier message stays byte-stable and+the provider prefix cache keeps growing (``moa_loop._attach_reference_guidance``). Strict-+alternation chat templates (llama.cpp / vLLM Jinja templates, Mistral, some OpenRouter routes)+400 on that adjacency. Merging proactively for everyone would re-introduce the divergence the+split shape removed and only move the 400, so the merge is reactive and destination-scoped:++* a 400 classified ``FailoverReason.role_alternation`` → retry ONCE with adjacent same-role+ messages merged;+* the destination (``base_url``/provider + model) is remembered on the facade for the rest of+ the session, so later iterations pre-merge for it and never pay the 400 again;+* destinations that accepted the split shape are never touched — their prefix stays byte-stable.+"""++from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)+++def destination_key(runtime: dict[str, Any]) -> tuple[str, str]:+ """``(route, model)`` identity of an aggregator destination: the base_url when the slot+ resolved one (two providers can share a model id), else the provider slug."""+ route = str(runtime.get("base_url") or runtime.get("provider") or "").strip().rstrip("/")+ return route, str(runtime.get("model") or "").strip()+++def merge_same_role_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Return ``messages`` with adjacent user turns folded into one (the only same-role adjacency+ the aggregator request produces); other rows are shared, never mutated. Returns the input+ object itself when nothing merged so callers can detect a no-op."""+ from agent.agent_runtime_helpers import _UNMERGEABLE, _merge_user_content++ merged: list[dict[str, Any]] = []+ changed = False+ for message in messages:+ prev = merged[-1] if merged else None+ content: Any = _UNMERGEABLE+ if prev is not None and prev.get("role") == "user" and message.get("role") == "user":+ content = _merge_user_content(prev.get("content", ""), message.get("content", ""))+ if content is _UNMERGEABLE:+ merged.append(message)+ continue+ merged[-1] = {**prev, "content": content}+ changed = True+ return merged if changed else messages+++def is_role_alternation_rejection(exc: Exception, runtime: dict[str, Any]) -> bool:+ """True when the aggregator destination rejected the request for adjacent same-role messages."""+ from agent.error_classifier import FailoverReason, classify_api_error++ try:+ classified = classify_api_error(+ exc, provider=str(runtime.get("provider") or ""), model=str(runtime.get("model") or ""),+ base_url=str(runtime.get("base_url") or ""),+ )+ except Exception: # pragma: no cover - classification must never mask the original error+ return False+ return classified.reason is FailoverReason.role_alternationdiff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex 21b747fac8c..5ce755d512f 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -22,6 +22,7 @@ from typing import Anyfrom agent.auxiliary_client import call_llmfrom agent.message_content import flatten_message_text+from agent.moa_alternation import destination_key, is_role_alternation_rejection, merge_same_role_messagesfrom agent.transports import get_transportfrom agent.usage_pricing import CanonicalUsage@@ -957,6 +958,10 @@ class MoAChatCompletions:self._fanout_turn_sig: str | None = Noneself._fanout_last_state_sig: str | None = Noneself._privacy_mode: str = "" # normalized moa.privacy_filter, refreshed per create()+ # Destinations (route, model) that 400'd on adjacent same-role messages this session:+ # their aggregator requests are pre-merged; every other destination keeps the split,+ # cache-stable shape (agent/moa_alternation.py).+ self._merge_same_role_destinations: set[tuple[str, str]] = set()def consume_reference_usage(self) -> tuple[Any, Any]:"""Pop pending fan-out ``(CanonicalUsage, cost_usd_or_None)`` and reset both@@ -1081,10 +1086,6 @@ class MoAChatCompletions:)trace = self._pending_traceif trace is not None:- # Trace the exact aggregator INPUT (persisted copy redacted; live input raw).- trace["aggregator_input_messages"] = (- _redact_trace_messages([dict(m) for m in agg_messages]) if getattr(self, "_privacy_mode", "") else agg_messages- )trace["aggregator_label"] = _slot_label(aggregator)# stream=True returns the RAW token stream (consumer reassembles + retries);# the non-streaming path forwards no stream/stream_options/timeout. The@@ -1097,13 +1098,40 @@ class MoAChatCompletions:stream_kwargs["timeout"] = api_kwargs["timeout"]# Pop the runtime's extra_body so the explicit kwarg never collides with **agg_runtime.agg_extra_body = _merge_slot_extra_body(agg_runtime.pop("extra_body", None), api_kwargs.get("extra_body"))- agg_response = call_llm(- task="moa_aggregator", messages=agg_messages, temperature=prepared["aggregator_temperature"],+ destination = destination_key(agg_runtime)+ # Facades built via __new__ (tests, swaps) have no __init__ state.+ remembered = getattr(self, "_merge_same_role_destinations", None)+ if remembered is None:+ remembered = self._merge_same_role_destinations = set()+ merged = destination in remembered+ if merged:+ agg_messages = merge_same_role_messages(agg_messages)+ send = functools.partial(+ call_llm, task="moa_aggregator", temperature=prepared["aggregator_temperature"],max_tokens=api_kwargs.get("max_tokens"), tools=tools, extra_body=agg_extra_body,reasoning_config=_aggregator_reasoning_config(aggregator), # same policy as direct create()**stream_kwargs, **agg_runtime,)+ try:+ agg_response = send(messages=agg_messages)+ except Exception as exc:+ # Strict-alternation template rejected ``user(task), user(guidance)``: merge the pair for+ # THIS destination only and retry once; remember it so later iterations pre-merge.+ retry_messages = None if merged else merge_same_role_messages(agg_messages)+ if retry_messages is None or retry_messages is agg_messages or not is_role_alternation_rejection(exc, agg_runtime):+ raise+ remembered.add(destination)+ logger.warning(+ "MoA aggregator %s rejected adjacent same-role messages — merging them for this "+ "destination for the rest of the session and retrying once: %.200s", _slot_label(aggregator), exc,+ )+ agg_messages = retry_messages+ agg_response = send(messages=agg_messages)if trace is not None:+ # Trace the exact aggregator INPUT as sent (persisted copy redacted; live input raw).+ trace["aggregator_input_messages"] = (+ _redact_trace_messages([dict(m) for m in agg_messages]) if getattr(self, "_privacy_mode", "") else agg_messages+ )# Streaming output lands as the turn's assistant message; the trace marks it.trace["aggregator_streamed"] = streamoutput = Nonediff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.pyindex c71cc07f3b3..8e8dab5aa13 100644--- a/tests/agent/test_error_classifier.py+++ b/tests/agent/test_error_classifier.py@@ -64,7 +64,7 @@ class TestFailoverReason:"ssl_cert_verification","context_overflow", "payload_too_large", "image_too_large","image_corrupt",- "model_not_found", "format_error",+ "model_not_found", "format_error", "role_alternation","invalid_encrypted_content","multimodal_tool_content_unsupported","reasoning_mandatory",diff --git a/tests/agent/test_moa_alternation_recovery.py b/tests/agent/test_moa_alternation_recovery.pynew file mode 100644index 00000000000..e8d0c05a812--- /dev/null+++ b/tests/agent/test_moa_alternation_recovery.py@@ -0,0 +1,90 @@+"""MoA aggregator: strict-alternation destinations get their adjacent same-role messages merged+reactively and per destination (#112358, last atom).++The guidance is deliberately a separate trailing ``user`` message so the prefix stays cache-stable;+a chat template that 400s on ``user(task), user(guidance)`` must get ONE merged retry, be remembered+for the session, and never change the bytes sent to destinations that accepted the split shape.+"""++from types import SimpleNamespace++import pytest++from agent import moa_loop+from agent.error_classifier import FailoverReason, classify_api_error++ALTERNATION_MSG = "Conversation roles must alternate user/assistant/user/assistant/..."+++class _AlternationRejected(Exception):+ status_code = 400++ def __init__(self):+ super().__init__(f"Error code: 400 - {{'error': {{'message': '{ALTERNATION_MSG}', 'type': 'invalid_request_error'}}}}")+ self.response = SimpleNamespace(status_code=400, headers={})+ self.body = {"message": ALTERNATION_MSG, "type": "invalid_request_error"}+++def _strict_destination(calls, strict_models):+ """``call_llm`` double: 400s like a strict chat template when adjacent non-system messages share a role."""+ def call_llm(**kw):+ calls.append(kw)+ msgs = [m for m in kw["messages"] if m["role"] != "system"]+ if kw["model"] in strict_models and any(a["role"] == b["role"] for a, b in zip(msgs, msgs[1:])):+ raise _AlternationRejected()+ return SimpleNamespace(choices=[])+ return call_llm+++def facade(monkeypatch):+ monkeypatch.setattr(+ moa_loop, "_slot_runtime",+ lambda slot: {"provider": "custom", "model": slot["model"], "base_url": "http://strict.local/v1",+ "api_mode": "chat_completions"},+ )+ f = moa_loop.MoAChatCompletions("default", agent=None)+ f._pending_trace = None+ return f+++def _send(facade, model, messages, guidance="[Mixture of Agents reference context]\nadvice"):+ prepared = facade.rebase_prepared_request(+ {"guidance": guidance, "aggregator": {"provider": "custom", "model": model}, "aggregator_temperature": None},+ messages,+ )+ return facade._call_prepared_aggregator(prepared, {"tools": None})+++def test_alternation_400_is_classified_and_retried_once_merged_then_remembered(monkeypatch, facade):+ classified = classify_api_error(_AlternationRejected(), provider="custom", model="strict-model")+ assert classified.reason is FailoverReason.role_alternation++ calls = []+ monkeypatch.setattr(moa_loop, "call_llm", _strict_destination(calls, {"strict-model"}))+ task = [{"role": "system", "content": "sys"}, {"role": "user", "content": "task"}]++ _send(facade, "strict-model", task) # iteration 1 of turn 1: split shape rejected → one merged retry+ assert [[m["role"] for m in c["messages"]] for c in calls] == [["system", "user", "user"], ["system", "user"]]+ assert calls[-1]["messages"][-1]["content"] == "task\n\n[Mixture of Agents reference context]\nadvice"++ del calls[:]+ _send(facade, "strict-model", [*task, {"role": "assistant", "content": "answer"}, {"role": "user", "content": "task2"}])+ # Remembered destination: iteration 1 of the next turn is pre-merged, no 400 paid again.+ assert [[m["role"] for m in c["messages"]] for c in calls] == [["system", "user", "assistant", "user"]]+ assert calls[0]["messages"][-1]["content"].startswith("task2\n\n[Mixture of Agents reference context]")+++def test_destinations_that_accept_the_split_shape_keep_byte_identical_requests(monkeypatch, facade):+ calls = []+ monkeypatch.setattr(moa_loop, "call_llm", _strict_destination(calls, {"strict-model"}))+ task = [{"role": "system", "content": "sys"}, {"role": "user", "content": "task"}]+ guidance = "[Mixture of Agents reference context]\nadvice"++ _send(facade, "strict-model", task, guidance) # teaches the facade about the strict destination+ del calls[:]+ _send(facade, "lenient-model", task, guidance)++ # The lenient destination on the SAME facade still gets the split, cache-stable shape in one request.+ assert len(calls) == 1+ assert calls[0]["messages"] == [*task, {"role": "user", "content": guidance}]diff --git a/website/docs/user-guide/features/mixture-of-agents.md b/website/docs/user-guide/features/mixture-of-agents.mdindex 72ae9e465b0..18abd47e9e1 100644--- a/website/docs/user-guide/features/mixture-of-agents.md+++ b/website/docs/user-guide/features/mixture-of-agents.md@@ -245,6 +245,8 @@ Both internal call types cache normally:- **Reference models** receive a trimmed, deterministic view of the conversation (system prompt and tool transcript stripped — see the loop above). Because that view is a stable function of the stable history, a reference model's prompt prefix repeats across iterations and caches normally. References are short advisory calls with no tools.- **The aggregator** is the acting model. The reference outputs are appended as their *own* trailing user message of private guidance — never merged into your message. Because that block sits at the tail — below the entire stable prefix (system prompt + your message + prior tool history) — it does not invalidate any cached prefix: every request in a tool loop is a byte-identical extension of the previous one minus its guidance block, so the aggregator gets a cache hit on everything above the injection and only the freshly appended tail is new. That is exactly how every normal turn behaves, where each new user message is also uncached tail tokens. Aggregators on the Anthropic Messages, Bedrock Converse or native Gemini wire merge the two adjacent user turns into one message, but as separate content blocks: your message's block is byte-identical to the one later iterations replay, and the guidance block follows it, so the cached prefix still runs through your message.+ On the OpenAI-compatible wire the request ends `user(your message), user(guidance)` on the first iteration of a turn. A few chat templates that enforce strict user/assistant alternation (llama.cpp and vLLM Jinja templates, some OpenRouter routes) reject that with a 400 such as `Conversation roles must alternate`. Hermes recovers on its own: it retries that one request with the two adjacent user messages merged, remembers that aggregator destination (endpoint + model) for the rest of the session so later turns are merged up front, and leaves every other destination on the split, cache-stable shape. The merge is applied only where a destination demanded it, because merging everywhere would reintroduce the prefix divergence described above.+So MoA does not sacrifice prompt caching on either call type. Its only real cost is the extra reference calls (once per user turn with the default `fanout`) — you pay for multiple model perspectives, not for broken caches. The long-lived conversation prefix shared with the rest of Hermes is fully intact.## Notes