From fb10d4dc6d5649d9b6adfd6546e88a31652bfbb3 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Wed, 20 Mar 2024 16:36:45 +0800 Subject: [PATCH 1/7] =?UTF-8?q?doc:=20=E6=B7=BB=E5=8A=A0=E5=85=83=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/.vuepress/sidebar.ts | 31 +++++++++++--- src/posts/config/sensitive-words.md | 15 ------- src/posts/metadata/README.md | 14 +++++++ src/posts/metadata/adapter-qq-botpy.md | 33 +++++++++++++++ src/posts/metadata/llm-models.md | 57 ++++++++++++++++++++++++++ src/posts/metadata/sensitive-words.md | 15 +++++++ 6 files changed, 144 insertions(+), 21 deletions(-) delete mode 100644 src/posts/config/sensitive-words.md create mode 100644 src/posts/metadata/README.md create mode 100644 src/posts/metadata/adapter-qq-botpy.md create mode 100644 src/posts/metadata/llm-models.md create mode 100644 src/posts/metadata/sensitive-words.md diff --git a/src/.vuepress/sidebar.ts b/src/.vuepress/sidebar.ts index af26b16b7..e6c4551b0 100644 --- a/src/.vuepress/sidebar.ts +++ b/src/.vuepress/sidebar.ts @@ -84,7 +84,7 @@ export default sidebar({ }, { text: "配置详解", - icon: "context", + icon: "config", collapsible: true, prefix: "posts/config/", link: "posts/config/", @@ -109,11 +109,6 @@ export default sidebar({ icon: "config", link: "command" }, - { - text: "sensitive-words.json", - icon: "config", - link: "sensitive-words" - }, { text: "system.json", icon: "config", @@ -121,6 +116,30 @@ export default sidebar({ }, ] }, + { + text: "元数据配置", + icon: "enum", + collapsible: true, + prefix: "posts/metadata/", + link: "posts/metadata/", + children: [ + { + text: "敏感词 sensitive-words.json", + icon: "enum", + link: "sensitive-words" + }, + { + text: "模型列表 llm-models.json", + icon: "enum", + link: "llm-models" + }, + { + text: "qq-botpy ID 映射 adapter-qq-botpy.json", + icon: "enum", + link: "adapter-qq-botpy" + } + ] + }, { text: "常见问题", icon: "info", diff --git a/src/posts/config/sensitive-words.md b/src/posts/config/sensitive-words.md deleted file mode 100644 index 7b0d5cb0c..000000000 --- a/src/posts/config/sensitive-words.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -head: - - - meta - - name: keywords - content: sensitive-words.json 配置文件 -title: sensitive-words.json 配置项 -icon: config -order: 5 -author: RockChinQ -date: 2024-02-18 -category: - - 配置文件 ---- - -本地敏感词词库,参考 `data/config/sensitive-words.json` 内容进行修改即可。 \ No newline at end of file diff --git a/src/posts/metadata/README.md b/src/posts/metadata/README.md new file mode 100644 index 000000000..2aec922e1 --- /dev/null +++ b/src/posts/metadata/README.md @@ -0,0 +1,14 @@ +--- +head: + - - meta + - name: keywords + content: ChatGPT QQ机器人教程,QChatGPT项目部署教程 +title: 元数据配置详解 +icon: config +author: RockChinQ +date: 2024-03-20 +index: false +--- + +元数据配置是程序运行期间生成的,用于描述某些数据的数据文件,比如:大语言模型数据、敏感词库、QQ 官方 API 的 ID 映射关系等,这些数据相比于配置文件较为复杂,一般不需要用户手动修改。 +元数据文件均位于 `data/metadata/` 目录下,请点击左侧目录查看各个文件的详细配置项。 \ No newline at end of file diff --git a/src/posts/metadata/adapter-qq-botpy.md b/src/posts/metadata/adapter-qq-botpy.md new file mode 100644 index 000000000..3eb5bf7a6 --- /dev/null +++ b/src/posts/metadata/adapter-qq-botpy.md @@ -0,0 +1,33 @@ +--- +head: + - - meta + - name: keywords + content: adapter-qq-botpy.json 元数据 +title: adapter-qq-botpy.json 元数据 +icon: config +order: 3 +author: RockChinQ +date: 2024-03-20 +category: + - 配置文件 +--- + +`data/metadata/adapter-qq-botpy.json`,QQ 官方 API 适配器元数据。官方 API 在使用群聊接口时,群id和成员id为字符串,而 QChatGPT 内部只支持整型 id,为使重启后仍然是相同的对应关系,因此需要保存到一个文件中。 + +## 格式 + +```json +{ + "mapping": { + "groups": { + "15944D6D2B525C6E3536134D4669F067": 443241151434655 + }, + "members": { + "547A6244A731B4BEEBE5EE2AE4CD00A8": 232437565267568 + } + } +} +``` + +- `groups`: 群id映射关系,key为字符串群id,value为整型群id。 +- `members`: 成员id映射关系,key为字符串成员id,value为整型成员id。 diff --git a/src/posts/metadata/llm-models.md b/src/posts/metadata/llm-models.md new file mode 100644 index 000000000..300c403f8 --- /dev/null +++ b/src/posts/metadata/llm-models.md @@ -0,0 +1,57 @@ +--- +head: + - - meta + - name: keywords + content: llm-models.json 元数据 +title: llm-models.json 元数据 +icon: config +order: 2 +author: RockChinQ +date: 2024-03-20 +category: + - 配置文件 +--- + +`data/metadata/llm-models.json`,受支持的大语言模型列表,本文件中指定了可用于 `data/config/provider.json` 中的 `model` 列表,指定每个模型对应的 `Key 管理器` 和 `API 请求器`。 + +## 格式 + +```json +{ + "list": [ + { + "name": "default", + "requester": "openai-chat-completions", + "token_mgr": "openai", + "tool_call_supported": false + }, + { + "name": "gpt-3.5-turbo", + "tool_call_supported": true + } + ] +} +``` + +模型均列于`list`数组中,每个模型的字段如下: + +- `name`: 模型名称,用于在 `data/config/provider.json` 中的 `model` 列表中指定。 +- `model_name`: 进行请求时使用的模型名称,用于区分使用不同请求器的相同模型,若未设置则使用 `name` 字段。 +- `requester`: 请求器名称,指定使用哪个请求器请求该模型的响应,不同的请求器对应不同的 API,当前支持的模型,可以在 `data/config/provider.json` 中的 `requester` 列表中找到。 +- `token_mgr`: Key 管理器,此模型使用的 key 组,对应 `data/config/provider.json` 中的 `keys` 列表。 +- `tool_call_supported`: 是否支持工具调用,标记此模型是否支持使用`内容函数`。 + +`default` 模型是必须的,这是模型的默认配置,其他模型可以不设置所有的字段,只需设置 `name` 字段即可,其他字段会继承 `default` 模型的配置。 + +## 自动更新机制 + +每次启动时,程序会自动从中央服务器获取最新的模型列表,相同的模型名称会被下载的新配置覆盖。 + +## 自定义模型 + +根据上述格式添加即可。 + +- 如果需要使用目前不支持的接口(请求器),需要自己扩展请求器,请参考插件开发文档。 +- key 组可以自己在 `data/config/provider.json` 中的 `keys` 列表中添加。 +- 修改模型配置一般是没有必要的,每次启动时下载的模型列表会覆盖本地的相同模型名称的配置。 + diff --git a/src/posts/metadata/sensitive-words.md b/src/posts/metadata/sensitive-words.md new file mode 100644 index 000000000..6a9d82ea3 --- /dev/null +++ b/src/posts/metadata/sensitive-words.md @@ -0,0 +1,15 @@ +--- +head: + - - meta + - name: keywords + content: sensitive-words.json 元数据 +title: sensitive-words.json 元数据 +icon: config +order: 1 +author: RockChinQ +date: 2024-02-18 +category: + - 配置文件 +--- + +本地敏感词词库,参考 `data/metadata/sensitive-words.json` 内容进行修改即可。 \ No newline at end of file From 1a6c02da411be76efdd46aa22a530d3e4ac6ec28 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Wed, 20 Mar 2024 16:52:43 +0800 Subject: [PATCH 2/7] =?UTF-8?q?doc:=20=E6=9B=B4=E6=96=B0=20provider.json?= =?UTF-8?q?=20=E7=9A=84=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/posts/config-intro.md | 76 ------------------------------------ src/posts/config/provider.md | 64 +++++++++++++++++++++++------- src/posts/deploy/config.md | 34 ++-------------- 3 files changed, 53 insertions(+), 121 deletions(-) delete mode 100644 src/posts/config-intro.md diff --git a/src/posts/config-intro.md b/src/posts/config-intro.md deleted file mode 100644 index 59cc6317d..000000000 --- a/src/posts/config-intro.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: QChatGPT的详细配置解读 -icon: context -# 这是侧边栏的顺序 -order: 4 -# 设置作者 -author: Lazy -# 设置写作时间 -date: 2024-02-13 -category: - - 使用指南 -tag: - - 配置方法 - - 使用指南 ---- - - -:::info 目录 -[[toc]] -::: - -## 配置文件 - -### 配置文件是什么? - -当你下载好本项目后,会发现有一个`templates`文件夹,内部存放的就是即将生成的配置文件的模板 - -配置文件有以下这些: - -- `command.json`:用于存放有关QChatGPT项目命令的 -- `pipeline.json`:QChatGPT 3.0新引入的概念,平台适配器获取到消息事件之后,发送给pipeline排队进行处理 -- `platform.json`:与消息平台有关的配置 -- `plugin-settings.json`:用于配置插件 -- `provider.json`:控制AI功能,设置与OpenAI交互的参数,key,模型,反代地址,简单的人格预设等 -- `scenario-template.json`:配置人格预设的模板,实现更高级的人格预设 -- `sensitive-words.json`:设置敏感词,防止出现不当言论 -- `system.json`:设置一些系统信息,如管理员,代理,日志管理,并发数,持续渠道提示信息 - -以下是对各个配置文件的详细解读 - - -## plugin-settings.json - -这个文件会被复制到`plugins/`目录下 - -以前插件设置分为 metadata.json switch.json settions.json - -现在统一到这里管理 - -每次启动时,会同步这里的设置和实际加载的插件设置 - -**这个文件内容是由程序自动生成的,不要手动添加或删除项目,仅可修改优先级和启用状态** - -示例: - -```json -"plugins": [ - { - "name": "Nahida", - "description": "Hello Nahida", - "version": "0.1", - "author": "RockChinQ", - "source": "", - "main_file": "plugins/Nahida/main.py", - "pkg_path": "plugins/Nahida/", - "priority": 0, - "enabled": true - } -] -``` - -`source`:源码地址,若无内容,则表示这个插件不支持程序自动更新 - -`priority`: 插件运行优先级,在初始化、事件调用时,高优先级的插件将优先被处理 - -`enabled`:设置为false时,不会初始化,也不会被调用 diff --git a/src/posts/config/provider.md b/src/posts/config/provider.md index 223a4f22e..31c8f2f26 100644 --- a/src/posts/config/provider.md +++ b/src/posts/config/provider.md @@ -27,34 +27,70 @@ category: `enable-chat`:是否开启AI聊天功能 -## OpenAI 接口配置 openai-config +## 模型接口密钥 keys ```json -"openai-config": { - "api-keys": [ +"keys": { + "openai": [ "sk-1234567890" ], - "base_url": "https://api.openai.com/v1", - "chat-completions-params": { - "model": "gpt-3.5-turbo" - }, - "request-timeout": 120 + "anthropic": [ + "sk-1234567890" + ], + "moonshot": [ + "sk-1234567890" + ] }, ``` -`api-keys`:以列表的形式设置若干个api key +`keys`:设置密钥组,以字典的形式设置若干个密钥组,每个密钥组的键为密钥组名称,值为密钥列表。模型与密钥组的对应关系,请查看元数据板块。 -`base_url`:设置接口地址,后面一定要加`/v1` +## 大模型请求器 requester -`model`:填写要使用的模型名称。通常来说直接填写模型名称即可,但如果要使用原生接口不是 ChatCompletion 但以 ChatCompletion 接口格式接入的模型,请在模型名称前方加一个 `OneAPI/` 前缀以进行区分。 -简单来说可以认为是:现阶段非 OpenAI 的模型接入都需要在模型名称前方加一个 `OneAPI/` 前缀。 +```json +"requester": { + "openai-chat-completions": { + "base-url": "https://api.openai.com/v1", + "args": {}, + "timeout": 120 + }, + "anthropic-messages": { + "base-url": "https://api.anthropic.com", + "args": { + "max_tokens": 1024 + }, + "timeout": 120 + }, + "moonshot-chat-completions": { + "base-url": "https://api.moonshot.cn/v1", + "args": {}, + "timeout": 120 + } + }, +``` + +`requester`:设置请求器,以字典的形式设置若干个请求器,每个请求器的键为请求器名称,值为请求器配置。模型与请求器的对应关系,请查看元数据板块。实现请求器的方式,请查看插件编写教程。 + +`base-url`:设置接口地址。 + +`args`:请求时除了model之外的其他参数,以字典的形式设置。 + +`timeout`:设置请求超时时间,以秒为单位,对于耗时较长的模型,建议设置较大值 + +## 使用的模型 model + +```json +"model": "gpt-3.5-turbo", +``` + +`model`:设置要使用的模型名称。通常来说直接填写模型名称即可,但如果要使用原生接口不是 ChatCompletion 但以 ChatCompletion 接口格式接入的模型,请在模型名称前方加一个 `OneAPI/` 前缀以进行区分。 +简单来说可以认为是:现阶段非 OpenAI 的模型接入都需要在模型名称前方加一个 `OneAPI/` 前缀。 例如: 1. 通过 OneAPI 等中转服务接入了 OpenAI 的 `gpt-4` 模型,由于 `gpt-4` 也是使用 ChatCompletion 接口格式进行请求,则可以直接填入 `gpt-4`; 2. 通过 OneAPI 等中转服务接入了 Google 的 `gemini-pro` 模型,由于 `gemini-pro` 原生接口格式并非 ChatCompletion,因此需要填入 `OneAPI/gemini-pro`。 - -`request-timeout`:设置请求超时时间,以秒为单位,对于耗时较长的模型,建议设置较大值 +具体支持的模型列表和各个模型对应的请求器和密钥组,请查看元数据板块。 ## 情景预设(人格) prompt diff --git a/src/posts/deploy/config.md b/src/posts/deploy/config.md index 310c4d7f4..6083a1e44 100644 --- a/src/posts/deploy/config.md +++ b/src/posts/deploy/config.md @@ -128,36 +128,8 @@ date: 2024-02-18 修改此配置文件以设置所连接的 AI 提供商的相关信息,仅讲解必要的配置项,更多的配置项详解请查看[配置详解](../config/)。 -```json -"openai-config": { - "api-keys": [ - "sk-1234567890" - ], - "base_url": "https://api.openai.com/v1", - "chat-completions-params": { - "model": "gpt-3.5-turbo" - }, - "request-timeout": 120 -}, -``` +需要修改 `keys`, `requester`, `model` 字段,目前支持 `openai(GPT)`, `anthropic(claude)`, `moonshot(月之暗面)` 三种接口及对应模型。 -`api-keys`:支持以列表的形式设置若干个api key,例如: +例如需要使用 OpenAI 的模型,则 将 OpenAI 的 api key 填写到 `keys.openai` 下,支持多个key。并修改 `model` 为需要使用的模型名称。若您使用了中转站,或者需要使用反向代理,则设置 `requester.openai-chat-completions` 下的 `base-url` 配置。 -```json -"api-keys": [ - "sk-1234567890", - "sk-23452354253", - "sk-2352453674" -], -``` - -`base_url`:设置接口地址,如果你从第三方购买了key,或者需要使用反向代理时才需要修改这个参数,后面一定要加`/v1` - -`model`:填写要使用的模型名称。通常来说直接填写模型名称即可,但如果要使用原生接口不是 ChatCompletion 但以 ChatCompletion 接口格式接入的模型,请在模型名称前方加一个 `OneAPI/` 前缀以进行区分。 -简单来说可以认为是:现阶段非 OpenAI 的模型接入都需要在模型名称前方加一个 `OneAPI/` 前缀。 - -例如: -1. 通过 OneAPI 等中转服务接入了 OpenAI 的 `gpt-4` 模型,由于 `gpt-4` 也是使用 ChatCompletion 接口格式进行请求,则可以直接填入 `gpt-4`; -2. 通过 OneAPI 等中转服务接入了 Google 的 `gemini-pro` 模型,由于 `gemini-pro` 原生接口格式并非 ChatCompletion,因此需要填入 `OneAPI/gemini-pro`。 - -`request-timeout`:设置请求超时时间,以秒为单位,对于耗时较长的模型(如GPT4),建议设置较大值 \ No newline at end of file +具体设置方法请查看 配置详解模块的`provider.json` 页。 \ No newline at end of file From aeb8fdae6dd4d34d8883ed47c36230650382f1f6 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Wed, 20 Mar 2024 23:27:35 +0800 Subject: [PATCH 3/7] =?UTF-8?q?doc:=20=E6=9B=B4=E6=96=B0=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E5=BC=80=E5=8F=91=E6=95=99=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/posts/plugin/develop.md | 369 +++++------------------------------- src/posts/plugin/intro.md | 4 +- 2 files changed, 54 insertions(+), 319 deletions(-) diff --git a/src/posts/plugin/develop.md b/src/posts/plugin/develop.md index 6604f64fc..9cd13dfaf 100644 --- a/src/posts/plugin/develop.md +++ b/src/posts/plugin/develop.md @@ -13,12 +13,7 @@ category: index: false --- -:::warning -本教程基于 QChatGPT 2.x 编写,3.0 具有不全面的向后兼容性,请尽可能使用本教程内推荐的方法进行开发。 -::: - > 请先阅读[插件介绍页](../plugin/intro.md) -> 请先阅读[技术信息页](../develop/technology-info.md) > 建议先阅读本项目源码,了解项目架构 > 问题、需求请到仓库issue发起 @@ -30,28 +25,24 @@ index: false ## 💬简介 -尽管“为一个基于OpenAI API的QQ机器人开发插件支持”这事看起来有点小题大做,但萌生此想法后的几天内好几个人提出了这个需求,最终促使此项目正式支持插件。 +本页讲解普通插件开发步骤,插件内部有两种方法:事件监听器、内容函数。 +事件监听器能在某些事件触发时进行响应,更改行为。内容函数可供大语言模型调用,具体请查看插件介绍页。 -## 🧱实现 - -基于`importlib`库加载模块的方法动态加载额外Python程序文件以便实现插件加载,插件均存放在`plugins`文件夹,其中的所有`.py`文件都将被加载(除了所有`__init__.py`) - -## 📚示例代码 - -请查看代码目录`tests/plugin_examples`中的插件目录 +QChatGPT 还支持组件扩展,可以不局限于监听预定事件,做到整个组件替换,具体请阅读完此页后查看**组件扩展**页。 ## 💻快速开始 按照文档部署此项目,并使其正常运行。 在`plugins`目录下新建目录`hello`,在其中新建空文件`__init__.py`以标记此目录为软件包,继续新建文件`main.py`。 -> 您也可以使用[hello_plugin](https://github.com/RockChinQ/hello_plugin)作为模板直接生成插件代码仓库 +> 建议使用[hello_plugin](https://github.com/RockChinQ/hello_plugin)作为模板直接生成插件代码仓库后按照下方步骤进行修改。 编辑`main.py`输入以下内容: ```Python -from pkg.plugin.models import * -from pkg.plugin.host import EventContext, PluginHost +from pkg.plugin.context import register, handler, llm_func, BasePlugin, APIHost, EventContext +from pkg.plugin.events import * # 导入事件类 + """ 在收到私聊或群聊消息"hello"时,回复"hello, <发送者id>!"或"hello, everyone!" @@ -60,42 +51,45 @@ from pkg.plugin.host import EventContext, PluginHost # 注册插件 @register(name="Hello", description="hello world", version="0.1", author="RockChinQ") -class HelloPlugin(Plugin): +class HelloPlugin(BasePlugin): # 插件加载时触发 - # plugin_host (pkg.plugin.host.PluginHost) 提供了与主程序交互的一些方法,详细请查看其源码 - def __init__(self, plugin_host: PluginHost): + def __init__(self, host: APIHost): + pass + + # 异步初始化 + async def initialize(self): pass # 当收到个人消息时触发 - @on(PersonNormalMessageReceived) - def person_normal_message_received(self, event: EventContext, **kwargs): - msg = kwargs['text_message'] + @handler(PersonNormalMessageReceived) + async def person_normal_message_received(self, ctx: EventContext): + msg = ctx.event.text_message # 这里的 event 即为 PersonNormalMessageReceived 的对象 if msg == "hello": # 如果消息为hello # 输出调试信息 - logging.debug("hello, {}".format(kwargs['sender_id'])) + self.ap.logger.debug("hello, {}".format(ctx.event.sender_id)) # 回复消息 "hello, <发送者id>!" - event.add_return("reply", ["hello, {}!".format(kwargs['sender_id'])]) + ctx.add_return("reply", ["hello, {}!".format(ctx.event.sender_id)]) # 阻止该事件默认行为(向接口获取回复) - event.prevent_default() + ctx.prevent_default() # 当收到群消息时触发 - @on(GroupNormalMessageReceived) - def group_normal_message_received(self, event: EventContext, **kwargs): - msg = kwargs['text_message'] + @handler(GroupNormalMessageReceived) + async def group_normal_message_received(self, ctx: EventContext): + msg = ctx.event.text_message # 这里的 event 即为 GroupNormalMessageReceived 的对象 if msg == "hello": # 如果消息为hello # 输出调试信息 - logging.debug("hello, {}".format(kwargs['sender_id'])) + self.ap.logger.debug("hello, {}".format(ctx.event.sender_id)) # 回复消息 "hello, everyone!" - event.add_return("reply", ["hello, everyone!"]) + ctx.add_return("reply", ["hello, everyone!"]) # 阻止该事件默认行为(向接口获取回复) - event.prevent_default() + ctx.prevent_default() # 插件卸载时触发 def __del__(self): @@ -107,25 +101,20 @@ class HelloPlugin(Plugin): ### 解读此插件程序 -- `import`从`pkg.plugin`引入`models`模块的所有字段(此程序使用了其中的`register函数`、`on函数`、`Plugin类`、`PersonNormalMessageReceived事件`、`GroupNormalMessageReceived事件`) -- `@register()`将类`HelloPlugin`标记为一个插件类,声明插件名称为`Hello`以及插件简介、版本、作者 -- 声明类`HelloPlugin`继承于`Plugin`,此类可以随意命名,插件名称只与`register`调用时的参数有关 +- `import pkg.plugin.context`导入`register(用于注册插件类)`, `handler(用于注册事件监听器)`, `llm_func(用于注册内容函数)`,`BasePlugin(插件基类)`, `APIHost(API宿主)`, `EventContext(事件上下文类)`等内容 +- `import pkg.plugin.events`导入所有支持的事件类 +- `@register`将类`HelloPlugin`标记为一个插件类,声明插件名称为`Hello`以及插件简介、版本、作者 +- 声明类`HelloPlugin`继承于`BasePlugin`,此类可以随意命名,插件名称只与`register`调用时的参数有关 - 声明此类的`__init__`方法,此方法是可选的,其中的代码将在主程序启动时加载插件的时候被执行 -- `@on`将方法`person_normal_message_received`标记为一个事件处理器,处理`PersonNormalMessageReceived`(收到私聊消息并在获取OpenAI回复前触发)事件,此方法可以随意命名,绑定的事件只与`on`中的参数有关,更多支持的事件可到`pkg.plugin.models.py`文件中查看或查看下方`API`节 -- 输出调试信息,程序中可通过`logging`将日志输出到控制台和`qchatgpt.log`文件 -- 方法内部从参数中取出`text_message`参数,判断是否为`hello`,如果是就将返回值`reply`设置为`["hello, {}!".format(kwargs['sender_id'])]`,接下来调用`event`对象的`prevent_default`方法,阻止原程序默认行为 - - 每个事件`提供的参数`和`支持的返回值`请查看`pkg.plugin.models`中的每个事件的注释或查看下方`API`节 - - `event`对象提供的方法请查看`pkg.plugin.host`中的`EventContext`类或查看下方`API`节 +- 插件类中还支持添加一个异步方法`async def initialize(self)`用于异步初始化 +- `@handler`将方法`person_normal_message_received`标记为一个事件监听器,处理`PersonNormalMessageReceived`(收到私聊消息并在获取OpenAI回复前触发)事件,此方法可以随意命名,绑定的事件只与`handler`中的参数有关,更多支持的事件可到`pkg.plugin.events`文件中查看或查看下方`API`节 +- 通过`self.ap.logger`日志器输出调试信息,插件类父类中的`ap`对象是整个程序的上下文对象,可以通过这个对象访问程序内所有对象 +- 事件监听器方法获得的第二个参数`ctx`即为本次事件的上下文,其中的`event`为本次事件的事件对象,可以从中取出相关参数,具体事件可以取得的参数请查看`pkg.plugin.events`文件中的每个事件类的注释 +- 事件监听器方法内部从参数中取出`text_message`参数,判断是否为`hello`,如果是就将返回值`reply`设置为`["hello, {}!".format(ctx.event.sender_id)]`,接下来调用`ctx.prevent_default()`方法,阻止原程序默认行为 + - 每个事件支持的返回值请查看`pkg.plugin.events`中的每个事件的注释 - 用相似的程序注册`GroupNormalMessageReceived`事件处理群消息 -编写完毕保存后,重新启动主程序,查看到输出中包含以下内容,即为加载成功: - -``` -[2023-01-16 18:29:47.193] host.py (43) - [INFO] : 加载模块: hello.main -[2023-01-16 18:29:47.194] models.py (209) - [INFO] : 插件注册完成: n='Hello', d='hello world', v=0.1, a='RockChinQ' () -``` - -> 建议在`config.py`中设置`logging_level = logging.DEBUG`以便开启调试输出 +编写完毕保存后,重新启动主程序,向机器人发送`!plugin`命令,若有`Hello`插件则说明插件加载成功 ## ❗规范(重要) @@ -140,46 +129,21 @@ class HelloPlugin(Plugin): > 您的插件不一定必须包含内容函数,请先查看内容函数页了解此功能 -
-示例:联网插件 - -加载含有联网功能的内容函数的插件[WebwlkrPlugin](https://github.com/RockChinQ/WebwlkrPlugin),向机器人询问在线内容 - -``` -# 控制台输出 -[2023-07-29 17:37:18.698] message.py (26) - [INFO] : [person_1010553892]发送消息:介绍一下这个项目:https://git... -[2023-07-29 17:37:21.292] util.py (67) - [INFO] : message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=1902 request_id=941afc13b2e1bba1e7877b92a970cdea response_code=200 -[2023-07-29 17:37:21.293] chat_completion.py (159) - [INFO] : 执行函数调用: name=Webwlkr-access_the_web, arguments={'url': 'https://github.com/RockChinQ/QChatGPT', 'brief_len': 512} -[2023-07-29 17:37:21.848] chat_completion.py (164) - [INFO] : 函数执行完成。 -``` - -![Webwlkr插件](https://github.com/RockChinQ/QChatGPT/blob/master/res/screenshots/webwlkr_plugin.png?raw=true) - -
- ### 内容函数编写步骤 -1️⃣ 请先按照上方步骤编写您的插件基础结构,现在请删除(当然你也可以不删,只是为了简洁)上述插件内容的诸个由`@on`装饰的类函数 +1️⃣ 请先按照上方步骤编写您的插件基础结构,现在请删除(当然你也可以不删,只是为了简洁)上述插件内容的诸个由`@handler`装饰的类函数
-删除后的结构 +删除后的类结构 ```python -from pkg.plugin.models import * -from pkg.plugin.host import EventContext, PluginHost - -""" -在收到私聊或群聊消息"hello"时,回复"hello, <发送者id>!"或"hello, everyone!" -""" - # 注册插件 @register(name="Hello", description="hello world", version="0.1", author="RockChinQ") class HelloPlugin(Plugin): # 插件加载时触发 - # plugin_host (pkg.plugin.host.PluginHost) 提供了与主程序交互的一些方法,详细请查看其源码 - def __init__(self, plugin_host: PluginHost): + def __init__(self, plugin_host: APIHost): pass # 插件卸载时触发 @@ -189,14 +153,13 @@ class HelloPlugin(Plugin):
-2️⃣ 现在我们将以下函数添加到刚刚删除的函数的位置 +2️⃣ 现在我们将以下函数添加到刚刚删除的函数的位置(作为类方法) ```Python # 要添加的函数 - -@func(name="access_the_web") # 设置函数名称 -def _(url: str): +@llm_fun(name="access_the_web") # 设置函数名称 +async def access_web(self, query, url: str): """Call this function to search about the question before you answer any questions. - Do not search through baidu.com at any time. - If you need to search somthing, visit https://www.google.com/search?q=xxx. @@ -235,264 +198,36 @@ def _(url: str): return s ``` -
-现在这个文件内容应该是这样 - -```python -from pkg.plugin.models import * -from pkg.plugin.host import EventContext, PluginHost - -""" -在收到私聊或群聊消息"hello"时,回复"hello, <发送者id>!"或"hello, everyone!" -""" - - -# 注册插件 -@register(name="Hello", description="hello world", version="0.1", author="RockChinQ") -class HelloPlugin(Plugin): - - # 插件加载时触发 - # plugin_host (pkg.plugin.host.PluginHost) 提供了与主程序交互的一些方法,详细请查看其源码 - def __init__(self, plugin_host: PluginHost): - pass - - @func(name="access_the_web") - def _(url: str): - """Call this function to search about the question before you answer any questions. - - Do not search through baidu.com at any time. - - If you need to search somthing, visit https://www.google.com/search?q=xxx. - - If user ask you to open a url (start with http:// or https://), visit it directly. - - Summary the plain content result by yourself, DO NOT directly output anything in the result you got. - - Args: - url(str): url to visit - - Returns: - str: plain text content of the web page - """ - import requests - from bs4 import BeautifulSoup - # 你需要先使用 - # pip install beautifulsoup4 - # 安装依赖 - - r = requests.get( - url, - timeout=10, - headers={ - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.183" - } - ) - soup = BeautifulSoup(r.text, 'html.parser') - - s = soup.get_text() - - # 删除多余的空行或仅有\t和空格的行 - s = re.sub(r'\n\s*\n', '\n', s) - - if len(s) >= 512: # 截取获取到的网页纯文本内容的前512个字 - return s[:512] - - return s - - # 插件卸载时触发 - def __del__(self): - pass -``` - -
#### 请注意: - 函数的注释必须严格按照要求的格式进行书写,具体格式请查看[此文档](https://github.com/RockChinQ/CallingGPT/wiki/1.-Function-Format#function-format) -- 内容函数和`以@on装饰的行为函数`可以同时存在于同一个插件,并同时受到`switch.json`中的插件开关的控制 -- 务必确保您使用的模型支持函数调用功能,可以到`config.py`的`completion_api_params`中修改模型,推荐使用`gpt-3.5-turbo-16k` +- 内容函数和`以@llm_func装饰的行为函数`可以同时存在于同一个插件,并同时受到`plugins/plugins.json`中的插件开关的控制 +- 务必确保您使用的模型支持函数调用功能 3️⃣ 现在您的程序已具备网络访问功能,重启程序,询问机器人有关在线的内容或直接发送文章链接请求其总结。 - 这仅仅是一个示例,需要更高效的网络访问能力支持插件,请查看[WebwlkrPlugin](https://github.com/RockChinQ/WebwlkrPlugin) -## 🔒版本要求 - -若您的插件对主程序的版本有要求,可以使用以下函数进行断言,若不符合版本,此函数将报错并打断此函数所在的流程: - -```python -require_ver("v2.5.1") # 要求最低版本为 v2.5.1 -``` - -```python -require_ver("v2.5.1", "v2.6.0") # 要求最低版本为 v2.5.1, 同时要求最高版本为 v2.6.0 -``` - -- 此函数在主程序`v2.5.1`中加入 -- 此函数声明在`pkg.plugin.models`模块中,在插件示例代码最前方已引入此模块所有内容,故可直接使用 - ## 📄API参考 ### 说明 -事件处理函数将会获得一系列参数,可以在`kwargs`中取出。 -其中`host`参数(`pkg.plugin.host.PluginHost`类的实例)是插件宿主,提供与主程序各个模块交互的一些方法。 -`event`参数(`pkg.plugin.host.EventContext`类的实例)是事件执行期间的上下文,提供对此次事件执行的一些操作方法。 - +事件监听器方法获得的`ctx: EventContext`对象可以到`pkg.plugin.context`模块中查看其结构,`ctx`对象的`event`属性为本次事件的事件对象,可以从中取出相关参数,具体事件可以取得的参数请查看`pkg.plugin.events`文件中的每个事件类的注释。 事件返回值均为**可选**的,可以通过调用`event.add_return(key: str, ret)`来提交返回值 ### 事件 -所有事件参数均有`host`和`event`,以下仅展示其他参数 +若一个事件是一次请求(用户发送消息)中的事件,其事件对象中会含有`query`对象,这个对象中包含了此次请求(即用户发送一条消息的处理过程,一个请求过程可能会触发多个事件)处理过程中的数据。 +所有支持的事件,请查看`pkg.plugin.events`文件中的每个事件类的注释。 关于`YiriMirai`支持的消息链组件,请查看 [YiriMirai的文档](https://yiri-mirai.wybxc.cc/docs/basic/message-chain) -```Python -PersonMessageReceived = "person_message_received" -"""收到私聊消息时,在判断是否应该响应前触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - message_chain: mirai.models.message.MessageChain 消息链 -""" +### BasePlugin 结构 -GroupMessageReceived = "group_message_received" -"""收到群聊消息时,在判断是否应该响应前触发(所有群消息) - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - message_chain: mirai.models.message.MessageChain 消息链 -""" +#### self.ap -PersonNormalMessageReceived = "person_normal_message_received" -"""判断为应该处理的私聊普通消息时触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - text_message: str 消息文本 - - returns (optional): - alter: str 修改后的消息文本 - reply: list 回复消息组件列表,元素为YiriMirai支持的消息组件 -""" +在插件的方法中访问`self.ap`即为`pkg.core.app.Application`类的对象,包含了整个程序的上下文对象,可以通过这个对象访问程序内所有对象。 -PersonCommandSent = "person_command_sent" -"""判断为应该处理的私聊命令时触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - command: str 命令 - params: list[str] 参数列表 - text_message: str 完整命令文本 - is_admin: bool 是否为管理员 - - returns (optional): - alter: str 修改后的完整命令文本 - reply: list 回复消息组件列表,元素为YiriMirai支持的消息组件 -""" - -GroupNormalMessageReceived = "group_normal_message_received" -"""判断为应该处理的群聊普通消息时触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - text_message: str 消息文本 - - returns (optional): - alter: str 修改后的消息文本 - reply: list 回复消息组件列表,元素为YiriMirai支持的消息组件 -""" - -GroupCommandSent = "group_command_sent" -"""判断为应该处理的群聊命令时触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - command: str 命令 - params: list[str] 参数列表 - text_message: str 完整命令文本 - is_admin: bool 是否为管理员 - - returns (optional): - alter: str 修改后的完整命令文本 - reply: list 回复消息组件列表,元素为YiriMirai支持的消息组件 -""" - -NormalMessageResponded = "normal_message_responded" -"""获取到对普通消息的文字响应时触发 - kwargs: - launcher_type: str 发起对象类型(group/person) - launcher_id: int 发起对象ID(群号/QQ号) - sender_id: int 发送者ID(QQ号) - session: pkg.openai.session.Session 会话对象 - prefix: str 回复文字消息的前缀 - response_text: str 响应文本 - finish_reason: str 响应结束原因 - - returns (optional): - prefix: str 修改后的回复文字消息的前缀 - reply: list 替换回复消息组件列表 -""" - -SessionFirstMessageReceived = "session_first_message_received" -"""会话被第一次交互时触发 - kwargs: - session_name: str 会话名称(_) - session: pkg.openai.session.Session 会话对象 - default_prompt: str 预设值 -""" - -SessionExplicitReset = "session_reset" -"""会话被用户手动重置时触发,此事件不支持阻止默认行为 - kwargs: - session_name: str 会话名称(_) - session: pkg.openai.session.Session 会话对象 -""" - -SessionExpired = "session_expired" -"""会话过期时触发 - kwargs: - session_name: str 会话名称(_) - session: pkg.openai.session.Session 会话对象 - session_expire_time: int 已设置的会话过期时间(秒) -""" - -KeyExceeded = "key_exceeded" -"""api-key超额时触发 - kwargs: - key_name: str 超额的api-key名称 - usage: dict 超额的api-key使用情况 - exceeded_keys: list[str] 超额的api-key列表 -""" - -KeySwitched = "key_switched" -"""api-key超额切换成功时触发,此事件不支持阻止默认行为 - kwargs: - key_name: str 切换成功的api-key名称 - key_list: list[str] api-key列表 -""" - -PromptPreProcessing = "prompt_pre_processing" # 于v2.5.1加入 -"""每回合调用接口前对prompt进行预处理时触发,此事件不支持阻止默认行为 - kwargs: - session_name: str 会话名称(_) - default_prompt: list 此session使用的情景预设内容 - prompt: list 此session现有的prompt内容 - text_message: str 用户发送的消息文本 - - returns (optional): - default_prompt: list 修改后的情景预设内容 - prompt: list 修改后的prompt内容 - text_message: str 修改后的消息文本 -""" -``` - -### host: PluginHost 详解 - -提供与主程序各个模块交互的一些方法,具体查看`pkg.plugin.host`中的`PluginHost`类 - -### event: EventContext 详解 - -提供对此次事件执行的一些操作方法,具体查看`pkg.plugin.host`中的`EventContext`类 +#### self.host +在插件的方法中访问`self.host`即为`pkg.plugin.context.APIHost`类的对象,提供了主程序的一些API,详细请查看其源码。 \ No newline at end of file diff --git a/src/posts/plugin/intro.md b/src/posts/plugin/intro.md index 45f00f785..6979b7b0c 100644 --- a/src/posts/plugin/intro.md +++ b/src/posts/plugin/intro.md @@ -18,9 +18,9 @@ index: false ## 插件分类 -**插件**,是QChatGPT的扩展模块,分为**行为插件**和**内容函数**两种类型。行为插件由主程序运行中的事件驱动,而内容函数由GPT生成的内容驱动。这两种驱动方式都统一包装在插件类中。 +**插件**,是QChatGPT的扩展模块,其中包含**事件监听器**和**内容函数**两种可执行内容。事件监听器由主程序运行中的事件驱动,而内容函数由GPT生成的内容驱动。这两种驱动方式都统一包装在插件类中。 -### 行为插件 +### 事件监听器 插件监听 QChatGPT 运行期间的各种事件,QChatGPT 在事件发生时,携带事件相关信息调用插件注册的监听器。插件可以通过注册监听器以在指定情况下被触发。 From 05f364a4d22ad3d362b2e28f553715ee0c40f02c Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Wed, 20 Mar 2024 23:31:30 +0800 Subject: [PATCH 4/7] typos --- src/posts/plugin/develop.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/posts/plugin/develop.md b/src/posts/plugin/develop.md index 9cd13dfaf..a47412f5b 100644 --- a/src/posts/plugin/develop.md +++ b/src/posts/plugin/develop.md @@ -158,7 +158,7 @@ class HelloPlugin(Plugin): ```Python # 要添加的函数 -@llm_fun(name="access_the_web") # 设置函数名称 +@llm_func(name="access_the_web") # 设置函数名称 async def access_web(self, query, url: str): """Call this function to search about the question before you answer any questions. - Do not search through baidu.com at any time. @@ -202,7 +202,7 @@ async def access_web(self, query, url: str): #### 请注意: - 函数的注释必须严格按照要求的格式进行书写,具体格式请查看[此文档](https://github.com/RockChinQ/CallingGPT/wiki/1.-Function-Format#function-format) -- 内容函数和`以@llm_func装饰的行为函数`可以同时存在于同一个插件,并同时受到`plugins/plugins.json`中的插件开关的控制 +- 内容函数和`以 @handler 装饰的事件监听器`可以同时存在于同一个插件,并同时受到`plugins/plugins.json`中的插件开关的控制 - 务必确保您使用的模型支持函数调用功能 3️⃣ 现在您的程序已具备网络访问功能,重启程序,询问机器人有关在线的内容或直接发送文章链接请求其总结。 @@ -214,7 +214,7 @@ async def access_web(self, query, url: str): ### 说明 事件监听器方法获得的`ctx: EventContext`对象可以到`pkg.plugin.context`模块中查看其结构,`ctx`对象的`event`属性为本次事件的事件对象,可以从中取出相关参数,具体事件可以取得的参数请查看`pkg.plugin.events`文件中的每个事件类的注释。 -事件返回值均为**可选**的,可以通过调用`event.add_return(key: str, ret)`来提交返回值 +事件返回值均为**可选**的,可以通过调用`ctx.add_return(key: str, ret)`来提交返回值 ### 事件 From 6fbbc37a2da58369cb63d690de68c559b33efeb5 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Thu, 21 Mar 2024 16:21:55 +0800 Subject: [PATCH 5/7] =?UTF-8?q?doc:=20=E6=B7=BB=E5=8A=A0=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E6=89=A9=E5=B1=95=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/.vuepress/sidebar.ts | 5 +++++ src/posts/plugin/develop.md | 2 +- src/posts/plugin/extension.md | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/posts/plugin/extension.md diff --git a/src/.vuepress/sidebar.ts b/src/.vuepress/sidebar.ts index e6c4551b0..c9fb38586 100644 --- a/src/.vuepress/sidebar.ts +++ b/src/.vuepress/sidebar.ts @@ -187,6 +187,11 @@ export default sidebar({ icon: "code", link: "develop", }, + { + text: "组件扩展", + icon: "code", + link: "extension", + }, ], }, { diff --git a/src/posts/plugin/develop.md b/src/posts/plugin/develop.md index a47412f5b..60ae2ef26 100644 --- a/src/posts/plugin/develop.md +++ b/src/posts/plugin/develop.md @@ -35,7 +35,7 @@ QChatGPT 还支持组件扩展,可以不局限于监听预定事件,做到 按照文档部署此项目,并使其正常运行。 在`plugins`目录下新建目录`hello`,在其中新建空文件`__init__.py`以标记此目录为软件包,继续新建文件`main.py`。 -> 建议使用[hello_plugin](https://github.com/RockChinQ/hello_plugin)作为模板直接生成插件代码仓库后按照下方步骤进行修改。 +> 建议使用[HelloPlugin](https://github.com/RockChinQ/HelloPlugin)作为模板直接生成插件代码仓库后按照下方步骤进行修改。 编辑`main.py`输入以下内容: diff --git a/src/posts/plugin/extension.md b/src/posts/plugin/extension.md new file mode 100644 index 000000000..7d2769eb8 --- /dev/null +++ b/src/posts/plugin/extension.md @@ -0,0 +1,34 @@ +--- +head: + - - meta + - name: keywords + content: QChatGPT 组件扩展教程 +title: 组件扩展 +icon: code +order: 4 +author: RockChinQ +date: 2024-03-21 +category: + - 插件介绍 +index: false +--- + +> 请先阅读[插件介绍页](../plugin/intro.md) + +:::info 目录 +[[toc]] +::: + +普通的以 `BasePlugin` 子类包装的插件只能监听预定事件,而组件扩展则可以替换整个组件,实现更强大的功能扩展。 + +- 组件扩展不需要包装在 `BasePlugin` 子类中 +- 扩展的组件不受插件开关控制 +- 扩展的组件通常由配置文件中的选项选用 + +## 可扩展的组件 + +### 命令 + +- 基类:`pkg.command.operator.CommandOperator` +- 装饰器:`pkg.command.operator.operator_class(name: str, help: str="", usage: str=None, alias: list[str]=[], privilege: int=1, parent_class: typing.Type[CommandOperator] = None)` +- 参考类:`pkg.command.operators/` \ No newline at end of file From a2baa2a072aec56e07647e2d081f278d397541b3 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Fri, 22 Mar 2024 16:38:15 +0800 Subject: [PATCH 6/7] =?UTF-8?q?doc:=20=E6=B7=BB=E5=8A=A0=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E6=89=A9=E5=B1=95=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/posts/plugin/develop.md | 4 +-- src/posts/plugin/extension.md | 67 +++++++++++++++++++++++++++++++++-- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/posts/plugin/develop.md b/src/posts/plugin/develop.md index 60ae2ef26..0a723f5dc 100644 --- a/src/posts/plugin/develop.md +++ b/src/posts/plugin/develop.md @@ -209,7 +209,7 @@ async def access_web(self, query, url: str): - 这仅仅是一个示例,需要更高效的网络访问能力支持插件,请查看[WebwlkrPlugin](https://github.com/RockChinQ/WebwlkrPlugin) -## 📄API参考 +## 📄名词解释 ### 说明 @@ -218,7 +218,7 @@ async def access_web(self, query, url: str): ### 事件 -若一个事件是一次请求(用户发送消息)中的事件,其事件对象中会含有`query`对象,这个对象中包含了此次请求(即用户发送一条消息的处理过程,一个请求过程可能会触发多个事件)处理过程中的数据。 +若一个事件是一次请求(用户发送消息)中的事件,其事件对象中会含有`query`对象,这个对象中包含了此次请求(即用户发送一条消息的处理过程,一个请求过程可能会触发多个事件)处理过程中的上下文数据。 所有支持的事件,请查看`pkg.plugin.events`文件中的每个事件类的注释。 关于`YiriMirai`支持的消息链组件,请查看 [YiriMirai的文档](https://yiri-mirai.wybxc.cc/docs/basic/message-chain) diff --git a/src/posts/plugin/extension.md b/src/posts/plugin/extension.md index 7d2769eb8..253deacd1 100644 --- a/src/posts/plugin/extension.md +++ b/src/posts/plugin/extension.md @@ -21,14 +21,77 @@ index: false 普通的以 `BasePlugin` 子类包装的插件只能监听预定事件,而组件扩展则可以替换整个组件,实现更强大的功能扩展。 -- 组件扩展不需要包装在 `BasePlugin` 子类中 +- 组件扩展不需要包装在 `BasePlugin` 子类中,可以放在插件目录下任意一个模块中 - 扩展的组件不受插件开关控制 - 扩展的组件通常由配置文件中的选项选用 ## 可扩展的组件 +扩展一个组件的方法,新建一个类,继承于组件的基类,然后在类上使用对应的装饰器,再根据使用方式来配置使用该实现的组件。 + +大部分组件中包含了`ap: pkg.core.app.Application`对象,可以用这个对象来与整个程序的各个部分进行交互。 +大部分组件支持实现`async def initialize(self)`方法,用于在组件加载时进行异步初始化。 +`ap`对象中包含了各个配置文件的管理器对象,可以用于访问各个配置文件。 + ### 命令 +新增一个命令。 + - 基类:`pkg.command.operator.CommandOperator` - 装饰器:`pkg.command.operator.operator_class(name: str, help: str="", usage: str=None, alias: list[str]=[], privilege: int=1, parent_class: typing.Type[CommandOperator] = None)` -- 参考类:`pkg.command.operators/` \ No newline at end of file +- 参考实现:`pkg.command.operators/` +- 使用方式:加载成功后,执行命令`!cmd`可查看所有命令和命令帮助信息。 + +### 内容过滤器 + +新增一个在处理消息前后判断是否要继续的内容处理器。 + +- 基类:`pkg.pipeline.cntfilter.filter.ContentFilter` +- 装饰器:`pkg.pipeline.cntfilter.filter.filter_class(name: str)` +- 参考实现:`pkg.pipeline.cntfilter.filters/` +- 使用方式:加载成功后,每次都会在过滤器实现声明的检查阶段调用内容过滤器的`process`方法。 + +### 长消息处理策略 + +新增一个长消息处理策略。类似:文本转合并转发消息组件、文本转图片。 + +- 基类:`pkg.pipeline.longtext.strategy.LongTextStrategy` +- 装饰器:`pkg.pipeline.longtext.strategy.strategy_class(name: str)` +- 参考实现:`pkg.pipeline.longtext.strategies/` +- 使用方式:需要在 `data/config/platform.json` 的 `long-text-strategy` 字段中将 `strategy` 设置为新增的策略名称。 + +### 会话限速算法 + +新增一个会话限速算法。会话请求在进入和退出时均会调用限速算法实现类的方法,实现类可以控制等待或丢弃请求。 + +- 基类:`pkg.pipeline.ratelimit.algo.RateLimitAlgo` +- 装饰器:`pkg.pipeline.ratelimit.algo.algo_class(name: str)` +- 参考实现:`pkg.pipeline.ratelimit.algos/` +- 使用方式:需要在 `data/config/pipeline.json` 的 `rate-limit` 字段中将 `algo` 设置为新增的算法名称。 + +### LLM 接口请求器 + +新增一个 LLM 接口请求器,例如:接入ChatGLM接口等。 + +- 基类:`pkg.provider.modelmgr.api.LLMAPIRequester` +- 装饰器:`pkg.provider.modelmgr.api.api_requester_class(name: str)` +- 参考实现:`pkg.provider.modelmgr.apis/` +- 使用方式:需要在`data/metadata/llm-models.json`中添加模型,将模型的`requester`字段设置为新增的请求器名称。具体请查看元数据配置板块。 + +### Prompt 加载器 + +新增一个 Prompt 加载器。 + +- 基类:`pkg.provider.sysprompt.loader.PromptLoader` +- 装饰器:`pkg.provider.sysprompt.loader.loader_class(name: str)` +- 参考实现:`pkg.provider.sysprompt.loaders/` +- 使用方式:需要在`data/config/provider.json`将`prompt-mode`设置为新增的加载器名称。 + +### 消息平台适配器 + +新增一个消息平台适配器,例如:接入Telegram等。 + +- 基类:`pkg.platform.adapter.MessageSourceAdapter` +- 装饰器:`pkg.platform.adapter.adapter_class(name: str)` +- 参考实现:`pkg.platform.adapters/` +- 使用方式:`data/config/platform.json`的`platform-adapters`中各个配置信息,将在初始化时自动根据`adapter`名称查找对应的适配器实现,并将配置传递给适配器以进行初始化。消息平台适配器实现复杂,建议多参考现有的实现。 From 949e67ec1a53f1454a0356107e33945629c8ce98 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Fri, 22 Mar 2024 17:09:15 +0800 Subject: [PATCH 7/7] =?UTF-8?q?doc:=20=E6=B7=BB=E5=8A=A0=E9=83=A8=E5=88=86?= =?UTF-8?q?api=E5=8F=82=E8=80=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/.vuepress/sidebar.ts | 5 +++++ src/posts/plugin/apiref.md | 45 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/posts/plugin/apiref.md diff --git a/src/.vuepress/sidebar.ts b/src/.vuepress/sidebar.ts index c9fb38586..fb129b931 100644 --- a/src/.vuepress/sidebar.ts +++ b/src/.vuepress/sidebar.ts @@ -192,6 +192,11 @@ export default sidebar({ icon: "code", link: "extension", }, + { + text: "API 参考", + icon: "api", + link: "apiref", + }, ], }, { diff --git a/src/posts/plugin/apiref.md b/src/posts/plugin/apiref.md new file mode 100644 index 000000000..05907bae8 --- /dev/null +++ b/src/posts/plugin/apiref.md @@ -0,0 +1,45 @@ +--- +head: + - - meta + - name: keywords + content: QChatGPT API 参考 +title: API 参考 +icon: code +order: 5 +author: RockChinQ +date: 2024-03-22 +category: + - 插件介绍 +index: false +--- + +暂时未设计独立 API 层,本页面讲解了一些常用的功能的调用方法。 +以下提到的对象及访问方式均在前文有所提及,请先阅读插件开发教程。 + +## 消息处理 + +### 回复消息 + +切入方法:`pkg.platform.adapter.MessageSourceAdapter.reply_message` + +由于程序中可能同时运行多个 消息平台适配器(MessageSourceAdapter),故在`query: pkg.core.entities.Query` 对象中包含了 `adapter` 对象,保存了此次请求对应的适配器,通过这个对象可以调用适配器的回复消息方法。 + +需要传入: +- `message_source`本次消息的来源事件,可以从`query`对象中获取。 +- `message`回复的消息内容,YiriMirai 的 MessageChain对象 +- `quote_origin: bool`是否引用原消息 + +### 发送主动消息 + +不推荐。 + +切入方法:`pkg.platform.adapter.MessageSourceAdapter.send_message` + +需要自己找到一个适配器对象,然后调用此方法。 +`ap: pkg.core.app.Application`的`platform_mgr: pkg.platform.manager.PlatformManager`对象中保存了所有适配器对象:`adapters`,从中取出一个即可调用`send_message`方法。 + +需要传入: + +- `target_type`目标类型,可以是`group`或`person` +- `target_id`目标id +- `message`消息内容,YiriMirai 的 MessageChain对象