2a95791992
run_agent.py: delete the `# noqa: F401` re-export block (agent.process_bootstrap
OpenAI/_SafeWriter/_get_proxy_*, model_tools get_tool_definitions/
handle_function_call/check_toolset_requirements, FailoverReason,
_qwen_portal_headers/_routermint_headers, session_persistence names,
estimate_request_tokens_rough, ContextCompressor + friends, jittered_backoff,
prompt_builder names, message_sanitization names, tool_dispatch_helpers
names) — 41 names run_agent never used itself — and the `_STREAM_DIAG_HEADERS`
back-compat class alias (no in-tree reader). run_agent now imports only what
it uses (get_toolset_for_tool, is_local_endpoint, coalesce/uniquify tool-call
ids, cleanup_vm/get_active_env from terminal_tool_lifecycle).
agent/*: `_ra().X` late-binds that only reached a re-export now import the
defining module directly (agent_runtime_helpers -> process_bootstrap.OpenAI,
model_tools.handle_function_call, session_persistence._safe_session_filename_component;
agent_init -> model_tools.get_tool_definitions/check_toolset_requirements,
_lazy_headers("agent.client_lifecycle", ...) for qwen/routermint;
system_prompt -> agent.prompt_builder / model_tools directly, dropping its
own _ra() shim and the `_r` parameter threading). `_ra()` stays for
run_agent-resident names (logger, AIAgent, _hermes_home, _set_interrupt, ...).
toolsets.py: remove resolve_multiple_toolsets (shim-only, restored by
34abf954bd); tests/test_toolsets.py pins the same union behavior via
resolve_toolset over each name.
providers/__init__.py: drop the OMIT_TEMPERATURE re-export (no callers via the
package); ProviderProfile stays because __init__ uses it for annotations —
2 tests repointed to providers.base.
agent/iteration_budget.py: drop the "run_agent re-exports the class"
docstring pointer; 4 tests import IterationBudget from its home.
model_tools.py (arg_coercion names), agent/tool_executor.py, and
hermes_cli/cli_session_mixin.py repoints landed via a sibling commit on this
shared worktree.
Callers repointed: gateway/run.py, hermes_cli/cli_chat_turn_mixin.py,
hermes_cli/cli_tui_mixin.py, tui_gateway/session_workdir.py,
agent/transports/codex.py (one-line imports) + comment pointers in
tools/file_state.py, tools/schema_sanitizer.py, scripts/tool_search_livetest.py.
Tests: patch("run_agent.X") / monkeypatch.setattr(run_agent, "X") /
`from run_agent import X` -> defining module across 99 test files.
147 lines
5.6 KiB
Python
147 lines
5.6 KiB
Python
"""Regression test for the thinking-only prefill reaching the wire.
|
|
|
|
A thinking-only response (reasoning tokens, no visible text) makes the loop
|
|
append an empty assistant turn and re-send so the model continues its own
|
|
reasoning. On providers that don't echo reasoning back, the API copy has its
|
|
reasoning fields stripped before ``_drop_thinking_only_and_merge_users`` runs,
|
|
so the drop pass used to see a bare ``{"role": "assistant", "content": ""}``
|
|
and let it through. Gemini rejects that with
|
|
|
|
400 INVALID_ARGUMENT: Requests ending with a model turn are not supported.
|
|
|
|
classified as non-retryable, so the turn aborts outright.
|
|
|
|
Unlike the unit tests in ``test_thinking_only_sanitizer.py``, this drives
|
|
``run_conversation`` and asserts on the payload actually handed to the client,
|
|
so it exercises the API-copy build that decides whether ``_thinking_prefill``
|
|
survives as far as the drop pass.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
|
|
@pytest.fixture()
|
|
def loop_agent():
|
|
"""AIAgent with a mocked OpenAI client, mirroring the fixture in
|
|
``test_dropped_tool_call_recovery.py``."""
|
|
from run_agent import AIAgent
|
|
with (
|
|
patch("model_tools.get_tool_definitions", return_value=[]),
|
|
patch("model_tools.check_toolset_requirements", return_value={}),
|
|
patch("agent.process_bootstrap.OpenAI"),
|
|
):
|
|
agent = AIAgent(
|
|
api_key="test-key-1234567890",
|
|
base_url="https://openrouter.ai/api/v1",
|
|
quiet_mode=True,
|
|
skip_context_files=True,
|
|
skip_memory=True,
|
|
)
|
|
agent.client = MagicMock()
|
|
agent._cached_system_prompt = "You are helpful."
|
|
agent._use_prompt_caching = False
|
|
agent.tool_delay = 0
|
|
agent.compression_enabled = False
|
|
agent.save_trajectories = False
|
|
return agent
|
|
|
|
|
|
def _thinking_only_response():
|
|
"""Reasoning tokens, no visible text — what triggers the prefill retry."""
|
|
from tests.run_agent.test_run_agent import _mock_response
|
|
return _mock_response(
|
|
content="",
|
|
finish_reason="stop",
|
|
reasoning="Let me work through the request step by step.",
|
|
)
|
|
|
|
|
|
def _final_response(text="Here is the answer."):
|
|
"""An ordinary text turn that ends the loop."""
|
|
from tests.run_agent.test_run_agent import _mock_response
|
|
return _mock_response(content=text, finish_reason="stop")
|
|
|
|
|
|
def _sent_messages(create_mock, call_index):
|
|
call = create_mock.call_args_list[call_index]
|
|
return call.kwargs.get("messages") or call.args[0].get("messages")
|
|
|
|
|
|
class TestThinkingPrefillTrailingTurn:
|
|
|
|
def test_request_after_prefills_does_not_end_on_assistant(self, loop_agent):
|
|
# Two thinking-only responses queue two prefill stubs, then the model
|
|
# finally produces text. The third request is the one that used to go
|
|
# out ending on a model turn.
|
|
loop_agent.client.chat.completions.create.side_effect = [
|
|
_thinking_only_response(),
|
|
_thinking_only_response(),
|
|
_final_response(),
|
|
]
|
|
|
|
with (
|
|
patch.object(loop_agent, "_persist_session"),
|
|
patch.object(loop_agent, "_save_trajectory"),
|
|
patch.object(loop_agent, "_cleanup_task_resources"),
|
|
):
|
|
loop_agent.run_conversation("do the thing")
|
|
|
|
create = loop_agent.client.chat.completions.create
|
|
assert create.call_count >= 3, (
|
|
"Two thinking-only responses should each trigger a prefill retry."
|
|
)
|
|
|
|
final_request = _sent_messages(create, 2)
|
|
assert final_request[-1]["role"] != "assistant", (
|
|
"Request ends on a model turn, which Gemini rejects with a "
|
|
"non-retryable 400. The thinking-only prefill stubs must be "
|
|
f"dropped before send. Got roles: {[m['role'] for m in final_request]}"
|
|
)
|
|
|
|
def test_prefill_stubs_are_absent_from_the_wire_payload(self, loop_agent):
|
|
"""The stubs should be gone entirely, not merely trailed by a nudge."""
|
|
loop_agent.client.chat.completions.create.side_effect = [
|
|
_thinking_only_response(),
|
|
_final_response(),
|
|
]
|
|
|
|
with (
|
|
patch.object(loop_agent, "_persist_session"),
|
|
patch.object(loop_agent, "_save_trajectory"),
|
|
patch.object(loop_agent, "_cleanup_task_resources"),
|
|
):
|
|
loop_agent.run_conversation("do the thing")
|
|
|
|
sent = _sent_messages(loop_agent.client.chat.completions.create, 1)
|
|
empty_assistants = [
|
|
m for m in sent
|
|
if m.get("role") == "assistant" and not (m.get("content") or "").strip()
|
|
]
|
|
assert not empty_assistants, (
|
|
f"Empty assistant stub(s) reached the wire: {empty_assistants}"
|
|
)
|
|
|
|
def test_internal_marker_never_reaches_the_wire(self, loop_agent):
|
|
"""``_thinking_prefill`` survives the API-copy build on purpose, but the
|
|
transport must still keep it off the wire."""
|
|
loop_agent.client.chat.completions.create.side_effect = [
|
|
_thinking_only_response(),
|
|
_final_response(),
|
|
]
|
|
|
|
with (
|
|
patch.object(loop_agent, "_persist_session"),
|
|
patch.object(loop_agent, "_save_trajectory"),
|
|
patch.object(loop_agent, "_cleanup_task_resources"),
|
|
):
|
|
loop_agent.run_conversation("do the thing")
|
|
|
|
sent = _sent_messages(loop_agent.client.chat.completions.create, 1)
|
|
leaked = [m for m in sent if any(str(k).startswith("_") for k in m)]
|
|
assert not leaked, f"Internal scaffolding keys reached the wire: {leaked}"
|