### Install and Run Frontend Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/browser_use_fullstack_runtime/README.md Navigate to the frontend directory, install dependencies, and start the React development server. The application will typically open in your browser automatically. ```bash cd frontend npm install npm run start # The browser will open automatically, or visit http://localhost:3000 ``` -------------------------------- ### Run AgentScope Example with Spring Boot Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/simple_agent_use_examples/agentscope_use_example/README.md Alternatively, run the example using the Spring Boot Maven plugin. This is another way to start the AgentScope application. ```bash mvn spring-boot:run ``` -------------------------------- ### Test the Plugin in Example Project Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/maven_plugin/README.md Build and test the plugin within a sample project. ```bash cd examples/simple_agent_use_examples/agentscope_use_example mvn clean package deployer:build ``` -------------------------------- ### Initialize Sandbox Service and Tools Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/service.md Shows how to create and start a SandboxService using Docker, and then initialize a BrowserSandbox with related tools. ```java import io.agentscope.core.tool.Toolkit; import io.agentscope.runtime.engine.agents.agentscope.tools.ToolkitInit; import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service using Docker as the backend BaseClientStarter clientStarter = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientStarter) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to (or create) a browser-type sandbox with specified user and session IDs Sandbox sandbox = new BrowserSandbox(sandboxService, "user_1", "session_1"); // Initialize a toolkit and register browser-related tools bound to this sandbox Toolkit toolkit = new Toolkit(); toolkit.registerTool(ToolkitInit.BrowserNavigateTool(sandbox)); toolkit.registerTool(ToolkitInit.BrowserTakeScreenshotTool(sandbox)); // The Agent can now use these tools to perform safe, isolated browser operations } } ``` -------------------------------- ### Initialize and Use Mobile Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Demonstrates initializing a MobileSandbox with a Docker client and performing common mobile operations like listing tools, getting screen resolution, tapping, inputting text, sending key events, and taking screenshots. Ensure the sandbox service is started before creating the MobileSandbox instance. ```java import io.agentscope.runtime.sandbox.box.MobileSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); try (MobileSandbox mobileSandbox = new MobileSandbox(sandboxService, "userId", "sessionId")) { System.out.println("Listing all available tools:"); System.out.println(mobileSandbox.listTools("")); System.out.println("Getting screen resolution:"); System.out.println(mobileSandbox.mobileGetScreenResolution()); System.out.println("Tapping at coordinates (500, 1000):"); System.out.println(mobileSandbox.mobileTap(500, 1000)); System.out.println("Inputting text:"); System.out.println(mobileSandbox.mobileInputText("Greetings from AgentScope!")); System.out.println("Sending HOME key event (key code 3):"); System.out.println(mobileSandbox.mobileKeyEvent(3)); System.out.println("Taking a screenshot:"); String screenshotResult = mobileSandbox.mobileGetScreenshot(); System.out.println(screenshotResult); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Run AgentScope Example with Maven Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/simple_agent_use_examples/agentscope_use_example/README.md Execute the AgentScope example using Maven. This command specifies the main class to run for the deployment. ```bash mvn exec:java -Dexec.mainClass="io.agentscope.AgentScopeDeployExample" ``` -------------------------------- ### Install AgentScope Runtime Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Install the AgentScope Runtime library using pip. This is a prerequisite for using the sandbox environment. ```bash pip install agentscope-runtime ``` -------------------------------- ### Install AgentScope Runtime Java from Source Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/install.md Clone the repository and build from source using Maven. This is suitable for development and testing with SNAPSHOT versions. ```bash git clone https://github.com/agentscope-ai/agentscope-runtime-java.git cd agentscope-runtime-java mvn clean install -Dskiptests ``` -------------------------------- ### Initialize and Use Base Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Demonstrates how to initialize the SandboxService with a Docker client, start the service, and then connect to a Base Sandbox to list available tools. The sandbox is automatically deleted after use. ```java import com.google.gson.Gson; import io.agentscope.runtime.sandbox.box.BaseSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (Sandbox sandbox = new BaseSandbox(sandboxService, "userId", "sessionId")) { Gson gson = new Gson(); String tools = gson.toJson(sandbox.listTools("")); System.out.println("Available tools: "); System.out.println(tools); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Deploy AgentApp from Configuration File Source: https://context7.com/agentscope-ai/agentscope-runtime-java/llms.txt Illustrates starting an AgentApp using external configuration from a .env or properties file. This approach allows for fully externalized configuration of application settings. ```properties agent.app.port=10001 agent.app.handler.provider.class=com.example.MyHandlerProvider agent.app.state.service.provider.class=com.example.MyStateServiceProvider ``` ```java AgentApp appFromFile = new AgentApp(new String[]{"--file", ".env"}); appFromFile.run(); ``` -------------------------------- ### Run AgentScope Example with RocketMQ Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/simple_agent_use_rocketmq_example/agentscope_use_rocketmq_server_example/README.md Execute the AgentScope Java example using Maven, providing necessary parameters for RocketMQ and API keys. The main class `io.agentscope.AgentScopeDeployRocketMQExample` is used. ```bash mvn exec:java -Dexec.mainClass=io.agentscope.AgentScopeDeployRocketMQExample -DrocketMQEndpoint= -DrocketMQNamespace= -DbizTopic=AgentTask -DbizConsumerGroup=AgentTaskConsumerGroup -DrocketMQAK= -DrocketMQSK= -DapiKey= ``` -------------------------------- ### Build and Run AgentApp Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/quickstart.md Initializes the AgentApp with the configured AgentScopeAgentHandler and starts the application, listening on the specified port. ```java AgentApp agentApp = new AgentApp(agentHandler); agentApp.run(10001); ``` -------------------------------- ### Example Dockerfile for a Custom Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/advanced.md This Dockerfile sets up a custom sandbox environment including Node.js, Python, development tools, supervisor, nginx, and Google Chrome. It also installs specific Node.js packages for steel-browser and artifacts backend. ```dockerfile FROM node:22-slim # Set ENV variables ENV NODE_ENV=production ENV WORKSPACE_DIR=/workspace ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --fix-missing \ curl \ python3 \ python3-pip \ python3-venv \ build-essential \ libssl-dev \ git \ supervisor \ vim \ nginx \ gettext-base WORKDIR /agentscope_runtime RUN python3 -m venv venv ENV PATH="/agentscope_runtime/venv/bin:$PATH" # Copy application files COPY src/agentscope_runtime/sandbox/box/shared/app.py ./ COPY src/agentscope_runtime/sandbox/box/shared/routers/ ./routers/ COPY src/agentscope_runtime/sandbox/box/shared/dependencies/ ./dependencies/ COPY src/agentscope_runtime/sandbox/box/shared/artifacts/ ./ext_services/artifacts/ COPY examples/custom_sandbox/box/third_party/markdownify-mcp/ ./mcp_project/markdownify-mcp/ COPY examples/custom_sandbox/box/third_party/steel-browser/ ./ext_services/steel-browser/ COPY examples/custom_sandbox/box/ ./ RUN pip install -r requirements.txt # Install Google Chrome & fonts RUN curl -fsSL https://dl.google.com/linux/linux_signing_key.pub | apt-key add - && \ echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list && \ apt-get update && apt-get install -y --fix-missing google-chrome-stable \ google-chrome-stable \ fonts-wqy-zenhei \ fonts-wqy-microhei # Install steel browser WORKDIR /agentscope_runtime/ext_services/steel-browser RUN npm ci --omit=dev \ && npm install -g webpack webpack-cli \ && npm run build -w api \ && rm -rf node_modules/.cache # Install artifacts backend WORKDIR /agentscope_runtime/ext_services/artifacts RUN npm install \ && rm -rf node_modules/.cache ``` -------------------------------- ### Run AgentScope Client Example with RocketMQ Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/simple_agent_use_rocketmq_example/agentscope_use_rocketmq_client_example/README.md Execute the AgentScope A2A client example using Maven. Configure RocketMQ connection details and topic/group IDs as parameters. Ensure RocketMQ LiteTopic is deployed and resources are created. ```bash mvn compile exec:java -Dexec.mainClass=io.agentscope.A2aAgentCallerExample -DrocketMQNamespace= -DworkAgentResponseTopic=WorkerAgentResponse -DworkAgentResponseGroupID=CID_HOST_AGENT_LITE -DrocketMQAK= -DrocketMQSK= ``` -------------------------------- ### Create and Use GUI Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Demonstrates how to create and interact with a GUI sandbox. The sandbox is automatically deleted after execution. Ensure Docker is installed and running. ```java import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (GuiSandbox guiSandbox = new GuiSandbox(sandboxService, "userId", "sessionId")) { Gson gson = new Gson(); String tools = gson.toJson(guiSandbox.listTools("")); System.out.println("Available tools: "); System.out.println(tools); String desktopUrl = guiSandbox.getDesktopUrl(); System.out.println("GUI Desktop URL: " + desktopUrl); String cursorPosition = guiSandbox.computerUse("get_cursor_position"); System.out.println("Cursor Position: " + cursorPosition); String screenShot = guiSandbox.computerUse("get_screenshot"); System.out.println("Screenshot (base64): " + screenShot); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and Use Sandbox Service in AgentScope Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/sandbox.md Demonstrates starting the sandbox service, creating a browser sandbox, and registering sandbox tools with an Agent's Toolkit. Ensure the Docker client is available if using DockerClientStarter. ```java import io.agentscope.core.tool.Toolkit; import io.agentscope.runtime.engine.agents.agentscope.tools.ToolkitInit; import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // 1. Start the sandbox service BaseClientStarter clientStarter = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientStarter) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // 2. Connect to or create a sandbox (here, a browser-type sandbox is created) Sandbox sandbox = new BrowserSandbox(sandboxService, "user", "session"); // 3. Obtain tool methods and register them into the Agent's Toolkit Toolkit toolkit = new Toolkit(); toolkit.registerTool(ToolkitInit.BrowserNavigateTool(sandbox)); toolkit.registerTool(ToolkitInit.BrowserTakeScreenshotTool(sandbox)); // From this point on, the Agent can safely invoke these tools within the sandbox } } ``` -------------------------------- ### Install AgentScope Deployer Maven Plugin Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/maven_plugin/README.md Build the plugin locally before using it in your project. ```bash cd maven_plugin mvn clean install ``` -------------------------------- ### Generated Dockerfile Example Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/maven_plugin/README.md An example of a Dockerfile automatically generated by the plugin for a Java application. ```dockerfile FROM eclipse-temurin:17-jre WORKDIR /app # Copy JAR file COPY my-app-1.0.0.jar app.jar # Environment variables ENV SPRING_PROFILES_ACTIVE=production # Expose port EXPOSE 8080 # Run application ENTRYPOINT ["java", "-jar", "app.jar"] ``` -------------------------------- ### Build the AgentScope RocketMQ Client Project Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/simple_agent_use_rocketmq_example/agentscope_use_rocketmq_client_example/README.md Compile the Java project using Maven. Ensure you have Java 17+ and Maven 3.6+ installed. ```bash mvn clean compile ``` -------------------------------- ### Create and Use Filesystem Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Shows how to create and use a Filesystem sandbox for file operations. This sandbox is automatically deleted after execution. Docker must be installed and running. ```java import com.google.gson.Gson; import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (FilesystemSandbox filesystemSandbox = new FilesystemSandbox(sandboxService, "userId", "sessionId")) { Gson gson = new Gson(); String tools = gson.toJson(filesystemSandbox.listTools("")); System.out.println("Available tools: "); System.out.println(tools); String desktopUrl = filesystemSandbox.getDesktopUrl(); System.out.println("GUI Desktop URL: " + desktopUrl); String result = filesystemSandbox.createDirectory("test"); System.out.println("Created directory 'test' at: " + result); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and Use InMemorySessionHistoryService Source: https://context7.com/agentscope-ai/agentscope-runtime-java/llms.txt Demonstrates creating, starting, appending messages, retrieving, listing, and deleting sessions using `InMemorySessionHistoryService`. Ensure the service is stopped after use. ```java SessionHistoryService svc = new InMemorySessionHistoryService(); svc.start(); // Create session Session session = svc.createSession("user-1", Optional.of("sess-001")).join(); // Append messages Message userMsg = new Message(); userMsg.setRole(Role.USER); userMsg.setContent("What is 2 + 2?"); svc.appendMessage(session, List.of(userMsg)).join(); // Retrieve session to inspect history Optional found = svc.getSession("user-1", "sess-001").join(); found.ifPresent(s -> System.out.println("Message count: " + s.getMessages().size())); // List all sessions for a user List sessions = svc.listSessions("user-1").join(); System.out.println("Sessions: " + sessions.size()); // Delete session svc.deleteSession("user-1", "sess-001").join(); svc.stop(); ``` -------------------------------- ### Create and Use Browser Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Illustrates how to create and utilize a Browser sandbox for browser-related operations. The sandbox is automatically removed after use. Ensure Docker is installed and running. ```java import com.google.gson.Gson; import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (BrowserSandbox browserSandbox = new BrowserSandbox(sandboxService, "userId", "sessionId")) { Gson gson = new Gson(); String tools = gson.toJson(browserSandbox.listTools("")); System.out.println("Available tools: "); System.out.println(tools); String desktopUrl = browserSandbox.getDesktopUrl(); System.out.println("GUI Desktop URL: " + desktopUrl); ``` -------------------------------- ### Manage Sandboxes with SandboxService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Demonstrates how to create, start, connect to, execute code within, and close a sandbox using the SandboxService. Reusing the same user and session IDs will reuse the existing sandbox instance. ```java import io.agentscope.runtime.sandbox.box.BaseSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); try { // Connect to a sandbox, specifying the desired sandbox type BaseSandbox baseSandbox = new BaseSandbox(sandboxService, "userId", "sessionId"); // Call tool methods directly on the sandbox instance String pythonResult = baseSandbox.runIpythonCell("a=1"); System.out.println("Sandbox execution result: " + pythonResult); // Using the same session_id and user_id reuses the same sandbox instance baseSandbox = new BaseSandbox(sandboxService, "userId", "sessionId"); pythonResult = baseSandbox.runIpythonCell("print(a)"); System.out.println("Sandbox execution result: " + pythonResult); // Close the sandbox explicitly baseSandbox.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and Run AgentApp Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/deployment/agent_app.md Create a minimal AgentApp instance and start a SpringBoot-based HTTP service skeleton. The service initially provides basic endpoints like '/', '/health', '/readiness', '/liveness', and '/a2a'. The '/process' endpoint is not exposed by default. ```java MyAgentScopeAgentHandler agentHandler = new MyAgentScopeAgentHandler(); // Initialize agentHandler properties AgentApp agentApp = new AgentApp(agentHandler); // Service will be exposed at http://localhost:10001 agentApp.run("localhost",10001); ``` -------------------------------- ### Manage Sandbox Lifecycle and Tools with SandboxService Source: https://context7.com/agentscope-ai/agentscope-runtime-java/llms.txt Demonstrates the full lifecycle management of sandbox containers using SandboxService, including creation, starting, stopping, and tool invocation. Ensure AGENTBAY_API_KEY is set for cloud sandbox usage. ```java ManagerConfig config = ManagerConfig.builder() .clientStarter(DockerClientStarter.builder().build()) .portRange(new PortRange(49152, 59152)) .containerPrefixKey("myapp_") .agentBayApiKey(System.getenv("AGENTBAY_API_KEY")) // optional cloud sandbox .build(); SandboxService svc = new SandboxService(config); svc.start(); // Create/reuse a base sandbox container BaseSandbox sandbox = new BaseSandbox(svc, "user-1", "session-1"); ContainerModel info = sandbox.getInfo(); System.out.println("Container ID: " + info.getContainerId()); System.out.println("Base URL: " + info.getBaseUrl()); // List available tools inside the sandbox Map tools = svc.listTools(sandbox, null); System.out.println("Tool count: " + tools.size()); // Call a tool directly String result = svc.callTool(sandbox, "execute_python_code", Map.of("code", "print(2 + 2)")); System.out.println("Result: " + result); // {"content":[{"type":"text","text":"4\n"}]} // Add MCP servers to the sandbox svc.addMcpServers(sandbox, Map.of("filesystem", Map.of("command", "npx", "args", List.of("-y", "@modelcontextprotocol/server-filesystem", "/workspace"))), false); // Stop and clean up svc.stopAndRemoveSandbox("user-1", "session-1", sandbox.getSandboxType()); svc.stop(); ``` -------------------------------- ### Manage Long-Term Memories with MemoryService Source: https://context7.com/agentscope-ai/agentscope-runtime-java/llms.txt Provides examples of using the `MemoryService` interface for long-term memory operations, including adding, semantic searching, listing, and deleting memories. Supports user-specific and session-specific memory management. Ensure the service is started and stopped. ```java MemoryService memSvc = new InMemoryMemoryService(); memSvc.start(); // Add messages to memory List msgs = new ArrayList<>(); Message m = new Message(); m.setRole(Role.ASSISTANT); m.setContent("The user prefers bullet-point summaries."); msgs.add(m); memSvc.addMemory("user-1", msgs, Optional.of("session-1")).join(); // Semantic search List query = new ArrayList<>(); Message q = new Message(); q.setRole(Role.USER); q.setContent("What formatting does the user prefer?"); query.add(q); List results = memSvc.searchMemory( "user-1", query, Optional.of(Map.of("top_k", 5)) ).join(); System.out.println("Results: " + results.size()); // List all memories with pagination List all = memSvc.listMemory( "user-1", Optional.of(Map.of("page_num", 1, "page_size", 20)) ).join(); // Delete memories for a specific session memSvc.deleteMemory("user-1", Optional.of("session-1")).join(); // Delete all memories for a user memSvc.deleteMemory("user-1", Optional.empty()).join(); memSvc.stop(); ``` -------------------------------- ### Initialize and Use SandboxService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/service.md Demonstrates initializing SandboxService with a Kubernetes client configuration and connecting to a browser sandbox for tool registration. ```java import io.agentscope.core.tool.Toolkit; import io.agentscope.runtime.engine.agents.agentscope.tools.ToolkitInit; import io.agentscope.runtime.engine.services.sandbox.SandboxService; import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.client.config.BaseClientConfig; import io.agentscope.runtime.sandbox.manager.client.config.KubernetesClientConfig; import io.agentscope.runtime.sandbox.manager.model.ManagerConfig; public class Main { public static void main(String[] args) { BaseClientConfig clientConfig = KubernetesClientConfig.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .containerDeployment(clientConfig) .build(); SandboxService sandboxService = new SandboxService( new SandboxManager(managerConfig) ); sandboxService.start(); Sandbox sandbox = sandboxService.connect("TestSession", "User1", BrowserSandbox.class); Toolkit toolkit = new Toolkit(); toolkit.registerTool(ToolkitInit.BrowserNavigateTool(sandbox)); toolkit.registerTool(ToolkitInit.BrowserTakeScreenshotTool(sandbox)); } } ``` -------------------------------- ### Create Training Instance with AgentScope Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/training_sandbox.md Initializes the sandbox service, connects to a sandbox, retrieves environment profiles, and creates a training instance. This instance is assigned a unique ID and contains the initial query state. ```java import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import io.agentscope.runtime.sandbox.box.APPWorldSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; import java.lang.reflect.Type; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (APPWorldSandbox appWorldSandbox = new APPWorldSandbox(sandboxService, "userId", "sessionId")) { String profileList = appWorldSandbox.getEnvProfile("appworld", "train", null); System.out.println("Profile List: " + profileList); Gson gson = new Gson(); Type listType = new TypeToken>() {}.getType(); List profiles = gson.fromJson(profileList, listType); if (profiles.isEmpty()) { System.out.println("No profiles available."); return; } String initResponse = appWorldSandbox.createInstance("appworld", profiles.get(0)); Type instanceType = new TypeToken>() {}.getType(); Map instance = gson.fromJson(initResponse, instanceType); String instanceInfoStr = instance.get("info").toString(); Type infoType = new TypeToken>() {}.getType(); Map infoMap = gson.fromJson(instanceInfoStr, infoType); String instanceId = (String) infoMap.get("instance_id"); String query = instance.get("state").toString(); System.out.println("Created instance " + instanceId + " with query: " + query); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Verify Appworld Sandbox Installation Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/training_sandbox.md Verifies the installation of the Appworld sandbox by creating a sandbox service, connecting to an APPWorldSandbox instance, and retrieving environment profile information. ```java import io.agentscope.runtime.sandbox.box.APPWorldSandbox; import io.agentscope.runtime.sandbox.manager.ManagerConfig; import io.agentscope.runtime.sandbox.manager.SandboxService; import io.agentscope.runtime.sandbox.manager.client.container.BaseClientStarter; import io.agentscope.runtime.sandbox.manager.client.container.docker.DockerClientStarter; public class Main { public static void main(String[] args) { // Create and start the sandbox service BaseClientStarter clientConfig = DockerClientStarter.builder().build(); ManagerConfig managerConfig = ManagerConfig.builder() .clientStarter(clientConfig) .build(); SandboxService sandboxService = new SandboxService(managerConfig); sandboxService.start(); // Connect to a sandbox (the sandbox will be automatically deleted after execution) try (APPWorldSandbox appWorldSandbox = new APPWorldSandbox(sandboxService, "userId", "sessionId")) { String profileList = appWorldSandbox.getEnvProfile("appworld", "train", null); System.out.println("Profile List: " + profileList); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Load Kernel Modules for Linux Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/sandbox.md Commands to install necessary kernel modules and load them for sandbox operation on a Linux host. Ensure the kernel version matches when installing extra modules. ```bash # 1. Install additional kernel modules sudo apt update && sudo apt install -y linux-modules-extra-$(uname -r) # 2. Load kernel modules and create device nodes sudo modprobe binder_linux devices="binder,hwbinder,vndbinder" sudo modprobe ashmem_linux ``` -------------------------------- ### Initialize Services and Deploy AgentApp Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/README.md Configure the custom agent handler with necessary services like state, session history, memory, and sandbox services. Then, deploy the agent using AgentApp, specifying the port for the server to listen on. ```java // Create and configure the agent handler MyAgentScopeAgentHandler agentHandler = new MyAgentScopeAgentHandler(); agentHandler.setStateService(new InMemoryStateService()); agentHandler.setSessionHistoryService(new InMemorySessionHistoryService()); agentHandler.setMemoryService(new InMemoryMemoryService()); agentHandler.setSandboxService(new SandboxService( new SandboxManager(ManagerConfig.builder().build()) )); // Deploy using AgentApp AgentApp agentApp = new AgentApp(agentHandler); agentApp.run(8090); // Server will listen on port 8090 ``` -------------------------------- ### Install AgentScope Runtime from Source Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/advanced.md Install AgentScope Runtime in editable mode to enable custom sandbox development. This allows for immediate changes without reinstallation and facilitates custom sandbox registration. ```bash git clone https://github.com/agentscope-ai/agentscope-runtime.git cd agentscope-runtime git submodule update --init --recursive pip install -e . ``` -------------------------------- ### Initialize Agent Tools with ToolkitInit Source: https://context7.com/agentscope-ai/agentscope-runtime-java/llms.txt Demonstrates initializing various AgentTool instances for execution, filesystem operations, and browser automation using the ToolkitInit factory. MCP tools can also be generated from JSON server configurations. ```java Sandbox sandbox = sandboxService.connect(userId, sessionId, BaseSandbox.class); // --- Execution tools --- AgentTool pythonTool = ToolkitInit.RunPythonCodeTool(sandbox); AgentTool shellTool = ToolkitInit.RunShellCommandTool(sandbox); // --- Filesystem tools --- AgentTool readFile = ToolkitInit.ReadFileTool(sandbox); AgentTool writeFile = ToolkitInit.WriteFileTool(sandbox); AgentTool editFile = ToolkitInit.EditFileTool(sandbox); AgentTool listDir = ToolkitInit.ListDirectoryTool(sandbox); AgentTool dirTree = ToolkitInit.DirectoryTreeTool(sandbox); AgentTool search = ToolkitInit.SearchFilesTool(sandbox); // --- Browser tools --- AgentTool nav = ToolkitInit.BrowserNavigateTool(sandbox); AgentTool click = ToolkitInit.BrowserClickTool(sandbox); AgentTool type = ToolkitInit.BrowserTypeTool(sandbox); AgentTool screenshot = ToolkitInit.BrowserTakeScreenshotTool(sandbox); AgentTool snapshot = ToolkitInit.BrowserSnapshotTool(sandbox); AgentTool pdf = ToolkitInit.BrowserPdfSaveTool(sandbox); // --- MCP tools (whitelist/blacklist filtering) --- List mcpTools = ToolkitInit.getMcpTools( Map.of("github", Map.of( "command", "npx", "args", List.of("-y", "@modelcontextprotocol/server-github"), "env", Map.of("GITHUB_PERSONAL_ACCESS_TOKEN", System.getenv("GITHUB_TOKEN")) )), "base", sandboxService, Set.of("create_issue", "list_issues"), // whitelist null // blacklist ); Toolkit toolkit = new Toolkit(); toolkit.registerTool(pythonTool); toolkit.registerTool(nav); mcpTools.forEach(toolkit::registerTool); ``` -------------------------------- ### Build and Run Java Backend with Maven Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/examples/browser_use_fullstack_runtime/README.md Build the parent project, then navigate to the backend directory to package the Spring Boot application. Run the backend using Maven or by executing the generated JAR file. ```bash cd ../../.. mvn clean install -DskipTests cd examples/browser_use_fullstack_runtime/backend mvn clean package # Option 1: Run with Maven mvn spring-boot:run # Option 2: Run the JAR java -jar target/browser-agent-backend-1.0.0.jar ``` -------------------------------- ### Initialize and Use InMemoryStateService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/state.md Demonstrates initializing the InMemoryStateService, saving agent state, and exporting it. Assumes the agent has state_dict and load_state_dict methods. ```python from agentscope_runtime.engine.services.agent_state import InMemoryStateService # Initialize service state_service = InMemoryStateService() await state_service.start() # Assume agent has state_dict method agent_state = agent.state_dict() # Save state (returns round_id) round_id = await state_service.save_state( user_id="User1", session_id="TestSession", state=agent_state ) print(f"State saved in round {round_id}") # Export latest state (or specify round_id) loaded_state = await state_service.export_state( user_id="User1", session_id="TestSession" ) agent.load_state_dict(loaded_state) ``` -------------------------------- ### A2A Streaming Output (SSE) Response Format Example Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/deployment/agent_app.md This is an example of the Server-Sent Events (SSE) response format received from the agent. It includes multiple events for task submission, status updates, artifact updates, and the final completion status. ```bash id:2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc event:jsonrpc data:{"jsonrpc":"2.0","id":"2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc","result":{"id":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","status":{"state":"submitted","timestamp":"2025-12-10T08:18:30.104001Z"},"artifacts":[],"history":[{"role":"user","parts":[{"text":"Hello, please calculate the 30th Fibonacci number using Python","kind":"text"}],"messageId":"c4911b64c8404b7a8bf7200dd225b152","contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","metadata":{"userId":"me","sessionId":"test1"},"kind":"message"}],"kind":"task"}} id:2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc event:jsonrpc data:{"jsonrpc":"2.0","id":"2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc","result":{"taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","status":{"state":"working","timestamp":"2025-12-10T08:18:30.107693Z"},"contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","final":false,"kind":"status-update"}} id:2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc event:jsonrpc data:{"jsonrpc":"2.0","id":"2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc","result":{"taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","artifact":{"artifactId":"ef4de8cc-5042-4d17-800a-78257b7d51ba","name":"agent-response","parts":[{"text":"Calling tool run_ipython_cell with arguments: {\"code\":\"def fibonacci(n):\n if n <= 0:\n return 'Input should be a positive integer.'\n elif n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n a, b = 0, 1\n for _ in range(2, n):\n a, b = b, a + b\n return b\n\n# Calculate the 30th Fibonacci number\nfibonacci(30)"} (call ID: call_3b7697e5158b44ea95cc11)","kind":"text"}],"metadata":{"type":"toolCall"}},"contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","append":false,"lastChunk":false,"kind":"artifact-update"}} id:2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc event:jsonrpc data:{"jsonrpc":"2.0","id":"2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc","result":{"taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","artifact":{"artifactId":"ef4de8cc-5042-4d17-800a-78257b7d51ba","name":"agent-response","parts":[{"text":"Tool run_ipython_cell returned result: [{\"text\":\"{\\\"meta\\\":null,\\\"content\\\":[{\\\"type\\\":\\\"text\\\",\\\"text\\\":\\\"Out[1]: 514229\\\\n\\\",\\\"annotations\\\":null,\\\"description\\\":\\\"stdout\\\"}],\\\"isError\\\":false}\",\"type\":\"text\"}] (call ID: call_3b7697e5158b44ea95cc11)","kind":"text"}],"metadata":{"type":"toolResponse"}},"contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","append":true,"lastChunk":false,"kind":"artifact-update"}} ...... id:2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc event:jsonrpc data:{"jsonrpc":"2.0","id":"2d2b4dc8-8ea2-437b-888d-3aaf3a8239dc","result":{"taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","status":{"state":"completed","message":{"role":"agent","parts":[{"text":"run_ipython_cellrun_ipython_cellThe 30th Fibonacci number is 514229.","kind":"text"}],"messageId":"a4258fb3-5b79-461d-934a-8802dd0bebb8","contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","taskId":"8a3021a6-1b4e-4fc9-b70b-a39f03aa476c","metadata":{"type":"final_response"},"kind":"message"},"timestamp":"2025-12-10T08:18:38.298168Z"},"contextId":"ea00d2b3-ce89-4707-b457-ef58a68b35ff","final":true,"kind":"status-update"}} ``` -------------------------------- ### Initialize BFCL Sandbox Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/sandbox/training_sandbox.md Connects to the BFCLSandbox, retrieves environment profiles, creates an instance, and extracts instance information. Ensure OPENAI_API_KEY and DATASET_SUB_TYPE environment variables are set. ```java try (Sandbox sandbox = sandboxService.connect("sessionId", "userId", BFCLSandbox.class)){ if(sandbox instanceof BFCLSandbox bfclSandbox){ String profileList = bfclSandbox.getEnvProfile("bfcl"); System.out.println("Connected to BFCLSandbox. Profile List: " + profileList); Gson gson = new Gson(); Type listType = new TypeToken>(){}.getType(); List list = gson.fromJson(profileList, listType); String initResponse = bfclSandbox.createInstance("bfcl", list.get(0)); Type instanceType = new TypeToken>(){}.getType(); Map instance = gson.fromJson(initResponse, instanceType); String instanceInfo = instance.get("info").toString(); Type infoType = new TypeToken>(){}.getType(); Map infoMap = gson.fromJson(instanceInfo, infoType); String instanceId = (String) infoMap.get("instance_id"); String query = instance.get("state").toString(); System.out.println("Created instance " + instanceId + " with query: " + query); } else { System.err.println("Failed to connect to TrainingSandbox."); } } ``` -------------------------------- ### Switch to RedisStateService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/state.md Shows how to switch from InMemoryStateService to RedisStateService by instantiating RedisStateService with a Redis URL. It then demonstrates saving and exporting state using the Redis backend. ```python from agentscope_runtime.engine.services.agent_state import RedisStateService state_service = RedisStateService(redis_url="redis://localhost:6379/0") await state_service.start() # Save state await state_service.save_state(user_id="User1", session_id="ProdSession", state=agent.state_dict()) # Export state state = await state_service.export_state(user_id="User1", session_id="ProdSession") agent.load_state_dict(state) ``` -------------------------------- ### Using LongTermMemoryAdapter with InMemoryMemoryService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/memory.md Encapsulates the underlying MemoryService as an agent's LongTermMemory module using LongTermMemoryAdapter. This example demonstrates initialization with an InMemoryMemoryService for local testing. ```java import io.agentscope.runtime.adapters.agentscope.memory.LongTermMemoryAdapter; import io.agentscope.runtime.engine.services.memory.persistence.memory.service.InMemoryMemoryService; import io.agentscope.runtime.engine.services.memory.service.MemoryService; public class Main { public static void main(String[] args) { // Choose backend implementation (this example uses InMemory for local testing) MemoryService memoryService = new InMemoryMemoryService(); LongTermMemoryAdapter longTermMemory = null; // Wrap with adapter, bind to LongTermMemory module longTermMemory = new LongTermMemoryAdapter( memoryService, "User1", "Test Session" ); // After this, you can directly use long_term_memory in the Agent to access cross-session long-term memory } } ``` -------------------------------- ### Run Agent App Locally Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/deployment/agent_app.md Starts the local Agent application on the specified host and port. Ensure the AgentApp instance is properly initialized before calling this method. ```java agentApp.run("localhost", 10001); ``` -------------------------------- ### Manage Service Lifecycle and Health Check Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/service.md Illustrates starting, checking the health of, and stopping a MemoryService using its lifecycle methods and handling the health check future. ```java import io.agentscope.runtime.engine.services.memory.persistence.memory.service.InMemoryMemoryService; import io.agentscope.runtime.engine.services.memory.service.MemoryService; import java.util.concurrent.CompletableFuture; public class Main { public static void main(String[] args) { MemoryService memoryService = new InMemoryMemoryService(); memoryService.start(); CompletableFuture healthFuture = memoryService.health(); healthFuture.thenAccept(isHealthy -> { if (isHealthy) { System.out.println("Service is healthy!"); } else { System.err.println("Service is DOWN!"); } }); memoryService.stop(); } } ``` -------------------------------- ### Using MemoryAdapter with SessionHistoryService Source: https://github.com/agentscope-ai/agentscope-runtime-java/blob/main/cookbook/en/service/session_history.md Demonstrates how to initialize and use the MemoryAdapter to bind a SessionHistoryService implementation to an agent's Memory module. This example uses InMemorySessionHistoryService for local testing. ```java import io.agentscope.runtime.adapters.agentscope.memory.MemoryAdapter; import io.agentscope.runtime.engine.services.memory.persistence.session.InMemorySessionHistoryService; import io.agentscope.runtime.engine.services.memory.service.SessionHistoryService; public class Main { public static void main(String[] args) { // Choose backend implementation (this example uses InMemory for local testing) SessionHistoryService sessionHistoryService = new InMemorySessionHistoryService(); MemoryAdapter memory = null; // Wrap with adapter, bind to Memory module memory = new MemoryAdapter( sessionHistoryService, "User1", "TestSession" ); // After this, you can directly use memory in the Agent to access session history } } ```