编写第一个插件
插件可以改变 Bub 应用处理任务的方式。这个插件用回声回复替代模型阶段,让你无需模型凭据就能检查插件发现和轮次处理。需要内置 agent 的模型调用与会话记录时,保留它的模型实现。
按安装 Bub中的说明准备 Python 3.12+ 和 uv。这篇教程会创建一个同时包含 Bub 0.6.0 和插件的项目环境。
创建以下包目录:
bub-echo-plugin/
├── pyproject.toml
└── src/
└── bub_echo_plugin/
├── __init__.py
└── plugin.py
将 __init__.py 留空。在 pyproject.toml 中写入:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "bub-echo-plugin"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["bub[app]>=0.6.0"]
[project.entry-points."bub"]
echo = "bub_echo_plugin.plugin:echo_plugin"
[tool.hatch.build.targets.wheel]
packages = ["src/bub_echo_plugin"]
bub 入口点组告诉应用到哪里寻找插件。
在 src/bub_echo_plugin/plugin.py 中写入:
from bub import hookimpl
class EchoPlugin:
@hookimpl
def run_model(self, prompt, session_id, state):
return f"[echo:{session_id}] {prompt}"
echo_plugin = EchoPlugin()
应用仍会构建收到的提示词。你的 run_model 实现提供回复,替代内置 agent 的执行。
安装并试运行
Section titled “安装并试运行”在插件目录安装项目和依赖:
uv sync
uv run bub hooks
uv sync 会以可编辑模式安装这个包。在同一个项目中通过 uv run 运行 Bub,它就能发现插件。
报告应在 run_model 下列出 echo。内置 agent 则出现在 run_model_stream 下。
uv run bub run "hello from my plugin"
没有其他插件覆盖模型阶段时,回复包含:
[echo:cli:local] hello from my plugin
如果没有看到 echo,检查安装插件的环境是否就是运行 bub 的环境。如果已经列出却返回其他回复,检查其他模型 hooks 及其优先级。