### Higress Integration Quickstart Source: https://java.agentscope.io/_sources/v2/en/integration/infrastructure/higress Quickstart example demonstrating how to create a Higress MCP client, register it with HigressToolkit, and use it to build an Agent. This setup allows the Agent to discover and use tools published via Higress. ```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(); ``` -------------------------------- ### Execute Harness Quickstart Example Source: https://java.agentscope.io/_sources/v1/en/docs/harness/overview This command executes the quickstart example for the Harness agent. It specifies the main class to run and skips spotless checks. ```bash mvn -pl agentscope-examples/agents/harness-examples/harness-quickstart exec:java \ -Dexec.mainClass=io.agentscope.harness.example.QuickstartExample \ -Dspotless.check.skip=true -q ``` -------------------------------- ### Run Harness Quickstart Example Source: https://java.agentscope.io/_sources/v1/en/docs/harness/overview Command to set the environment variable for the API key and then run the Maven install command for the harness-quickstart module. It skips tests, Javadoc, and spotless checks for a faster build. ```bash export DASHSCOPE_API_KEY=your_key_here # First run: install dependency modules to local repo (skip javadoc and spotless) mvn -pl agentscope-examples/agents/harness-examples/harness-quickstart -am install \ -DskipTests -Dspotless.check.skip=true -Dmaven.javadoc.skip=true -q ``` -------------------------------- ### Example Project Setup Source: https://java.agentscope.io/_sources/v1/en/docs/task/agui Clone the example project and set the DASHSCOPE_API_KEY environment variable to run the complete AG-UI integration demo. ```bash export DASHSCOPE_API_KEY=your-key cd agentscope-examples/integration/agui mvn spring-boot:run ``` -------------------------------- ### Run Complete MCP Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/mcp Execute the complete MCP tool example using Maven after navigating to the quickstart directory. ```bash cd agentscope-examples/documentation/quickstart mvn exec:java -Dexec.mainClass="io.agentscope.examples.quickstart.McpToolExample" ``` -------------------------------- ### Complete Online Training Example in Java Source: https://java.agentscope.io/_sources/v1/en/docs/task/online-training A comprehensive Java example demonstrating the setup and execution of online training. It includes starting the TrainingRunner, defining agent behavior with a production model, and stopping the runner upon completion. ```java import io.agentscope.core.training.runner.TrainingRunner; import io.agentscope.core.training.strategy.SamplingRateStrategy; // 1. Start training runner (no Task ID/Run ID needed!) TrainingRunner runner = TrainingRunner.builder() .trinityEndpoint("http://trinity-backend:8010") .modelName("/path/to/qwen-model") .selectionStrategy(SamplingRateStrategy.of(0.1)) // 10% sampling .rewardCalculator(agent -> 0.0) // Custom reward calculation logic .commitIntervalSeconds(300) // Commit every 5 minutes .build(); runner.start(); // 2. Use your Agent normally - training happens transparently! ReActAgent agent = ReActAgent.builder() .name("ProductionAgent") .model(gpt4Model) // Production model (GPT-4) .tools(tools) .build(); // User requests are processed normally (using GPT-4), 10% automatically sampled for training Msg response = agent.call(Msg.builder().textContent("Search for Python tutorials").build()).block(); // 3. Stop when training is complete runner.stop(); ``` -------------------------------- ### Quickstart Training Runner Configuration Source: https://java.agentscope.io/_sources/v2/en/integration/ecosystem/training Configure and start the TrainingRunner to intercept Agent calls, sample traffic, and initiate the training pipeline. This example demonstrates setting a Trinity endpoint, model name, sampling rate, custom 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 ``` -------------------------------- ### Initialize AgentScope Studio Connection and Attach Hook Source: https://java.agentscope.io/_sources/v2/en/integration/ecosystem/studio Quickstart example demonstrating how to initialize the Studio connection and attach a `StudioMessageHook` to a `ReActAgent` for real-time message mirroring. ```java import io.agentscope.core.studio.StudioManager; import io.agentscope.core.studio.StudioMessageHook; // 1) Initialize Studio connection (HTTP + WebSocket) StudioManager.init() .studioUrl("http://localhost:8000") .project("MyProject") .runName("experiment_001") .initialize() .block(); // 2) Attach StudioMessageHook so messages are pushed to Studio ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .hook(new StudioMessageHook(StudioManager.getClient())) .build(); // 3) Use the Agent normally; Studio mirrors the conversation agent.call(msg).block(); ``` -------------------------------- ### Build and Run Example Project Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/handoffs Commands to build and run the AgentScope handoff example project using Maven. This includes packaging the project and starting the Spring Boot application. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/handoffs -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/handoffs spring-boot:run ``` -------------------------------- ### Quickstart Example for HarnessAgent Source: https://java.agentscope.io/_sources/v1/en/docs/harness/overview Demonstrates workspace-driven persona, session persistence, and explicit conversation compaction with HarnessAgent. The workspace is initialized, a model is built, and HarnessAgent is configured with workspace, session, and compaction settings. Two conversation turns are made with the same RuntimeContext to show state restoration. ```java public class QuickstartExample { public static void main(String[] args) throws Exception { // 1. Prepare workspace: generate AGENTS.md on first run, reuse afterwards Path workspace = Paths.get(".agentscope/workspace"); initWorkspaceIfAbsent(workspace); // 2. Build model Model model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen-max") .stream(true) .build(); // 3. Build HarnessAgent: workspace injection, session persistence, and trace logging // are enabled by default; compaction is explicitly configured here HarnessAgent agent = HarnessAgent.builder() .name("quickstart-agent") .sysPrompt("You are a note-taking assistant.") .model(model) .workspace(workspace) .compaction(CompactionConfig.builder() .triggerMessages(30) .keepMessages(10) .flushBeforeCompact(true) // extract facts to daily log before compacting .build()) .build(); // 4. Two conversation turns with the same RuntimeContext // Same sessionId → turn 2 auto-restores state from turn 1 RuntimeContext ctx = RuntimeContext.builder() .sessionId("demo-session") .userId("alice") .build(); Msg turn1 = agent.call( Msg.builder().role(MsgRole.USER) .textContent("My name is Alice, and I'm preparing a tech talk on ReAct today.") .build(), ctx).block(); System.out.println("[turn1] " + turn1.getTextContent()); Msg turn2 = agent.call( Msg.builder().role(MsgRole.USER) .textContent("What is my name? What am I doing today?") .build(), ctx).block(); System.out.println("[turn2] " + turn2.getTextContent()); } private static void initWorkspaceIfAbsent(Path workspace) throws Exception { Files.createDirectories(workspace); Path agentsMd = workspace.resolve("AGENTS.md"); if (Files.exists(agentsMd)) return; Files.writeString(agentsMd, """# Note-taking Assistant You are an assistant that helps users organize notes and knowledge. ## Behavior Guidelines - Actively record key facts the user mentions (names, plans, preferences, etc.) - Reply concisely, using bullet lists when helpful - For uncertain information, say so clearly rather than guessing """); } } ``` -------------------------------- ### Install and Run AgentScope Studio Source: https://java.agentscope.io/_sources/v1/en/docs/task/observability Install the AgentScope Studio package globally or locally and start the development server. Studio will be accessible at http://localhost:5173. ```bash git clone https://github.com/agentscope-ai/agentscope-studio cd agentscope-studio npm install npm run dev ``` ```bash npm install -g @agentscope/studio # or npm install @agentscope/studio as_studio ``` -------------------------------- ### Building and Running the Supervisor Example Project Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/supervisor Commands to build the supervisor example project using Maven and then run the Spring Boot application. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/supervisor -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/supervisor spring-boot:run ``` -------------------------------- ### Build and Run AgentScope Skills Example Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/skills Commands to build and run the multi-agent skills example project using Maven. This includes packaging the application and starting the Spring Boot application. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/skills -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/skills spring-boot:run ``` -------------------------------- ### Run Higress Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/mcp Navigate to the agentscope-examples directory and execute the Higress tool example using Maven. ```bash cd agentscope-examples/documentation/quickstart mvn exec:java -Dexec.mainClass="io.agentscope.examples.quickstart.HigressToolExample" ``` -------------------------------- ### Quickstart with Lettuce (Standalone) Source: https://java.agentscope.io/_sources/v2/en/integration/session/redis Initialize a Redis session using a Lettuce Redis client in standalone mode. ```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(); ``` -------------------------------- ### Complete Session Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/session Demonstrates creating, loading, using, and saving an agent session with in-memory storage. ```java import io.agentscope.core.ReActAgent; 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.session.JsonSession; import io.agentscope.core.session.Session; import java.nio.file.Path; public class SessionExample { public static void main(String[] args) { // Create components InMemoryMemory memory = new InMemoryMemory(); ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .memory(memory) .build(); // Set up session String sessionId = "user_session_001"; Path sessionPath = Path.of(System.getProperty("user.home"), ".agentscope", "sessions"); Session session = new JsonSession(sessionPath); // Load existing session (if exists) if (agent.loadIfExists(session, sessionId)) { System.out.println("Loaded session: " + sessionId); } else { System.out.println("New session: " + sessionId); } // Use Agent Msg userMsg = Msg.builder() .role(MsgRole.USER) .content(TextBlock.builder().text("Hello").build()) .build(); Msg response = agent.call(userMsg).block(); // Save session agent.saveTo(session, sessionId); System.out.println("Session saved"); } } ``` -------------------------------- ### Build and Run AgentScope Routing Examples Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/routing Commands to build and run the AgentScope routing examples project using Maven. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/routing -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/routing spring-boot:run ``` -------------------------------- ### Complete Studio Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/observability This example demonstrates a full conversation loop between a user and an AI agent, with all interactions visualized in Studio. Ensure the Studio backend is running and accessible at http://localhost:3000. ```java package io.agentscope.examples; import io.agentscope.core.ReActAgent; import io.agentscope.core.message.Msg; import io.agentscope.core.model.DashScopeChatModel; import io.agentscope.core.studio.StudioManager; import io.agentscope.core.studio.StudioMessageHook; import io.agentscope.core.studio.StudioUserAgent; public class StudioExample { public static void main(String[] args) throws Exception { String apiKey = System.getenv("DASHSCOPE_API_KEY"); System.out.println("Connecting to Studio at http://localhost:3000..."); // Initialize Studio StudioManager.init() .studioUrl("http://localhost:3000") .project("JavaExamples") .runName("studio_demo_" + System.currentTimeMillis()) .initialize() .block(); System.out.println("Connected to Studio\n"); try { // Create Agent (with Studio Hook) ReActAgent agent = ReActAgent.builder() .name("Assistant") .sysPrompt("You are a helpful AI assistant.") .model(DashScopeChatModel.builder() .apiKey(apiKey) .modelName("qwen3-max") .build()) .hook(new StudioMessageHook(StudioManager.getClient())) .build(); // Create user Agent StudioUserAgent user = StudioUserAgent.builder() .name("User") .studioClient(StudioManager.getClient()) .webSocketClient(StudioManager.getWebSocketClient()) .build(); // Conversation loop System.out.println("Starting conversation (type 'exit' to quit)"); System.out.println("Open http://localhost:3000 to interact\n"); Msg msg = null; int turn = 1; while (true) { System.out.println("[Turn " + turn + "] Waiting for user input..."); msg = user.call(msg).block(); if (msg == null || "exit".equalsIgnoreCase(msg.getTextContent())) { System.out.println("\nConversation ended"); break; } System.out.println("[Turn " + turn + "] User: " + msg.getTextContent()); msg = agent.call(msg).block(); if (msg != null) { System.out.println("[Turn " + turn + "] Agent: " + msg.getTextContent() + "\n"); } turn++; } } finally { System.out.println("\nShutting down..."); StudioManager.shutdown(); System.out.println("Done\n"); } } } ``` -------------------------------- ### Shell Command Execution and State Persistence Example Source: https://java.agentscope.io/_sources/v1/en/docs/harness/sandbox/index Illustrates how shell commands like 'pip install' and script execution are handled, with state (installed packages, created files) persisting across multiple calls within the sandbox. ```text call 1: shell_execute("pip install pandas") → pandas installed in sandbox call 2: shell_execute("python analyze.py") → directly available, no reinstall call 3: shell_execute("cat results.csv") → reads file produced in call 2 ``` -------------------------------- ### Run Sub-agent Example Interactively Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/subagent Execute the multi-agent sub-agent example interactively using Maven. This command starts the application with interactive chat enabled. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/subagent spring-boot:run \ -Dspring-boot.run.arguments="--subagent.run-interactive=true" ``` -------------------------------- ### Run Hook Example with Maven Source: https://java.agentscope.io/_sources/v1/en/docs/task/hook Execute the complete Hook example using Maven. Navigate to the example directory and run the specified Maven command. ```bash cd agentscope-examples/documentation/quickstart mvn exec:java -Dexec.mainClass="io.agentscope.examples.quickstart.HookExample" ``` -------------------------------- ### Quickstart: Initialize MySQL Skill Repository Source: https://java.agentscope.io/_sources/v2/en/integration/skill/mysql-repository Initialize the MysqlSkillRepository with a HikariDataSource and optionally enable auto-creation of database tables. Then, load all skills and register them with a Toolkit. ```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); ``` -------------------------------- ### Install Trinity Training Backend Source: https://java.agentscope.io/_sources/v1/en/docs/task/online-training Clone the Trinity-RFT repository and install the necessary Python dependencies, including flash-attn, to set up the training backend. Ensure Python 3.10-3.12 and CUDA >= 12.8 are installed. ```bash git clone https://github.com/agentscope-ai/Trinity-RFT cd Trinity-RFT pip install -e ".[dev]" pip install flash-attn==2.8.1 ``` -------------------------------- ### Complete Dify RAG Configuration Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/rag A comprehensive example of Dify RAG configuration, covering connection, retrieval, reranking, metadata filtering, and HTTP settings. Use this as a template for full setup. ```java DifyRAGConfig config = DifyRAGConfig.builder() // === Connection Configuration (Required) === .apiKey(System.getenv("DIFY_RAG_API_KEY")) // Dataset API Key .datasetId("your-dataset-uuid") // Dataset ID (UUID format) // === Endpoint Configuration (Optional) === .apiBaseUrl("https://api.dify.ai/v1") // Dify Cloud (default) // .apiBaseUrl("https://your-dify.com/v1") // Self-hosted instance // === Retrieval Configuration (Optional) === .retrievalMode(RetrievalMode.HYBRID_SEARCH) // Retrieval mode, default HYBRID_SEARCH // Available modes: KEYWORD, SEMANTIC_SEARCH, HYBRID_SEARCH, FULLTEXT .topK(10) // Number of results, range 1-100, default 10 .scoreThreshold(0.5) // Similarity threshold, range 0.0-1.0, default 0.0 .weights(0.6) // Hybrid search semantic weight, range 0.0-1.0 // === Reranking Configuration (Optional) === .enableRerank(true) // Enable reranking, default false .rerankConfig(RerankConfig.builder() .providerName("cohere") // Rerank model provider .modelName("rerank-english-v2.0") // Rerank model name .topN(5) // Number of results after reranking .build()) // === Metadata Filtering (Optional) === .metadataFilter(MetadataFilter.builder() .logicalOperator("AND") // Logical operator: AND or OR .addCondition(MetadataFilterCondition.builder() .name("category") // Metadata field name .comparisonOperator("=") // Comparison operator .value("documentation") // Filter value .build()) .build()) // === HTTP Configuration (Optional) === .connectTimeout(Duration.ofSeconds(30)) // Connection timeout, default 30s .readTimeout(Duration.ofSeconds(60)) // Read timeout, default 60s .maxRetries(3) // Max retries, default 3 .addCustomHeader("X-Custom-Header", "value") // Custom headers .build(); ``` -------------------------------- ### Complete Bailian Configuration Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/rag A comprehensive example demonstrating all configurable options for Bailian, including connection, retrieval, reranking, query rewriting, and other settings. ```java BailianConfig config = BailianConfig.builder() // === Connection Configuration (Required) === .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) .workspaceId("llm-xxx") // Bailian workspace ID .indexId("mymxbdxxxx") // Knowledge base index ID // === Endpoint Configuration (Optional) === .endpoint("bailian.cn-beijing.aliyuncs.com") // Default value // Other available endpoints: // - bailian.cn-shanghai-finance-1.aliyuncs.com (Finance Cloud) // - bailian-vpc.cn-beijing.aliyuncs.com (VPC) // === Retrieval Configuration (Optional) === .denseSimilarityTopK(100) // Vector retrieval Top K, range 0-100, default 100 .sparseSimilarityTopK(100) // Keyword retrieval Top K, range 0-100, default 100 // Note: denseSimilarityTopK + sparseSimilarityTopK <= 200 // === Reranking Configuration (Optional) === .enableReranking(true) // Enable reranking, default true .rerankConfig(RerankConfig.builder() .modelName("gte-rerank-hybrid") // Rerank model .rerankMinScore(0.3f) // Minimum score threshold .rerankTopN(5) // Number of results to return .build()) // === Query Rewriting Configuration (Optional, for multi-turn conversations) === .enableRewrite(true) // Enable query rewriting, default false .rewriteConfig(RewriteConfig.builder() .modelName("conv-rewrite-qwen-1.8b") // Rewrite model .build()) // === Other Configuration (Optional) === .searchFilters(List.of(Map.of("tag", "value"))) // Search filters .saveRetrieverHistory(false) // Save retrieval history, default false .build(); ``` -------------------------------- ### Run Bailian Memory Example with Maven Source: https://java.agentscope.io/_sources/v1/en/docs/task/memory Navigate to the advanced examples directory and execute the BailianMemoryExample using Maven. Ensure all required environment variables are set prior to execution. ```bash cd agentscope-examples/documentation/advanced mvn exec:java -Dexec.mainClass="io.agentscope.examples.advanced.BailianMemoryExample" ``` -------------------------------- ### Build Project with Maven Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/workflow Builds the AgentScope workflow example project using Maven, skipping tests. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/workflow -am -B package -DskipTests ``` -------------------------------- ### Start Explorer and Trainer Services Source: https://java.agentscope.io/_sources/v1/en/docs/task/online-training Commands to start the Trinity Explorer and Trainer services using their respective configuration files. The Explorer service address will be printed in the logs. ```bash trinity run --config explorer.yaml ``` ```bash trinity run --config trainer.yaml ``` -------------------------------- ### Minimal Sandbox Agent Setup Source: https://java.agentscope.io/_sources/v2/en/docs/harness/sandbox This snippet demonstrates the basic setup of a HarnessAgent using Docker for its filesystem. It specifies the agent's name, model, workspace, and the Docker image to use. Each conversation is isolated by default using a unique sessionId. ```java HarnessAgent agent = HarnessAgent.builder() .name("code-agent") .model(model) .workspace(workspace) .filesystem(new DockerFilesystemSpec() .image("ubuntu:24.04")) .build(); agent.call(msg, RuntimeContext.builder() .sessionId("user-1-conv-1") .build()).block(); ``` -------------------------------- ### RAGFlow Knowledge Quickstart Source: https://java.agentscope.io/_sources/v2/en/integration/rag/ragflow Configure and initialize RAGFlowKnowledge for retrieving documents. Ensure RAGFlow is running and accessible via 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(); ``` -------------------------------- ### RAGFlow Quick Start Configuration and Retrieval Source: https://java.agentscope.io/_sources/v1/en/docs/task/rag Quick start for RAGFlow integration, configuring API key, base URL, and dataset IDs, then performing a retrieval. Use this for basic RAGFlow usage. ```java RAGFlowConfig config = RAGFlowConfig.builder() .apiKey("ragflow-your-api-key") // Required: API Key .baseUrl("http://address") // Required: RAGFlow service address .addDatasetId("dataset-id") // Required: Set at least dataset_ids or document_ids .topK(10).similarityThreshold(0.3) .build(); RAGFlowKnowledge knowledge = RAGFlowKnowledge.builder().config(config).build(); List results = knowledge.retrieve("query", RetrieveConfig.builder().limit(5).build()).block(); ``` -------------------------------- ### Skill Directory Structure Example Source: https://java.agentscope.io/_sources/v2/en/docs/harness/workspace An example structure for a skill directory, including the main description file (SKILL.md), optional references, and optional scripts. ```text skills/code-reviewer/ ├── SKILL.md ← YAML frontmatter (name + description) + instructions ├── references/style-guide.md ← optional, agent reads on demand └── scripts/run-checks.sh ← optional, agent invokes via execute_shell_command ``` -------------------------------- ### Complete RAGFlow Configuration Example Source: https://java.agentscope.io/_sources/v1/en/docs/task/rag A comprehensive example demonstrating all available configuration options for RAGFlowConfig, including connection, dataset, document filtering, retrieval, pagination, advanced features, metadata, and HTTP settings. ```java RAGFlowConfig config = RAGFlowConfig.builder() // === Connection Configuration (Required) === .apiKey("ragflow-your-api-key") // RAGFlow API Key .baseUrl("http://address") // RAGFlow service address (Required) // === Dataset/Document Configuration (At least one required) === .addDatasetId("datasetId1") .addDatasetId("datasetId2") // Supports multiple datasets // Or batch set: .datasetIds(List.of("id1", "id2")) // === Document Filtering (Optional, limits search scope) === .addDocumentId("documentId1") .addDocumentId("documentId2") // Or batch set: .documentIds(List.of("doc1", "doc2")) // Note: If only setting document_ids, ensure all documents use the same embedding model // === Retrieval Configuration (Optional) === .topK(1024) // Number of chunks for vector computation, default 1024 .similarityThreshold(0.2) // Similarity threshold, range 0.0-1.0, default 0.2 .vectorSimilarityWeight(0.3) // Vector similarity weight, range 0.0-1.0, default 0.3 // (1 - weight) is term similarity weight //=== Pagination Parameters === .page(1) // Page number, default 1 .pageSize(30) // Page size, default 30 // === Advanced Retrieval Features (Optional) === .useKg(false) // Knowledge graph multi-hop query, default false .tocEnhance(false) // TOC-enhanced retrieval, default false .rerankId(1) // Rerank model ID .keyword(false) // Keyword matching, default false .highlight(false) // Highlight matched results, default false .addCrossLanguage("en") // Add target language // Or batch set: .crossLanguages(List.of("en", "zh", "ja")) // === Metadata Filtering (Optional) === .metadataCondition(Map.of( "logic", "and", // Logical operator: and or or "conditions", List.of( Map.of( "name", "author", // Metadata field name "comparison_operator", "=", // Comparison operator "value", "Toby" // Filter value ), Map.of( "name", "date", "comparison_operator", ">=", "value", "2024-01-01" ) ) )) // === HTTP Configuration (Optional) === .timeout(Duration.ofSeconds(30)) // HTTP timeout, default 30s .maxRetries(3) // Max retries, default 3 .addCustomHeader("X-Custom-Header", "value") // Custom headers .build(); ``` -------------------------------- ### HarnessAgent Builder Example Source: https://java.agentscope.io/_sources/v2/en/docs/harness/architecture Demonstrates building a HarnessAgent with various capabilities like workspace, session persistence, memory compaction, and tool result eviction. ```java var harness = HarnessAgent.builder() .workspace("/tmp/harness/workspace") .session(new LocalSession("my-session-id")) .compaction(new LocalCompaction("/tmp/harness/compacted")) .toolResultEviction(new LocalToolResultEviction("/tmp/harness/evicted")) .build(); ``` -------------------------------- ### Tools Configuration Example Source: https://java.agentscope.io/_sources/v2/en/docs/harness/workspace Configures the allowed and denied tools, and registers MCP servers. Environment variables can be used for configuration. ```jsonc { // 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"} } } } ``` -------------------------------- ### Quickstart MySQL Session with Pre-Created Schema Source: https://java.agentscope.io/_sources/v2/en/integration/session/mysql Initialize a MysqlSession when the database and table are already created. This form is safer as it will throw an exception if the schema is missing. ```java Session session = new MysqlSession(ds); // throws IllegalStateException if missing Session session = new MysqlSession(ds, false); // explicit ``` -------------------------------- ### Maven Build and Run Commands Source: https://java.agentscope.io/_sources/v1/en/docs/multi-agent/pipeline Provides the command-line instructions for building the pipeline agent example using Maven and running the Spring Boot application. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/pipeline -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/pipeline spring-boot:run ``` -------------------------------- ### Quick Start: Create and Call Remote A2A Agent Source: https://java.agentscope.io/_sources/v1/en/docs/task/a2a Instantiate an A2aAgent to interact with a remote A2A service. This example shows basic setup and making a call to the remote agent. ```java import io.agentscope.core.a2a.agent.A2aAgent; import io.agentscope.core.a2a.agent.card.WellKnownAgentCardResolver; // Create A2A Agent A2aAgent agent = A2aAgent.builder() .name("remote-agent") .agentCardResolver(new WellKnownAgentCardResolver( "http://127.0.0.1:8080", "/.well-known/agent-card.json", Map.of())) .build(); // Call remote Agent Msg response = agent.call(userMsg).block(); ``` -------------------------------- ### Basic MsgHub Setup and Usage Source: https://java.agentscope.io/_sources/v1/en/docs/task/msghub Shows how to create agents, define an announcement message, and use MsgHub with try-with-resources for automatic lifecycle management. Ensure to use DashScopeMultiAgentFormatter for proper message handling. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.formatter.dashscope.DashScopeMultiAgentFormatter; 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.DashScopeChatModel; import io.agentscope.core.pipeline.MsgHub; // Create model with MultiAgentFormatter (important!) DashScopeChatModel model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen3-max") .formatter(new DashScopeMultiAgentFormatter()) .build(); // Create agents ReActAgent alice = ReActAgent.builder() .name("Alice") .sysPrompt("You are Alice, a friendly teacher. Be brief in your responses.") .model(model) .memory(new InMemoryMemory()) .build(); ReActAgent bob = ReActAgent.builder() .name("Bob") .sysPrompt("You are Bob, a curious student. Be brief in your responses.") .model(model) .memory(new InMemoryMemory()) .build(); ReActAgent charlie = ReActAgent.builder() .name("Charlie") .sysPrompt("You are Charlie, a thoughtful observer. Be brief in your responses.") .model(model) .memory(new InMemoryMemory()) .build(); // Create announcement message Msg announcement = Msg.builder() .name("system") .role(MsgRole.SYSTEM) .content(TextBlock.builder() .text("Welcome to the discussion! Please introduce yourself briefly.") .build()) .build(); // Use MsgHub with try-with-resources try (MsgHub hub = MsgHub.builder() .name("Introduction") .participants(alice, bob, charlie) .announcement(announcement) .enableAutoBroadcast(true) // Default is true .build()) { // Enter the hub (broadcasts announcement to all participants) hub.enter().block(); // Each agent introduces themselves // Their responses are automatically broadcast to others Msg aliceReply = alice.call().block(); System.out.println("Alice: " + aliceReply.getTextContent()); Msg bobReply = bob.call().block(); System.out.println("Bob: " + bobReply.getTextContent()); Msg charlieReply = charlie.call().block(); System.out.println("Charlie: " + charlieReply.getTextContent()); } // Hub is automatically closed, subscribers are cleaned up ``` -------------------------------- ### Quick Start: Creating and Using a Session Source: https://java.agentscope.io/_sources/v1/en/docs/task/session Demonstrates the basic workflow of creating components, initializing a session, loading existing state if available, interacting with the agent, and saving the session. ```java import io.agentscope.core.session.JsonSession; import io.agentscope.core.session.Session; import java.nio.file.Path; // 1. Create components InMemoryMemory memory = new InMemoryMemory(); ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .memory(memory) .build(); // 2. Create Session and load existing session Path sessionPath = Path.of(System.getProperty("user.home"), ".agentscope", "sessions"); Session session = new JsonSession(sessionPath); agent.loadIfExists(session, "userId"); // 3. Use Agent Msg response = agent.call(userMsg).block(); // 4. Save session agent.saveTo(session, "userId"); ``` -------------------------------- ### Quickstart: Assemble and Use Simple Knowledge Source: https://java.agentscope.io/_sources/v2/en/integration/rag/simple This Java snippet demonstrates how to set up a RAG pipeline using `SimpleKnowledge`. It includes initializing an embedding model, a vector store, ingesting documents, and performing a retrieval. Ensure your environment variables like `DASHSCOPE_API_KEY` are set. ```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(); ``` -------------------------------- ### Gradle Dependency for AgentScope (All-in-One) Source: https://java.agentscope.io/_sources/v1/en/docs/quickstart/installation Use this Gradle dependency for the all-in-one AgentScope package. This approach is recommended for most users to get started quickly. ```gradle implementation 'io.agentscope:agentscope:1.0.12' ``` -------------------------------- ### Quickstart: Initialize Git Repository Skill Source: https://java.agentscope.io/_sources/v2/en/integration/skill/git-repository Initialize a GitSkillRepository with a public repository URL. All skills from the repository are then registered into a Toolkit. A shutdown hook is added to clean up the temporary local directory upon JVM termination. ```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)); ``` -------------------------------- ### Streaming UI Event Processing Example Source: https://java.agentscope.io/_sources/v2/en/docs/building-blocks/message-and-event This example shows a typical loop for a streaming UI, processing agent events to display output incrementally. It's suitable for real-time user interfaces where content needs to be updated as it's generated. The code logs start, text deltas, tool calls, tool results, and completion events. ```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(); ``` -------------------------------- ### Start Ray Cluster Source: https://java.agentscope.io/_sources/v1/en/docs/task/online-training Command to start the Ray cluster head node. Ensure this is running before starting Explorer and Trainer services. ```bash ray start --head ``` -------------------------------- ### Quick Start: Registering and Using an Agent as a Tool Source: https://java.agentscope.io/_sources/v1/en/docs/task/agent-as-tool Demonstrates how to create a model, register a sub-agent as a tool using a Toolkit, and then use this toolkit with a main agent. The main agent will automatically invoke the expert agent when needed. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.tool.Toolkit; import io.agentscope.core.model.DashScopeChatModel; // Create model DashScopeChatModel model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen-plus") .build(); // Create sub-agent Provider (factory) // Note: Must use lambda to ensure new instance is created for each call Toolkit toolkit = new Toolkit(); toolkit.registration() .subAgent(() -> ReActAgent.builder() .name("Expert") .sysPrompt("You are a domain expert responsible for answering professional questions.") .model(model) .build()) .apply(); // Create main agent with toolkit ReActAgent mainAgent = ReActAgent.builder() .name("Coordinator") .sysPrompt("You are a coordinator. When facing professional questions, call the call_expert tool to consult the expert.") .model(model) .toolkit(toolkit) .build(); // Main agent will automatically call expert agent when needed Msg response = mainAgent.call(userMsg).block(); ``` -------------------------------- ### Mem0 Quickstart with Agentscope Source: https://java.agentscope.io/_sources/v2/en/integration/memory/mem0 Build a Mem0 memory instance and wire it into an Agent for automatic memory recording and retrieval. Supports local, self-hosted, and SaaS deployments. ```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(); ``` -------------------------------- ### Local Knowledge Base Quick Start Source: https://java.agentscope.io/_sources/v1/en/docs/task/rag Set up a local knowledge base using SimpleKnowledge, configure an embedding model, add documents using a TextReader, and perform retrieval. ```java // 1. Create knowledge base EmbeddingModel embeddingModel = DashScopeTextEmbedding.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("text-embedding-v3") .dimensions(1024) .build(); Knowledge knowledge = SimpleKnowledge.builder() .embeddingModel(embeddingModel) .embeddingStore(InMemoryStore.builder().dimensions(1024).build()) .build(); // 2. Add documents TextReader reader = new TextReader(512, SplitStrategy.PARAGRAPH, 50); List docs = reader.read(ReaderInput.fromString("Text content...")).block(); knowledge.addDocuments(docs).block(); // 3. Retrieve List results = knowledge.retrieve("query", RetrieveConfig.builder().limit(3).scoreThreshold(0.5).build()).block(); ``` -------------------------------- ### Quickstart AG-UI Agent Adapter Source: https://java.agentscope.io/_sources/v2/en/integration/protocol/agui Initialize and use 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); ``` -------------------------------- ### Quickstart MySQL Session with Auto-Creation Source: https://java.agentscope.io/_sources/v2/en/integration/session/mysql Initialize a HikariDataSource with your MySQL connection details and create a MysqlSession instance. Setting createIfNotExist to true will automatically create the database and table if they do not exist. ```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(); ``` -------------------------------- ### Sandbox Recovery Branches Source: https://java.agentscope.io/_sources/v1/en/docs/harness/sandbox/index Illustrates the four recovery branches based on container availability and snapshot presence. Branch A is the fastest warm start, while Branch D is a full cold start. ```text Branch A: workspaceRootReady=true & directory still exists in container → only re-apply ephemeral entries (fastest, warm start) Branch B: workspaceRootReady=true & directory lost in container → restore from snapshot + re-apply ephemeral entries Branch C: workspaceRootReady=false & snapshot available → restore from snapshot + re-apply all entries Branch D: workspaceRootReady=false & no snapshot available → full initialization from WorkspaceSpec (cold start) ```