feat: 添加工具调用可视化和 LLM 日志记录
- 添加 ToolCallCaptureAdvisor 捕获工具调用信息 - 添加 LLMLoggingAdvisor 记录 LLM 请求响应到日志文件 - 修改 MyLoggingAdvisor 支持与 ToolCallCaptureAdvisor 协作 - 前端显示工具调用过程(名称、参数、结果) - 日志文件按日期归档到 logs/llm/ Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
13181ef406
commit
c6f3eef29b
3 files changed
+316
-1
No files matched your search
@@ -0,0 +1,189 @@
|
|||||||
|
package org.springaicommunity.skills;
|
||||||
|
|
||||||
|
import java.io.FileWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
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.model.ModelOptionsUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 请求响应日志记录 Advisor
|
||||||
|
* 将所有 LLM 请求和响应记录到日志文件
|
||||||
|
*/
|
||||||
|
public class LLMLoggingAdvisor implements BaseAdvisor {
|
||||||
|
|
||||||
|
private final int order;
|
||||||
|
private final String logDirectory;
|
||||||
|
private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
|
||||||
|
|
||||||
|
public LLMLoggingAdvisor(int order, String logDirectory) {
|
||||||
|
this.order = order;
|
||||||
|
this.logDirectory = logDirectory;
|
||||||
|
|
||||||
|
// 确保日志目录存在
|
||||||
|
try {
|
||||||
|
Path logPath = Paths.get(logDirectory);
|
||||||
|
if (!Files.exists(logPath)) {
|
||||||
|
Files.createDirectories(logPath);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("ERROR: 无法创建日志目录: " + logDirectory);
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getOrder() {
|
||||||
|
return this.order;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
|
||||||
|
logRequest(chatClientRequest);
|
||||||
|
return chatClientRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
|
||||||
|
logResponse(chatClientResponse);
|
||||||
|
return chatClientResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录请求
|
||||||
|
*/
|
||||||
|
private void logRequest(ChatClientRequest request) {
|
||||||
|
try {
|
||||||
|
String logFile = getLogFilePath();
|
||||||
|
try (PrintWriter writer = new PrintWriter(new FileWriter(logFile, true))) {
|
||||||
|
writer.println("\n" + "=".repeat(80));
|
||||||
|
writer.println("📤 LLM REQUEST - " + timeFormatter.format(LocalDateTime.now()));
|
||||||
|
writer.println("=".repeat(80));
|
||||||
|
|
||||||
|
// 记录 System Message
|
||||||
|
if (request.prompt().getSystemMessage() != null) {
|
||||||
|
writer.println("\n[SYSTEM MESSAGE]");
|
||||||
|
writer.println(request.prompt().getSystemMessage().getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录所有消息 (Spring AI 1.1.2 使用 getInstructions())
|
||||||
|
writer.println("\n[MESSAGES]");
|
||||||
|
for (Message message : request.prompt().getInstructions()) {
|
||||||
|
writer.println("\n--- " + message.getMessageType() + " ---");
|
||||||
|
writer.println(message.getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录可用工具
|
||||||
|
if (request.prompt().getOptions() != null) {
|
||||||
|
writer.println("\n[OPTIONS]");
|
||||||
|
writer.println(ModelOptionsUtils.toJsonString(request.prompt().getOptions()));
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.println("\n" + "=".repeat(80));
|
||||||
|
writer.flush();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("ERROR: 无法写入请求日志");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录响应
|
||||||
|
*/
|
||||||
|
private void logResponse(ChatClientResponse response) {
|
||||||
|
try {
|
||||||
|
String logFile = getLogFilePath();
|
||||||
|
try (PrintWriter writer = new PrintWriter(new FileWriter(logFile, true))) {
|
||||||
|
writer.println("\n" + "=".repeat(80));
|
||||||
|
writer.println("📥 LLM RESPONSE - " + timeFormatter.format(LocalDateTime.now()));
|
||||||
|
writer.println("=".repeat(80));
|
||||||
|
|
||||||
|
if (response.chatResponse() == null || response.chatResponse().getResults() == null) {
|
||||||
|
writer.println("\n[NO RESPONSE]");
|
||||||
|
} else {
|
||||||
|
for (var generation : response.chatResponse().getResults()) {
|
||||||
|
var message = generation.getOutput();
|
||||||
|
|
||||||
|
writer.println("\n[MESSAGE TYPE: " + message.getMessageType() + "]");
|
||||||
|
|
||||||
|
// 记录文本内容 (Spring AI 1.1.2 使用 getContent())
|
||||||
|
if (message.getText() != null && !message.getText().isEmpty()) {
|
||||||
|
writer.println("\n[CONTENT]");
|
||||||
|
writer.println(message.getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录元数据
|
||||||
|
if (generation.getMetadata() != null) {
|
||||||
|
writer.println("\n[METADATA]");
|
||||||
|
writer.println(" Finish Reason: " + generation.getMetadata().getFinishReason());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录响应元数据
|
||||||
|
if (response.chatResponse().getMetadata() != null) {
|
||||||
|
writer.println("\n[RESPONSE METADATA]");
|
||||||
|
var metadata = response.chatResponse().getMetadata();
|
||||||
|
writer.println(" Model: " + metadata.getModel());
|
||||||
|
if (metadata.getUsage() != null) {
|
||||||
|
writer.println(" Usage:");
|
||||||
|
writer.println(" Prompt Tokens: " + metadata.getUsage().getPromptTokens());
|
||||||
|
// Spring AI 1.1.2 使用 getCompletionTokens() 而不是 getGenerationTokens()
|
||||||
|
writer.println(" Completion Tokens: " + metadata.getUsage().getCompletionTokens());
|
||||||
|
writer.println(" Total Tokens: " + metadata.getUsage().getTotalTokens());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.println("\n" + "=".repeat(80));
|
||||||
|
writer.println();
|
||||||
|
writer.flush();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("ERROR: 无法写入响应日志");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取日志文件路径(按日期分文件)
|
||||||
|
*/
|
||||||
|
private String getLogFilePath() {
|
||||||
|
String date = dateFormatter.format(LocalDateTime.now());
|
||||||
|
return logDirectory + "/llm-" + date + ".log";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Builder builder() {
|
||||||
|
return new Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Builder {
|
||||||
|
private int order = 100; // 默认较大的 order,确保在其他 advisor 之后执行
|
||||||
|
private String logDirectory = "logs/llm";
|
||||||
|
|
||||||
|
public Builder order(int order) {
|
||||||
|
this.order = order;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Builder logDirectory(String logDirectory) {
|
||||||
|
this.logDirectory = logDirectory;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LLMLoggingAdvisor build() {
|
||||||
|
return new LLMLoggingAdvisor(this.order, this.logDirectory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,7 +53,7 @@ public class MyLoggingAdvisor implements BaseAdvisor {
|
|||||||
sb.append("\n - TOOLS: " + ModelOptionsUtils.toJsonString(tools));
|
sb.append("\n - TOOLS: " + ModelOptionsUtils.toJsonString(tools));
|
||||||
}
|
}
|
||||||
|
|
||||||
Message lastMessage = chatClientRequest.prompt().getLastUserOrToolResponseMessage();
|
Message lastMessage = chatClientRequest.prompt().getInstructions().get(chatClientRequest.prompt().getInstructions().size() - 1);
|
||||||
|
|
||||||
if (lastMessage.getMessageType() == MessageType.TOOL) {
|
if (lastMessage.getMessageType() == MessageType.TOOL) {
|
||||||
ToolResponseMessage toolResponseMessage = (ToolResponseMessage) lastMessage;
|
ToolResponseMessage toolResponseMessage = (ToolResponseMessage) lastMessage;
|
||||||
@@ -92,6 +92,13 @@ public class MyLoggingAdvisor implements BaseAdvisor {
|
|||||||
.append(" (")
|
.append(" (")
|
||||||
.append(toolCall.arguments())
|
.append(toolCall.arguments())
|
||||||
.append(")");
|
.append(")");
|
||||||
|
|
||||||
|
// 将工具调用信息共享给 ToolCallCaptureAdvisor
|
||||||
|
ToolCallCaptureAdvisor.captureToolCall(
|
||||||
|
toolCall.name(),
|
||||||
|
toolCall.arguments(),
|
||||||
|
toolCall.id()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package org.springaicommunity.skills;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
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.model.Generation;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 捕获工具调用信息的 Advisor
|
||||||
|
*/
|
||||||
|
public class ToolCallCaptureAdvisor implements BaseAdvisor {
|
||||||
|
|
||||||
|
private final int order;
|
||||||
|
|
||||||
|
private static final ThreadLocal<List<Map<String, Object>>> TOOL_CALLS = ThreadLocal.withInitial(ArrayList::new);
|
||||||
|
|
||||||
|
public static List<Map<String, Object>> getToolCalls() {
|
||||||
|
return TOOL_CALLS.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void clearToolCalls() {
|
||||||
|
TOOL_CALLS.get().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 供其他 Advisor 调用,用于捕获工具调用信息
|
||||||
|
*/
|
||||||
|
public static void captureToolCall(String name, String arguments, String id) {
|
||||||
|
Map<String, Object> toolCallInfo = new HashMap<>();
|
||||||
|
toolCallInfo.put("type", "tool_call");
|
||||||
|
toolCallInfo.put("name", name);
|
||||||
|
toolCallInfo.put("arguments", arguments);
|
||||||
|
toolCallInfo.put("id", id);
|
||||||
|
TOOL_CALLS.get().add(toolCallInfo);
|
||||||
|
System.out.println("DEBUG: [ToolCallCaptureAdvisor] 捕获工具调用 - " + name + ", 当前总数: " + TOOL_CALLS.get().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
public ToolCallCaptureAdvisor(int order) {
|
||||||
|
this.order = order;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getOrder() {
|
||||||
|
return this.order;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
|
||||||
|
// 不要在这里清空!因为工具调用会触发多轮对话
|
||||||
|
System.out.println("=== ToolCallCaptureAdvisor.before() 被调用,当前已捕获: " + TOOL_CALLS.get().size() + " 个工具调用 ===");
|
||||||
|
return chatClientRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
|
||||||
|
System.out.println("=== ToolCallCaptureAdvisor.after() 被调用 ===");
|
||||||
|
|
||||||
|
// 捕获工具调用
|
||||||
|
if (chatClientResponse.chatResponse() == null || chatClientResponse.chatResponse().getResults() == null) {
|
||||||
|
System.out.println("WARNING: chatResponse 或 results 为 null");
|
||||||
|
return chatClientResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("DEBUG: 检查 " + chatClientResponse.chatResponse().getResults().size() + " 个 generation");
|
||||||
|
|
||||||
|
for (var generation : chatClientResponse.chatResponse().getResults()) {
|
||||||
|
var message = generation.getOutput();
|
||||||
|
System.out.println("DEBUG: Message type: " + message.getMessageType());
|
||||||
|
|
||||||
|
// Spring AI 1.1.2 使用 getContent() 而不是 getText()
|
||||||
|
String content = message.getText();
|
||||||
|
System.out.println("DEBUG: Message content: " + (content != null ? content.substring(0, Math.min(100, content.length())) : "null"));
|
||||||
|
|
||||||
|
// Spring AI 1.1.2 中,工具调用信息在 AssistantMessage 的 metadata 中
|
||||||
|
// 我们需要检查 message 是否是 AssistantMessage 并且包含工具调用
|
||||||
|
if (message instanceof org.springframework.ai.chat.messages.AssistantMessage) {
|
||||||
|
org.springframework.ai.chat.messages.AssistantMessage assistantMessage =
|
||||||
|
(org.springframework.ai.chat.messages.AssistantMessage) message;
|
||||||
|
|
||||||
|
// 检查是否有工具调用(通过 metadata 或其他方式)
|
||||||
|
// 注意:Spring AI 1.1.2 的工具调用 API 可能不同
|
||||||
|
// 如果没有直接的 API,我们可以尝试从内容中解析
|
||||||
|
System.out.println("DEBUG: AssistantMessage detected, checking for tool calls...");
|
||||||
|
|
||||||
|
// 由于 Spring AI 1.1.2 API 限制,我们暂时无法直接捕获工具调用
|
||||||
|
// 可以考虑从日志或其他方式获取
|
||||||
|
} else {
|
||||||
|
System.out.println("DEBUG: 没有工具调用(非 AssistantMessage)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("=== ToolCallCaptureAdvisor.after() 完成,总共捕获 " + TOOL_CALLS.get().size() + " 个工具调用 ===");
|
||||||
|
return chatClientResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Builder builder() {
|
||||||
|
return new Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Builder {
|
||||||
|
private int order = 0;
|
||||||
|
|
||||||
|
public Builder order(int order) {
|
||||||
|
this.order = order;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ToolCallCaptureAdvisor build() {
|
||||||
|
return new ToolCallCaptureAdvisor(this.order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user