refactor(agent): deduplicate model request preparation

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-18 00:26:19 +08:00
1 parent 1a4cee5815
commit 756f6a6fe5
2 files changed
+87 -44

No files matched your search

+58
View File
@@ -669,6 +669,64 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
]
@pytest.mark.asyncio
async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
calls: list[dict] = []
async def chat_stream_with_retry(*, messages, tools=None, **kwargs):
calls.append({"messages": messages, "tools": tools, **kwargs})
attempt = len(calls)
return LLMResponse(
content=f"attempt {attempt}" if attempt < 3 else "recovered answer",
tool_calls=(
[ToolCallRequest(id=f"bad_{attempt}", name="", arguments={})]
if attempt < 3 else []
),
finish_reason="tool_calls" if attempt < 3 else "stop",
usage=LLMUsage.reported(input_tokens=10 * attempt, output_tokens=attempt),
)
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
definitions = [{"type": "function", "function": {"name": "lookup", "parameters": {}}}]
tools.get_definitions.return_value = definitions
tools.execute = AsyncMock()
hook = AgentHook()
hook.wants_streaming = MagicMock(return_value=True)
result = await AgentRunner().run(make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
hook=hook,
))
assert result.final_content == "recovered answer"
assert result.stop_reason == "completed"
assert result.messages == [
{"role": "user", "content": "do task"},
{"role": "assistant", "content": "recovered answer"},
]
assert [item["tools"] for item in calls] == [definitions, definitions, None]
assert ["on_content_delta" in item for item in calls] == [True, True, False]
assert [item["provider_context"].response_preset for item in calls] == ["", "", ""]
assert calls[1]["messages"][-1]["content"].startswith(calls[0]["messages"][-1]["content"])
assert "attempt 1" in calls[1]["messages"][-1]["content"]
assert calls[2]["messages"][-1]["content"].startswith(calls[1]["messages"][-1]["content"])
assert "attempt 2" in calls[2]["messages"][-1]["content"]
tools.execute.assert_not_awaited()
assert result.usage is not None
assert (result.usage.input_tokens, result.usage.output_tokens) == (60, 6)
assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [(60, 6)]
@pytest.mark.asyncio
async def test_runner_replaces_empty_tool_result_with_marker():
from nanobot.agent.runner import AgentRunner