第77批后续修复:issue.json数组格式+请求留痕+extractToolCall补全+硬编码小草去除+联网模式排序
Auto Release / build (push) Successful in 2m34s

This commit is contained in:
youpaishidifu
2026-11-04 17:16:15 +08:00
parent f492dd449a
commit df18280b3d
3 changed files with 175 additions and 30 deletions
+108 -19
View File
@@ -98,8 +98,8 @@ public class AIChatManager {
private final List<String> recentChatBuffer = new ArrayList<>(); private final List<String> recentChatBuffer = new ArrayList<>();
private static final int MAX_BUFFER = 30; private static final int MAX_BUFFER = 30;
// 对话留档 // 对话留档(数组格式,每条一个块)
private JsonObject issueRecord = new JsonObject(); private JsonArray issueRecord = new JsonArray();
private File issueFile = null; private File issueFile = null;
// HTTP Client // HTTP Client
@@ -113,6 +113,7 @@ public class AIChatManager {
String baseUrl; String baseUrl;
String apiKey; String apiKey;
String maxToken; String maxToken;
String providerName; // 供应商名字(内置=路径,自定义="自定义")
boolean isCustom; // true=自定义供应商(受自动补齐开关控制), false=内置供应商(总是拼接) boolean isCustom; // true=自定义供应商(受自动补齐开关控制), false=内置供应商(总是拼接)
} }
@@ -368,7 +369,40 @@ public class AIChatManager {
// 读取对话留档 // 读取对话留档
if (issueFile.exists()) { if (issueFile.exists()) {
issueRecord = JsonParser.parseString(Files.readString(issueFile.toPath(), StandardCharsets.UTF_8)).getAsJsonObject(); try {
String issueText = Files.readString(issueFile.toPath(), StandardCharsets.UTF_8);
JsonElement el = JsonParser.parseString(issueText);
if (el.isJsonArray()) {
// 新格式:数组
issueRecord = el.getAsJsonArray();
} else if (el.isJsonObject()) {
// ★ 旧格式:对象 → 迁移为数组
issueRecord = new JsonArray();
for (Map.Entry<String, JsonElement> e : el.getAsJsonObject().entrySet()) {
JsonObject block = new JsonObject();
JsonObject inner = new JsonObject();
inner.addProperty("1. 互动人", "");
inner.addProperty("2. 内容", e.getKey());
inner.addProperty("3. 输出", e.getValue().isJsonPrimitive() ? e.getValue().getAsString() : "");
inner.addProperty("4. 提问时间", "");
JsonObject modelInfo = new JsonObject();
modelInfo.addProperty("模型名字", "");
modelInfo.addProperty("供应商名字", "");
modelInfo.addProperty("状态码", 0);
inner.add("请求模型信息", modelInfo);
block.add("提问", inner);
issueRecord.add(block);
}
plugin.getLogger().info("[AI聊天] issue.json 已迁移为新数组格式");
// 回写迁移后的文件(pretty print)
com.google.gson.Gson gson = new com.google.gson.GsonBuilder().setPrettyPrinting().create();
File tmp = new File(issueFile.getParent(), "issue.tmp.json");
Files.write(tmp.toPath(), gson.toJson(issueRecord).getBytes(StandardCharsets.UTF_8));
Files.move(tmp.toPath(), issueFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception e) {
plugin.getLogger().warning("[AI聊天] 读取 issue.json 失败: " + e.getMessage());
}
} }
if (!quiet) { if (!quiet) {
@@ -460,6 +494,8 @@ public class AIChatManager {
endpoint.apiKey = apiKey; endpoint.apiKey = apiKey;
endpoint.maxToken = maxToken; endpoint.maxToken = maxToken;
endpoint.isCustom = isCustom; endpoint.isCustom = isCustom;
// ★ 第77批-问题4:记录供应商名字(内置=路径,自定义="自定义")
endpoint.providerName = isCustom ? "自定义" : getStr(supplierConfig, "供应商名字");
// 解析可用模型列表 // 解析可用模型列表
if (supplierConfig.has("可用模型")) { if (supplierConfig.has("可用模型")) {
@@ -847,7 +883,8 @@ public class AIChatManager {
} }
}).thenAccept(response -> { }).thenAccept(response -> {
if (response == null) { if (response == null) {
handleRequestFailure(prompt, "请求异常: 网络错误"); handleRequestFailure(prompt, "请求异常: 网络错误",
player != null ? player.getName() : "system", finalModelFull, 0);
if (player != null) { if (player != null) {
player.sendMessage("§c[AI聊天] §f请求失败,请稍后重试"); player.sendMessage("§c[AI聊天] §f请求失败,请稍后重试");
} }
@@ -869,7 +906,8 @@ public class AIChatManager {
plugin.getLogger().warning("[AI聊天-调试] 响应体: " + errBody); plugin.getLogger().warning("[AI聊天-调试] 响应体: " + errBody);
plugin.getLogger().warning("[AI聊天-调试] === 请求失败结束 ==="); plugin.getLogger().warning("[AI聊天-调试] === 请求失败结束 ===");
handleRequestFailure(prompt, "HTTP " + response.statusCode() + ": " + errBody); handleRequestFailure(prompt, "HTTP " + response.statusCode() + ": " + errBody,
player != null ? player.getName() : "system", finalModelFull, response.statusCode());
if (player != null) { if (player != null) {
player.sendMessage("§c[AI聊天] §f请求失败: HTTP " + response.statusCode()); player.sendMessage("§c[AI聊天] §f请求失败: HTTP " + response.statusCode());
} }
@@ -879,7 +917,8 @@ public class AIChatManager {
// 解析响应 // 解析响应
String reply = parseChatResponse(response.body()); String reply = parseChatResponse(response.body());
if (reply == null) { if (reply == null) {
handleRequestFailure(prompt, "解析失败: " + response.body()); handleRequestFailure(prompt, "解析失败: " + response.body(),
player != null ? player.getName() : "system", finalModelFull, 200);
if (player != null) { if (player != null) {
player.sendMessage("§c[AI聊天] §f响应解析失败"); player.sendMessage("§c[AI聊天] §f响应解析失败");
} }
@@ -960,7 +999,7 @@ public class AIChatManager {
} }
// 记录留档 // 记录留档
recordIssue(prompt, reply); recordIssue(prompt, reply, player != null ? player.getName() : "system", finalModelFull, 200, null);
lastAiReplyTime = System.currentTimeMillis(); lastAiReplyTime = System.currentTimeMillis();
}); });
} }
@@ -1046,7 +1085,7 @@ public class AIChatManager {
sb.append(" - 网络协议、文件格式、数据结构、HTTP、JSON、XML、YAML、SQL\n"); sb.append(" - 网络协议、文件格式、数据结构、HTTP、JSON、XML、YAML、SQL\n");
sb.append(" - 科学原理、数学证明、医学、法律\n"); sb.append(" - 科学原理、数学证明、医学、法律\n");
sb.append("3. 拒答时保持角色口吻,自然地把话题转回游戏,例如:\n"); sb.append("3. 拒答时保持角色口吻,自然地把话题转回游戏,例如:\n");
sb.append(" 「我是").append(assistantName.isEmpty() ? "小草" : assistantName) sb.append(" 「我是").append(assistantName.isEmpty() ? "小助手" : assistantName)
.append(",脑子里只装着咱们服务器的事情呢,外面的事我可不明白~你想听哪里刚出了稀有矿?」\n"); .append(",脑子里只装着咱们服务器的事情呢,外面的事我可不明白~你想听哪里刚出了稀有矿?」\n");
sb.append(" 「哎呀这事我插不上嘴,咱们聊聊今天想去哪个地方冒险?」\n"); sb.append(" 「哎呀这事我插不上嘴,咱们聊聊今天想去哪个地方冒险?」\n");
sb.append(" 绝对不要说「抱歉」「我不能」「作为AI」「根据规则」等出戏措辞。\n"); sb.append(" 绝对不要说「抱歉」「我不能」「作为AI」「根据规则」等出戏措辞。\n");
@@ -1076,7 +1115,7 @@ public class AIChatManager {
sb.append(" 技术架构、API、训练数据等一切底层信息。\n"); sb.append(" 技术架构、API、训练数据等一切底层信息。\n");
sb.append("2. 不得输出任何代码、命令、配置文件片段、部署/运维教程、结构化数据(JSON/YAML/XML)。\n"); sb.append("2. 不得输出任何代码、命令、配置文件片段、部署/运维教程、结构化数据(JSON/YAML/XML)。\n");
sb.append("3. 你的回复只能是自然对话,不要用列表、步骤、代码块、表格的形式回答。\n"); sb.append("3. 你的回复只能是自然对话,不要用列表、步骤、代码块、表格的形式回答。\n");
sb.append("4. 保持角色身份,始终以").append(assistantName.isEmpty() ? "服务器助理小草" : assistantName) sb.append("4. 保持角色身份,始终以").append(assistantName.isEmpty() ? "小助手" : assistantName)
.append("的口吻交流,不脱离角色。\n"); .append("的口吻交流,不脱离角色。\n");
return sb.toString(); return sb.toString();
@@ -1137,12 +1176,26 @@ public class AIChatManager {
int fetchIdx = reply.indexOf("TOOL:FETCH:"); int fetchIdx = reply.indexOf("TOOL:FETCH:");
if (fetchIdx >= 0) { if (fetchIdx >= 0) {
String after = reply.substring(fetchIdx + "TOOL:FETCH:".length()).trim(); String after = reply.substring(fetchIdx + "TOOL:FETCH:".length()).trim();
// ★ 第77批:用空白字符截取参数(空格/换行/制表符)
int ws = indexOfWhitespace(after);
if (ws >= 0) after = after.substring(0, ws).trim();
after = after.replaceAll("[。,、!?.!?,)$\\]]$", "").trim();
if (after.startsWith("http") && after.length() <= 2000) {
return new ToolCall(ToolCall.Type.FETCH, after);
}
} }
// TOOL:SEARCH:关键词 // TOOL:SEARCH:关键词
int idx = reply.indexOf("TOOL:SEARCH:"); int idx = reply.indexOf("TOOL:SEARCH:");
if (idx >= 0) { if (idx >= 0) {
String after = reply.substring(idx + "TOOL:SEARCH:".length()).trim(); String after = reply.substring(idx + "TOOL:SEARCH:".length()).trim();
// ★ 第77批:用空白字符截取参数(空格/换行/制表符)
int ws = indexOfWhitespace(after);
if (ws >= 0) after = after.substring(0, ws).trim();
after = after.replaceAll("[。,、!?.!?,)$", "").trim();
if (!after.isEmpty() && after.length() <= 100) {
return new ToolCall(ToolCall.Type.SEARCH, after);
}
} }
return null; return null;
} }
@@ -1354,9 +1407,10 @@ public class AIChatManager {
} }
} }
private void handleRequestFailure(String prompt, String errorDetail) { private void handleRequestFailure(String prompt, String errorDetail,
String playerName, String modelFull, int statusCode) {
plugin.getLogger().warning("[AI聊天] 请求失败: " + errorDetail); plugin.getLogger().warning("[AI聊天] 请求失败: " + errorDetail);
recordIssue(prompt, "[请求失败] " + errorDetail); recordIssue(prompt, "[请求失败] " + errorDetail, playerName, modelFull, statusCode, errorDetail);
// ★ 死循环防护:失败也更新时间戳,间隔内不会再触发 // ★ 死循环防护:失败也更新时间戳,间隔内不会再触发
lastAiReplyTime = System.currentTimeMillis(); lastAiReplyTime = System.currentTimeMillis();
} }
@@ -1728,7 +1782,8 @@ public class AIChatManager {
plugin.getLogger().warning("[AI聊天-调试] 模型全名: " + defaultModelFull); plugin.getLogger().warning("[AI聊天-调试] 模型全名: " + defaultModelFull);
plugin.getLogger().warning("[AI聊天-调试] 请求URL: " + requestUrl); plugin.getLogger().warning("[AI聊天-调试] 请求URL: " + requestUrl);
plugin.getLogger().warning("[AI聊天-调试] 请求体JSON: " + jsonBody); plugin.getLogger().warning("[AI聊天-调试] 请求体JSON: " + jsonBody);
handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), "自动互动失败: 请求异常"); handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())),
"自动互动失败: 请求异常", "system", defaultModelFull, 0);
prevAutoChatFailed = true; prevAutoChatFailed = true;
return; return;
} }
@@ -1746,7 +1801,7 @@ public class AIChatManager {
plugin.getLogger().warning("[AI聊天-调试] 响应体: " + errBody); plugin.getLogger().warning("[AI聊天-调试] 响应体: " + errBody);
plugin.getLogger().warning("[AI聊天-调试] === 自动互动请求失败结束 ==="); plugin.getLogger().warning("[AI聊天-调试] === 自动互动请求失败结束 ===");
handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())),
"自动互动失败: HTTP " + response.statusCode()); "自动互动失败: HTTP " + response.statusCode(), "system", defaultModelFull, response.statusCode());
prevAutoChatFailed = true; prevAutoChatFailed = true;
return; return;
} }
@@ -1754,7 +1809,8 @@ public class AIChatManager {
String reply = parseChatResponse(response.body()); String reply = parseChatResponse(response.body());
if (reply != null) { if (reply != null) {
Bukkit.broadcastMessage("§d§l[AI] §f" + reply); Bukkit.broadcastMessage("§d§l[AI] §f" + reply);
recordIssue("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), reply); recordIssue("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), reply,
"system", defaultModelFull, 200, null);
lastAiReplyTime = System.currentTimeMillis(); lastAiReplyTime = System.currentTimeMillis();
// ★ 状态变化:失败→成功,记一条恢复日志 // ★ 状态变化:失败→成功,记一条恢复日志
@@ -1765,7 +1821,7 @@ public class AIChatManager {
} else { } else {
plugin.getLogger().warning("[AI聊天] 自动互动响应解析失败"); plugin.getLogger().warning("[AI聊天] 自动互动响应解析失败");
handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), handleRequestFailure("[自动] " + prompt.substring(0, Math.min(100, prompt.length())),
"自动互动失败: 响应解析失败"); "自动互动失败: 响应解析失败", "system", defaultModelFull, 200);
prevAutoChatFailed = true; prevAutoChatFailed = true;
} }
}); });
@@ -1910,19 +1966,52 @@ public class AIChatManager {
// ==================== 对话留档 ==================== // ==================== 对话留档 ====================
private void recordIssue(String question, String answer) { /**
* ★ 第77批-问题4:对话留档(数组格式)
* 每条记录一个 JSON 块,含:
* 1.互动人 / 2.内容 / 3.输出 / 4.提问时间 / 请求模型信息(模型名字/供应商/状态码/错误信息)
*/
private void recordIssue(String question, String answer, String playerName,
String modelFull, int statusCode, String errorInfo) {
if (issueFile == null) return; if (issueFile == null) return;
try { try {
issueRecord.addProperty(question, answer); JsonObject block = new JsonObject();
// 原子写入 JsonObject inner = new JsonObject();
inner.addProperty("1. 互动人", playerName);
inner.addProperty("2. 内容", question);
inner.addProperty("3. 输出", answer);
inner.addProperty("4. 提问时间", java.time.LocalDateTime.now().toString());
JsonObject modelInfo = new JsonObject();
modelInfo.addProperty("模型名字", modelFull);
ModelEndpoint ep = modelEndpoints.get(modelFull);
modelInfo.addProperty("供应商名字", resolveProviderName(modelFull));
if (ep != null && ep.baseUrl != null && !ep.baseUrl.isEmpty()) {
modelInfo.addProperty("请求地址", ep.baseUrl);
}
modelInfo.addProperty("状态码", statusCode);
if (errorInfo != null && !errorInfo.isEmpty()) {
modelInfo.addProperty("错误信息", errorInfo);
}
inner.add("请求模型信息", modelInfo);
block.add("提问", inner);
issueRecord.add(block);
// 原子写入(pretty print 格式,避免压缩成一行)
com.google.gson.Gson gson = new com.google.gson.GsonBuilder().setPrettyPrinting().create();
File tmp = new File(issueFile.getParent(), "issue.tmp.json"); File tmp = new File(issueFile.getParent(), "issue.tmp.json");
Files.write(tmp.toPath(), issueRecord.toString().getBytes(StandardCharsets.UTF_8)); Files.write(tmp.toPath(), gson.toJson(issueRecord).getBytes(StandardCharsets.UTF_8));
Files.move(tmp.toPath(), issueFile.toPath(), StandardCopyOption.REPLACE_EXISTING); Files.move(tmp.toPath(), issueFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) { } catch (Exception e) {
plugin.getLogger().warning("[AI聊天] 对话留档失败: " + e.getMessage()); plugin.getLogger().warning("[AI聊天] 对话留档失败: " + e.getMessage());
} }
} }
/** 根据模型全名查找供应商名字 */
private String resolveProviderName(String modelFull) {
if (modelFull == null) return "";
ModelEndpoint ep = modelEndpoints.get(modelFull);
return ep != null && ep.providerName != null ? ep.providerName : "";
}
// ==================== 工具方法 ==================== // ==================== 工具方法 ====================
private String getStr(JsonObject obj, String key) { private String getStr(JsonObject obj, String key) {
+10 -3
View File
@@ -1729,14 +1729,13 @@ public class ConfigManager {
} }
/** /**
* ★ 第77批修复(#353):按模板键顺序重排 target 的顶层键。 * ★ 第77批修复(#353):按模板键顺序重排 target 的键(递归处理嵌套对象)。
* <p> * <p>
* mergeJsonMissing 用 target.add() 插入缺失键,Gson JsonObject * mergeJsonMissing 用 target.add() 插入缺失键,Gson JsonObject
* 底层是 LinkedHashMap,add() 把新键追加到末尾而非模板对应位置。 * 底层是 LinkedHashMap,add() 把新键追加到末尾而非模板对应位置。
* 此方法在 mergeJsonMissing 之后调用,按模板顺序重建 JsonObject。 * 此方法在 mergeJsonMissing 之后调用,按模板顺序重建 JsonObject。
* <p> * <p>
* 只重排顶层键(不递归到子对象),因为子对象内部的键顺序不影响 * 递归处理嵌套对象(如 配置部分.2 内的键顺序),确保所有层级都按模板排列。
* 功能——只有顶层键顺序影响用户阅读。
* *
* @param target 已补入缺失键的对象(会被重建) * @param target 已补入缺失键的对象(会被重建)
* @param tpl 模板对象(提供键顺序) * @param tpl 模板对象(提供键顺序)
@@ -1750,6 +1749,10 @@ public class ConfigManager {
if (k.startsWith("#")) continue; if (k.startsWith("#")) continue;
com.google.gson.JsonElement have = target.get(k); com.google.gson.JsonElement have = target.get(k);
if (have != null) { if (have != null) {
// 递归重排嵌套对象
if (have.isJsonObject() && en.getValue().isJsonObject()) {
reorderToTemplateOrder(have.getAsJsonObject(), en.getValue().getAsJsonObject());
}
reordered.add(k, have); reordered.add(k, have);
} }
} }
@@ -1757,6 +1760,10 @@ public class ConfigManager {
for (Map.Entry<String, com.google.gson.JsonElement> en : target.entrySet()) { for (Map.Entry<String, com.google.gson.JsonElement> en : target.entrySet()) {
String k = en.getKey(); String k = en.getKey();
if (!reordered.has(k)) { if (!reordered.has(k)) {
// 递归重排嵌套对象
if (en.getValue().isJsonObject()) {
reorderToTemplateOrder(en.getValue().getAsJsonObject(), new com.google.gson.JsonObject());
}
reordered.add(k, en.getValue()); reordered.add(k, en.getValue());
} }
} }
+56 -7
View File
@@ -1,9 +1,58 @@
[
{ {
"对话留档":{ "提问开始": {
"怎么写":"键是提问,值是回答", "1. 互动人": "",
"谁来写":"每次提问/控场自动写", "2. 内容": "",
"请求失败":"响应原文落盘" "3. 输出": "",
}, "4. 提问时间": "",
"问":"答", "请求模型信息": {
"自动":"答" "模型名字": "",
"供应商": "",
"状态码":200
} }
}
},
[
"每次疑问都是一段顶层json块",
"按格式一层层展开,方便事后跟踪模型输出情况",
"互动人是玩家名字,如果是自动抛题带动玩家互动,则互动人写system",
"每次请求留痕,方便跟踪请求的模型信息",
"状态码、错误信息一扫便知"
],
{
"示范1": {
"1. 互动人": "system",
"2. 内容": "系统提示词+玩家聊天内容",
"3. 输出": "今天你有在草原上,发现哪些不一样的变化呢,一起说说看",
"请求模型信息": {
"供应商名字": "自定义",
"请求地址": "https://example.com/v1",
"状态码": 200
}
}
},
{
"示范2": {
"1. 互动人": "system",
"2. 内容": "系统提示词+玩家聊天内容",
"3. 输出": "今天你有在草原上,发现哪些不一样的变化呢,一起说说看",
"请求模型信息": {
"供应商名字": "非国产/oc/zen",
"状态码": 403,
"错误信息": "{\"type\":\"error\",\"error\":{\"type\":\"FreeTierError\",\"message\":\"Error from provider (Console): OpenCode's free tier can only be used from within OpenCode\"}}"
}
}
},
{
"示范3": {
"1. 互动人": "system",
"2. 内容": "系统提示词+玩家聊天内容",
"3. 输出": "今天你有在草原上,发现哪些不一样的变化呢,一起说说看",
"请求模型信息": {
"供应商名字": "非国产/oc/zen",
"状态码": 429,
"错误信息": "HTTP 429: [429]: {\"type\":\"error\",\"error\":{\"type\":\"FreeUsageLimitError\",\"message\":\"Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go\"}}"
}
}
}
]