AS AgentScopeAPI 手册 / API Reference
包package Guide

核心概念Core concepts

AgentScope 不是一个"把提示词包一层"的封装,而是一套围绕 消息、模型、智能体、工具、状态 组织的运行时。理解下面几层之间的关系,比记住某个类的构造参数更重要;每个概念都给出对应的 Python 与 Java API 入口。

1. 分层结构

从下到上,框架可以分成六层:

层 职责 Python Java
消息 统一对话与多模态内容的表示 Msg、TextBlock、ToolCallBlock Msg、TextBlock、ToolUseBlock
模型 供应商适配、流式响应、用量统计 ChatModelBase、OpenAIChatModel Model、OpenAIChatModel
格式化 把统一消息转换成各供应商协议 FormatterBase Formatter
智能体 推理—行动循环、事件、中断、结构化输出 Agent ReActAgent、AgentBase
能力 工具、MCP、技能、RAG、记忆 Toolkit、MCPClient、KnowledgeBase Toolkit、SimpleKnowledge
运行保障 状态、会话、权限、中间件、可观测性 AgentState、MiddlewareBase AgentState、Hook、MiddlewareBase

依赖方向始终向下:智能体依赖模型和工具,模型依赖格式化器,任何一层都不反向依赖智能体。这个约束让模型、工具与存储都可以独立替换。

2. 消息模型

一条消息由 角色、发送者名称 和 内容块列表 组成。内容块是 AgentScope 的核心抽象:文本、思考、工具调用、工具结果、图片/音频/文件都只是不同类型的块。

  • Python 的 Msg 是 Pydantic 模型,content 为 list[ContentBlock]。构造用户消息时用 UserMsg(或直接 Msg(role="user", content=[TextBlock(...)])),它会自动把纯字符串包装成 TextBlock。
  • Java 的 Msg 通过 Msg.builder() 构造,UserMessage、AssistantMessage、SystemMessage、ToolResultMessage 是它的角色子类。Msg.builder().textContent("...") 是写单段文本的快捷方式。

内容块分离带来两个直接好处:

  1. 多模态不需要特殊 API:图片、音频、文件用 DataBlock/ImageBlock 表达,与文本走同一条消息通道。
  2. 流式增量是结构化的:模型返回的思考、文本、工具调用参数分别以块事件下发,UI 可以按块类型渲染,而不是解析字符串。

消息还携带 usage、finished_reason、structured_output、error 等运行元数据。它们不参与模型上下文,但用于计费、可观测性和错误恢复。

3. 模型与格式化器

模型适配器负责 调用供应商 API 并归一化响应;格式化器负责 把 AgentScope 消息翻译成该供应商的请求格式。两者分开,是为了让同一套智能体逻辑在 OpenAI、DashScope、Anthropic、Gemini、Ollama 等协议之间切换时不需要改业务代码。

Python 的 ChatModelBase 定义了 __call__、count_tokens、generate_structured_output 等能力。以 OpenAIChatModel 为例:

from agentscope.credential import OpenAICredential
from agentscope.model import OpenAIChatModel

model = OpenAIChatModel(
    credential=OpenAICredential(api_key="sk-...", base_url=None),
    model="gpt-4o-mini",
    stream=True,
    context_size=128_000,
)

Java 侧 Model 是统一接口,供应商实现位于 agentscope-extensions-model-* 构件。例如 OpenAIChatModel.builder().apiKey(...).modelName(...).build()。

模型层有几个容易忽略的语义:

  • 流式是默认行为。stream=True 时返回增量响应;智能体的 reply_stream/stream 再把这些增量包装成事件。
  • 重试属于模型层。max_retries、retry_delay 在模型适配器内部生效;智能体层的 ModelConfig.max_retries 用于"主模型失败后切换备用模型"的次数,两者不要混淆。
  • 上下文窗口是模型的属性。context_size(Python)或 contextWindowSize(Java)参与上下文压缩阈值计算。

4. ReAct 智能体

ReAct = Reasoning + Acting。一次回复不是一次模型调用,而是一个循环:

  1. 组装系统提示、历史消息、当前输入、工具 schema、结构化输出约束;
  2. 调用模型,流式读取思考/文本/工具调用;
  3. 如果没有工具调用,循环结束,产出最终消息;
  4. 如果有工具调用,按权限策略执行工具,把结果作为 ToolResultBlock 追加到上下文;
  5. 重复 2–4,直到得到最终答案、达到最大迭代次数、被中断或出错。

Python 的 Agent 就是这个循环的默认实现。构造参数把不同关注点拆开:

from agentscope.agent import Agent, ContextConfig, ReActConfig
from agentscope.tool import Toolkit

agent = Agent(
    name="assistant",
    system_prompt="You are a careful engineer.",
    model=model,
    toolkit=Toolkit(),
    react_config=ReActConfig(max_iters=12),          # 循环上限与中断行为
    context_config=ContextConfig(trigger_ratio=0.8), # 上下文压缩
)

对外有三个入口:

  • await agent.reply(msg):返回最终的 Msg;
  • agent.reply_stream(msg):异步生成事件流,适合 UI 增量渲染;
  • await agent.observe(msg):只把消息写入上下文,不触发模型调用,常用于多智能体协作时同步他人发言。

Java 的 ReActAgent 通过 Builder 配置同样的关注点:name、sysPrompt、model、toolkit、maxIters、middlewares、stateStore、permissionContext 等。执行入口是响应式的:

Msg reply = agent.call("Summarize this repository.").block();

call 返回 Mono<Msg>,stream 返回 Flux<Event>。事件类型(思考增量、工具调用、工具结果、回复结束等)定义在 io.agentscope.core.event 包中。

中断与人类确认

工具执行前可以要求人工确认。Python 通过 ToolCallBlock 的状态与事件流中的确认请求表达;Java 通过 RequireUserConfirmEvent、ConfirmResult 以及权限引擎表达。两者都遵循同一个原则:确认是循环中的一等状态,而不是回调里的临时布尔值。中断后恢复时,智能体从保存的状态继续,而不是重放整个对话。

结构化输出

reply(..., structured_schema=Model) / call(..., ResultType.class) 会把输出约束成给定 schema。实现方式不是单纯解析 JSON,而是在循环中注入一个结构化输出工具,模型必须调用它并提供符合 schema 的参数。这样即使模型先说了一段自然语言,最终结构化结果仍然可用。

5. 工具系统

工具是智能体与外部世界交互的唯一通道。Python 的 Toolkit 管理三类能力:

  • 函数工具:用 FunctionTool 包装普通函数,签名和 Google 风格 docstring 会被解析为 JSON Schema;
  • MCP 工具:通过 MCPClient 连接外部 MCP 服务器;
  • 技能:Skill/SkillLoaderBase 提供按需加载的指令与资源。
from agentscope.tool import FunctionTool, Toolkit

def get_weather(city: str) -> str:
    """Return the current weather for a city.

    Args:
        city: The city name.
    """
    return f"{city}: sunny, 24C"

toolkit = Toolkit(tools=[FunctionTool(get_weather)])

Java 的工具通过注解声明,Toolkit.registerTool(Object) 扫描 @Tool 方法,@ToolParam 描述参数。MCP 通过 McpClientBuilder 注册;技能通过 SkillBox 与 AgentSkillRepository 管理。

工具系统还负责:

  • 分组与激活:只把当前激活的工具 schema 发给模型,降低 token 消耗;
  • 并发与只读标记:is_concurrency_safe / readOnly 决定工具能否并行执行;
  • 权限检查:工具调用前经过 PermissionEngine,可以允许、拒绝或要求确认;
  • 流式工具结果:长任务可以边执行边返回 ToolChunk。

6. 状态、记忆与会话

AgentScope 把"一次回复的临时变量"和"需要持久化的会话状态"分开:

  • Python 的 AgentState 保存 session_id、context、reply_context、tool_context、tasks_context、middle_context 等。它可以直接序列化,由你的存储层负责读写。
  • Java 的 AgentState 结构类似,并配套 AgentStateStore 抽象,内置 InMemoryAgentStateStore、JsonFileAgentStateStore、MySQL/Redis 实现。

两个容易混淆的概念:

  • 上下文(context) 是发给模型的消息列表,会随对话增长,需要压缩;
  • 记忆(memory) 是跨会话保留的信息。Python 通过 AgenticMemoryMiddleware、Mem0Middleware、ReMeMiddleware 等中间件接入;Java 有独立的 Memory、LongTermMemory 抽象与 AgentStateMemoryView。

上下文压缩由 ContextConfig(Python)/ AutoContextConfig(Java)控制。达到阈值后,框架会生成结构化摘要替换旧消息,并保留工具调用、任务状态等关键信息。压缩本身是一次模型调用,因此也会出现在事件流中。

7. 中间件与钩子

两者都是扩展点,但定位不同:

  • 中间件(middleware) 包裹"模型调用 / 推理 / 行动"等阶段,可以修改输入输出、短路执行、注入额外上下文。Python 的 MiddlewareBase 与 Java 的 MiddlewareBase 都属于这一层。
  • 钩子(hook) 监听循环中的事件,用于观测、记录、干预。Java 的 Hook 体系(PreReasoningEvent、PostActingEvent 等)是主要实现;Python 的事件流承担了类似职责。

选择原则:需要 改变行为 用中间件;需要 观察或记录 用钩子/事件。两者都不应该持有跨请求的可变全局状态,因为同一个智能体可能并发处理多个会话。

8. 多智能体与工作流

Python 提供 TeamPipeline 与 GoalPipeline:前者按团队成员分工协作,后者围绕目标驱动多轮执行。智能体之间通过 observe 同步消息,通过共享的 AgentState 或外部存储协调状态。

Java 的多智能体更偏向"工具化":SubAgentTool 把一个智能体暴露成另一个智能体的工具;A2A 扩展把远程智能体接入为 A2aAgent;AG-UI 扩展负责把智能体事件流适配到前端协议。

9. RAG 与知识库

RAG 在 AgentScope 中被拆成可替换的四段:

  1. 解析:PDF、Word、PPT、Excel、图片、纯文本 → 文档;
  2. 切块:按 token、段落或章节切分;
  3. 嵌入:EmbeddingModelBase / EmbeddingModel;
  4. 检索:向量库(Milvus、Qdrant、Elasticsearch、MongoDB、内存等)。

Python 的 KnowledgeBase 把嵌入模型和向量集合绑定在一起,提供 insert_document、search、delete_document 等操作。Java 对应 SimpleKnowledge,配合 Reader 与 VDBStoreBase。智能体侧通过 RAGMiddleware(Python)或 GenericRAGHook(Java)把检索结果注入上下文。

10. 技能、MCP、权限与工作区

  • 技能(skill):一段带元数据的指令与资源包,按需加载,避免把所有领域知识塞进系统提示。Python 用 LocalSkillLoader;Java 用 FileSystemSkillRepository、ClasspathSkillRepository、GitSkillRepository。
  • MCP:Model Context Protocol 客户端。Python 的 MCPClient 支持 stdio 与 HTTP;Java 的 McpClientBuilder 支持同步/异步客户端。
  • 权限:PermissionEngine 根据工具、路径、模式决定允许/拒绝/询问。两版都支持工作目录白名单与危险路径检查。
  • 工作区:Python 的 LocalWorkspace、DockerWorkspace、E2BWorkspace 等提供隔离的执行环境;Java 侧对应 sandbox 扩展构件。

11. 可观测性与部署

  • Python 的 TracingMiddleware、事件流与 agentscope.tui 控制台渲染器;
  • Java 的 OtelTracingMiddleware、JsonlTraceExporter 与 Reactor 的 Flux<Event>;
  • 部署:Python 的 agentscope.app 提供 Web 服务、频道、存储与知识库管理;Java 提供 Spring Boot starters、A2A server、AG-UI 运行时。

理解了这十一块,再看 API 页就不会迷失:每个类都属于某一层,每个方法都是该层契约的一部分。接下来可以进入 Python 快速开始 或 Java 快速开始。

AgentScope is not a thin prompt wrapper. It is a runtime organized around messages, models, agents, tools and state. Understanding how these layers relate matters more than memorizing constructor parameters; each concept below points to its Python and Java API entry points.

1. Layers

From bottom to top:

Layer Responsibility Python Java
Messages Unified conversational and multimodal content Msg, TextBlock, ToolCallBlock Msg, TextBlock, ToolUseBlock
Models Vendor adapters, streaming, usage ChatModelBase, OpenAIChatModel Model, OpenAIChatModel
Formatting Convert unified messages to vendor protocols FormatterBase Formatter
Agents Reason-act loop, events, interruption, structured output Agent ReActAgent, AgentBase
Capabilities Tools, MCP, skills, RAG, memory Toolkit, MCPClient, KnowledgeBase Toolkit, SimpleKnowledge
Operations State, sessions, permissions, middleware, observability AgentState, MiddlewareBase AgentState, Hook, MiddlewareBase

Dependencies always point downward. Agents depend on models and tools, models depend on formatters, and no layer depends back on agents. That constraint keeps models, tools and stores independently replaceable.

2. Messages

A message has a role, a sender name and a list of content blocks. Content blocks are the central abstraction: text, thinking, tool calls, tool results, images, audio and files are all just block types.

  • Python's Msg is a Pydantic model with content: list[ContentBlock]. Build user messages with UserMsg (or Msg(role="user", content=[TextBlock(...)])); it wraps a plain string into a TextBlock automatically.
  • Java's Msg is built with Msg.builder(). UserMessage, AssistantMessage, SystemMessage and ToolResultMessage are role subclasses. Msg.builder().textContent("...") is the shorthand for a single text segment.

Separating content blocks buys two things:

  1. Multimodality needs no special API. Images, audio and files travel through the same message channel as DataBlock/ImageBlock.
  2. Streaming deltas are structured. Thinking, text and tool-call arguments arrive as typed block events, so a UI can render by block type instead of parsing strings.

Messages also carry usage, finished_reason, structured_output and error. These do not enter the model context; they support billing, observability and recovery.

3. Models and formatters

A model adapter calls the vendor API and normalizes the response. A formatter translates AgentScope messages into that vendor's request shape. Keeping them separate lets the same agent logic move between OpenAI, DashScope, Anthropic, Gemini, Ollama and others without changing business code.

Python's ChatModelBase defines __call__, count_tokens and generate_structured_output. For example, OpenAIChatModel:

from agentscope.credential import OpenAICredential
from agentscope.model import OpenAIChatModel

model = OpenAIChatModel(
    credential=OpenAICredential(api_key="sk-...", base_url=None),
    model="gpt-4o-mini",
    stream=True,
    context_size=128_000,
)

On the Java side, Model is the common interface and vendor implementations live in agentscope-extensions-model-* artifacts. For example: OpenAIChatModel.builder().apiKey(...).modelName(...).build().

Three semantics are easy to miss:

  • Streaming is the default. With stream=True the model yields incremental responses; the agent's reply_stream/stream wraps those into events.
  • Retry belongs to the model layer. max_retries and retry_delay operate inside the adapter. Agent-level ModelConfig.max_retries counts failovers to a fallback model. Do not conflate them.
  • The context window is a model property. context_size (Python) or contextWindowSize (Java) feeds context-compression thresholds.

4. The ReAct agent

ReAct = Reasoning + Acting. A reply is not a single model call but a loop:

  1. Assemble system prompt, history, current input, tool schemas and structured-output constraints.
  2. Call the model and stream thinking/text/tool calls.
  3. If there is no tool call, finish with the final message.
  4. If there are tool calls, execute them under the permission policy and append ToolResultBlocks to the context.
  5. Repeat 2–4 until a final answer, the iteration limit, an interruption or an error.

Python's Agent is the default implementation. Its constructor separates concerns:

from agentscope.agent import Agent, ContextConfig, ReActConfig
from agentscope.tool import Toolkit

agent = Agent(
    name="assistant",
    system_prompt="You are a careful engineer.",
    model=model,
    toolkit=Toolkit(),
    react_config=ReActConfig(max_iters=12),          # loop limits and interruption
    context_config=ContextConfig(trigger_ratio=0.8), # context compression
)

It exposes three entry points:

  • await agent.reply(msg) returns the final Msg;
  • agent.reply_stream(msg) yields an async event stream for incremental UIs;
  • await agent.observe(msg) writes a message into the context without calling the model, typically used to sync peers in multi-agent collaboration.

Java's ReActAgent configures the same concerns through a builder: name, sysPrompt, model, toolkit, maxIters, middlewares, stateStore, permissionContext and more. Execution is reactive:

Msg reply = agent.call("Summarize this repository.").block();

call returns Mono<Msg> and stream returns Flux<Event>. Event types (thinking deltas, tool calls, tool results, reply completion, etc.) live in io.agentscope.core.event.

Interruption and human confirmation

Tool execution can require human confirmation. Python expresses this through ToolCallBlock state and confirmation requests in the event stream; Java uses RequireUserConfirmEvent, ConfirmResult and the permission engine. Both follow the same rule: confirmation is a first-class state in the loop, not a temporary boolean in a callback. After an interruption, the agent resumes from saved state rather than replaying the whole conversation.

Structured output

reply(..., structured_schema=Model) / call(..., ResultType.class) constrain the output to a schema. This is not naive JSON parsing: the loop injects a structured-output tool that the model must call with schema-conforming arguments. Even if the model emits prose first, the final structured value remains usable.

5. Tools

Tools are the only channel through which an agent touches the outside world. Python's Toolkit manages three kinds of capability:

  • Function tools: FunctionTool wraps a plain function; its signature and Google-style docstring become a JSON Schema.
  • MCP tools: MCPClient connects to external MCP servers.
  • Skills: Skill/SkillLoaderBase provide instructions and resources loaded on demand.
from agentscope.tool import FunctionTool, Toolkit

def get_weather(city: str) -> str:
    """Return the current weather for a city.

    Args:
        city: The city name.
    """
    return f"{city}: sunny, 24C"

toolkit = Toolkit(tools=[FunctionTool(get_weather)])

Java declares tools with annotations: Toolkit.registerTool(Object) scans @Tool methods and @ToolParam describes parameters. MCP clients register through McpClientBuilder; skills are managed by SkillBox and AgentSkillRepository.

The tool system also handles:

  • Groups and activation — only active tool schemas are sent to the model, saving tokens;
  • Concurrency and read-only flags — is_concurrency_safe / readOnly decide whether tools may run in parallel;
  • Permission checks — every call passes through PermissionEngine, which can allow, deny or ask;
  • Streaming tool results — long-running tools can emit ToolChunks while executing.

6. State, memory and sessions

AgentScope separates temporary variables of one reply from session state that must persist:

  • Python's AgentState holds session_id, context, reply_context, tool_context, tasks_context, middle_context and more. It is serializable; your storage layer owns persistence.
  • Java's AgentState has a similar shape and ships with the AgentStateStore abstraction plus in-memory, JSON-file, MySQL and Redis implementations.

Two concepts are easy to confuse:

  • Context is the message list sent to the model; it grows with the conversation and must be compressed.
  • Memory is information kept across sessions. Python wires it through AgenticMemoryMiddleware, Mem0Middleware and ReMeMiddleware; Java has dedicated Memory and LongTermMemory abstractions plus AgentStateMemoryView.

Context compression is controlled by ContextConfig (Python) or AutoContextConfig (Java). Once the threshold is crossed, the framework replaces older messages with a structured summary while preserving tool calls and task state. Compression is itself a model call and therefore appears in the event stream.

7. Middleware and hooks

Both are extension points, with different roles:

  • Middleware wraps stages such as model call, reasoning and acting. It can modify inputs/outputs, short-circuit execution and inject context. Python's MiddlewareBase and Java's MiddlewareBase live here.
  • Hooks observe loop events for tracing and intervention. Java's Hook system (PreReasoningEvent, PostActingEvent, ...) is the primary implementation; Python's event stream plays a similar role.

Rule of thumb: use middleware to change behavior, hooks/events to observe or record. Neither should hold mutable global state across requests, because one agent may serve several sessions concurrently.

8. Multi-agent systems and workflows

Python ships TeamPipeline and GoalPipeline: the former splits work across team members, the latter drives multiple rounds toward a goal. Agents synchronize through observe and coordinate state through a shared AgentState or external storage.

Java leans toward "agent as tool": SubAgentTool exposes one agent as a tool of another; the A2A extension connects remote agents as A2aAgent; the AG-UI extension adapts agent event streams to frontend protocols.

9. RAG and knowledge bases

RAG is split into four replaceable stages:

  1. Parse — PDF, Word, PPT, Excel, images, plain text → documents;
  2. Chunk — by token, paragraph or section;
  3. Embed — EmbeddingModelBase / EmbeddingModel;
  4. Retrieve — vector stores (Milvus, Qdrant, Elasticsearch, MongoDB, in-memory, ...).

Python's KnowledgeBase binds an embedding model to a vector collection and offers insert_document, search, delete_document. Java's counterpart is SimpleKnowledge with Reader and VDBStoreBase. On the agent side, RAGMiddleware (Python) or GenericRAGHook (Java) injects retrieved context.

10. Skills, MCP, permissions and workspaces

  • Skills are instruction/resource bundles loaded on demand, so domain knowledge does not have to live in the system prompt. Python uses LocalSkillLoader; Java offers FileSystemSkillRepository, ClasspathSkillRepository and GitSkillRepository.
  • MCP is the Model Context Protocol client. Python's MCPClient supports stdio and HTTP; Java's McpClientBuilder provides sync and async clients.
  • Permissions: PermissionEngine decides allow/deny/ask based on tool, path and mode. Both editions support working-directory allowlists and dangerous-path checks.
  • Workspaces provide isolated execution environments. Python has LocalWorkspace, DockerWorkspace, E2BWorkspace and more; Java exposes equivalent sandbox extensions.

11. Observability and deployment

  • Python: TracingMiddleware, the event stream and the agentscope.tui console renderer.
  • Java: OtelTracingMiddleware, JsonlTraceExporter and Reactor's Flux<Event>.
  • Deployment: Python's agentscope.app provides web services, channels, storage and knowledge-base management; Java provides Spring Boot starters, an A2A server and an AG-UI runtime.

With these eleven blocks in mind, API pages stop feeling like a maze: every class belongs to a layer and every method is part of that layer's contract. Continue with the Python quick start or the Java quick start.