Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Comments

fix: 修复prompt#133

Merged
JohnRichard4096 merged 2 commits intomainfrom
fix-chat
Jan 5, 2026
Merged

fix: 修复prompt#133
JohnRichard4096 merged 2 commits intomainfrom
fix-chat

Conversation

@JohnRichard4096
Copy link
Member

@JohnRichard4096 JohnRichard4096 commented Jan 5, 2026

Summary by Sourcery

在优化工具观察消息并升级软件包版本的同时,改进聊天提示词构造、配置使用方式和管理员处理逻辑。

新特性:

  • 当启用记忆抽象时,在 system prompt 中包含先前会话的摘要。

漏洞修复:

  • 通过仅在内容存在时,将消息列表和工具观察结果包裹在显式的纯文本代码块中,修正用于摘要生成和聊天的提示词格式。
  • 在解析昵称和 cookie 占位符时,使用聊天处理器的本地配置,而不是全局配置管理器。
  • 当没有工具结果时,避免发送空的观察消息。

增强:

  • 通过将机器人管理员检查委托给共享的 is_lp_admin 辅助函数,并移除未使用的管理员配置和辅助 API,来简化管理员授权逻辑。

构建:

  • 将项目版本从 0.5.3 升级到 0.5.3.1。
Original summary in English

Summary by Sourcery

Refine chat prompt construction, configuration usage, and admin handling while tightening tool observation messaging and bumping the package version.

New Features:

  • Include prior conversation summary in the system prompt when memory abstraction is enabled.

Bug Fixes:

  • Correct prompt formatting for abstract generation and chat by wrapping message lists and tool observations in explicit text code fences only when content exists.
  • Use the chat handler's local configuration instead of the global config manager when resolving nickname and cookie placeholders.
  • Avoid sending empty observation messages when no tool results are available.

Enhancements:

  • Simplify admin authorization logic by delegating bot admin checks to the shared is_lp_admin helper and removing unused admin configuration and helper APIs.

Build:

  • Bump project version from 0.5.3 to 0.5.3.1.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 5, 2026

Reviewer's Guide

调整用于聊天交互的提示词构建和系统 schema,修复配置使用引用,对工具观察消息进行条件发送,简化与管理员相关的配置和检查,并将包的补丁版本号向上调整。

run_tools 中条件工具观察消息的时序图

sequenceDiagram
    participant Caller
    participant run_tools
    participant Bot
    participant LLM

    Caller->>run_tools: call run_tools(msg_list, event, call_count, original_msg)
    loop for each tool_result
        run_tools->>Bot: send(nonebot_event, message) when message_mode == show
        Bot-->>run_tools: ack
    end
    alt result_msg_list is not empty
        run_tools->>run_tools: build observation_msg from result_msg_list
        run_tools->>run_tools: append Message(role user, content observation_block) to msg_list
        run_tools->>LLM: send updated msg_list for next reasoning
        LLM-->>run_tools: tool-aware response
    else result_msg_list is empty
        run_tools->>LLM: send msg_list without observation_msg
        LLM-->>run_tools: response without new observations
    end
    run_tools-->>Caller: recursive processing continues
Loading

更新后的聊天配置和管理员 API 类图

classDiagram
    class Config {
        +FunctionConfig function
        +ExtendConfig extended
        +LLM_Config llm_config
        +UsageLimitConfig usage_limit
        +dict~str,Any~ extra
    }

    class FunctionConfig {
    }

    class ExtendConfig {
    }

    class LLM_Config {
        +bool enable_memory_abstract
    }

    class UsageLimitConfig {
        +bool enable_usage_limit
        +int group_daily_limit
        +int user_daily_limit
    }

    class Admin {
        +Config config
        +Bot bot
        +Event event
        +async send_error(msg str) Admin
    }

    %% 本 PR 中移除的类
    class AdminConfig_removed {
        +bool allow_send_to_admin
        +list~int~ admins
        +int admin_group
    }

    Config *-- FunctionConfig
    Config *-- ExtendConfig
    Config *-- LLM_Config
    Config *-- UsageLimitConfig

    Admin *-- Config
Loading

文件级变更

Change Details Files
优化用于摘要生成和主聊天提示词的提示构建和 schema,包括摘要注入以及正确的配置使用。
  • 在构建用于摘要生成的用户消息时,将被丢弃的消息包装在带标签的围栏文本块中。
  • 通过拼接 schema、系统提示标签以及可选的会话摘要来构建主系统提示,而不是使用单个长字面量。
  • 在替换提示占位符和检查功能开关时,使用实例级配置而不是全局的 config_manager。
  • 当启用记忆抽象功能时,追加带有记忆摘要内容的 标签。
amrita/plugins/chat/handlers/chat.py
仅在实际存在工具结果时才向模型发送工具观察消息。
  • 在构造观察消息以及追加用户 Message 前添加检查,确保工具结果列表非空。
  • 在保持围栏格式的前提下,将观察消息构造方式从按行拼接改为简单字符串拼接。
amrita/plugins/chat/builtin_hook.py
从聊天插件中移除未使用的管理员专用配置结构和 API,改为依赖已有的管理员检查逻辑。
  • 删除 AdminConfig 定义以及其在聊天配置主 Config 模型中的集成。
  • 移除依赖已删 AdminConfig 的 Chat.is_admin 辅助方法。
  • 将 is_bot_admin 规则检查改为委托给 is_lp_admin,而不是从聊天配置中读取管理员 ID。
amrita/plugins/chat/config.py
amrita/plugins/chat/API.py
amrita/plugins/chat/check_rule.py
提升包的补丁版本以体现此次缺陷修复发布。
  • 将项目版本号从 0.5.3 增加到 0.5.3.1。
pyproject.toml

提示与命令

与 Sourcery 交互

  • 触发新的评审: 在 pull request 中评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的评审评论。
  • 从评审评论生成 GitHub issue: 在评审评论下回复,请求 Sourcery 从该评论创建 issue。你也可以在评审评论中回复 @sourcery-ai issue 来从该评论创建一个 issue。
  • 生成 pull request 标题: 在 pull request 标题的任意位置写上 @sourcery-ai 即可在任意时间生成标题。你也可以在 pull request 中评论 @sourcery-ai title 来(重新)生成标题。
  • 生成 pull request 总结: 在 pull request 正文的任意位置写上 @sourcery-ai summary,即可在任意时间在指定位置生成 PR 总结。你也可以在 pull request 中评论 @sourcery-ai summary 来(重新)生成总结。
  • 生成评审者指南: 在 pull request 中评论 @sourcery-ai guide,即可在任意时间(重新)生成评审者指南。
  • 解决所有 Sourcery 评论: 在 pull request 中评论 @sourcery-ai resolve,以解决所有 Sourcery 评论。如果你已经处理完所有评论且不想再看到它们,这会很有用。
  • 撤销所有 Sourcery 评审: 在 pull request 中评论 @sourcery-ai dismiss,以撤销所有现有的 Sourcery 评审。特别适用于你希望从一次全新的评审开始的情况——别忘了随后评论 @sourcery-ai review 来触发新的评审!

自定义你的体验

访问你的 dashboard 以:

  • 启用或禁用评审功能,例如 Sourcery 生成的 pull request 总结、评审者指南等。
  • 更改评审语言。
  • 添加、移除或编辑自定义评审指令。
  • 调整其他评审设置。

获取帮助

Original review guide in English

Reviewer's Guide

Adjusts prompt construction and system schema for chat interactions, fixes config usage references, conditions tool observation messages, simplifies admin-related configuration and checks, and bumps the package patch version.

Sequence diagram for conditional tool observation message in run_tools

sequenceDiagram
    participant Caller
    participant run_tools
    participant Bot
    participant LLM

    Caller->>run_tools: call run_tools(msg_list, event, call_count, original_msg)
    loop for each tool_result
        run_tools->>Bot: send(nonebot_event, message) when message_mode == show
        Bot-->>run_tools: ack
    end
    alt result_msg_list is not empty
        run_tools->>run_tools: build observation_msg from result_msg_list
        run_tools->>run_tools: append Message(role user, content observation_block) to msg_list
        run_tools->>LLM: send updated msg_list for next reasoning
        LLM-->>run_tools: tool-aware response
    else result_msg_list is empty
        run_tools->>LLM: send msg_list without observation_msg
        LLM-->>run_tools: response without new observations
    end
    run_tools-->>Caller: recursive processing continues
Loading

Class diagram for updated chat configuration and admin API

classDiagram
    class Config {
        +FunctionConfig function
        +ExtendConfig extended
        +LLM_Config llm_config
        +UsageLimitConfig usage_limit
        +dict~str,Any~ extra
    }

    class FunctionConfig {
    }

    class ExtendConfig {
    }

    class LLM_Config {
        +bool enable_memory_abstract
    }

    class UsageLimitConfig {
        +bool enable_usage_limit
        +int group_daily_limit
        +int user_daily_limit
    }

    class Admin {
        +Config config
        +Bot bot
        +Event event
        +async send_error(msg str) Admin
    }

    %% Removed class in this PR
    class AdminConfig_removed {
        +bool allow_send_to_admin
        +list~int~ admins
        +int admin_group
    }

    Config *-- FunctionConfig
    Config *-- ExtendConfig
    Config *-- LLM_Config
    Config *-- UsageLimitConfig

    Admin *-- Config
Loading

File-Level Changes

Change Details Files
Refine prompt construction and schema for abstract generation and main chat prompt, including summary injection and correct config usage.
  • Wrap dropped messages in a labeled fenced text block when building the abstract-generation user message.
  • Build the main system prompt by concatenating schema, system prompt tags, and optional conversation summary instead of a single long literal.
  • Use the instance config instead of the global config_manager when replacing prompt placeholders and checking feature flags.
  • Append a tag with memory abstract content when memory abstraction is enabled.
amrita/plugins/chat/handlers/chat.py
Only send tool observation messages to the model when there are actual tool results.
  • Guard construction of the observation message and appended user Message with a check that the tool result list is non-empty.
  • Change observation message construction from joined lines to simple string concatenation while keeping fenced formatting.
amrita/plugins/chat/builtin_hook.py
Remove unused admin-specific config structures and APIs from the chat plugin and rely on existing admin checks instead.
  • Delete AdminConfig definition and its integration into the main Config model in chat config.
  • Remove the Chat.is_admin helper that depended on the removed AdminConfig.
  • Change is_bot_admin rule check to delegate to is_lp_admin instead of reading admin IDs from chat config.
amrita/plugins/chat/config.py
amrita/plugins/chat/API.py
amrita/plugins/chat/check_rule.py
Bump package patch version to reflect the bugfix release.
  • Increment project version from 0.5.3 to 0.5.3.1.
pyproject.toml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - 我发现了两个问题,并给出了一些整体性的反馈:

  • 新的摘要 content 构造方式("消息列表:\n```text".join([...]) + "```")会在每个条目之间都插入这一行头部,而不是只在开头插入一次,而且在 text 之后缺少一个换行符;建议显式构造,例如:`"消息列表:\ntext\n" + "".join(...) + "```"`。
  • self.train["content"] 中新加入的 <SUMMARY> 段落缺少对应的闭合标签 </SUMMARY>,但 schema 文本表明它应该是成对标签;将摘要内容同时包裹在起始和结束标签中会更清晰、更安全。
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- 新的摘要 `content` 构造方式(`"消息列表:\n```text".join([...]) + "```"`)会在每个条目之间都插入这一行头部,而不是只在开头插入一次,而且在 ```text 之后缺少一个换行符;建议显式构造,例如:`"消息列表:\n```text\n" + "".join(...) + "```"`。
-`self.train["content"]` 中新加入的 `<SUMMARY>` 段落缺少对应的闭合标签 `</SUMMARY>`,但 schema 文本表明它应该是成对标签;将摘要内容同时包裹在起始和结束标签中会更清晰、更安全。

## Individual Comments

### Comment 1
<location> `amrita/plugins/chat/handlers/chat.py:205-206` </location>
<code_context>
-                            self._dropped_messages + dropped_part, split_role=True
-                        )
-                    ]
+                content=(
+                    "消息列表:\n```text".join(
+                        [
+                            f"{it}\n"
</code_context>

<issue_to_address>
**issue (bug_risk):** 使用 `"消息列表:\n```text".join(...)` 会导致在每条消息之间重复这一行头部,而不是只在最前面加上它。

由于头部字符串被用作 `join` 的分隔符,结果会是 `seg1 + header + seg2 + ...`,而不是在完整内容前只有一个头部。如果你希望只有一个头部和一对代码块标记,建议先把所有条目拼接,再整体包一层,比如:

```python
content = (
    "消息列表:\n```text\n"
    + "".join(
        f"{it}\n" for it in text_generator(
            self._dropped_messages + dropped_part, split_role=True
        )
    )
    + "```"
)
```
</issue_to_address>

### Comment 2
<location> `amrita/plugins/chat/handlers/chat.py:477` </location>
<code_context>
                 .replace("{user_name}", str(event.sender.nickname))
             )
             + "\n</SYSTEM_PROMPT>"
+            + f"\n<SUMMARY>{data.memory_abstract if config.llm_config.enable_memory_abstract else ''}"
         )
         async with MemoryLimiter(self.data, self.train) as lim:
</code_context>

<issue_to_address>
**issue (bug_risk):** `<SUMMARY>` 标签被打开但从未关闭,这与 schema 描述不一致,也可能导致后续解析出错。

在 schema 中 `<SUMMARY>` 被视为成对标签,但这里只输出了起始标签,没有对应的 `</SUMMARY>` 闭合标签。这可能会破坏期望结构良好的标签的下游消费者。建议将内容包裹为完整的一对标签:

```python
summary = data.memory_abstract if config.llm_config.enable_memory_abstract else ""
self.train["content"] = (
    ...
    + "\n</SYSTEM_PROMPT>"
    + f"\n<SUMMARY>{summary}</SUMMARY>"
)
```
</issue_to_address>

Sourcery 对开源项目是免费的——如果你觉得我们的代码审查有帮助,欢迎分享 ✨
帮我变得更有用!请在每条评论上点 👍 或 👎,我会根据你的反馈改进后续的代码审查。
Original comment in English

Hey - I've found 2 issues, and left some high level feedback:

  • The new content construction for the abstract ("消息列表:\n```text".join([...]) + "```") will insert the header between every item instead of once at the beginning and also omits a newline after text; consider building it explicitly, e.g. `"消息列表:\ntext\n" + "".join(...) + "```"`.
  • The newly added <SUMMARY> section in self.train["content"] is missing a closing </SUMMARY> tag even though the schema text implies a tag pair; it would be clearer and safer to wrap the summary content with both opening and closing tags.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `content` construction for the abstract (`"消息列表:\n```text".join([...]) + "```"`) will insert the header between every item instead of once at the beginning and also omits a newline after ```text; consider building it explicitly, e.g. `"消息列表:\n```text\n" + "".join(...) + "```"`.
- The newly added `<SUMMARY>` section in `self.train["content"]` is missing a closing `</SUMMARY>` tag even though the schema text implies a tag pair; it would be clearer and safer to wrap the summary content with both opening and closing tags.

## Individual Comments

### Comment 1
<location> `amrita/plugins/chat/handlers/chat.py:205-206` </location>
<code_context>
-                            self._dropped_messages + dropped_part, split_role=True
-                        )
-                    ]
+                content=(
+                    "消息列表:\n```text".join(
+                        [
+                            f"{it}\n"
</code_context>

<issue_to_address>
**issue (bug_risk):** Using `"消息列表:\n```text".join(...)` will repeat the header between every message instead of prefixing it once.

Because the header string is used as the `join` separator, you get `seg1 + header + seg2 + ...` rather than a single header before the full content. If you want one header and one code block wrapper, build the string once around the concatenated items, e.g.:

```python
content = (
    "消息列表:\n```text\n"
    + "".join(
        f"{it}\n" for it in text_generator(
            self._dropped_messages + dropped_part, split_role=True
        )
    )
    + "```"
)
```
</issue_to_address>

### Comment 2
<location> `amrita/plugins/chat/handlers/chat.py:477` </location>
<code_context>
                 .replace("{user_name}", str(event.sender.nickname))
             )
             + "\n</SYSTEM_PROMPT>"
+            + f"\n<SUMMARY>{data.memory_abstract if config.llm_config.enable_memory_abstract else ''}"
         )
         async with MemoryLimiter(self.data, self.train) as lim:
</code_context>

<issue_to_address>
**issue (bug_risk):** The `<SUMMARY>` tag is opened but never closed, which contradicts the schema description and may confuse downstream parsing.

Here `<SUMMARY>` is treated as a paired tag in the schema, but only the opening tag is emitted and no closing `</SUMMARY>` is added. This can break consumers expecting well-formed tags. Consider wrapping the content as a full pair:

```python
summary = data.memory_abstract if config.llm_config.enable_memory_abstract else ""
self.train["content"] = (
    ...
    + "\n</SYSTEM_PROMPT>"
    + f"\n<SUMMARY>{summary}</SUMMARY>"
)
```
</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.

@JohnRichard4096 JohnRichard4096 merged commit ef5a8ae into main Jan 5, 2026
5 checks passed
@JohnRichard4096 JohnRichard4096 deleted the fix-chat branch January 5, 2026 05:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant