news 2026/5/1 7:00:56

《AgentScope-Java 深入浅出教程》附录A API参考快速指南

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
《AgentScope-Java 深入浅出教程》附录A API参考快速指南

本附录提供AgentScope-Java核心API的快速参考,方便开发者查阅常用接口和方法。


A.1 Agent API

A.1.1 ReActAgent

// 创建AgentReActAgentagent=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();// 同步调用Msgresponse=agent.call(userMsg).block();// 流式调用Flux<Event>eventFlux=agent.stream(userMsg);// 结构化输出Msgresponse=agent.call(userMsg,Schema.class).block();// 恢复执行(HITL)Msgresponse=agent.call().block();// 中断执行agent.interrupt();// 会话管理agent.saveTo(session,sessionId);agent.loadFrom(session,sessionId);agent.loadIfExists(session,sessionId);

A.1.2 UserAgent

// 创建UserAgentUserAgentuserAgent=UserAgent.builder().name("HumanUser")// 必需:用户名称.inputMethod(userInput)// 必需:输入方式.build();// 用户输入接口publicinterfaceUserInputBase{Mono<Msg>getUserInput(Stringprompt);}

A.2 Model API

A.2.1 DashScopeChatModel

DashScopeChatModelmodel=DashScopeChatModel.builder().apiKey("sk-xxx")// 必需:API密钥.modelName("qwen-max")// 必需:模型名称.stream(true)// 可选:流式输出.enableThinking(true)// 可选:深度思考.formatter(newDashScopeChatFormatter())// 可选:格式化器.defaultOptions(GenerateOptions.builder().thinkingBudget(1024).temperature(0.7).maxTokens(4096).build()).build();

A.2.2 OpenAIChatModel

OpenAIChatModelmodel=OpenAIChatModel.builder().apiKey("sk-xxx").modelName("gpt-4").baseUrl("https://api.openai.com/v1")// 可选:自定义端点.formatter(newOpenAIChatFormatter()).build();

A.2.3 GenerateOptions

GenerateOptionsoptions=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

InMemoryMemorymemory=newInMemoryMemory();// 添加消息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

AutoContextConfigconfig=AutoContextConfig.builder().tokenRatio(0.4)// 上下文占比.lastKeep(10)// 保留最近N条.build();AutoContextMemorymemory=newAutoContextMemory(config,model);

A.3.3 Mem0LongTermMemory

Mem0LongTermMemorylongTermMemory=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

// 创建消息MsguserMsg=Msg.builder().role(MsgRole.USER).name("User").content(TextBlock.builder().text("Hello").build()).metadata(Map.of("key","value")).build();// 获取内容Stringtext=msg.getTextContent();List<TextBlock>textBlocks=msg.getContentBlocks(TextBlock.class);booleanhasTools=msg.hasContentBlocks(ToolUseBlock.class);// 结构化数据Schemadata=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 Tool API

A.5.1 工具注解

publicclassMyTools{@Tool(name="tool_name",// 工具名称description="Tool description"// 工具描述)publicStringmyTool(@ToolParam(name="param1",// 参数名description="Parameter description"// 参数描述)Stringparam1,@ToolParam(name="param2",description="Optional param",required=false// 可选参数)Integerparam2){return"result";}}

A.5.2 Toolkit

Toolkittoolkit=newToolkit();// 注册工具toolkit.registerTool(newMyTools());// 获取工具信息Set<String>toolNames=toolkit.getToolNames();List<ToolDefinition>tools=toolkit.getTools();// MCP集成toolkit.registerMcpClient(mcpClient).block();

A.6 Pipeline API

A.6.1 MsgHub

// 创建Hubtry(MsgHubhub=MsgHub.builder().name("HubName").participants(agent1,agent2,agent3)// 参与者.announcement(announcementMsg)// 公告.enableAutoBroadcast(true)// 自动广播.build()){hub.enter().block();// 进入Hubagent1.call().block();// Agent发言hub.broadcast(messages).block();// 手动广播hub.setAutoBroadcast(false);// 关闭自动广播hub.exit().block();// 退出Hub}

A.6.2 SequentialPipeline

SequentialPipelinepipeline=SequentialPipeline.builder().addAgent(agent1).addAgent(agent2).addAgent(agent3).build();Msgresult=pipeline.execute(inputMsg).block(Duration.ofMinutes(3));

A.7 Hook API

A.7.1 Hook接口

publicinterfaceHook{<TextendsHookEvent>Mono<T>onEvent(Tevent);}

A.7.2 事件类型

事件类型触发时机
PreReasoningEvent推理前
PostReasoningEvent推理后
PreActingEvent执行前
PostActingEvent执行后
PostCallEvent调用完成后
ErrorEvent发生错误时

A.7.3 PostReasoningEvent方法

// 停止Agent执行(HITL)postReasoningEvent.stopAgent();// 跳转到推理阶段postReasoningEvent.gotoReasoning();// 获取推理消息Msgmsg=postReasoningEvent.getReasoningMessage();

A.8 Session API

A.8.1 Session接口

publicinterfaceSession{<T>voidsave(SessionKeykey,Stringname,Tvalue);<T>Tget(SessionKeykey,Stringname,Class<T>type);<T>voidsaveList(SessionKeykey,Stringname,List<T>values,Class<T>elementType);<T>List<T>getList(SessionKeykey,Stringname,Class<T>elementType);voiddelete(SessionKeykey);booleanexists(SessionKeykey);}

A.8.2 实现类

// 内存SessionSessionsession=newInMemorySession();// JSON文件SessionSessionsession=newJsonSession(Paths.get("/path/to/sessions"));

A.9 RAG API

A.9.1 Knowledge

Knowledgeknowledge=SimpleKnowledge.builder().embeddingModel(embeddingModel).embeddingStore(vectorStore).build();// 添加文档knowledge.addDocuments(documents).block();// 检索List<Document>results=knowledge.retrieve(query,limit).block();

A.9.2 RAGMode

模式描述
GENERIC每次查询自动检索
AGENTICAgent决定何时检索

A.10 Tracing API

A.10.1 TracerRegistry

// 注册追踪器TracerRegistry.register(tracer);// 启用追踪HookTracerRegistry.enableTracingHook();// 禁用追踪HookTracerRegistry.disableTracingHook();

A.10.2 TelemetryTracer

TelemetryTracertracer=TelemetryTracer.builder().endpoint("https://endpoint/v1/traces").addHeader("Authorization","Bearer token").build();

A.11 A2A API

A.11.1 AgentRunner

publicinterfaceAgentRunner{StringgetAgentName();StringgetAgentDescription();Flux<Event>stream(List<Msg>requestMessages,AgentRequestOptionsoptions);voidstop(StringtaskId);}

A.11.2 A2aClientAgent

A2aClientAgentremoteAgent=A2aClientAgent.builder().name("remote_agent").serverUrl("http://agent-service:8080").build();
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/27 22:29:19

target_modules设为all-linear有什么好处?

target_modules设为all-linear有什么好处&#xff1f; 1. 引言&#xff1a;LoRA微调中的target_modules选择 在大语言模型的参数高效微调&#xff08;Parameter-Efficient Fine-Tuning, PEFT&#xff09;中&#xff0c;LoRA&#xff08;Low-Rank Adaptation&#xff09; 因其…

作者头像 李华
网站建设 2026/5/1 6:06:19

基于SAM3文本引导万物分割模型的快速实践|一键实现图像精准分割

基于SAM3文本引导万物分割模型的快速实践&#xff5c;一键实现图像精准分割 1. 引言&#xff1a;从交互式分割到自然语言驱动 图像分割作为计算机视觉的核心任务之一&#xff0c;长期以来依赖于人工标注或特定提示&#xff08;如点、框&#xff09;来完成目标提取。Meta AI推…

作者头像 李华
网站建设 2026/4/30 19:44:45

YOLOv8打架斗殴识别:公共安全监控部署教程

YOLOv8打架斗殴识别&#xff1a;公共安全监控部署教程 1. 引言 1.1 公共安全场景中的智能监控需求 在车站、校园、商场、工业园区等公共场所&#xff0c;突发性群体冲突事件时有发生。传统视频监控依赖人工轮巡&#xff0c;响应滞后&#xff0c;难以实现事前预警与实时干预。…

作者头像 李华
网站建设 2026/5/1 6:09:58

3步解锁GHelper隐藏性能:从新手到高手的终极配置指南

3步解锁GHelper隐藏性能&#xff1a;从新手到高手的终极配置指南 【免费下载链接】g-helper Lightweight Armoury Crate alternative for Asus laptops. Control tool for ROG Zephyrus G14, G15, G16, M16, Flow X13, Flow X16, TUF, Strix, Scar and other models 项目地址…

作者头像 李华
网站建设 2026/4/23 20:26:23

HunyuanVideo-Foley批量处理秘籍:50条短视频音效只花5块钱

HunyuanVideo-Foley批量处理秘籍&#xff1a;50条短视频音效只花5块钱 你有没有遇到过这样的情况&#xff1a;公司每天要发布几十条商品短视频&#xff0c;每一条都要配上合适的背景音、环境声、点击声甚至脚步声&#xff1f;传统做法是人工剪辑加音效&#xff0c;不仅耗时耗力…

作者头像 李华
网站建设 2026/5/1 6:29:20

LeetDown iOS降级工具:老设备性能重生的完全操作手册

LeetDown iOS降级工具&#xff1a;老设备性能重生的完全操作手册 【免费下载链接】LeetDown a GUI macOS Downgrade Tool for A6 and A7 iDevices 项目地址: https://gitcode.com/gh_mirrors/le/LeetDown 还在为老旧iPhone或iPad运行缓慢而困扰吗&#xff1f;LeetDown这…

作者头像 李华