Skip to content

feat: 支持自定义开关和配置多少次工具重复调用后system notice提示#8757

Open
elecvoid243 wants to merge 4 commits into
AstrBotDevs:masterfrom
elecvoid243:tool_systemnotice
Open

feat: 支持自定义开关和配置多少次工具重复调用后system notice提示#8757
elecvoid243 wants to merge 4 commits into
AstrBotDevs:masterfrom
elecvoid243:tool_systemnotice

Conversation

@elecvoid243

@elecvoid243 elecvoid243 commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Modifications / 改动点

Resolve #8163

简述

当模型连续调用同一个工具达到一定次数时,向下一轮 prompt 注入一条 [SYSTEM NOTICE],提醒模型
之前该阈值在代码里硬编码(连续 3 / 4 / 5 次触发 L1 / L2 / L3 三档),且无法关闭。本次改动将其改造为可配置的

新增配置

provider_settings 下新增一个子配置块(默认开启,阈值 3):

provider_settings:
  repeated_tool_call_notice:
    enable: true       # 是否启用连续工具调用提醒
    threshold: 3       # 同一个工具连续调用达到此次数时触发 L1 提示
连续调用次数 行为
< threshold 不提示,正常执行
threshold 注入 L1 提示(温和版)
threshold + 1 注入 L2 提示(升级版)
threshold + 2 注入 L3 提示(严肃版)
enable: false 整个机制关闭,不再注入任何 SYSTEM NOTICE

threshold 在 runner 构造期会被规范化:非整数回退到默认值、布尔值被视为无效、负数/0 兜底为 1。

改动列表

astrbot/core/agent/runners/tool_loop_agent_runner.py

  • 删除三个硬编码阈值 REPEATED_TOOL_NOTICE_L1/L2/L3_THRESHOLD
  • 新增单一默认值 REPEATED_TOOL_NOTICE_DEFAULT_THRESHOLD = 3
  • reset() 新增构造参数:
    • repeated_tool_notice_enabled: bool = True
    • repeated_tool_notice_threshold: int = REPEATED_TOOL_NOTICE_DEFAULT_THRESHOLD
  • 新增 _normalize_repeated_tool_notice_threshold() 类方法做健壮性处理
  • _build_repeated_tool_call_guidance() 在禁用时直接返回 ""

astrbot/core/astr_main_agent.py

  • MainAgentBuildConfig 新增两个字段:
    • repeated_tool_notice_enabled: bool = True
    • repeated_tool_notice_threshold: int = 3
  • 新增 MainAgentBuildConfig.provider_settings: dict,用于在主 agent 构建时把 dashboard 端的 repeated_tool_call_notice 配置注入
  • 新增 _resolve_repeated_tool_notice_config() 辅助函数,优先读取 provider_settings["repeated_tool_call_notice"],缺失时回落到 build config 默认值
  • build_main_agent() 解析后把两个值传给 ToolLoopAgentRunner.reset()

astrbot/core/astr_agent_tool_exec.py

  • ctx.get_config().get("provider_settings", {}) 提取为局部变量
  • 构造 MainAgentBuildConfig 时一并传入 provider_settings=provider_settings,确保 sub-agent hand-off 也能继承该配置

astrbot/core/cron/manager.py

  • 同上:在 cron 触发的 chat 中把 provider_settings 透传给 MainAgentBuildConfig

astrbot/core/star/context.py

  • Context.llm_generate() 中新增配置桥接层
    • provider_settings.repeated_tool_call_notice 读取默认值
    • 仅在调用方没显式通过 kwargs 覆盖时才注入
    • 显式传参(main agent / sub-agent / cron)的优先级永远高于 dashboard 配置
    • get_config() 调用被 try/except 包裹,配置读取失败不会阻塞 LLM 调用链
    • provider_settingsnotice_cfg 都做了 isinstance(..., dict) 防御

astrbot/core/config/default.py

  • DEFAULT_CONFIG 新增 provider_settings.repeated_tool_call_notice = {"enable": true, "threshold": 3}
  • CONFIG_METADATA_2 新增对应 JSON schema(enable: bool, threshold: int
  • CONFIG_METADATA_3 新增前端元数据:
    • enableagent_runner_type == "local" 时显示
    • threshold 在上述条件 enable: true 时显示(联动隐藏)
  • 元数据自带 description / hint,dashboard 端自动渲染

前端 — i18n

三份 dashboard 翻译同步更新:

文件 状态
dashboard/src/i18n/locales/zh-CN/features/config-metadata.json ✅ 新增
dashboard/src/i18n/locales/en-US/features/config-metadata.json ✅ 新增
dashboard/src/i18n/locales/ru-RU/features/config-metadata.json ✅ 新增

测试 test/test_tool_loop_agent_runner.py

由于REPEATED_TOOL_NOTICE_L1/L2/L3_THRESHOLD常量已经废弃,修改测试脚本并补充新的行为测试

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

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

settings

将次数改为5:连续调用5次才触发
log


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.
    / 我的更改没有引入恶意代码。

@dosubot dosubot Bot added size:L This PR changes 100-499 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 13, 2026

@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:

  • The repeated_tool_call_notice config is now resolved in multiple places (ToolLoopAgentRunner._normalize_repeated_tool_notice_threshold, _resolve_repeated_tool_notice_config, Context.tool_loop_agent), which duplicates logic and defaults; consider centralizing this into a shared helper so enable/threshold semantics and fallback behavior stay consistent.
  • _resolve_repeated_tool_notice_config currently returns tuple[bool, object] and forwards an untyped threshold that is later normalized; it would be clearer to normalize the threshold there (e.g., to int >= 1) and keep the return type as tuple[bool, int] so callers don’t need to reason about non-int values.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated_tool_call_notice config is now resolved in multiple places (ToolLoopAgentRunner._normalize_repeated_tool_notice_threshold, _resolve_repeated_tool_notice_config, Context.tool_loop_agent), which duplicates logic and defaults; consider centralizing this into a shared helper so enable/threshold semantics and fallback behavior stay consistent.
- _resolve_repeated_tool_notice_config currently returns tuple[bool, object] and forwards an untyped threshold that is later normalized; it would be clearer to normalize the threshold there (e.g., to int >= 1) and keep the return type as tuple[bool, int] so callers don’t need to reason about non-int values.

## Individual Comments

### Comment 1
<location path="astrbot/core/star/context.py" line_range="240" />
<code_context>
             if k not in ["stream", "agent_hooks", "agent_context"]
         }
+
+        # 从 provider_settings 注入「连续工具调用提醒」的默认配置,
+        # 仅当调用者没有显式通过 kwargs 覆盖时生效。
+        # 字段命名与 ToolLoopAgentRunner.reset() / MainAgentBuildConfig 保持一致。
</code_context>
<issue_to_address>
**issue (complexity):** Consider extracting a shared helper to resolve the repeated-tool notice config once and then apply it via setdefault on other_kwargs to avoid duplicated logic and branching.

You can reduce duplication and branching here by reusing a single resolver and then applying `setdefault` on `other_kwargs`, instead of inlining the full resolution logic again.

For example, extract a helper (or reuse the semantics of `_resolve_repeated_tool_notice_config`) that normalizes `provider_settings` and returns `(enabled, threshold)`:

```python
# shared helper, e.g. near _resolve_repeated_tool_notice_config
def _resolve_repeated_tool_notice_from_provider_settings(provider_settings) -> tuple[bool | None, int | None]:
    if not isinstance(provider_settings, dict):
        return None, None

    notice_cfg = provider_settings.get("repeated_tool_call_notice")
    if not isinstance(notice_cfg, dict):
        return None, None

    enabled = bool(notice_cfg.get("enable", True))
    threshold = notice_cfg.get("threshold", 3)
    return enabled, threshold
```

Then the call site becomes simpler and easier to maintain:

```python
other_kwargs = {
    k: v
    for k, v in kwargs.items()
    if k not in ["stream", "agent_hooks", "agent_context"]
}

try:
    cfg = self.get_config(umo=event.unified_msg_origin)
    provider_settings = cfg.get("provider_settings", {})
except Exception:
    provider_settings = {}

enabled, threshold = _resolve_repeated_tool_notice_from_provider_settings(provider_settings)

if enabled is not None:
    other_kwargs.setdefault("repeated_tool_notice_enabled", enabled)
if threshold is not None:
    other_kwargs.setdefault("repeated_tool_notice_threshold", threshold)
```

This keeps all behavior (including defaults and `get_config` error handling) but:

- Removes the duplicated `dict` normalization / `isinstance` checks.
- Encapsulates the config semantics in a single helper shared with other call sites.
- Flattens the branching: always resolve once, then `setdefault` each kwarg independently.
</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.

if k not in ["stream", "agent_hooks", "agent_context"]
}

# 从 provider_settings 注入「连续工具调用提醒」的默认配置,

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.

issue (complexity): Consider extracting a shared helper to resolve the repeated-tool notice config once and then apply it via setdefault on other_kwargs to avoid duplicated logic and branching.

You can reduce duplication and branching here by reusing a single resolver and then applying setdefault on other_kwargs, instead of inlining the full resolution logic again.

For example, extract a helper (or reuse the semantics of _resolve_repeated_tool_notice_config) that normalizes provider_settings and returns (enabled, threshold):

# shared helper, e.g. near _resolve_repeated_tool_notice_config
def _resolve_repeated_tool_notice_from_provider_settings(provider_settings) -> tuple[bool | None, int | None]:
    if not isinstance(provider_settings, dict):
        return None, None

    notice_cfg = provider_settings.get("repeated_tool_call_notice")
    if not isinstance(notice_cfg, dict):
        return None, None

    enabled = bool(notice_cfg.get("enable", True))
    threshold = notice_cfg.get("threshold", 3)
    return enabled, threshold

Then the call site becomes simpler and easier to maintain:

other_kwargs = {
    k: v
    for k, v in kwargs.items()
    if k not in ["stream", "agent_hooks", "agent_context"]
}

try:
    cfg = self.get_config(umo=event.unified_msg_origin)
    provider_settings = cfg.get("provider_settings", {})
except Exception:
    provider_settings = {}

enabled, threshold = _resolve_repeated_tool_notice_from_provider_settings(provider_settings)

if enabled is not None:
    other_kwargs.setdefault("repeated_tool_notice_enabled", enabled)
if threshold is not None:
    other_kwargs.setdefault("repeated_tool_notice_threshold", threshold)

This keeps all behavior (including defaults and get_config error handling) but:

  • Removes the duplicated dict normalization / isinstance checks.
  • Encapsulates the config semantics in a single helper shared with other call sites.
  • Flattens the branching: always resolve once, then setdefault each kwarg independently.

@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 introduces a configurable mechanism to notify the LLM when a tool is called repeatedly, helping to prevent infinite loops. It replaces hardcoded thresholds with customizable settings (enable and threshold) under provider settings, updating the agent runner, main agent, cron manager, configuration schemas, and dashboard localization. The feedback suggests improving the return type hint of _resolve_repeated_tool_notice_config from tuple[bool, object] to tuple[bool, int] for better type safety.

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.

Comment thread astrbot/core/astr_main_agent.py Outdated
elecvoid243 and others added 2 commits June 13, 2026 17:32
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]支持自定义开关和配置多少次工具重复调用后system notice提示

1 participant