better:优化文档

This commit is contained in:
SengokuCola
2025-06-15 23:30:53 +08:00
parent 517f0c29e1
commit 2879b5dba0
14 changed files with 3680 additions and 1048 deletions

View File

@@ -9,11 +9,29 @@
### 🎯 Action组件
#### SmartGreetingAction - 智能问候
- **触发方式**: 关键词触发 (你好、hello、hi、嗨等)
- **激活类型**:
- Focus模式: KEYWORD (关键词激活)
- Normal模式: KEYWORD (关键词激活)
- **触发关键词**: 你好、hello、hi、嗨、问候、早上好、晚上好
- **支持模式**: 所有聊天模式
- **功能**: 智能问候支持LLM个性化生成
- **并行执行**: 否
- **功能**: 智能问候支持多种风格和LLM个性化生成
- **参数**: username(用户名), greeting_style(问候风格)
- **配置**: 可自定义问候模板、启用表情、LLM生成
#### HelpfulAction - 智能助手
- **激活类型**:
- Focus模式: LLM_JUDGE (LLM智能判断)
- Normal模式: RANDOM (随机激活概率15%)
- **支持模式**: 所有聊天模式
- **并行执行**: 是
- **功能**: 主动提供帮助和建议展示LLM判断激活机制
- **参数**: help_type(帮助类型), topic(主题), complexity(复杂度)
- **特点**:
- 通过LLM智能判断是否需要提供帮助
- 展示两层决策机制的实际应用
- 支持多种帮助类型(解释、建议、指导、提示)
### 📝 Command组件
#### 1. ComprehensiveHelpCommand - 综合帮助系统
@@ -94,36 +112,69 @@
### 组件控制
```toml
[components]
enable_greeting = true # 启用智能问候
enable_help = true # 启用帮助系统
enable_send = true # 启用消息发送
# ... 其他组件开关
enable_greeting = true # 启用智能问候Action
enable_helpful = true # 启用智能助手Action
enable_help = true # 启用帮助系统Command
enable_send = true # 启用消息发送Command
enable_echo = true # 启用回声Command
enable_info = true # 启用消息信息Command
enable_dice = true # 启用骰子Command
```
### 功能配置
### Action配置
```toml
[greeting]
template = "你好,{username}" # 问候模板
enable_emoji = true # 启用表情
enable_llm = false # 启用LLM生成
[helpful]
enable_llm = false # 启用LLM生成帮助
enable_emoji = true # 启用鼓励表情
random_activation_probability = 0.15 # 随机激活概率
```
### Command配置
```toml
[send]
max_message_length = 500 # 最大消息长度
[echo]
max_length = 200 # 回声最大长度
enable_formatting = true # 启用格式化
[help]
enable_llm = false # 启用LLM生成帮助内容
enable_emoji = true # 启用帮助表情
```
## 🚀 使用示例
### 智能问候
### Action组件示例
#### 智能问候Action (关键词激活)
```
用户: 你好
机器人: 你好朋友欢迎使用MaiBot综合插件系统😊
机器人: 嗨!很开心见到你~ 😊
用户: 早上好
机器人: 早上好!今天也要元气满满哦! ✨
```
### 帮助查询
#### 智能助手Action (LLM判断激活)
```
用户: 我不太懂怎么使用这个功能
机器人: 关于功能使用我来为你解释一下这是一个simple级别的概念...
这个概念其实很简单,让我用通俗的话来说明。 💡
用户: Python装饰器是什么
机器人: 关于Python装饰器我来为你解释一下这是一个medium级别的概念...
装饰器是一种设计模式,用于在不修改原函数的情况下扩展功能。 🎯
```
### Command组件示例
#### 帮助查询
```
用户: /help
机器人: [显示完整命令帮助列表]
@@ -132,27 +183,53 @@ enable_formatting = true # 启用格式化
机器人: [显示send命令的详细帮助]
```
### 消息发送
#### 消息发送
```
用户: /send group 123456 大家好!
机器人: ✅ 消息已成功发送到 群聊 123456
```
### 日志监控(不拦截)
#### 骰子命令
```
用户: /log info 这是一条测试消息
[日志记录但消息继续处理,可能触发智能问候等其他功能]
用户: !dice
机器人: 🎲 你投出了: 4
用户: !骰子 3
机器人: 🎲 你投出了3个骰子: 2, 5, 1 (总计: 8)
```
### 两层决策机制展示
#### 第一层:激活控制
```
# SmartGreetingAction - 关键词激活
用户消息包含"你好" → Action被激活 → 进入候选池
# HelpfulAction - LLM判断激活
用户表达困惑 → LLM判断"是" → Action被激活 → 进入候选池
用户正常聊天 → LLM判断"否" → Action不激活 → 不进入候选池
```
#### 第二层:使用决策
```
# 即使Action被激活LLM还会根据action_require判断是否真正使用
# 比如HelpfulAction的条件"避免过度频繁地提供帮助,要恰到好处"
# 如果刚刚已经提供了帮助,可能不会再次选择使用
```
## 📁 文件结构
```
src/plugins/built_in/example_comprehensive/
├── plugin.py # 主插件文件
├── config.toml # 配置文件
└── README.md # 说明文档
plugins/example_plugin/ # 用户插件目录
├── plugin.py # 主插件文件
├── config.toml # 配置文件
└── README.md # 说明文档
```
> 💡 **目录说明**
> - `plugins/` - 用户自定义插件目录(推荐放置位置)
> - `src/plugins/builtin/` - 系统内置插件目录
## 🔄 架构升级
此插件展示了从旧插件系统到新插件系统的完整升级:
@@ -169,13 +246,48 @@ src/plugins/built_in/example_comprehensive/
此插件可作为开发新插件的完整参考:
1. **Action开发**: 参考 `SmartGreetingAction`
2. **Command开发**: 参考各种Command实现
3. **拦截控制**: 根据需要设置 `intercept_message`
4. **配置使用**: 通过 `self.api.get_config()` 读取配置
5. **错误处理**: 完整的异常捕获和用户反馈
6. **日志记录**: 结构化的日志输出
### Action开发规范
1. **必须项检查清单**:
- ✅ 激活控制必须项:`focus_activation_type`, `normal_activation_type`, `mode_enable`, `parallel_action`
- ✅ 基本信息必须项:`action_name`, `action_description`
- ✅ 功能定义必须项:`action_parameters`, `action_require`, `associated_types`
2. **激活类型选择**:
- `KEYWORD`: 适合明确触发词的功能(如问候)
- `LLM_JUDGE`: 适合需要智能判断的功能(如帮助)
- `RANDOM`: 适合增加随机性的功能
- `ALWAYS`: 适合总是考虑的功能
- `NEVER`: 用于临时禁用
3. **两层决策设计**:
- 第一层激活控制控制Action是否进入候选池
- 第二层使用决策LLM根据场景智能选择
### Command开发规范
1. **拦截控制**: 根据需要设置 `intercept_message`
2. **正则表达式**: 使用命名组捕获参数
3. **错误处理**: 完整的异常捕获和用户反馈
### 通用开发规范
1. **配置使用**: 通过 `self.api.get_config()` 读取配置
2. **日志记录**: 结构化的日志输出
3. **API调用**: 使用新的统一API接口
4. **注册简化**: Action使用 `get_action_info()` 无参数调用
## 🎉 总结
这个综合示例插件完美展示了新插件系统的强大功能,特别是**拦截控制机制**,让开发者可以精确控制消息处理流程,实现更灵活的插件交互模式。
这个综合示例插件完美展示了新插件系统的强大功能
### 🚀 核心特性
- **两层决策机制**优化LLM决策压力提升性能
- **完整的Action规范**:所有必须项都在类中统一定义
- **灵活的激活控制**:支持多种激活类型和条件
- **精确的拦截控制**Command可以精确控制消息处理流程
### 📚 学习价值
- **Action vs Command**: 清晰展示两种组件的不同设计理念
- **激活机制**: 实际演示关键词、LLM判断、随机等激活方式
- **配置驱动**: 展示如何通过配置文件控制插件行为
- **错误处理**: 完整的异常处理和用户反馈机制
这个插件是理解和掌握MaiBot插件系统的最佳起点🌟

View File

@@ -8,11 +8,13 @@ description = "展示新插件系统完整功能的示例插件"
# 组件启用控制
[components]
enable_greeting = false
enable_help = false
enable_send = false
enable_echo = false
enable_info = false
enable_greeting = true
enable_helpful = true
enable_help = true
enable_send = true
enable_echo = true
enable_info = true
enable_dice = true
# 智能问候配置
[greeting]
@@ -37,11 +39,19 @@ show_detailed_info = true
include_stream_info = true
max_content_preview = 100
# 智能帮助配置
[helpful]
enable_llm = false
enable_emoji = true
random_activation_probability = 0.15
# 帮助系统配置
[help]
show_extended_help = true
include_action_info = true
include_config_info = true
enable_llm = false
enable_emoji = true
# 骰子命令配置
[dice]

View File

@@ -42,19 +42,270 @@ logger = get_logger("example_comprehensive")
class SmartGreetingAction(BaseAction):
"""智能问候Action - 基于关键词触发的问候系统"""
# 激活设置
# ===== 激活控制必须项 =====
focus_activation_type = ActionActivationType.KEYWORD
normal_activation_type = ActionActivationType.KEYWORD
activation_keywords = ["你好", "hello", "hi", "", "问候", "早上好", "晚上好"]
keyword_case_sensitive = False
mode_enable = ChatMode.ALL
parallel_action = False
# Action参数定义
action_parameters = {"username": "要问候的用户名(可选)"}
# ===== 基本信息必须项 =====
action_name = "smart_greeting"
action_description = "智能问候系统,基于关键词触发,支持个性化问候消息"
# Action使用场景
action_require = ["用户发送包含问候词汇的消息", "检测到新用户加入时", "响应友好交流需求"]
# 关键词配置
activation_keywords = ["你好", "hello", "hi", "", "问候", "早上好", "晚上好"]
keyword_case_sensitive = False
# ===== 功能定义必须项 =====
action_parameters = {
"username": "要问候的用户名(可选)",
"greeting_style": "问候风格casual(随意)、formal(正式)、friendly(友好)默认casual"
}
action_require = [
"用户发送包含问候词汇的消息时使用",
"检测到新用户加入时使用",
"响应友好交流需求时使用",
"避免在短时间内重复问候同一用户"
]
associated_types = ["text", "emoji"]
async def execute(self) -> Tuple[bool, str]:
"""执行智能问候"""
logger.info(f"{self.log_prefix} 执行智能问候动作: {self.reasoning}")
try:
# 获取参数
username = self.action_data.get("username", "")
greeting_style = self.action_data.get("greeting_style", "casual")
# 获取配置
template = self.api.get_config("greeting.template", "你好,{username}欢迎使用MaiBot综合插件系统")
enable_emoji = self.api.get_config("greeting.enable_emoji", True)
enable_llm = self.api.get_config("greeting.enable_llm", False)
# 构建问候消息
if enable_llm:
# 使用LLM生成个性化问候
greeting_message = await self._generate_llm_greeting(username, greeting_style)
else:
# 使用模板生成问候
greeting_message = await self._generate_template_greeting(template, username, greeting_style)
# 发送问候消息
await self.send_text(greeting_message)
# 可选发送表情
if enable_emoji:
emojis = ["😊", "👋", "🎉", "", "🌟"]
selected_emoji = random.choice(emojis)
await self.send_type("emoji", selected_emoji)
logger.info(f"{self.log_prefix} 智能问候执行成功")
return True, f"{username or '用户'}发送了{greeting_style}风格的问候"
except Exception as e:
logger.error(f"{self.log_prefix} 智能问候执行失败: {e}")
return False, f"问候失败: {str(e)}"
async def _generate_template_greeting(self, template: str, username: str, style: str) -> str:
"""使用模板生成问候消息"""
# 根据风格调整问候语
style_templates = {
"casual": "{username}!很开心见到你~",
"formal": "您好{username},很荣幸为您服务!",
"friendly": "你好{username}!欢迎来到这里,希望我们能成为好朋友!😊"
}
selected_template = style_templates.get(style, template)
username_display = f" {username}" if username else ""
return selected_template.format(username=username_display)
async def _generate_llm_greeting(self, username: str, style: str) -> str:
"""使用LLM生成个性化问候"""
try:
# 获取可用模型
models = self.api.get_available_models()
if not models:
logger.warning(f"{self.log_prefix} 无可用LLM模型使用默认问候")
return await self._generate_template_greeting("你好{username}", username, style)
# 构建提示词
prompt = f"""
请生成一个{style}风格的问候消息。
用户名: {username or "用户"}
要求:
- 风格: {style}
- 简洁友好
- 不超过50字
- 符合中文表达习惯
"""
# 调用LLM
model_config = next(iter(models.values()))
success, response, reasoning, model_name = await self.api.generate_with_model(
prompt=prompt,
model_config=model_config,
request_type="plugin.greeting",
temperature=0.7,
max_tokens=100
)
if success and response:
return response.strip()
else:
logger.warning(f"{self.log_prefix} LLM生成失败使用默认问候")
return await self._generate_template_greeting("你好{username}", username, style)
except Exception as e:
logger.error(f"{self.log_prefix} LLM问候生成异常: {e}")
return await self._generate_template_greeting("你好{username}", username, style)
class HelpfulAction(BaseAction):
"""智能帮助Action - 展示LLM_JUDGE激活类型和随机激活的综合示例"""
# ===== 激活控制必须项 =====
focus_activation_type = ActionActivationType.LLM_JUDGE
normal_activation_type = ActionActivationType.RANDOM
mode_enable = ChatMode.ALL
parallel_action = True
# ===== 基本信息必须项 =====
action_name = "helpful_assistant"
action_description = "智能助手Action主动提供帮助和建议展示LLM判断激活"
# LLM判断提示词
llm_judge_prompt = """
判定是否需要使用智能帮助动作的条件:
1. 用户表达了困惑或需要帮助
2. 用户提出了问题但没有得到满意答案
3. 对话中出现了技术术语或复杂概念
4. 用户似乎在寻找解决方案
5. 适合提供额外信息或建议的场合
不要使用的情况:
1. 用户明确表示不需要帮助
2. 对话进行得很顺利,无需干预
3. 用户只是在闲聊,没有实际需求
请回答""""
"""
# 随机激活概率
random_activation_probability = 0.15
# ===== 功能定义必须项 =====
action_parameters = {
"help_type": "帮助类型explanation(解释)、suggestion(建议)、guidance(指导)、tips(提示)",
"topic": "帮助主题或用户关心的问题",
"complexity": "复杂度simple(简单)、medium(中等)、advanced(高级)"
}
action_require = [
"用户表达困惑或寻求帮助时使用",
"检测到用户遇到技术问题时使用",
"对话中出现知识盲点时主动提供帮助",
"避免过度频繁地提供帮助,要恰到好处"
]
associated_types = ["text", "emoji"]
async def execute(self) -> Tuple[bool, str]:
"""执行智能帮助"""
logger.info(f"{self.log_prefix} 执行智能帮助动作: {self.reasoning}")
try:
# 获取参数
help_type = self.action_data.get("help_type", "suggestion")
topic = self.action_data.get("topic", "")
complexity = self.action_data.get("complexity", "simple")
# 根据帮助类型生成响应
help_message = await self._generate_help_message(help_type, topic, complexity)
# 发送帮助消息
await self.send_text(help_message)
# 可选发送鼓励表情
if self.api.get_config("help.enable_emoji", True):
emojis = ["💡", "🤔", "💪", "🎯", ""]
selected_emoji = random.choice(emojis)
await self.send_type("emoji", selected_emoji)
logger.info(f"{self.log_prefix} 智能帮助执行成功")
return True, f"提供了{help_type}类型的帮助,主题:{topic}"
except Exception as e:
logger.error(f"{self.log_prefix} 智能帮助执行失败: {e}")
return False, f"帮助失败: {str(e)}"
async def _generate_help_message(self, help_type: str, topic: str, complexity: str) -> str:
"""生成帮助消息"""
# 获取配置
enable_llm = self.api.get_config("help.enable_llm", False)
if enable_llm:
return await self._generate_llm_help(help_type, topic, complexity)
else:
return await self._generate_template_help(help_type, topic, complexity)
async def _generate_template_help(self, help_type: str, topic: str, complexity: str) -> str:
"""使用模板生成帮助消息"""
help_templates = {
"explanation": f"关于{topic},我来为你解释一下:这是一个{complexity}级别的概念...",
"suggestion": f"针对{topic},我建议你可以尝试以下方法...",
"guidance": f"{topic}方面,我可以为你提供一些指导...",
"tips": f"关于{topic},这里有一些实用的小贴士..."
}
base_message = help_templates.get(help_type, f"关于{topic},我很乐意为你提供帮助!")
# 根据复杂度调整消息
if complexity == "advanced":
base_message += "\n\n这个话题比较深入,需要一些基础知识。"
elif complexity == "simple":
base_message += "\n\n这个概念其实很简单,让我用通俗的话来说明。"
return base_message
async def _generate_llm_help(self, help_type: str, topic: str, complexity: str) -> str:
"""使用LLM生成个性化帮助"""
try:
models = self.api.get_available_models()
if not models:
return await self._generate_template_help(help_type, topic, complexity)
prompt = f"""
请生成一个{help_type}类型的帮助消息。
主题: {topic}
复杂度: {complexity}
要求:
- 风格友好、耐心
- 内容准确、有用
- 长度适中(100-200字)
- 根据复杂度调整语言难度
"""
model_config = next(iter(models.values()))
success, response, reasoning, model_name = await self.api.generate_with_model(
prompt=prompt,
model_config=model_config,
request_type="plugin.help",
temperature=0.7,
max_tokens=300
)
if success and response:
return response.strip()
else:
return await self._generate_template_help(help_type, topic, complexity)
except Exception as e:
logger.error(f"{self.log_prefix} LLM帮助生成异常: {e}")
return await self._generate_template_help(help_type, topic, complexity)
# ===== Command组件 =====
@@ -405,6 +656,7 @@ class ExampleComprehensivePlugin(BasePlugin):
# 从配置获取组件启用状态
enable_greeting = self.get_config("components.enable_greeting", True)
enable_helpful = self.get_config("components.enable_helpful", True)
enable_help = self.get_config("components.enable_help", True)
enable_send = self.get_config("components.enable_send", True)
enable_echo = self.get_config("components.enable_echo", True)
@@ -412,16 +664,12 @@ class ExampleComprehensivePlugin(BasePlugin):
enable_dice = self.get_config("components.enable_dice", True)
components = []
# 添加Action组件
# 添加Action组件 - 使用类中定义的所有属性
if enable_greeting:
components.append(
(
SmartGreetingAction.get_action_info(
name="smart_greeting", description="智能问候系统,基于关键词触发"
),
SmartGreetingAction,
)
)
components.append((SmartGreetingAction.get_action_info(), SmartGreetingAction))
if enable_helpful:
components.append((HelpfulAction.get_action_info(), HelpfulAction))
# 添加Command组件
if enable_help: