refactor(agent): compose image tools in application runtimes (#6172)
* refactor(agent): move image configuration ownership into tools * refactor(agent): compose image tools in application runtimes
This commit is contained in:
1 parent
e148296d5c
commit
105b772203
22 files changed
+269
-236
No files matched your search
@@ -2,29 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent import context as agent_context
|
||||
from nanobot.agent.tools.image_generation import (
|
||||
ImageGenerationTool,
|
||||
reload_image_generation_tool,
|
||||
request_image_generation_reload,
|
||||
)
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool, reload_image_generation_tool
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
|
||||
|
||||
def _runtime_state(tmp_path):
|
||||
return SimpleNamespace(
|
||||
workspace=tmp_path,
|
||||
tools_config=ToolsConfig(),
|
||||
_image_generation_provider_configs={},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -33,71 +15,72 @@ async def test_image_generation_reload_replaces_and_removes_live_tool(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
config = load_config()
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "other-instance.json")
|
||||
config = load_config(config_path)
|
||||
config.providers.openrouter.api_key = "first-key"
|
||||
config.tools.image_generation.enabled = True
|
||||
config.tools.image_generation.provider = "openrouter"
|
||||
config.tools.image_generation.model = "openai/first-image-model"
|
||||
save_config(config)
|
||||
save_config(config, config_path)
|
||||
|
||||
state = _runtime_state(tmp_path)
|
||||
registry = ToolRegistry()
|
||||
result = await reload_image_generation_tool(state, registry)
|
||||
assert registry.get_definitions() == []
|
||||
result = await reload_image_generation_tool(config_path=config_path, workspace=tmp_path, registry=registry)
|
||||
|
||||
first_tool = registry.get("generate_image")
|
||||
assert result["requires_restart"] is False
|
||||
assert isinstance(first_tool, ImageGenerationTool)
|
||||
assert first_tool.config.model == "openai/first-image-model"
|
||||
assert first_tool.provider_configs["openrouter"].api_key == "first-key"
|
||||
assert [definition["function"]["name"] for definition in registry.get_definitions()] == [
|
||||
"generate_image"
|
||||
]
|
||||
|
||||
config = load_config()
|
||||
config = load_config(config_path)
|
||||
config.providers.openrouter.api_key = "second-key"
|
||||
config.tools.image_generation.model = "openai/second-image-model"
|
||||
save_config(config)
|
||||
save_config(config, config_path)
|
||||
|
||||
result = await reload_image_generation_tool(state, registry)
|
||||
result = await reload_image_generation_tool(config_path=config_path, workspace=tmp_path, registry=registry)
|
||||
second_tool = registry.get("generate_image")
|
||||
assert result["requires_restart"] is False
|
||||
assert isinstance(second_tool, ImageGenerationTool)
|
||||
assert second_tool is not first_tool
|
||||
assert second_tool.config.model == "openai/second-image-model"
|
||||
assert second_tool.provider_configs["openrouter"].api_key == "second-key"
|
||||
assert state.tools_config.image_generation.model == "openai/second-image-model"
|
||||
|
||||
config = load_config()
|
||||
config = load_config(config_path)
|
||||
config.tools.image_generation.enabled = False
|
||||
save_config(config)
|
||||
save_config(config, config_path)
|
||||
|
||||
result = await reload_image_generation_tool(state, registry)
|
||||
result = await reload_image_generation_tool(config_path=config_path, workspace=tmp_path, registry=registry)
|
||||
assert result["requires_restart"] is False
|
||||
assert not registry.has("generate_image")
|
||||
assert registry.get_definitions() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_generation_reload_reaches_agent_runtime_control(
|
||||
async def test_image_generation_reload_failure_preserves_live_tool(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
config = load_config()
|
||||
config.providers.openrouter.api_key = "image-key"
|
||||
config = load_config(config_path)
|
||||
config.tools.image_generation.enabled = True
|
||||
save_config(config)
|
||||
|
||||
bus = MessageBus()
|
||||
state = _runtime_state(tmp_path)
|
||||
config.providers.openrouter.api_key = "working-key"
|
||||
save_config(config, config_path)
|
||||
registry = ToolRegistry()
|
||||
await reload_image_generation_tool(config_path=config_path, workspace=tmp_path, registry=registry)
|
||||
working_tool = registry.get("generate_image")
|
||||
definitions = registry.get_definitions()
|
||||
|
||||
async def consume_control() -> None:
|
||||
message = await bus.consume_inbound()
|
||||
assert await agent_context.handle_runtime_control(state, message, registry) is True
|
||||
missing_env = "NANOBOT_TEST_IMAGE_RELOAD_KEY"
|
||||
monkeypatch.delenv(missing_env, raising=False)
|
||||
config.providers.openrouter.api_key = f"${{{missing_env}}}"
|
||||
save_config(config, config_path)
|
||||
result = await reload_image_generation_tool(config_path=config_path, workspace=tmp_path, registry=registry)
|
||||
|
||||
consumer = asyncio.create_task(consume_control())
|
||||
result = await request_image_generation_reload(bus, timeout=2.0)
|
||||
await consumer
|
||||
|
||||
assert result["ok"] is True
|
||||
assert result["requires_restart"] is False
|
||||
assert registry.has("generate_image")
|
||||
assert result["ok"] is False
|
||||
assert result["requires_restart"] is True
|
||||
assert registry.get("generate_image") is working_tool
|
||||
assert registry.get_definitions() == definitions
|
||||
@@ -7,10 +7,12 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.image_generation import register_image_generation_tool
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.loader import set_config_path
|
||||
from nanobot.config.schema import ImageGenerationToolConfig, ProviderConfig, ToolsConfig
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.image_generation import GeneratedImageResponse
|
||||
|
||||
@@ -58,15 +60,18 @@ async def test_generate_image_does_not_attach_media_to_final_response(
|
||||
LLMResponse(content="Done", finish_reason="stop"),
|
||||
]
|
||||
)
|
||||
config = Config()
|
||||
config.tools.image_generation.enabled = True
|
||||
config.providers.openrouter.api_key = "sk-or-test"
|
||||
tools = ToolRegistry()
|
||||
register_image_generation_tool(config, tools, workspace=tmp_path)
|
||||
loop = AgentLoop(
|
||||
bus=MessageBus(),
|
||||
provider=provider,
|
||||
workspace=tmp_path,
|
||||
model="test-model",
|
||||
tools_config=ToolsConfig(
|
||||
image_generation=ImageGenerationToolConfig(enabled=True),
|
||||
),
|
||||
image_generation_provider_config=ProviderConfig(api_key="sk-or-test"),
|
||||
tools_config=config.tools,
|
||||
tool_registry=tools,
|
||||
)
|
||||
|
||||
result = await loop._process_message(
|
||||
|
||||
@@ -13,6 +13,7 @@ from nanobot.agent.tools.context import (
|
||||
current_request_context,
|
||||
reset_request_context,
|
||||
)
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool, register_image_generation_tool
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -105,6 +106,28 @@ def test_loop_from_config_uses_caller_owned_registry(tmp_path: Path) -> None:
|
||||
assert loop.tools.has("read_file")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider_name", ["openrouter", "aihubmix"])
|
||||
def test_loop_uses_pre_registered_image_tool(
|
||||
tmp_path: Path,
|
||||
provider_name: str,
|
||||
) -> None:
|
||||
config = _config_for_loop(tmp_path)
|
||||
config.tools.image_generation.enabled = True
|
||||
config.tools.image_generation.provider = provider_name
|
||||
getattr(config.providers, provider_name).api_key = "configured-image-key"
|
||||
registry = ToolRegistry()
|
||||
register_image_generation_tool(config, registry, workspace=config.workspace_path)
|
||||
configured_tool = registry.get("generate_image")
|
||||
loop = AgentLoop.from_config(config, tool_registry=registry, provider=_provider_for_loop())
|
||||
|
||||
tool = registry.get("generate_image")
|
||||
assert loop.tools is registry
|
||||
assert isinstance(tool, ImageGenerationTool)
|
||||
assert tool is configured_tool
|
||||
assert tool.provider_configs[provider_name].api_key == "configured-image-key"
|
||||
assert registry.has("read_file")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_loop_binds_request_context_for_tool_execution(tmp_path: Path) -> None:
|
||||
provider = MagicMock()
|
||||
|
||||
@@ -118,6 +118,23 @@ def test_from_config_composes_configured_mcp_outside_agent_loop(tmp_path):
|
||||
assert bot._mcp_provider._registry is bot._loop.tools
|
||||
|
||||
|
||||
def test_from_config_uses_instance_image_settings(tmp_path, monkeypatch):
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool
|
||||
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "default.json")
|
||||
config_path = _write_config(
|
||||
tmp_path,
|
||||
{"tools": {"imageGeneration": {"enabled": True, "model": "instance-image-model"}}},
|
||||
)
|
||||
|
||||
bot = Nanobot.from_config(config_path, workspace=tmp_path)
|
||||
|
||||
tool = bot._loop.tools.get("generate_image")
|
||||
assert isinstance(tool, ImageGenerationTool)
|
||||
assert tool.config.model == "instance-image-model"
|
||||
assert tool.provider_configs["openrouter"].api_key == "sk-test-key"
|
||||
|
||||
|
||||
def test_from_config_accepts_default_model_override(tmp_path):
|
||||
config_path = _write_config(tmp_path)
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ def test_tool_context_has_required_fields():
|
||||
required = {
|
||||
"config", "workspace", "bus", "subagent_manager",
|
||||
"cron_service", "exec_session_manager", "file_state_store",
|
||||
"provider_snapshot_loader", "image_generation_provider_configs", "timezone",
|
||||
"provider_snapshot_loader", "providers_config", "timezone",
|
||||
"runtime_control",
|
||||
}
|
||||
assert required <= field_names
|
||||
@@ -72,7 +72,7 @@ def test_tool_context_defaults():
|
||||
assert ctx.cron_service is None
|
||||
assert ctx.exec_session_manager is None
|
||||
assert ctx.provider_snapshot_loader is None
|
||||
assert ctx.image_generation_provider_configs is None
|
||||
assert ctx.providers_config is None
|
||||
assert ctx.runtime_control is None
|
||||
assert ctx.timezone == "UTC"
|
||||
|
||||
@@ -175,6 +175,23 @@ def test_loader_wires_shared_exec_session_manager(tmp_path):
|
||||
assert "write_stdin" not in definition_names
|
||||
|
||||
|
||||
def test_loader_preserves_caller_supplied_tool(tmp_path):
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
|
||||
tool = ReadFileTool(workspace=tmp_path / "custom-root")
|
||||
registry = ToolRegistry()
|
||||
registry.register(tool)
|
||||
|
||||
registered = ToolLoader(test_classes=[ReadFileTool]).load(
|
||||
ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry,
|
||||
)
|
||||
|
||||
assert registry.get("read_file") is tool
|
||||
assert "read_file" not in registered
|
||||
|
||||
|
||||
# --- Task 4: _FsTool.create() ---
|
||||
|
||||
|
||||
@@ -344,9 +361,10 @@ def test_image_gen_tool_config_cls():
|
||||
|
||||
def test_image_gen_tool_enabled():
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool
|
||||
from nanobot.config.schema import ProvidersConfig
|
||||
mock_config = MagicMock()
|
||||
mock_config.image_generation.enabled = True
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp")
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp", providers_config=ProvidersConfig())
|
||||
assert ImageGenerationTool.enabled(ctx) is True
|
||||
mock_config.image_generation.enabled = False
|
||||
assert ImageGenerationTool.enabled(ctx) is False
|
||||
@@ -354,14 +372,16 @@ def test_image_gen_tool_enabled():
|
||||
|
||||
def test_image_gen_tool_create():
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool
|
||||
from nanobot.config.schema import ProviderConfig, ProvidersConfig
|
||||
mock_config = MagicMock()
|
||||
mock_config.image_generation = MagicMock()
|
||||
ctx = ToolContext(
|
||||
config=mock_config, workspace="/tmp",
|
||||
image_generation_provider_configs={"openrouter": MagicMock()},
|
||||
providers_config=ProvidersConfig(openrouter=ProviderConfig(api_key="image-key")),
|
||||
)
|
||||
tool = ImageGenerationTool.create(ctx)
|
||||
assert isinstance(tool, ImageGenerationTool)
|
||||
assert tool.provider_configs["openrouter"].api_key == "image-key"
|
||||
|
||||
|
||||
# --- Task 7: MyToolConfig + MCP wrappers ---
|
||||
|
||||
@@ -25,6 +25,7 @@ def _router(
|
||||
config_path: Path | None = None,
|
||||
mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None,
|
||||
mcp_reload: Callable[[], Awaitable[dict[str, object]]] | None = None,
|
||||
image_generation_reload: Callable[[], Awaitable[dict[str, object]]] | None = None,
|
||||
rename_model_preset: Callable[[str, str], int] | None = None,
|
||||
refresh_runtime_config: Callable[[], None] | None = None,
|
||||
) -> WebUISettingsRouter:
|
||||
@@ -47,6 +48,7 @@ def _router(
|
||||
runtime_capabilities={},
|
||||
mcp_runtime_status=mcp_runtime_status,
|
||||
mcp_reload=mcp_reload,
|
||||
image_generation_reload=image_generation_reload,
|
||||
mcp_oauth_redirect_uri=lambda _request: "https://gateway.example/auth/mcp/callback",
|
||||
)
|
||||
|
||||
@@ -657,7 +659,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
async def test_image_switch_round_trip_clears_restart(tmp_path, monkeypatch, enabled):
|
||||
async def test_image_switch_round_trip_clears_restart(tmp_path, enabled):
|
||||
from nanobot.config.loader import save_config
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
@@ -666,11 +668,10 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, monkeypatch, ena
|
||||
config.tools.image_generation.enabled = enabled
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.request_image_generation_reload",
|
||||
AsyncMock(return_value={"ok": False, "requires_restart": True}),
|
||||
router = _router(
|
||||
config_path=config_path,
|
||||
image_generation_reload=AsyncMock(return_value={"ok": False, "requires_restart": True}),
|
||||
)
|
||||
router = _router(config_path=config_path)
|
||||
router.logger.warning = MagicMock()
|
||||
path = "/api/settings/image-generation/update"
|
||||
changed = await router.dispatch(None, _mutation_request(path, {"enabled": not enabled}), path)
|
||||
|
||||
Reference in new issue
Block a user