完整代码:
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.coding.ShellCommandTool;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.Set;
import java.util.function.Function;
public class ShellCommandToolExample {
// 简单的用户批准回调函数(控制台交互)
private static final Function<String, Boolean> APPROVAL_CALLBACK = command -> {
System.out.println("\n⚠️ Agent 想要执行以下 Shell 命令:");
System.out.println(" " + command);
System.out.print("是否允许执行?(y/n): ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine().trim().toLowerCase();
return input.equals("y") || input.equals("yes");
};
public static void main(String[] args) {
// 1. 创建 Toolkit
Toolkit toolkit = new Toolkit();
// 2. 定义允许执行的命令白名单(只允许 ls、pwd、echo、cat 等安全命令)
Set<String> allowedCommands = Set.of(
"ls", "pwd", "echo", "cat", "date", "whoami",
"ls -l", "ls -la", "echo *", "cat " // 支持前缀匹配
);
// 3. 创建 ShellCommandTool(推荐同时设置白名单 + 批准回调 + 超时)
ShellCommandTool shellTool = new ShellCommandTool(
"/Users/wei/tmp", // 指定工作目录
allowedCommands, // 白名单
APPROVAL_CALLBACK, // 手动批准(强烈推荐)
null,
StandardCharsets.UTF_8
);
toolkit.registerTool(shellTool);
// 4. 创建模型和 Agent
DashScopeChatModel model = DashScopeChatModel.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen3-max")
.build();
ReActAgent agent = ReActAgent.builder()
.name("ShellAgent")
.sysPrompt("你是一个 AI 助手。")
.model(model)
.toolkit(toolkit)
.build();
// 5. 测试示例查询
String[] testQueries = {
"列出当前目录下的所有文件和文件夹",
"显示当前工作目录路径",
"输出今天的日期和时间",
"创建一个名为 test.txt 的文件,内容为 Hello from AgentScope Shell Tool"
};
for (String query : testQueries) {
System.out.println("\n=== 用户问题: " + query + " ===");
Msg msg = agent.call(Msg.builder().textContent(query).build()).block();
System.out.println(msg.getTextContent());
}
}
}
完整代码: