AS AgentScopeAPI 手册 / API Reference
包package Guide

Python ↔ Java 对照Python ↔ Java mapping

两个版本共享概念,但命名、包结构与并发模型不同。本页给出逐项映射,便于在两种实现之间迁移代码或对照阅读 API。

1. 概念与类型对照

概念 Python 2.0.11 Java 2.0.4 说明
消息 agentscope.message.Msg io.agentscope.core.message.Msg 都由角色 + 内容块组成
用户消息构造 UserMsg(name, content) Msg.builder().role(MsgRole.USER)... 或 UserMessage Java 的角色是枚举
文本块 TextBlock TextBlock 字段名不同
工具调用块 ToolCallBlock ToolUseBlock Java 用 "Use" 而非 "Call"
工具结果块 ToolResultBlock ToolResultBlock 状态枚举命名相近
模型基类 ChatModelBase Model Python 用 __call__,Java 用 Mono/Flux
OpenAI 适配器 agentscope.model.OpenAIChatModel io.agentscope.extensions.model.openai.OpenAIChatModel Java 在独立构件
凭据 OpenAICredential Builder 的 apiKey(...) Java 多数模型直接接收 key
格式化器 FormatterBase Formatter 泛型参数不同
智能体 Agent ReActAgent Python 的 Agent 即 ReAct 实现
智能体基类 无独立基类 AgentBase、Agent 接口 Java 拆分接口与实现
工具注册 Toolkit(tools=[FunctionTool(fn)]) Toolkit.registerTool(obj) + @Tool Python 用签名/docstring
工具参数 函数签名 + Google docstring @ToolParam 都生成 JSON Schema
MCP MCPClient McpClientBuilder / McpClientWrapper 都支持 stdio/HTTP
技能 Skill、LocalSkillLoader AgentSkill、SkillBox、AgentSkillRepository Java 更强调仓库
状态 AgentState AgentState 字段高度对应
状态存储 由调用方序列化 AgentStateStore Java 内置多种实现
回复上下文 ReplyContext AgentState 的 reply_id / cur_iter Java 平铺在状态中
工具上下文 ToolContext ToolContextState / ToolExecutionContext 前者持久化,后者单次调用
行为扩展 MiddlewareBase + 事件流 MiddlewareBase + Hook Java 钩子更细
多智能体 TeamPipeline、GoalPipeline SubAgentTool、A2A 设计取向不同
RAG 知识库 KnowledgeBase SimpleKnowledge 都绑定嵌入模型与向量库
向量库 MilvusLiteStore、QdrantStore 等 MilvusStore、QdrantStore 等 Java 类名少 "Lite"
嵌入模型 EmbeddingModelBase EmbeddingModel 都是接口/基类
权限 PermissionEngine PermissionEngine 概念与模式一致
工作区 LocalWorkspace、DockerWorkspace sandbox 扩展 Java 以构件提供
实时语音 RealtimeAgent、RealtimeModelBase 扩展构件 协议支持范围不同
服务化 agentscope.app Spring Boot starters 部署形态不同

2. 构造模型

Python

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

model = OpenAIChatModel(
    credential=OpenAICredential(api_key="sk-..."),
    model="gpt-4o-mini",
    stream=True,
)

Java

import io.agentscope.extensions.model.openai.OpenAIChatModel;

OpenAIChatModel model = OpenAIChatModel.builder()
    .apiKey("sk-...")
    .modelName("gpt-4o-mini")
    .stream(true)
    .build();

差异:Python 把凭据作为独立对象传入,便于复用与轮换;Java 的多数供应商 Builder 直接接收 apiKey,也支持自定义 httpTransport、proxy 等。

3. 构造消息

Python

from agentscope.message import UserMsg

msg = UserMsg("user", "What's the weather in Hangzhou?")

也可以显式构造内容块:

from agentscope.message import Msg, TextBlock

msg = Msg(
    name="user",
    role="user",
    content=[TextBlock(text="What's the weather in Hangzhou?")],
)

Java

import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;

Msg msg = Msg.builder()
    .name("user")
    .role(MsgRole.USER)
    .textContent("What's the weather in Hangzhou?")
    .build();

差异:Python 的角色是字符串字面量,Java 是 MsgRole 枚举;Java 还提供 UserMessage、AssistantMessage 等角色子类。

4. 注册工具

Python

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

import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.agentscope.core.tool.Toolkit;

public final class WeatherTools {
    @Tool(name = "get_weather", description = "Return the current weather for a city.")
    public String getWeather(
            @ToolParam(name = "city", description = "The city name") String city) {
        return city + ": sunny, 24C";
    }
}

Toolkit toolkit = new Toolkit();
toolkit.registerTool(new WeatherTools());

差异:Python 从函数元数据推导 schema;Java 用注解显式声明,并可在 @Tool 上配置只读、并发安全、危险路径等策略。

5. 构建智能体

Python

from agentscope.agent import Agent, ReActConfig

agent = Agent(
    name="assistant",
    system_prompt="You are a concise assistant.",
    model=model,
    toolkit=toolkit,
    react_config=ReActConfig(max_iters=10),
)

Java

import io.agentscope.core.ReActAgent;

ReActAgent agent = ReActAgent.builder()
    .name("assistant")
    .sysPrompt("You are a concise assistant.")
    .model(model)
    .toolkit(toolkit)
    .maxIters(10)
    .build();

差异:Python 用独立的配置对象(ReActConfig、ContextConfig、ModelConfig)分组参数;Java 把常用项平铺在 Builder 上,复杂能力(RAG、技能、长期记忆)用专门方法接入。

6. 调用与流式

Python

reply = await agent.reply(msg)
print(reply.get_text_content())

async for event in agent.reply_stream(msg):
    if isinstance(event, TextBlockDeltaEvent):
        print(event.delta, end="")

Java

Msg reply = agent.call(msg).block();
System.out.println(reply.getTextContent());

agent.streamEvents("Explain ReAct.")
    .doOnNext(event -> {
        if (event instanceof TextBlockDeltaEvent delta) {
            System.out.print(delta.getDelta());
        }
    })
    .blockLast();

差异:Python 的 reply_stream 返回异步生成器,Java 返回 Flux;Python 的最终消息可以直接由 reply 返回,Java 用 Mono.block() 或响应式订阅。

7. 结构化输出

Python

class Report(BaseModel):
    city: str
    temperature_c: float

reply = await agent.reply(msg, structured_schema=Report)
data = reply.structured_output

Java

public record Report(String city, double temperatureC) {}

Msg reply = agent.call(msg, Report.class).block();
Report report = reply.getStructuredData(Report.class);

差异:Python 直接用 Pydantic 模型,Java 用类/record + Jackson。两者都在循环内以工具调用的方式实现。

8. 状态与持久化

Python

from agentscope.state import AgentState

state = AgentState(session_id="demo")
agent = Agent(..., state=state)

payload = state.model_dump_json()

Java

import io.agentscope.core.state.AgentState;
import io.agentscope.core.state.JsonFileAgentStateStore;

AgentState state = AgentState.builder()
    .sessionId("demo")
    .userId("user-1")
    .build();

var store = new JsonFileAgentStateStore(Path.of("./state"));
ReActAgent agent = ReActAgent.builder()
    .stateStore(store)
    .defaultSessionId("demo")
    .build();

差异:Python 由调用方决定存储;Java 抽象出 AgentStateStore,并内置内存、JSON、MySQL、Redis 实现。

9. RAG

Python

from agentscope.rag import KnowledgeBase, MilvusLiteStore

kb = KnowledgeBase(
    name="handbook",
    description="Engineering handbook",
    embedding_model=embedding,
    vector_store=MilvusLiteStore(uri="./kb.db"),
    collection="handbook",
)
hits = await kb.search(["deployment"], top_k=5)

Java

import io.agentscope.core.rag.knowledge.SimpleKnowledge;
import io.agentscope.core.rag.store.InMemoryStore;

SimpleKnowledge kb = SimpleKnowledge.builder()
    .embeddingModel(embeddingModel)
    .embeddingStore(InMemoryStore.builder().dimensions(1536).build())
    .build();

var hits = kb.retrieve("deployment",
    RetrieveConfig.builder().limit(5).build()).block();

差异:Python 的 KnowledgeBase 直接接收集合名;Java 用 Knowledge 接口 + VDBStoreBase,向量库通常自带维度配置。

10. 迁移时的注意事项

  1. 并发模型:Python 用 await,Java 用 Reactor;不要在 Java 的 map 中做阻塞 I/O。
  2. 异常处理:Python 抛异常;Java 的 Mono/Flux 把错误作为信号传播,使用 onErrorResume 等操作符。
  3. 取消与中断:Python 用 asyncio.CancelledError/中断事件;Java 用 Disposable、interrupt() 与 Reactor 的取消信号。
  4. 配置粒度:Python 的配置对象可整体复用;Java 的 Builder 每次构建产生新实例,配置在构建时冻结。
  5. 包名:Java 的模型、RAG 存储、协议支持在独立 Maven 构件中,迁移时要同时调整依赖。

Both editions share concepts but differ in naming, package layout and concurrency. This page maps them item by item so you can migrate code or read the two APIs side by side.

1. Concepts and types

Concept Python 2.0.11 Java 2.0.4 Notes
Message agentscope.message.Msg io.agentscope.core.message.Msg Both are role + content blocks
User message UserMsg(name, content) Msg.builder().role(MsgRole.USER)... or UserMessage Java roles are enums
Text block TextBlock TextBlock Field names differ
Tool call block ToolCallBlock ToolUseBlock Java says "Use", Python says "Call"
Tool result block ToolResultBlock ToolResultBlock Similar state enums
Model base ChatModelBase Model __call__ vs Mono/Flux
OpenAI adapter agentscope.model.OpenAIChatModel io.agentscope.extensions.model.openai.OpenAIChatModel Java uses a separate artifact
Credential OpenAICredential apiKey(...) on the builder Java models usually take the key directly
Formatter FormatterBase Formatter Different generic parameters
Agent Agent ReActAgent Python's Agent is the ReAct implementation
Agent base none separate AgentBase, Agent interface Java splits interface and implementation
Tool registration Toolkit(tools=[FunctionTool(fn)]) Toolkit.registerTool(obj) + @Tool Signatures/docstrings vs annotations
Tool params function signature + Google docstring @ToolParam Both produce JSON Schema
MCP MCPClient McpClientBuilder / McpClientWrapper Both support stdio/HTTP
Skill Skill, LocalSkillLoader AgentSkill, SkillBox, AgentSkillRepository Java emphasizes repositories
State AgentState AgentState Closely corresponding fields
State store caller serializes AgentStateStore Java ships several implementations
Reply context ReplyContext reply_id / cur_iter on state Java flattens it
Tool context ToolContext ToolContextState / ToolExecutionContext Persisted vs per-call
Behavior extension MiddlewareBase + events MiddlewareBase + Hook Java hooks are finer-grained
Multi-agent TeamPipeline, GoalPipeline SubAgentTool, A2A Different design biases
RAG knowledge KnowledgeBase SimpleKnowledge Both bind embedding + vector store
Vector store MilvusLiteStore, QdrantStore, ... MilvusStore, QdrantStore, ... Java drops "Lite"
Embedding EmbeddingModelBase EmbeddingModel Base class vs interface
Permission PermissionEngine PermissionEngine Same concepts and modes
Workspace LocalWorkspace, DockerWorkspace sandbox extensions Java delivers them as artifacts
Realtime voice RealtimeAgent, RealtimeModelBase extension artifacts Protocol coverage differs
Serving agentscope.app Spring Boot starters Different deployment shapes

2. Constructing a model

Python

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

model = OpenAIChatModel(
    credential=OpenAICredential(api_key="sk-..."),
    model="gpt-4o-mini",
    stream=True,
)

Java

import io.agentscope.extensions.model.openai.OpenAIChatModel;

OpenAIChatModel model = OpenAIChatModel.builder()
    .apiKey("sk-...")
    .modelName("gpt-4o-mini")
    .stream(true)
    .build();

Difference: Python passes a reusable credential object; most Java vendor builders take the key directly and expose httpTransport, proxy, etc.

3. Constructing messages

Python

from agentscope.message import UserMsg

msg = UserMsg("user", "What's the weather in Hangzhou?")

Or with explicit blocks:

from agentscope.message import Msg, TextBlock

msg = Msg(
    name="user",
    role="user",
    content=[TextBlock(text="What's the weather in Hangzhou?")],
)

Java

import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;

Msg msg = Msg.builder()
    .name("user")
    .role(MsgRole.USER)
    .textContent("What's the weather in Hangzhou?")
    .build();

Difference: Python roles are string literals; Java uses the MsgRole enum and also offers UserMessage, AssistantMessage, etc.

4. Registering tools

Python

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

import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.agentscope.core.tool.Toolkit;

public final class WeatherTools {
    @Tool(name = "get_weather", description = "Return the current weather for a city.")
    public String getWeather(
            @ToolParam(name = "city", description = "The city name") String city) {
        return city + ": sunny, 24C";
    }
}

Toolkit toolkit = new Toolkit();
toolkit.registerTool(new WeatherTools());

Difference: Python derives the schema from function metadata; Java declares it with annotations and can set read-only, concurrency-safe and dangerous-path policies on @Tool.

5. Building the agent

Python

from agentscope.agent import Agent, ReActConfig

agent = Agent(
    name="assistant",
    system_prompt="You are a concise assistant.",
    model=model,
    toolkit=toolkit,
    react_config=ReActConfig(max_iters=10),
)

Java

import io.agentscope.core.ReActAgent;

ReActAgent agent = ReActAgent.builder()
    .name("assistant")
    .sysPrompt("You are a concise assistant.")
    .model(model)
    .toolkit(toolkit)
    .maxIters(10)
    .build();

Difference: Python groups parameters into config objects (ReActConfig, ContextConfig, ModelConfig); Java flattens common options onto the builder and attaches complex capabilities (RAG, skills, long-term memory) with dedicated methods.

6. Calling and streaming

Python

reply = await agent.reply(msg)
print(reply.get_text_content())

async for event in agent.reply_stream(msg):
    if isinstance(event, TextBlockDeltaEvent):
        print(event.delta, end="")

Java

Msg reply = agent.call(msg).block();
System.out.println(reply.getTextContent());

agent.streamEvents("Explain ReAct.")
    .doOnNext(event -> {
        if (event instanceof TextBlockDeltaEvent delta) {
            System.out.print(delta.getDelta());
        }
    })
    .blockLast();

Difference: Python returns an async generator from reply_stream; Java returns Flux. Python returns the final message directly from reply; Java blocks or subscribes to a Mono.

7. Structured output

Python

class Report(BaseModel):
    city: str
    temperature_c: float

reply = await agent.reply(msg, structured_schema=Report)
data = reply.structured_output

Java

public record Report(String city, double temperatureC) {}

Msg reply = agent.call(msg, Report.class).block();
Report report = reply.getStructuredData(Report.class);

Difference: Python uses a Pydantic model; Java uses a class/record with Jackson. Both implement it as a tool call inside the loop.

8. State and persistence

Python

from agentscope.state import AgentState

state = AgentState(session_id="demo")
agent = Agent(..., state=state)

payload = state.model_dump_json()

Java

import io.agentscope.core.state.AgentState;
import io.agentscope.core.state.JsonFileAgentStateStore;

AgentState state = AgentState.builder()
    .sessionId("demo")
    .userId("user-1")
    .build();

var store = new JsonFileAgentStateStore(Path.of("./state"));
ReActAgent agent = ReActAgent.builder()
    .stateStore(store)
    .defaultSessionId("demo")
    .build();

Difference: Python leaves storage to the caller; Java abstracts it behind AgentStateStore with in-memory, JSON, MySQL and Redis implementations.

9. RAG

Python

from agentscope.rag import KnowledgeBase, MilvusLiteStore

kb = KnowledgeBase(
    name="handbook",
    description="Engineering handbook",
    embedding_model=embedding,
    vector_store=MilvusLiteStore(uri="./kb.db"),
    collection="handbook",
)
hits = await kb.search(["deployment"], top_k=5)

Java

import io.agentscope.core.rag.knowledge.SimpleKnowledge;
import io.agentscope.core.rag.store.InMemoryStore;

SimpleKnowledge kb = SimpleKnowledge.builder()
    .embeddingModel(embeddingModel)
    .embeddingStore(InMemoryStore.builder().dimensions(1536).build())
    .build();

var hits = kb.retrieve("deployment",
    RetrieveConfig.builder().limit(5).build()).block();

Difference: Python's KnowledgeBase takes a collection name directly; Java uses the Knowledge interface plus VDBStoreBase, where the store usually owns dimension configuration.

10. Migration notes

  1. Concurrency — Python uses await, Java uses Reactor. Never block inside a Java map.
  2. Errors — Python raises exceptions; Java propagates error signals through Mono/Flux (onErrorResume, ...).
  3. Cancellation — Python uses asyncio.CancelledError and interruption events; Java uses Disposable, interrupt() and Reactor cancellation.
  4. Config granularity — Python config objects are reusable; Java builders freeze configuration at build time.
  5. Packages — Java model providers, RAG stores and protocol support live in separate Maven artifacts, so migrations must update dependencies too.