### Quickstart: Initialize Mem0 Memory and Agent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/memory/mem0.md Configure and build a Mem0LongTermMemory instance for local use and then wire it into a ReActAgent. This setup automatically handles memory recording and retrieval during agent interactions. ```java import io.agentscope.core.memory.mem0.Mem0LongTermMemory; import io.agentscope.core.memory.mem0.Mem0ApiType; // 1. Build a memory instance (local, no auth) Mem0LongTermMemory memory = Mem0LongTermMemory.builder() .agentName("Assistant") .userId("user_123") .apiBaseUrl("http://localhost:8000") .apiType(Mem0ApiType.SELF_HOSTED) .build(); // 2. Wire it into an Agent ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .longTermMemory(memory) .longTermMemoryMode(LongTermMemoryMode.BOTH) .build(); // 3. Talk normally — memory is recorded/retrieved automatically agent.call(new UserMessage("I prefer homestays when traveling")).block(); ``` -------------------------------- ### Quickstart TrainingRunner Configuration Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/ecosystem/training.md Initialize and start the TrainingRunner to intercept Agent calls and begin sampling for online training. Customize sampling rate, reward calculation, and commit interval. ```java import io.agentscope.core.training.runner.TrainingRunner; import io.agentscope.core.training.strategy.SamplingRateStrategy; TrainingRunner runner = TrainingRunner.builder() .trinityEndpoint("http://localhost:8080") .modelName("/path/to/model") .selectionStrategy(SamplingRateStrategy.of(0.1)) // 10% sampling .rewardCalculator(agent -> 0.0) // custom reward .commitIntervalSeconds(300) // commit every 5 minutes .build(); runner.start(); // intercept Agent calls and start sampling // Business code keeps using the Agent unmodified agent.call(msg).block(); runner.stop(); // stop the training pipeline ``` -------------------------------- ### Higress Integration Quickstart Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/infrastructure/higress.md Set up a HigressMcpClient and register it with HigressToolkit to use Higress-managed tools within an Agent. ```java import io.agentscope.extensions.higress.HigressMcpClientBuilder; import io.agentscope.extensions.higress.HigressMcpClientWrapper; import io.agentscope.extensions.higress.HigressToolkit; // 1) Create a client against an MCP endpoint published by Higress HigressMcpClientWrapper client = HigressMcpClientBuilder .create("higress") .streamableHttpEndpoint("http://gateway/mcp-servers/union-tools-search") .build(); // 2) Register with HigressToolkit (a Toolkit subclass that caches the Higress client) HigressToolkit toolkit = new HigressToolkit(); toolkit.registerMcpClient(client).block(); // 3) Use it from an Agent ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .toolkit(toolkit) .build(); ``` -------------------------------- ### Install Git MCP Server Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Install the git server for McpToolExample using npm. ```bash # For git server npm install -g @modelcontextprotocol/server-git ``` -------------------------------- ### Quickstart Dify Knowledge Integration Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/rag/dify.md Initialize DifyKnowledge with configuration including API key, dataset ID, and retrieval mode. This example demonstrates how to retrieve documents based on a query. ```java import io.agentscope.core.rag.integration.dify.DifyKnowledge; import io.agentscope.core.rag.integration.dify.DifyRAGConfig; import io.agentscope.core.rag.integration.dify.RetrievalMode; import io.agentscope.core.rag.model.RetrieveConfig; DifyRAGConfig config = DifyRAGConfig.builder() .apiKey(System.getenv("DIFY_RAG_API_KEY")) .datasetId("your-dataset-id") .retrievalMode(RetrievalMode.HYBRID_SEARCH) .enableRerank(true) .build(); DifyKnowledge knowledge = DifyKnowledge.builder() .config(config) .build(); List hits = knowledge.retrieve( "How do I renew my membership?", RetrieveConfig.builder().limit(5).scoreThreshold(0.5).build() ).block(); ``` -------------------------------- ### Install Filesystem MCP Server Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Install the filesystem server for McpToolExample using npm. ```bash # For filesystem server npm install -g @modelcontextprotocol/server-filesystem ``` -------------------------------- ### Run Basic Chat Example with Debug Logging Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Execute the BasicChatExample with debug logging enabled to get detailed output. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample" \ -Dorg.slf4j.simpleLogger.defaultLogLevel=debug ``` -------------------------------- ### Run McpTool Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the McpToolExample to demonstrate MCP tool server integration, focusing on MCP and external tools. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.McpToolExample" ``` -------------------------------- ### Run Session Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the SessionExample to demonstrate persistent conversations using JsonSession for state management. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.SessionExample" ``` -------------------------------- ### Run Hook Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the HookExample to demonstrate monitoring agent execution using hooks and lifecycle callbacks. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.HookExample" ``` -------------------------------- ### Quickstart: Initialize and Use SimpleKnowledge Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/rag/simple.md Demonstrates the basic steps to set up an EmbeddingModel, Vector Store, SimpleKnowledge, ingest documents, and perform a retrieval. ```java import io.agentscope.core.embedding.dashscope.DashScopeTextEmbedding; import io.agentscope.core.rag.knowledge.SimpleKnowledge; import io.agentscope.core.rag.store.InMemoryStore; import io.agentscope.core.rag.model.RetrieveConfig; // 1) Embedding model EmbeddingModel embeddings = DashScopeTextEmbedding.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("text-embedding-v3") .dimensions(1024) .build(); // 2) Vector store (in-process here) VDBStoreBase store = InMemoryStore.builder().dimensions(1024).build(); // 3) Assemble Knowledge SimpleKnowledge knowledge = SimpleKnowledge.builder() .embeddingModel(embeddings) .embeddingStore(store) .build(); // 4) Ingest documents List docs = new TikaReader().read(input).block(); knowledge.addDocuments(docs).block(); // 5) Retrieve List hits = knowledge.retrieve( "What is AgentScope?", RetrieveConfig.builder().limit(5).scoreThreshold(0.5).build() ).block(); ``` -------------------------------- ### ngrok Tunnel Setup Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-claw/README.md Start a tunnel to make your local machine accessible from the public internet. This is required for WeCom and Feishu callbacks. ```bash ngrok http 8080 ``` -------------------------------- ### Build and Install AgentScope Java Library Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Builds and installs the main AgentScope Java library from the project root. ```bash cd agentscope-core-java mvn clean install ``` -------------------------------- ### Quickstart with Lettuce (Standalone) Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/redis.md Initialize a Redis session using Lettuce client in standalone mode. Ensure Redis is running on localhost:6379. ```java import io.lettuce.core.RedisClient; import io.agentscope.core.session.Session; import io.agentscope.core.session.redis.RedisSession; RedisClient redisClient = RedisClient.create("redis://localhost:6379"); Session session = RedisSession.builder() .lettuceClient(redisClient) .build(); ``` -------------------------------- ### Example CLI Prompts Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-codingagent/README.md Examples of user prompts for the interactive CLI agent, including writing files, fetching URLs, cloning repositories, and exiting. ```bash You> write hello.txt with a haiku about Java You> fetch https://github.com/anthropics/anthropic-sdk-python/blob/main/README.md and summarize it You> clone https://github.com/owner/repo into the workspace and tell me what it does You> /exit ``` -------------------------------- ### Compile AgentScope Java Examples Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Compiles the example code after the main library is built. ```bash cd examples mvn compile ``` -------------------------------- ### Distributed Sandbox Deployment Configuration Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/harness/sandbox.md This example demonstrates configuring a HarnessAgent for distributed deployment. It combines a DockerFilesystem with a specific isolation scope, a distributed session (e.g., Redis), and an OSS snapshot. The 'sandboxDistributed' option simplifies this setup. ```java HarnessAgent.builder() .name("assistant") .model(model) .filesystem(new DockerFilesystemSpec() .image("ubuntu:24.04") .isolationScope(IsolationScope.USER)) .sandboxDistributed(SandboxDistributedOptions.oss(redisSession, ossSnapshotSpec)) .build(); ``` -------------------------------- ### Initialize and Use HarnessAgent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/blogs/agentscope-v1-harness.md Example of building a HarnessAgent with custom workspace and compaction configurations, and making a call with a RuntimeContext. ```java HarnessAgent agent = HarnessAgent.builder() .name("my-agent") .model(model) .workspace(Paths.get(".agentscope/workspace")) .compaction(CompactionConfig.builder() .triggerMessages(50) .keepMessages(20) .build()) .build(); RuntimeContext ctx = RuntimeContext.builder() .sessionId("user-session-001") .userId("alice") .build(); Msg reply = agent.call(userMessage, ctx).block(); ``` -------------------------------- ### Quickstart MySQL Skill Repository Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/skill/mysql-repository.md Initialize and use the MysqlSkillRepository with a HikariDataSource. The `createIfNotExist` flag will auto-create the necessary database tables if they don't exist. ```java import com.zaxxer.hikari.HikariDataSource; import io.agentscope.core.skill.repository.mysql.MysqlSkillRepository; HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl("jdbc:mysql://localhost:3306/agentscope"); ds.setUsername("root"); ds.setPassword("***"); // Second arg createIfNotExist=true: auto-create database and tables MysqlSkillRepository repo = new MysqlSkillRepository(ds, true); Toolkit toolkit = new Toolkit(); repo.getAllSkills().forEach(toolkit::registerSkill); ``` -------------------------------- ### Quickstart: Initialize MySQL Session (Pre-created DB/Table) Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/mysql.md Initialize a MysqlSession when the database and table are already created. This form is safer as it will throw an exception if they are missing. ```java Session session = new MysqlSession(ds); // throws IllegalStateException if missing Session session = new MysqlSession(ds, false); // explicit ``` -------------------------------- ### Quickstart: Initialize GitSkillRepository Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/skill/git-repository.md Initialize a GitSkillRepository with a public repository URL. All skills are registered into a Toolkit. A shutdown hook is added to clean up the temporary local directory. ```java import io.agentscope.core.skill.repository.GitSkillRepository; import io.agentscope.core.skill.AgentSkill; // Public repo + default branch, temporary local directory GitSkillRepository repo = new GitSkillRepository( "https://github.com/agentscope/skills.git" ); // Register all skills into a Toolkit Toolkit toolkit = new Toolkit(); repo.getAllSkills().forEach(toolkit::registerSkill); // Clean up the temp directory on shutdown Runtime.getRuntime().addShutdownHook(new Thread(repo::close)); ``` -------------------------------- ### Quickstart: Initialize MySQL Session Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/mysql.md Initialize a HikariDataSource with your MySQL connection details and create a MysqlSession. The `createIfNotExist` flag can automatically create the database and table. ```java import com.zaxxer.hikari.HikariDataSource; import io.agentscope.core.session.Session; import io.agentscope.core.session.mysql.MysqlSession; HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl("jdbc:mysql://localhost:3306/agentscope?serverTimezone=UTC"); ds.setUsername("root"); ds.setPassword("***"); // Second arg createIfNotExist=true: auto-create database and table Session session = new MysqlSession(ds, true); SessionManager manager = SessionManager.builder().session(session).build(); ``` -------------------------------- ### Install MCP Server Filesystem Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Install the MCP server for filesystem operations using npm. ```bash npm install -g @modelcontextprotocol/server-filesystem ``` -------------------------------- ### Plan File Structure Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/harness/workspace.md Illustrates the default directory structure for plan files, with PLAN.md being the current plan written by plan_write. ```tree plans/ └── PLAN.md ← current plan written by plan_write ``` -------------------------------- ### Run Interruption Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the InterruptionExample to demonstrate the agent interruption mechanism, including user interruption and recovery. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.InterruptionExample" ``` -------------------------------- ### Complete AgentScope Java Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/SKILL.md This example demonstrates the full lifecycle of an AgentScope agent in Java. It includes setting up a model, defining tools, implementing a streaming hook, building the agent, and making a user request. Note that .block() is used here for simplicity in a main method and should not be used in production agent logic. ```java package com.example.agentscope; import io.agentscope.core.ReActAgent; import io.agentscope.core.hook.Hook; import io.agentscope.core.hook.HookEvent; import io.agentscope.core.hook.ReasoningChunkEvent; import io.agentscope.core.memory.InMemoryMemory; import io.agentscope.core.message.Msg; import io.agentscope.core.message.MsgRole; import io.agentscope.core.message.TextBlock; import io.agentscope.core.model.Model; import io.agentscope.core.tool.Tool; import io.agentscope.core.tool.ToolParam; import io.agentscope.core.tool.Toolkit; import io.agentscope.core.model.DashScopeChatModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * Complete example demonstrating AgentScope best practices. */ public class CompleteExample { private static final Logger log = LoggerFactory.getLogger(CompleteExample.class); public static void main(String[] args) { // 1. Create model (no .temperature() method, use defaultOptions) Model model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen-plus") .stream(true) .build(); // 2. Create toolkit with tools Toolkit toolkit = new Toolkit(); toolkit.registerTool(new WeatherTools()); toolkit.registerTool(new TimeTools()); // 3. Create hook for streaming output Hook streamingHook = new Hook() { @Override public Mono onEvent(T event) { if (event instanceof ReasoningChunkEvent e) { String text = e.getIncrementalChunk().getTextContent(); if (text != null) { System.out.print(text); } } return Mono.just(event); } @Override public int priority() { return 500; // Low priority } }; // 4. Build agent ReActAgent agent = ReActAgent.builder() .name("Assistant") .sysPrompt("You are a helpful assistant. Use tools when appropriate.") .model(model) .toolkit(toolkit) .memory(new InMemoryMemory()) .hook(streamingHook) .maxIters(10) .build(); // 5. Use agent Msg userMsg = Msg.builder() .role(MsgRole.USER) .content(TextBlock.builder() .text("What's the weather in San Francisco and what time is it?") .build()) .build(); try { System.out.println("User: " + userMsg.getTextContent()); System.out.print("Assistant: "); // ⚠️ IMPORTANT: .block() is ONLY allowed in main() methods for demo purposes // NEVER use .block() in agent logic, service methods, or library code Msg response = agent.call(userMsg).block(); System.out.println("\n\n--- Response Details ---"); System.out.println("Role: " + response.getRole()); System.out.println("Content: " + response.getTextContent()); } catch (Exception e) { log.error("Error during agent execution", e); System.err.println("Error: " + e.getMessage()); } } /** * Example tool class for weather information. */ public static class WeatherTools { @Tool(description = "Get current weather for a city. Returns temperature and conditions.") public String getWeather( @ToolParam(name = "city", description = "City name, e.g., 'San Francisco'") String city) { log.info("Getting weather for city: {}", city); // Simulate API call return String.format("Weather in %s: Sunny, 22°C, Light breeze", city); } } /** * Example tool class for time information. */ public static class TimeTools { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Tool(description = "Get current date and time") public String getCurrentTime() { LocalDateTime now = LocalDateTime.now(); String formatted = now.format(FORMATTER); log.info("Returning current time: {}", formatted); return "Current time: " + formatted; } } } ``` -------------------------------- ### Quickstart AG-UI Agent Adapter Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/protocol/agui.md Initialize and run the AguiAgentAdapter to stream AgentScope events as AG-UI events. Configure reasoning emission and run timeouts. ```java import io.agentscope.core.agui.adapter.AguiAdapterConfig; import io.agentscope.core.agui.adapter.AguiAgentAdapter; import io.agentscope.core.agui.event.AguiEvent; import io.agentscope.core.agui.model.RunAgentInput; import reactor.core.publisher.Flux; AguiAdapterConfig config = AguiAdapterConfig.builder() .enableReasoning(true) // emit ThinkingBlock as REASONING_* events .runTimeout(Duration.ofMinutes(5)) .build(); AguiAgentAdapter adapter = new AguiAgentAdapter(agent, config); // Events you'd ship to the front end via SSE Flux events = adapter.run(runAgentInput); ``` -------------------------------- ### RAGFlow Knowledge Quickstart Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/rag/ragflow.md Configure and use RAGFlowKnowledge for document retrieval. Ensure RAGFlow is running and accessible via the baseUrl. ```java import io.agentscope.core.rag.integration.ragflow.RAGFlowConfig; import io.agentscope.core.rag.integration.ragflow.RAGFlowKnowledge; import io.agentscope.core.rag.model.RetrieveConfig; RAGFlowConfig config = RAGFlowConfig.builder() .apiKey("ragflow-xxxxxxxx") .baseUrl("http://localhost:9380") .knowledgeBaseId("kb-xxxxx") .topK(10) .similarityThreshold(0.5) .enableRerank(true) .build(); RAGFlowKnowledge knowledge = RAGFlowKnowledge.builder() .config(config) .build(); List hits = knowledge.retrieve( "What is AI?", RetrieveConfig.builder().limit(5).build() ).block(); ``` -------------------------------- ### Run Tool Group Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the ToolGroupExample to demonstrate autonomous tool group management. Focuses on meta-tools, tool groups, and self-activation. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolGroupExample" ``` -------------------------------- ### Tools Configuration Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/harness/workspace.md Configures the allowed and denied tools, and specifies MCP servers for the agent. Environment variables can be used for configuration. ```json { // allowlist: when non-empty, only listed tools survive "allow": ["read_file", "grep_files", "execute"], // denylist: listed tools are always removed (wins over allow) "deny": ["write_file"], // MCP servers, keyed by name "mcpServers": { "amap": { "transport": "streamableHttp", "url": "https://mcp.amap.com/mcp?key=${AMAP_API_KEY}" }, "local-py": { "transport": "stdio", "command": "python", "args": ["mcp_servers/my_server.py"], "env": {"PYTHONUNBUFFERED": "1"} } } } ``` -------------------------------- ### Run Streaming Web Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the StreamingWebExample to demonstrate Spring Boot integration with SSE streaming for real-time web API communication. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.StreamingWebExample" ``` -------------------------------- ### Knowledge Base Structure Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/harness/workspace.md Demonstrates the organization of knowledge base files, where KNOWLEDGE.md is injected into the system prompt and other files are read on demand. ```tree knowledge/ ├── KNOWLEDGE.md ← entry / overview, injected in full into the system prompt ├── api-reference.md ├── domain-terms.md └── ... ``` -------------------------------- ### Configure Redisson Client Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/redis.md Initialize a Redis session with Redisson client. This example configures a single server connection. ```java import org.redisson.Redisson; import org.redisson.config.Config; import org.redisson.api.RedissonClient; import io.agentscope.core.session.Session; Config config = new Config(); config.useSingleServer().setAddress("redis://localhost:6379"); RedissonClient redisson = Redisson.create(config); Session session = RedisSession.builder() .redissonClient(redisson) .build(); ``` -------------------------------- ### Run Basic Chat Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the BasicChatExample to demonstrate the simplest agent conversation. Learn to create a ReActAgent and configure its Model, Memory, and Formatter. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.BasicChatExample" ``` -------------------------------- ### AgentScope Builder Quick Start Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-builder/README.md Build and run the AgentScope Builder application. Ensure your model API key is set as an environment variable. ```bash # Set your model API key export DASHSCOPE_API_KEY=sk-xxx # Build and run mvn -pl agentscope-examples/agents/agentscope-builder -am clean package -DskipTests java -jar agentscope-examples/agents/agentscope-builder/target/agentscope-builder-*.jar ``` -------------------------------- ### Quickstart Bailian Long-Term Memory Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/memory/bailian.md Initialize and use BailianLongTermMemory with essential configurations. Ensure to use try-with-resources for proper connection management. ```java import io.agentscope.core.memory.bailian.BailianLongTermMemory; try (BailianLongTermMemory memory = BailianLongTermMemory.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .userId("user_001") .memoryLibraryId("lib_xxxxx") .projectId("proj_xxxxx") .build()) { ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .longTermMemory(memory) .longTermMemoryMode(LongTermMemoryMode.BOTH) .build(); agent.call(new UserMessage("Remind me to drink water at 9am every day")).block(); } ``` -------------------------------- ### Product Requirements Extraction Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Demonstrates extracting structured product requirements from natural language input. The output is a typed ProductRequirements object. ```text === Example 1: Product Information === Query: I'm looking for a laptop. I need at least 16GB RAM, prefer Apple brand... Extracted structured data: Product Type: laptop Brand: Apple Min RAM: 16 GB Max Budget: $2000.0 Features: [lightweight, travel-friendly] ``` -------------------------------- ### Initialize XXL-Job Executor and AgentScheduler Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-extensions/agentscope-extensions-scheduler/README.md Configure and start the XXL-Job Executor to connect to the admin server. Then, create an AgentScheduler instance using the initialized executor. ```java XxlJobExecutor executor = new XxlJobExecutor(); executor.setAdminAddresses("http://localhost:8080/xxl-job-admin"); // Server address obtained in Step 1 executor.setAppname("agentscope-demo"); // Application name, must match server configuration executor.setAccessToken("xxxxxxxx"); // Access token (optional, recommended for production) executor.setPort(9999); // Executor port executor.start(); // Create AgentScope scheduler instance AgentScheduler scheduler = new XxlJobAgentScheduler(executor); ``` -------------------------------- ### Create a Human Approval Tool Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/building-blocks/tool.md Implement an external tool by setting `externalTool` to `true` and skipping `callAsync`. This example defines a `HumanApprovalTool` for requesting human approval. ```java import io.agentscope.core.permission.PermissionDecision; import io.agentscope.core.tool.ToolBase; import io.agentscope.core.tool.ToolExecutionContext; import java.util.List; import java.util.Map; import reactor.core.publisher.Mono; public class HumanApprovalTool extends ToolBase { public HumanApprovalTool() { super( ToolBase.builder() .name("HumanApproval") .description("Request human approval for a sensitive operation.") .inputSchema(Map.of( "type", "object", "properties", Map.of( "action", Map.of("type", "string"), "reason", Map.of("type", "string")), "required", List.of("action", "reason"))) .readOnly(false) .concurrencySafe(true) .externalTool(true)); } @Override public Mono checkPermissions( Map toolInput, ToolExecutionContext context) { return Mono.just(PermissionDecision.allow("External tool dispatch is always allowed.")); } } ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/README.md Installs the necessary development dependencies for the project. Ensure you have Python 3.10+ installed. ```bash python -m pip install --upgrade pip pip install -e ".[dev]" ``` -------------------------------- ### Create and Run Your First Agent with HarnessAgent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/quickstart.md This Java example demonstrates setting up a note-taking agent using HarnessAgent. It showcases workspace configuration, automatic session persistence, and conversation compaction. The model is specified as a string, and the API key is automatically picked up from the environment. ```java import io.agentscope.core.agent.RuntimeContext; import io.agentscope.core.message.UserMessage; import io.agentscope.harness.agent.HarnessAgent; import io.agentscope.harness.agent.memory.compaction.CompactionConfig; import java.nio.file.Paths; public class FirstAgent { public static void main(String[] args) { HarnessAgent agent = HarnessAgent.builder() .name("note-taker") .sysPrompt("You are a note-taking assistant.") // String form resolved via ModelRegistry — picks up DASHSCOPE_API_KEY // from the environment. Use "openai:gpt-5.5", "anthropic:claude-sonnet-4-5", // "gemini:gemini-2.0-flash", or "ollama:llama3" to switch providers. .model("dashscope:qwen-plus") .workspace(Paths.get(".agentscope/workspace")) .compaction(CompactionConfig.builder() .triggerMessages(30) .keepMessages(10) .build()) .build(); RuntimeContext ctx = RuntimeContext.builder() .sessionId("demo-session") .userId("alice") .build(); // Turn 1: introduce yourself + state today's task agent.call(new UserMessage("My name is Alice, and I'm preparing a tech talk on ReAct today."), ctx).block(); // Turn 2: same sessionId — state from turn 1 is restored automatically agent.call(new UserMessage("What is my name? What am I doing today?"), ctx).block(); } } ``` -------------------------------- ### Streaming UI Example with Agent Events Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/building-blocks/message-and-event.md This example shows a typical streaming UI loop using agent events, suitable for real-time updates in a web application. It processes events to display agent output incrementally and logs key stages of the interaction. This pattern is useful for building responsive user interfaces that reflect ongoing agent processing. ```java import io.agentscope.core.event.AgentEndEvent; import io.agentscope.core.event.AgentStartEvent; import io.agentscope.core.event.TextBlockDeltaEvent; import io.agentscope.core.event.ToolCallStartEvent; import io.agentscope.core.event.ToolResultEndEvent; import io.agentscope.core.message.UserMessage; agent.streamEvents(new UserMessage("user", "Help me fix this bug")) .doOnNext(event -> { if (event instanceof AgentStartEvent start) { System.out.println("[start replyId=" + start.getReplyId() + "]"); } else if (event instanceof TextBlockDeltaEvent delta) { System.out.print(delta.getDelta()); } else if (event instanceof ToolCallStartEvent tc) { System.out.println("\n[calling " + tc.getToolCallName() + "...]"); } else if (event instanceof ToolResultEndEvent end) { System.out.println("[tool finished: " + end.getState() + "]"); } else if (event instanceof AgentEndEvent end) { System.out.println("\n[done]"); } }) .blockLast(); ``` -------------------------------- ### Create and Use a ReAct Agent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/README.md This example shows how to build a ReAct agent, configure it with a system prompt and a chat model (DashScope), and make a simple text-based call. The API key should be set as an environment variable. ```java ReActAgent agent = ReActAgent.builder() .name("Assistant") .sysPrompt("You are a helpful AI assistant.") .model(DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen-max") .build()) .build(); Msg response = agent.call(Msg.builder() .textContent("Hello!") .build()).block(); System.out.println(response.getTextContent()); ``` -------------------------------- ### observe Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/building-blocks/agent.md Injects a message into the agent's context without triggering a reply, useful in multi-agent setups. ```APIDOC ## observe ### Description Use `observe` to inject a message into the agent's context without triggering a reply — useful in multi-agent setups where one agent observes another agent's output. ### Method `observe(Msg msg)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java agent.observe(otherAgentMsg).block(); ``` ### Response #### Success Response (200) This method returns a Mono and does not return any specific data upon successful completion. #### Response Example None ``` -------------------------------- ### Run Tool Calling Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the ToolCallingExample to demonstrate equipping agents with tools. Learn to define tools with the @Tool annotation, register them to a Toolkit, and observe automatic tool calling by the agent. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.ToolCallingExample" ``` -------------------------------- ### Configure Jedis Client Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/redis.md Integrate AgentScope session with Jedis client. This example uses a Jedis pooled connection. ```java import redis.clients.jedis.UnifiedJedis; import io.agentscope.core.session.Session; UnifiedJedis jedis = new redis.clients.jedis.JedisPooled("localhost", 6379); Session session = RedisSession.builder() .jedisClient(jedis) // UnifiedJedis, JedisCluster, JedisSentineled all work .build(); ``` -------------------------------- ### Unified Diff Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-codingagent/src/main/resources/workspace-templates/skills/apply-patch/SKILL.md Construct a unified diff for applying changes to a file. This format is used by git apply. ```diff diff --git a/path/to/file b/path/to/file --- a/path/to/file +++ b/path/to/file @@ -10,7 +10,7 @@ context line -old line +new line ``` -------------------------------- ### Configuring Skill Repositories for Production Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/others/going-to-production.md Demonstrates how to configure GitSkillRepository and MysqlSkillRepository. For production, MysqlSkillRepository with writeable set to false is recommended for read-only distribution. ```java HarnessAgent agent = HarnessAgent.builder() // ... .skillRepository(new GitSkillRepository("https://github.com/your-org/team-skills.git")) .skillRepository(MysqlSkillRepository.builder(dataSource) .databaseName("agentscope") .skillsTableName("skills") .createIfNotExist(true) .writeable(false) // read-only distribution; recommended for production .build()) .build(); ``` -------------------------------- ### Run Structured Output Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/README.md Executes the StructuredOutputExample to demonstrate generating typed structured output from natural language. Learn to define output schemas using Java classes and request structured responses. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.examples.StructuredOutputExample" ``` -------------------------------- ### Start DingTalk 1:1 Chat Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-codingagent/README.md Initiate a direct message conversation with the bot in DingTalk. The bot will respond to the message. ```text 帮我克隆 https://github.com/owner/repo 并总结这个项目 ``` -------------------------------- ### Run the DataAgent application Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-dataagent/README.md Execute the DataAgent application using the Java JAR file. The application will start on http://localhost:8080. ```bash java -jar target/agentscope-dataagent-*-exec.jar ``` -------------------------------- ### Registering a FileSystemSkillRepository Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/building-blocks/tool.md Attaches a FileSystemSkillRepository to a ReActAgent builder to enable skill discovery from a specified directory. The builder automatically installs DynamicSkillMiddleware. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.skill.repository.FileSystemSkillRepository; import java.nio.file.Paths; ReActAgent agent = ReActAgent.builder() .name("SkillCreator") .sysPrompt("...") .model(model) .skillRepository(new FileSystemSkillRepository(Paths.get("/path/to/skills"), false)) .build(); ``` -------------------------------- ### Plan Mode Denial Message Example Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/harness/plan-mode.md Illustrates the message an agent receives when attempting to use a non-whitelisted tool during Plan Mode. ```text [Tool denied — plan mode is active] Only read-only tools and plan_enter / plan_write / plan_exit / todo_write are allowed. ``` -------------------------------- ### Wiring AgentSkillRepository with Toolkit and ReActAgent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/skill/index.md Demonstrates how to load all skills from a repository, register them to a Toolkit, and then build a ReActAgent using that toolkit. Ensure you have an AgentSkillRepository implementation and a model instance ready. ```java AgentSkillRepository repo = ...; // any implementation List skills = repo.getAllSkills(); Toolkit toolkit = new Toolkit(); skills.forEach(toolkit::registerSkill); ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .toolkit(toolkit) .build(); ``` -------------------------------- ### Build A2A Server with ReActAgent Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/protocol/a2a.md Construct an AgentScopeA2aServer to expose a ReActAgent. This setup requires configuring the agent builder and transport properties. ```java import io.agentscope.core.a2a.server.AgentScopeA2aServer; import io.agentscope.core.a2a.server.transport.jsonrpc.JsonRpcTransportProperties; ReActAgent.Builder agentBuilder = ReActAgent.builder() .name("backend-agent") .model(model); AgentScopeA2aServer server = AgentScopeA2aServer.builder() .agentBuilder(agentBuilder) .transportProperties(new JsonRpcTransportProperties()) // .agentCard(customCard) // .agentRegistry(myRegistry) .build(); // Delegate inbound requests to the transport wrapper from your web framework TransportWrapper wrapper = server.getTransportWrapper("JSONRPC"); // ... Spring/Quarkus controller forwards to wrapper.handle(...) server.postEndpointReady(); // call after the web server is listening — triggers registration etc. ``` -------------------------------- ### Start DingTalk Group Chat Source: https://github.com/agentscope-ai/agentscope-java/blob/main/agentscope-examples/agents/agentscope-codingagent/README.md Engage the bot in a DingTalk group chat by mentioning it. The bot will reply within the group conversation. ```text @coding-bot 看一下昨天合并到 main 的那个 PR,有没有遗留 TODO ``` -------------------------------- ### Registering Tools with Toolkit Source: https://github.com/agentscope-ai/agentscope-java/blob/main/SKILL.md Instantiate a Toolkit and register instances of your tool classes to make them available for use. ```java Toolkit toolkit = new Toolkit(); toolkit.registerTool(new WeatherTools()); toolkit.registerTool(new AsyncTools()); ``` -------------------------------- ### Configuring Docker Sandbox for Production Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/others/going-to-production.md Example of configuring a Docker-based sandbox environment. The isolationScope is set to SESSION for user isolation within a session. ```java .filesystem(new DockerFilesystemSpec() .image("ubuntu:24.04") .isolationScope(IsolationScope.SESSION)) ``` -------------------------------- ### Configure AgentRun with NAS and OSS Mounts Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/others/going-to-production.md Set up an AgentRunFilesystemSpec for scenarios requiring multiple sandbox instances to mount the same directory, leveraging NAS for efficiency. This example configures API keys, account ID, region, template name, NAS mount, and an OSS mount. ```java .filesystem(new AgentRunFilesystemSpec() .apiKey(System.getenv("AGENTRUN_API_KEY")) .accountId(System.getenv("ALI_ACCOUNT_ID")) .region("cn-hangzhou") .templateName("python-3.12") .nasConfig(new AgentRunNasMountConfig().fileSystemId("...").mountTargetDomain("...").mountDir("/workspace")) .addOssMount(new AgentRunOssMountConfig().bucketName("data").mountDir("/mnt/oss"))) ``` -------------------------------- ### Direct API Usage: Maintenance Operations Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/session/mysql.md Provides examples for checking session existence, deleting a session, and listing all active session keys. ```java // Maintenance boolean exists = session.exists(key); session.delete(key); Set all = session.listSessionKeys(); ``` -------------------------------- ### Configure and Use NacosSkillRepository Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/infrastructure/nacos.md Initialize NacosSkillRepository to download skills from Nacos. Skill version and label resolution follows a specific order: Properties → System Properties → Environment Variables. ```java import io.agentscope.core.nacos.skill.NacosSkillRepository; Properties props = new Properties(); props.setProperty(NacosSkillRepository.SKILL_VERSION_PATH, "1.2.0"); // or SKILL_LABEL_PATH = "stable" NacosSkillRepository repo = new NacosSkillRepository(aiService, "default-namespace", props); AgentSkill skill = repo.getSkill("calculator"); ``` -------------------------------- ### Registering Built-in TodoTools Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/docs/building-blocks/tool.md An example of registering the built-in TodoTools with a Toolkit. This tool helps maintain a structured task list for the current session. ```java Toolkit toolkit = new Toolkit(); toolkit.registerTool(new io.agentscope.core.tool.builtin.TodoTools()); ``` -------------------------------- ### Configure GitSkillRepository with Branch and Local Path Source: https://github.com/agentscope-ai/agentscope-java/blob/main/docs/v2/en/integration/skill/git-repository.md Initialize GitSkillRepository specifying a branch, a fixed local path for the repository clone, a source label, and whether to enable auto-sync. ```java GitSkillRepository repo = new GitSkillRepository( "https://github.com/agentscope/skills.git", "develop", // branch Path.of("/var/skills/repo"), // local path (null = temp dir) "agentscope-public", // source label (visible in Toolkit) true // autoSync ); ```