mirror of
https://github.com/LiteyukiStudio/nonebot-plugin-marshoai.git
synced 2025-12-21 23:06:42 +00:00
Compare commits
11 Commits
v1.0.0.dev
...
v1.0.0.dev
| Author | SHA1 | Date | |
|---|---|---|---|
| b0d6f87134 | |||
| cf96ab3ffe | |||
| da710ac0bd | |||
| db3100c567 | |||
| c3d4a797c0 | |||
| bdd80d0c2e | |||
| 99c113833e | |||
| 87b18c424b | |||
| 7893f28259 | |||
| 339d0e05bf | |||
| 777e577a17 |
@@ -22,7 +22,6 @@ order: 2
|
||||
- 元数据:包含插件的信息,如名称、版本、作者等
|
||||
- function call:供AI调用的函数
|
||||
|
||||
|
||||
:::tip
|
||||
如果你编写过NoneBot插件,那么你会发现插件的编写方式和NoneBot插件的编写方式几乎一样。
|
||||
:::
|
||||
@@ -76,14 +75,19 @@ def fortune_telling(name: str, age: int) -> str:
|
||||
```python
|
||||
@on_function_call(description="在设备上执行命令").params(
|
||||
command=String(description="命令内容")
|
||||
).permission(SUPERUSER).rule(RegexRule("查询(.*)的天气"))
|
||||
).permission(SUPERUSER)
|
||||
def execute_command(command: str) -> str:
|
||||
return eval(command)
|
||||
```
|
||||
|
||||
## 依赖注入
|
||||
|
||||
function call支持NoneBot2原生的会话上下文依赖注入,例如Bot、Event等
|
||||
function call支持NoneBot2原生的会话上下文依赖注入
|
||||
|
||||
- Event 及其子类实例
|
||||
- Bot 及其子类实例
|
||||
- Matcher 及其子类实例
|
||||
- T_State
|
||||
|
||||
```python
|
||||
@on_function_call(description="获取个人信息")
|
||||
@@ -95,14 +99,39 @@ async def get_bot_info(b: Bot) -> str:
|
||||
return f"机器人ID: {b.self_id}"
|
||||
```
|
||||
|
||||
## 其他
|
||||
## 兼容性
|
||||
|
||||
- function call支持同步和异步函数
|
||||
- 本文是一个引导,要查看具体功能请查阅[插件 API 文档](./api/plugin/index)
|
||||
插件可以编写NoneBot或者轻雪插件的内容,可作为NoneBot插件或者轻雪插件单独发布
|
||||
|
||||
不过,所编写功能仅会在对应的实例上加载对应的功能,如果通过marshoai加载混合插件,那么插件中NoneBot的功能将会依附于marshoai插件,
|
||||
若通过NoneBot加载包含marshoai功能的NoneBot插件,那么marshoai功能将会依附于NoneBot插件。
|
||||
|
||||
**我们建议**:若插件中包含了NoneBot功能,仍然使用marshoai进行加载,这样更符合逻辑。若你想发布为NoneBot插件,请注意`require("nonebot_plugin_marshoai")`,这是老生常谈了。
|
||||
|
||||
:::tip
|
||||
本质上都是动态导入和注册声明加载,运行时把这些东西塞到一起
|
||||
:::
|
||||
|
||||
## 插件热重载
|
||||
|
||||
插件热重载是一个实验性功能,可以在不重启机器人的情况下更新插件
|
||||
|
||||
:::warning
|
||||
框架无法完全消除之前插件带来的副作用,当开发测试中效果不符合预期时请重启机器人实例
|
||||
|
||||
为了更好地让热重载功能正常工作,尽可能使用函数式的编程风格,以减少副作用的影响
|
||||
:::
|
||||
|
||||
将`MARSHOAI_DEVMODE`环境变量设置为`true`,然后在配置的插件目录`MARSHOAI_PLUGIN_DIRS`下开发插件,当插件发生变化时,机器人会自动变动的插件。
|
||||
|
||||
## AIGC 自举
|
||||
|
||||
:::warning
|
||||
该功能为实验性功能,请注意甄别AI的行为,不要让AI执行危险的操作。
|
||||
:::
|
||||
function call为AI赋能,实现了文件io操作,AI可以调用function call来读取文档然后给自己编写代码,实现自举。
|
||||
function call为AI赋能,实现了文件io操作,AI可以调用function call来读取文档然后给自己编写代码,实现自举。
|
||||
|
||||
## 其他
|
||||
|
||||
- function call支持同步和异步函数
|
||||
- 本文是一个引导,要查看具体功能请查阅[插件 API 文档](./api/plugin/index)
|
||||
|
||||
@@ -61,9 +61,11 @@ title: 安装
|
||||
当 nonebot 连接到支持的 OneBot v11 实现端时,可以接收头像双击戳一戳消息并进行响应。详见`MARSHOAI_POKE_SUFFIX`配置项。
|
||||
|
||||
## 🛠️ ~~小棉工具~~(已弃用)
|
||||
|
||||
小棉工具(MarshoTools)是`v0.5.0`版本的新增功能,支持加载外部函数库来为 Marsho 提供 Function Call 功能。
|
||||
|
||||
## 🧩 小棉插件
|
||||
|
||||
小棉插件是`v1.0.0`的新增功能,替代旧的小棉工具功能。[使用文档](https://marsho.liteyuki.icu/dev/extension)
|
||||
|
||||
## 👍 夸赞名单
|
||||
@@ -132,10 +134,17 @@ title: 安装
|
||||
| MARSHOAI_ENABLE_NICKNAME_TIP | `bool` | `true` | 启用后用户未设置昵称时提示用户设置 |
|
||||
| MARSHOAI_ENABLE_PRAISES | `bool` | `true` | 是否启用夸赞名单功能 |
|
||||
| MARSHOAI_ENABLE_TOOLS | `bool` | `false` | 是否启用小棉工具 |
|
||||
| MARSHOAI_ENABLE_PLUGINS | `bool` | `true` | 是否启用小棉插件 |
|
||||
| MARSHOAI_ENABLE_PLUGINS | `bool` | `true` | 是否启用小棉插件 |
|
||||
| MARSHOAI_PLUGINS | `list[str]` | `[]` | 要从`sys.path`加载的插件的名称,例如从pypi安装的包 |
|
||||
| MARSHOAI_PLUGIN_DIRS | `list[str]` | `[]` | 插件目录路径列表 |
|
||||
| MARSHOAI_LOAD_BUILTIN_TOOLS | `bool` | `true` | 是否加载内置工具包 |
|
||||
| MARSHOAI_TOOLSET_DIR | `list` | `[]` | 外部工具集路径列表 |
|
||||
| MARSHOAI_DISABLED_TOOLKITS | `list` | `[]` | 禁用的工具包包名列表 |
|
||||
| MARSHOAI_ENABLE_RICHTEXT_PARSE | `bool` | `true` | 是否启用自动解析消息(若包含图片链接则发送图片、若包含LaTeX公式则发送公式图) |
|
||||
| MARSHOAI_SINGLE_LATEX_PARSE | `bool` | `false` | 单行公式是否渲染(当消息富文本解析启用时可用)(如果单行也渲……只能说不好看) |
|
||||
| MARSHOAI_SINGLE_LATEX_PARSE | `bool` | `false` | 单行公式是否渲染(当消息富文本解析启用时可用)(如果单行也渲……只能说不好看) |
|
||||
|
||||
#### 开发及调试选项
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
| ------------------------ | ------ | ------- | ---------------- |
|
||||
| MARSHOAI_DEVMODE | `bool` | `false` | 是否启用开发者模式 |
|
||||
|
||||
@@ -6,9 +6,11 @@ require("nonebot_plugin_localstore")
|
||||
import nonebot_plugin_localstore as store # type: ignore
|
||||
from nonebot import get_driver, logger # type: ignore
|
||||
|
||||
# from .hunyuan import *
|
||||
from .azure import *
|
||||
from .config import config
|
||||
|
||||
# from .hunyuan import *
|
||||
from .dev import *
|
||||
from .metadata import metadata
|
||||
|
||||
__author__ = "Asankilp"
|
||||
|
||||
@@ -112,7 +112,7 @@ async def _preload_tools():
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def _preload_plugins():
|
||||
async def _():
|
||||
"""启动钩子加载插件"""
|
||||
if config.marshoai_enable_plugins:
|
||||
marshoai_plugin_dirs = config.marshoai_plugin_dirs # 外部插件目录列表
|
||||
@@ -350,10 +350,12 @@ async def marsho(
|
||||
tool_call.function.arguments.replace("'", '"')
|
||||
)
|
||||
logger.info(
|
||||
f"调用函数 {tool_call.function.name} ,参数为 {function_args}"
|
||||
f"调用函数 {tool_call.function.name.replace('-', '.')}\n参数:"
|
||||
+ "\n".join([f"{k}={v}" for k, v in function_args.items()])
|
||||
)
|
||||
await UniMessage(
|
||||
f"调用函数 {tool_call.function.name} ,参数为 {function_args}"
|
||||
f"调用函数 {tool_call.function.name.replace('-', '.')}\n参数:"
|
||||
+ "\n".join([f"{k}={v}" for k, v in function_args.items()])
|
||||
).send()
|
||||
# TODO 临时追加插件函数,若工具中没有则调用插件函数
|
||||
if tools.has_function(tool_call.function.name):
|
||||
@@ -363,9 +365,9 @@ async def marsho(
|
||||
) # 获取返回值
|
||||
else:
|
||||
if caller := get_function_calls().get(
|
||||
tool_call.function.name
|
||||
tool_call.function.name.replace("-", ".")
|
||||
):
|
||||
logger.debug(f"调用插件函数 {tool_call.function.name}")
|
||||
logger.debug(f"调用插件函数 {caller.full_name}")
|
||||
# 权限检查,规则检查 TODO
|
||||
# 实现依赖注入,检查函数参数及参数注解类型,对Event类型的参数进行注入
|
||||
func_return = await caller.with_ctx(
|
||||
@@ -377,8 +379,10 @@ async def marsho(
|
||||
)
|
||||
).call(**function_args)
|
||||
else:
|
||||
logger.error(f"未找到函数 {tool_call.function.name}")
|
||||
func_return = f"未找到函数 {tool_call.function.name}"
|
||||
logger.error(
|
||||
f"未找到函数 {tool_call.function.name.replace('-', '.')}"
|
||||
)
|
||||
func_return = f"未找到函数 {tool_call.function.name.replace('-', '.')}"
|
||||
tool_msg.append(
|
||||
ToolMessage(tool_call_id=tool_call.id, content=func_return) # type: ignore
|
||||
)
|
||||
|
||||
@@ -52,7 +52,7 @@ class ConfigModel(BaseModel):
|
||||
marshoai_plugin_dirs: list[str] = []
|
||||
"""插件目录(不是工具)"""
|
||||
marshoai_devmode: bool = False
|
||||
"""开发者模式"""
|
||||
"""开发者模式,启用本地插件插件重载"""
|
||||
marshoai_plugins: list[str] = []
|
||||
"""marsho插件的名称列表,从pip安装的使用包名,从本地导入的使用路径"""
|
||||
|
||||
|
||||
@@ -1,7 +1,127 @@
|
||||
from nonebot import require
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from nonebot import get_driver, logger, require
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.typing import T_State
|
||||
|
||||
from nonebot_plugin_marshoai.plugin.load import reload_plugin
|
||||
|
||||
from .azure import context
|
||||
from .config import config
|
||||
from .plugin.func_call.models import SessionContext
|
||||
|
||||
require("nonebot_plugin_alconna")
|
||||
|
||||
from nonebot_plugin_alconna import Alconna, on_alconna
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot_plugin_alconna import (
|
||||
Alconna,
|
||||
Args,
|
||||
MultiVar,
|
||||
Subcommand,
|
||||
UniMessage,
|
||||
on_alconna,
|
||||
)
|
||||
|
||||
function_call = on_alconna("marshocall")
|
||||
from .observer import *
|
||||
from .plugin import get_plugin, get_plugins
|
||||
from .plugin.func_call.caller import get_function_calls
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
function_call = on_alconna(
|
||||
command=Alconna(
|
||||
"marsho-function-call",
|
||||
Subcommand(
|
||||
"call",
|
||||
Args["function_name", str]["kwargs", MultiVar(str), []],
|
||||
alias={"c"},
|
||||
),
|
||||
Subcommand(
|
||||
"list",
|
||||
alias={"l"},
|
||||
),
|
||||
Subcommand("info", Args["function_name", str], alias={"i"}),
|
||||
),
|
||||
aliases={"mfc"},
|
||||
permission=SUPERUSER,
|
||||
)
|
||||
|
||||
|
||||
@function_call.assign("list")
|
||||
async def list_functions():
|
||||
reply = "共有如下可调用函数:\n"
|
||||
for function in get_function_calls().values():
|
||||
reply += f"- {function.short_info}\n"
|
||||
await UniMessage(reply).send()
|
||||
|
||||
|
||||
@function_call.assign("info")
|
||||
async def function_info(function_name: str):
|
||||
function = get_function_calls().get(function_name)
|
||||
if function is None:
|
||||
await UniMessage(f"未找到函数 {function_name}").send()
|
||||
return
|
||||
await UniMessage(str(function)).send()
|
||||
|
||||
|
||||
@function_call.assign("call")
|
||||
async def call_function(
|
||||
function_name: str,
|
||||
kwargs: list[str],
|
||||
event: Event,
|
||||
bot: Bot,
|
||||
matcher: Matcher,
|
||||
state: T_State,
|
||||
):
|
||||
function = get_function_calls().get(function_name)
|
||||
if function is None:
|
||||
for f in get_function_calls().values():
|
||||
if f.short_name == function_name:
|
||||
function = f
|
||||
break
|
||||
else:
|
||||
await UniMessage(f"未找到函数 {function_name}").send()
|
||||
return
|
||||
await UniMessage(
|
||||
str(
|
||||
await function.with_ctx(
|
||||
SessionContext(event=event, bot=bot, matcher=matcher, state=state)
|
||||
).call(**{i.split("=", 1)[0]: i.split("=", 1)[1] for i in kwargs})
|
||||
)
|
||||
).send()
|
||||
|
||||
|
||||
@on_file_system_event(
|
||||
(str(Path(__file__).parent / "plugins"), *config.marshoai_plugin_dirs),
|
||||
recursive=True,
|
||||
)
|
||||
def on_plugin_file_change(event):
|
||||
if event.src_path.endswith(".py"):
|
||||
logger.info(f"文件变动: {event.src_path}")
|
||||
# 层层向上查找到插件目录
|
||||
dir_list: list[str] = event.src_path.split("/") # type: ignore
|
||||
dir_list[-1] = dir_list[-1].split(".", 1)[0]
|
||||
dir_list.reverse()
|
||||
for plugin_name in dir_list:
|
||||
if plugin := get_plugin(plugin_name):
|
||||
if plugin.module_path.endswith("__init__.py"):
|
||||
# 包插件
|
||||
if os.path.dirname(plugin.module_path).replace(
|
||||
"\\", "/"
|
||||
) in event.src_path.replace("\\", "/"):
|
||||
logger.debug(f"找到变动插件: {plugin.name},正在重新加载")
|
||||
reload_plugin(plugin)
|
||||
context.reset_all()
|
||||
break
|
||||
else:
|
||||
# 单文件插件
|
||||
if plugin.module_path == event.src_path:
|
||||
logger.debug(f"找到变动插件: {plugin.name},正在重新加载")
|
||||
reload_plugin(plugin)
|
||||
context.reset_all()
|
||||
break
|
||||
else:
|
||||
logger.debug("未找到变动插件")
|
||||
return
|
||||
|
||||
@@ -47,6 +47,13 @@ class MarshoContext:
|
||||
if target_id in target_dict:
|
||||
target_dict[target_id].clear()
|
||||
|
||||
def reset_all(self):
|
||||
"""
|
||||
重置所有上下文
|
||||
"""
|
||||
self.contents["private"].clear()
|
||||
self.contents["non-private"].clear()
|
||||
|
||||
def build(self, target_id: str, is_private: bool) -> list:
|
||||
"""
|
||||
构建返回的上下文,不包括系统消息
|
||||
|
||||
99
nonebot_plugin_marshoai/observer.py
Executable file
99
nonebot_plugin_marshoai/observer.py
Executable file
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
此模块用于注册观察者函数,使用watchdog监控文件变化并重启bot
|
||||
启用该模块需要在配置文件中设置`dev_mode`为True
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Callable, TypeAlias
|
||||
|
||||
from nonebot import get_driver, logger
|
||||
from watchdog.events import FileSystemEvent, FileSystemEventHandler
|
||||
from watchdog.observers import Observer
|
||||
|
||||
from .config import config
|
||||
|
||||
CALLBACK_FUNC: TypeAlias = Callable[[FileSystemEvent], None] # 位置1为FileSystemEvent
|
||||
FILTER_FUNC: TypeAlias = Callable[[FileSystemEvent], bool] # 位置1为FileSystemEvent
|
||||
|
||||
observer = Observer()
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
|
||||
def debounce(wait):
|
||||
"""
|
||||
防抖函数
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
nonlocal last_call_time
|
||||
current_time = time.time()
|
||||
if (current_time - last_call_time) > wait:
|
||||
last_call_time = current_time
|
||||
return func(*args, **kwargs)
|
||||
|
||||
last_call_time = None
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def check_for_reloader():
|
||||
if config.marshoai_devmode:
|
||||
logger.debug("Marsho Reload enabled, watching for file changes...")
|
||||
observer.start()
|
||||
|
||||
|
||||
class CodeModifiedHandler(FileSystemEventHandler):
|
||||
"""
|
||||
Handler for code file changes
|
||||
"""
|
||||
|
||||
@debounce(1)
|
||||
def on_modified(self, event):
|
||||
raise NotImplementedError("on_modified must be implemented")
|
||||
|
||||
def on_created(self, event):
|
||||
self.on_modified(event)
|
||||
|
||||
def on_deleted(self, event):
|
||||
self.on_modified(event)
|
||||
|
||||
def on_moved(self, event):
|
||||
self.on_modified(event)
|
||||
|
||||
def on_any_event(self, event):
|
||||
self.on_modified(event)
|
||||
|
||||
|
||||
def on_file_system_event(
|
||||
directories: tuple[str, ...],
|
||||
recursive: bool = True,
|
||||
event_filter: FILTER_FUNC | None = None,
|
||||
) -> Callable[[CALLBACK_FUNC], CALLBACK_FUNC]:
|
||||
"""
|
||||
注册文件系统变化监听器
|
||||
Args:
|
||||
directories: 监听目录们
|
||||
recursive: 是否递归监听子目录
|
||||
event_filter: 事件过滤器, 返回True则执行回调函数
|
||||
Returns:
|
||||
装饰器,装饰一个函数在接收到数据后执行
|
||||
"""
|
||||
|
||||
def decorator(func: CALLBACK_FUNC) -> CALLBACK_FUNC:
|
||||
def wrapper(event: FileSystemEvent):
|
||||
|
||||
if event_filter is not None and not event_filter(event):
|
||||
return
|
||||
func(event)
|
||||
|
||||
code_modified_handler = CodeModifiedHandler()
|
||||
code_modified_handler.on_modified = wrapper
|
||||
for directory in directories:
|
||||
observer.schedule(code_modified_handler, directory, recursive=recursive)
|
||||
return func
|
||||
|
||||
return decorator
|
||||
@@ -8,6 +8,7 @@ from nonebot.permission import Permission
|
||||
from nonebot.rule import Rule
|
||||
from nonebot.typing import T_State
|
||||
|
||||
from ..models import Plugin
|
||||
from ..typing import ASYNC_FUNCTION_CALL_FUNC, F
|
||||
from .models import SessionContext, SessionContextDepends
|
||||
from .utils import async_wrap, is_coroutine_callable
|
||||
@@ -16,10 +17,17 @@ _caller_data: dict[str, "Caller"] = {}
|
||||
|
||||
|
||||
class Caller:
|
||||
def __init__(self, name: str | None = None, description: str | None = None):
|
||||
self._name = name
|
||||
def __init__(self, name: str = "", description: str | None = None):
|
||||
self._name: str = name
|
||||
"""函数名称"""
|
||||
self._description = description
|
||||
"""函数描述"""
|
||||
self._plugin: Plugin | None = None
|
||||
"""所属插件对象,装饰时声明"""
|
||||
self.func: ASYNC_FUNCTION_CALL_FUNC | None = None
|
||||
"""函数对象"""
|
||||
self.module_name: str = ""
|
||||
"""模块名,仅为父级模块名,不一定是插件顶级模块名"""
|
||||
self._parameters: dict[str, Any] = {}
|
||||
"""声明参数"""
|
||||
|
||||
@@ -91,13 +99,8 @@ class Caller:
|
||||
F: 函数对象
|
||||
"""
|
||||
global _caller_data
|
||||
if self._name is None:
|
||||
if module := inspect.getmodule(func):
|
||||
module_name = module.__name__.split(".")[-1]
|
||||
else:
|
||||
module_name = ""
|
||||
self._name = f"{module_name}-{func.__name__}"
|
||||
_caller_data[self._name] = self
|
||||
if not self._name:
|
||||
self._name = func.__name__
|
||||
|
||||
# 检查函数签名,确定依赖注入参数
|
||||
sig = inspect.signature(func)
|
||||
@@ -134,11 +137,14 @@ class Caller:
|
||||
self.func = async_wrap(func) # type: ignore
|
||||
|
||||
if module := inspect.getmodule(func):
|
||||
module_name = module.__name__.split(".")[-1] + "."
|
||||
module_name = module.__name__.split(".")[-1]
|
||||
else:
|
||||
module_name = ""
|
||||
|
||||
self.module_name = module_name
|
||||
_caller_data[self.full_name] = self
|
||||
logger.opt(colors=True).debug(
|
||||
f"<y>加载函数 {module_name}{func.__name__}: {self._description}</y>"
|
||||
f"<y>加载函数 {self.full_name}: {self._description}</y>"
|
||||
)
|
||||
|
||||
return func
|
||||
@@ -152,7 +158,7 @@ class Caller:
|
||||
return {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": self._name,
|
||||
"name": self.aifc_name,
|
||||
"description": self._description,
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
@@ -193,6 +199,11 @@ class Caller:
|
||||
self.set_ctx(ctx)
|
||||
return self
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self._name}({self._description})\n" + "\n".join(
|
||||
f" - {key}: {value}" for key, value in self._parameters.items()
|
||||
)
|
||||
|
||||
async def call(self, *args: Any, **kwargs: Any) -> Any:
|
||||
"""调用函数
|
||||
|
||||
@@ -214,8 +225,27 @@ class Caller:
|
||||
|
||||
return await self.func(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def short_name(self) -> str:
|
||||
"""函数本名"""
|
||||
return self._name.split(".")[-1]
|
||||
|
||||
def on_function_call(name: str | None = None, description: str | None = None) -> Caller:
|
||||
@property
|
||||
def aifc_name(self) -> str:
|
||||
"""AI调用名,没有点"""
|
||||
return self._name.replace(".", "-")
|
||||
|
||||
@property
|
||||
def full_name(self) -> str:
|
||||
"""完整名"""
|
||||
return self.module_name + "." + self._name
|
||||
|
||||
@property
|
||||
def short_info(self) -> str:
|
||||
return f"{self.full_name}({self._description})"
|
||||
|
||||
|
||||
def on_function_call(name: str = "", description: str | None = None) -> Caller:
|
||||
"""返回一个Caller类,可用于装饰一个函数,使其注册为一个可被AI调用的function call函数
|
||||
|
||||
Args:
|
||||
|
||||
@@ -45,7 +45,9 @@ def get_plugins() -> dict[str, Plugin]:
|
||||
return _plugins
|
||||
|
||||
|
||||
def load_plugin(module_path: str | Path) -> Optional[Plugin]:
|
||||
def load_plugin(
|
||||
module_path: str | Path, allow_reload: bool = False
|
||||
) -> Optional[Plugin]:
|
||||
"""加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
|
||||
该函数产生的副作用在于将插件加载到 `_plugins` 中。
|
||||
|
||||
@@ -63,11 +65,15 @@ def load_plugin(module_path: str | Path) -> Optional[Plugin]:
|
||||
try:
|
||||
module = import_module(module_path) # 导入模块对象
|
||||
plugin = Plugin(
|
||||
name=module.__name__,
|
||||
name=module.__name__.split(".")[-1],
|
||||
module=module,
|
||||
module_name=module_path,
|
||||
module_path=module.__file__,
|
||||
)
|
||||
_plugins[plugin.name] = plugin
|
||||
if plugin.name in _plugins and not allow_reload:
|
||||
raise ValueError(f"插件名称重复: {plugin.name}")
|
||||
else:
|
||||
_plugins[plugin.name] = plugin
|
||||
|
||||
plugin.metadata = getattr(module, "__marsho_meta__", None)
|
||||
|
||||
@@ -117,3 +123,33 @@ def load_plugins(*plugin_dirs: str) -> set[Plugin]:
|
||||
if module_name and (plugin := load_plugin(module_name)):
|
||||
plugins.add(plugin)
|
||||
return plugins
|
||||
|
||||
|
||||
def reload_plugin(plugin: Plugin) -> Optional[Plugin]:
|
||||
"""开发模式下的重新加载插件
|
||||
该方法无法保证没有副作用,因为插件可能会有自己的初始化方法
|
||||
如果出现异常请重启即可
|
||||
Args:
|
||||
plugin: 插件对象
|
||||
Returns:
|
||||
Optional[Plugin]: 插件对象
|
||||
"""
|
||||
try:
|
||||
if plugin.module_path:
|
||||
if new_plugin := load_plugin(plugin.module_name, True):
|
||||
logger.opt(colors=True).debug(
|
||||
f'重新加载插件 "<y>{new_plugin.name}</y>" 成功, 若出现异常或副作用请重启'
|
||||
)
|
||||
return new_plugin
|
||||
else:
|
||||
logger.opt(colors=True).error(
|
||||
f'重新加载插件失败 "<r>{plugin.name}</r>"'
|
||||
)
|
||||
return None
|
||||
else:
|
||||
logger.opt(colors=True).error(f'插件不支持重载 "<r>{plugin.name}</r>"')
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.opt(colors=True).error(f'重新加载插件失败 "<r>{plugin.name}</r>"')
|
||||
traceback.print_exc()
|
||||
return None
|
||||
|
||||
@@ -57,7 +57,9 @@ class Plugin(BaseModel):
|
||||
module: ModuleType
|
||||
"""插件模块对象"""
|
||||
module_name: str
|
||||
"""点分割模块路径 例如a.b.c"""
|
||||
"""点分或/割模块路径 例如a.b.c"""
|
||||
module_path: str | None
|
||||
"""实际路径,单文件为.py的路径,包为__init__.py路径"""
|
||||
metadata: PluginMetadata | None = None
|
||||
"""元"""
|
||||
|
||||
@@ -69,3 +71,6 @@ class Plugin(BaseModel):
|
||||
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
return self.name == other.name
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Plugin({self.name}({self.module_path}))"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import time
|
||||
|
||||
from httpx import AsyncClient
|
||||
from newspaper import Article
|
||||
from newspaper import Article # type: ignore
|
||||
from nonebot import logger
|
||||
|
||||
from nonebot_plugin_marshoai.plugin.func_call.caller import on_function_call
|
||||
from nonebot_plugin_marshoai.plugin.func_call.params import String
|
||||
|
||||
from .utils import make_html_summary
|
||||
|
||||
headers = {
|
||||
"User-Agent": "Firefox/90.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0"
|
||||
}
|
||||
@@ -16,9 +16,8 @@ headers = {
|
||||
description="使用网页链接(url)获取网页内容摘要,可以让AI上网查询资料"
|
||||
).params(
|
||||
url=String(description="网页链接"),
|
||||
typ=String(description="获取类型,摘要还是内容", enum=["摘要", "内容"]),
|
||||
)
|
||||
async def get_web_content(url: str, typ: str) -> str:
|
||||
async def get_web_content(url: str) -> str:
|
||||
"""使用网页链接获取网页内容摘要
|
||||
为什么要获取摘要,不然token超限了
|
||||
|
||||
@@ -31,16 +30,19 @@ async def get_web_content(url: str, typ: str) -> str:
|
||||
async with AsyncClient(headers=headers) as client:
|
||||
try:
|
||||
response = await client.get(url)
|
||||
t1 = time.time()
|
||||
article = Article(url)
|
||||
article.set_html(response.text)
|
||||
article.parse()
|
||||
t2 = time.time()
|
||||
logger.debug(f"获取网页内容耗时: {t2 - t1}")
|
||||
if typ == "摘要":
|
||||
return f"标题: {article.title}\n作者: {article.authors}\n发布日期: {article.publish_date}"
|
||||
elif typ == "内容":
|
||||
return f"标题: {article.title}\n作者: {article.authors}\n发布日期: {article.publish_date}\n摘要: {article.summary}\n正文: {article.text}"
|
||||
if response.status_code == 200:
|
||||
article = Article(url)
|
||||
article.download(input_html=response.text)
|
||||
article.parse()
|
||||
if article.text:
|
||||
return article.text
|
||||
elif article.html:
|
||||
return await make_html_summary(article.html)
|
||||
else:
|
||||
return "未能获取到有效的网页内容"
|
||||
else:
|
||||
return "获取网页内容失败" + str(response.status_code)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"marsho builtin: 获取网页内容失败: {e}")
|
||||
return "获取网页内容失败:" + str(e)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from newspaper import Article # type: ignore
|
||||
from sumy.nlp.tokenizers import Tokenizer # type: ignore
|
||||
from sumy.parsers.plaintext import PlaintextParser # type: ignore
|
||||
from sumy.summarizers.lsa import LsaSummarizer # type: ignore
|
||||
|
||||
executor = ThreadPoolExecutor()
|
||||
|
||||
|
||||
async def make_html_summary(
|
||||
html_content: str, language: str = "english", length: int = 3
|
||||
) -> str:
|
||||
"""使用html内容生成摘要
|
||||
|
||||
Args:
|
||||
html_content (str): html内容
|
||||
language (str, optional): 语言. Defaults to "english".
|
||||
length (int, optional): 摘要长度. Defaults to 3.
|
||||
|
||||
Returns:
|
||||
str: 摘要
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
executor, _make_summary, html_content, language, length
|
||||
)
|
||||
|
||||
|
||||
def _make_summary(html_content: str, language: str, length: int) -> str:
|
||||
parser = PlaintextParser.from_string(html_content, Tokenizer(language))
|
||||
summarizer = LsaSummarizer()
|
||||
summary = summarizer(parser.document, length)
|
||||
return " ".join([str(sentence) for sentence in summary])
|
||||
|
||||
@@ -16,3 +16,8 @@ async def generate_random_numbers(count: int) -> str:
|
||||
|
||||
|
||||
# 该插件由MarshoAI自举编写
|
||||
|
||||
|
||||
@on_function_call(description="重载测试")
|
||||
def test_reload():
|
||||
return 1
|
||||
|
||||
@@ -12,7 +12,6 @@ dependencies = [
|
||||
"nonebot2>=2.2.0",
|
||||
"nonebot-plugin-alconna>=0.48.0",
|
||||
"nonebot-plugin-localstore>=0.7.1",
|
||||
"azure-ai-inference>=1.0.0b4",
|
||||
"zhDatetime>=1.1.1",
|
||||
"aiohttp>=3.9",
|
||||
"httpx>=0.27.0",
|
||||
@@ -24,7 +23,10 @@ dependencies = [
|
||||
"litedoc>=0.1.0.dev20241214103915",
|
||||
"newspaper3k>=0.2.8",
|
||||
"lxml[html_clean]>=5.3.0",
|
||||
"aiofiles>=24.1.0"
|
||||
"aiofiles>=24.1.0",
|
||||
"sumy>=0.11.0",
|
||||
"azure-ai-inference>=1.0.0b6",
|
||||
"watchdog>=6.0.0"
|
||||
|
||||
]
|
||||
license = { text = "MIT, Mulan PSL v2" }
|
||||
@@ -51,6 +53,7 @@ profile = "black"
|
||||
source = "scm"
|
||||
tag_filter = "v*"
|
||||
tag_regex = '^v(?:\D*)?(?P<version>([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|c|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$)$'
|
||||
fallback_version = "0.1.0"
|
||||
|
||||
[tool.pdm.build]
|
||||
includes = []
|
||||
|
||||
Reference in New Issue
Block a user