Merge pull request #75852 from NousResearch/fix/moa-completed-response-streaming-cluster
fix(moa): stream completed aggregator responses across all layers (#74031 + #74903 + #74543)
This commit is contained in:
@@ -1226,11 +1226,19 @@ class _CodexCompletionsAdapter:
|
||||
|
||||
event_stream = self._client.responses.create(**stream_kwargs)
|
||||
try:
|
||||
final = _consume_codex_event_stream(
|
||||
event_stream,
|
||||
model=resp_kwargs.get("model"),
|
||||
on_event=_on_each_event,
|
||||
)
|
||||
# Some Codex-compatible hosts accept ``stream=True`` but return
|
||||
# a completed Responses object instead of an SSE iterator. Do
|
||||
# not hand that object to the event consumer: typed Responses
|
||||
# (and compatibility shims such as SimpleNamespace) are not
|
||||
# event streams and may not be iterable at all.
|
||||
if hasattr(event_stream, "output"):
|
||||
final = event_stream
|
||||
else:
|
||||
final = _consume_codex_event_stream(
|
||||
event_stream,
|
||||
model=str(resp_kwargs.get("model") or model),
|
||||
on_event=_on_each_event,
|
||||
)
|
||||
finally:
|
||||
close_fn = getattr(event_stream, "close", None)
|
||||
if callable(close_fn):
|
||||
@@ -8110,6 +8118,16 @@ def call_llm(
|
||||
kwargs["stream"] = True
|
||||
if stream_options:
|
||||
kwargs["stream_options"] = stream_options
|
||||
if task == "moa_aggregator" and isinstance(client, CodexAuxiliaryClient):
|
||||
# CodexAuxiliaryClient (openai-codex, xai-oauth, and any other
|
||||
# Responses-shim provider) consumes the provider stream internally
|
||||
# and returns a completed response object. Routing that nested
|
||||
# MoA stream through Relay's generic managed stream makes the
|
||||
# manager iterate the completed SimpleNamespace itself (#55933).
|
||||
# Return the provider call directly; the MoA facade converts a
|
||||
# completed response into a one-chunk delta iterator at its
|
||||
# boundary.
|
||||
return client.chat.completions.create(**kwargs)
|
||||
return _relay_sync_stream(
|
||||
client,
|
||||
kwargs,
|
||||
|
||||
@@ -3979,7 +3979,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
|
||||
" To avoid this delay, set display.streaming: false "
|
||||
"in config.yaml\n"
|
||||
)
|
||||
logger.info(
|
||||
logger.exception(
|
||||
"Streaming failed before delivery: %s",
|
||||
e,
|
||||
)
|
||||
|
||||
@@ -836,6 +836,19 @@ def classify_api_error(
|
||||
if classified is not None:
|
||||
return classified
|
||||
|
||||
# Local MoA streaming compatibility errors are adapter-shape bugs, not a
|
||||
# provider outage. Falling back to another model would silently switch the
|
||||
# user's selected MoA route to a single-model answer (#55933 follow-up).
|
||||
if provider_lower == "moa" and (
|
||||
"'types.SimpleNamespace' object is not iterable" in str(error)
|
||||
or "'types.SimpleNamespace' object has no attribute 'index'" in str(error)
|
||||
):
|
||||
return _result(
|
||||
FailoverReason.format_error,
|
||||
retryable=False,
|
||||
should_fallback=False,
|
||||
)
|
||||
|
||||
# Local MoA config drift is deterministic: a persisted session can retain
|
||||
# a preset name that was later renamed/deleted. Retrying the same lookup
|
||||
# cannot recover and makes a clear config error look like an API outage.
|
||||
|
||||
+73
-1
@@ -13,6 +13,7 @@ import logging
|
||||
import re
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, wait as _futures_wait
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from agent.auxiliary_client import call_llm
|
||||
@@ -1300,6 +1301,53 @@ def aggregate_moa_context(
|
||||
)
|
||||
|
||||
|
||||
def _completed_response_as_stream_chunk(response: Any) -> Any:
|
||||
"""Convert a completed Chat Completions response into one delta stream chunk.
|
||||
|
||||
MoA's outer streaming consumer expects ``choices[0].delta`` chunks. A
|
||||
completed aggregator response carries ``choices[0].message`` instead; adapt
|
||||
it here, at the MoA facade boundary, so provider-specific Relay behavior and
|
||||
other transports remain untouched.
|
||||
"""
|
||||
|
||||
choices = getattr(response, "choices", None)
|
||||
first_choice = choices[0] if isinstance(choices, (list, tuple)) and choices else None
|
||||
message = getattr(first_choice, "message", None)
|
||||
raw_tool_calls = getattr(message, "tool_calls", None)
|
||||
tool_call_deltas = None
|
||||
if isinstance(raw_tool_calls, (list, tuple)) and raw_tool_calls:
|
||||
tool_call_deltas = []
|
||||
for index, tc in enumerate(raw_tool_calls):
|
||||
function = getattr(tc, "function", None)
|
||||
tool_call_deltas.append(SimpleNamespace(
|
||||
index=getattr(tc, "index", index),
|
||||
id=getattr(tc, "id", None),
|
||||
type=getattr(tc, "type", None) or "function",
|
||||
function=SimpleNamespace(
|
||||
name=getattr(function, "name", None),
|
||||
arguments=getattr(function, "arguments", None),
|
||||
),
|
||||
))
|
||||
delta = SimpleNamespace(
|
||||
content=getattr(message, "content", None),
|
||||
tool_calls=tool_call_deltas,
|
||||
reasoning_content=getattr(message, "reasoning_content", None),
|
||||
reasoning=getattr(message, "reasoning", None),
|
||||
reasoning_details=getattr(message, "reasoning_details", None),
|
||||
)
|
||||
choice = SimpleNamespace(
|
||||
index=getattr(first_choice, "index", 0),
|
||||
delta=delta,
|
||||
finish_reason=getattr(first_choice, "finish_reason", None) or "stop",
|
||||
)
|
||||
return SimpleNamespace(
|
||||
id=getattr(response, "id", None),
|
||||
model=getattr(response, "model", None),
|
||||
choices=[choice],
|
||||
usage=getattr(response, "usage", None),
|
||||
)
|
||||
|
||||
|
||||
def _attach_reference_guidance(agg_messages: list[dict[str, Any]], guidance: str) -> None:
|
||||
"""Attach the per-turn reference block at the END of the aggregator prompt.
|
||||
|
||||
@@ -1685,6 +1733,14 @@ class MoAChatCompletions:
|
||||
self._pending_trace["aggregator_output"] = _extract_text(_agg_response)
|
||||
except Exception: # pragma: no cover - defensive
|
||||
self._pending_trace["aggregator_output"] = None
|
||||
if stream and hasattr(_agg_response, "choices"):
|
||||
# Some aggregator adapters (notably openai-codex Responses) consume
|
||||
# their provider stream internally and return a completed response
|
||||
# object even when the acting consumer requested token streaming.
|
||||
# The outer chat-completions streaming loop expects delta chunks;
|
||||
# hand it a one-chunk iterator instead of letting it iterate the
|
||||
# SimpleNamespace response itself (#55933).
|
||||
return iter((_completed_response_as_stream_chunk(_agg_response),))
|
||||
return _agg_response
|
||||
|
||||
def create(self, **api_kwargs: Any) -> Any:
|
||||
@@ -2174,8 +2230,24 @@ def build_moa_facade(agent, preset_name: Any = None) -> MoAClient:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
resolved_preset = preset_name
|
||||
if resolved_preset is None and getattr(agent, "provider", None) == "moa":
|
||||
resolved_preset = getattr(agent, "model", None)
|
||||
|
||||
resolved_preset = str(resolved_preset or "default")
|
||||
try:
|
||||
from hermes_cli.config import load_config
|
||||
from hermes_cli.moa_config import normalize_moa_config
|
||||
|
||||
moa_cfg = normalize_moa_config(load_config().get("moa") or {})
|
||||
presets = moa_cfg.get("presets") or {}
|
||||
if resolved_preset not in presets:
|
||||
resolved_preset = moa_cfg.get("default_preset") or "default"
|
||||
except Exception:
|
||||
resolved_preset = "default"
|
||||
|
||||
return MoAClient(
|
||||
str(preset_name or getattr(agent, "model", None) or "default"),
|
||||
resolved_preset,
|
||||
reference_callback=_moa_reference_relay,
|
||||
# Thread the agent through so the reference fan-out wait can be
|
||||
# aborted on a user interrupt (see _run_references_parallel).
|
||||
|
||||
@@ -11,6 +11,7 @@ import pytest
|
||||
|
||||
from agent.auxiliary_client import (
|
||||
_NOUS_MODEL,
|
||||
CodexAuxiliaryClient,
|
||||
get_text_auxiliary_client,
|
||||
get_available_vision_backends,
|
||||
resolve_vision_provider_client,
|
||||
@@ -3301,6 +3302,43 @@ class TestCodexAuxiliaryAdapterNullOutputRecovery:
|
||||
codex_runtime._consume_codex_event_stream = original_consume
|
||||
|
||||
|
||||
class TestCodexAuxiliaryAdapterCompletedResponse:
|
||||
def test_accepts_completed_response_when_stream_was_requested(self):
|
||||
completed = SimpleNamespace(
|
||||
status="completed",
|
||||
id="resp_completed",
|
||||
output=[SimpleNamespace(
|
||||
type="message",
|
||||
content=[SimpleNamespace(
|
||||
type="output_text",
|
||||
text="completed response",
|
||||
)],
|
||||
)],
|
||||
usage=SimpleNamespace(
|
||||
input_tokens=11,
|
||||
output_tokens=3,
|
||||
total_tokens=14,
|
||||
),
|
||||
)
|
||||
|
||||
class FakeResponses:
|
||||
def create(self, **kwargs):
|
||||
assert kwargs["stream"] is True
|
||||
return completed
|
||||
|
||||
fake_client = SimpleNamespace(responses=FakeResponses())
|
||||
adapter = _CodexCompletionsAdapter(fake_client, "gpt-5.6-terra")
|
||||
|
||||
response = adapter.create(
|
||||
messages=[{"role": "user", "content": "review this"}],
|
||||
)
|
||||
|
||||
assert response.choices[0].message.content == "completed response"
|
||||
assert response.usage.prompt_tokens == 11
|
||||
assert response.usage.completion_tokens == 3
|
||||
assert response.usage.total_tokens == 14
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #23432 — auxiliary timeout poisons cached client; later aux calls fail
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -4051,3 +4089,43 @@ class TestCustomEndpointApiKeyInheritance:
|
||||
|
||||
assert captured.get("api_key") == "no-key-required"
|
||||
|
||||
|
||||
class TestMoaAggregatorStreamingBypass:
|
||||
def test_moa_aggregator_stream_bypasses_relay_for_codex_auxiliary_client(self, monkeypatch):
|
||||
"""The MoA facade owns the streaming contract. For Codex Responses-shim
|
||||
clients (openai-codex, xai-oauth), call_llm must return the provider's
|
||||
direct create() result instead of routing through Relay's managed
|
||||
stream, which cannot iterate a completed SimpleNamespace (#74903).
|
||||
"""
|
||||
|
||||
completed = SimpleNamespace(
|
||||
choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))]
|
||||
)
|
||||
|
||||
real_client = SimpleNamespace(
|
||||
api_key="test-key",
|
||||
base_url="https://chatgpt.com/backend-api/codex/",
|
||||
close=lambda: None,
|
||||
)
|
||||
client = CodexAuxiliaryClient(real_client, "gpt-5.6-sol")
|
||||
direct_create = MagicMock(return_value=completed)
|
||||
monkeypatch.setattr(client.chat.completions, "create", direct_create)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"agent.auxiliary_client._get_cached_client",
|
||||
lambda *args, **kwargs: (client, "gpt-5.6-sol"),
|
||||
)
|
||||
relay_stream = MagicMock(side_effect=AssertionError("_relay_sync_stream must not be used"))
|
||||
monkeypatch.setattr("agent.auxiliary_client._relay_sync_stream", relay_stream)
|
||||
|
||||
result = call_llm(
|
||||
task="moa_aggregator",
|
||||
provider="openai-codex",
|
||||
model="gpt-5.6-sol",
|
||||
messages=[{"role": "user", "content": "只回答 OK"}],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
assert result is completed
|
||||
direct_create.assert_called_once()
|
||||
relay_stream.assert_not_called()
|
||||
|
||||
@@ -90,6 +90,69 @@ def test_create_streams_aggregator_when_requested(monkeypatch, tmp_path):
|
||||
assert agg["tools"] is not None
|
||||
|
||||
|
||||
def test_build_moa_facade_ignores_fallback_model_name_when_restoring(monkeypatch, tmp_path):
|
||||
"""A fallback restore must not turn the temporary fallback model name into
|
||||
a MoA preset. Sessions that drifted to e.g. deepseek-v4-flash previously
|
||||
crashed on restore with MoAPresetNotFoundError because build_moa_facade()
|
||||
reused agent.model as the preset (#MoA restore path).
|
||||
"""
|
||||
home = tmp_path / ".hermes"
|
||||
_write_cfg(home)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
|
||||
from agent.moa_loop import build_moa_facade
|
||||
|
||||
agent = SimpleNamespace(
|
||||
provider="moa",
|
||||
model="deepseek-v4-flash",
|
||||
tool_progress_callback=None,
|
||||
)
|
||||
|
||||
client = build_moa_facade(agent, None)
|
||||
|
||||
assert client.chat.completions.preset_name == "review"
|
||||
|
||||
|
||||
def test_create_wraps_completed_aggregator_response_as_delta_chunk(monkeypatch, tmp_path):
|
||||
"""When an aggregator adapter returns a completed response despite
|
||||
stream=True (Codex Responses compatibility shape), MoA must return a
|
||||
one-chunk delta iterator for the outer streaming accumulator instead of
|
||||
the raw non-iterable response object (#55933).
|
||||
"""
|
||||
|
||||
completed = _response("aggregator acted")
|
||||
completed.choices[0].message.tool_calls = [
|
||||
SimpleNamespace(
|
||||
id="call_1",
|
||||
type="function",
|
||||
function=SimpleNamespace(name="read_file", arguments='{"path":"x"}'),
|
||||
)
|
||||
]
|
||||
|
||||
def on_call(kwargs):
|
||||
if kwargs["task"] == "moa_aggregator":
|
||||
return completed
|
||||
return None
|
||||
|
||||
facade, calls = _facade(monkeypatch, tmp_path, on_call=on_call)
|
||||
stream = facade.create(
|
||||
messages=[{"role": "user", "content": "q"}],
|
||||
tools=[],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
chunk = next(iter(stream))
|
||||
assert chunk.choices[0].delta.content == "aggregator acted"
|
||||
assert chunk.choices[0].delta.tool_calls[0].index == 0
|
||||
assert chunk.choices[0].delta.tool_calls[0].function.name == "read_file"
|
||||
assert chunk.choices[0].finish_reason == "stop"
|
||||
with pytest.raises(StopIteration):
|
||||
next(stream)
|
||||
|
||||
agg = next(c for c in calls if c["task"] == "moa_aggregator")
|
||||
assert agg["stream"] is True
|
||||
|
||||
|
||||
def test_create_non_stream_path_unchanged(monkeypatch, tmp_path):
|
||||
"""Default (no stream): the aggregator call carries NO stream/stream_options
|
||||
keys, so the non-streaming path is byte-identical to before."""
|
||||
|
||||
Reference in New Issue
Block a user