Compare commits
1
Commits
6b602f5cd0
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e059d1aa50 |
No files matched your search
@@ -11,6 +11,7 @@ import org.springaicommunity.agent.tools.SkillsTool;
|
|||||||
import org.springaicommunity.agent.tools.TodoWriteTool;
|
import org.springaicommunity.agent.tools.TodoWriteTool;
|
||||||
import org.springaicommunity.agent.tools.TodoWriteTool.Todos;
|
import org.springaicommunity.agent.tools.TodoWriteTool.Todos;
|
||||||
import org.springaicommunity.agent.tools.TodoWriteTool.Todos.TodoItem;
|
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.ChatClient;
|
||||||
import org.springframework.ai.chat.client.advisor.ToolCallAdvisor;
|
import org.springframework.ai.chat.client.advisor.ToolCallAdvisor;
|
||||||
import org.springframework.ai.chat.memory.ChatMemory;
|
import org.springframework.ai.chat.memory.ChatMemory;
|
||||||
@@ -80,7 +81,8 @@ public class Application {
|
|||||||
ChatClient.Builder chatClientBuilder(ChatModel chatModel,
|
ChatClient.Builder chatClientBuilder(ChatModel chatModel,
|
||||||
@Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs,
|
@Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs,
|
||||||
SyncMcpToolCallbackProvider mcpToolCallbackProvider,
|
SyncMcpToolCallbackProvider mcpToolCallbackProvider,
|
||||||
ApplicationEventPublisher applicationEventPublisher) {
|
ApplicationEventPublisher applicationEventPublisher,
|
||||||
|
ReActAdvisor reactAdvisor) {
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
return ChatClient.builder(chatModel)
|
return ChatClient.builder(chatModel)
|
||||||
@@ -98,7 +100,13 @@ public class Application {
|
|||||||
.defaultSystem("""
|
.defaultSystem("""
|
||||||
IMPORTANT: When the user requests any task, you MUST first check if there is an available Skill that matches the task.
|
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 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:
|
Tool Priority:
|
||||||
1. FIRST: Check available Skills and use the Skill tool if a matching skill exists
|
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
|
2. SECOND: Use other built-in tools (Bash, FileSystem, Glob, Grep, etc.) only if no suitable Skill is available
|
||||||
@@ -137,17 +145,23 @@ public class Application {
|
|||||||
.defaultToolCallbacks(mcpToolCallbackProvider.getToolCallbacks())
|
.defaultToolCallbacks(mcpToolCallbackProvider.getToolCallbacks())
|
||||||
|
|
||||||
.defaultAdvisors(
|
.defaultAdvisors(
|
||||||
// Tool Calling advisor
|
// ReAct Advisor - order=-10,最先执行,添加 ReAct 推理引导
|
||||||
|
reactAdvisor,
|
||||||
|
|
||||||
|
// Tool Calling advisor - 处理工具调用的递归循环
|
||||||
ToolCallAdvisor.builder().build(),
|
ToolCallAdvisor.builder().build(),
|
||||||
// Custom logging advisor - order=-1 确保最先执行,可以捕获工具调用
|
|
||||||
|
// Custom logging advisor - order=-1,记录请求和工具调用
|
||||||
MyLoggingAdvisor.builder()
|
MyLoggingAdvisor.builder()
|
||||||
.order(-1)
|
.order(-1)
|
||||||
.showAvailableTools(true)
|
.showAvailableTools(true)
|
||||||
.showSystemMessage(true)
|
.showSystemMessage(true)
|
||||||
.build(),
|
.build(),
|
||||||
// Tool call capture advisor (接收来自 MyLoggingAdvisor 的工具调用信息)
|
|
||||||
|
// Tool call capture advisor - order=0,捕获工具调用信息供前端展示
|
||||||
ToolCallCaptureAdvisor.builder().order(0).build(),
|
ToolCallCaptureAdvisor.builder().order(0).build(),
|
||||||
// LLM 请求响应日志记录 - order=100 确保最后执行
|
|
||||||
|
// LLM 请求响应日志记录 - order=100,最后执行,记录完整交互
|
||||||
LLMLoggingAdvisor.builder()
|
LLMLoggingAdvisor.builder()
|
||||||
.logDirectory("logs/llm")
|
.logDirectory("logs/llm")
|
||||||
.order(100)
|
.order(100)
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package org.springaicommunity.skills.advisor;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.ai.chat.client.ChatClientRequest;
|
||||||
|
import org.springframework.ai.chat.client.ChatClientResponse;
|
||||||
|
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
|
||||||
|
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
|
||||||
|
import org.springframework.ai.chat.messages.Message;
|
||||||
|
import org.springframework.ai.chat.messages.SystemMessage;
|
||||||
|
import org.springframework.ai.chat.prompt.Prompt;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ReAct (Reasoning + Acting) Advisor
|
||||||
|
*
|
||||||
|
* 在系统提示中添加 ReAct 模式引导,让 AI 按照以下流程思考:
|
||||||
|
* 1. Thought(思考):分析问题,决定需要做什么
|
||||||
|
* 2. Action(行动):使用可用工具执行操作
|
||||||
|
* 3. Observation(观察):审查操作结果
|
||||||
|
* 4. Iterate(迭代):重复上述过程直到完成任务
|
||||||
|
*
|
||||||
|
* 该 Advisor 与 ToolCallAdvisor 配合使用:
|
||||||
|
* - ReActAdvisor 负责添加推理引导
|
||||||
|
* - ToolCallAdvisor 负责处理工具调用的递归循环
|
||||||
|
*
|
||||||
|
* @author Claude Code
|
||||||
|
* @since 2026-02-04
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class ReActAdvisor implements BaseAdvisor {
|
||||||
|
|
||||||
|
private static final String REACT_SYSTEM_PROMPT = """
|
||||||
|
You are an AI assistant using the ReAct (Reasoning + Acting) pattern.
|
||||||
|
|
||||||
|
For each user request, follow this iterative process:
|
||||||
|
|
||||||
|
1. **Thought**: Analyze the problem and decide what needs to be done
|
||||||
|
- Break down complex tasks into steps
|
||||||
|
- Identify what information or tools you need
|
||||||
|
|
||||||
|
2. **Action**: Execute actions using available tools
|
||||||
|
- FIRST: Check if there's a relevant Skill (docx, pdf, pptx, xlsx, etc.)
|
||||||
|
- SECOND: Use other tools (Bash, FileSystem, Grep, Glob) if no Skill matches
|
||||||
|
|
||||||
|
3. **Observation**: Review the results of your actions
|
||||||
|
- Analyze what you learned
|
||||||
|
- Determine if you need more information
|
||||||
|
|
||||||
|
4. **Iterate**: Repeat the process until you can provide a complete answer
|
||||||
|
- The framework will automatically handle tool calling loops
|
||||||
|
- Continue reasoning and acting until the task is fully completed
|
||||||
|
|
||||||
|
Important guidelines:
|
||||||
|
- Always explain your reasoning before taking actions
|
||||||
|
- Prioritize Skills over other tools when applicable
|
||||||
|
- Be thorough and complete tasks fully before responding
|
||||||
|
- If you encounter errors, analyze them and try alternative approaches
|
||||||
|
""";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientRequest before(ChatClientRequest request, AdvisorChain chain) {
|
||||||
|
// 获取原有的系统消息
|
||||||
|
String originalSystemText = request.prompt().getSystemMessage() != null
|
||||||
|
? request.prompt().getSystemMessage().getText()
|
||||||
|
: "";
|
||||||
|
|
||||||
|
// 在原有系统提示的基础上添加 ReAct 提示
|
||||||
|
String enhancedSystemText = originalSystemText.isEmpty() ? REACT_SYSTEM_PROMPT
|
||||||
|
: originalSystemText + "\n\n" + REACT_SYSTEM_PROMPT;
|
||||||
|
|
||||||
|
// 创建新的系统消息
|
||||||
|
SystemMessage enhancedSystemMessage = new SystemMessage(enhancedSystemText);
|
||||||
|
|
||||||
|
// 创建新的消息列表(包含增强的系统消息和原有的其他消息)
|
||||||
|
List<Message> newMessages = new ArrayList<>();
|
||||||
|
newMessages.add(enhancedSystemMessage);
|
||||||
|
|
||||||
|
// 添加原有的非系统消息(使用 getInstructions() 获取消息列表)
|
||||||
|
for (Message msg : request.prompt().getInstructions()) {
|
||||||
|
if (!(msg instanceof SystemMessage)) {
|
||||||
|
newMessages.add(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建新的 Prompt
|
||||||
|
Prompt enhancedPrompt = new Prompt(newMessages, request.prompt().getOptions());
|
||||||
|
|
||||||
|
// 使用反射或简单方式:直接修改 request 的 prompt
|
||||||
|
// 由于 ChatClientRequest 可能是不可变的,我们需要创建一个包装类或使用其他方式
|
||||||
|
// 最简单的方式:利用 Spring AI 的内部机制,直接替换 prompt
|
||||||
|
|
||||||
|
// 注意:这里我们需要找到正确的方式来创建新的 ChatClientRequest
|
||||||
|
// 让我们先尝试直接返回原始请求,看看是否可以通过其他方式修改
|
||||||
|
|
||||||
|
// 临时方案:直接返回原始请求(不修改)
|
||||||
|
// TODO: 需要找到正确的 API 来修改系统消息
|
||||||
|
return new ChatClientRequest(enhancedPrompt, request.context());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientResponse after(ChatClientResponse response, AdvisorChain chain) {
|
||||||
|
// 不需要修改响应,直接返回
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getOrder() {
|
||||||
|
return -10; // 在其他 Advisor 之前执行,确保 ReAct 提示最先添加
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -44,7 +44,7 @@ public class HttpTrafficLogger {
|
|||||||
@Value("${ai.proxy.log.directory:logs/http-traffic}")
|
@Value("${ai.proxy.log.directory:logs/http-traffic}")
|
||||||
private String logDirectory;
|
private String logDirectory;
|
||||||
|
|
||||||
@Value("${ai.proxy.log.max-body-size:102400}")
|
@Value("${ai.proxy.log.max-body-size:1024000}")
|
||||||
private int maxBodySize;
|
private int maxBodySize;
|
||||||
|
|
||||||
// 异步写入日志的线程池
|
// 异步写入日志的线程池
|
||||||
@@ -92,17 +92,17 @@ public class HttpTrafficLogger {
|
|||||||
sb.append("================================================================================\n");
|
sb.append("================================================================================\n");
|
||||||
sb.append("📤 HTTP REQUEST - ").append(now.format(DATETIME_FORMATTER));
|
sb.append("📤 HTTP REQUEST - ").append(now.format(DATETIME_FORMATTER));
|
||||||
sb.append(" [").append(requestId).append("]\n");
|
sb.append(" [").append(requestId).append("]\n");
|
||||||
sb.append("================================================================================\n");
|
// sb.append("================================================================================\n");
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
|
|
||||||
// 请求行
|
// 请求行
|
||||||
sb.append(method).append(" ").append(path).append(" HTTP/1.1\n");
|
// sb.append(method).append(" ").append(path).append(" HTTP/1.1\n");
|
||||||
sb.append("Host: ").append(extractHost(url)).append("\n");
|
// sb.append("Host: ").append(extractHost(url)).append("\n");
|
||||||
|
//
|
||||||
// 请求头
|
// // 请求头
|
||||||
appendHeaders(sb, headers);
|
// appendHeaders(sb, headers);
|
||||||
|
//
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
|
|
||||||
// 请求体
|
// 请求体
|
||||||
if (body != null && body.length > 0) {
|
if (body != null && body.length > 0) {
|
||||||
@@ -143,16 +143,16 @@ public class HttpTrafficLogger {
|
|||||||
sb.append("\n");
|
sb.append("\n");
|
||||||
|
|
||||||
// 状态行
|
// 状态行
|
||||||
sb.append("HTTP/1.1 ").append(statusCode);
|
// sb.append("HTTP/1.1 ").append(statusCode);
|
||||||
if (statusText != null && !statusText.isEmpty()) {
|
// if (statusText != null && !statusText.isEmpty()) {
|
||||||
sb.append(" ").append(statusText);
|
// sb.append(" ").append(statusText);
|
||||||
}
|
// }
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
|
//
|
||||||
// 响应头
|
// // 响应头
|
||||||
appendHeaders(sb, headers);
|
// appendHeaders(sb, headers);
|
||||||
|
//
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
|
|
||||||
// 响应体
|
// 响应体
|
||||||
if (body != null && body.length > 0) {
|
if (body != null && body.length > 0) {
|
||||||
@@ -180,12 +180,12 @@ public class HttpTrafficLogger {
|
|||||||
sb.append("================================================================================\n");
|
sb.append("================================================================================\n");
|
||||||
sb.append("📥 HTTP STREAM RESPONSE START - ").append(now.format(DATETIME_FORMATTER));
|
sb.append("📥 HTTP STREAM RESPONSE START - ").append(now.format(DATETIME_FORMATTER));
|
||||||
sb.append(" [").append(requestId).append("]\n");
|
sb.append(" [").append(requestId).append("]\n");
|
||||||
sb.append("================================================================================\n");
|
// sb.append("================================================================================\n");
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
|
|
||||||
sb.append("HTTP/1.1 ").append(statusCode).append(" OK\n");
|
// sb.append("HTTP/1.1 ").append(statusCode).append(" OK\n");
|
||||||
appendHeaders(sb, headers);
|
// appendHeaders(sb, headers);
|
||||||
sb.append("\n");
|
// sb.append("\n");
|
||||||
sb.append("--- STREAM DATA BEGIN ---\n");
|
sb.append("--- STREAM DATA BEGIN ---\n");
|
||||||
|
|
||||||
asyncWriteLog(sb.toString());
|
asyncWriteLog(sb.toString());
|
||||||
@@ -210,12 +210,12 @@ public class HttpTrafficLogger {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
// StringBuilder sb = new StringBuilder();
|
||||||
sb.append("--- STREAM DATA END ---\n");
|
// sb.append("--- STREAM DATA END ---\n");
|
||||||
sb.append("流式响应完成,总耗时: ").append(durationMs).append("ms\n");
|
// sb.append("流式响应完成,总耗时: ").append(durationMs).append("ms\n");
|
||||||
sb.append("================================================================================\n");
|
// sb.append("================================================================================\n");
|
||||||
|
//
|
||||||
asyncWriteLog(sb.toString());
|
// asyncWriteLog(sb.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in new issue
Block a user