Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions examples/simple_sandbox_tool_example/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>

<groupId>com.example</groupId>
<artifactId>agentscope-examples-simple</artifactId>
<version>1.0.0</version>
<name>AgentScope Spring MVC Demo</name>
<description>AgentScope simple sample project using Spring MVC</description>

<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- AgentScope Core -->
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-core</artifactId>
<version>0.2.0</version>
</dependency>

<!-- Sandbox Tool -->
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-runtime-agentscope</artifactId>
<version>1.0.0-BETA1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.agentscope;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* AgentScope Spring Boot application main class
*/
@SpringBootApplication
public class AgentScopeApplication {

public static void main(String[] args) {
SpringApplication.run(AgentScopeApplication.class, args);

System.out.println("\n" + "=".repeat(70));
System.out.println("🎉 AgentScope Demo started successfully!");
System.out.println("=".repeat(70));
System.out.println();

System.out.println("📡 API endpoints:");
System.out.println(" • Health check: http://localhost:8080/api/chat/health");
System.out.println(" • Send message: http://localhost:8080/api/chat");
System.out.println(" • View tools: http://localhost:8080/api/chat/tools");
System.out.println(" • Reset conversation: http://localhost:8080/api/chat/reset");
System.out.println();

System.out.println("🛠️ Available tools:");
System.out.println(" • Weather tool - query city weather and forecasts");
System.out.println(" • Calculator tool - math operations (add, subtract, multiply, divide, power, sqrt)");
System.out.println(" • Sandbox tool - sandbox browser search");
System.out.println();

System.out.println("💡 Quick tests:");
System.out.println(" curl -X POST http://localhost:8080/api/chat \\");
System.out.println(" -H \"Content-Type: application/json\" \\");
System.out.println(" -d '{\"message\": \"How is the weather in Beijing today?\"}'");
System.out.println();

System.out.println("curl -X POST http://localhost:8080/api/chat \\\n" +
" -H \"Content-Type: application/json\" \\\n" +
" -d '{\"message\": \"Use the browser tool to search on Baidu for today'\\''s gold price\"}'");

System.out.println(" curl -X POST http://localhost:8080/api/chat \\");
System.out.println(" -H \"Content-Type: application/json\" \\");
System.out.println(" -d '{\"message\": \"Calculate 123 + 456\"}'");
System.out.println();

System.out.println("📚 More info:");
System.out.println(" • See README.md for detailed docs");
System.out.println(" • See QUICKSTART.md to get started quickly");
System.out.println(" • Import AgentScope-API.postman_collection.json to test with Postman");
System.out.println();
System.out.println("=".repeat(70) + "\n");
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.agentscope.config;

import com.example.agentscope.tools.CalculatorTool;
import com.example.agentscope.tools.WeatherTool;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.memory.InMemoryMemory;
import io.agentscope.core.model.DashScopeChatModel;
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.DockerClientConfig;
import io.agentscope.runtime.sandbox.manager.model.ManagerConfig;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
* AgentScope configuration class
* Configure Agent, Model, and Toolkit
*/
@Configuration
public class AgentConfig {

@Value("${DASHSCOPE_API_KEY:#{null}}")
private String apiKey;

/**
* Configure the DashScope chat model
*/
@Bean
public DashScopeChatModel chatModel() {
String key = apiKey != null ? apiKey : System.getenv("DASHSCOPE_API_KEY");

if (key == null || key.isEmpty()) {
throw new IllegalStateException(
"DASHSCOPE_API_KEY is not configured. Please set env var: export DASHSCOPE_API_KEY=your-api-key"
);
}

return DashScopeChatModel.builder()
.apiKey(key)
.modelName("qwen3-max")
.build();
}

/**
* Reuse SandboxService as a singleton
*/
@Bean
public SandboxService sandboxService() {
BaseClientConfig clientConfig = DockerClientConfig.builder().build();
ManagerConfig managerConfig = ManagerConfig.builder()
.containerDeployment(clientConfig)
.build();

SandboxService service = new SandboxService(
new SandboxManager(managerConfig)
);
service.start();
return service;
}

/**
* Configure the toolkit and register all tools
*/
@Bean
public Toolkit createToolkit(SandboxService sandboxService) {
Toolkit toolkit = new Toolkit();
WeatherTool weatherTool = new WeatherTool();
CalculatorTool calculatorTool = new CalculatorTool();

toolkit.registerTool(weatherTool);
toolkit.registerTool(calculatorTool);
try {
Sandbox sandbox = sandboxService.connect("userId", "sessionId", BrowserSandbox.class);
toolkit.registerTool(ToolkitInit.BrowserNavigateTool(sandbox));
if (sandbox instanceof BrowserSandbox browserSandbox) {
String desktopUrl = browserSandbox.getDesktopUrl();
System.out.println("GUI Desktop URL: " + desktopUrl);
}
} catch (Exception ignored) {
}
return toolkit;
}

/**
* Create an independent Agent for each request to avoid shared state
*/
@Bean
@Scope("prototype")
public ReActAgent createAgentInstance(DashScopeChatModel chatModel, Toolkit toolkit) {
return ReActAgent.builder()
.name("Smart Assistant")
.sysPrompt("""
You are an intelligent assistant named "XiaoZhi". You can help users:
1. Query weather information
2. Perform mathematical calculations

Use the available tools to answer user questions and provide accurate and helpful responses.
Be friendly, professional, and clear in your answers.
""")
.model(chatModel)
.toolkit(toolkit)
.memory(new InMemoryMemory())
.maxIters(5)
.build();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.agentscope.controller;

import com.example.agentscope.model.ChatRequest;
import com.example.agentscope.model.ChatResponse;
import com.example.agentscope.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
* Chat API controller
* Provide external REST API endpoints
*/
@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*")
public class ChatController {

@Autowired
private ChatService chatService;

/**
* Health check endpoint
*/
@GetMapping("/health")
public ResponseEntity<String> health() {
return ResponseEntity.ok("AgentScope service is running ✓");
}

/**
* Send a message to the Agent
*
* @param request Chat request
* @return Chat response
*/
@PostMapping
public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {
try {
ChatResponse response = chatService.chat(request);
return ResponseEntity.ok(response);
} catch (Exception e) {
ChatResponse errorResponse = new ChatResponse();
errorResponse.setSuccess(false);
errorResponse.setMessage("An error occurred while processing the request: " + e.getMessage());
errorResponse.setError(e.getClass().getSimpleName());
return ResponseEntity.internalServerError().body(errorResponse);
}
}

/**
* Get available tool list
*/
@GetMapping("/tools")
public ResponseEntity<?> getTools() {
try {
return ResponseEntity.ok(chatService.getAvailableTools());
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body("Failed to get tool list: " + e.getMessage());
}
}

/**
* Reset conversation history
*/
@PostMapping("/reset")
public ResponseEntity<String> reset() {
try {
chatService.resetMemory();
return ResponseEntity.ok("Conversation history reset ✓");
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body("Reset failed: " + e.getMessage());
}
}
}

Loading
Loading