AS AgentScopeAPI 手册 / API Reference
包package Guide

架构Architecture

本页说明两件事:框架本身如何分层与运行,以及这本手册如何从官方源码静态生成。前者帮助你定位扩展点,后者解释了为什么每个签名都能追溯到具体版本。

1. 两个版本,一套概念模型

Python 与 Java 版不是逐行翻译,而是共享同一套概念模型的不同运行时实现:

概念 Python 2.0.11 Java 2.0.4
消息 agentscope.message.Msg + 内容块 io.agentscope.core.message.Msg + 内容块
模型 ChatModelBase 与各供应商适配器 Model 与 agentscope-extensions-model-*
智能体 agentscope.agent.Agent io.agentscope.core.ReActAgent
工具 Toolkit + FunctionTool + MCP + 技能 Toolkit + @Tool + MCP + SkillBox
状态 AgentState(由调用方持久化) AgentState + AgentStateStore
扩展 中间件、事件流 中间件、Hook、Reactor 事件
服务化 agentscope.app Spring Boot starters、A2A、AG-UI

共享概念带来可迁移性,但两版的并发模型不同:Python 基于 asyncio,Java 基于 Project Reactor。阅读 API 时要注意返回类型:Python 的 async def 对应 Java 的 Mono/Flux。

2. Python 包的层次

agentscope 的 39 个公开包可以分成四组:

核心运行时

  • agentscope.agent — Agent、A2AAgent、RealtimeAgent 与四个配置对象(ModelConfig、ContextConfig、ReActConfig、InjectionConfig);
  • agentscope.message — Msg、UserMsg 与全部内容块;
  • agentscope.model — 模型基类与供应商适配器;
  • agentscope.formatter — 各协议的消息格式化器;
  • agentscope.tool — Toolkit、FunctionTool、内置工具与 MCP;
  • agentscope.state — 会话状态与回复/工具/任务上下文;
  • agentscope.middleware — 中间件基类与内置中间件;
  • agentscope.event — 事件类型;
  • agentscope.permission — 权限引擎与规则。

能力组件

  • agentscope.rag、agentscope.embedding — 解析、切块、嵌入、向量检索;
  • agentscope.mcp、agentscope.skill、agentscope.sop — 外部工具、技能与标准作业流程;
  • agentscope.workspace — 本地/容器/云端隔离工作区;
  • agentscope.realtime、agentscope.asr、agentscope.tts、agentscope.classifier — 实时语音、识别、合成与分类模型。

应用层

  • agentscope.app 及其子包 — 频道(钉钉、飞书、Discord 等)、消息总线、存储、知识库管理、工作区管理、访问策略。

开发体验

  • agentscope.console、agentscope.tui — 控制台渲染与终端 UI;
  • agentscope.exception、agentscope.types — 错误与公共类型。

依赖方向:能力组件依赖核心运行时,应用层依赖能力组件,核心运行时不知道应用层的存在。

3. Java 构件的分类

Java 版把"核心"与"可选能力"拆成 Maven 构件。本手册覆盖 96 个含源码的官方构件,分为:

  • core — agentscope-core,包含智能体、消息、模型 SPI、工具、状态、记忆、RAG 抽象、权限、钩子、追踪;
  • extension — agentscope-extensions-*:模型供应商(OpenAI、DashScope、Anthropic、Gemini、Ollama 等)、RAG 存储(Milvus、Qdrant、PgVector、Elasticsearch)、A2A、AG-UI、沙箱、频道、技能仓库等;
  • starter — *-spring-boot-starter:把模型、智能体或协议自动装配到 Spring Boot;
  • runtime — agentscope-runtime-* 与 1.x 旧版运行时,保留在独立分组;
  • integration — agentscope-harness、agentscope-copilotkit、agentscope-codingagent 等集成构件。

聚合构件 agentscope 的源码 jar 会重复所有模块,因此不作为"类归属"来源;当同一个全限定类名出现在多个 runtime 构件中时,本手册按"最具体构件 + 与包名最匹配"的规则去重,共解决 126 个重复类。

4. 一次回复的生命周期

以 Java 的 ReActAgent.call 为例(Python 的 reply 结构相同):

call(msgs, runtimeContext)
  │
  ├─ 解析/创建 AgentState(按 userId + sessionId)
  ├─ 合并系统提示、历史上下文、新输入
  ├─ 构建工具 schema(只包含激活的工具组)
  ├─ 注入中间件链
  │
  ├─ loop: iter = 0..maxIters
  │    ├─ Formatter: Msg[] → 供应商请求
  │    ├─ Model: 流式/非流式调用
  │    ├─ Accumulator: 增量 → 完整思考/文本/工具调用
  │    ├─ 若存在工具调用:
  │    │    ├─ PermissionEngine 检查
  │    │    ├─ 执行工具(可并发、可流式)
  │    │    ├─ 生成 ToolResultBlock
  │    │    └─ 追加到上下文,继续循环
  │    └─ 否则: 生成最终 Msg,结束
  │
  ├─ 上下文压缩(达到阈值时)
  ├─ 持久化 AgentState(如果配置了 store)
  └─ 返回 Msg / 发出事件

关键设计点:

  • 流式与非流式共享同一执行路径。call 只是把 Flux 聚合为 Mono,不存在两套逻辑。
  • 工具调用是上下文的一部分。工具结果以 ToolResultBlock 写回消息列表,而不是旁路缓存,因此压缩、持久化、重放都能看到完整轨迹。
  • 中断是可恢复状态。中断时保存 reply_context 与未完成的工具调用;恢复时从断点继续。
  • 并发按会话串行。共享 (userId, sessionId) 的调用会串行化,不同会话可以并发;RuntimeContext 不是共享可变状态。

5. 上下文压缩

当 token 数逼近模型窗口时,ContextConfig / AutoContextConfig 触发压缩:

  1. 保留系统提示、最近的若干轮消息、未完成的工具调用与任务状态;
  2. 让模型生成结构化摘要(任务、当前状态、关键发现、下一步、需保留的上下文);
  3. 用摘要替换旧消息,并记录压缩事件;
  4. 如果摘要失败,按配置回退为截断或抛出错误。

这就是为什么 AgentState 同时保存 context 和 summary:前者是当前窗口,后者是历史压缩结果。

6. 扩展点

扩展点 Python Java
模型供应商 继承 ChatModelBase 实现 Model 或 ModelProvider SPI
消息协议 继承 FormatterBase 实现 Formatter
工具 FunctionTool、实现 ToolBase @Tool、实现 AgentTool
工具执行环境 ToolContext / workspace ToolExecutionContext
长期记忆 记忆中间件 实现 LongTermMemory
状态存储 自行序列化 AgentState 实现 AgentStateStore
行为拦截 MiddlewareBase MiddlewareBase / Hook
多智能体 TeamPipeline / GoalPipeline SubAgentTool、A2A
权限 PermissionEngine PermissionEngine
沙箱 agentscope.workspace sandbox 扩展构件

新增扩展时优先实现接口/基类,不要修改核心类;核心运行时只通过抽象依赖这些能力。

7. 版本与来源策略

本手册固定以下来源,所有页面都标注了源文件与行号:

  • Python 2.0.11:PyPI 官方 wheel,不导入包,直接用 ast 解析;
  • Java 2.0.4:Maven Central 的 -sources.jar,使用 JDK Compiler Tree API 解析,--release 21、-proc:none,不解析第三方类路径;
  • 预览与旧版:2.1.0-BETA1、2.0.0-RC4 等预览构件单独标记;1.x runtime 归入 legacy 分组;
  • 排除项:示例、测试、构建插件与聚合 jar。

静态抽取的边界:

  • 只解析源码中显式声明的内容,不执行代码、不解析依赖中的父类(外部基类以文本显示);
  • Java 记录组件通过解析 record header 获得,并在缺少显式访问器时合成访问器(页面中标记为 generated);
  • 注解元素的默认值、泛型边界、导入信息均来自语法树;
  • 文档只保留 Javadoc/docstring 的结构化字段(摘要、参数、返回、异常、示例、弃用等),不还原 HTML 样式。

8. 手册的生成流水线

官方 wheel / sources.jar
        │
        ├─ extract_python.py  → inventory/python.json
        └─ extract_java.py    → inventory/java.json(96 构件合并去重)
                                   │
translations/*.zh.json ────────────┤
        │                          ▼
        └───────────────  sitegen(pysite / javasite / build)
                                   │
                    ┌──────────────┼──────────────┐
                    ▼              ▼              ▼
                 API 页面        指南/覆盖率      search-index.json
                                   │
                              check_links.py

生成器不依赖数据库或在线服务:清单是 JSON,翻译是稳定 ID 的 JSON,输出是纯静态 HTML/CSS/JS。因此构建可复现,站点可离线托管,搜索也不需要后端。

9. 站点的三种语言模式

语言模式由 html[data-lang] 控制,内容块在生成时就带有 .lang-zh / .lang-en 标记:

  • 中英混合:中文在上、英文在下,英文使用弱化颜色;
  • 纯中文:只显示中文;缺失翻译时回退英文并加 EN 标记;
  • 纯英文:隐藏中文块,保留英文签名与文档。

模式选择写入 localStorage,在首屏渲染前由内联脚本应用,避免闪烁。API 签名、代码块、包名、类名永远保留英文原文,不参与翻译。

This page covers two things: how the framework is layered and executed, and how this manual is generated statically from official sources. The first helps you find extension points; the second explains why every signature traces back to a pinned version.

1. Two editions, one conceptual model

The Python and Java editions are not line-by-line translations. They are different runtimes sharing one conceptual model:

Concept Python 2.0.11 Java 2.0.4
Message agentscope.message.Msg + content blocks io.agentscope.core.message.Msg + content blocks
Model ChatModelBase and vendor adapters Model and agentscope-extensions-model-*
Agent agentscope.agent.Agent io.agentscope.core.ReActAgent
Tools Toolkit + FunctionTool + MCP + skills Toolkit + @Tool + MCP + SkillBox
State AgentState (persisted by the caller) AgentState + AgentStateStore
Extension middleware, event stream middleware, Hook, Reactor events
Serving agentscope.app Spring Boot starters, A2A, AG-UI

The shared model aids migration, but concurrency differs: Python is asyncio-based, Java is Project Reactor-based. Watch return types when reading the API: a Python async def corresponds to Java Mono/Flux.

2. Python package layers

The 39 public agentscope packages fall into four groups.

Core runtime

  • agentscope.agent — Agent, A2AAgent, RealtimeAgent and four config objects (ModelConfig, ContextConfig, ReActConfig, InjectionConfig);
  • agentscope.message — Msg, UserMsg and all content blocks;
  • agentscope.model — model base classes and vendor adapters;
  • agentscope.formatter — protocol-specific message formatters;
  • agentscope.tool — Toolkit, FunctionTool, built-in tools and MCP;
  • agentscope.state — session state and reply/tool/task contexts;
  • agentscope.middleware — middleware base and built-ins;
  • agentscope.event — event types;
  • agentscope.permission — permission engine and rules.

Capabilities

  • agentscope.rag, agentscope.embedding — parsing, chunking, embedding, vector retrieval;
  • agentscope.mcp, agentscope.skill, agentscope.sop — external tools, skills and standard operating procedures;
  • agentscope.workspace — local/container/cloud isolated workspaces;
  • agentscope.realtime, agentscope.asr, agentscope.tts, agentscope.classifier — realtime voice, recognition, synthesis and classification models.

Application layer

  • agentscope.app and its subpackages — channels (DingTalk, Feishu, Discord, ...), message bus, storage, knowledge-base management, workspace management and access policies.

Developer experience

  • agentscope.console, agentscope.tui — console rendering and terminal UI;
  • agentscope.exception, agentscope.types — errors and shared types.

Dependency direction: capabilities depend on the core runtime, the application layer depends on capabilities, and the core runtime knows nothing about the application layer.

3. Java artifact taxonomy

Java splits core and optional capabilities into Maven artifacts. This manual covers 96 official source-bearing artifacts:

  • core — agentscope-core: agents, messages, model SPI, tools, state, memory, RAG abstractions, permissions, hooks, tracing;
  • extension — agentscope-extensions-*: model providers (OpenAI, DashScope, Anthropic, Gemini, Ollama, ...), RAG stores (Milvus, Qdrant, PgVector, Elasticsearch), A2A, AG-UI, sandboxes, channels and skill repositories;
  • starter — *-spring-boot-starter: auto-configuration for models, agents or protocols in Spring Boot;
  • runtime — agentscope-runtime-* and the 1.x line, kept in a separate group;
  • integration — agentscope-harness, agentscope-copilotkit, agentscope-codingagent and similar.

The umbrella agentscope source jar duplicates every module, so it is not used as an ownership source. When one fully-qualified class appears in several runtime artifacts, the manual de-duplicates by "most specific artifact + best package match", resolving 126 duplicates.

4. Lifecycle of one reply

Using Java's ReActAgent.call (Python's reply has the same shape):

call(msgs, runtimeContext)
  │
  ├─ resolve/create AgentState (by userId + sessionId)
  ├─ merge system prompt, history, new input
  ├─ build tool schemas (active tool groups only)
  ├─ inject the middleware chain
  │
  ├─ loop: iter = 0..maxIters
  │    ├─ Formatter: Msg[] → vendor request
  │    ├─ Model: streaming or non-streaming call
  │    ├─ Accumulator: deltas → complete thinking/text/tool calls
  │    ├─ if tool calls exist:
  │    │    ├─ PermissionEngine check
  │    │    ├─ execute tools (parallel and streaming capable)
  │    │    ├─ produce ToolResultBlock
  │    │    └─ append to context, continue
  │    └─ else: produce final Msg, stop
  │
  ├─ context compression (when threshold is crossed)
  ├─ persist AgentState (if a store is configured)
  └─ return Msg / emit events

Key design points:

  • Streaming and non-streaming share one execution path. call simply aggregates the Flux into a Mono; there are not two implementations.
  • Tool calls are part of the context. Results are written back as ToolResultBlocks rather than cached on the side, so compression, persistence and replay all see the full trajectory.
  • Interruption is recoverable state. Interruption saves reply_context and pending tool calls; resuming continues from the breakpoint.
  • Concurrency is serialized per session. Calls sharing (userId, sessionId) are serialized while distinct sessions run concurrently. RuntimeContext is not shared mutable state.

5. Context compression

When tokens approach the model window, ContextConfig / AutoContextConfig triggers compression:

  1. Keep the system prompt, the most recent turns, pending tool calls and task state;
  2. Ask the model for a structured summary (task, current state, key findings, next steps, context to preserve);
  3. Replace older messages with the summary and record a compression event;
  4. If summarization fails, fall back to truncation or raise, depending on configuration.

This is why AgentState holds both context and summary: the former is the current window, the latter is the compressed history.

6. Extension points

Extension point Python Java
Model provider subclass ChatModelBase implement Model or the ModelProvider SPI
Message protocol subclass FormatterBase implement Formatter
Tool FunctionTool, implement ToolBase @Tool, implement AgentTool
Tool execution env ToolContext / workspace ToolExecutionContext
Long-term memory memory middleware implement LongTermMemory
State store serialize AgentState yourself implement AgentStateStore
Behavior interception MiddlewareBase MiddlewareBase / Hook
Multi-agent TeamPipeline / GoalPipeline SubAgentTool, A2A
Permission PermissionEngine PermissionEngine
Sandbox agentscope.workspace sandbox extensions

Prefer implementing interfaces/base classes over modifying core classes. The runtime depends on these capabilities only through abstractions.

7. Version and source policy

This manual pins the following sources and shows file and line numbers on every page:

  • Python 2.0.11: official PyPI wheel, parsed directly with ast without importing the package;
  • Java 2.0.4: -sources.jar from Maven Central, parsed with the JDK Compiler Tree API using --release 21 and -proc:none, without resolving third-party classpaths;
  • Preview and legacy: 2.1.0-BETA1, 2.0.0-RC4 and other previews are marked; 1.x runtime artifacts live in a legacy group;
  • Excluded: examples, tests, build plugins and the umbrella jar.

Limits of static extraction:

  • Only explicit source declarations are parsed; code is not executed and dependency parents are not resolved (external bases appear as text);
  • Java record components come from parsing the record header; missing accessors are synthesized and marked as generated;
  • Annotation defaults, generic bounds and imports come from the syntax tree;
  • Documentation keeps structured Javadoc/docstring fields (summary, params, returns, throws, examples, deprecation) without recreating HTML styling.

8. The manual build pipeline

official wheel / sources.jar
        │
        ├─ extract_python.py  → inventory/python.json
        └─ extract_java.py    → inventory/java.json (96 artifacts merged and deduplicated)
                                   │
translations/*.zh.json ────────────┤
        │                          ▼
        └───────────────  sitegen (pysite / javasite / build)
                                   │
                    ┌──────────────┼──────────────┐
                    ▼              ▼              ▼
                 API pages     guides/coverage   search-index.json
                                   │
                              check_links.py

The generator needs no database or online service: inventories are JSON, translations are stable-ID JSON, and the output is pure static HTML/CSS/JS. Builds are reproducible, the site can be hosted offline, and search needs no backend.

9. Three language modes

Language mode is controlled by html[data-lang]; content blocks are emitted with .lang-zh / .lang-en markers at generation time:

  • Mixed: Chinese on top, English below in a muted color;
  • Chinese-only: Chinese only; missing translations fall back to English with an EN badge;
  • English-only: Chinese blocks are hidden; English signatures and docs remain.

The chosen mode is stored in localStorage and applied by an inline script before first paint to avoid flashing. Signatures, code blocks, package names and type names always stay in English and are never translated.