Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 32 additions & 21 deletions agent/auxiliary_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6104,25 +6104,29 @@ def _build_call_kwargs(
kwargs["temperature"] = temperature

if max_tokens is not None:
# We do NOT cap output by default. Most chat-completions providers treat
# an omitted max_tokens as "use the model's max output", which is what we
# want for auxiliary tasks (compression summaries, titles, vision, etc.) β€”
# an explicit cap only risks truncating a summary or 400-ing on providers
# that reject the parameter outright (e.g. GitHub Copilot / newer OpenAI
# GPT-5 models require max_completion_tokens, not max_tokens; ZAI vision
# models reject it entirely with error 1210). Omitting it sidesteps all of
# those wire-format quirks at once.
# When the caller explicitly provides a max_tokens, forward it using
# the provider/model-correct wire field (max_tokens vs
# max_completion_tokens) via auxiliary_max_tokens_param. This is
# used by MoA reference_max_tokens and by auxiliary callers that
# pass an explicit cap (e.g. title_generation max_tokens=500).
#
# The one exception is the Anthropic Messages wire (MiniMax and any
# ``/anthropic`` endpoint reached through the OpenAI SDK wrapper), where
# max_tokens is a MANDATORY field β€” omitting it is a hard 400. Keep it only
# there.
# When max_tokens is None (the default for most auxiliary tasks), no
# cap is sent β€” most providers treat an omitted max_tokens as "use the
# model's max output", which is what we want for compression summaries,
# titles, vision, etc. Omitting also sidesteps providers that reject the
# parameter outright (GitHub Copilot, ZAI vision error 1210, etc.).
#
# NVIDIA NIM (integrate.api.nvidia.com and local NIM endpoints) is a
# second exception: some modelsβ€”notably minimaxai/minimax-m3β€”return HTTP
# 200 with an empty choices[] payload when max_tokens is omitted. The main
# NVIDIA chat path already sends an output cap via the provider profile;
# preserve it on the auxiliary path too.
# The exception is the Anthropic Messages wire (MiniMax and any
# /anthropic endpoint), where max_tokens is MANDATORY β€” omitting it is
# a hard 400. auxiliary_max_tokens_param returns {"max_tokens": value}
# for those providers, which is correct.
#
# NVIDIA NIM: some models return HTTP 200 with empty choices[] when
# max_tokens is omitted. The main chat path sends a cap via the
# provider profile; preserve it here too.
#
# If a provider rejects the param, the retry logic below catches the
# error and strips max_tokens/max_completion_tokens before retrying.
_effective_base = base_url or (
_current_custom_base_url() if provider == "custom" else ""
)
Expand All @@ -6131,11 +6135,18 @@ def _build_call_kwargs(
_provider_norm in {"nvidia", "nvidia-nim", "nim", "build-nvidia", "nemotron"}
or base_url_host_matches(_effective_base, "integrate.api.nvidia.com")
)
if (
_is_anthropic_compat_endpoint(provider, _effective_base)
or _is_nvidia_nim
):
_is_anthropic_compat = _is_anthropic_compat_endpoint(provider, _effective_base)
if _is_anthropic_compat or _is_nvidia_nim:
# These require max_tokens on the wire (Anthropic-compat mandates
# it; NIM needs it to avoid empty responses).
kwargs["max_tokens"] = max_tokens
else:
# Use the model-aware helper to pick max_tokens vs
# max_completion_tokens. The retry logic below handles any
# provider that rejects the param by stripping and retrying.
kwargs.update(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This broadens explicit output-cap forwarding to every non-Anthropic/NIM auxiliary route, but current main intentionally omits those caps to avoid OpenAI-compatible and ZAI failures (2062a840; tests/agent/test_auxiliary_client.py:278). Please scope the repair to the documented MoA reference-cap path, or preserve the existing omission behavior for unrelated auxiliary tasks.

auxiliary_max_tokens_param(max_tokens, model=model)
)

if tools:
# Defensive dedup: providers like Google Vertex, Azure, and Bedrock
Expand Down
19 changes: 12 additions & 7 deletions agent/moa_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,11 @@ def __init__(



def _slot_label(slot: dict[str, str]) -> str:
def _slot_label(slot: dict[str, Any]) -> str:
return f"{slot.get('provider', '').strip()}:{slot.get('model', '').strip()}"


def _slot_runtime(slot: dict[str, str]) -> dict[str, Any]:
def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:
"""Resolve a reference/aggregator slot to real runtime call kwargs.

A MoA slot is just a model selection β€” it must be called the same way any
Expand Down Expand Up @@ -218,7 +218,7 @@ def _maybe_apply_moa_cache_control(


def _run_reference(
slot: dict[str, str],
slot: dict[str, Any],
ref_messages: list[dict[str, Any]],
*,
temperature: float | None = None,
Expand Down Expand Up @@ -270,11 +270,16 @@ def _run_reference(
# (their caching is automatic; markers are ignored harmlessly, but we
# only decorate when the policy says the route honors them).
messages = _maybe_apply_moa_cache_control(messages, runtime)
# Per-slot max_tokens takes precedence over the preset-level
# reference_max_tokens passed in by the caller. This lets each
# reference model have its own output cap independently.
_slot_max_tokens: int | None = slot.get("max_tokens")
_effective_max_tokens = _slot_max_tokens if _slot_max_tokens is not None else max_tokens
response = call_llm(
task="moa_reference",
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
max_tokens=_effective_max_tokens,
**runtime,
)
usage = CanonicalUsage()
Expand Down Expand Up @@ -334,7 +339,7 @@ def _run_reference(


def _run_references_parallel(
reference_models: list[dict[str, str]],
reference_models: list[dict[str, Any]],
ref_messages: list[dict[str, Any]],
*,
temperature: float | None = None,
Expand Down Expand Up @@ -572,8 +577,8 @@ def aggregate_moa_context(
*,
user_prompt: str,
api_messages: list[dict[str, Any]],
reference_models: list[dict[str, str]],
aggregator: dict[str, str],
reference_models: list[dict[str, Any]],
aggregator: dict[str, Any],
temperature: float | None = None,
aggregator_temperature: float | None = None,
max_tokens: int | None = None,
Expand Down
13 changes: 11 additions & 2 deletions hermes_cli/moa_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _coerce_fanout(value: Any) -> str:
return mode if mode in {"per_iteration", "user_turn"} else "per_iteration"


def _clean_slot(slot: Any) -> dict[str, str] | None:
def _clean_slot(slot: Any) -> dict[str, Any] | None:
if not isinstance(slot, dict):
return None
provider = str(slot.get("provider") or "").strip()
Expand All @@ -87,7 +87,16 @@ def _clean_slot(slot: Any) -> dict[str, str] | None:
# an invalid slot is dropped, falling back to the preset's defaults.
if provider.lower() == "moa":
return None
return {"provider": provider, "model": model}
cleaned: dict[str, Any] = {"provider": provider, "model": model}
# Optional per-slot max_tokens: overrides the preset-level
# reference_max_tokens for this specific reference model. None (the
# default) = no cap, so existing slots are unaffected. Allows tuning
# each advisor's output length independently β€” useful when one model
# is verbose and another is terse.
slot_mt = _coerce_int_or_none(slot.get("max_tokens"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a new user-facing per-slot max_tokens configuration surface. Please split it from the repair for the already documented preset-level reference_max_tokens setting; the two changes need separate maintainer direction.

if slot_mt is not None:
cleaned["max_tokens"] = slot_mt
return cleaned


def _default_preset() -> dict[str, Any]:
Expand Down
57 changes: 46 additions & 11 deletions tests/agent/test_auxiliary_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,28 +276,27 @@ def test_explicit_provider_and_base_url_still_win_over_config(self):


class TestBuildCallKwargsMaxTokens:
"""_build_call_kwargs should not cap output by default (#34530).

Most chat-completions providers treat an omitted max_tokens as "use the
model max", which is what we want for auxiliary tasks. An explicit cap only
risks truncation or a wire-format 400 (GitHub Copilot / GPT-5 reject
max_tokens; ZAI vision rejects it entirely). The Anthropic Messages wire is
the one exception β€” max_tokens is a mandatory field there.
"""_build_call_kwargs forwards max_tokens when explicitly provided.

An explicit max_tokens is forwarded using the provider/model-correct wire
field (max_tokens vs max_completion_tokens) via auxiliary_max_tokens_param.
When max_tokens is None (the default), no cap is sent β€” most providers
treat an omitted max_tokens as "use the model max", which is what we want
for auxiliary tasks. The Anthropic Messages wire is the exception β€”
max_tokens is a mandatory field there. If a provider rejects the param,
the retry logic in call_llm strips it and retries.
"""

@pytest.mark.parametrize(
"provider,model,base_url",
[
("copilot", "gpt-5.4", "https://api.githubcopilot.com"),
("copilot", "gpt-5.5", "https://api.githubcopilot.com"),
("custom", "gpt-5", "https://api.openai.com/v1"),
("openrouter", "anthropic/claude-sonnet-4.6", "https://openrouter.ai/api/v1"),
("nous", "hermes-4", "https://inference-api.nousresearch.com/v1"),
("custom", "qwen", "http://localhost:8080/v1"),
("zai", "glm-4v-flash", "https://open.bigmodel.cn/api/paas/v4"),
],
)
def test_omits_max_tokens_for_openai_compatible(self, provider, model, base_url):
def test_forwards_max_tokens_for_standard_models(self, provider, model, base_url):
from agent.auxiliary_client import _build_call_kwargs

kwargs = _build_call_kwargs(
Expand All @@ -307,6 +306,42 @@ def test_omits_max_tokens_for_openai_compatible(self, provider, model, base_url)
max_tokens=1234,
base_url=base_url,
)
assert kwargs.get("max_tokens") == 1234
assert "max_completion_tokens" not in kwargs

@pytest.mark.parametrize(
"provider,model,base_url",
[
("copilot", "gpt-5.4", "https://api.githubcopilot.com"),
("copilot", "gpt-5.5", "https://api.githubcopilot.com"),
("custom", "gpt-5", "https://api.openai.com/v1"),
],
)
def test_uses_max_completion_tokens_for_newer_openai_models(self, provider, model, base_url):
"""GPT-5+ / o-series models require max_completion_tokens, not max_tokens."""
from agent.auxiliary_client import _build_call_kwargs

kwargs = _build_call_kwargs(
provider=provider,
model=model,
messages=[{"role": "user", "content": "hi"}],
max_tokens=1234,
base_url=base_url,
)
assert kwargs.get("max_completion_tokens") == 1234
assert "max_tokens" not in kwargs

def test_omits_max_tokens_when_none(self):
"""When max_tokens is None (default), no cap is sent."""
from agent.auxiliary_client import _build_call_kwargs

kwargs = _build_call_kwargs(
provider="openrouter",
model="anthropic/claude-sonnet-4.6",
messages=[{"role": "user", "content": "hi"}],
max_tokens=None,
base_url="https://openrouter.ai/api/v1",
)
assert "max_tokens" not in kwargs
assert "max_completion_tokens" not in kwargs

Expand Down
82 changes: 82 additions & 0 deletions tests/agent/test_moa_slot_max_tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Tests for per-slot max_tokens in MoA reference calls.

Verifies that a ``max_tokens`` field on a reference slot dict takes
precedence over the preset-level ``reference_max_tokens``, and that
slot-level max_tokens=None falls back to the preset-level cap.
"""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import pytest


class TestRunReferenceSlotMaxTokens:
"""_run_reference should prefer slot-level max_tokens over preset-level."""

def test_slot_max_tokens_overrides_preset_level(self):
"""When slot has max_tokens, it overrides the preset-level cap."""
from agent.moa_loop import _run_reference

captured_kwargs: dict = {}

def fake_call_llm(**kwargs):
captured_kwargs.update(kwargs)
mock_resp = MagicMock()
mock_resp.choices = [MagicMock(message=MagicMock(content="advice"))]
mock_resp.usage = None
return mock_resp

slot = {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro", "max_tokens": 600}

with patch("agent.moa_loop._slot_runtime", return_value={"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}), \
patch("agent.moa_loop.call_llm", side_effect=fake_call_llm), \
patch("agent.moa_loop._maybe_apply_moa_cache_control", side_effect=lambda msgs, rt: msgs):
_run_reference(slot, [{"role": "user", "content": "hi"}], max_tokens=2000)

assert captured_kwargs.get("max_tokens") == 600

def test_slot_max_tokens_absent_falls_back_to_preset(self):
"""When slot has no max_tokens, the preset-level cap is used."""
from agent.moa_loop import _run_reference

captured_kwargs: dict = {}

def fake_call_llm(**kwargs):
captured_kwargs.update(kwargs)
mock_resp = MagicMock()
mock_resp.choices = [MagicMock(message=MagicMock(content="advice"))]
mock_resp.usage = None
return mock_resp

slot = {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}

with patch("agent.moa_loop._slot_runtime", return_value={"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}), \
patch("agent.moa_loop.call_llm", side_effect=fake_call_llm), \
patch("agent.moa_loop._maybe_apply_moa_cache_control", side_effect=lambda msgs, rt: msgs):
_run_reference(slot, [{"role": "user", "content": "hi"}], max_tokens=2000)

assert captured_kwargs.get("max_tokens") == 2000

def test_both_none_means_uncapped(self):
"""When neither slot nor preset has max_tokens, it's None (uncapped)."""
from agent.moa_loop import _run_reference

captured_kwargs: dict = {}

def fake_call_llm(**kwargs):
captured_kwargs.update(kwargs)
mock_resp = MagicMock()
mock_resp.choices = [MagicMock(message=MagicMock(content="advice"))]
mock_resp.usage = None
return mock_resp

slot = {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}

with patch("agent.moa_loop._slot_runtime", return_value={"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}), \
patch("agent.moa_loop.call_llm", side_effect=fake_call_llm), \
patch("agent.moa_loop._maybe_apply_moa_cache_control", side_effect=lambda msgs, rt: msgs):
_run_reference(slot, [{"role": "user", "content": "hi"}], max_tokens=None)

assert captured_kwargs.get("max_tokens") is None
Loading