新增 ReActAdvisor 引导 AI 按照 Thought-Action-Observation-Iterate 流程进行推理和工具调用,提升任务执行的系统性和完整性。同时优化 HTTP 流量日志,简化输出格式,提高日志可读性。 主要变更: - 新增 ReActAdvisor 实现 ReAct 推理模式,order=-10 确保最先执行 - 在系统提示中添加 Skills 目录结构和脚本路径使用说明 - 优化 Advisor 链注释,明确各 Advisor 的执行顺序和职责 - 简化 HttpTrafficLogger 输出,移除冗余的请求/响应头信息 - 将日志最大体积从 100KB 提升到 1MB,支持更大的请求体 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
241 lines
7.8 KiB
Java
241 lines
7.8 KiB
Java
package org.springaicommunity.skills;
|
|
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
import org.springaicommunity.agent.tools.FileSystemTools;
|
|
import org.springaicommunity.agent.tools.GlobTool;
|
|
import org.springaicommunity.agent.tools.GrepTool;
|
|
import org.springaicommunity.agent.tools.ShellTools;
|
|
import org.springaicommunity.agent.tools.SkillsTool;
|
|
import org.springaicommunity.agent.tools.TodoWriteTool;
|
|
import org.springaicommunity.agent.tools.TodoWriteTool.Todos;
|
|
import org.springaicommunity.agent.tools.TodoWriteTool.Todos.TodoItem;
|
|
import org.springaicommunity.skills.advisor.ReActAdvisor;
|
|
import org.springframework.ai.chat.client.ChatClient;
|
|
import org.springframework.ai.chat.client.advisor.ToolCallAdvisor;
|
|
import org.springframework.ai.chat.memory.ChatMemory;
|
|
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
|
import org.springframework.ai.chat.model.ChatModel;
|
|
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
|
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.boot.SpringApplication;
|
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
import org.springframework.context.ApplicationEvent;
|
|
import org.springframework.context.ApplicationEventPublisher;
|
|
import org.springframework.context.annotation.Bean;
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.context.event.EventListener;
|
|
import org.springframework.core.io.Resource;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
@SpringBootApplication
|
|
@Configuration
|
|
public class Application {
|
|
|
|
public static void main(String[] args) {
|
|
SpringApplication.run(Application.class, args);
|
|
}
|
|
|
|
/**
|
|
* 用于流式响应的 ChatClient.Builder (不支持工具调用)
|
|
*/
|
|
@Bean("streamChatClientBuilder")
|
|
ChatClient.Builder streamChatClientBuilder(ChatModel chatModel, @Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs) {
|
|
|
|
// @formatter:off
|
|
return ChatClient.builder(chatModel)
|
|
.defaultSystem("Always use the available skills to assist the user in their requests.")
|
|
|
|
// 流式响应不支持工具调用,所以不配置工具
|
|
|
|
.defaultAdvisors(
|
|
// Custom logging advisor
|
|
MyLoggingAdvisor.builder()
|
|
.showAvailableTools(false)
|
|
.showSystemMessage(false)
|
|
.build())
|
|
.defaultToolContext(Map.of("foo", "bar"));
|
|
// @formatter:on
|
|
}
|
|
|
|
/**
|
|
* 流式 ChatClient 实例(预先构建好)
|
|
*/
|
|
@Bean
|
|
ChatClient streamChatClient(@Qualifier("streamChatClientBuilder") ChatClient.Builder streamChatClientBuilder, ChatMemory chatMemory) {
|
|
return streamChatClientBuilder
|
|
.defaultAdvisors(
|
|
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor.builder(chatMemory).build()
|
|
)
|
|
.build();
|
|
}
|
|
|
|
|
|
/**
|
|
* 用于非流式响应的 ChatClient.Builder (支持工具调用)
|
|
*/
|
|
@Bean("chatClientBuilder")
|
|
ChatClient.Builder chatClientBuilder(ChatModel chatModel,
|
|
@Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs,
|
|
SyncMcpToolCallbackProvider mcpToolCallbackProvider,
|
|
ApplicationEventPublisher applicationEventPublisher,
|
|
ReActAdvisor reactAdvisor) {
|
|
|
|
// @formatter:off
|
|
return ChatClient.builder(chatModel)
|
|
// Skills tool
|
|
.defaultToolCallbacks(SkillsTool.builder().addSkillsResources(agentSkillsDirs).build())
|
|
|
|
// Todo management tool
|
|
.defaultTools(TodoWriteTool.builder()
|
|
// Publish todo update events
|
|
.todoEventHandler(event ->
|
|
applicationEventPublisher.publishEvent(new TodoUpdateEvent(this, event.todos())))
|
|
.build())
|
|
|
|
// 添加 System Prompt 指导工具的正确使用
|
|
.defaultSystem("""
|
|
IMPORTANT: When the user requests any task, you MUST first check if there is an available Skill that matches the task.
|
|
Skills provide specialized capabilities and domain knowledge for specific tasks.
|
|
Skills Directory Structure:
|
|
- Base Path: D:\\\\workspace\\\\spring-ai-skill\\\\src\\\\main\\\\resources\\\\.claude\\\\skills
|
|
- Each skill has its own subdirectory: {base_path}\\\\{skill_name}
|
|
- Example: xlsx skill is located at D:\\\\workspace\\\\spring-ai-skill\\\\src\\\\main\\\\resources\\\\.claude\\\\skills\\\\xlsx
|
|
- When executing scripts from a skill, ALWAYS use the full absolute path
|
|
- Example script path: D:\\\\workspace\\\\spring-ai-skill\\\\src\\\\main\\\\resources\\\\.claude\\\\skills\\\\xlsx\\\\script.py
|
|
|
|
Tool Priority:
|
|
1. FIRST: Check available Skills and use the Skill tool if a matching skill exists
|
|
2. SECOND: Use other built-in tools (Bash, FileSystem, Glob, Grep, etc.) only if no suitable Skill is available
|
|
|
|
Always prioritize Skills over other tools when a relevant Skill is available for the user's request.
|
|
|
|
When using the TodoWrite tool, you MUST provide the todos parameter as an object with a "todos" array, not a direct array.
|
|
|
|
Correct format:
|
|
{
|
|
"todos": [
|
|
{"content": "task 1", "status": "pending"},
|
|
{"content": "task 2", "status": "pending"}
|
|
]
|
|
}
|
|
|
|
Incorrect format (DO NOT USE):
|
|
[
|
|
{"content": "task 1", "status": "pending"},
|
|
{"content": "task 2", "status": "pending"}
|
|
]
|
|
""")
|
|
|
|
// Built-in tools
|
|
.defaultTools(
|
|
// Bash execution tool
|
|
ShellTools.builder().build(),
|
|
// Read, Write and Edit files tool
|
|
FileSystemTools.builder().build(),
|
|
// Glob file pattern matching tool
|
|
GlobTool.builder().build(),
|
|
// Grep content search tool
|
|
GrepTool.builder().build())
|
|
|
|
// MCP tools (通过 Spring AI 自动配置注入)
|
|
.defaultToolCallbacks(mcpToolCallbackProvider.getToolCallbacks())
|
|
|
|
.defaultAdvisors(
|
|
// ReAct Advisor - order=-10,最先执行,添加 ReAct 推理引导
|
|
reactAdvisor,
|
|
|
|
// Tool Calling advisor - 处理工具调用的递归循环
|
|
ToolCallAdvisor.builder().build(),
|
|
|
|
// Custom logging advisor - order=-1,记录请求和工具调用
|
|
MyLoggingAdvisor.builder()
|
|
.order(-1)
|
|
.showAvailableTools(true)
|
|
.showSystemMessage(true)
|
|
.build(),
|
|
|
|
// Tool call capture advisor - order=0,捕获工具调用信息供前端展示
|
|
ToolCallCaptureAdvisor.builder().order(0).build(),
|
|
|
|
// LLM 请求响应日志记录 - order=100,最后执行,记录完整交互
|
|
LLMLoggingAdvisor.builder()
|
|
.logDirectory("logs/llm")
|
|
.order(100)
|
|
.build())
|
|
.defaultToolContext(Map.of("foo", "bar"));
|
|
// @formatter:on
|
|
}
|
|
|
|
/**
|
|
* 非流式 ChatClient 实例(预先构建好,支持工具调用)
|
|
*/
|
|
@Bean
|
|
ChatClient chatClient(@Qualifier("chatClientBuilder") ChatClient.Builder chatClientBuilder, ChatMemory chatMemory) {
|
|
return chatClientBuilder
|
|
.defaultAdvisors(
|
|
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor.builder(chatMemory).build()
|
|
)
|
|
.build();
|
|
}
|
|
|
|
@Bean
|
|
ChatMemory chatMemory() {
|
|
return MessageWindowChatMemory.builder()
|
|
.maxMessages(100)
|
|
.build();
|
|
}
|
|
|
|
/**
|
|
* Todo 更新事件
|
|
*/
|
|
public static class TodoUpdateEvent extends ApplicationEvent {
|
|
|
|
private final List<TodoItem> todos;
|
|
|
|
public TodoUpdateEvent(Object source, List<TodoItem> todos) {
|
|
super(source);
|
|
this.todos = List.copyOf(todos);
|
|
}
|
|
|
|
public List<TodoItem> getTodos() {
|
|
return todos;
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* Todo 进度监听器
|
|
*/
|
|
@Component
|
|
public static class TodoProgressListener {
|
|
|
|
@EventListener
|
|
public void onTodoUpdate(TodoUpdateEvent event) {
|
|
int completed = (int) event.getTodos().stream().filter(t -> t.status() == Todos.Status.completed).count();
|
|
int total = event.getTodos().size();
|
|
|
|
if (total == 0) {
|
|
return;
|
|
}
|
|
|
|
System.out.printf("\n📋 Progress: %d/%d tasks completed (%.0f%%)\n", completed, total,
|
|
(completed * 100.0 / total));
|
|
|
|
for (TodoItem item : event.getTodos()) {
|
|
String statusIcon = switch (item.status()) {
|
|
case completed -> "[✓]";
|
|
case in_progress -> "[→]";
|
|
case pending -> "[ ]";
|
|
};
|
|
System.out.printf(" %s %s\n", statusIcon, item.content());
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|