Compare commits

...

33 Commits

Author SHA1 Message Date
c8dd126042 🐛 移除make_chat函数中的tool_choice参数以简化函数调用 2024-12-29 16:33:25 +08:00
9ff8beb4d9 🐛 修复插件加载逻辑,移除多余的空行以提高代码可读性 2024-12-29 16:07:05 +08:00
3003dfad55 🐛 优化插件加载逻辑,修复内置插件加载的问题,动态加载内置插件并增强对sys.path下包的支持 2024-12-29 15:57:11 +08:00
fb428ffc19 更新安装文档,修正链接,添加小棉工具的相关信息 2024-12-29 15:01:10 +08:00
4b2676b9fc 更新marsho函数以处理tool_calls,优化函数调用参数,添加占位符参数以兼容部分模型(如GLM) 2024-12-29 06:33:52 +08:00
7c6319b839 更改主页链接引用 2024-12-25 13:23:43 +08:00
4b7e9d14f7 添加旧readme,版本发布预计时间 2024-12-25 13:18:54 +08:00
0c4835e75b Merge branch 'main' of github.com:LiteyukiStudio/nonebot-plugin-marshoai 2024-12-24 00:54:20 +08:00
3600b62176 添加贡献者展示组件,并更新项目文档以感谢贡献者 2024-12-24 00:54:16 +08:00
6631d84705 无效化需要使用ob11适配器的chat模块 2024-12-24 00:50:51 +08:00
9ba4f0cfa1 优化内存模块导入,确保正确获取数据文件 2024-12-24 00:40:05 +08:00
e4d9fef670 添加小棉工具弃用提示 2024-12-24 00:29:48 +08:00
1c74ddca7d 尝试调教pre-commit 2024-12-23 23:56:08 +08:00
83a5f6ae5d 再次修改description,尝试重新isort 2024-12-23 23:50:56 +08:00
f9dc5e500e 添加强制设置昵称配置项,移动测试插件到单独文件夹,稍微修改memory插件description(应该还是无法达到预期喵) 2024-12-23 23:36:47 +08:00
ba6b02d68e 新增marsho.status命令 2024-12-19 23:24:48 +08:00
c503228a5f 修复package.json语法错误 2024-12-17 23:47:58 +08:00
b9983330ab 重新触发pre-commit检查 2024-12-17 23:37:43 +08:00
19363b22ac 修复函数调用名错误,补充config 2024-12-17 23:33:53 +08:00
8b5a57d223 🐛 修复AI调用名的格式,将点替换为下划线 2024-12-17 23:17:05 +08:00
XuChenXu
9cca629b87 记忆系统实现 (#29)
*  添加记忆系统

* 🎨 black优化格式

* 🐛 删除apscheduler

*  将记忆插件转换为插件形式
2024-12-17 22:56:57 +08:00
Nya_Twisuki
b331a209c3 MegaKits插件移植 (#28)
* 新增了萌百插件(meowiki)

* 更新萌百搜索

* 删除萌百插件, 结束开发

* 新建MegaKits插件

* 修复

* 摩尔斯电码加密/解码

* 猫语转换/翻译
2024-12-17 22:54:04 +08:00
b0d6f87134 更新pyproject.toml,修改tag_regex以支持开发版本号,并添加fallback_version配置 2024-12-17 21:18:19 +08:00
cf96ab3ffe 更新文档,优化热重载功能说明,强调使用函数式编程风格以减少副作用影响 2024-12-17 21:14:34 +08:00
da710ac0bd 更新文档,建议使用函数式编程风格以更好地利用热重载功能,强调避免全局变量的使用 2024-12-17 21:12:20 +08:00
db3100c567 更新文档,添加热重载功能的偏函数式编程建议,强调避免全局变量使用 2024-12-17 21:11:44 +08:00
c3d4a797c0 更新插件热重载文档,明确副作用提示并修正插件自动加载描述 2024-12-17 21:11:01 +08:00
bdd80d0c2e 更新文档,添加插件热重载和兼容性说明,优化安装配置项描述 2024-12-17 21:09:20 +08:00
99c113833e 支持开发热重载插件,支持独立测试函数 2024-12-17 20:51:42 +08:00
87b18c424b 优化函数列表显示,添加短信息属性以改善函数调用的描述 2024-12-17 19:38:46 +08:00
7893f28259 添加函数调用支持,重构插件加载机制,优化函数描述和模块路径管理 2024-12-17 19:32:51 +08:00
339d0e05bf 移除获取类型参数,更新依赖azure-ai-inference版本,修正版本标签正则表达式 2024-12-17 14:52:26 +08:00
777e577a17 优化网页内容获取功能,添加摘要生成支持,重构相关函数 2024-12-17 13:51:18 +08:00
38 changed files with 1088 additions and 119 deletions

5
.gitignore vendored
View File

@@ -187,4 +187,7 @@ docs/.vitepress/cache
docs/.vitepress/dist docs/.vitepress/dist
# viztracer # viztracer
result.json result.json
data/*
marshoplugins/*

View File

@@ -27,6 +27,7 @@ _✨ 使用 OpenAI 标准格式 API 的聊天机器人插件 ✨_
插件内置了猫娘小棉(Marsho)的人物设定,可以进行可爱的聊天! 插件内置了猫娘小棉(Marsho)的人物设定,可以进行可爱的聊天!
*谁不喜欢回复消息快又可爱的猫娘呢?* *谁不喜欢回复消息快又可爱的猫娘呢?*
**对 OneBot 以外的适配器与非 GitHub Models API的支持未经过完全验证。** **对 OneBot 以外的适配器与非 GitHub Models API的支持未经过完全验证。**
**MarshoAI v1.0.0 预计在春节前后发布。重写好累啊QwQ**
[Melobot 实现](https://github.com/LiteyukiStudio/marshoai-melo) [Melobot 实现](https://github.com/LiteyukiStudio/marshoai-melo)
## 🐱 设定 ## 🐱 设定

0
docs/.vitepress/config/zh.ts Executable file → Normal file
View File

View File

@@ -0,0 +1,23 @@
<script setup lang="ts">
const contributorImgSrc = `https://contrib.rocks/image?repo=LiteyukiStudio/nonebot-plugin-marshoai`
const contributorsUrl = `https://github.com/LiteyukiStudio/nonebot-plugin-marshoai/graphs/contributors`
</script>
<template>
<div class="contributor-bar">
<a :href="contributorsUrl">
<div class="contributor-list">
<img :src=contributorImgSrc alt="Contributors">
</div>
</a>
</div>
</template>
<style scoped>
.contributor-bar {
display: flex;
flex-direction: column;
align-items: center;
}
</style>

View File

@@ -117,6 +117,7 @@ Add options in the `.env` file from the diagram below in nonebot2 project.
| MARSHOAI_DEFAULT_MODEL | `str` | `gpt-4o-mini` | The default model of Marsho | | MARSHOAI_DEFAULT_MODEL | `str` | `gpt-4o-mini` | The default model of Marsho |
| MARSHOAI_PROMPT | `str` | Catgirl Marsho's character prompt | Marsho's basic system prompt **※Some models(o1 and so on) don't support it** | | MARSHOAI_PROMPT | `str` | Catgirl Marsho's character prompt | Marsho's basic system prompt **※Some models(o1 and so on) don't support it** |
| MARSHOAI_ADDITIONAL_PROMPT | `str` | | Marsho's external system prompt | | MARSHOAI_ADDITIONAL_PROMPT | `str` | | Marsho's external system prompt |
| MARSHOAI_ENFORCE_NICKNAME | `bool` | `true` | Enforce user to set nickname or not |
| MARSHOAI_POKE_SUFFIX | `str` | `揉了揉你的猫耳` | When double click Marsho who connected to OneBot adapter, the chat content. When it's empty string, double click function is off. Such as, the default content is `*[昵称]揉了揉你的猫耳。` | | MARSHOAI_POKE_SUFFIX | `str` | `揉了揉你的猫耳` | When double click Marsho who connected to OneBot adapter, the chat content. When it's empty string, double click function is off. Such as, the default content is `*[昵称]揉了揉你的猫耳。` |
| MARSHOAI_AZURE_ENDPOINT | `str` | `https://models.inference.ai.azure.com` | OpenAI standard API | | MARSHOAI_AZURE_ENDPOINT | `str` | `https://models.inference.ai.azure.com` | OpenAI standard API |
| MARSHOAI_TEMPERATURE | `float` | `null` | temperature parameter | | MARSHOAI_TEMPERATURE | `float` | `null` | temperature parameter |

View File

@@ -9,7 +9,9 @@ order: 2
扩展分为两类,一类为插件,一类为工具。 扩展分为两类,一类为插件,一类为工具。
- 插件 - 插件
- 工具(由于开发的不便利性已经停止维护未来可能会放弃支持如有需求请看README中的内容我们不推荐再使用此功能) - 工具(由于开发的不便利性已经停止维护未来可能会放弃支持如有需求请看README中的内容我们不推荐再使用此功能)
**`v1.0.0`之前的版本不支持小棉插件。**
## 插件 ## 插件
@@ -22,7 +24,6 @@ order: 2
- 元数据:包含插件的信息,如名称、版本、作者等 - 元数据:包含插件的信息,如名称、版本、作者等
- function call供AI调用的函数 - function call供AI调用的函数
:::tip :::tip
如果你编写过NoneBot插件那么你会发现插件的编写方式和NoneBot插件的编写方式几乎一样。 如果你编写过NoneBot插件那么你会发现插件的编写方式和NoneBot插件的编写方式几乎一样。
::: :::
@@ -58,7 +59,11 @@ async def weather(location: str) -> str:
## 函数调用参数 ## 函数调用参数
`on_function_call`装饰器用于标记一个函数为function call`description`参数用于描述这个函数的作用,`params`方法用于定义函数的参数,`String``Integer`等是OpenAI API接受的参数的类型`description`是参数的描述。这些都是给AI看的AI会根据这些信息来调用函数。 `on_function_call`装饰器用于标记一个函数为function call`description`参数用于描述这个函数的作用,`params`方法用于定义函数的参数,`String``Integer`等是OpenAI API接受的参数的类型`description`是参数的描述。这些都是给AI看的AI会根据这些信息来调用函数。
:::warning
参数名不得为`placeholder`。此参数名是Marsho内部保留的用于保证兼容性的占位参数。
:::
```python ```python
@on_function_call(description="可以用于算命").params( @on_function_call(description="可以用于算命").params(
@@ -76,14 +81,19 @@ def fortune_telling(name: str, age: int) -> str:
```python ```python
@on_function_call(description="在设备上执行命令").params( @on_function_call(description="在设备上执行命令").params(
command=String(description="命令内容") command=String(description="命令内容")
).permission(SUPERUSER).rule(RegexRule("查询(.*)的天气")) ).permission(SUPERUSER)
def execute_command(command: str) -> str: def execute_command(command: str) -> str:
return eval(command) return eval(command)
``` ```
## 依赖注入 ## 依赖注入
function call支持NoneBot2原生的会话上下文依赖注入例如Bot、Event等 function call支持NoneBot2原生的会话上下文依赖注入
- Event 及其子类实例
- Bot 及其子类实例
- Matcher 及其子类实例
- T_State
```python ```python
@on_function_call(description="获取个人信息") @on_function_call(description="获取个人信息")
@@ -95,14 +105,39 @@ async def get_bot_info(b: Bot) -> str:
return f"机器人ID: {b.self_id}" return f"机器人ID: {b.self_id}"
``` ```
## 其他 ## 兼容性
- function call支持同步和异步函数 插件可以编写NoneBot或者轻雪插件的内容可作为NoneBot插件或者轻雪插件单独发布
- 本文是一个引导,要查看具体功能请查阅[插件 API 文档](./api/plugin/index)
不过所编写功能仅会在对应的实例上加载对应的功能如果通过marshoai加载混合插件那么插件中NoneBot的功能将会依附于marshoai插件
若通过NoneBot加载包含marshoai功能的NoneBot插件那么marshoai功能将会依附于NoneBot插件。
**我们建议**若插件中包含了NoneBot功能仍然使用marshoai进行加载这样更符合逻辑。若你想发布为NoneBot插件请注意`require("nonebot_plugin_marshoai")`,这是老生常谈了。
:::tip
本质上都是动态导入和注册声明加载,运行时把这些东西塞到一起
:::
## 插件热重载
插件热重载是一个实验性功能,可以在不重启机器人的情况下更新插件
:::warning
框架无法完全消除之前插件带来的副作用,当开发测试中效果不符合预期时请重启机器人实例
为了更好地让热重载功能正常工作,尽可能使用函数式的编程风格,以减少副作用的影响
:::
`MARSHOAI_DEVMODE`环境变量设置为`true`,然后在配置的插件目录`MARSHOAI_PLUGIN_DIRS`下开发插件,当插件发生变化时,机器人会自动变动的插件。
## AIGC 自举 ## AIGC 自举
:::warning :::warning
该功能为实验性功能请注意甄别AI的行为不要让AI执行危险的操作。 该功能为实验性功能请注意甄别AI的行为不要让AI执行危险的操作。
::: :::
function call为AI赋能实现了文件io操作AI可以调用function call来读取文档然后给自己编写代码实现自举。 function call为AI赋能实现了文件io操作AI可以调用function call来读取文档然后给自己编写代码实现自举。
## 其他
- function call支持同步和异步函数
- 本文是一个引导,要查看具体功能请查阅[插件 API 文档](./api/plugin/index)

View File

@@ -39,3 +39,11 @@ pre-commit install # 安装 pre-commit 钩子
- [`Google Docstring`](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) 文档规范 - [`Google Docstring`](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) 文档规范
可以在编辑器中安装相应的插件进行辅助 可以在编辑器中安装相应的插件进行辅助
## 其他
感谢以下的贡献者们:
<ContributorsBar />
<script setup> import ContributorsBar from '../../components/ContributorsBar.vue' </script>

0
docs/zh/index.md Executable file → Normal file
View File

View File

@@ -0,0 +1,151 @@
---
title: 安装
---
## 💿 安装
<details open>
<summary>使用 nb-cli 安装</summary>
在 nonebot2 项目的根目录下打开命令行, 输入以下指令即可安装
nb plugin install nonebot-plugin-marshoai
</details>
<details>
<summary>使用包管理器安装</summary>
在 nonebot2 项目的插件目录下, 打开命令行, 根据你使用的包管理器, 输入相应的安装命令
<details>
<summary>pip</summary>
pip install nonebot-plugin-marshoai
</details>
<details>
<summary>pdm</summary>
pdm add nonebot-plugin-marshoai
</details>
<details>
<summary>poetry</summary>
poetry add nonebot-plugin-marshoai
</details>
<details>
<summary>conda</summary>
conda install nonebot-plugin-marshoai
</details>
打开 nonebot2 项目根目录下的 `pyproject.toml` 文件, 在 `[tool.nonebot]` 部分追加写入
plugins = ["nonebot_plugin_marshoai"]
</details>
## 🤖 获取 token(GitHub Models)
- 新建一个[personal access token](https://github.com/settings/tokens/new)**不需要给予任何权限**。
- 将新建的 token 复制,添加到`.env`文件中的`marshoai_token`配置项中。
## 🎉 使用
发送`marsho`指令可以获取使用说明(若在配置中自定义了指令前缀请使用自定义的指令前缀)。
#### 👉 戳一戳
当 nonebot 连接到支持的 OneBot v11 实现端时,可以接收头像双击戳一戳消息并进行响应。详见`MARSHOAI_POKE_SUFFIX`配置项。
## 🛠️ ~~小棉工具~~(已弃用)
小棉工具(MarshoTools)是`v0.5.0`版本的新增功能,支持加载外部函数库来为 Marsho 提供 Function Call 功能。
## 🧩 小棉插件
小棉插件是`v1.0.0`的新增功能,替代旧的小棉工具功能。[使用文档](https://marsho.liteyuki.icu/dev/extension)
## 👍 夸赞名单
夸赞名单存储于插件数据目录下的`praises.json`里(该目录路径会在 Bot 启动时输出到日志),当配置项为`true`
时发起一次聊天后自动生成,包含人物名字与人物优点两个基本数据。
存储于其中的人物会被 Marsho “认识”和“喜欢”。
其结构类似于:
```json
{
"like": [
{
"name": "Asankilp",
"advantages": "赋予了Marsho猫娘人格使用vim与vscode为Marsho写了许多代码使Marsho更加可爱"
},
{
"name": "神羽(snowykami)",
"advantages": "人脉很广,经常找小伙伴们开银趴,很会写后端代码"
},
...
]
}
```
## ⚙️ 可配置项
在 nonebot2 项目的`.env`文件中添加下表中的配置
#### 插件行为
| 配置项 | 类型 | 默认值 | 说明 |
| ------------------------ | ------ | ------- | ---------------- |
| MARSHOAI_USE_YAML_CONFIG | `bool` | `false` | 是否使用 YAML 配置文件格式 |
| MARSHOAI_DEVMODE | `bool` | `false` | 是否启用开发者模式 |
#### Marsho 使用方式
| 配置项 | 类型 | 默认值 | 说明 |
| --------------------- | ---------- | ----------- | ----------------- |
| MARSHOAI_DEFAULT_NAME | `str` | `marsho` | 调用 Marsho 默认的命令前缀 |
| MARSHOAI_ALIASES | `set[str]` | `set{"小棉"}` | 调用 Marsho 的命令别名 |
| MARSHOAI_AT | `bool` | `false` | 决定是否使用at触发 |
| MARSHOAI_MAIN_COLOUR | `str` | `FFAAAA` | 主题色,部分工具和功能可用 |
#### AI 调用
| 配置项 | 类型 | 默认值 | 说明 |
| -------------------------------- | ------- | --------------------------------------- | --------------------------------------------------------------------------------------------- |
| MARSHOAI_TOKEN | `str` | | 调用 AI API 所需的 token |
| MARSHOAI_DEFAULT_MODEL | `str` | `gpt-4o-mini` | Marsho 默认调用的模型 |
| MARSHOAI_PROMPT | `str` | 猫娘 Marsho 人设提示词 | Marsho 的基本系统提示词 **※部分模型(o1等)不支持系统提示词。** |
| MARSHOAI_ADDITIONAL_PROMPT | `str` | | Marsho 的扩展系统提示词 |
| MARSHOAI_ENFORCE_NICKNAME | `bool` | `true` | 是否强制用户设置昵称 |
| MARSHOAI_POKE_SUFFIX | `str` | `揉了揉你的猫耳` | 对 Marsho 所连接的 OneBot 用户进行双击戳一戳时,构建的聊天内容。此配置项为空字符串时,戳一戳响应功能会被禁用。例如,默认值构建的聊天内容将为`*[昵称]揉了揉你的猫耳。` |
| MARSHOAI_AZURE_ENDPOINT | `str` | `https://models.inference.ai.azure.com` | OpenAI 标准格式 API 端点 |
| MARSHOAI_TEMPERATURE | `float` | `null` | 推理生成多样性(温度)参数 |
| MARSHOAI_TOP_P | `float` | `null` | 推理核采样参数 |
| MARSHOAI_MAX_TOKENS | `int` | `null` | 最大生成 token 数 |
| MARSHOAI_ADDITIONAL_IMAGE_MODELS | `list` | `[]` | 额外添加的支持图片的模型列表,例如`hunyuan-vision` |
#### 功能开关
| 配置项 | 类型 | 默认值 | 说明 |
| --------------------------------- | ------ | ------ | -------------------------- |
| MARSHOAI_ENABLE_SUPPORT_IMAGE_TIP | `bool` | `true` | 启用后用户发送带图请求时若模型不支持图片,则提示用户 |
| MARSHOAI_ENABLE_NICKNAME_TIP | `bool` | `true` | 启用后用户未设置昵称时提示用户设置 |
| MARSHOAI_ENABLE_PRAISES | `bool` | `true` | 是否启用夸赞名单功能 |
| MARSHOAI_ENABLE_TOOLS | `bool` | `false` | 是否启用小棉工具 |
| 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_DEVMODE | `bool` | `false` | 是否启用开发者模式 |

View File

@@ -60,11 +60,8 @@ title: 安装
当 nonebot 连接到支持的 OneBot v11 实现端时,可以接收头像双击戳一戳消息并进行响应。详见`MARSHOAI_POKE_SUFFIX`配置项。 当 nonebot 连接到支持的 OneBot v11 实现端时,可以接收头像双击戳一戳消息并进行响应。详见`MARSHOAI_POKE_SUFFIX`配置项。
## 🛠️ ~~小棉工具~~(已弃用) ## 🛠️ 小棉工具
小棉工具(MarshoTools)是`v0.5.0`版本的新增功能,支持加载外部函数库来为 Marsho 提供 Function Call 功能。 小棉工具(MarshoTools)是`v0.5.0`版本的新增功能,支持加载外部函数库来为 Marsho 提供 Function Call 功能。[使用文档]
## 🧩 小棉插件
小棉插件是`v1.0.0`的新增功能,替代旧的小棉工具功能。[使用文档](https://marsho.liteyuki.icu/dev/extension)
## 👍 夸赞名单 ## 👍 夸赞名单
@@ -98,7 +95,6 @@ title: 安装
| 配置项 | 类型 | 默认值 | 说明 | | 配置项 | 类型 | 默认值 | 说明 |
| ------------------------ | ------ | ------- | ---------------- | | ------------------------ | ------ | ------- | ---------------- |
| MARSHOAI_USE_YAML_CONFIG | `bool` | `false` | 是否使用 YAML 配置文件格式 | | MARSHOAI_USE_YAML_CONFIG | `bool` | `false` | 是否使用 YAML 配置文件格式 |
| MARSHOAI_DEVMODE | `bool` | `false` | 是否启用开发者模式 |
#### Marsho 使用方式 #### Marsho 使用方式
@@ -131,9 +127,7 @@ title: 安装
| MARSHOAI_ENABLE_SUPPORT_IMAGE_TIP | `bool` | `true` | 启用后用户发送带图请求时若模型不支持图片,则提示用户 | | MARSHOAI_ENABLE_SUPPORT_IMAGE_TIP | `bool` | `true` | 启用后用户发送带图请求时若模型不支持图片,则提示用户 |
| MARSHOAI_ENABLE_NICKNAME_TIP | `bool` | `true` | 启用后用户未设置昵称时提示用户设置 | | MARSHOAI_ENABLE_NICKNAME_TIP | `bool` | `true` | 启用后用户未设置昵称时提示用户设置 |
| MARSHOAI_ENABLE_PRAISES | `bool` | `true` | 是否启用夸赞名单功能 | | MARSHOAI_ENABLE_PRAISES | `bool` | `true` | 是否启用夸赞名单功能 |
| MARSHOAI_ENABLE_TOOLS | `bool` | `false` | 是否启用小棉工具 | | MARSHOAI_ENABLE_TOOLS | `bool` | `true` | 是否启用小棉工具 |
| MARSHOAI_ENABLE_PLUGINS | `bool` | `true` | 是否启用小棉插件 |
| MARSHOAI_PLUGIN_DIRS | `list[str]` | `[]` | 插件目录路径列表 |
| MARSHOAI_LOAD_BUILTIN_TOOLS | `bool` | `true` | 是否加载内置工具包 | | MARSHOAI_LOAD_BUILTIN_TOOLS | `bool` | `true` | 是否加载内置工具包 |
| MARSHOAI_TOOLSET_DIR | `list` | `[]` | 外部工具集路径列表 | | MARSHOAI_TOOLSET_DIR | `list` | `[]` | 外部工具集路径列表 |
| MARSHOAI_DISABLED_TOOLKITS | `list` | `[]` | 禁用的工具包包名列表 | | MARSHOAI_DISABLED_TOOLKITS | `list` | `[]` | 禁用的工具包包名列表 |

View File

@@ -6,9 +6,11 @@ require("nonebot_plugin_localstore")
import nonebot_plugin_localstore as store # type: ignore import nonebot_plugin_localstore as store # type: ignore
from nonebot import get_driver, logger # type: ignore from nonebot import get_driver, logger # type: ignore
# from .hunyuan import *
from .azure import * from .azure import *
from .config import config from .config import config
# from .hunyuan import *
from .dev import *
from .metadata import metadata from .metadata import metadata
__author__ = "Asankilp" __author__ = "Asankilp"

View File

@@ -72,6 +72,14 @@ marsho_help_cmd = on_alconna(
priority=10, priority=10,
block=True, block=True,
) )
marsho_status_cmd = on_alconna(
Alconna(
config.marshoai_default_name + ".status",
),
priority=10,
block=True,
)
marsho_at = on_message(rule=to_me() & at_enable, priority=11) marsho_at = on_message(rule=to_me() & at_enable, priority=11)
nickname_cmd = on_alconna( nickname_cmd = on_alconna(
Alconna( Alconna(
@@ -109,20 +117,24 @@ async def _preload_tools():
logger.info( logger.info(
"如果启用小棉工具后使用的模型出现报错,请尝试将 MARSHOAI_ENABLE_TOOLS 设为 false。" "如果启用小棉工具后使用的模型出现报错,请尝试将 MARSHOAI_ENABLE_TOOLS 设为 false。"
) )
logger.opt(colors=True).warning(
"<y>小棉工具已被弃用,可能会在未来版本中移除。</y>"
)
@driver.on_startup @driver.on_startup
async def _preload_plugins(): async def _():
"""启动钩子加载插件""" """启动钩子加载插件"""
if config.marshoai_enable_plugins: if config.marshoai_enable_plugins:
marshoai_plugin_dirs = config.marshoai_plugin_dirs # 外部插件目录列表 marshoai_plugin_dirs = config.marshoai_plugin_dirs # 外部插件目录列表
"""加载内置插件""" """加载内置插件"""
marshoai_plugin_dirs.insert( for p in os.listdir(Path(__file__).parent / "plugins"):
0, Path(__file__).parent / "plugins" load_plugin(f"{__package__}.plugins.{p}")
) # 预置插件目录
"""加载指定目录插件""" """加载指定目录插件"""
load_plugins(*marshoai_plugin_dirs) load_plugins(*marshoai_plugin_dirs)
"""加载sys.path下的包"""
"""加载sys.path下的包, 包括从pip安装的包"""
for package_name in config.marshoai_plugins: for package_name in config.marshoai_plugins:
load_plugin(package_name) load_plugin(package_name)
logger.info( logger.info(
@@ -226,6 +238,16 @@ async def marsho_help():
await marsho_help_cmd.finish(metadata.usage) await marsho_help_cmd.finish(metadata.usage)
@marsho_status_cmd.handle()
async def marsho_status():
await marsho_status_cmd.finish(
f"当前使用的模型:{model_name}\n"
# f"当前会话数量:{len(target_list)}\n"
# f"当前上下文数量:{len(context.contexts)}"
f"当前支持图片的模型:{str(SUPPORT_IMAGE_MODELS + config.marshoai_additional_image_models)}"
)
@marsho_at.handle() @marsho_at.handle()
@marsho_cmd.handle() @marsho_cmd.handle()
async def marsho( async def marsho(
@@ -246,21 +268,28 @@ async def marsho(
if not text: if not text:
# 发送说明 # 发送说明
# await UniMessage(metadata.usage + "\n当前使用的模型" + model_name).send() # await UniMessage(metadata.usage + "\n当前使用的模型" + model_name).send()
await marsho_cmd.finish(INTRODUCTION + "\n当前使用的模型:" + model_name) await marsho_cmd.finish(INTRODUCTION)
try: try:
user_id = event.get_user_id() user_id = event.get_user_id()
nicknames = await get_nicknames() nicknames = await get_nicknames()
user_nickname = nicknames.get(user_id, "") user_nickname = nicknames.get(user_id, "")
if user_nickname != "": if user_nickname != "":
nickname_prompt = f"\n*此消息的说话者:{user_nickname}*" nickname_prompt = (
f"\n*此消息的说话者id为:{user_id},名字为:{user_nickname}*"
)
else: else:
nickname_prompt = "" nickname_prompt = ""
# 用户名无法获取,暂时注释 # 用户名无法获取,暂时注释
# user_nickname = event.sender.nickname # 未设置昵称时获取用户名 # user_nickname = event.sender.nickname # 未设置昵称时获取用户名
# nickname_prompt = f"\n*此消息的说话者:{user_nickname}" # nickname_prompt = f"\n*此消息的说话者:{user_nickname}"
if config.marshoai_enforce_nickname:
await UniMessage(
"※你未设置自己的昵称。你**必须**使用「nickname [昵称]」命令设置昵称后才能进行对话。"
).send()
return
if config.marshoai_enable_nickname_tip: if config.marshoai_enable_nickname_tip:
await UniMessage( await UniMessage(
"*你未设置自己的昵称。推荐使用'nickname [昵称]'命令设置昵称来获得个性化(可能)回答。" "你未设置自己的昵称。推荐使用nickname [昵称]命令设置昵称来获得个性化(可能)回答。"
).send() ).send()
is_support_image_model = ( is_support_image_model = (
@@ -285,7 +314,9 @@ async def marsho(
) # type: ignore ) # type: ignore
) # type: ignore ) # type: ignore
elif config.marshoai_enable_support_image_tip: elif config.marshoai_enable_support_image_tip:
await UniMessage("*此模型不支持图片处理。").send() await UniMessage(
"*此模型不支持图片处理或管理员未启用此模型的图片支持。图片将被忽略。"
).send()
backup_context = await get_backup_context(target.id, target.private) backup_context = await get_backup_context(target.id, target.private)
if backup_context: if backup_context:
context.set_context( context.set_context(
@@ -307,6 +338,10 @@ async def marsho(
) )
# await UniMessage(str(response)).send() # await UniMessage(str(response)).send()
choice = response.choices[0] choice = response.choices[0]
# Sprint(choice)
# 当tool_calls非空时将finish_reason设置为TOOL_CALLS
if choice.message.tool_calls != None:
choice["finish_reason"] = CompletionsFinishReason.TOOL_CALLS
if choice["finish_reason"] == CompletionsFinishReason.STOPPED: if choice["finish_reason"] == CompletionsFinishReason.STOPPED:
# 当对话成功时将dict的上下文添加到上下文类中 # 当对话成功时将dict的上下文添加到上下文类中
context.append( context.append(
@@ -349,11 +384,16 @@ async def marsho(
function_args = json.loads( function_args = json.loads(
tool_call.function.arguments.replace("'", '"') tool_call.function.arguments.replace("'", '"')
) )
# 删除args的placeholder参数
if "placeholder" in function_args:
del function_args["placeholder"]
logger.info( 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( 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() ).send()
# TODO 临时追加插件函数,若工具中没有则调用插件函数 # TODO 临时追加插件函数,若工具中没有则调用插件函数
if tools.has_function(tool_call.function.name): if tools.has_function(tool_call.function.name):
@@ -363,9 +403,9 @@ async def marsho(
) # 获取返回值 ) # 获取返回值
else: else:
if caller := get_function_calls().get( 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 # 权限检查,规则检查 TODO
# 实现依赖注入检查函数参数及参数注解类型对Event类型的参数进行注入 # 实现依赖注入检查函数参数及参数注解类型对Event类型的参数进行注入
func_return = await caller.with_ctx( func_return = await caller.with_ctx(
@@ -377,18 +417,26 @@ async def marsho(
) )
).call(**function_args) ).call(**function_args)
else: else:
logger.error(f"未找到函数 {tool_call.function.name}") logger.error(
func_return = f"未找到函数 {tool_call.function.name}" f"未找到函数 {tool_call.function.name.replace('-', '.')}"
)
func_return = f"未找到函数 {tool_call.function.name.replace('-', '.')}"
tool_msg.append( tool_msg.append(
ToolMessage(tool_call_id=tool_call.id, content=func_return) # type: ignore ToolMessage(tool_call_id=tool_call.id, content=func_return).as_dict() # type: ignore
) )
request_msg = context_msg + [UserMessage(content=usermsg).as_dict()] + tool_msg # type: ignore
response = await make_chat( response = await make_chat(
client=client, client=client,
model_name=model_name, model_name=model_name,
msg=context_msg + [UserMessage(content=usermsg)] + tool_msg, # type: ignore msg=request_msg, # type: ignore
tools=tools.get_tools_list(), tools=(
tools_lists if tools_lists else None
), # TODO 临时追加函数,后期优化
) )
choice = response.choices[0] choice = response.choices[0]
# 当tool_calls非空时将finish_reason设置为TOOL_CALLS
if choice.message.tool_calls != None:
choice["finish_reason"] = CompletionsFinishReason.TOOL_CALLS
if choice["finish_reason"] == CompletionsFinishReason.STOPPED: if choice["finish_reason"] == CompletionsFinishReason.STOPPED:
# 对话成功 添加上下文 # 对话成功 添加上下文

View File

@@ -34,8 +34,9 @@ class ConfigModel(BaseModel):
marshoai_single_latex_parse: bool = False marshoai_single_latex_parse: bool = False
marshoai_enable_nickname_tip: bool = True marshoai_enable_nickname_tip: bool = True
marshoai_enable_support_image_tip: bool = True marshoai_enable_support_image_tip: bool = True
marshoai_enforce_nickname: bool = True
marshoai_enable_praises: bool = True marshoai_enable_praises: bool = True
marshoai_enable_time_prompt: bool = True # marshoai_enable_time_prompt: bool = True
marshoai_enable_tools: bool = False marshoai_enable_tools: bool = False
marshoai_enable_plugins: bool = True marshoai_enable_plugins: bool = True
marshoai_load_builtin_tools: bool = True marshoai_load_builtin_tools: bool = True
@@ -52,7 +53,7 @@ class ConfigModel(BaseModel):
marshoai_plugin_dirs: list[str] = [] marshoai_plugin_dirs: list[str] = []
"""插件目录(不是工具)""" """插件目录(不是工具)"""
marshoai_devmode: bool = False marshoai_devmode: bool = False
"""开发者模式""" """开发者模式,启用本地插件插件重载"""
marshoai_plugins: list[str] = [] marshoai_plugins: list[str] = []
"""marsho插件的名称列表从pip安装的使用包名从本地导入的使用路径""" """marsho插件的名称列表从pip安装的使用包名从本地导入的使用路径"""

View File

@@ -32,6 +32,8 @@ marshoai_enable_nickname_tip: true # 是否启用昵称提示。
marshoai_enable_support_image_tip: true # 是否启用支持图片提示。 marshoai_enable_support_image_tip: true # 是否启用支持图片提示。
marshoai_enforce_nickname: true # 是否强制要求设定昵称。
marshoai_enable_praises: true # 是否启用夸赞名单功能。 marshoai_enable_praises: true # 是否启用夸赞名单功能。
marshoai_enable_tools: false # 是否启用工具支持。 marshoai_enable_tools: false # 是否启用工具支持。
@@ -46,6 +48,8 @@ marshoai_disabled_toolkits: [] # 已禁用的工具包列表。
marshoai_plugin_dirs: [] # 插件路径。 marshoai_plugin_dirs: [] # 插件路径。
marshoai_plugins: [] # 导入的插件名可以为pip包或本地导入的使用路径。
marshoai_devmode: false # 是否启用开发者模式。 marshoai_devmode: false # 是否启用开发者模式。
marshoai_azure_endpoint: "https://models.inference.ai.azure.com" # OpenAI 标准格式 API 的端点。 marshoai_azure_endpoint: "https://models.inference.ai.azure.com" # OpenAI 标准格式 API 的端点。

View File

@@ -30,6 +30,7 @@ INTRODUCTION: str = f"""MarshoAI-NoneBot by LiteyukiStudio
我的主页在这里哦~↓↓↓ 我的主页在这里哦~↓↓↓
https://marsho.liteyuki.icu https://marsho.liteyuki.icu
※ 使用 「{config.marshoai_default_name}.status」命令获取状态信息。
※ 使用「{config.marshoai_default_name}.help」命令获取使用说明。""" ※ 使用「{config.marshoai_default_name}.help」命令获取使用说明。"""

View File

@@ -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") 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(
f"{config.marshoai_default_name}.funccall",
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

View File

@@ -47,6 +47,13 @@ class MarshoContext:
if target_id in target_dict: if target_id in target_dict:
target_dict[target_id].clear() 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: def build(self, target_id: str, is_private: bool) -> list:
""" """
构建返回的上下文,不包括系统消息 构建返回的上下文,不包括系统消息

View 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

View File

@@ -8,6 +8,7 @@ from nonebot.permission import Permission
from nonebot.rule import Rule from nonebot.rule import Rule
from nonebot.typing import T_State from nonebot.typing import T_State
from ..models import Plugin
from ..typing import ASYNC_FUNCTION_CALL_FUNC, F from ..typing import ASYNC_FUNCTION_CALL_FUNC, F
from .models import SessionContext, SessionContextDepends from .models import SessionContext, SessionContextDepends
from .utils import async_wrap, is_coroutine_callable from .utils import async_wrap, is_coroutine_callable
@@ -16,10 +17,17 @@ _caller_data: dict[str, "Caller"] = {}
class Caller: class Caller:
def __init__(self, name: str | None = None, description: str | None = None): def __init__(self, name: str = "", description: str | None = None):
self._name = name self._name: str = name
"""函数名称"""
self._description = description self._description = description
"""函数描述"""
self._plugin: Plugin | None = None
"""所属插件对象,装饰时声明"""
self.func: ASYNC_FUNCTION_CALL_FUNC | None = None self.func: ASYNC_FUNCTION_CALL_FUNC | None = None
"""函数对象"""
self.module_name: str = ""
"""模块名,仅为父级模块名,不一定是插件顶级模块名"""
self._parameters: dict[str, Any] = {} self._parameters: dict[str, Any] = {}
"""声明参数""" """声明参数"""
@@ -91,13 +99,8 @@ class Caller:
F: 函数对象 F: 函数对象
""" """
global _caller_data global _caller_data
if self._name is None: if not self._name:
if module := inspect.getmodule(func): self._name = func.__name__
module_name = module.__name__.split(".")[-1]
else:
module_name = ""
self._name = f"{module_name}-{func.__name__}"
_caller_data[self._name] = self
# 检查函数签名,确定依赖注入参数 # 检查函数签名,确定依赖注入参数
sig = inspect.signature(func) sig = inspect.signature(func)
@@ -134,11 +137,14 @@ class Caller:
self.func = async_wrap(func) # type: ignore self.func = async_wrap(func) # type: ignore
if module := inspect.getmodule(func): if module := inspect.getmodule(func):
module_name = module.__name__.split(".")[-1] + "." module_name = module.__name__.split(".")[-1]
else: else:
module_name = "" module_name = ""
self.module_name = module_name
_caller_data[self.full_name] = self
logger.opt(colors=True).debug( logger.opt(colors=True).debug(
f"<y>加载函数 {module_name}{func.__name__}: {self._description}</y>" f"<y>加载函数 {self.full_name}: {self._description}</y>"
) )
return func return func
@@ -152,12 +158,18 @@ class Caller:
return { return {
"type": "function", "type": "function",
"function": { "function": {
"name": self._name, "name": self.aifc_name,
"description": self._description, "description": self._description,
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": { "properties": {
key: value.data() for key, value in self._parameters.items() **{
key: value.data() for key, value in self._parameters.items()
},
"placeholder": {
"type": "string",
"description": "占位符,用于显示在对话框中", # 为保证兼容性而设置的无用参数
},
}, },
}, },
"required": [ "required": [
@@ -193,6 +205,11 @@ class Caller:
self.set_ctx(ctx) self.set_ctx(ctx)
return self 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: async def call(self, *args: Any, **kwargs: Any) -> Any:
"""调用函数 """调用函数
@@ -214,8 +231,27 @@ class Caller:
return await self.func(*args, **kwargs) 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.full_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函数 """返回一个Caller类可用于装饰一个函数使其注册为一个可被AI调用的function call函数
Args: Args:

View File

@@ -45,7 +45,9 @@ def get_plugins() -> dict[str, Plugin]:
return _plugins 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` 安装的插件。 """加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
该函数产生的副作用在于将插件加载到 `_plugins` 中。 该函数产生的副作用在于将插件加载到 `_plugins` 中。
@@ -63,11 +65,15 @@ def load_plugin(module_path: str | Path) -> Optional[Plugin]:
try: try:
module = import_module(module_path) # 导入模块对象 module = import_module(module_path) # 导入模块对象
plugin = Plugin( plugin = Plugin(
name=module.__name__, name=module.__name__.split(".")[-1],
module=module, module=module,
module_name=module_path, 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) plugin.metadata = getattr(module, "__marsho_meta__", None)
@@ -101,9 +107,7 @@ def load_plugins(*plugin_dirs: str) -> set[Plugin]:
for plugin_dir in plugin_dirs: for plugin_dir in plugin_dirs:
for f in os.listdir(plugin_dir): for f in os.listdir(plugin_dir):
path = Path(os.path.join(plugin_dir, f)) path = Path(os.path.join(plugin_dir, f))
module_name = None module_name = None
if os.path.isfile(path) and f.endswith(".py"): if os.path.isfile(path) and f.endswith(".py"):
"""单文件加载""" """单文件加载"""
module_name = f"{path_to_module_name(Path(plugin_dir))}.{f[:-3]}" module_name = f"{path_to_module_name(Path(plugin_dir))}.{f[:-3]}"
@@ -117,3 +121,33 @@ def load_plugins(*plugin_dirs: str) -> set[Plugin]:
if module_name and (plugin := load_plugin(module_name)): if module_name and (plugin := load_plugin(module_name)):
plugins.add(plugin) plugins.add(plugin)
return plugins 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

View File

@@ -57,7 +57,9 @@ class Plugin(BaseModel):
module: ModuleType module: ModuleType
"""插件模块对象""" """插件模块对象"""
module_name: str module_name: str
"""点分割模块路径 例如a.b.c""" """点分或/割模块路径 例如a.b.c"""
module_path: str | None
"""实际路径,单文件为.py的路径包为__init__.py路径"""
metadata: PluginMetadata | None = None metadata: PluginMetadata | None = None
"""""" """"""
@@ -69,3 +71,6 @@ class Plugin(BaseModel):
def __eq__(self, other: Any) -> bool: def __eq__(self, other: Any) -> bool:
return self.name == other.name return self.name == other.name
def __str__(self) -> str:
return f"Plugin({self.name}({self.module_path}))"

View File

@@ -1,6 +1,6 @@
from nonebot_plugin_marshoai.plugin import PluginMetadata from nonebot_plugin_marshoai.plugin import PluginMetadata
from .chat import * # from .chat import *
from .file_io import * from .file_io import *
from .liteyuki import * from .liteyuki import *
from .manager import * from .manager import *

View File

@@ -1,12 +1,12 @@
import time
from httpx import AsyncClient from httpx import AsyncClient
from newspaper import Article from newspaper import Article # type: ignore
from nonebot import logger from nonebot import logger
from nonebot_plugin_marshoai.plugin.func_call.caller import on_function_call from nonebot_plugin_marshoai.plugin.func_call.caller import on_function_call
from nonebot_plugin_marshoai.plugin.func_call.params import String from nonebot_plugin_marshoai.plugin.func_call.params import String
from .utils import make_html_summary
headers = { headers = {
"User-Agent": "Firefox/90.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" "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上网查询资料" description="使用网页链接(url)获取网页内容摘要,可以让AI上网查询资料"
).params( ).params(
url=String(description="网页链接"), 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超限了 为什么要获取摘要不然token超限了
@@ -31,16 +30,19 @@ async def get_web_content(url: str, typ: str) -> str:
async with AsyncClient(headers=headers) as client: async with AsyncClient(headers=headers) as client:
try: try:
response = await client.get(url) response = await client.get(url)
t1 = time.time() if response.status_code == 200:
article = Article(url) article = Article(url)
article.set_html(response.text) article.download(input_html=response.text)
article.parse() article.parse()
t2 = time.time() if article.text:
logger.debug(f"获取网页内容耗时: {t2 - t1}") return article.text
if typ == "摘要": elif article.html:
return f"标题: {article.title}\n作者: {article.authors}\n发布日期: {article.publish_date}" return await make_html_summary(article.html)
elif typ == "内容": else:
return f"标题: {article.title}\n作者: {article.authors}\n发布日期: {article.publish_date}\n摘要: {article.summary}\n正文: {article.text}" return "未能获取到有效的网页内容"
else:
return "获取网页内容失败" + str(response.status_code)
except Exception as e: except Exception as e:
logger.error(f"marsho builtin: 获取网页内容失败: {e}") logger.error(f"marsho builtin: 获取网页内容失败: {e}")
return "获取网页内容失败:" + str(e) return "获取网页内容失败:" + str(e)

View File

@@ -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])

View File

@@ -0,0 +1,65 @@
import json
from pathlib import Path
from nonebot import require
from nonebot_plugin_localstore import get_plugin_data_file # type: ignore
from nonebot_plugin_marshoai.plugin import ( # type: ignore
PluginMetadata,
on_function_call,
)
from nonebot_plugin_marshoai.plugin.func_call.params import String # type: ignore
__marsho_meta__ = PluginMetadata(
name="记忆保存",
author="MarshoAI",
description="这个插件可以帮助AI记住一些事情",
)
memory_path = get_plugin_data_file("memory.json")
if not Path(memory_path).exists():
with open(memory_path, "w", encoding="utf-8") as f:
json.dump({}, f, ensure_ascii=False, indent=4)
# print(memory_path)
@on_function_call(
description="当你发现与你对话的用户的一些信息值得你记忆,或者用户让你记忆等时,调用此函数存储记忆内容"
).params(
memory=String(description="你想记住的内容,概括并保留关键内容"),
user_id=String(description="你想记住的人的id"),
)
async def write_memory(memory: str, user_id: str):
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
memorys = memory_data.get(user_id, [])
memorys.append(memory)
memory_data[user_id] = memorys
with open(memory_path, "w", encoding="utf-8") as f:
json.dump(memory_data, f, ensure_ascii=False, indent=4)
return "记忆已经保存啦~"
@on_function_call(
description="当用户与你发起对话时,你需要回忆有关他的一切,因此调用此函数读取记忆内容"
).params(user_id=String(description="你想读取记忆的人的id"))
async def read_memory(user_id: str):
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
memorys = memory_data.get(user_id, [])
if not memorys:
return "好像对ta还没有任何记忆呢~"
return "这些是有关ta的记忆" + "\n".join(memorys)
async def organize_memories():
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
for i in memory_data:
...
# TODO 用大模型对记忆进行整理

View File

@@ -0,0 +1,17 @@
[
{
"type": "function",
"function": {
"name": "marshoai_memory__write_memory",
"description": "如果在上下中你看见并觉得应该记住的人的行为与事件请调用这个函数并将记忆内容写入。请尽量每次都调用总结ta的习惯、爱好和性格,以及你对ta的印象和ta对你的印象;比如用户喜欢干什么吃什么。"
}
},
{
"type": "function",
"function": {
"name": "marshoai_memory__read_memory",
"description": "每当你想要获取更多有关某人的信息的时候,请调用这个函数。"
}
}
]

View File

@@ -0,0 +1,45 @@
from nonebot_plugin_marshoai.plugin import (
Integer,
Parameter,
PluginMetadata,
String,
on_function_call,
)
from . import mk_morse_code, mk_nya_code
__marsho_meta__ = PluginMetadata(
name="MegaKits插件",
description="一个功能混杂的多文件插件",
author="Twisuki",
)
@on_function_call(description="摩尔斯电码加密").params(
msg=String(description="被加密语句")
)
async def morse_encrypt(msg: str) -> str:
"""摩尔斯电码加密"""
return str(await mk_morse_code.morse_encrypt(msg))
@on_function_call(description="摩尔斯电码解密").params(
msg=String(description="被解密语句")
)
async def morse_decrypt(msg: str) -> str:
"""摩尔斯电码解密"""
return str(await mk_morse_code.morse_decrypt(msg))
@on_function_call(description="转换为猫语").params(msg=String(description="被转换语句"))
async def nya_encrypt(msg: str) -> str:
"""转换为猫语"""
return str(await mk_nya_code.nya_encrypt(msg))
@on_function_call(description="将猫语翻译回人类语言").params(
msg=String(description="被翻译语句")
)
async def nya_decrypt(msg: str) -> str:
"""将猫语翻译回人类语言"""
return str(await mk_nya_code.nya_decrypt(msg))

View File

@@ -0,0 +1,82 @@
# MorseCode
MorseEncode = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"V": "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
".": ".-.-.-",
":": "---...",
",": "--..--",
";": "-.-.-.",
"?": "..--..",
"=": "-...-",
"'": ".----.",
"/": "-..-.",
"!": "-.-.--",
"-": "-....-",
"_": "..--.-",
'"': ".-..-.",
"(": "-.--.",
")": "-.--.-",
"$": "...-..-",
"&": "....",
"@": ".--.-.",
" ": " ",
}
MorseDecode = {value: key for key, value in MorseEncode.items()}
async def morse_encrypt(msg: str):
result = ""
msg = msg.upper()
for char in msg:
if char in MorseEncode:
result += MorseEncode[char]
else:
result += "..--.."
result += " "
return result
async def morse_decrypt(msg: str):
result = ""
msg = msg.replace("_", "-")
msg_arr = msg.split(" ")
for element in msg_arr:
if element in MorseDecode:
result += MorseDecode[element]
else:
result += "?"
return result

View File

@@ -0,0 +1,74 @@
# NyaCode
import base64
import random
NyaCodeCharset = ["", "", "?", "~"]
NyaCodeSpecialCharset = ["", "!", "...", ".."]
NyaCodeEncode = {}
for i in range(64):
triplet = ""
for j in range(3):
index = (i // (4**j)) % 4
triplet += NyaCodeCharset[index]
if i < 26:
char = chr(65 + i) # 大写字母 A-Z
elif i < 52:
char = chr(97 + (i - 26)) # 小写字母 a-z
elif i < 62:
char = chr(48 + (i - 52)) # 数字 0-9
elif i == 62:
char = chr(43) # 特殊字符 +
else:
char = chr(47) # 特殊字符 /
NyaCodeEncode[char] = triplet
NyaCodeDecode = {value: key for key, value in NyaCodeEncode.items()}
async def nya_encrypt(msg: str):
result = ""
b64str = base64.b64encode(msg.encode()).decode().replace("=", "")
nyastr = ""
for b64char in b64str:
nyastr += NyaCodeEncode[b64char]
for char in nyastr:
if char == "" and random.random() < 0.5:
result += "!"
if random.random() < 0.25:
result += random.choice(NyaCodeSpecialCharset) + char
else:
result += char
return result
async def nya_decrypt(msg: str):
msg = msg.replace("", "").replace("!", "").replace(".", "")
nyastr = []
i = 0
if len(msg) % 3 != 0:
return "这句话不是正确的猫语"
while i < len(msg):
nyachar = msg[i : i + 3]
try:
if all(char in NyaCodeCharset for char in nyachar):
nyastr.append(nyachar)
i += 3
except Exception:
return "这句话不是正确的猫语"
b64str = ""
for nyachar in nyastr:
b64str += NyaCodeDecode[nyachar]
b64str += "=" * (4 - len(b64str) % 4)
try:
result = base64.b64decode(b64str.encode()).decode()
except Exception:
return "翻译失败"
return result

View File

@@ -16,3 +16,8 @@ async def generate_random_numbers(count: int) -> str:
# 该插件由MarshoAI自举编写 # 该插件由MarshoAI自举编写
@on_function_call(description="重载测试")
def test_reload():
return 1

View File

@@ -0,0 +1,47 @@
from pathlib import Path
from nonebot import require
require("nonebot_plugin_localstore")
import json
from nonebot_plugin_localstore import get_data_file
memory_path = get_data_file("marshoai", "memory.json")
if not Path(memory_path).exists():
with open(memory_path, "w", encoding="utf-8") as f:
json.dump({}, f, ensure_ascii=False, indent=4)
print(memory_path)
async def write_memory(memory: str, user_id: str):
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
memorys = memory_data.get(user_id, [])
memorys.append(memory)
memory_data[user_id] = memorys
with open(memory_path, "w", encoding="utf-8") as f:
json.dump(memory_data, f, ensure_ascii=False, indent=4)
return "记忆已经保存啦~"
async def read_memory(user_id: str):
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
memorys = memory_data.get(user_id, [])
if not memorys:
return "好像对ta还没有任何记忆呢~"
return "这些是有关ta的记忆" + "\n".join(memorys)
async def organize_memories():
with open(memory_path, "r", encoding="utf-8") as f:
memory_data = json.load(f)
for i in memory_data:
...
# TODO 用大模型对记忆进行整理

View File

@@ -0,0 +1,46 @@
[
{
"type": "function",
"function": {
"name": "marshoai_memory__write_memory",
"description": "如果在上下中你看见并觉得应该记住的人的行为与事件请调用这个函数并将记忆内容写入。请尽量每次都调用总结ta的习惯、爱好和性格,以及你对ta的印象和ta对你的印象",
"parameters": {
"type": "object",
"properties": {
"memory": {
"type": "string",
"description": "你想记住的内容,概括并保留关键内容。"
},
"user_id": {
"type": "string",
"description": "你想记住的人的id。"
}
}
},
"required": [
"memory",
"user_id"
]
}
},
{
"type": "function",
"function": {
"name": "marshoai_memory__read_memory",
"description": "每当你想要获取更多有关某人的信息的时候,请调用这个函数。",
"parameters": {
"type": "object",
"properties": {
"user_id": {
"type": "string",
"description": "你想获取的人的id。"
}
}
},
"required": [
"user_id"
]
}
}
]

View File

@@ -1,2 +0,0 @@
async def write_memory(memory: str):
return ""

View File

@@ -1,21 +0,0 @@
[
{
"type": "function",
"function": {
"name": "marshoai_memory__write_memory",
"description": "当你想记住有关与你对话的人的一些信息的时候,调用此函数。",
"parameters": {
"type": "object",
"properties": {
"memory": {
"type": "string",
"description": "你想记住的内容,概括并保留关键内容。"
}
}
},
"required": [
"memory"
]
}
}
]

View File

@@ -1,15 +1,10 @@
{ {
"type": "module", "type": "module",
"devDependencies": { "devDependencies": {"vitepress": "^1.5.0", "vitepress-sidebar": "^1.30.2"},
"vitepress": "^1.5.0", "scripts": {
"vitepress-sidebar": "^1.30.2" "docs:dev": "vitepress dev docs --host",
}, "docs:build": "vitepress build docs",
"scripts": { "docs:preview": "vitepress preview docs"
"docs:dev": "vitepress dev docs --host", },
"docs:build": "vitepress build docs", "dependencies": {"vue": "^3.5.13"}
"docs:preview": "vitepress preview docs" }
},
"dependencies": {
"vue": "^3.5.13"
}
}

View File

@@ -9,10 +9,9 @@ authors = [
{ name="LiteyukiStudio", email = "support@liteyuki.icu"} { name="LiteyukiStudio", email = "support@liteyuki.icu"}
] ]
dependencies = [ dependencies = [
"nonebot2>=2.2.0", "nonebot2>=2.4.0",
"nonebot-plugin-alconna>=0.48.0", "nonebot-plugin-alconna>=0.48.0",
"nonebot-plugin-localstore>=0.7.1", "nonebot-plugin-localstore>=0.7.1",
"azure-ai-inference>=1.0.0b4",
"zhDatetime>=1.1.1", "zhDatetime>=1.1.1",
"aiohttp>=3.9", "aiohttp>=3.9",
"httpx>=0.27.0", "httpx>=0.27.0",
@@ -24,7 +23,10 @@ dependencies = [
"litedoc>=0.1.0.dev20241214103915", "litedoc>=0.1.0.dev20241214103915",
"newspaper3k>=0.2.8", "newspaper3k>=0.2.8",
"lxml[html_clean]>=5.3.0", "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" } license = { text = "MIT, Mulan PSL v2" }
@@ -51,6 +53,7 @@ profile = "black"
source = "scm" source = "scm"
tag_filter = "v*" 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]*))?$)$' 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] [tool.pdm.build]
includes = [] includes = []
@@ -73,3 +76,6 @@ dev = [
test = [ test = [
"nonebug>=0.4.3", "nonebug>=0.4.3",
] ]
[tool.ruff.lint]
ignore = ["E402"]