From 4e2534a8c484236ff6d56f18186e91704cb26cc5 Mon Sep 17 00:00:00 2001 From: SanaeFox <36219542+Hoshinonyaruko@users.noreply.github.com> Date: Thu, 6 Jun 2024 14:43:54 +0800 Subject: [PATCH] Beta138 (#137) * beta1 * beta2 * beta3 * beta4 * beta5 * beta6 * beta7 * beta8 * beta9 * beta10 * beta11 * beta12 * beta13 * beta14 * beta15 * beta16 * beta16 * beta19 * beta20 * beta21 * beta22 * beta23 * beta24 * beta25 * beta27 * beta28 * beta29 * beta30 * beta31 * beta33 * beta34 * beta35 * beta36 * beta37 * beta38 * beta39 * beta40 * beta41 * beta42 * beta43 * beta44 * beta45 * beta45 * beta46 * beat48 * beta49 * beta50 * beta51 * beta52 * beta53 * beta54 * beta55 * beta57 * beta58 * beta59 * beta61 * beta62 * beta63 * beta63 * beta64 * beta65 * beta66 * beta67 * beta70 * beta71 * beta72 * beta72 * beta74 * beta75 * beta76 * beta77 * beta78 * beta79 * beta80 * beta81 * beta82 * beta83 * beta85 * beta86 * beta87 * beta88 * beta89 * beta90 * beta91 * beta92 * beta93 * beta94 * beta94 * beta96 * beta97 * beta98 * beta99 * beta100 * beta101 * beta102 * beta104 * beta105 * beta106 * beta107 * beta108 * beta109 * beta110 * beta111 * beta112 * beta113 * beta115 * beta116 * beta117 * beta118 * beta119 * beta120 * beta121 * beta122 * beta123 * beta124 * beta125 * beta126 * beta127 * beta128 * beta129 * beta130 * beta131 * beta132 * beta1333 * beta134 * beta135 * beta136 * beta137 * beta138 --- applogic/env.go | 2 +- applogic/flow.go | 16 ++-- applogic/gensokyo.go | 72 +++++++++-------- applogic/memory.go | 46 +++++------ applogic/vectorsensitive.go | 8 +- config/config.go | 151 +++++++++++++++++++----------------- structs/struct.go | 48 +++++++----- template/config_template.go | 6 ++ utils/blacklist.go | 14 ++-- utils/utils.go | 104 +++++++++++++++++++------ 10 files changed, 272 insertions(+), 195 deletions(-) diff --git a/applogic/env.go b/applogic/env.go index 065e124..2bf57a6 100644 --- a/applogic/env.go +++ b/applogic/env.go @@ -105,7 +105,7 @@ func (app *App) GetAndSendEnv(msg string, promptstr string, message structs.Oneb if message.RealMessageType == "group_private" || message.MessageType == "private" { utils.SendPrivateMessageRaw(message.UserID, newResponse, selfid) } else { - utils.SendGroupMessage(message.GroupID, message.UserID, newResponse, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, newResponse, selfid, promptstr) } } diff --git a/applogic/flow.go b/applogic/flow.go index 605ff7b..99a5d05 100644 --- a/applogic/flow.go +++ b/applogic/flow.go @@ -404,7 +404,7 @@ func (app *App) ProcessExitChoicesQ(promptstr string, requestmsg *string, messag } } if bestMatchCount > 0 { - app.HandleExit(bestText, message, selfid) + app.HandleExit(bestText, message, selfid, promptstr) return } } @@ -422,7 +422,7 @@ func (app *App) ProcessExitChoicesQ(promptstr string, requestmsg *string, messag texts := strings.Split(addedTexts, "-") if len(texts) > 0 { selectedText := texts[rand.Intn(len(texts))] - app.HandleExit(selectedText, message, selfid) + app.HandleExit(selectedText, message, selfid, promptstr) return } } @@ -431,7 +431,7 @@ func (app *App) ProcessExitChoicesQ(promptstr string, requestmsg *string, messag } // HandleExit 处理用户退出逻辑,包括发送消息和重置用户状态。 -func (app *App) HandleExit(exitText string, message *structs.OnebotGroupMessage, selfid string) { +func (app *App) HandleExit(exitText string, message *structs.OnebotGroupMessage, selfid string, promptstr string) { userid := message.UserID if config.GetGroupContext() && message.MessageType != "private" { userid = message.GroupID @@ -442,12 +442,12 @@ func (app *App) HandleExit(exitText string, message *structs.OnebotGroupMessage, RestoreResponse := config.GetRandomRestoreResponses() if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(message.UserID, RestoreResponse, selfid) + utils.SendPrivateMessage(message.UserID, RestoreResponse, selfid, promptstr) } else { - utils.SendSSEPrivateRestoreMessage(message.UserID, RestoreResponse) + utils.SendSSEPrivateRestoreMessage(message.UserID, RestoreResponse, promptstr) } } else { - utils.SendGroupMessage(message.GroupID, message.UserID, RestoreResponse, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, RestoreResponse, selfid, promptstr) } app.deleteCustomRecord(userid) } @@ -508,7 +508,7 @@ func (app *App) ProcessExitChoicesA(promptstr string, response *string, message } } if bestMatchCount > 0 { - app.HandleExit(bestText, message, selfid) + app.HandleExit(bestText, message, selfid, promptstr) return } } @@ -526,7 +526,7 @@ func (app *App) ProcessExitChoicesA(promptstr string, response *string, message texts := strings.Split(addedTexts, "-") if len(texts) > 0 { selectedText := texts[rand.Intn(len(texts))] - app.HandleExit(selectedText, message, selfid) + app.HandleExit(selectedText, message, selfid, promptstr) return } } diff --git a/applogic/gensokyo.go b/applogic/gensokyo.go index 6e88ed7..cd5bd86 100644 --- a/applogic/gensokyo.go +++ b/applogic/gensokyo.go @@ -339,7 +339,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { } } - if utils.BlacklistIntercept(message, selfid) { + if utils.BlacklistIntercept(message, selfid, promptstr) { fmtf.Printf("userid:[%v]groupid:[%v]这位用户或群在黑名单中,被拦截", message.UserID, message.GroupID) return } @@ -355,12 +355,12 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { RestoreResponse := config.GetRandomRestoreResponses() if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(message.UserID, RestoreResponse, selfid) + utils.SendPrivateMessage(message.UserID, RestoreResponse, selfid, promptstr) } else { - utils.SendSSEPrivateRestoreMessage(message.UserID, RestoreResponse) + utils.SendSSEPrivateRestoreMessage(message.UserID, RestoreResponse, promptstr) } } else { - utils.SendGroupMessage(message.GroupID, message.UserID, RestoreResponse, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, RestoreResponse, selfid, promptstr) } // 处理故事情节的重置 if config.GetGroupContext() && message.MessageType != "private" { @@ -402,7 +402,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 进行字数拦截 if config.GetQuestionMaxLenth() != 0 { - if utils.LengthIntercept(newmsg, message, selfid) { + if utils.LengthIntercept(newmsg, message, selfid, promptstr) { fmtf.Printf("字数过长,可在questionMaxLenth配置项修改,Q: %v", newmsg) // 发送响应 w.WriteHeader(http.StatusOK) @@ -413,7 +413,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 进行语言判断拦截 skipLangCheck为false时 if len(config.GetAllowedLanguages()) > 0 && !skipLangCheck { - if utils.LanguageIntercept(newmsg, message, selfid) { + if utils.LanguageIntercept(newmsg, message, selfid, promptstr) { fmtf.Printf("不安全!不支持的语言,可在config.yml设置允许的语言,allowedLanguages配置项,Q: %v", newmsg) // 发送响应 w.WriteHeader(http.StatusOK) @@ -440,7 +440,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 向量安全词部分,机器人向量安全屏障 if config.GetVectorSensitiveFilter() { - ret, retstr, err := app.InterceptSensitiveContent(vector, message, selfid) + ret, retstr, err := app.InterceptSensitiveContent(vector, message, selfid, promptstr) if err != nil { fmtf.Printf("Error in InterceptSensitiveContent: %v", err) // 发送响应 @@ -490,12 +490,12 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 发送响应消息 if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(message.UserID, responseText, selfid) + utils.SendPrivateMessage(message.UserID, responseText, selfid, promptstr) } else { - utils.SendSSEPrivateMessage(message.UserID, responseText) + utils.SendSSEPrivateMessage(message.UserID, responseText, promptstr) } } else { - utils.SendGroupMessage(message.GroupID, message.UserID, responseText, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, responseText, selfid, promptstr) } // 发送响应 w.WriteHeader(http.StatusOK) @@ -535,12 +535,12 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { if saveresponse != "" { if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(message.UserID, saveresponse, selfid) + utils.SendPrivateMessage(message.UserID, saveresponse, selfid, promptstr) } else { - utils.SendSSEPrivateSafeMessage(message.UserID, saveresponse) + utils.SendSSEPrivateSafeMessage(message.UserID, saveresponse, promptstr) } } else { - utils.SendGroupMessage(message.GroupID, message.UserID, saveresponse, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, saveresponse, selfid, promptstr) } } // 发送响应 @@ -575,7 +575,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 处理保存记忆 if ismemoryCommand { - app.handleSaveMemory(message, conversationID, parentMessageID) // 适配群 + app.handleSaveMemory(message, conversationID, parentMessageID, promptstr) // 适配群 return } @@ -597,13 +597,13 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 处理记忆列表 if ismemoryLoadCommand { - app.handleMemoryList(message) // 适配群 + app.handleMemoryList(message, promptstr) // 适配群 return } // 新增处理载入记忆的逻辑 if isPrefixedMemoryLoadCommand { - app.handleLoadMemory(message, checkResetCommand) // 适配群 + app.handleLoadMemory(message, checkResetCommand, promptstr) // 适配群 return } @@ -621,7 +621,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 处理新对话 if isnewConversationCommand { - app.handleNewConversation(message, conversationID, parentMessageID) // 适配群 + app.handleNewConversation(message, conversationID, parentMessageID, promptstr) // 适配群 return } @@ -686,6 +686,10 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { PromptMarksLength := config.GetPromptMarksLength(promptstr) app.GetAndSendEnv(requestmsg, promptstr, message, selfid, CustomRecord.PromptStrStat, PromptMarksLength) } + + // 按提示词区分的细化替换 这里主要不是为了安全和敏感词,而是细化效果,也就没有使用acnode提高效率 + requestmsg = utils.ReplaceTextIn(requestmsg, promptstr) + if config.GetGroupContext() && message.MessageType != "private" { fmtf.Printf("实际请求conversation端点内容:[%v]%v\n", message.GroupID, requestmsg) } else { @@ -817,7 +821,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { // 判断消息类型,如果是私人消息或私有群消息,发送私人消息;否则,根据配置决定是否发送群消息 if userinfo.RealMessageType == "group_private" || userinfo.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(userinfo.UserID, newPart, selfid) + utils.SendPrivateMessage(userinfo.UserID, newPart, selfid, promptstr) } else { //判断是否最后一条 var state int @@ -830,16 +834,16 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { Content: newPart, State: state, } - utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE) + utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE, promptstr) } } else { // 这里发送的是newPart api最后补充的部分 if !config.GetMdPromptKeyboardAtGroup() { // 如果没有 EnhancedAContent if EnhancedAContent == "" { - utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, newPart, selfid) + utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, newPart, selfid, promptstr) } else { - utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, newPart+EnhancedAContent, selfid) + utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, newPart+EnhancedAContent, selfid, promptstr) } } else { // 如果没有 EnhancedAContent @@ -864,9 +868,9 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { if !config.GetUsePrivateSSE() { // 如果没有 EnhancedAContent if EnhancedAContent == "" { - utils.SendPrivateMessage(userinfo.UserID, response, selfid) + utils.SendPrivateMessage(userinfo.UserID, response, selfid, promptstr) } else { - utils.SendPrivateMessage(userinfo.UserID, response+EnhancedAContent, selfid) + utils.SendPrivateMessage(userinfo.UserID, response+EnhancedAContent, selfid, promptstr) } } else { //判断是否最后一条 @@ -880,15 +884,15 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { Content: response, State: state, } - utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE) + utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE, promptstr) } } else { if !config.GetMdPromptKeyboardAtGroup() { // 如果没有 EnhancedAContent if EnhancedAContent == "" { - utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, response, selfid) + utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, response, selfid, promptstr) } else { - utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, response+EnhancedAContent, selfid) + utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, response+EnhancedAContent, selfid, promptstr) } } else { // 如果没有 EnhancedAContent @@ -936,7 +940,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { Content: EnhancedAContent, State: 11, } - utils.SendPrivateMessageSSE(message.UserID, messageSSE) + utils.SendPrivateMessageSSE(message.UserID, messageSSE, promptstr) } } } @@ -1015,7 +1019,7 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { State: 20, PromptKeyboard: promptkeyboard, } - utils.SendPrivateMessageSSE(message.UserID, messageSSE) + utils.SendPrivateMessageSSE(message.UserID, messageSSE, promptstr) ResetIndex(newmsg) } } @@ -1041,9 +1045,9 @@ func (app *App) GensokyoHandler(w http.ResponseWriter, r *http.Request) { if response, ok = responseData["response"].(string); ok && response != "" { // 判断消息类型,如果是私人消息或私有群消息,发送私人消息;否则,根据配置决定是否发送群消息 if message.RealMessageType == "group_private" || message.MessageType == "private" { - utils.SendPrivateMessage(message.UserID, response, selfid) + utils.SendPrivateMessage(message.UserID, response, selfid, promptstr) } else { - utils.SendGroupMessage(message.GroupID, message.UserID, response, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, response, selfid, promptstr) } } @@ -1157,7 +1161,7 @@ func processMessage(response string, conversationid string, newmesssage string, // 判断消息类型,如果是私人消息或私有群消息,发送私人消息;否则,根据配置决定是否发送群消息 if userinfo.RealMessageType == "group_private" || userinfo.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(userinfo.UserID, accumulatedMessage, selfid) + utils.SendPrivateMessage(userinfo.UserID, accumulatedMessage, selfid, promptstr) } else { if IncrementIndex(newmesssage) == 1 { //第一条信息 @@ -1170,18 +1174,18 @@ func processMessage(response string, conversationid string, newmesssage string, ActionButton: 10, CallbackData: uerid, } - utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE) + utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE, promptstr) } else { //SSE的前半部分 messageSSE := structs.InterfaceBody{ Content: accumulatedMessage, State: 1, } - utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE) + utils.SendPrivateMessageSSE(userinfo.UserID, messageSSE, promptstr) } } } else { - utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, accumulatedMessage, selfid) + utils.SendGroupMessage(userinfo.GroupID, userinfo.UserID, accumulatedMessage, selfid, promptstr) } ClearMessage(conversationid) diff --git a/applogic/memory.go b/applogic/memory.go index ce6ece5..832f965 100644 --- a/applogic/memory.go +++ b/applogic/memory.go @@ -81,7 +81,7 @@ func GetMemoryTitle(msg string) string { } // 保存记忆 -func (app *App) handleSaveMemory(msg structs.OnebotGroupMessage, ConversationID string, ParentMessageID string) { +func (app *App) handleSaveMemory(msg structs.OnebotGroupMessage, ConversationID string, ParentMessageID string, promptstr string) { conversationTitle := "2024-5-19/18:26" // 默认标题,根据实际需求可能需要调整为动态生成的时间戳 userid := msg.UserID @@ -124,11 +124,11 @@ func (app *App) handleSaveMemory(msg structs.OnebotGroupMessage, ConversationID // 发送保存成功的响应 saveMemoryResponse := "记忆保存成功!" - app.sendMemoryResponseWithkeyBoard(msg, saveMemoryResponse, keyboard) + app.sendMemoryResponseWithkeyBoard(msg, saveMemoryResponse, keyboard, promptstr) } // 获取记忆列表 -func (app *App) handleMemoryList(msg structs.OnebotGroupMessage) { +func (app *App) handleMemoryList(msg structs.OnebotGroupMessage, promptstr string) { userid := msg.UserID if config.GetGroupContext() && msg.MessageType != "private" { @@ -172,11 +172,11 @@ func (app *App) handleMemoryList(msg structs.OnebotGroupMessage) { responseBuilder.WriteString(fmt.Sprintf("提示:发送 %s 任意标题开头的前n字即可载入记忆\n如:%s %s", loadMemoryCommand, loadMemoryCommand, exampleTitle)) // 发送组合后的信息,包括键盘数组 - app.sendMemoryResponseByline(msg, responseBuilder.String(), keyboard) + app.sendMemoryResponseByline(msg, responseBuilder.String(), keyboard, promptstr) } // 载入记忆 -func (app *App) handleLoadMemory(msg structs.OnebotGroupMessage, checkResetCommand string) { +func (app *App) handleLoadMemory(msg structs.OnebotGroupMessage, checkResetCommand string, promptstr string) { userid := msg.UserID if config.GetGroupContext() && msg.MessageType != "private" { @@ -198,7 +198,7 @@ func (app *App) handleLoadMemory(msg structs.OnebotGroupMessage, checkResetComma memories, err := app.GetUserMemories(userid) if err != nil { log.Printf("Error retrieving memories: %s", err) - app.sendMemoryResponse(msg, "获取记忆失败") + app.sendMemoryResponse(msg, "获取记忆失败", promptstr) return } @@ -212,7 +212,7 @@ func (app *App) handleLoadMemory(msg structs.OnebotGroupMessage, checkResetComma } if matchedMemory == nil { - app.sendMemoryResponse(msg, "未找到匹配的记忆") + app.sendMemoryResponse(msg, "未找到匹配的记忆", promptstr) return } @@ -220,51 +220,51 @@ func (app *App) handleLoadMemory(msg structs.OnebotGroupMessage, checkResetComma err = app.updateUserContextPro(userid, matchedMemory.ConversationID, matchedMemory.ParentMessageID) if err != nil { log.Printf("Error adding memory: %s", err) - app.sendMemoryResponse(msg, "载入记忆失败") + app.sendMemoryResponse(msg, "载入记忆失败", promptstr) return } // 组合回复信息 responseMessage := fmt.Sprintf("成功载入了标题为 '%s' 的记忆", matchedMemory.ConversationTitle) - app.sendMemoryResponse(msg, responseMessage) + app.sendMemoryResponse(msg, responseMessage, promptstr) } -func (app *App) sendMemoryResponseWithkeyBoard(msg structs.OnebotGroupMessage, response string, keyboard []string) { +func (app *App) sendMemoryResponseWithkeyBoard(msg structs.OnebotGroupMessage, response string, keyboard []string, promptstr string) { strSelfID := strconv.FormatInt(msg.SelfID, 10) if msg.RealMessageType == "group_private" || msg.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(msg.UserID, response, strSelfID) + utils.SendPrivateMessage(msg.UserID, response, strSelfID, promptstr) } else { - utils.SendSSEPrivateMessageWithKeyboard(msg.UserID, response, keyboard) + utils.SendSSEPrivateMessageWithKeyboard(msg.UserID, response, keyboard, promptstr) } } else { - utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID) + utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID, promptstr) } } -func (app *App) sendMemoryResponse(msg structs.OnebotGroupMessage, response string) { +func (app *App) sendMemoryResponse(msg structs.OnebotGroupMessage, response string, promptstr string) { strSelfID := strconv.FormatInt(msg.SelfID, 10) if msg.RealMessageType == "group_private" || msg.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(msg.UserID, response, strSelfID) + utils.SendPrivateMessage(msg.UserID, response, strSelfID, promptstr) } else { - utils.SendSSEPrivateMessage(msg.UserID, response) + utils.SendSSEPrivateMessage(msg.UserID, response, promptstr) } } else { - utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID) + utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID, promptstr) } } -func (app *App) sendMemoryResponseByline(msg structs.OnebotGroupMessage, response string, keyboard []string) { +func (app *App) sendMemoryResponseByline(msg structs.OnebotGroupMessage, response string, keyboard []string, promptstr string) { strSelfID := strconv.FormatInt(msg.SelfID, 10) if msg.RealMessageType == "group_private" || msg.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(msg.UserID, response, strSelfID) + utils.SendPrivateMessage(msg.UserID, response, strSelfID, promptstr) } else { - utils.SendSSEPrivateMessageByLine(msg.UserID, response, keyboard) + utils.SendSSEPrivateMessageByLine(msg.UserID, response, keyboard, promptstr) } } else { - utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID) + utils.SendGroupMessage(msg.GroupID, msg.UserID, response, strSelfID, promptstr) } } @@ -280,7 +280,7 @@ func formatHistory(history []structs.Message) string { return result } -func (app *App) handleNewConversation(msg structs.OnebotGroupMessage, conversationID string, parentMessageID string) { +func (app *App) handleNewConversation(msg structs.OnebotGroupMessage, conversationID string, parentMessageID string, promotstr string) { // 使用预定义的时间戳作为会话标题 conversationTitle := "2024-5-19/18:26" // 实际应用中应使用动态生成的时间戳 userid := msg.UserID @@ -323,6 +323,6 @@ func (app *App) handleNewConversation(msg structs.OnebotGroupMessage, conversati if len(loadCommand) > 0 { loadMemoryCommand := loadCommand[0] // 使用数组中的第一个指令 saveMemoryResponse := fmt.Sprintf("旧的对话已经保存,可发送 %s 来查看,可以开始新的对话了!", loadMemoryCommand) - app.sendMemoryResponse(msg, saveMemoryResponse) + app.sendMemoryResponse(msg, saveMemoryResponse, promotstr) } } diff --git a/applogic/vectorsensitive.go b/applogic/vectorsensitive.go index e5dc922..090abdc 100644 --- a/applogic/vectorsensitive.go +++ b/applogic/vectorsensitive.go @@ -258,7 +258,7 @@ func (app *App) textExistsInDatabase(text string) (bool, error) { return exists, nil } -func (app *App) InterceptSensitiveContent(vector []float64, message structs.OnebotGroupMessage, selfid string) (int, string, error) { +func (app *App) InterceptSensitiveContent(vector []float64, message structs.OnebotGroupMessage, selfid string, promptstr string) (int, string, error) { // 自定义阈值 Threshold := config.GetVertorSensitiveThreshold() @@ -283,12 +283,12 @@ func (app *App) InterceptSensitiveContent(vector []float64, message structs.Oneb if saveresponse != "" { if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - utils.SendPrivateMessage(message.UserID, saveresponse, selfid) + utils.SendPrivateMessage(message.UserID, saveresponse, selfid, promptstr) } else { - utils.SendSSEPrivateSafeMessage(message.UserID, saveresponse) + utils.SendSSEPrivateSafeMessage(message.UserID, saveresponse, promptstr) } } else { - utils.SendGroupMessage(message.GroupID, message.UserID, saveresponse, selfid) + utils.SendGroupMessage(message.GroupID, message.UserID, saveresponse, selfid, promptstr) } return 1, saveresponse, nil } diff --git a/config/config.go b/config/config.go index f91c204..5da50f7 100644 --- a/config/config.go +++ b/config/config.go @@ -3015,76 +3015,6 @@ func getTemperatureHunyuanInternal(options ...string) float64 { return value } -// // 获取助手ID -// func GetYuanqiAssistantID(options ...string) string { -// mu.Lock() -// defer mu.Unlock() -// return getYuanqiAssistantIDInternal(options...) -// } - -// func getYuanqiAssistantIDInternal(options ...string) string { -// if len(options) == 0 || options[0] == "" { -// if instance != nil { -// return instance.Settings.YuanqiAssistantID -// } -// return "" // 默认值或错误处理 -// } - -// basename := options[0] -// assistantIDInterface, err := prompt.GetSettingFromFilename(basename, "YuanqiAssistantID") -// if err != nil { -// log.Println("Error retrieving YuanqiAssistantID:", err) -// return getYuanqiAssistantIDInternal() // 递归调用内部函数,不传递任何参数 -// } - -// assistantID, ok := assistantIDInterface.(string) -// if !ok { // 检查类型断言是否失败 -// log.Println("Type assertion failed for YuanqiAssistantID, fetching default") -// return getYuanqiAssistantIDInternal() // 递归调用内部函数,不传递任何参数 -// } - -// if assistantID == "" { -// return getYuanqiAssistantIDInternal() // 递归调用内部函数,不传递任何参数 -// } - -// return assistantID -// } - -// // 获取Token -// func GetYuanqiToken(options ...string) string { -// mu.Lock() -// defer mu.Unlock() -// return getYuanqiTokenInternal(options...) -// } - -// func getYuanqiTokenInternal(options ...string) string { -// if len(options) == 0 || options[0] == "" { -// if instance != nil { -// return instance.Settings.YuanqiToken -// } -// return "" // 默认值或错误处理 -// } - -// basename := options[0] -// YuanqiTokenInterface, err := prompt.GetSettingFromFilename(basename, "YuanqiToken") -// if err != nil { -// log.Println("Error retrieving YuanqiToken:", err) -// return getYuanqiTokenInternal() // 递归调用内部函数,不传递任何参数 -// } - -// YuanqiToken, ok := YuanqiTokenInterface.(string) -// if !ok { // 检查类型断言是否失败 -// log.Println("Type assertion failed for YuanqiToken, fetching default") -// return getYuanqiTokenInternal() // 递归调用内部函数,不传递任何参数 -// } - -// if YuanqiToken == "" { -// return getYuanqiTokenInternal() // 递归调用内部函数,不传递任何参数 -// } - -// return YuanqiToken -// } - // GetYuanqiConf return conf.YuanqiAssistantID, conf.YuanqiToken func GetYuanqiConf(options ...string) (string, string) { mu.Lock() @@ -3102,9 +3032,6 @@ func getYuanqiConfInternal(options ...string) (string, string) { conf := instance.Settings.Yuanqiconfs[index] return conf.YuanqiAssistantID, conf.YuanqiToken } - } else { - log.Println("No configurations available in instance or default behavior") - return "", "" // 默认值或错误处理 } // 使用prompt包从指定的文件名中获取配置 @@ -3133,6 +3060,84 @@ func getYuanqiConfInternal(options ...string) (string, string) { return conf.YuanqiAssistantID, conf.YuanqiToken } +// 获取 ReplacementPairsIn +func GetReplacementPairsIn(options ...string) []structs.ReplacementPair { + mu.Lock() + defer mu.Unlock() + return getReplacementPairsInInternal(options...) +} + +// getReplacementPairsInInternal 内部递归函数,处理配置获取逻辑 +func getReplacementPairsInInternal(options ...string) []structs.ReplacementPair { + // 从instance中读取配置数组 + if instance != nil && len(instance.Settings.ReplacementPairsIn) > 0 { + if len(options) == 0 || options[0] == "" { + return instance.Settings.ReplacementPairsIn + } + } + + // 使用prompt包从指定的文件名中获取配置 + basename := options[0] + confInterface, err := prompt.GetSettingFromFilename(basename, "ReplacementPairsIn") + if err != nil { + log.Printf("Error retrieving settings from file: %s, error: %v", basename, err) + return getReplacementPairsInInternal() // 递归调用内部函数,不传递任何参数 + } + + // 断言获取的interface{}为[]ReplacementPair + confs, ok := confInterface.([]structs.ReplacementPair) + if !ok { + log.Println("Type assertion failed for ReplacementPair, attempting default behavior") + return getReplacementPairsInInternal() // 递归调用内部函数,尝试默认配置 + } + + if len(confs) == 0 { + log.Println("No configurations found in file:", basename) + return getReplacementPairsInInternal() // 递归调用内部函数,尝试默认配置 + } + + return confs +} + +// 获取 ReplacementPairsOut +func GetReplacementPairsOut(options ...string) []structs.ReplacementPair { + mu.Lock() + defer mu.Unlock() + return getReplacementPairsOutInternal(options...) +} + +// getReplacementPairsInOutternal 内部递归函数,处理配置获取逻辑 +func getReplacementPairsOutInternal(options ...string) []structs.ReplacementPair { + // 从instance中读取配置数组 + if instance != nil && len(instance.Settings.ReplacementPairsOut) > 0 { + if len(options) == 0 || options[0] == "" { + return instance.Settings.ReplacementPairsOut + } + } + + // 使用prompt包从指定的文件名中获取配置 + basename := options[0] + confInterface, err := prompt.GetSettingFromFilename(basename, "ReplacementPairsOut") + if err != nil { + log.Printf("Error retrieving settings from file: %s, error: %v", basename, err) + return getReplacementPairsOutInternal() // 递归调用内部函数,不传递任何参数 + } + + // 断言获取的interface{}为[]ReplacementPair + confs, ok := confInterface.([]structs.ReplacementPair) + if !ok { + log.Println("Type assertion failed for ReplacementPair, attempting default behavior") + return getReplacementPairsOutInternal() // 递归调用内部函数,尝试默认配置 + } + + if len(confs) == 0 { + log.Println("No configurations found in file:", basename) + return getReplacementPairsOutInternal() // 递归调用内部函数,尝试默认配置 + } + + return confs +} + // 获取助手版本 func GetYuanqiVersion(options ...string) float64 { mu.Lock() diff --git a/structs/struct.go b/structs/struct.go index 41cfa19..4b3514c 100644 --- a/structs/struct.go +++ b/structs/struct.go @@ -245,27 +245,35 @@ type WXFunctionCall struct { Thought string `json:"thought,omitempty"` } +// ReplacementPair 表示一对替换词,其中包含原始词和目标替换词。 +type ReplacementPair struct { + OriginalWord string `yaml:"originalWord"` + TargetWord string `yaml:"targetWord"` +} + type Settings struct { - AllApi bool `yaml:"allApi"` - SecretId string `yaml:"secretId"` - SecretKey string `yaml:"secretKey"` - Region string `yaml:"region"` - UseSse bool `yaml:"useSse"` - Port int `yaml:"port"` - SelfPath string `yaml:"selfPath"` - HttpPath string `yaml:"path"` - HttpPaths []string `yaml:"paths"` - Lotus string `yaml:"lotus"` - PathToken string `yaml:"pathToken"` - SystemPrompt []string `yaml:"systemPrompt"` - IPWhiteList []string `yaml:"iPWhiteList"` - ApiType int `yaml:"apiType"` - Proxy string `yaml:"proxy"` - UrlSendPics bool `yaml:"urlSendPics"` // 自己构造图床加速图片发送 - MdPromptKeyboardAtGroup bool `yaml:"mdPromptKeyboardAtGroup"` // 群内使用md能力模拟PromptKeyboard - GroupHintWords []string `yaml:"groupHintWords"` - GroupHintChance int `yaml:"groupHintChance"` - GroupContext bool `yaml:"groupContext"` + AllApi bool `yaml:"allApi"` + SecretId string `yaml:"secretId"` + SecretKey string `yaml:"secretKey"` + Region string `yaml:"region"` + UseSse bool `yaml:"useSse"` + Port int `yaml:"port"` + SelfPath string `yaml:"selfPath"` + HttpPath string `yaml:"path"` + HttpPaths []string `yaml:"paths"` + Lotus string `yaml:"lotus"` + PathToken string `yaml:"pathToken"` + SystemPrompt []string `yaml:"systemPrompt"` + IPWhiteList []string `yaml:"iPWhiteList"` + ApiType int `yaml:"apiType"` + Proxy string `yaml:"proxy"` + UrlSendPics bool `yaml:"urlSendPics"` // 自己构造图床加速图片发送 + MdPromptKeyboardAtGroup bool `yaml:"mdPromptKeyboardAtGroup"` // 群内使用md能力模拟PromptKeyboard + GroupHintWords []string `yaml:"groupHintWords"` + GroupHintChance int `yaml:"groupHintChance"` + GroupContext bool `yaml:"groupContext"` + ReplacementPairsIn []ReplacementPair `yaml:"replacementPairsIn"` + ReplacementPairsOut []ReplacementPair `yaml:"replacementPairsOut"` HunyuanType int `yaml:"hunyuanType"` MaxTokensHunyuan int `yaml:"maxTokensHunyuan"` diff --git a/template/config_template.go b/template/config_template.go index 08ade01..2a1d2d2 100644 --- a/template/config_template.go +++ b/template/config_template.go @@ -51,6 +51,12 @@ settings: groupHintWords : [] #当机器人位于群内时,需满足包含groupHintWords数组任意内容如[CQ:at,qq=2] 机器人的名字 等 groupHintChance : 0 #需与groupHintWords联用,代表不满足hintwords时概率触发,不启用groupHintWords相当于百分百概率回复. groupContext : false #群上下文 在智能体在群内时,以群为单位处理上下文. + replacementPairsIn: #每个不同的yml文件,都可以有自己独立的替换词规则,IN OUT分离 + - originalWord: "hello" + targetWord: "hi" + replacementPairsOut: #每个不同的yml文件,都可以有自己独立的替换词规则,IN OUT分离 + - originalWord: "hello" + targetWord: "hi" #Ws服务器配置 wsServerToken : "" #ws密钥 可以由onebotv11反向ws接入 diff --git a/utils/blacklist.go b/utils/blacklist.go index 77b1aea..f8eaf70 100644 --- a/utils/blacklist.go +++ b/utils/blacklist.go @@ -93,7 +93,7 @@ func WatchBlacklist(filePath string) { } // BlacklistIntercept 检查用户ID是否在黑名单中,如果在,则发送预设消息 -func BlacklistIntercept(message structs.OnebotGroupMessage, selfid string) bool { +func BlacklistIntercept(message structs.OnebotGroupMessage, selfid string, promptstr string) bool { // 检查群ID是否在黑名单中 if IsInBlacklist(strconv.FormatInt(message.GroupID, 10)) { // 获取黑名单响应消息 @@ -102,12 +102,12 @@ func BlacklistIntercept(message structs.OnebotGroupMessage, selfid string) bool // 根据消息类型发送响应 if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - SendPrivateMessage(message.UserID, responseMessage, selfid) + SendPrivateMessage(message.UserID, responseMessage, selfid, promptstr) } else { - SendSSEPrivateMessage(message.UserID, responseMessage) + SendSSEPrivateMessage(message.UserID, responseMessage, promptstr) } } else { - SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid) + SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid, promptstr) } fmt.Printf("groupid:[%v]这个群在黑名单中,被拦截\n", message.GroupID) @@ -122,12 +122,12 @@ func BlacklistIntercept(message structs.OnebotGroupMessage, selfid string) bool // 根据消息类型发送响应 if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - SendPrivateMessage(message.UserID, responseMessage, selfid) + SendPrivateMessage(message.UserID, responseMessage, selfid, promptstr) } else { - SendSSEPrivateMessage(message.UserID, responseMessage) + SendSSEPrivateMessage(message.UserID, responseMessage, promptstr) } } else { - SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid) + SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid, promptstr) } fmt.Printf("userid:[%v]这位用户在黑名单中,被拦截\n", message.UserID) diff --git a/utils/utils.go b/utils/utils.go index 8022efc..a3b8e1b 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -207,7 +207,7 @@ func ExtractEventDetails(eventData map[string]interface{}) (string, structs.Usag return responseTextBuilder.String(), totalUsage } -func SendGroupMessage(groupID int64, userID int64, message string, selfid string) error { +func SendGroupMessage(groupID int64, userID int64, message string, selfid string, promptstr string) error { //TODO: 用userid作为了echo,在ws收到回调信息的时候,加入到全局撤回数组,AddMessageID,实现撤回 if server.IsSelfIDExists(selfid) { // 创建消息结构体 @@ -254,6 +254,9 @@ func SendGroupMessage(groupID int64, userID int64, message string, selfid string message = acnode.CheckWordOUT(message) } + //精细化替换 每个yml配置文件都可以具有一个非全局的文本替换规则 + message = ReplaceTextOut(message, promptstr) + // 去除末尾的换行符 不去除会导致不好看 message = removeTrailingCRLFs(message) @@ -351,6 +354,9 @@ func SendGroupMessageMdPromptKeyboard(groupID int64, userID int64, message strin message = acnode.CheckWordOUT(message) } + //精细化替换 每个yml配置文件都可以具有一个非全局的文本替换规则 + message = ReplaceTextOut(message, promptstr) + // 去除末尾的换行符 不去除会导致不好看 message = removeTrailingCRLFs(message) @@ -548,7 +554,7 @@ func SendGroupMessageMdPromptKeyboard(groupID int64, userID int64, message strin return nil } -func SendPrivateMessage(UserID int64, message string, selfid string) error { +func SendPrivateMessage(UserID int64, message string, selfid string, promptstr string) error { if server.IsSelfIDExists(selfid) { // 创建消息结构体 msg := map[string]interface{}{ @@ -593,6 +599,9 @@ func SendPrivateMessage(UserID int64, message string, selfid string) error { message = acnode.CheckWordOUT(message) } + //精细化替换 每个yml配置文件都可以具有一个非全局的文本替换规则 + message = ReplaceTextOut(message, promptstr) + // 去除末尾的换行符 不去除会导致不好看 message = removeTrailingCRLFs(message) @@ -732,7 +741,7 @@ func SendPrivateMessageRaw(UserID int64, message string, selfid string) error { return nil } -func SendPrivateMessageSSE(UserID int64, message structs.InterfaceBody) error { +func SendPrivateMessageSSE(UserID int64, message structs.InterfaceBody, promptstr string) error { // 获取基础URL baseURL := config.GetHttpPath() // 假设config.GetHttpPath()返回基础URL @@ -764,6 +773,9 @@ func SendPrivateMessageSSE(UserID int64, message structs.InterfaceBody) error { message.Content = acnode.CheckWordOUT(message.Content) } + //精细化替换 每个yml配置文件都可以具有一个非全局的文本替换规则 + message.Content = ReplaceTextOut(message.Content, promptstr) + // 调试用的 if config.GetPrintHanming() { fmtf.Printf("流式信息替换后:%v", message.Content) @@ -943,7 +955,7 @@ func PostSensitiveMessages() error { } // SendSSEPrivateMessage 分割并发送消息的核心逻辑,直接遍历字符串 -func SendSSEPrivateMessage(userID int64, content string) { +func SendSSEPrivateMessage(userID int64, content string, promptstr string) { punctuations := []rune{'。', '!', '?', ',', ',', '.', '!', '?', '~'} splitProbability := config.GetSplitByPuntuations() @@ -995,12 +1007,12 @@ func SendSSEPrivateMessage(userID int64, content string) { } // 发送SSE消息函数 - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) } } // SendSSEPrivateMessageWithKeyboard 分割并发送消息的核心逻辑,直接遍历字符串 -func SendSSEPrivateMessageWithKeyboard(userID int64, content string, keyboard []string) { +func SendSSEPrivateMessageWithKeyboard(userID int64, content string, keyboard []string, promptstr string) { punctuations := []rune{'。', '!', '?', ',', ',', '.', '!', '?', '~'} splitProbability := config.GetSplitByPuntuations() @@ -1057,12 +1069,12 @@ func SendSSEPrivateMessageWithKeyboard(userID int64, content string, keyboard [] } // 发送SSE消息函数 - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) } } // SendSSEPrivateMessageByline 分割并发送消息的核心逻辑,直接遍历字符串 -func SendSSEPrivateMessageByLine(userID int64, content string, keyboard []string) { +func SendSSEPrivateMessageByLine(userID int64, content string, keyboard []string, promptstr string) { // 直接使用 strings.Split 按行分割字符串 parts := strings.Split(content, "\n") @@ -1105,12 +1117,12 @@ func SendSSEPrivateMessageByLine(userID int64, content string, keyboard []string } // 发送SSE消息函数 - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) } } // SendSSEPrivateSafeMessage 分割并发送安全消息的核心逻辑,直接遍历字符串 -func SendSSEPrivateSafeMessage(userID int64, saveresponse string) { +func SendSSEPrivateSafeMessage(userID int64, saveresponse string, promptstr string) { // 将字符串转换为rune切片,以正确处理多字节字符 runes := []rune(saveresponse) @@ -1137,14 +1149,14 @@ func SendSSEPrivateSafeMessage(userID int64, saveresponse string) { State: 1, } - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) // 中间 messageSSE = structs.InterfaceBody{ Content: parts[1], State: 11, } - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) // 从配置中获取恢复响应数组 RestoreResponses := config.GetRestoreCommand() @@ -1172,11 +1184,11 @@ func SendSSEPrivateSafeMessage(userID int64, saveresponse string) { } // 发送SSE私人消息 - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) } // SendSSEPrivateRestoreMessage 分割并发送重置消息的核心逻辑,直接遍历字符串 -func SendSSEPrivateRestoreMessage(userID int64, RestoreResponse string) { +func SendSSEPrivateRestoreMessage(userID int64, RestoreResponse string, promptstr string) { // 将字符串转换为rune切片,以正确处理多字节字符 runes := []rune(RestoreResponse) @@ -1204,14 +1216,14 @@ func SendSSEPrivateRestoreMessage(userID int64, RestoreResponse string) { State: 1, } - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) //中间 messageSSE = structs.InterfaceBody{ Content: parts[1], State: 11, } - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) // 从配置中获取promptkeyboard promptkeyboard := config.GetPromptkeyboard() @@ -1224,11 +1236,11 @@ func SendSSEPrivateRestoreMessage(userID int64, RestoreResponse string) { } // 发送SSE私人消息 - SendPrivateMessageSSE(userID, messageSSE) + SendPrivateMessageSSE(userID, messageSSE, promptstr) } // LanguageIntercept 检查文本语言,如果不在允许列表中,则返回 true 并发送消息 -func LanguageIntercept(text string, message structs.OnebotGroupMessage, selfid string) bool { +func LanguageIntercept(text string, message structs.OnebotGroupMessage, selfid string, promptstr string) bool { hintWords := config.GetGroupHintWords() // 遍历所有触发词,将其从文本中剔除 for _, word := range hintWords { @@ -1253,12 +1265,12 @@ func LanguageIntercept(text string, message structs.OnebotGroupMessage, selfid s // 发送响应消息 if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - SendPrivateMessage(message.UserID, responseMessage, selfid) + SendPrivateMessage(message.UserID, responseMessage, selfid, promptstr) } else { - SendSSEPrivateMessage(message.UserID, responseMessage) + SendSSEPrivateMessage(message.UserID, responseMessage, promptstr) } } else { - SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid) + SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid, promptstr) } return true // 拦截 @@ -1301,7 +1313,7 @@ func FriendlyLanguageNameCN(lang whatlanggo.Lang) string { } // LengthIntercept 检查文本长度,如果超过最大长度,则返回 true 并发送消息 -func LengthIntercept(text string, message structs.OnebotGroupMessage, selfid string) bool { +func LengthIntercept(text string, message structs.OnebotGroupMessage, selfid string, promptstr string) bool { maxLen := config.GetQuestionMaxLenth() if len(text) > maxLen { // 长度超出限制,获取并发送响应消息 @@ -1310,12 +1322,12 @@ func LengthIntercept(text string, message structs.OnebotGroupMessage, selfid str // 根据消息类型发送响应 if message.RealMessageType == "group_private" || message.MessageType == "private" { if !config.GetUsePrivateSSE() { - SendPrivateMessage(message.UserID, responseMessage, selfid) + SendPrivateMessage(message.UserID, responseMessage, selfid, promptstr) } else { - SendSSEPrivateMessage(message.UserID, responseMessage) + SendSSEPrivateMessage(message.UserID, responseMessage, promptstr) } } else { - SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid) + SendGroupMessage(message.GroupID, message.UserID, responseMessage, selfid, promptstr) } return true // 拦截 @@ -1486,3 +1498,45 @@ func MakeAlternating(messages []structs.MessageContent) []structs.MessageContent return correctedMessages } + +// ReplaceTextIn 使用给定的替换对列表对文本进行替换 +func ReplaceTextIn(text string, promptstr string) string { + // 调用 GetReplacementPairsIn 函数获取替换对列表 + replacementPairs := config.GetReplacementPairsIn(promptstr) + + fmt.Printf("测试测试:%+v,%v", replacementPairs, promptstr) + + if len(replacementPairs) == 0 { + return text + } + + // 遍历所有的替换对,并在文本中进行替换 + for _, pair := range replacementPairs { + // 使用 strings.Replace 替换文本中的所有出现 + // 注意这里我们使用 -1 作为最后的参数,表示替换文本中的所有匹配项 + text = strings.Replace(text, pair.OriginalWord, pair.TargetWord, -1) + } + + // 返回替换后的文本 + return text +} + +// ReplaceTextOut 使用给定的替换对列表对文本进行替换 +func ReplaceTextOut(text string, promptstr string) string { + // 调用 GetReplacementPairsIn 函数获取替换对列表 + replacementPairs := config.GetReplacementPairsOut(promptstr) + + if len(replacementPairs) == 0 { + return text + } + + // 遍历所有的替换对,并在文本中进行替换 + for _, pair := range replacementPairs { + // 使用 strings.Replace 替换文本中的所有出现 + // 注意这里我们使用 -1 作为最后的参数,表示替换文本中的所有匹配项 + text = strings.Replace(text, pair.OriginalWord, pair.TargetWord, -1) + } + + // 返回替换后的文本 + return text +}