附录A API参考快速指南
本附录提供AgentScope-Java核心API的快速参考,方便开发者查阅常用接口和方法。
A.1 Agent API
A.1.1 ReActAgent
// 创建Agent
ReActAgent agent = ReActAgent.builder()
.name("AgentName") // 必需:Agent名称
.sysPrompt("You are a helpful assistant") // 必需:系统提示词
.model(chatModel) // 必需:语言模型
.memory(memory) // 可选:记忆组件
.toolkit(toolkit) // 可选:工具包
.hooks(List.of(hook1, hook2)) // 可选:Hook列表
.maxIters(10) // 可选:最大迭代次数
.longTermMemory(longTermMemory) // 可选:长期记忆
.knowledge(knowledge) // 可选:知识库
.ragMode(RAGMode.AGENTIC) // 可选:RAG模式
.enablePlan() // 可选:启用计划管理
.structuredOutputReminder(StructuredOutputReminder.PROMPT) // 可选
.build();
// 同步调用
Msg response = agent.call(userMsg).block();
// 流式调用
Flux<Event> eventFlux = agent.stream(userMsg);
// 结构化输出
Msg response = agent.call(userMsg, Schema.class).block();
// 恢复执行(HITL)
Msg response = agent.call().block();
// 中断执行
agent.interrupt();
// 会话管理
agent.saveTo(session, sessionId);
agent.loadFrom(session, sessionId);
agent.loadIfExists(session, sessionId);
A.1.2 UserAgent
// 创建UserAgent
UserAgent userAgent = UserAgent.builder()
.name("HumanUser") // 必需:用户名称
.inputMethod(userInput) // 必需:输入方式
.build();
// 用户输入接口
public interface UserInputBase {
Mono<Msg> getUserInput(String prompt);
}
A.2 Model API
A.2.1 DashScopeChatModel
DashScopeChatModel model = DashScopeChatModel.builder()
.apiKey("sk-xxx") // 必需:API密钥
.modelName("qwen-max") // 必需:模型名称
.stream(true) // 可选:流式输出
.enableThinking(true) // 可选:深度思考
.formatter(new DashScopeChatFormatter()) // 可选:格式化器
.defaultOptions(GenerateOptions.builder()
.thinkingBudget(1024)
.temperature(0.7)
.maxTokens(4096)
.build())
.build();
A.2.2 OpenAIChatModel
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey("sk-xxx")
.modelName("gpt-4")
.baseUrl("https://api.openai.com/v1") // 可选:自定义端点
.formatter(new OpenAIChatFormatter())
.build();
A.2.3 GenerateOptions
GenerateOptions options = GenerateOptions.builder()
.temperature(0.7) // 温度参数
.maxTokens(4096) // 最大token数
.thinkingBudget(1024) // 思考预算
.topP(0.9) // Top-P采样
.seed(42) // 随机种子
.build();
A.3 Memory API
A.3.1 InMemoryMemory
InMemoryMemory memory = new InMemoryMemory();
// 添加消息
memory.addMessage(msg);
memory.addMessages(List.of(msg1, msg2));
// 获取消息
List<Msg> messages = memory.getMessages();
List<Msg> recent = memory.getRecentMessages(10);
// 清空
memory.clear();
A.3.2 AutoContextMemory
AutoContextConfig config = AutoContextConfig.builder()
.tokenRatio(0.4) // 上下文占比
.lastKeep(10) // 保留最近N条
.build();
AutoContextMemory memory = new AutoContextMemory(config, model);
A.3.3 Mem0LongTermMemory
Mem0LongTermMemory longTermMemory = Mem0LongTermMemory.builder()
.apiKey("mem0-api-key")
.userId("user-123")
.agentName("MyAgent")
.apiBaseUrl("https://api.mem0.ai")
.build();
A.4 Message API
A.4.1 Msg
// 创建消息
Msg userMsg = Msg.builder()
.role(MsgRole.USER)
.name("User")
.content(TextBlock.builder().text("Hello").build())
.metadata(Map.of("key", "value"))
.build();
// 获取内容
String text = msg.getTextContent();
List<TextBlock> textBlocks = msg.getContentBlocks(TextBlock.class);
boolean hasTools = msg.hasContentBlocks(ToolUseBlock.class);
// 结构化数据
Schema data = msg.getStructuredData(Schema.class);
A.4.2 ContentBlock类型
| 类型 | 描述 |
| TextBlock | 文本内容 |
| ImageBlock | 图片内容 |
| AudioBlock | 音频内容 |
| VideoBlock | 视频内容 |
| ToolUseBlock | 工具调用请求 |
| ToolResultBlock | 工具执行结果 |
| ThinkingBlock | 思考过程 |
| FileBlock | 文件内容 |
A.4.3 MsgRole
| 角色 | 描述 |
| SYSTEM | 系统消息 |
| USER | 用户消息 |
| ASSISTANT | 助手消息 |
| TOOL | 工具结果 |
A.5.1 工具注解
public class MyTools {
@Tool(
name = "tool_name", // 工具名称
description = "Tool description" // 工具描述
)
public String myTool(
@ToolParam(
name = "param1", // 参数名
description = "Parameter description" // 参数描述
) String param1,
@ToolParam(
name = "param2",
description = "Optional param",
required = false // 可选参数
) Integer param2) {
return "result";
}
}
Toolkit toolkit = new Toolkit();
// 注册工具
toolkit.registerTool(new MyTools());
// 获取工具信息
Set<String> toolNames = toolkit.getToolNames();
List<ToolDefinition> tools = toolkit.getTools();
// MCP集成
toolkit.registerMcpClient(mcpClient).block();
A.6 Pipeline API
A.6.1 MsgHub
// 创建Hub
try (MsgHub hub = MsgHub.builder()
.name("HubName")
.participants(agent1, agent2, agent3) // 参与者
.announcement(announcementMsg) // 公告
.enableAutoBroadcast(true) // 自动广播
.build()) {
hub.enter().block(); // 进入Hub
agent1.call().block(); // Agent发言
hub.broadcast(messages).block(); // 手动广播
hub.setAutoBroadcast(false); // 关闭自动广播
hub.exit().block(); // 退出Hub
}
A.6.2 SequentialPipeline
SequentialPipeline pipeline = SequentialPipeline.builder()
.addAgent(agent1)
.addAgent(agent2)
.addAgent(agent3)
.build();
Msg result = pipeline.execute(inputMsg)
.block(Duration.ofMinutes(3));
A.7 Hook API
A.7.1 Hook接口
public interface Hook {
<T extends HookEvent> Mono<T> onEvent(T event);
}
A.7.2 事件类型
| 事件类型 | 触发时机 |
| PreReasoningEvent | 推理前 |
| PostReasoningEvent | 推理后 |
| PreActingEvent | 执行前 |
| PostActingEvent | 执行后 |
| PostCallEvent | 调用完成后 |
| ErrorEvent | 发生错误时 |
A.7.3 PostReasoningEvent方法
// 停止Agent执行(HITL)
postReasoningEvent.stopAgent();
// 跳转到推理阶段
postReasoningEvent.gotoReasoning();
// 获取推理消息
Msg msg = postReasoningEvent.getReasoningMessage();
A.8 Session API
A.8.1 Session接口
public interface Session {
<T> void save(SessionKey key, String name, T value);
<T> T get(SessionKey key, String name, Class<T> type);
<T> void saveList(SessionKey key, String name, List<T> values, Class<T> elementType);
<T> List<T> getList(SessionKey key, String name, Class<T> elementType);
void delete(SessionKey key);
boolean exists(SessionKey key);
}
A.8.2 实现类
// 内存Session
Session session = new InMemorySession();
// JSON文件Session
Session session = new JsonSession(Paths.get("/path/to/sessions"));
A.9 RAG API
A.9.1 Knowledge
Knowledge knowledge = SimpleKnowledge.builder()
.embeddingModel(embeddingModel)
.embeddingStore(vectorStore)
.build();
// 添加文档
knowledge.addDocuments(documents).block();
// 检索
List<Document> results = knowledge.retrieve(query, limit).block();
A.9.2 RAGMode
| 模式 | 描述 |
| GENERIC | 每次查询自动检索 |
| AGENTIC | Agent决定何时检索 |
A.10 Tracing API
A.10.1 TracerRegistry
// 注册追踪器
TracerRegistry.register(tracer);
// 启用追踪Hook
TracerRegistry.enableTracingHook();
// 禁用追踪Hook
TracerRegistry.disableTracingHook();
A.10.2 TelemetryTracer
TelemetryTracer tracer = TelemetryTracer.builder()
.endpoint("https://endpoint/v1/traces")
.addHeader("Authorization", "Bearer token")
.build();
A.11 A2A API
A.11.1 AgentRunner
public interface AgentRunner {
String getAgentName();
String getAgentDescription();
Flux<Event> stream(List<Msg> requestMessages, AgentRequestOptions options);
void stop(String taskId);
}
A.11.2 A2aClientAgent
A2aClientAgent remoteAgent = A2aClientAgent.builder()
.name("remote_agent")
.serverUrl("http://agent-service:8080")
.build();