Skip to content

fix: preserve fallback models for future tasks#9054

Open
catDforD wants to merge 2 commits into
AstrBotDevs:masterfrom
catDforD:fix/8996-future-task-fallback
Open

fix: preserve fallback models for future tasks#9054
catDforD wants to merge 2 commits into
AstrBotDevs:masterfrom
catDforD:fix/8996-future-task-fallback

Conversation

@catDforD

@catDforD catDforD commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Closes #8996

Modifications / 改动点

  • 修复未来任务触发主 Agent 时未传递 provider_settings 的问题。

  • 让未来任务路径能够正确读取 fallback_chat_models,主模型请求失败后可继续切换到备选模型。

  • 增加回归测试,验证 active cron/future task 唤醒 Agent 时会保留 fallback 模型配置。

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

  • 修复前,未来任务在主模型不可用的情况下不会自动切到备用模型:
0cb75e17a7674924d52f4b0b591517da 00da39ba3a40772124d611560618afac
  • 修复后,未来任务能够在主模型不可用的情况下自动切到备用模型:
c59bfb847a81af40dace4a4e56649672 17ab4f9f46fb44aa83c626cd1f71db55

Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Ensure cron-triggered agent executions preserve provider settings, including fallback models, when waking the main agent.

Bug Fixes:

  • Preserve provider settings, including tool_call_timeout and fallback_chat_models, when running the main agent from active cron or future tasks so fallback models continue to work if the primary model fails.

Tests:

  • Add unit test verifying that waking the main agent from an active cron job passes through provider_settings and retains fallback_chat_models in the agent build configuration.

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. area:core The bug / feature is about astrbot's core, backend area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. labels Jun 27, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the cron manager to extract and pass provider_settings to the MainAgentBuildConfig when waking up the main agent, ensuring settings like fallback chat models are preserved. It also adds a corresponding unit test to verify this behavior and appends test.md to .gitignore. There are no review comments, so I have no feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In _woke_main_agent, consider passing a shallow copy of provider_settings into MainAgentBuildConfig (e.g., provider_settings = dict(provider_settings)), to avoid unexpected side effects if MainAgentBuildConfig or downstream logic mutates the dict that is also stored in ctx.get_config().
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `_woke_main_agent`, consider passing a shallow copy of `provider_settings` into `MainAgentBuildConfig` (e.g., `provider_settings = dict(provider_settings)`), to avoid unexpected side effects if `MainAgentBuildConfig` or downstream logic mutates the dict that is also stored in `ctx.get_config()`.

## Individual Comments

### Comment 1
<location path="tests/unit/test_cron_manager.py" line_range="540-541" />
<code_context>
+class TestRunActiveAgentJob:
+    """Tests for active agent cron job execution."""
+
+    @pytest.mark.asyncio
+    async def test_woke_main_agent_passes_provider_settings(self, cron_manager):
+        """Test active cron agent keeps fallback chat model settings."""
+        provider_settings = {
</code_context>
<issue_to_address>
**suggestion (testing):** Consider adding a complementary test for when `provider_settings` is missing or `None` to cover the default behavior.

This only exercises the case where `provider_settings` is present. Please add a test where `ctx.get_config.return_value` either omits `provider_settings` or sets it to `None`, and assert that `MainAgentBuildConfig.tool_call_timeout` falls back to `120` and that `provider_settings` becomes an empty dict (or whatever the expected behavior is). That will protect against regressions in handling misconfigured or legacy configs.

Suggested implementation:

```python
class TestRunActiveAgentJob:
    """Tests for active agent cron job execution."""

    @pytest.mark.asyncio
    async def test_woke_main_agent_passes_provider_settings(self, cron_manager):
        """Test active cron agent keeps fallback chat model settings."""
        provider_settings = {
            "tool_call_timeout": 77,
            "fallback_chat_models": ["fallback-provider"],
        }
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            "provider_settings": provider_settings,
        }
        cron_manager.ctx = ctx

        # Exercise the code path that builds the MainAgentBuildConfig
        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # Ensure that provider_settings are passed through correctly
        assert main_agent_build_config.provider_settings == provider_settings
        assert (
            main_agent_build_config.tool_call_timeout
            == provider_settings["tool_call_timeout"]
        )

    @pytest.mark.asyncio
    async def test_woke_main_agent_uses_defaults_when_provider_settings_missing(
        self, cron_manager
    ):
        """Test default behavior when provider_settings is missing from config."""
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            # Note: provider_settings is intentionally omitted to test defaults
        }
        cron_manager.ctx = ctx

        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # When provider_settings is missing, we expect it to default to an empty dict
        assert main_agent_build_config.provider_settings == {}
        # And tool_call_timeout should fall back to the default of 120 seconds
        assert main_agent_build_config.tool_call_timeout == 120

    @pytest.mark.asyncio
    async def test_woke_main_agent_uses_defaults_when_provider_settings_is_none(
        self, cron_manager
    ):
        """Test default behavior when provider_settings is explicitly set to None."""
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            "provider_settings": None,
        }
        cron_manager.ctx = ctx

        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # When provider_settings is None, we expect it to be normalized to an empty dict
        assert main_agent_build_config.provider_settings == {}
        # And tool_call_timeout should again fall back to the default of 120 seconds
        assert main_agent_build_config.tool_call_timeout == 120

```

The above changes assume that:
1. There is an async method `cron_manager._get_main_agent_build_config()` that returns a `MainAgentBuildConfig` object.
2. `MainAgentBuildConfig` exposes `provider_settings` and `tool_call_timeout` attributes, and the default `tool_call_timeout` is `120`.

If your cron manager uses a different method name or return type:
- Replace `_get_main_agent_build_config()` with the actual method that constructs the main agent build config for the active agent job.
- Adjust the attribute access (`provider_settings`, `tool_call_timeout`) to match the real `MainAgentBuildConfig` (or equivalent) API.
- If the default timeout is configured elsewhere (e.g., a constant), you may want to import and assert against that constant instead of the hard-coded `120` to keep the test aligned with configuration defaults.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +540 to +541
@pytest.mark.asyncio
async def test_woke_main_agent_passes_provider_settings(self, cron_manager):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Consider adding a complementary test for when provider_settings is missing or None to cover the default behavior.

This only exercises the case where provider_settings is present. Please add a test where ctx.get_config.return_value either omits provider_settings or sets it to None, and assert that MainAgentBuildConfig.tool_call_timeout falls back to 120 and that provider_settings becomes an empty dict (or whatever the expected behavior is). That will protect against regressions in handling misconfigured or legacy configs.

Suggested implementation:

class TestRunActiveAgentJob:
    """Tests for active agent cron job execution."""

    @pytest.mark.asyncio
    async def test_woke_main_agent_passes_provider_settings(self, cron_manager):
        """Test active cron agent keeps fallback chat model settings."""
        provider_settings = {
            "tool_call_timeout": 77,
            "fallback_chat_models": ["fallback-provider"],
        }
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            "provider_settings": provider_settings,
        }
        cron_manager.ctx = ctx

        # Exercise the code path that builds the MainAgentBuildConfig
        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # Ensure that provider_settings are passed through correctly
        assert main_agent_build_config.provider_settings == provider_settings
        assert (
            main_agent_build_config.tool_call_timeout
            == provider_settings["tool_call_timeout"]
        )

    @pytest.mark.asyncio
    async def test_woke_main_agent_uses_defaults_when_provider_settings_missing(
        self, cron_manager
    ):
        """Test default behavior when provider_settings is missing from config."""
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            # Note: provider_settings is intentionally omitted to test defaults
        }
        cron_manager.ctx = ctx

        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # When provider_settings is missing, we expect it to default to an empty dict
        assert main_agent_build_config.provider_settings == {}
        # And tool_call_timeout should fall back to the default of 120 seconds
        assert main_agent_build_config.tool_call_timeout == 120

    @pytest.mark.asyncio
    async def test_woke_main_agent_uses_defaults_when_provider_settings_is_none(
        self, cron_manager
    ):
        """Test default behavior when provider_settings is explicitly set to None."""
        ctx = MagicMock()
        ctx.get_config.return_value = {
            "admins_id": [],
            "provider_settings": None,
        }
        cron_manager.ctx = ctx

        main_agent_build_config = await cron_manager._get_main_agent_build_config()

        # When provider_settings is None, we expect it to be normalized to an empty dict
        assert main_agent_build_config.provider_settings == {}
        # And tool_call_timeout should again fall back to the default of 120 seconds
        assert main_agent_build_config.tool_call_timeout == 120

The above changes assume that:

  1. There is an async method cron_manager._get_main_agent_build_config() that returns a MainAgentBuildConfig object.
  2. MainAgentBuildConfig exposes provider_settings and tool_call_timeout attributes, and the default tool_call_timeout is 120.

If your cron manager uses a different method name or return type:

  • Replace _get_main_agent_build_config() with the actual method that constructs the main agent build config for the active agent job.
  • Adjust the attribute access (provider_settings, tool_call_timeout) to match the real MainAgentBuildConfig (or equivalent) API.
  • If the default timeout is configured elsewhere (e.g., a constant), you may want to import and assert against that constant instead of the hard-coded 120 to keep the test aligned with configuration defaults.

Comment thread .gitignore Outdated
# Other
chroma
venv/*
test.md

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

可以删了,保持changes干净

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@itxaiohanglover

Copy link
Copy Markdown

Good fix! Preserving provider_settings in the cron agent build config ensures fallback models and other provider-specific settings work in scheduled tasks. The defensive for None provider_settings is a nice touch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]未来任务在主模型无响应后不会自动切换至备选模型

3 participants