# https://github.com/agentscope-ai/agentscope 项目说明书

生成时间：2026-06-21 12:48:19 UTC

## 目录

- [项目总览与架构](#page-1)
- [智能体核心与事件驱动设计](#page-2)
- [模型集成、工具与技能](#page-3)
- [多租户服务、Web UI 与可扩展中间件](#page-4)

<a id='page-1'></a>

## 项目总览与架构

### 相关页面

相关主题：[智能体核心与事件驱动设计](#page-2), [模型集成、工具与技能](#page-3), [多租户服务、Web UI 与可扩展中间件](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- [src/agentscope/agent/_config.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)
- [src/agentscope/app/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/__init__.py)
- [src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)
- [src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)
- [src/agentscope/app/_tools/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py)
- [src/agentscope/app/_tools/_team_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py)
- [src/agentscope/app/middleware/_tool_offload_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py)
- [src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)
- [src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)
- [src/agentscope/middleware/_tracing/_converter.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py)
- [src/agentscope/middleware/_tracing/_extractor.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_extractor.py)
</details>

# 项目总览与架构

## 项目定位与核心目标

AgentScope 是一个面向多智能体（Multi-Agent）应用构建的 Python 框架，强调“以开发者为中心”（Developer-Centric）的设计哲学。根据 [README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md) 中的项目说明，框架同时提供了 Python SDK 与基于 FastAPI 的可部署服务，目标用户包括需要快速搭建智能体原型的应用开发者，以及希望将智能体嵌入现有微服务体系的后端工程师。

框架的核心设计理念可以从社区反馈中印证：在 Issue #842 中，用户特别称赞其“每一个细节都非常用心”的设计体验，体现了框架在配置项默认值、错误信息与开发流程上对开发者友好性的重视。

## 系统架构总览

AgentScope 的整体架构采用“**核心智能体运行时 + 中间件管道 + 可插拔服务层**”三层模型。智能体（Agent）是业务执行单元；中间件（Middleware）以钩子方式拦截并增强推理、回复与工具调用过程；服务层（App）负责将会话、调度与工具组装为可独立部署的 Web 应用。

```mermaid
flowchart TB
    subgraph App[应用服务层 - src/agentscope/app]
        A1[create_app FastAPI 工厂]
        A2[Storage & MessageBus]
        A3[get_toolkit 工具装配]
    end
    subgraph Core[核心智能体运行时]
        B1[Agent]
        B2[Toolkit / Tool]
        B3[ChatModel]
        B4[Msg / ContentBlock]
    end
    subgraph MW[中间件管道]
        C1[Budget / 预算控制]
        C2[LongTerm Memory / Mem0]
        C3[ToolOffload / 后台工具]
        C4[Tracing / OTel GenAI]
    end
    A1 --> B1
    A3 --> B2
    B1 --> C1
    B1 --> C2
    B1 --> C4
    B2 --> C3
```

三层之间的协作关系如下：

- **应用服务层**通过 [`create_app`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py) 工厂创建 FastAPI 应用，并将 `StorageBase`、`MessageBus`、`WorkspaceManagerBase` 等外部资源纳入统一生命周期管理；其导出定义见 [`src/agentscope/app/__init__.py`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/__init__.py)。
- **核心智能体运行时**承担模型推理、消息流转与工具调用；[`Agent` 的配置类](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py) 中集中定义了 `ReActConfig`（最大迭代次数与拒绝处理）、`ModelConfig`（重试次数）等关键参数。
- **中间件管道**通过 `MiddlewareBase` 派生类以非侵入方式增强 Agent 行为，例如 [`ReplyBudgetControlMiddleware`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py) 在加权 token 用量达到预算时向智能体注入“必须立即收尾”的提示。

## 关键子系统

### 工具装配与团队编排

[`get_toolkit`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py) 是工具编排的核心入口：它把工作区内置工具、计划类任务工具、后台任务控制、定时任务控制、团队参与工具以及调用方自定义扩展聚合到一个 `Toolkit` 实例中。值得注意的是，团队工具的可见性**仅依赖智能体的 `source` 字段**——`source='user'` 始终拥有 `TeamCreate / AgentCreate / TeamSay / TeamDelete` 完整领导者工具集，`source='team'` 的工作者仅看到 `TeamSay`，这一选择由 [`app/_tools/__init__.py`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py) 中的注释明确说明。

以 [`TeamCreate`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py) 为例，其执行流程在调用时直接读写 `StorageBase`，并在同一会话已绑定其他团队时返回明确的错误状态，避免在工具层进行状态刷新——这种“单次运行内连续创建并使用团队”的设计正是基于上述 toolkit 不变的特性。

### 后台工具与记忆

[`ToolOffloadMiddleware`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py) 把长时间运行工具的完成结果通过 `MessageBus.inbox_push` 推入收件箱，并通过 `enqueue_wakeup` 唤醒空闲会话，使分布式部署下的后台任务能够可靠地交付结果。长期记忆方面，[`Mem0Middleware`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py) 提供三种模式（`static_control` / `agent_control` / `both`），允许框架静态注入记忆上下文或以工具方式让智能体自主检索。

### 可观测性

[`_converter.py`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py) 与 [`_extractor.py`](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_extractor.py) 共同实现了与 OpenTelemetry GenAI 规范的适配：前者把 `ContentBlock`（包括 `TextBlock`、`ThinkingBlock`、`ToolCallBlock`、`DataBlock` 等）转换为 OTel 语义下的 part 格式，后者则负责把 `Msg` 对象抽取为符合规范的 span 属性，便于接入分布式追踪系统。

## 社区关注热点

Wiki 的维护者也应当关注社区中反馈的几个与架构直接相关的话题：

| 议题 | 与架构的关联 |
|------|--------------|
| Issue #1453：`SKILL.md` 未被自动加载 | 涉及工具装配层是否原生支持意图识别 → 动态 SKILL 加载流程，需扩展 `get_toolkit` 与技能发现机制 |
| Issue #1660：ripgrep 在非标准 glibc 环境触发源码编译 | 与工具（`Grep`）的依赖管理相关，可考虑将其转为可选依赖 |
| Issue #1474：VantaGrid 确定性记忆中间件 RFC | 与 `Mem0Middleware` 的检索机制对比，体现社区对 O(1) 召回与共享状态的探索 |

## See Also

- 安装与快速上手：[README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- 模型供应商覆盖：[scripts/model_examples/README.md](https://github.com/agentscope-ai/agentscope/blob/main/scripts/model_examples/README.md)
- Web 前端依赖：[examples/web_ui/package.json](https://github.com/agentscope-ai/agentscope/blob/main/examples/web_ui/package.json)

---

<a id='page-2'></a>

## 智能体核心与事件驱动设计

### 相关页面

相关主题：[项目总览与架构](#page-1), [模型集成、工具与技能](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agentscope/agent/_config.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)
- [README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- [src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)
- [src/agentscope/middleware/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/__init__.py)
- [src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)
- [src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)
- [src/agentscope/middleware/_tracing/_converter.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py)
- [src/agentscope/app/middleware/_tool_offload_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py)
- [src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)
- [src/agentscope/app/_tools/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py)
- [src/agentscope/app/_tools/_team_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py)
- [src/agentscope/app/_tools/_agent_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_agent_create.py)
</details>

# 智能体核心与事件驱动设计

## 概述

AgentScope 是一个面向开发者的多智能体（Multi-Agent）平台，其核心由"智能体运行时 + 工具集合 + 中间件钩子 + 事件总线"四部分组成。智能体本身并不耦合任何具体业务，而是通过事件（Event）暴露推理生命周期，通过中间件（Middleware）拦截生命周期中的关键节点，从而实现回复预算控制、长期记忆注入、工具调用结果分发、追踪（Tracing）等横切关注点。这种以"事件驱动 + 中间件拦截"为骨架的设计，使得 AgentScope 既能作为轻量级 Python 库被 `from agentscope.agent import Agent` 直接使用，也能通过 `agentscope.app.create_app` 工厂方法注册为 FastAPI 服务，向多智能体团队、WebUI 与后台调度系统统一提供能力（资料来源：[README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)）。

## 智能体核心与配置模型

`Agent` 类是平台的核心运行时对象，对外的所有推理循环都以 `reply()` 异步接口对外暴露。在构建智能体实例时，开发者无需关心网络或模型细节，只需通过 Pydantic 化的配置类显式声明其行为边界。AgentScope 将所有可调参数集中在 `agentscope.agent._config` 中：

- `ModelConfig`：定义 `max_retries`、模型客户端等元数据，并显式允许任意类型（`arbitrary_types_allowed=True`），便于把自定义 `ChatModel` 子类注入到智能体中（资料来源：[src/agentscope/agent/_config.py:ModelConfig](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)）。
- `ReActConfig`：控制推理-行动循环的 `max_iters` 与 `stop_on_reject` 开关，后者用于在工具被拒绝时让智能体暂停以便人工介入（资料来源：[src/agentscope/agent/_config.py:ReActConfig](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)）。
- `SummaryConfig`：用于在长期会话中触发上下文压缩，包含 `summary_template`、`summary_schema`（默认通过 `SummarySchema.model_json_schema()` 工厂生成）、`tool_result_limit`（默认 50000 token）等字段，确保历史不会无限膨胀（资料来源：[src/agentscope/agent/_config.py:SummaryConfig](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)）。

这一组配置类共同决定了智能体的"循环上限、压缩策略和工具结果阈值"，配合 Quickstart 中的 `DashScopeChatModel` + `DashScopeCredential` 即可在不到 20 行代码中跑通一个最小可运行示例（资料来源：[README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)）。

## 事件驱动的中间件系统

中间件（Middleware）是事件驱动设计的承载体。`agentscope.middleware` 顶层模块统一导出 `MiddlewareBase` 与若干官方实现：`Mem0Middleware`、`TracingMiddleware`、`ReplyBudgetControlMiddleware`、`TTSMiddleware`（资料来源：[src/agentscope/middleware/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/__init__.py)）。它们都继承自 `MiddlewareBase`，通过覆写 `on_reply` 等异步生成器钩子，介入智能体的回复生命周期：

```mermaid
flowchart LR
    User[User/上游事件] --> ReAct[ReAct 推理循环]
    ReAct -->|on_reply 前置| MW1[BudgetControl]
    MW1 --> MW2[LongtermMemory]
    MW2 --> MW3[Tracing]
    MW3 --> Model[ChatModel 调用]
    Model --> Tool[Tool 执行]
    Tool --> Bus[事件总线/Hint]
    Bus --> ReAct
```

- **预算控制**：`ReplyBudgetControlMiddleware` 以加权公式 `cost = input_token_weight*input_tokens + output_token_weight*output_tokens` 累计一次回复中的 token 开销；达到阈值后向智能体上下文注入 `HintBlock` 提醒，并将 `tool_choice` 强制设为 `"none"`，使智能体立刻收尾。所有状态以中间件 key 写入 `agent.state.middle_context`，因此即便经过人类介入（Human-in-the-loop）中断恢复，预算仍然连续生效；并在 `ReplyEndEvent` 时自动清理（资料来源：[src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)）。
- **长期记忆**：`Mem0Middleware` 在初始化时校验 `user_id` 与 `mode`（`static_control`/`agent_control`/`both`），在 `on_reply` 钩子中按 `top_k`、`threshold` 等参数将记忆检索结果写入系统提示或开放给智能体的 `search_memory`/`add_memory` 工具（资料来源：[src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)）。
- **追踪与可观测性**：`TracingMiddleware` 借助 `_converter.py` 中的 `_convert_media_block` 把 `DataBlock`/`Base64Source`/`URLSource` 等多模态内容统一转写为 OpenTelemetry GenAI 规范的 `type=uri` 或 `type=blob` 部分，并按 `image/audio/video` 派生 `modality` 字段，从而在分布式追踪后端中保留完整的多模态语义（资料来源：[src/agentscope/middleware/_tracing/_converter.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py)）。

## 工具装配与团队编排

工具（Toolkit）是事件驱动循环中"行动"阶段的执行者。`app._service._toolkit.get_toolkit` 是单次回复的工具装配入口，它按固定顺序将工具聚合进 `Toolkit`：

1. 工作区内置工具（Bash / Read / Write / Grep 等）；
2. 规划类工具（`TaskCreate` / `TaskList` / `TaskGet` / `TaskUpdate`）；
3. 后台任务控制（`ToolStop`，来自 `BackgroundTaskManager.list_tools`）；
4. 调度控制（`ScheduleCreate` / `ScheduleView` / `ScheduleDelete` / `ScheduleList`），仅当会话配置了模型时才挂载；
5. 团队工具，根据 `agent_record.source` 选择：worker 仅看到 `TeamSay`，leader 看到 `TeamCreate / AgentCreate / TeamSay / TeamDelete`；
6. 调用方通过 `extra_factory` 注入的自定义工具。

工作区的 `skills` 与 `mcps` 则映射到 `Toolkit` 的 `skills_or_loaders` 与 `mcps` 参数（资料来源：[src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)）。

团队工具的可见性规则以 `source` 字段为唯一依据，而非运行时刷新工具集：`source='user'` 始终看到完整的 leader 工具集；`source='team'` 的 worker 仅看到 `TeamSay`。每个工具的 `__call__` 在执行时再次读取最新的 storage 状态以校验前置条件，例如 `TeamCreate` 会显式拒绝"已经属于 team X 的 session"，提示调用方先 `TeamDelete`（资料来源：[src/agentscope/app/_tools/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py)、[src/agentscope/app/_tools/_team_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py)）。`AgentCreate` 则使用 `DEFAULT_SUB_AGENT_TEMPLATE`，模板中明确了子代理的 `system_prompt_template`、`override_leader_mode`、`extend_leader_permission_rules` 等关键参数，便于上层业务按团队章程生成结构化提示（资料来源：[src/agentscope/app/_tools/_agent_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_agent_create.py)）。

## 服务化与事件生命周期

`agentscope.app.create_app` 是平台的服务化入口，它接收 `StorageBase`、`MessageBus`、`WorkspaceManagerBase` 三个必选依赖，返回配置好的 `FastAPI` 实例（资料来源：[src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)）。其设计强调三点：

- **存储与传输解耦**：持久化后端（如 SQL）与实时消息总线（如 Redis）由不同对象承载，二者的 `__aenter__/__aexit__` 生命周期都交由 FastAPI 的 lifespan 管理，从而允许按场景分别优化。
- **后台任务结果回收**：当工具被 `ToolOffloadMiddleware` 切到后台执行并完成时，结果以 `HintBlock`（带 `<system-notification>` 前后缀）投递到 `message_bus.inbox_push`，再由 `enqueue_wakeup` 唤醒对应的空闲会话，与团队消息走同一条交付链路——这就是典型的事件驱动闭环（资料来源：[src/agentscope/app/middleware/_tool_offload_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py)）。
- **可挂载子系统**：`create_app` 支持 `extra_middlewares` 注入，允许在不动核心的前提下挂载业务专属中间件；既可独立 `uvicorn.run`，也可 `root.mount("/agentscope", agentscope_app)` 嵌入既有服务（资料来源：[src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)）。

## 常见失败模式与社区关注点

- **依赖与平台兼容性**：在 Alibaba Cloud Linux 等非标准 glibc/musl 环境下安装时，ripgrep 会被源码编译，社区已提出将其降为可选依赖（与代码搜索/RAG 工具相关，非核心必需），参见 Issue #1660。
- **技能（SKILL）执行路径**：用户提问命中 `unit-converter` 技能时，智能体是否按 `SKILL.md` 执行，依赖 `Toolkit` 的 `skills_or_loaders` 是否在 `get_toolkit` 阶段被正确装配（资料来源：[src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)），相关讨论见 Issue #1453。
- **记忆后端扩展**：社区 RFC #1474 提出基于 NIAH 基准的确定性记忆中间件方案，提示 `Mem0Middleware` 的 `static_control/agent_control/both` 模式仍有进一步标准化空间（资料来源：[src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)）。

## See Also

- README：[README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- 智能体配置：[src/agentscope/agent/_config.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)
- 中间件入口：[src/agentscope/middleware/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/__init__.py)
- 预算控制中间件：[src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)
- Mem0 长期记忆：[src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)
- 工具装配：[src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)
- 服务工厂：[src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)

---

<a id='page-3'></a>

## 模型集成、工具与技能

### 相关页面

相关主题：[智能体核心与事件驱动设计](#page-2), [多租户服务、Web UI 与可扩展中间件](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)
- [src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)
- [src/agentscope/app/_tools/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py)
- [src/agentscope/app/_tools/_agent_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_agent_create.py)
- [src/agentscope/app/_tools/_team_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py)
- [src/agentscope/agent/_config.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)
- [src/agentscope/embedding/_embedding_model_card.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/embedding/_embedding_model_card.py)
- [src/agentscope/embedding/_ollama/_model.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/embedding/_ollama/_model.py)
- [src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)
- [src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)
- [src/agentscope/middleware/_tracing/_converter.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py)
- [src/agentscope/app/middleware/_tool_offload_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py)
- [scripts/model_examples/README.md](https://github.com/agentscope-ai/agentscope/blob/main/scripts/model_examples/README.md)
- [README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
</details>

# 模型集成、工具与技能

## 1. 概述

在 AgentScope 中，"模型集成"、"工具（Tool）"与"技能（Skill）"共同构成了 Agent 与外部世界交互的三层抽象：模型负责推理，工具负责动作执行，技能则通过可加载的领域知识（`SKILL.md`）来约束执行规范。这三者通过统一的 `Toolkit` 容器在 FastAPI 服务装配阶段被绑定到每个 `(agent, session)` 对上，从而保证一次对话回合（chat turn）拥有完整且一致的执行环境。

社区中关于 [issue #1453](https://github.com/agentscope-ai/agentscope/issues/1453) 的讨论——"Agent 未读取 SKILL.md 而直接调用通用工具"——正反映了工具与技能之间的职责边界：技能应作为规范文档被加载并约束 Agent 行为，而不是被当作普通工具函数去执行。

资料来源：[src/agentscope/app/_service/_toolkit.py:21-43]()，[src/agentscope/app/_tools/__init__.py:1-25]()。

## 2. 模型集成

### 2.1 聊天模型与嵌入模型

AgentScope 支持多提供商聊天模型（DashScope、OpenAI、DeepSeek、Gemini、Moonshot、xAI、Ollama 等）。每个提供商的接入凭证通过环境变量注入，例如 `DASHSCOPE_API_KEY`、`OPENAI_API_KEY` 等（[scripts/model_examples/README.md:1-40]()）。Ollama 不需要 API Key，只需本地启动服务。

嵌入模型（Embedding Model）使用独立的 `EmbeddingModelCard` 描述，其 `output_types` 字段使用 `application/x-embedding` 表示产出稠密向量。`parameter_schema` 由 `Parameters` 内嵌类 + YAML `parameter_overrides` 组合而成，用于向前端暴露可调参数（[src/agentscope/embedding/_embedding_model_card.py:11-55]()）。例如 Ollama 嵌入模型 `OllamaEmbeddingModel` 继承通用的批处理与重试逻辑，支持 `nomic-embed-text`、`mxbai-embed-large` 等本地模型（[src/agentscope/embedding/_ollama/_model.py:1-35]()）。

### 2.2 模型与中间件协作

聊天模型并非孤立使用，而是被多个中间件包装。`ReplyBudgetControlMiddleware` 按 `input_token_weight * input_tokens + output_token_weight * output_tokens` 的加权公式跟踪单次回复的累计 token 消耗，达到预算后注入 `<system-reminder>` 提示并强制 `tool_choice="none"`（[src/agentscope/middleware/_budget.py:1-55]()）。`Mem0Middleware` 接受 `static_control` / `agent_control` / `both` 三种模式，其中 `agent_control` / `both` 模式会把 `search_memory` / `add_memory` 工具的说明以 Markdown 形式拼接到系统提示中（[src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py:1-55]()）。

## 3. 工具系统

### 3.1 工具的装配

`get_toolkit` 是单次对话回合的工具装配入口，它按固定顺序把以下来源的工具集中到一个 `Toolkit` 中：

1. **工作区内置工具**（Bash / Read / Write / Grep 等）
2. **任务规划工具**（`TaskCreate` / `TaskList` / `TaskGet` / `TaskUpdate`）
3. **后台任务控制**（`ToolStop`）
4. **调度控制**（`ScheduleCreate` / `ScheduleView` / `ScheduleDelete` / `ScheduleList`，仅当 session 配置了模型时挂载）
5. **团队工具**——根据 `agent_record.source` 内联选择：worker (`"team"`) 仅获得 `TeamSay`；其余来源获得 `TeamCreate / AgentCreate / TeamSay / TeamDelete` 的完整套件
6. **调用方提供的扩展**（`extra_factory`）

工作区中的技能和 MCP 配置则作为 `Toolkit` 的 `skills_or_loaders` 与 `mcps` 参数挂入（[src/agentscope/app/_service/_toolkit.py:21-100]()）。

### 3.2 工具可见性规则

`source='user'` 的 Agent 始终看到完整的 leader 侧工具集，而不论其当前是否真的领导一个团队。每个工具在 `__call__` 时通过 storage 实时检查前置条件并清晰报错——例如 `TeamCreate` 会先确认 session 未绑定到任何 team，否则提示需要先调用 `TeamDelete`（[src/agentscope/app/_tools/_team_create.py:1-55]()）。`AgentCreate` 则把 worker 加入当前团队，其默认模板 `DEFAULT_SUB_AGENT_TEMPLATE` 提供了通用的系统提示模板，定义了成员如何通过 `TeamSay` 与领导对话（[src/agentscope/app/_tools/_agent_create.py:1-60]()）。

### 3.3 后台工具与提示注入

当工具被标记为后台执行时，`_ToolOffloadMiddleware` 会在工具完成后构造 `<system-notification>` 提示块，通过 `MessageBus.inbox_push` + `enqueue_wakeup` 把结果推回 session inbox，再由 `InboxMiddleware` 在下一轮推理中排入上下文（[src/agentscope/app/middleware/_tool_offload_middleware.py:1-50]()）。

## 4. 技能系统与可观测性

技能（Skill）通过 `Toolkit.skills_or_loaders` 参数接入，加载后的 `SKILL.md` 文档会被注入到 Agent 的系统提示，从而为特定任务提供规范约束。社区讨论 [issue #1453](https://github.com/agentscope-ai/agentscope/issues/1453) 中的"动态加载并严格按 SKILL.md 执行"流程，正是技能系统与意图识别协同的设计目标；若 Agent 跳过 `SKILL.md` 直接调用通用工具（如 `execute_shell_command`），说明意图识别未正确路由到对应技能文档，这是装配阶段需要排查的方向。

`ReActConfig` 控制推理-行动循环：`max_iters` 限制单次回复最大迭代次数，`stop_on_reject=True` 时遇到工具调用被拒绝即停止推理并等待外部交互（[src/agentscope/agent/_config.py:1-25]()）。

可观测性方面，`middleware/_tracing/_converter.py` 负责把 `ContentBlock` 转换为 OpenTelemetry GenAI part 格式，支持 `image` / `audio` / `video` / `unknown` 四种 modality 派生（[src/agentscope/middleware/_tracing/_converter.py:1-45]()）。

## 5. 端到端流程

下图展示了从 FastAPI 启动到单次 chat 回合中，模型、工具与技能的协作关系：

```mermaid
flowchart TD
    A[create_app: FastAPI 工厂] --> B[get_toolkit 装配]
    B --> C1[工作区内置工具]
    B --> C2[Task 系列 + Schedule 工具]
    B --> C3[Team 工具 by source]
    B --> C4[skills_or_loaders]
    B --> C5[mcps]
    B --> D[Toolkit 实例]
    D --> E[Agent 推理循环 ReActConfig]
    E --> F[ChatModel + Middleware]
    F --> G[工具调用 / 技能文档约束]
    G --> H[ToolResult → 上下文]
    H --> I[回复结束 ReplyEndEvent]
```

## 6. 常见注意事项

| 现象 | 根因 | 参考 |
| --- | --- | --- |
| `Toolkit` 中缺少 `Schedule*` 工具 | 当前 session 未配置模型 | [src/agentscope/app/_service/_toolkit.py:55-58]() |
| `TeamCreate` 报错"session already in team" | session 已绑定 team，需先 `TeamDelete` | [src/agentscope/app/_tools/_team_create.py:1-55]() |
| Agent 忽略 SKILL.md 直接调用通用工具 | 意图识别未路由到对应技能；需检查 `skills_or_loaders` 装配 | [issue #1453](https://github.com/agentscope-ai/agentscope/issues/1453) |
| 嵌入模型参数面板缺失字段 | YAML `parameter_overrides` 未声明 | [src/agentscope/embedding/_embedding_model_card.py:11-55]() |
| ripgrep 安装时触发本地编译 | ripgrep 是代码搜索等工具的硬依赖 | [issue #1660](https://github.com/agentscope-ai/agentscope/issues/1660) |

## 7. See Also

- [AgentScope README](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- 中间件体系：Budget / Mem0 / Tracing
- 团队协作：`TeamCreate` / `AgentCreate` / `TeamSay` / `TeamDelete`

---

<a id='page-4'></a>

## 多租户服务、Web UI 与可扩展中间件

### 相关页面

相关主题：[项目总览与架构](#page-1), [模型集成、工具与技能](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agentscope/app/_app.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py)
- [src/agentscope/app/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/__init__.py)
- [src/agentscope/app/_service/_toolkit.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py)
- [src/agentscope/app/_tools/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py)
- [src/agentscope/app/_tools/_team_create.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py)
- [src/agentscope/app/_router/_agent.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_router/_agent.py)
- [src/agentscope/app/middleware/_tool_offload_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py)
- [src/agentscope/middleware/__init__.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/__init__.py)
- [src/agentscope/middleware/_budget.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py)
- [src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py)
- [src/agentscope/middleware/_tracing/_converter.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py)
- [src/agentscope/agent/_config.py](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py)
- [README.md](https://github.com/agentscope-ai/agentscope/blob/main/README.md)
- [scripts/model_examples/README.md](https://github.com/agentscope-ai/agentscope/blob/main/scripts/model_examples/README.md)
</details>

# 多租户服务、Web UI 与可扩展中间件

AgentScope 提供了一整套面向生产部署的多租户 FastAPI 服务、配套 Web UI，以及高度可扩展的中间件体系。本页围绕 `agentscope.app` 与 `agentscope.middleware` 子系统，介绍整体架构、Toolkit 组装逻辑、团队协作工具与常用中间件。

## FastAPI 多租户多会话服务

`create_app` 是 AgentScope 服务化部署的单一入口，封装了路由、生命周期、资源注入等所有内置组件，可独立运行，也可挂载到现有 FastAPI 应用下 资料来源：[src/agentscope/app/_app.py:30-60](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py#L30-L60)。`extra_middlewares` 参数允许在不动核心代码的前提下插入自定义 ASGI 中间件，从而满足鉴权、限流、审计等横切需求。

服务通过 `StorageBase` 持久化代理、会话与团队记录，通过 `MessageBus` 解耦跨会话消息传输与持久化后端（典型为 SQL 持久化 + Redis 传输），并通过 `WorkspaceManagerBase` 为每个会话动态解析工作区 资料来源：[src/agentscope/app/_app.py:60-90](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_app.py#L60-L90)。两个后端生命周期都由 `__aenter__` / `__aexit__` 统一管理，避免资源泄漏。

Web UI 由 `examples/web_ui` 下的独立前端项目提供，`v2.0.2` 起新增了 CI 格式与构建检查以保证前端质量 资料来源：[README.md:60-120](https://github.com/agentscope-ai/agentscope/blob/main/README.md#L60-L120)。

## Toolkit 组装与会话生命周期

每次会话回合都会调用 `get_toolkit` 重新组装工具集，按以下顺序注入 资料来源：[src/agentscope/app/_service/_toolkit.py:30-80](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py#L30-L80)：

1. 工作区内建工具（Bash / Read / Write / Grep 等）
2. 计划任务工具（`TaskCreate` / `TaskList` / `TaskGet` / `TaskUpdate`）
3. 后台任务控制工具（`ToolStop`，由 `BackgroundTaskManager.list_tools` 提供）
4. 调度控制工具（`Schedule*` 系列），仅在会话配置了模型时附加
5. 团队工具——按 `agent_record.source` 字段选择：`source='team'` 的 worker 仅获得 `TeamSay`；其他源则获得完整领导侧工具集（`TeamCreate / AgentCreate / TeamSay / TeamDelete`）
6. 调用方通过 `extra_factory` 注入的扩展工具

工作区的 skills 与 MCPs 会转换为 Toolkit 的 `skills_or_loaders` 与 `mcps` 参数，从而支持按需加载 `SKILL.md` 与外部工具 资料来源：[src/agentscope/app/_service/_toolkit.py:80-120](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_service/_toolkit.py#L80-L120)。社区中关于 "AgentScope SKILL 执行问题" 的讨论（Issue #1453）正是涉及该加载路径与意图识别的衔接。

## 团队协作与子代理模板

团队工具是 App 层的标志性能力，区别于工作区内置工具的两大特征是：构造期绑定 `StorageBase + MessageBus` 与请求级 `user_id / session_id / agent_id`，并由 `agent.source` 决定可见性 资料来源：[src/agentscope/app/_tools/__init__.py:1-30](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/__init__.py#L1-L30)。`TeamCreate` 在创建前会校验当前会话是否已绑定团队，重复创建会返回明确错误状态 资料来源：[src/agentscope/app/_tools/_team_create.py:80-130](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_tools/_team_create.py#L80-L130)。

`SubAgentTemplate` 允许服务部署者预定义可被 `AgentCreate` 调用的子代理蓝图，通过 `custom_subagent_templates` 注入到 `create_app` 中，并在 `v2.0.2` 起正式支持自定义模板 资料来源：[README.md:120-180](https://github.com/agentscope-ai/agentscope/blob/main/README.md#L120-L180)。

## 可扩展中间件系统

中间件是 AgentScope 横切关注点的统一抽象，通过 `MiddlewareBase` 钩子嵌入到代理的回复循环中。`agentscope.middleware` 内置以下常用中间件 资料来源：[src/agentscope/middleware/__init__.py:1-20](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/__init__.py#L1-L20)：

| 中间件 | 作用 |
|---|---|
| `ReplyBudgetControlMiddleware` | 按加权 token 用量限制单次回复成本，超限注入提示并禁用工具调用 资料来源：[src/agentscope/middleware/_budget.py:1-40](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_budget.py#L1-L40) |
| `Mem0Middleware` | 集成 mem0 长记忆，支持 `static_control / agent_control / both` 三种注入模式，要求非空 `user_id` 资料来源：[src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py:40-80](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py#L40-L80) |
| `TracingMiddleware` | 将 `ContentBlock` 转换为 OpenTelemetry GenAI 规范的多模态 span 资料来源：[src/agentscope/middleware/_tracing/_converter.py:1-50](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/middleware/_tracing/_converter.py#L1-L50) |
| `TTSMiddleware` | 流式语音合成，配合 v2.0.2 的 DashScope/OpenAI omni 实时字幕 资料来源：[README.md:180-220](https://github.com/agentscope-ai/agentscope/blob/main/README.md#L180-L220) |

App 层还内置了 `_tool_offload_middleware`，在长时工具完成时把结果推入 `MessageBus` 的 inbox 并触发 wakeup，让空闲会话被自动唤醒 资料来源：[src/agentscope/app/middleware/_tool_offload_middleware.py:60-120](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/middleware/_tool_offload_middleware.py#L60-L120)。社区 RFC #1474（VantaGrid）正是基于这种 "可插拔记忆中间件" 形态提出确定性共享记忆方案。

## 配置与扩展点

代理与上下文的核心配置均由 Pydantic 模型描述，例如 `ContextConfig.compression_summary_model` 定义压缩模型输出结构，`ReActConfig.max_iters` 与 `stop_on_reject` 控制推理-行动循环边界，`ModelConfig` 抽象不同模型提供方参数 资料来源：[src/agentscope/agent/_config.py:60-140](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/agent/_config.py#L60-L140)。这些 schema 会经由 `/agents` 路由反射给前端用于动态生成表单 资料来源：[src/agentscope/app/_router/_agent.py:40-80](https://github.com/agentscope-ai/agentscope/blob/main/src/agentscope/app/_router/_agent.py#L40-L80)，且其 `format: textarea` 提示会被 Schema 驱动的 UI 渲染器识别为多行输入。

模型提供方覆盖 OpenAI、Anthropic、DashScope、DeepSeek、Gemini、Moonshot、xAI 与 Ollama 等 资料来源：[scripts/model_examples/README.md:1-40](https://github.com/agentscope-ai/agentscope/blob/main/scripts/model_examples/README.md#L1-L40)。

## See Also

- 代理与工具系统：见 [src/agentscope/agent](https://github.com/agentscope-ai/agentscope/tree/main/src/agentscope/agent) 与 [src/agentscope/tool](https://github.com/agentscope-ai/agentscope/tree/main/src/agentscope/tool)
- Web UI 前端：[examples/web_ui](https://github.com/agentscope-ai/agentscope/tree/main/examples/web_ui)
- 中间件扩展：见 `MiddlewareBase` 钩子与 `extra_middlewares` 注入点

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：agentscope-ai/agentscope

摘要：发现 6 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

## 1. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/agentscope-ai/agentscope | README/documentation is current enough for a first validation pass.

## 2. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/agentscope-ai/agentscope | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/agentscope-ai/agentscope | no_demo; severity=medium

## 4. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/agentscope-ai/agentscope | no_demo; severity=medium

## 5. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/agentscope-ai/agentscope | issue_or_pr_quality=unknown

## 6. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/agentscope-ai/agentscope | release_recency=unknown

<!-- canonical_name: agentscope-ai/agentscope; human_manual_source: deepwiki_human_wiki -->
