### Quick Start: Agent Initialization and Session Handling Source: https://java.agentscope.io/llms-full.txt This example demonstrates the typical workflow of initializing an Agent, creating a Session, loading an existing session if it exists, interacting with the Agent, and finally saving the session. It covers component creation, session path setup, and agent interaction. ```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"); ``` -------------------------------- ### Run Higress Quickstart Example Source: https://java.agentscope.io/llms-full.txt Navigate to the agentscope-examples/quickstart directory and execute the McpToolExample using Maven to run the Higress quickstart example. ```bash cd agentscope-examples/quickstart mvn exec:java -Dexec.mainClass="io.agentscope.examples.quickstart.McpToolExample" ``` -------------------------------- ### Build and Run Supervisor Example Project Source: https://java.agentscope.io/llms-full.txt Commands to build and run the supervisor example project from the AgentScope repository. Ensure you have Maven installed. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/supervisor -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/supervisor spring-boot:run ``` -------------------------------- ### Start AgentScope Studio Server Source: https://java.agentscope.io/llms-full.txt Instructions for starting the AgentScope Studio server locally, either from source code or via npm installation. ```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 ``` -------------------------------- ### Complete Agent Session Example Source: https://java.agentscope.io/llms-full.txt A full example demonstrating the setup and usage of a ReActAgent with JsonSession, including loading an existing session, interacting with the agent, and saving the session state. ```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 SQL Assistant Example Source: https://java.agentscope.io/llms-full.txt Commands to build and run the SQL assistant example project using Maven. Ensure you are in the repository root. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/skills -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/skills spring-boot:run ``` -------------------------------- ### Initialize and Run Studio Example Source: https://java.agentscope.io/llms-full.txt This example demonstrates how to initialize Studio, create a ReActAgent with a StudioMessageHook, and a StudioUserAgent for interactive conversation. It requires the DASHSCOPE_API_KEY environment variable to be set. ```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"); } } } ``` -------------------------------- ### Run Example Project with Maven Source: https://java.agentscope.io/llms-full.txt Instructions to set up and run the example AgentScope project using Maven. Ensure your DASHSCOPE_API_KEY is exported and navigate to the project directory before running the command. ```bash export DASHSCOPE_API_KEY=your-key cd agentscope-examples/agui mvn spring-boot:run ``` -------------------------------- ### A2aAgent Client - Quick Start Source: https://java.agentscope.io/llms-full.txt Demonstrates the basic setup and usage of the A2aAgent client to interact with remote agents. ```APIDOC ## A2aAgent Client - Quick Start ### Description Use remote A2A services as local Agents. ### Method N/A (Client-side library usage) ### Endpoint N/A (Client-side library usage) ### Parameters N/A for this quick start example. ### Request Example ```java import io.agentscope.core.a2a.agent.A2aAgent; import io.agentscope.core.a2a.agent.card.WellKnownAgentCardResolver; import java.util.Map; // 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(); // Assuming userMsg is defined ``` ### Response N/A for this quick start example. ``` -------------------------------- ### Build and Run AgentScope Handoffs Example Source: https://java.agentscope.io/llms-full.txt Commands to build and run the AgentScope handoffs example project using Maven. This includes packaging the application 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 ``` -------------------------------- ### Build and Run AgentScope Routing Example Source: https://java.agentscope.io/llms-full.txt Builds the AgentScope routing example project and runs the Spring Boot application from the repository root. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/routing -am -B package -DskipTests ./mvnw -pl agentscope-examples/multiagent-patterns/routing spring-boot:run ``` -------------------------------- ### Build Example Project Source: https://java.agentscope.io/llms-full.txt Builds the multiagent-patterns workflow module of the agentscope-examples project. Skips tests during the build process. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/workflow -am -B package -DskipTests ``` -------------------------------- ### Quick Start: Agent as Tool Registration Source: https://java.agentscope.io/llms-full.txt This example demonstrates how to register a sub-agent as a tool using a `Toolkit`. It requires creating a `DashScopeChatModel`, defining the sub-agent's behavior with `ReActAgent.builder()`, and then applying the toolkit to the main agent. Ensure the `DASHSCOPE_API_KEY` environment variable is set. ```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(); ``` -------------------------------- ### Start Ray Cluster Source: https://java.agentscope.io/llms-full.txt Initiate the Ray cluster using the 'ray start --head' command. This is a prerequisite for launching the Explorer and Trainer services. ```bash ray start --head ``` -------------------------------- ### Install Trinity-RFT Framework Source: https://java.agentscope.io/llms-full.txt Clone the Trinity-RFT repository and install the necessary dependencies, including flash-attn, to set up the training backend. Ensure Python and CUDA versions meet the requirements. ```bash git clone https://github.com/agentscope-ai/Trinity-RFT cd Trinity-RFT pip install -e ".[dev]" pip install flash-attn==2.8.1 ``` -------------------------------- ### Run AgentScope Subagent Example Interactively Source: https://java.agentscope.io/llms-full.txt Execute the multi-agent subagent example in an interactive mode using Maven wrapper. This command enables a chat runner on startup. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/subagent spring-boot:run \ -Dspring-boot.run.arguments="--subagent.run-interactive=true" ``` -------------------------------- ### Configure and Start Training Runner Source: https://java.agentscope.io/llms-full.txt Initialize and start the TrainingRunner in Java. Provide the Trinity endpoint, model name, and custom strategies for selection and reward calculation. The commit interval and repeat time can also be configured. ```java TrainingRunner trainingRunner = TrainingRunner.builder() .trinityEndpoint(TRINITY_ENDPOINT) // Trinity Explorer service address .modelName(TRAINING_MODEL_NAME) // Corresponds to model_path in Trinity configuration .selectionStrategy(new CustomStrategy()) .rewardCalculator(new CustomReward()) .commitIntervalSeconds(60*5) .repeatTime(1) .build(); trainingRunner.start(); ``` -------------------------------- ### Quick Start with A2aAgent Client Source: https://java.agentscope.io/llms-full.txt Initializes an A2aAgent to interact with remote A2A services. This example shows how to build the agent with a name and an AgentCardResolver, and then call a 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(); ``` -------------------------------- ### Start Explorer and Trainer Services Source: https://java.agentscope.io/llms-full.txt Launch the Explorer and Trainer services by running 'trinity run --config .yaml'. Ensure the correct configuration files are specified. ```bash trinity run --config explorer.yaml ``` ```bash trinity run --config trainer.yaml ``` -------------------------------- ### Complete Multi-Agent Debate Example in Java Source: https://java.agentscope.io/llms-full.txt This example sets up a debate between two agents (Alice and Bob) moderated by a third agent. It demonstrates agent creation, model configuration, message handling, and a debate loop with a judge. Ensure the DASHSCOPE_API_KEY environment variable is set. ```java package io.agentscope.examples; 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; public class MultiAgentDebateExample { public static class JudgeResult { public boolean finished; public String correctAnswer; } public static void main(String[] args) { // Topic String topic = """ The two circles are externally tangent and there is no relative sliding. The radius of circle A is 1/3 the radius of circle B. Circle A rolls around circle B one trip back to its starting point. How many times will circle A revolve in total? """; // Create model DashScopeChatModel model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen3-max") .formatter(new DashScopeMultiAgentFormatter()) .build(); // Create debaters ReActAgent alice = ReActAgent.builder() .name("Alice") .sysPrompt("You're a debater named Alice. Topic: " + topic) .model(model) .memory(new InMemoryMemory()) .build(); ReActAgent bob = ReActAgent.builder() .name("Bob") .sysPrompt("You're a debater named Bob. Topic: " + topic) .model(model) .memory(new InMemoryMemory()) .build(); // Create moderator ReActAgent moderator = ReActAgent.builder() .name("Moderator") .sysPrompt("You're a moderator evaluating a debate on: " + topic) .model(model) .memory(new InMemoryMemory()) .build(); // Run debate for (int round = 1; round <= 5; round++) { System.out.println("\n=== Round " + round + " ===\n"); try (MsgHub hub = MsgHub.builder() .participants(alice, bob, moderator) .build()) { hub.enter().block(); Msg aliceMsg = alice.call(Msg.builder() .name("user") .role(MsgRole.USER) .content(TextBlock.builder() .text("Present your argument.") .build()) .build()).block(); System.out.println("Alice: " + aliceMsg.getTextContent()); Msg bobMsg = bob.call(Msg.builder() .name("user") .role(MsgRole.USER) .content(TextBlock.builder() .text("Respond to Alice and present your argument.") .build()) .build()).block(); System.out.println("Bob: " + bobMsg.getTextContent()); } // Moderator judgment Msg judgeMsg = moderator.call( Msg.builder() .name("user") .role(MsgRole.USER) .content(TextBlock.builder() .text("Evaluate the debate. Is there a correct answer?") .build()) .build(), JudgeResult.class ).block(); JudgeResult result = judgeMsg.getStructuredData(JudgeResult.class); if (result.finished) { System.out.println("\n=== Debate Concluded ==="); System.out.println("Answer: " + result.correctAnswer); break; } } } } ``` -------------------------------- ### Define StateGraph for Routing Source: https://java.agentscope.io/llms-full.txt Illustrates the setup of a StateGraph for routing, including the sequence of nodes: START, preprocess, routing, postprocess, and END. It also shows the configuration of a key factory for managing state keys. ```java new StateGraph("routing_graph", keyFactory) ``` -------------------------------- ### Implement Custom Session Storage with DatabaseSession Source: https://java.agentscope.io/llms-full.txt Implement the `Session` interface to create custom storage backends. This example shows a `DatabaseSession` class with methods for saving, getting, and deleting session data. ```java import io.agentscope.core.session.Session; import io.agentscope.core.state.SessionKey; import io.agentscope.core.state.State; import java.util.List; import java.util.Optional; import java.util.Set; public class DatabaseSession implements Session { @Override public void save(SessionKey sessionKey, String key, State value) { // Save single state to database } @Override public void save(SessionKey sessionKey, String key, List values) { // Save state list to database } @Override public Optional get(SessionKey sessionKey, String key, Class type) { // Get single state from database return Optional.empty(); } @Override public List getList(SessionKey sessionKey, String key, Class itemType) { // Get state list from database return List.of(); } @Override public boolean exists(SessionKey sessionKey) { // Check if session exists return false; } @Override public void delete(SessionKey sessionKey) { // Delete session } @Override public Set listSessionKeys() { // List all sessions return Set.of(); } @Override public void close() { // Close connection } } ``` ```java // Usage Session session = new DatabaseSession(dbConnection); agent.saveTo(session, "user123"); ``` -------------------------------- ### Complete Training Runner Example in Java Source: https://java.agentscope.io/llms-full.txt This snippet shows how to initialize and run a TrainingRunner with custom configurations like endpoint, model path, sampling rate, reward calculator, and commit interval. It then demonstrates normal agent usage and finally stops the runner. ```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(); ``` -------------------------------- ### Vision Agent Example in Java Source: https://java.agentscope.io/llms-full.txt Demonstrates how to create a ReActAgent with vision capabilities using DashScope's qwen-vl-max model. It shows how to construct a multimodal message with text and an image, and then send it to the agent for processing. ```java package io.agentscope.examples; import io.agentscope.core.ReActAgent; import io.agentscope.core.formatter.dashscope.DashScopeChatFormatter; import io.agentscope.core.memory.InMemoryMemory; import io.agentscope.core.message.*; import io.agentscope.core.model.DashScopeChatModel; import io.agentscope.core.tool.Toolkit; import java.util.List; public class VisionExample { public static void main(String[] args) throws Exception { String apiKey = System.getenv("DASHSCOPE_API_KEY"); // 1. Create Vision Agent ReActAgent agent = ReActAgent.builder() .name("VisionAssistant") .sysPrompt("You are an AI assistant with vision capabilities.") .model(DashScopeChatModel.builder() .apiKey(apiKey) .modelName("qwen-vl-max") .stream(true) .formatter(new DashScopeChatFormatter()) .build()) .memory(new InMemoryMemory()) .toolkit(new Toolkit()) .build(); // 2. Create multimodal message String base64Image = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64pa..."; Msg userMsg = Msg.builder() .role(MsgRole.USER) .content(List.of( TextBlock.builder() .text("What color is this image?") .build(), ImageBlock.builder() .source(Base64Source.builder() .data(base64Image) .mediaType("image/png") .build()) .build() )) .build(); // 3. Send request and get response Msg response = agent.call(userMsg).block(); System.out.println(response.getTextContent()); } } ``` -------------------------------- ### Build StateGraph with Key Strategies Source: https://java.agentscope.io/llms-full.txt Configure a StateGraph with specific key strategies for state variables. This example sets up 'messages' to use AppendStrategy and 'active_agent' to use ReplaceStrategy, allowing handoff tools to update routing state. ```java // In your config: build the graph with key strategies StateGraph graph = new StateGraph("agent_scope_handoffs", () -> { Map strategies = new HashMap<>(); strategies.put("messages", new AppendStrategy(false)); strategies.put(AgentScopeStateConstants.ACTIVE_AGENT, new ReplaceStrategy()); return strategies; }); ``` -------------------------------- ### Connect to MCP Server (StdIO) Source: https://java.agentscope.io/llms-full.txt Connect to a local MCP server using the StdIO transport. This example connects to a filesystem MCP server. ```java import io.agentscope.core.tool.mcp.McpClientBuilder; import io.agentscope.core.tool.mcp.McpClientWrapper; // StdIO transport - connect to local MCP server McpClientWrapper mcpClient = McpClientBuilder.create("filesystem-mcp") .stdioTransport("npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp") .buildAsync() .block(); ``` -------------------------------- ### Quick Start: Bailian Knowledge Base Source: https://java.agentscope.io/llms-full.txt Initialize a Bailian knowledge base using Alibaba Cloud credentials and workspace/index IDs. Configure retrieval limits and score thresholds. ```java // Create knowledge base BailianConfig config = BailianConfig.builder() .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) .workspaceId("llm-xxx") .indexId("mymxbdxxxx") .build(); BailianKnowledge knowledge = BailianKnowledge.builder().config(config).build(); // Retrieve List results = knowledge.retrieve("query", RetrieveConfig.builder().limit(5).scoreThreshold(0.3).build()).block(); ``` -------------------------------- ### Deploy RAGFlow Source: https://java.agentscope.io/llms-full.txt Clone the RAGFlow repository and start the Docker containers to deploy the RAG engine. ```bash git clone https://github.com/infiniflow/ragflow.git && cd ragflow docker compose up -d ``` -------------------------------- ### Configure Multi-Agent Visualization in Studio Source: https://java.agentscope.io/llms-full.txt This example illustrates how to add a StudioMessageHook to multiple agents. Studio will then display messages from each agent separately, enabling multi-agent visualization. ```java // Add Hook to each Agent ReActAgent agent1 = ReActAgent.builder() .name("Agent1") .hook(new StudioMessageHook(client)) .build(); ReActAgent agent2 = ReActAgent.builder() .name("Agent2") .hook(new StudioMessageHook(client)) .build(); // Studio will display messages from both Agents separately ``` -------------------------------- ### Quick Start RAGFlow Knowledge Integration Source: https://java.agentscope.io/llms-full.txt Initialize RAGFlowConfig with API key, base URL, and dataset ID. Then, build a RAGFlowKnowledge instance to perform retrievals. ```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(); ``` -------------------------------- ### Reactive Programming with AgentScope and Project Reactor Source: https://java.agentscope.io/llms-full.txt Illustrates a fully reactive programming style using AgentScope's MsgHub with Project Reactor. This example chains agent calls and processes their responses reactively, blocking only at the end. ```java MsgHub hub = MsgHub.builder() .participants(alice, bob, charlie) .announcement(announcement) .build(); // Fully reactive chain hub.enter() .then(alice.call()) .doOnSuccess(msg -> System.out.println("Alice: " + msg.getTextContent())) .then(bob.call()) .doOnSuccess(msg -> System.out.println("Bob: " + msg.getTextContent())) .then(charlie.call()) .doOnSuccess(msg -> System.out.println("Charlie: " + msg.getTextContent())) .then(hub.exit()) .block(); // Only block once at the end ``` -------------------------------- ### Configure StdIO Transport for Filesystem MCP Server Source: https://java.agentscope.io/llms-full.txt Configure the StdIO transport for a local filesystem MCP server. This example uses 'npx' to run the server and specifies a directory. ```java // Filesystem server McpClientWrapper fsClient = McpClientBuilder.create("fs-mcp") .stdioTransport("npx", "-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir") .buildAsync() .block(); ``` -------------------------------- ### Configure Generation Options for DashScope and Ollama Source: https://java.agentscope.io/llms-full.txt Set generation parameters like temperature, topP, topK, maxTokens, and seed. This example shows how to build GenerateOptions and then use them to configure both DashScopeChatModel and OllamaChatModel. ```java GenerateOptions options = GenerateOptions.builder() .temperature(0.7) // Randomness (0.0-2.0) .topP(0.9) // Nucleus sampling .topK(40) // Top-K sampling .maxTokens(2000) // Maximum output tokens .seed(42L) // Random seed .toolChoice(new ToolChoice.Auto()) // Tool choice strategy .build(); DashScopeChatModel model = DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen3-max") .defaultOptions(options) .build(); OllamaChatModel model = OllamaChatModel.builder() .modelName("qwen3-max") .baseUrl("http://localhost:11434") .defaultOptions(OllamaOptions.fromGenerateOptions(options)) .build(); ``` -------------------------------- ### Complete RAGFlow Configuration Example in Java Source: https://java.agentscope.io/llms-full.txt This snippet shows a comprehensive configuration for RAGFlow, including connection details, dataset and document selection, retrieval parameters, advanced features, metadata filtering, and HTTP settings. Ensure all required fields like API key and base URL are provided. ```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(); ``` -------------------------------- ### Quick Start Dify Knowledge Base Integration Source: https://java.agentscope.io/llms-full.txt Initialize Dify knowledge base integration with API key, dataset ID, and retrieval mode. Retrieve documents using a query and specify the number of results. ```java DifyRAGConfig config = DifyRAGConfig.builder() .apiKey(System.getenv("DIFY_RAG_API_KEY")) .datasetId("your-dataset-id") .retrievalMode(RetrievalMode.HYBRID_SEARCH) .topK(10).scoreThreshold(0.5) .build(); DifyKnowledge knowledge = DifyKnowledge.builder().config(config).build(); List results = knowledge.retrieve("query", RetrieveConfig.builder().limit(5).build()).block(); ``` -------------------------------- ### New Session Data Format Example Source: https://java.agentscope.io/llms-full.txt Demonstrates the new data format used by `saveTo`/`loadFrom`, which organizes session data into a directory per session with independent files for different state types, using JSONL for lists. ```json {"role":"USER","name":"user","content":[{"type":"text","text":"Hello"}]} {"role":"ASSISTANT","name":"Assistant","content":[{"type":"text","text":"Hi!"}]} ``` -------------------------------- ### Create and Use a ReActAgent with Planning Enabled Source: https://java.agentscope.io/llms-full.txt Demonstrates how to build a ReActAgent with planning support, assign a complex task, and execute it. Ensure the 'model' and 'toolkit' are properly initialized before use. ```java ReActAgent agent = ReActAgent.builder() .name("PlanAgent") .sysPrompt("You are a systematic assistant that breaks down complex tasks into plans.") .model(model) .toolkit(toolkit) .enablePlan() .build(); Msg task = Msg.builder() .role(MsgRole.USER) .content(List.of(TextBlock.builder() .text("Build a simple calculator web app with HTML, CSS and JavaScript.") .build())) .build(); Msg response = agent.call(task).block(); ``` -------------------------------- ### Run SQL Workflow Demo Source: https://java.agentscope.io/llms-full.txt Runs the SQL workflow demo on startup. Requires DashScope API key. Enables SQL and runner beans. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/workflow spring-boot:run \n -Dspring-boot.run.arguments="--workflow.sql.enabled=true --workflow.runner.enabled=true" ``` -------------------------------- ### Create and Use MsgHub with Multiple Agents Source: https://java.agentscope.io/llms-full.txt Initialize MsgHub with multiple agents and a system announcement. Use try-with-resources for automatic cleanup. Ensure DashScopeMultiAgentFormatter is used for proper message handling across agents. ```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 ``` -------------------------------- ### Start and Continue Multi-turn Conversation Source: https://java.agentscope.io/llms-full.txt Omit `session_id` to start a new conversation. Provide an existing `session_id` to continue a previous one. The parent agent automatically manages `session_id` extraction from responses. ```java // First call: omit session_id to start a new session // Tool returns: // session_id: abc-123-def // // Expert response content... // Subsequent calls: provide session_id to continue the conversation // Parent agent automatically extracts session_id from previous response ``` -------------------------------- ### Enable Planning with Default Configuration Source: https://java.agentscope.io/llms-full.txt Enable the planning feature for an agent using the default `PlanNotebook` configuration. This is the recommended approach for most use cases. ```java ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .toolkit(toolkit) .enablePlan() // Enable planning .build(); ``` -------------------------------- ### Run RAG Workflow Demo Source: https://java.agentscope.io/llms-full.txt Runs the RAG workflow demo on startup. Requires DashScope API key and an embedding model. Enables RAG and runner beans. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/workflow spring-boot:run \n -Dspring-boot.run.arguments="--workflow.rag.enabled=true --workflow.runner.enabled=true" ``` -------------------------------- ### Create ReActAgent with DashScope API Source: https://java.agentscope.io/llms-full.txt Example of creating a ReActAgent using the DashScope API, including tool registration and message sending. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.message.Msg; import io.agentscope.core.model.DashScopeChatModel; import io.agentscope.core.tool.Toolkit; import io.agentscope.core.tool.Tool; import io.agentscope.core.tool.ToolParam; public class QuickStart { public static void main(String[] args) { // Prepare tools Toolkit toolkit = new Toolkit(); toolkit.registerTool(new SimpleTools()); // Create agent ReActAgent jarvis = ReActAgent.builder() .name("Jarvis") .sysPrompt("You are an assistant named Jarvis.") .model(DashScopeChatModel.builder() .apiKey(System.getenv("DASHSCOPE_API_KEY")) .modelName("qwen3-max") .build()) .toolkit(toolkit) .build(); // Send message Msg msg = Msg.builder() .textContent("Hello Jarvis, what time is it now?") .build(); Msg response = jarvis.call(msg).block(); System.out.println(response.getTextContent()); } } // Tool class class SimpleTools { @Tool(name = "get_time", description = "Get current time") public String getTime( @ToolParam(name = "zone", description = "Timezone, e.g., Beijing") String zone) { return java.time.LocalDateTime.now() .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } } ``` -------------------------------- ### InMemoryMemory Usage Example in Java Source: https://java.agentscope.io/llms-full.txt Demonstrates how to use `InMemoryMemory` as the default short-term memory for a `ReActAgent`, showing message storage and history access. ```java import io.agentscope.core.ReActAgent; import io.agentscope.core.memory.InMemoryMemory; ReActAgent agent = ReActAgent.builder() .name("Assistant") .model(model) .memory(new InMemoryMemory()) .build(); // Messages are automatically stored agent.call(msg1).block(); agent.call(msg2).block(); // Access history List history = agent.getMemory().getMessages(); System.out.println("Total messages: " + history.size()); ``` -------------------------------- ### Quick Start: SimpleKnowledge Base Source: https://java.agentscope.io/llms-full.txt Initialize a SimpleKnowledge base with an embedding model and an embedding store. Add documents using a TextReader and retrieve them. ```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(); ``` -------------------------------- ### Run AgentScope Simple Routing Demo Only Source: https://java.agentscope.io/llms-full.txt Builds and runs only the Simple routing demo of the AgentScope project, enabling it via a Spring Boot argument. ```bash ./mvnw -pl agentscope-examples/multiagent-patterns/routing spring-boot:run \ -Dspring-boot.run.arguments="--routing.runner.enabled=true" ``` -------------------------------- ### DashScope Model Configuration in Java Source: https://java.agentscope.io/llms-full.txt Shows how to configure DashScope chat models, including specifying model names like 'qwen-vl-max', 'qwen-vl-plus', or 'qwen-audio-turbo', and setting up a chat formatter. ```java DashScopeChatModel.builder() .modelName("qwen-vl-max") .modelName("qwen-vl-plus") .modelName("qwen-audio-turbo") .formatter(new DashScopeChatFormatter()) .build(); ``` -------------------------------- ### Create Asynchronous and Synchronous MCP Clients Source: https://java.agentscope.io/llms-full.txt Instantiate MCP clients for asynchronous (recommended) or synchronous operations using the McpClientBuilder. Both examples use the stdioTransport. ```java // Asynchronous client (recommended) McpClientWrapper asyncClient = McpClientBuilder.create("async-mcp") .stdioTransport("npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp") .buildAsync() .block(); ``` ```java // Synchronous client (for blocking operations) McpClientWrapper syncClient = McpClientBuilder.create("sync-mcp") .stdioTransport("npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp") .buildSync(); ``` -------------------------------- ### Supervisor Agent Invocation in Code Source: https://java.agentscope.io/llms-full.txt Example of how to inject and invoke the supervisor agent in your Java code using AgentScope. The response text can be retrieved using getTextContent(). ```java // Inject the supervisor ReActAgent (e.g. @Qualifier("supervisorAgent")) // and call it with a user Msg; // get text from the response with response.getTextContent() ``` -------------------------------- ### Create Image, Audio, and Video Content Blocks in Java Source: https://java.agentscope.io/llms-full.txt Demonstrates creating ImageBlock, AudioBlock, and VideoBlock using both Base64 encoding and URL sources. Base64 encoding is recommended for better compatibility. Ensure correct MIME types are specified. ```java import io.agentscope.core.message.*; import java.util.Base64; import java.nio.file.Files; import java.nio.file.Paths; // Image: Base64 method (recommended) String base64Image = Base64.getEncoder().encodeToString( Files.readAllBytes(Paths.get("image.png")) ); ImageBlock imageBlock = ImageBlock.builder() .source(Base64Source.builder() .data(base64Image) .mediaType("image/png") .build()) .build(); // Image: URL method ImageBlock urlImage = ImageBlock.builder() .source(URLSource.builder() .url("https://example.com/image.jpg") .build()) .build(); // Audio AudioBlock audioBlock = AudioBlock.builder() .source(Base64Source.builder() .data(base64AudioData) .mediaType("audio/mp3") .build()) .build(); // Video VideoBlock videoBlock = VideoBlock.builder() .source(URLSource.builder() .url("https://example.com/video.mp4") .build()) .build(); ``` ```java import io.agentscope.core.message.Msg; import io.agentscope.core.message.TextBlock; import io.agentscope.core.message.ImageBlock; import java.util.List; // Single image message Msg singleImageMsg = Msg.builder() .role(MsgRole.USER) .content(List.of( TextBlock.builder().text("What color is this image?").build(), imageBlock )) .build(); // Multiple images message Msg multiImageMsg = Msg.builder() .role(MsgRole.USER) .content(List.of( TextBlock.builder().text("Compare these two images").build(), ImageBlock.builder().source(base64Source1).build(), ImageBlock.builder().source(base64Source2).build() )) .build(); ``` -------------------------------- ### Old Session Data Format Example Source: https://java.agentscope.io/llms-full.txt Illustrates the old data format used by `SessionManager`, which stores all session state in a single JSON file per session. ```json { "agent": { "name": "Assistant", "iteration": 5 }, "memory": { "messages": [ {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi!"} ] } } ``` -------------------------------- ### Install AgentScope Documentation MCP Server Source: https://java.agentscope.io/llms-full.txt Command to add the AgentScope documentation MCP server for Claude Code. This allows querying documentation directly within the IDE. ```bash claude mcp add agentscope-docs -- uvx --from mcpdoc mcpdoc --urls AgentScopeJava:https://java.agentscope.io/llms.txt ```