Skip to content
Back to search

agentscope-java

SkillWorks with Claude CodeGitHub

Expert Java developer skill for AgentScope Java framework - a reactive, message-driven multi-agent system built on Project Reactor. Use when working with reactive programming, LLM integration, agent orchestration, multi-agent systems, or when the user mentions AgentScope, ReActAgent, Mono/Flux, Project Reactor, or Java agent development. Specializes in non-blocking code, tool integration, hooks, pipelines, and production-ready agent applications.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/agentscope-ai/agentscope-java with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/agentscope-ai/agentscope-java'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/agentscope-ai--agentscope-java/badge.svg)](/listings/agentscope-ai--agentscope-java)

HTML

<a href="/listings/agentscope-ai--agentscope-java"><img src="/api/listings/agentscope-ai--agentscope-java/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Installation

> AgentScope Java requires **JDK 17** or higher.

Maven

<dependency>
    <groupId>io.agentscope</groupId>
    <artifactId>agentscope-harness</artifactId>
    <version>2.0.3</version>
</dependency>

Model providers are shipped as separate extension modules in 2.0. Add the one you need — for example, DashScope:

<dependency>
    <groupId>io.agentscope</groupId>
    <artifactId>agentscope-extensions-model-dashscope</artifactId>
    <version>2.0.3</version>
</dependency>

Other options: `agentscope-extensions-model-openai`, `agentscope-extensions-model-anthropic`, `agentscope-extensions-model-gemini`, `agentscope-extensions-model-ollama`. See the [Model docs](https://java.agentscope.io/v2/en/docs/building-blocks/model.html) for details.

If you only need a bare `ReActAgent` without workspace / persistence / sandbox, depend on `agentscope-core` alone.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 1,057 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: agentscope-java
  3. description: Expert Java developer skill for AgentScope Java framework - a reactive, message-driven multi-agent system built on Project Reactor. Use when working with reactive programming, LLM integration, agent orchestration, multi-agent systems, or when the user mentions AgentScope, ReActAgent, Mono/Flux, Project Reactor, or Java agent development. Specializes in non-blocking code, tool integration, hooks, pipelines, and production-ready agent applications.
  4. license: Apache-2.0
  5. compatibility: Designed for Claude Code and Cursor. Requires Java 17+, Maven/Gradle, and familiarity with reactive programming concepts.
  6. metadata:
  7. framework: AgentScope Java
  8. language: Java 17+
  9. paradigm: Reactive Programming
  10. core-library: Project Reactor
  11. version: "1.0"
  12. ---
  13. When the user asks you to write AgentScope Java code, follow these instructions carefully.
  14. ## CRITICAL RULES - NEVER VIOLATE THESE
  15. **🚫 ABSOLUTELY FORBIDDEN:**
  16. 1. **NEVER use `.block()` in example code** - This is the #1 mistake. Only use `.block()` in `main()` methods or test code when explicitly creating a runnable example.
  17. 2. **NEVER use `Thread.sleep()`** - Use `Mono.delay()` instead.
  18. 3. **NEVER use `ThreadLocal`** - Use Reactor Context with `Mono.deferContextual()`.
  19. 4. **NEVER hardcode API keys** - Always use `System.getenv()`.
  20. 5. **NEVER ignore errors silently** - Always log errors and provide fallback values.
  21. 6. **NEVER use wrong import paths** - Shared model interfaces are in `io.agentscope.core.model.*`; provider models are in `io.agentscope.extensions.model.<provider>.*`.
  22. **✅ ALWAYS DO:**
  23. 1. **Use `Mono` and `Flux`** for all asynchronous operations.
  24. 2. **Chain operations** with `.map()`, `.flatMap()`, `.then()`.
  25. 3. **Use Builder pattern** for creating agents, models, and messages.
  26. 4. **Include error handling** with `.onErrorResume()` or `.onErrorReturn()`.
  27. 5. **Add logging** with SLF4J for important operations.
  28. 6. **Use correct imports**: `import io.agentscope.extensions.model.dashscope.DashScopeChatModel;`
  29. 7. **Use correct APIs** (many methods don't exist or have changed):
  30. - `toolkit.registerTool()` NOT `registerObject()`
  31. - `toolkit.getToolNames()` NOT `getTools()`
  32. - `event.getToolUse().getName()` NOT `getToolName()`
  33. - `result.getOutput()` NOT `getContent()` (ToolResultBlock)
  34. - `event.getToolResult()` NOT `getResult()` (PostActingEvent)
  35. - `toolUse.getInput()` NOT `getArguments()` (ToolUseBlock)
  36. - Model builder: NO `temperature()` method, use `defaultOptions(GenerateOptions.builder()...)`
  37. - Hook events: NO `getMessages()`, `getResponse()`, `getIterationCount()`, `getThinkingBlock()` methods
  38. - ToolResultBlock: NO `getToolUseName()` method, use `event.getToolUse().getName()` instead
  39. - ToolResultBlock.getOutput() returns `List<ContentBlock>` NOT `String`, need to convert
  40. - **@ToolParam format**: MUST use `@ToolParam(name = "x", description = "y")` NOT `@ToolParam(name="x")`
  41. ---
  42. ## WHEN GENERATING CODE
  43. **FIRST: Identify the context**
  44. - Is this a `main()` method or test code? → `.block()` is allowed (but add a warning comment)
  45. - Is this agent logic, service method, or library code? → `.block()` is **FORBIDDEN**
  46. **For every code example you provide:**
  47. 1. Check: Does it use `.block()`? → If yes in non-main/non-test code, **REWRITE IT**.
  48. 2. Check: Are all operations non-blocking? → If no, **FIX IT**.
  49. 3. Check: Does it have error handling? → If no, **ADD IT**.
  50. 4. Check: Are API keys from environment? → If no, **CHANGE IT**.
  51. 5. Check: Are imports correct? → If using provider models from `io.agentscope.core.model.*`, **FIX TO** `io.agentscope.extensions.model.<provider>.*`.
  52. **Default code structure for agent logic:**
  53. ```java
  54. // ✅ CORRECT - Non-blocking, reactive (use this pattern by default)
  55. return model.generate(messages, null, null)
  56. .map(response -> processResponse(response))
  57. .onErrorResume(e -> {
  58. log.error("Operation failed", e);
  59. return Mono.just(fallbackValue);
  60. });
  61. // ❌ WRONG - Never generate this in agent logic
  62. String result = model.generate(messages, null, null).block(); // DON'T DO THIS
  63. ```
  64. **Only for main() methods (add warning comment):**
  65. ```java
  66. public static void main(String[] args) {
  67. // ⚠️ .block() is ONLY allowed here because this is a main() method
  68. Msg response = agent.call(userMsg).block();
  69. System.out.println(response.getTextContent());
  70. }
  71. ```
  72. ---
  73. ## PROJECT SETUP
  74. **When creating a new AgentScope project, use the correct Maven dependencies:**
  75. ### Maven Configuration (pom.xml)
  76. **For production use (recommended):**
  77. ```xml
  78. <properties>
  79. <java.version>17</java.version>
  80. </properties>
  81. <dependencies>
  82. <!-- Use the latest stable release from Maven Central -->
  83. <dependency>
  84. <groupId>io.agentscope</groupId>
  85. <artifactId>agentscope</artifactId>
  86. <version>1.0.12</version>
  87. </dependency>
  88. </dependencies>
  89. ```
  90. **For local development (if working with source code):**
  91. ```xml
  92. <properties>
  93. <agentscope.version>1.0.12</agentscope.version>
  94. <java.version>17</java.version>
  95. </properties>
  96. <dependencies>
  97. <dependency>
  98. <groupId>io.agentscope</groupId>
  99. <artifactId>agentscope-core</artifactId>
  100. <version>${agentscope.version}</version>
  101. </dependency>
  102. <dependency>
  103. <groupId>io.agentscope</groupId>
  104. <artifactId>agentscope-extensions-model-dashscope</artifactId>
  105. <version>${agentscope.version}</version>
  106. </dependency>
  107. </dependencies>
  108. ```
  109. **⚠️ IMPORTANT: Version Selection**
  110. - **Use `agentscope:1.0.12`** for production (stable, from Maven Central)
  111. - **Use `agentscope-core:1.0.12`** only if you're developing AgentScope itself
  112. - **NEVER use version `0.1.0-SNAPSHOT`** - this version doesn't exist
  113. ### ⚠️ CRITICAL: Common Dependency Mistakes
  114. **❌ WRONG - These artifacts don't exist:**
  115. ```xml
  116. <!-- DON'T use these - they don't exist -->
  117. <dependency>
  118. <groupId>io.agentscope</groupId>
  119. <artifactId>agentscope-model-dashscope</artifactId> <!-- ❌ WRONG -->
  120. </dependency>
  121. <dependency>
  122. <groupId>io.agentscope</groupId>
  123. <artifactId>agentscope-model-openai</artifactId> <!-- ❌ WRONG -->
  124. </dependency>
  125. ```
  126. **❌ WRONG - These versions don't exist:**
  127. ```xml
  128. <dependency>
  129. <groupId>io.agentscope</groupId>
  130. <artifactId>agentscope-core</artifactId>
  131. <version>0.1.0-SNAPSHOT</version> <!-- ❌ WRONG - doesn't exist -->
  132. </dependency>
  133. <dependency>
  134. <groupId>io.agentscope</groupId>
  135. <artifactId>agentscope</artifactId>
  136. <version>0.1.0</version> <!-- ❌ WRONG - doesn't exist -->
  137. </dependency>
  138. ```
  139. **✅ CORRECT - Use the stable release:**
  140. ```xml
  141. <!-- For production: use the stable release from Maven Central -->
  142. <dependency>
  143. <groupId>io.agentscope</groupId>
  144. <artifactId>agentscope</artifactId>
  145. <version>1.0.12</version> <!-- ✅ CORRECT -->
  146. </dependency>
  147. ```
  148. ### Available Model Classes (provider-specific extension modules)
  149. ```java
  150. // DashScope (Alibaba Cloud)
  151. import io.agentscope.extensions.model.dashscope.DashScopeChatModel;
  152. // OpenAI
  153. import io.agentscope.extensions.model.openai.OpenAIChatModel;
  154. // Gemini (Google)
  155. import io.agentscope.extensions.model.gemini.GeminiChatModel;
  156. // Anthropic (Claude)
  157. import io.agentscope.extensions.model.anthropic.AnthropicChatModel;
  158. // Ollama (Local models)
  159. import io.agentscope.extensions.model.ollama.OllamaChatModel;
  160. ```
  161. ### Optional Extensions
  162. ```xml
  163. <!-- Long-term memory with Mem0 -->
  164. <dependency>
  165. <groupId>io.agentscope</groupId>
  166. <artifactId>agentscope-extensions-mem0</artifactId>
  167. <version>${agentscope.version}</version>
  168. </dependency>
  169. <!-- RAG with Dify -->
  170. <dependency>
  171. <groupId>io.agentscope</groupId>
  172. <artifactId>agentscope-extensions-rag-dify</artifactId>
  173. <version>${agentscope.version}</version>
  174. </dependency>
  175. ```
  176. ---
  177. ## PROJECT OVERVIEW & ARCHITECTURE
  178. AgentScope Java is a reactive, message-driven multi-agent framework built on **Project Reactor** and **Java 17+**.
  179. ### Core Abstractions
  180. - **`Agent`**: The fundamental unit of execution. Most agents extend `AgentBase`.
  181. - **`Msg`**: The message object exchanged between agents.
  182. - **`Memory`**: Stores conversation history (`InMemoryMemory`, `LongTermMemory`).
  183. - **`Toolkit` & `AgentTool`**: Defines capabilities the agent can use.
  184. - **`Model`**: Interfaces with LLMs (OpenAI, DashScope, Gemini, Anthropic, etc.).
  185. - **`Hook`**: Intercepts and modifies agent execution at various lifecycle points.
  186. - **`Pipeline`**: Orchestrates multiple agents in sequential or parallel patterns.
  187. ### Reactive Nature
  188. Almost all operations (agent calls, model inference, tool execution) return `Mono<T>` or `Flux<T>`.
  189. ### Key Design Principles
  190. 1. **Non-blocking**: All I/O operations are asynchronous
  191. 2. **Message-driven**: Agents communicate via immutable `Msg` objects
  192. 3. **Composable**: Agents and pipelines can be nested and combined
  193. 4. **Extensible**: Hooks and custom tools allow deep customization
  194. ---
  195. ## CODING STANDARDS & BEST PRACTICES
  196. ### 2.1 Java Version & Style
  197. **Target Java 17 (LTS) for maximum compatibility:**
  198. - Use **Java 17** features (Records, Switch expressions, Pattern Matching for instanceof, `var`, Sealed classes)
  199. - **AVOID Java 21+ preview features** (pattern matching in switch, record patterns)
  200. - Follow standard Java conventions (PascalCase for classes, camelCase for methods/variables)
  201. - Use **Lombok** where appropriate (`@Data`, `@Builder` for DTOs/Messages)
  202. - Prefer **immutability** for data classes
  203. - Use **meaningful names** that reflect domain concepts
  204. **⚠️ CRITICAL: Avoid Preview Features**
  205. ```java
  206. // ❌ WRONG - Requires Java 21 with --enable-preview
  207. return switch (event) {
  208. case PreReasoningEvent e -> Mono.just(e); // Pattern matching in switch
  209. default -> Mono.just(event);
  210. };
  211. // ✅ CORRECT - Java 17 compatible
  212. if (event instanceof PreReasoningEvent e) { // Pattern matching for instanceof (Java 17)
  213. return Mono.just(event);
  214. } else {
  215. return Mono.just(event);
  216. }
  217. ```
  218. ### 2.2 Reactive Programming (Critical)
  219. **⚠️ NEVER BLOCK IN AGENT LOGIC**
  220. Blocking operations will break the reactive chain and cause performance issues.
  221. **Rules:**
  222. - ❌ **Never use `.block()`** in agent logic (only in `main` methods or tests)
  223. - ✅ Use `Mono` for single results (e.g., `agent.call()`)
  224. - ✅ Use `Flux` for streaming responses (e.g., `model.stream()`)
  225. - ✅ Chain operations using `.map()`, `.flatMap()`, `.then()`
  226. - ✅ Use `Mono.defer()` for lazy evaluation
  227. - ✅ Use `Mono.deferContextual()` for reactive context access
  228. **Example:**
  229. ```java
  230. // ❌ WRONG - Blocking
  231. public Mono<String> processData(String input) {
  232. String result = externalService.call(input).block(); // DON'T DO THIS
  233. return Mono.just(result);
  234. }
  235. // ✅ CORRECT - Non-blocking
  236. public Mono<String> processData(String input) {
  237. return externalService.call(input)
  238. .map(this::transform)
  239. .flatMap(this::validate);
  240. }
  241. ```
  242. ### 2.3 Message Handling (`Msg`)
  243. Create messages using the Builder pattern:
  244. ```java
  245. Msg userMsg = Msg.builder()
  246. .role(MsgRole.USER)
  247. .content(TextBlock.builder().text("Hello").build())
  248. .name("user")
  249. .build();
  250. ```
  251. **Content Blocks:**
  252. - **`TextBlock`**: For text content
  253. - **`ThinkingBlock`**: For Chain of Thought (CoT) reasoning
  254. - **`ToolUseBlock`**: For tool calls
  255. - **`ToolResultBlock`**: For tool outputs
  256. **Helper Methods:**
  257. ```java
  258. // Prefer safe helper methods
  259. String text = msg.getTextContent(); // Safe, returns null if not found
  260. // Avoid direct access
  261. String text = msg.getContent().get(0).getText(); // May throw NPE
  262. ```
  263. ### 2.4 Implementing Agents
  264. Extend `AgentBase` and implement `doCall(List<Msg> msgs)`:
  265. ```java
  266. public class MyAgent extends AgentBase {
  267. private final Model model;
  268. private final Memory memory;
  269. public MyAgent(String name, Model model) {
  270. super(name, "A custom agent", true, List.of());
  271. this.model = model;
  272. this.memory = new InMemoryMemory();
  273. }
  274. @Override
  275. protected Mono<Msg> doCall(List<Msg> msgs) {
  276. // 1. Process inputs
  277. if (msgs != null) {
  278. msgs.forEach(memory::addMessage);
  279. }
  280. // 2. Call model or logic
  281. return model.generate(memory.getMessages(), null, null)
  282. .map(response -> Msg.builder()
  283. .name(getName())
  284. .role(MsgRole.ASSISTANT)
  285. .content(TextBlock.builder().text(response.getText()).build())
  286. .build());
  287. }
  288. }
  289. ```
  290. ### 2.5 Tool Definition
  291. Use `@Tool` annotation for function-based tools. Tools can return:
  292. - **`String`** (synchronous)
  293. - **`Mono<String>`** (asynchronous)
  294. - **`Mono<ToolResultBlock>`** (for complex results)
  295. **⚠️ CRITICAL: @ToolParam Format**
  296. - ✅ CORRECT: `@ToolParam(name = "city", description = "City name")`
  297. - ❌ WRONG: `@ToolParam(name="city", description="...")` (no spaces around `=`)
  298. - ❌ WRONG: `@ToolParam("city")` (missing name= and description=)
  299. **Synchronous Tool Example:**
  300. ```java
  301. public class WeatherTools {
  302. @Tool(description = "Get current weather for a city. Returns temperature and conditions.")
  303. public String getWeather(
  304. @ToolParam(name = "city", description = "City name, e.g., 'San Francisco'")
  305. String city) {
  306. // Implementation
  307. return "Sunny, 25°C";
  308. }
  309. }
  310. ```
  311. **Asynchronous Tool Example:**
  312. ```java
  313. public class AsyncTools {
  314. private final WebClient webClient;
  315. @Tool(description = "Fetch data from trusted API endpoint")
  316. public Mono<String> fetchData(
  317. @ToolParam(name = "url", description = "API endpoint URL (must start with https://api.myservice.com)")
  318. String url) {
  319. // SECURITY: Validate URL to prevent SSRF
  320. if (!url.startsWith("https://api.myservice.com")) {
  321. return Mono.just("Error: URL not allowed. Must start with https://api.myservice.com");
  322. }
  323. return webClient.get()
  324. .uri(url)
  325. .retrieve()
  326. .bodyToMono(String.class)
  327. .timeout(Duration.ofSeconds(10))
  328. .onErrorResume(e -> Mono.just("Error: " + e.getMessage()));
  329. }
  330. }
  331. ```
  332. **Register with Toolkit:**
  333. ```java
  334. Toolkit toolkit = new Toolkit();
  335. toolkit.registerTool(new WeatherTools());
  336. toolkit.registerTool(new AsyncTools());
  337. ```
  338. ---
  339. ## HOOK SYSTEM
  340. Hooks allow you to intercept and modify agent execution at various lifecycle points.
  341. ### Hook Interface
  342. ```java
  343. public interface Hook {
  344. <T extends HookEvent> Mono<T> onEvent(T event);
  345. default int priority() { return 100; } // Lower = higher priority
  346. }
  347. ```
  348. ### Common Hook Events
  349. - **`PreReasoningEvent`**: Before LLM reasoning (modifiable)
  350. - **`PostReasoningEvent`**: After LLM reasoning (modifiable)
  351. - **`ReasoningChunkEvent`**: Streaming reasoning chunks (notification)
  352. - **`PreActingEvent`**: Before tool execution (modifiable)
  353. - **`PostActingEvent`**: After tool execution (modifiable)
  354. - **`ActingChunkEvent`**: Streaming tool execution (notification)
  355. ### Hook Example
  356. **Java 17+ compatible (recommended):**
  357. ```java
  358. Hook loggingHook = new Hook() {
  359. @Override
  360. public <T extends HookEvent> Mono<T> onEvent(T event) {
  361. // Use if-instanceof instead of switch patterns (Java 17 compatible)
  362. if (event instanceof PreReasoningEvent e) {
  363. log.info("Reasoning with model: {}", e.getModelName());
  364. return Mono.just(event);
  365. } else if (event instanceof PreActingEvent e) {
  366. log.info("Calling tool: {}", e.getToolUse().getName());
  367. return Mono.just(event);
  368. } else if (event instanceof PostActingEvent e) {
  369. log.info("Tool {} completed", e.getToolUse().getName());
  370. return Mono.just(event);
  371. } else {
  372. return Mono.just(event);
  373. }
  374. }
  375. @Override
  376. public int priority() {
  377. return 500; // Low priority (logging)
  378. }
  379. };
  380. ReActAgent agent = ReActAgent.builder()
  381. .name("Assistant")
  382. .model(model)
  383. .hook(loggingHook)
  384. .build();
  385. ```
  386. **Alternative: Traditional if-else (Java 17):**
  387. ```java
  388. Hook loggingHook = new Hook() {
  389. @Override
  390. public <T extends HookEvent> Mono<T> onEvent(T event) {
  391. if (event instanceof PreReasoningEvent) {
  392. PreReasoningEvent e = (PreReasoningEvent) event;
  393. log.info("Reasoning with model: {}", e.getModelName());
  394. } else if (event instanceof PreActingEvent) {
  395. PreActingEvent e = (PreActingEvent) event;
  396. log.info("Calling tool: {}", e.getToolUse().getName());
  397. } else if (event instanceof PostActingEvent) {
  398. PostActingEvent e = (PostActingEvent) event;
  399. log.info("Tool {} completed", e.getToolUse().getName());
  400. }
  401. return Mono.just(event);
  402. }
  403. @Override
  404. public int priority() {
  405. return 500;
  406. }
  407. };
  408. ```
  409. **Priority Guidelines:**
  410. - **0-50**: Critical system hooks (auth, security)
  411. - **51-100**: High priority hooks (validation, preprocessing)
  412. - **101-500**: Normal priority hooks (business logic)
  413. - **501-1000**: Low priority hooks (logging, metrics)
  414. ---
  415. ## PIPELINE PATTERNS
  416. Pipelines orchestrate multiple agents in structured workflows.
  417. ### Sequential Pipeline
  418. Executes agents in sequence (output of one becomes input of next):
  419. ```java
  420. SequentialPipeline pipeline = SequentialPipeline.builder()
  421. .addAgent(researchAgent)
  422. .addAgent(summaryAgent)
  423. .addAgent(reviewAgent)
  424. .build();
  425. Msg result = pipeline.execute(userInput).block();
  426. ```
  427. ### Fanout Pipeline
  428. Executes agents in parallel and aggregates results:
  429. ```java
  430. FanoutPipeline pipeline = FanoutPipeline.builder()
  431. .addAgent(agent1)
  432. .addAgent(agent2)
  433. .addAgent(agent3)
  434. .build();
  435. Msg result = pipeline.execute(userInput).block();
  436. ```
  437. **When to Use:**
  438. - **Sequential**: When each agent depends on the previous agent's output
  439. - **Fanout**: When agents can work independently and results need aggregation
  440. ---
  441. ## MEMORY MANAGEMENT
  442. ### In-Memory (Short-term)
  443. ```java
  444. Memory memory = new InMemoryMemory();
  445. ```
  446. ### Long-Term Memory
  447. ```java
  448. // Configure long-term memory
  449. LongTermMemory longTermMemory = Mem0LongTermMemory.builder()
  450. .apiKey(System.getenv("MEM0_API_KEY"))
  451. .userId("user_123")
  452. .build();
  453. // Use with agent
  454. ReActAgent agent = ReActAgent.builder()
  455. .name("Assistant")
  456. .model(model)
  457. .longTermMemory(longTermMemory)
  458. .longTermMemoryMode(LongTermMemoryMode.BOTH) // STATIC_CONTROL, AGENTIC, or BOTH
  459. .build();
  460. ```
  461. **Memory Modes:**
  462. - **`STATIC_CONTROL`**: Framework automatically manages memory (via hooks)
  463. - **`AGENTIC`**: Agent decides when to use memory (via tools)
  464. - **`BOTH`**: Combines both approaches
  465. ---
  466. ## MCP (MODEL CONTEXT PROTOCOL) INTEGRATION
  467. AgentScope supports MCP for integrating external tools and resources.
  468. ```java
  469. // Create MCP client
  470. // SECURITY: In production, use a specific version or a local binary to prevent supply chain attacks
  471. McpClientWrapper mcpClient = McpClientBuilder.stdio()
  472. .command("npx")
  473. .args("-y", "@modelcontextprotocol/server-filesystem@0.6.2", "/path/to/files") // Always pin versions
  474. .build();
  475. // Register with toolkit
  476. Toolkit toolkit = new Toolkit();
  477. toolkit.registration()
  478. .mcpClient(mcpClient)
  479. .enableTools(List.of("read_file", "write_file"))
  480. .apply();
  481. // Use with agent
  482. ReActAgent agent = ReActAgent.builder()
  483. .name("Assistant")
  484. .model(model)
  485. .toolkit(toolkit)
  486. .build();
  487. ```
  488. ---
  489. ## TESTING
  490. ### Unit Testing with StepVerifier
  491. ```java
  492. @Test
  493. void testAgentCall() {
  494. Msg input = Msg.builder()
  495. .role(MsgRole.USER)
  496. .content(TextBlock.builder().text("Hello").build())
  497. .build();
  498. StepVerifier.create(agent.call(input))
  499. .assertNext(response -> {
  500. assertEquals(MsgRole.ASSISTANT, response.getRole());
  501. assertNotNull(response.getTextContent());
  502. })
  503. .verifyComplete();
  504. }
  505. ```
  506. ### Mocking External Dependencies
  507. ```java
  508. @Test
  509. void testWithMockModel() {
  510. Model mockModel = mock(Model.class);
  511. when(mockModel.generate(any(), any(), any()))
  512. .thenReturn(Mono.just(ChatResponse.builder()
  513. .text("Mocked response")
  514. .build()));
  515. ReActAgent agent = ReActAgent.builder()
  516. .name("TestAgent")
  517. .model(mockModel)
  518. .build();
  519. // Test agent behavior
  520. }
  521. ```
  522. **Testing Best Practices:**
  523. - Always test reactive chains with `StepVerifier`
  524. - Mock external dependencies (models, APIs)
  525. - Test error cases and edge conditions
  526. - Verify that hooks are called correctly
  527. - Test timeout and cancellation scenarios
  528. ---
  529. ## CODE STYLE GUIDE
  530. ### Logging
  531. ```java
  532. private static final Logger log = LoggerFactory.getLogger(MyClass.class);
  533. // Use parameterized logging
  534. log.info("Processing message from user: {}", userId);
  535. log.error("Failed to call model: {}", modelName, exception);
  536. ```
  537. ### Error Handling
  538. ```java
  539. // Prefer specific error messages
  540. return Mono.error(new IllegalArgumentException(
  541. "Invalid model name: " + modelName + ". Expected one of: " + VALID_MODELS));
  542. // Use onErrorResume for graceful degradation
  543. return model.generate(msgs, null, null)
  544. .onErrorResume(e -> {
  545. log.error("Model call failed, using fallback", e);
  546. return Mono.just(fallbackResponse);
  547. });
  548. ```
  549. ### Null Safety
  550. ```java
  551. // Use Optional for nullable returns
  552. public Optional<AgentTool> findTool(String name) {
  553. return Optional.ofNullable(tools.get(name));
  554. }
  555. // Use Objects.requireNonNull for validation
  556. public MyAgent(Model model) {
  557. this.model = Objects.requireNonNull(model, "Model cannot be null");
  558. }
  559. ```
  560. ### Comments
  561. ```java
  562. // Use Javadoc for public APIs
  563. /**
  564. * Creates a new agent with the specified configuration.
  565. *
  566. * @param name The agent name (must be unique)
  567. * @param model The LLM model to use
  568. * @return Configured agent instance
  569. * @throws IllegalArgumentException if name is null or empty
  570. */
  571. public static ReActAgent create(String name, Model model) {
  572. // Implementation
  573. }
  574. // Use inline comments sparingly, only for complex logic
  575. // Calculate exponential backoff: 2^attempt * baseDelay
  576. Duration delay = Duration.ofMillis((long) Math.pow(2, attempt) * baseDelayMs);
  577. ```
  578. ---
  579. ## KEY LIBRARIES
  580. - **Reactor Core**: `Mono`, `Flux` for reactive programming
  581. - **Jackson**: JSON serialization/deserialization
  582. - **SLF4J**: Logging (`private static final Logger log = LoggerFactory.getLogger(MyClass.class);`)
  583. - **OkHttp**: HTTP client for model APIs
  584. - **MCP SDK**: Model Context Protocol integration
  585. - **JUnit 5**: Testing framework
  586. - **Mockito**: Mocking framework
  587. - **Lombok**: Boilerplate reduction
  588. ---
  589. ## PROHIBITED PRACTICES
  590. ### ❌ NEVER Do These
  591. 1. **Block in reactive chains**
  592. ```java
  593. // ❌ WRONG
  594. return someMonoOperation().block();
  595. ```
  596. 2. **Use Thread.sleep() or blocking I/O**
  597. ```java
  598. // ❌ WRONG
  599. Thread.sleep(1000);
  600. // ✅ CORRECT
  601. return Mono.delay(Duration.ofSeconds(1));
  602. ```
  603. 3. **Mutate shared state without synchronization**
  604. ```java
  605. // ❌ WRONG
  606. private List<Msg> messages = new ArrayList<>();
  607. public void addMessage(Msg msg) {
  608. messages.add(msg); // Not thread-safe
  609. }
  610. ```
  611. 4. **Ignore errors silently**
  612. ```java
  613. // ❌ WRONG
  614. .onErrorResume(e -> Mono.empty())
  615. // ✅ CORRECT
  616. .onErrorResume(e -> {
  617. log.error("Operation failed", e);
  618. return Mono.just(fallbackValue);
  619. })
  620. ```
  621. 5. **Use ThreadLocal in reactive code**
  622. ```java
  623. // ❌ WRONG
  624. ThreadLocal<String> context = new ThreadLocal<>();
  625. // ✅ CORRECT
  626. return Mono.deferContextual(ctx -> {
  627. String value = ctx.get("key");
  628. // Use value
  629. });
  630. ```
  631. 6. **Create agents without proper resource management**
  632. ```java
  633. // ❌ WRONG - No cleanup
  634. public void processRequests() {
  635. for (int i = 0; i < 1000; i++) {
  636. ReActAgent agent = createAgent();
  637. agent.call(msg).block();
  638. }
  639. }
  640. ```
  641. 7. **Hardcode API keys or secrets**
  642. ```java
  643. // ❌ WRONG
  644. String apiKey = "sk-1234567890";
  645. // ✅ CORRECT
  646. String apiKey = System.getenv("OPENAI_API_KEY");
  647. ```
  648. 8. **Use Java preview features (requires --enable-preview)**
  649. ```java
  650. // ❌ WRONG - Requires Java 21 with --enable-preview
  651. return switch (event) {
  652. case PreReasoningEvent e -> handleReasoning(e);
  653. case PostActingEvent e -> handleActing(e);
  654. default -> Mono.just(event);
  655. };
  656. // ✅ CORRECT - Java 17 compatible
  657. if (event instanceof PreReasoningEvent e) {
  658. return handleReasoning(e);
  659. } else if (event instanceof PostActingEvent e) {
  660. return handleActing(e);
  661. } else {
  662. return Mono.just(event);
  663. }
  664. ```
  665. ---
  666. ## COMMON PITFALLS & SOLUTIONS
  667. ### ❌ Blocking Operations
  668. ```java
  669. // WRONG
  670. Msg response = agent.call(msg).block(); // Don't block in agent logic
  671. ```
  672. ```java
  673. // CORRECT
  674. return agent.call(msg)
  675. .flatMap(response -> processResponse(response));
  676. ```
  677. ### ❌ Null Handling
  678. ```java
  679. // WRONG
  680. String text = msg.getContent().get(0).getText(); // May throw NPE
  681. ```
  682. ```java
  683. // CORRECT
  684. String text = msg.getTextContent(); // Safe helper method
  685. // OR
  686. String text = msg.getContentBlocks(TextBlock.class).stream()
  687. .findFirst()
  688. .map(TextBlock::getText)
  689. .orElse("");
  690. ```
  691. ### ❌ Thread Context
  692. ```java
  693. // WRONG
  694. ThreadLocal<String> context = new ThreadLocal<>(); // May not work in reactive streams
  695. ```
  696. ```java
  697. // CORRECT
  698. return Mono.deferContextual(ctx -> {
  699. String value = ctx.get("key");
  700. // Use value
  701. });
  702. ```
  703. ### ❌ Error Swallowing
  704. ```java
  705. // WRONG
  706. .onErrorResume(e -> Mono.empty()) // Silent failure
  707. ```
  708. ```java
  709. // CORRECT
  710. .onErrorResume(e -> {
  711. log.error("Failed to process: {}", input, e);
  712. return Mono.just(createErrorResponse(e));
  713. })
  714. ```
  715. ---
  716. ## COMPLETE EXAMPLE
  717. ```java
  718. package com.example.agentscope;
  719. import io.agentscope.core.ReActAgent;
  720. import io.agentscope.core.hook.Hook;
  721. import io.agentscope.core.hook.HookEvent;
  722. import io.agentscope.core.hook.ReasoningChunkEvent;
  723. import io.agentscope.core.memory.InMemoryMemory;
  724. import io.agentscope.core.message.Msg;
  725. import io.agentscope.core.message.MsgRole;
  726. import io.agentscope.core.message.TextBlock;
  727. import io.agentscope.core.model.Model;
  728. import io.agentscope.core.tool.Tool;
  729. import io.agentscope.core.tool.ToolParam;
  730. import io.agentscope.core.tool.Toolkit;
  731. import io.agentscope.extensions.model.dashscope.DashScopeChatModel;
  732. import org.slf4j.Logger;
  733. import org.slf4j.LoggerFactory;
  734. import reactor.core.publisher.Mono;
  735. import java.time.LocalDateTime;
  736. import java.time.format.DateTimeFormatter;
  737. /**
  738. * Complete example demonstrating AgentScope best practices.
  739. */
  740. public class CompleteExample {
  741. private static final Logger log = LoggerFactory.getLogger(CompleteExample.class);
  742. public static void main(String[] args) {
  743. // 1. Create model (no .temperature() method, use defaultOptions)
  744. Model model = DashScopeChatModel.builder()
  745. .apiKey(System.getenv("DASHSCOPE_API_KEY"))
  746. .modelName("qwen-plus")
  747. .stream(true)
  748. .build();
  749. // 2. Create toolkit with tools
  750. Toolkit toolkit = new Toolkit();
  751. toolkit.registerTool(new WeatherTools());
  752. toolkit.registerTool(new TimeTools());
  753. // 3. Create hook for streaming output
  754. Hook streamingHook = new Hook() {
  755. @Override
  756. public <T extends HookEvent> Mono<T> onEvent(T event) {
  757. if (event instanceof ReasoningChunkEvent e) {
  758. String text = e.getIncrementalChunk().getTextContent();
  759. if (text != null) {
  760. System.out.print(text);
  761. }
  762. }
  763. return Mono.just(event);
  764. }
  765. @Override
  766. public int priority() {
  767. return 500; // Low priority
  768. }
  769. };
  770. // 4. Build agent
  771. ReActAgent agent = ReActAgent.builder()
  772. .name("Assistant")
  773. .sysPrompt("You are a helpful assistant. Use tools when appropriate.")
  774. .model(model)
  775. .toolkit(toolkit)
  776. .memory(new InMemoryMemory())
  777. .hook(streamingHook)
  778. .maxIters(10)
  779. .build();
  780. // 5. Use agent
  781. Msg userMsg = Msg.builder()
  782. .role(MsgRole.USER)
  783. .content(TextBlock.builder()
  784. .text("What's the weather in San Francisco and what time is it?")
  785. .build())
  786. .build();
  787. try {
  788. System.out.println("User: " + userMsg.getTextContent());
  789. System.out.print("Assistant: ");
  790. // ⚠️ IMPORTANT: .block() is ONLY allowed in main() methods for demo purposes
  791. // NEVER use .block() in agent logic, service methods, or library code
  792. Msg response = agent.call(userMsg).block();
  793. System.out.println("\n\n--- Response Details ---");
  794. System.out.println("Role: " + response.getRole());
  795. System.out.println("Content: " + response.getTextContent());
  796. } catch (Exception e) {
  797. log.error("Error during agent execution", e);
  798. System.err.println("Error: " + e.getMessage());
  799. }
  800. }
  801. /**
  802. * Example tool class for weather information.
  803. */
  804. public static class WeatherTools {
  805. @Tool(description = "Get current weather for a city. Returns temperature and conditions.")
  806. public String getWeather(
  807. @ToolParam(name = "city", description = "City name, e.g., 'San Francisco'")
  808. String city) {
  809. log.info("Getting weather for city: {}", city);
  810. // Simulate API call
  811. return String.format("Weather in %s: Sunny, 22°C, Light breeze", city);
  812. }
  813. }
  814. /**
  815. * Example tool class for time information.
  816. */
  817. public static class TimeTools {
  818. private static final DateTimeFormatter FORMATTER =
  819. DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  820. @Tool(description = "Get current date and time")
  821. public String getCurrentTime() {
  822. LocalDateTime now = LocalDateTime.now();
  823. String formatted = now.format(FORMATTER);
  824. log.info("Returning current time: {}", formatted);
  825. return "Current time: " + formatted;
  826. }
  827. }
  828. }
  829. ```
  830. ---
  831. ## QUICK REFERENCE
  832. ### Agent Creation
  833. ```java
  834. ReActAgent agent = ReActAgent.builder()
  835. .name("AgentName")
  836. .sysPrompt("System prompt")
  837. .model(model)
  838. .toolkit(toolkit)
  839. .memory(memory)
  840. .hooks(hooks)
  841. .maxIters(10)
  842. .build();
  843. ```
  844. ### Message Creation
  845. ```java
  846. Msg msg = Msg.builder()
  847. .role(MsgRole.USER)
  848. .content(TextBlock.builder().text("Hello").build())
  849. .build();
  850. ```
  851. ### Tool Registration
  852. ```java
  853. Toolkit toolkit = new Toolkit();
  854. toolkit.registerTool(new MyTools());
  855. ```
  856. ### Hook Creation
  857. ```java
  858. Hook hook = new Hook() {
  859. public <T extends HookEvent> Mono<T> onEvent(T event) {
  860. // Handle event
  861. return Mono.just(event);
  862. }
  863. };
  864. ```
  865. ### Pipeline Creation
  866. ```java
  867. SequentialPipeline pipeline = SequentialPipeline.builder()
  868. .addAgent(agent1)
  869. .addAgent(agent2)
  870. .build();
  871. ```
  872. ---
README.md · README · 218 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <img
  3. src="https://img.alicdn.com/imgextra/i1/O1CN01nTg6w21NqT5qFKH1u_!!6000000001621-55-tps-550-550.svg"
  4. alt="AgentScope Logo"
  5. width="200"
  6. />
  7. </p>
  8. <span align="center">
  9. [**中文主页**](https://github.com/agentscope-ai/agentscope-java/blob/main/README_zh.md) | [**日本語ホームページ**](https://github.com/agentscope-ai/agentscope-java/blob/main/README_ja.md) | [**Documentation**](https://java.agentscope.io/)
  10. </span>
  11. <p align="center">
  12. <a href="https://discord.gg/eYMpfnkG8h">
  13. <img
  14. src="https://img.shields.io/badge/Discord-Join%20Us-5865F2?logo=discord&logoColor=white"
  15. alt="discord"
  16. />
  17. </a>
  18. <a href="https://java.agentscope.io/">
  19. <img
  20. src="https://img.shields.io/badge/Docs-English%7C%E4%B8%AD%E6%96%87-blue?logo=markdown"
  21. alt="docs"
  22. />
  23. </a>
  24. <a href="https://img.shields.io/maven-central/v/io.agentscope/agentscope">
  25. <img
  26. src="https://img.shields.io/maven-central/v/io.agentscope/agentscope?color=green"
  27. alt="Maven Central"
  28. />
  29. </a>
  30. <a href="#">
  31. <img
  32. src="https://img.shields.io/badge/JDK-17%2B-orange?logo=openjdk"
  33. alt="JDK 17+"
  34. />
  35. </a>
  36. <a href="./LICENSE">
  37. <img
  38. src="https://img.shields.io/badge/license-Apache--2.0-black"
  39. alt="license"
  40. />
  41. </a>
  42. <a href="https://deepwiki.com/agentscope-ai/agentscope-java">
  43. <img
  44. src="https://deepwiki.com/badge.svg"
  45. alt="Ask DeepWiki"
  46. />
  47. </a>
  48. </p>
  49. ## What is AgentScope Java 2.0?
  50. AgentScope Java 2.0 is a production-ready framework for building distributed, enterprise-grade agents, providing essential abstractions that work with rising model capability and built-in support for long-running, safely-controlled agent execution.
  51. - [**Event System** →](https://java.agentscope.io/dev/en/docs/building-blocks/message-and-event.html) A unified event stream with 32 typed events for real-time frontend rendering and human-in-the-loop.
  52. - [**Permission System** →](https://java.agentscope.io/dev/en/docs/building-blocks/permission-system.html) Tool-call gating: allow / require user approval / deny.
  53. - [**Middleware** →](https://java.agentscope.io/dev/en/docs/building-blocks/middleware.html) AOP-style hook interception for flexibly extending the reasoning-acting loop.
  54. - [**Workspace & Sandbox** →](https://java.agentscope.io/dev/en/docs/harness/workspace.html) Run tools in isolated environments — local, Docker, Kubernetes, or AgentRun cloud sandbox.
  55. - [**Multi-Agent Orchestration** →](https://java.agentscope.io/dev/en/docs/harness/subagent.html) Multiple subagent definition patterns with `agent_spawn` / `agent_send` and real-time event forwarding.
  56. - [**Distributed Deployment** →](https://java.agentscope.io/dev/en/docs/others/going-to-production.html) True distributed session and memory management (Redis / MySQL / PostgreSQL / OSS / COS) with cross-replica session recovery.
  57. - [**Agent Evolution** →](https://help.aliyun.com/zh/document_detail/3042583.html) Provides Agent observability and auditing, Agent evaluation and experimentation, and Agent asset management and continuous optimization.
  58. <img src="./docs/imgs/landscape.png" alt="agentscope" width="100%"/>
  59. ## News
  60. <!-- BEGIN NEWS -->
  61. - **[2026-07] `v2.0.0 GA`:** First production-ready release! Dual-layer agent architecture, event stream, permission system, middleware, workspace sandbox, multi-agent orchestration, and distributed deployment all ready. [Docs](https://java.agentscope.io/) | [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0)
  62. - **[2026-07] `v2.0.0-RC5`:** Model provider modularization; unified DataBlock multimodal support; native structured output; Channel IM integration; Tencent Cloud COS state persistence. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0-RC5)
  63. - **[2026-06] `v2.0.0-RC4`:** Async tool execution and scheduled wakeup dispatching; subagent cross-replica routing and session recovery. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0-RC4)
  64. - **[2026-06] `v2.0.0-RC3`:** Unified `call()` / `streamEvents()` execution core; `AgentResultEvent`, `CustomEvent`, `HintBlockEvent` new event types. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0-RC3)
  65. - **[2026-06] `v2.0.0-RC2`:** Fully stateless agent; one-line DistributedBackend; subagent event forwarding; Channel module (DingTalk, Feishu, WeCom); A2A / AG-UI protocol support. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0-RC2)
  66. - **[2026-05] `v2.0.0-RC1`:** First 2.0 RC — harness engineering, enterprise distributed deployment, event stream / message model / middleware / HITL full redesign. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v2.0.0-RC1)
  67. - **[2026-05] `v1.1.0`:** Introduced `agentscope-harness` and `HarnessAgent`; Workspace (persona / memory / skills / subagents); pluggable filesystem (local / shared store / sandbox); session persistence with cross-process resume; layered memory and context compaction; declarative subagent orchestration. [Release Notes](https://github.com/agentscope-ai/agentscope-java/releases/tag/v1.1.0-RC1)
  68. <!-- END NEWS -->
  69. ## Community
  70. Welcome to join our community on
  71. | [Discord](https://discord.gg/eYMpfnkG8h) | DingTalk | WeChat |
  72. |--------------------------------------------------------------|-----------------------------------------------------------------------|--------------------------------------------------------------|
  73. | <img src="./docs/imgs/discord.png" width="100" height="100"> | <img src="./docs/imgs/dingtalk_qr_code.png" width="100" height="100"> | <img src="./docs/imgs/wechat.jpeg" width="100" height="100"> |
  74. ## Quickstart
  75. ### Installation
  76. > AgentScope Java requires **JDK 17** or higher.
  77. #### Maven
  78. ```xml
  79. <dependency>
  80. <groupId>io.agentscope</groupId>
  81. <artifactId>agentscope-harness</artifactId>
  82. <version>2.0.3</version>
  83. </dependency>
  84. ```
  85. Model providers are shipped as separate extension modules in 2.0. Add the one you need — for example, DashScope:
  86. ```xml
  87. <dependency>
  88. <groupId>io.agentscope</groupId>
  89. <artifactId>agentscope-extensions-model-dashscope</artifactId>
  90. <version>2.0.3</version>
  91. </dependency>
  92. ```
  93. Other options: `agentscope-extensions-model-openai`, `agentscope-extensions-model-anthropic`, `agentscope-extensions-model-gemini`, `agentscope-extensions-model-ollama`. See the [Model docs](https://java.agentscope.io/dev/en/docs/building-blocks/model.html) for details.
  94. For typed text and image classification, see [OpenAI Decisions](docs/dev/en/integration/judge/openai-decisions.md), available in `2.1.0-SNAPSHOT` builds containing the extension.
  95. To use the reasoning and tool APIs of `ReActAgent` and compose application capabilities yourself, depend on `agentscope-core` and your model extension.
  96. ## Hello AgentScope!
  97. Configure a shared Builder at startup, then use `builder.build()` to create and close an Agent for each request. The same identity and persistent storage keep the conversation across instances. Set `DASHSCOPE_API_KEY` before running:
  98. ```java
  99. import io.agentscope.core.agent.RuntimeContext;
  100. import io.agentscope.core.event.TextBlockDeltaEvent;
  101. import io.agentscope.core.event.ToolCallStartEvent;
  102. import io.agentscope.core.message.UserMessage;
  103. import io.agentscope.harness.agent.HarnessAgent;
  104. import java.nio.file.Paths;
  105. public class FirstAgent {
  106. // Configure once at startup; requests only call build().
  107. private static final HarnessAgent.Builder AGENT_BUILDER = HarnessAgent.builder()
  108. .name("assistant")
  109. .agentId("assistant")
  110. .sysPrompt("You are a helpful AI assistant.")
  111. .model("dashscope:qwen-plus")
  112. .workspace(Paths.get(".agentscope/workspace"));
  113. public static void main(String[] args) {
  114. try (HarnessAgent agent = AGENT_BUILDER.build()) {
  115. RuntimeContext ctx = RuntimeContext.builder()
  116. .sessionId("demo").userId("alice").build();
  117. agent.call(new UserMessage("Hello!"), ctx).block();
  118. }
  119. // COMMENT_Summarize today in three bullets.
  120. try (HarnessAgent agent = AGENT_BUILDER.build()) {
  121. RuntimeContext ctx = RuntimeContext.builder()
  122. .sessionId("demo").userId("alice").build();
  123. agent.streamEvents(new UserMessage("Summarize today in three bullets."), ctx)
  124. .doOnNext(event -> {
  125. switch (event.getType()) {
  126. case TEXT_BLOCK_DELTA -> System.out.print(
  127. ((TextBlockDeltaEvent) event).getDelta());
  128. case TOOL_CALL_START -> System.out.println(
  129. "\n[tool] " + ((ToolCallStartEvent) event).getToolCallName());
  130. default -> { }
  131. }
  132. })
  133. .blockLast();
  134. }
  135. }
  136. }
  137. ```
  138. Start with `call` / `streamEvents` for ordinary replies, multi-turn chat and workflow steps; follow the [Quick Start](https://java.agentscope.io/dev/en/docs/quickstart). Both also record Harness conversation history by default. Introduce [AgentSession](https://java.agentscope.io/dev/en/docs/harness/session-log) when work must continue after a page closes, queue while busy or resume after interruption. The [recoverable chat example](./agentscope-examples/agents/agentscope-chat/README.md) shows the full integration.
  139. ## Key Design
  140. AgentScope Java 2.0 is a major step up from a "build an agent" toolkit toward a complete platform for **running agents in production**. The improvements fall into three focus areas:
  141. ### 1 · Harness Engineering — built for long-running, complex tasks
  142. A bare ReAct loop solves one reasoning turn. **HarnessAgent** layers engineering infrastructure on top of ReActAgent via Middleware and Toolkit channels — the reasoning core stays untouched, capabilities layer on:
  143. - **Self-evolution & skill repository** — successful patterns auto-save as Markdown skills, shared across sessions and loaded on demand
  144. - **Layered memory** — in-context conversation + agent-curated `MEMORY.md` + on-disk fact log, with auto-compaction to bound the prompt
  145. - **Sub-agents** — declare child agent specs in Markdown, `agent_spawn` / `agent_send` at runtime, sync or background delegation
  146. - **Auto context management** — structured compaction preserves goals / state / findings / next steps; oversized tool results offload to disk
  147. - **Plan Mode** — read-only planning state for long tasks, plan files persist and drive execution
  148. ### 2 · Enterprise-grade distributed deployment
  149. Production agents must serve many tenants, run untrusted code safely, and survive rolling restarts. AgentScope 2.0 is built for stateless horizontal scaling:
  150. - **Multi-tenant isolation** — `session` / `user` / `agent` / `org` dimension isolation, `RuntimeContext` keys flow through workspace paths, KV namespaces, and sandbox state slots
  151. - **Secure sandbox** — local subprocess / Docker / Kubernetes / E2B cloud sandbox, with snapshot and resume
  152. - **Permission control** — three-state engine (allow / approve / deny), sensitive tools require HITL approval
  153. - **Session recovery** — `AgentStateStore` (in-memory / JSON file / MySQL / Redis / PostgreSQL) backs zero-downtime rolling deploys
  154. ### 3 · Foundation framework — a leaner, more developer-friendly core
  155. Messages, events, and the extension model are smaller, more orthogonal — HITL and event streaming are part of how the framework runs, not add-ons:
  156. - **Event stream** — 32 typed events covering model calls, text deltas, tool execution, and user confirmations in real time
  157. - **Message model** — text / files / images / audio / video / tool results unified into `ContentBlock`, role-strict validation at construction
  158. - **Middleware** — `onAgent` / `onReasoning` / `onActing` / `onModelCall` / `onSystemPrompt` / `onAgentStateReady` six stages replace v1's flat hooks
  159. - **HITL first class** — confirm tool arguments, approve sensitive actions, hand off to external systems, agent pauses and resumes exactly
  160. For the complete architecture overview, see the [documentation](https://java.agentscope.io/dev/en/docs/index.html).
  161. ## Contributing
  162. We welcome contributions from the community! Please refer to our [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines
  163. on how to contribute.
  164. ## License
  165. AgentScope is released under Apache License 2.0.
  166. ## Contributors
  167. All thanks to our contributors:
  168. <a href="https://github.com/agentscope-ai/agentscope-java/graphs/contributors">
  169. <img src="https://contrib.rocks/image?repo=agentscope-ai/agentscope-java&max=999&columns=12&anon=1" />
  170. </a>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.