# 复用 Bub 应用

如果你想把 Bub 嵌入自己现有的 Python 服务，除了直接使用微内核 [`bub.core.Agent`](/zh-cn/docs/sdk/) 之外，还可以按需复用 Bub 应用层已经做好的能力——包括配置加载、技能发现、插件 Hooks、内置工具以及完整的 Turn 消息处理流程。

选择哪个入口，取决于**你希望让 Bub 接管多少流程，以及哪些生命周期仍由你的宿主程序自己掌控**。

本页涉及的应用层接口需安装 [`app` 可选依赖](/zh-cn/docs/getting-started/install/#app-install)并配置模型凭据（如 `REPUBLIC_OPENAI_API_KEY`）：

```bash
uv add "bub[app]"
```

如果你只需要纯粹的「模型—工具—Tape」核心循环，不需要应用层的配置、技能或插件，直接从[核心 SDK](/zh-cn/docs/sdk/) 开始即可。

<a id="choose-a-depth"></a>

## 选择复用层级 {#choose-a-reuse-layer}

Bub 提供了从完整到轻量的五种复用入口。它们是并列关系而非强制升级路径，建议从能满足你需求的最小层级开始：

| 需要复用的能力 | 推荐入口 | 宿主程序负责的部分 |
| --- | --- | --- |
| **整套 CLI 或常驻网关** | `bub run` / `bub chat` / `bub gateway` 或自定义命令入口 | 提供配置、密钥与部署环境；无需编写 Python 调用循环 |
| **完整的消息 Turn**（从收消息到生成回复） | `BubFramework.process_inbound()` | 服务生命周期、顶层异常捕获、同会话并发锁、自定义回复发送 |
| **应用配置、技能、工具白名单与命令**（自行消费事件流） | `BubAgent.run_stream()` | 消费并关闭流、发送回复、跨 Turn 状态保存、同会话并发锁 |
| **为 `core.Agent` 接入插件的循环 Hooks** | `AgentPlugins.attach()` | 驱动 `agent.run()`、处理入站与出站消息、同会话并发锁 |
| **仅复用单个工具函数** | 直接导入工具并传给 `core.Agent(tools=[...])` | 管理模型连接、Tape 存储、Run 循环与所有资源生命周期 |

:::note
安装插件包后，不同层级的入口只会激活该层级对应的扩展点。例如，`AgentPlugins` 和 `BubAgent` 可复用插件提供的工具和 Agent 循环 Hooks；但插件注册的消息渠道、CLI 子命令或外围 Turn 阶段 Hooks，只有在 `BubFramework` 或 `bub gateway` 中才会运行。
:::

<a id="process-inbound"></a>

## 执行完整 Turn：`BubFramework.process_inbound()` {#run-a-complete-turn}

如果你希望 Bub 替你把「解析会话 ID、构造提示词、调用模型与工具、保存状态、组装出站回复」全套流程都跑完，最省心的入口是 `BubFramework.process_inbound()`。

将以下代码保存为 `embedded.py`：

```python title="embedded.py" {12-17}
import asyncio

from bub import BubFramework
from bub.envelope import content_of

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        result = await framework.process_inbound({
            "session_id": "embedded:customer-42",
            "channel": "embedded",
            "chat_id": "customer-42",
            "content": "请说明你能帮我处理哪些订单问题。",
        })

    print(result.session_id)
    for outbound in result.outbounds:
        print(content_of(outbound))

if __name__ == "__main__":
    asyncio.run(main())
```

运行：

```bash
uv run python embedded.py
```

使用要点：

- **启动时调用一次 `load_hooks()`**：加载内置实现与当前环境中安装的所有插件。
- **`framework.running()` 覆盖整个服务周期**：该上下文管理器持有插件生命周期资源、Tape 存储和 `SteeringInbox`。在 Web 服务中，应在服务启动/关闭（如 FastAPI 的 `lifespan`）时进出，不要每次请求重复进出。
- **从 `result.outbounds` 读取回复**：`process_inbound()` 返回汇总后的 `TurnResult`。若安装了会在 `dispatch_outbound` 阶段主动发消息的渠道插件，请注意避免宿主程序与插件重复发送。
- **启用流式模型阶段**：传入 `stream_output=True` 会改走流式 `run_model_stream` 并在内部消费完毕后返回 `TurnResult`（绑定了 `ChannelRouter` 时还可通过 `wrap_stream()` 实时转发增量事件；不绑定 Router 也可正常使用 `stream_output=True`）。

<a id="reuse-bubagent"></a>

## 只复用模型阶段：`BubAgent.run_stream()` {#model-stage}

如果你既想使用应用层的配置、技能发现、工具限制和逗号命令，又希望自己用 `async for` 消费流式事件（例如通过 SSE 推给前端），可直接调用 `BubAgent.run_stream()`。

`run_stream()` 返回 `AsyncStreamEvents` 异步迭代器（本身不是上下文管理器），**请务必配合 `contextlib.aclosing()` 使用**，确保提前退出或报错时底层流能正常关闭：

```python collapse={1-7} {14-19,21}
import asyncio
import contextlib

from bub import BubFramework
from bub.builtin.agent import BubAgent

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        agent = BubAgent(framework)
        stream = await agent.run_stream(
            session_id="customer-42",
            prompt="请直接用纯文本回答：你能处理哪些订单问题？",
            allowed_tools=[],
            allowed_skills=[],
        )

        async with contextlib.aclosing(stream):
            async for event in stream:
                if event.kind == "text":
                    print(event.data["delta"], end="", flush=True)
        print()

if __name__ == "__main__":
    asyncio.run(main())
```

请在 `async with framework.running():` 内部实例化 `BubAgent` 以获取活动存储，并在多个会话间复用同一个 `BubAgent` 实例。

与 `process_inbound()` 相比，`BubAgent.run_stream()` 的行为边界：

- **会执行**：将 `session_id` 解析为会话 Tape、绑定运行时 Agent、在 `state=None` 时自动调用 `load_state` Hooks，并支持执行逗号命令；
- **不执行**：跳过初始 `build_prompt`、结束时不调用 `save_state`、不执行 `render_outbound` 和 `dispatch_outbound`，也不对同 `session_id` 的并发请求加锁；
- **流消费约定**：需用 `aclosing()` 关闭流；`final` 事件仅代表单个 Step 结束，整个 `async for` 循环结束才代表整次运行完成。

:::tip[关于系统提示词]
默认系统提示词不会要求模型调用渠道技能（如 `telegram` 技能）回复；该指令仅由 `bub gateway` 和 `bub chat` 的 `ChannelManager` 动态注入。在你自己的服务中调用 `run_stream()` 或 `process_inbound()` 时，模型会直接输出文本。请勿直接覆盖 `agent.system_prompt` 属性，否则会抹掉插件、技能、延迟工具和代码模式注册的提示词片段。
:::

<a id="run-stream-options"></a>

### 按请求限制可用工具与技能 {#narrow-tools-and-skills}

调用 `BubAgent.run_stream()` 时，可通过 `allowed_tools` 和 `allowed_skills` 限制单次请求允许模型使用的工具与技能：

```python collapse={1-12} ins={27-28}
import asyncio
import contextlib

from bub import BubFramework
from bub.builtin.agent import BubAgent
from bub.core.tools import Tool

def lookup_order(order_id: str) -> str:
    return f"订单 {order_id}：处理中。"

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        order_tool = Tool.from_callable(
            lookup_order,
            name="orders.get",
            description="按订单号查询示例订单。",
        )
        agent = BubAgent(framework, tools=[order_tool])
        stream = await agent.run_stream(
            session_id="customer-42",
            prompt="查询订单 A123。",
            allowed_tools={"orders.get"},
            allowed_skills=[],
        )
        async with contextlib.aclosing(stream):
            async for event in stream:
                if event.kind == "text":
                    print(event.data["delta"], end="", flush=True)

if __name__ == "__main__":
    asyncio.run(main())
```

| 参数 | 传 `None`（默认） | 传空集合（`[]` 或 `set()`） |
| --- | --- | --- |
| `allowed_tools` | 允许使用该 Agent 实例上的全部工具 | 本次请求禁用所有工具 |
| `allowed_skills` | 允许使用发现的全部技能 | 本次请求禁用所有技能 |

传入未注册的工具名会抛出 `ValueError`。注意：

1. `allowed_tools` 仅限制模型调用和代码模式内的工具，**不限制逗号直接命令**（如 `,fs.read`）。如需拦截所有调用路径，请在 `before_tool_call` Hook 中校验权限。
2. 只有由**宿主代码**指定 `allowed_tools` 时才构成可靠约束；在对话中由模型生成的 `subagent` 工具白名单不构成强制安全边界。
3. 显式传入 `run_stream(state=...)` 会跳过 `load_state` Hooks。若需在正常加载状态的基础上添加自定义字段，请先调用 `await framework.build_state(message, session_id)`，再修改返回的字典（见 [Python API](/zh-cn/docs/reference/python-api/#framework)）。

<a id="components"></a>

## 只复用工具或 Agent 循环 Hooks {#reuse-tools-or-hooks}

### 1. 在 `core.Agent` 中直接复用插件工具 {#tool-implementations}

如果你的项目使用的是核心层的 `bub.core.Agent`，但看中了某个 Bub 插件提供的工具函数，你可以直接导入该工具并传给 `Agent(tools=[...])`，完全不需要启动 `BubFramework`。

下面以社区的 `bub-web-search` 插件为例，演示如何只提取它的 `web.search` 工具交给 `core.Agent` 使用。先安装依赖并设置环境变量：

```bash
uv add "bub[app]" \
  "bub-web-search @ git+https://github.com/bubbuild/bub-contrib.git@main#subdirectory=packages/bub-web-search"

export BUB_SEARCH_PROVIDER=jina
export BUB_SEARCH_JINA_API_KEY=jina_...
export REPUBLIC_OPENAI_API_KEY=sk-...
```

创建 `search_agent.py`：

```python title="search_agent.py" collapse={1-10} {13,19}
import asyncio
from pathlib import Path

import republic
from bub_web_search.tools import build_tools

from bub.core import Agent
from bub.core.store import FileTapeStore

async def main() -> None:
    search_tools = build_tools()
    search = search_tools.get("web.search")
    if search is None:
        raise RuntimeError("Configure BUB_SEARCH_PROVIDER and BUB_SEARCH_JINA_API_KEY first.")

    agent = Agent(
        store=FileTapeStore(Path("sessions")),
        tools=[search],
        system_prompt="先搜索可靠来源，再用中文回答，并附上来源链接。",
    )
    async with republic.get_model("openai:gpt-5-mini") as model:
        async with agent.run(
            "查找 Python asyncio 官方文档。",
            model=model,
            tape="research-42",
            options={"max_tokens": 4096},
        ) as stream:
            async for event in stream:
                if event.kind == "text":
                    print(event.data.get("delta", ""), end="", flush=True)
                elif event.kind == "error":
                    raise RuntimeError(str(event.data.get("message", "Agent failed")))
    print()

if __name__ == "__main__":
    asyncio.run(main())
```

运行 `uv run python search_agent.py` 即可看到搜索结果并把会话写入 `sessions/`。在这种方式下，你只拿走了插件里的工具对象，模型连接、Tape 存储和事件流消费均由宿主代码直接掌控。更多配置说明可参考 [`bub-web-search` 文档](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search)。

<a id="other-hooks"></a>

### 2. 用 `AgentPlugins` 将插件 Hooks 挂载到 `core.Agent` {#agent-loop-hooks}

如果你不仅想复用工具，还想在 `core.Agent` 上复用插件里的 `system_prompt`、`provide_tools`、`before_llm_call`、`before_tool_call` 等与 Agent 循环直接相关的 Hooks，可以使用 `AgentPlugins` 桥接器（事件映射关系见 [Hooks 参考](/zh-cn/docs/reference/hooks/#event-mapping)）。

将以下最小示例保存为 `agent_hooks.py`：

```python title="agent_hooks.py" wrap collapse={1-10} {21-25}
import asyncio

import republic

from bub.core import Agent
from bub.core.store import InMemoryTapeStore
from bub.hooks import hookimpl
from bub.hooks.agent import AgentPlugins
from bub.turn import TurnState

class PlainTextPlugin:
    """为 Agent 追加系统提示词。"""

    @hookimpl
    def system_prompt(self, prompt: str, state: TurnState) -> str:
        return "用简短、清楚的中文回答。"

async def main() -> None:
    plugins = AgentPlugins(plugins=[PlainTextPlugin()])
    async with plugins.running():
        components = {**plugins.components(), "store": InMemoryTapeStore()}
        agent = plugins.attach(Agent(system_prompt="回答用户的问题。", **components))
        state = await plugins.build_state("customer-42", agent=agent)

        async with republic.get_model("openai:gpt-5-mini") as model:
            async with agent.run("你能做什么？", model=model, tape="customer-42", state=state) as stream:
                async for event in stream:
                    if event.kind == "text":
                        print(event.data.get("delta", ""), end="", flush=True)
        print()

if __name__ == "__main__":
    asyncio.run(main())
```

运行示例：`uv run python agent_hooks.py`。

使用 `AgentPlugins` 时，请留意以下要点：

- **显式插件列表 vs. 自动发现**：`AgentPlugins(plugins=[...])` 仅注册传入的插件，不加载内置 Hooks 或环境中安装的第三方插件。如需加载全部已安装插件，可先创建 `framework = BubFramework()` 并调用 `framework.load_hooks()`，再传入 `AgentPlugins(framework)`。
- **合并 `components()`**：`plugins.components()` 返回插件提供的 `store`、`context` 和 `sidecars`。如需覆盖其中某项（如 `store`），请用 `{**plugins.components(), "store": ...}` 合并后再传给 `Agent()`。
- **在 `plugins.running()` 内运行**：先调用 `plugins.attach(agent)`，再注册你自己的 `agent.events.on(...)` 处理器，以便观察到插件修改后的事件状态。
- **仅覆盖循环阶段**：`attach()` 不会执行外围 Turn 的初始 `build_prompt`、`save_state`、出站渲染或渠道分发。此外，若插件依赖配套工具（如 `bub-context-budget` 需要 `tape.handoff` 工具）或长连接（如 [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding)），需一并提供对应组件。

## 绑定 `ChannelRouter` 接管渠道投递 {#bind-a-router}

如果你自己的宿主服务已经有了现成的消息返回逻辑（比如直接在 HTTP 响应里返回结果），读取 `TurnResult.outbounds` 就足够了，不需要配置 Router。

只有在你希望让 Bub 渠道层接管出站投递与流式包装时，才需要实现 `ChannelRouter` 并调用 `framework.bind_channel_router(router)`：

- `dispatch_output()`：执行消息投递；返回 `False` 不会触发自动重试，`process_inbound()` 仍会返回 `outbounds`。
- `wrap_stream()`：返回异步可迭代对象并透传模型事件（最终的 `model_output` 由包装后的流产出的文本增量拼接而成）。
- `admit_channel_message()`：供 `ChannelManager` 消息准入路径调用；直接调用 `process_inbound()` 不会自动执行准入检查或排队。

相关接口签名详见 [Python API](/zh-cn/docs/reference/python-api/#framework)，生命周期概念见 [Turn](/zh-cn/docs/concepts/turn/)。

<a id="lifecycle-and-concurrency"></a>

## 嵌入服务自检清单 {#lifecycle-failure-concurrency}

无论你选择了上面哪一种应用层入口，在将代码部署上线前，建议对照检查以下七个边界：

1. **启动时只调一次 `load_hooks()`**：不要在每次请求时重复扫描插件。
2. **共用单一 `running()` 作用域**：不要在同一个 `BubFramework` 上并发或嵌套进入 `running()`（`ChannelManager.listen_and_run()` 内部已包含 `running()`）。
3. **配置为进程级缓存**：多个 `BubFramework` 实例可隔离插件集，但应用配置（`Settings`）在进程内全局缓存。
4. **宿主程序捕获异常**：`run_stream()` 和 `process_inbound()` 报错均会向上抛出异常；`on_error` Hook 仅记录日志，不会吞掉异常。
5. **同会话并发需显式加锁**：按 `session_id` 使用宿主侧互斥锁（如 `asyncio.Lock`），或通过 `ChannelManager` 的 `follow_up` 策略串行化。
6. **确保关闭事件流**：可能提前退出的路径一律使用 `contextlib.aclosing()`。除 `temp/` 前缀会话外，普通会话的记录在运行过程中就会写入主 Tape；关闭流时会重试此前写入失败的记录，并让同一 Tape 上的其他运行可以读到它们。
7. **外部副作用不自动回滚**：模型报错、取消或丢弃 Tape 分支不会撤销工具对文件、网络或外部数据库的修改。

<a id="cli"></a>

## 直接运行或封装 CLI {#run-or-publish-cli}

如果你的场景并不需要把 Bub 嵌进另一个 Python 服务，而是直接作为命令行或守护进程使用，直接运行 `bub run`、`bub chat` 或 `bub gateway` 即可。如果你想把它包装成带有自己品牌命令名（如 `my-bub`）的发行包，并把自定义插件和技能一起打包分发给团队，请参考[打包与分发](/zh-cn/docs/app/distribution/)。