chat.go 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  1. // Package controllers - chat.go
  2. //
  3. // ⚠️ DEPRECATED NOTICE (弃用说明)
  4. // ================================================================================
  5. // 本文件中的AI对话核心功能已迁移至微服务实现。
  6. // 当前保留此文件是因为前端部分接口仍依赖这里的路由定义。
  7. //
  8. // 迁移状态:
  9. // - AI对话核心逻辑: ✅ 已迁移至微服务
  10. // - 辅助接口(历史记录、推荐问题等): ⚠️ 仍在使用中
  11. //
  12. // TODO: 待前端完全切换到微服务后,可以移除本文件中已弃用的方法
  13. // ================================================================================
  14. package controllers
  15. import (
  16. "bufio"
  17. "bytes"
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "regexp"
  23. "shudao-chat-go/models"
  24. "shudao-chat-go/utils"
  25. "strings"
  26. "time"
  27. "github.com/beego/beego/v2/server/web"
  28. )
  29. type ChatController struct {
  30. web.Controller
  31. }
  32. // 阿里大模型聊天函数
  33. func (c *ChatController) sendQwen3Message(userMessage string, useStream bool) (string, error) {
  34. // 从Beego配置读取阿里大模型配置
  35. apiURL, err := web.AppConfig.String("qwen3_api_url")
  36. if err != nil || apiURL == "" {
  37. return "", fmt.Errorf("配置文件中未找到qwen3_api_url")
  38. }
  39. model, err := web.AppConfig.String("qwen3_model")
  40. if err != nil || model == "" {
  41. return "", fmt.Errorf("配置文件中未找到qwen3_model")
  42. }
  43. // 在用户消息后面添加字数限制要求
  44. finalMessage := userMessage
  45. // fmt.Println("最终发送的消息:", finalMessage)
  46. // 创建阿里大模型请求
  47. qwen3Request := map[string]interface{}{
  48. "model": model,
  49. "stream": useStream,
  50. "temperature": 0.7,
  51. "messages": []map[string]string{
  52. // {"role": "system", "content": "你是一个乐于助人的助手。"},
  53. {"role": "user", "content": finalMessage},
  54. },
  55. }
  56. // 序列化请求
  57. requestBody, err := json.Marshal(qwen3Request)
  58. if err != nil {
  59. return "", fmt.Errorf("请求序列化失败: %v", err)
  60. }
  61. // 发送HTTP请求到阿里大模型
  62. req, err := http.NewRequest("POST", apiURL+"/v1/chat/completions", bytes.NewBuffer(requestBody))
  63. if err != nil {
  64. return "", fmt.Errorf("创建HTTP请求失败: %v", err)
  65. }
  66. // 设置请求头
  67. req.Header.Set("Content-Type", "application/json")
  68. // 发送请求
  69. client := &http.Client{Timeout: 600 * time.Second}
  70. resp, err := client.Do(req)
  71. if err != nil {
  72. return "", fmt.Errorf("请求发送失败: %v", err)
  73. }
  74. defer resp.Body.Close()
  75. // 检查HTTP状态码
  76. if resp.StatusCode != http.StatusOK {
  77. responseBody, err := io.ReadAll(resp.Body)
  78. if err != nil {
  79. return "", fmt.Errorf("阿里大模型API错误: 状态码 %d,读取响应失败: %v", resp.StatusCode, err)
  80. }
  81. return "", fmt.Errorf("阿里大模型API错误: %s", string(responseBody))
  82. }
  83. if useStream {
  84. // 处理流式响应
  85. // fmt.Println("处理流式响应1111111111")
  86. return c.handleStreamResponse(resp)
  87. } else {
  88. // 处理非流式响应
  89. return c.handleNonStreamResponse(resp)
  90. }
  91. }
  92. // 处理流式响应
  93. func (c *ChatController) handleStreamResponse(resp *http.Response) (string, error) {
  94. // 定义流式响应结构
  95. type StreamResponse struct {
  96. ID string `json:"id"`
  97. Object string `json:"object"`
  98. Created int64 `json:"created"`
  99. Model string `json:"model"`
  100. Choices []struct {
  101. Index int `json:"index"`
  102. Delta struct {
  103. Role string `json:"role,omitempty"`
  104. Content string `json:"content,omitempty"`
  105. ToolCalls []struct {
  106. Index int `json:"index"`
  107. ID string `json:"id"`
  108. Type string `json:"type"`
  109. Function struct {
  110. Name string `json:"name"`
  111. Arguments string `json:"arguments"`
  112. } `json:"function"`
  113. } `json:"tool_calls,omitempty"`
  114. } `json:"delta"`
  115. Logprobs interface{} `json:"logprobs"`
  116. FinishReason *string `json:"finish_reason"`
  117. StopReason *string `json:"stop_reason,omitempty"`
  118. } `json:"choices"`
  119. }
  120. // 逐行读取流式响应
  121. scanner := bufio.NewScanner(resp.Body)
  122. var fullContent strings.Builder
  123. var firstChunk = true
  124. for scanner.Scan() {
  125. line := scanner.Text()
  126. // 跳过空行和data:前缀
  127. if line == "" || !strings.HasPrefix(line, "data: ") {
  128. continue
  129. }
  130. // 移除"data: "前缀
  131. data := strings.TrimPrefix(line, "data: ")
  132. // 检查是否是结束标记
  133. if data == "[DONE]" {
  134. break
  135. }
  136. // 解析JSON数据
  137. var streamResp StreamResponse
  138. if err := json.Unmarshal([]byte(data), &streamResp); err != nil {
  139. continue // 跳过解析失败的数据
  140. }
  141. // 标记第一个块已处理
  142. if firstChunk {
  143. firstChunk = false
  144. }
  145. // 处理choices中的内容
  146. if len(streamResp.Choices) > 0 {
  147. choice := streamResp.Choices[0]
  148. if choice.Delta.Content != "" {
  149. fullContent.WriteString(choice.Delta.Content)
  150. }
  151. // 检查是否完成
  152. if choice.FinishReason != nil {
  153. break
  154. }
  155. }
  156. }
  157. if err := scanner.Err(); err != nil {
  158. return "", fmt.Errorf("读取流式响应失败: %v", err)
  159. }
  160. return fullContent.String(), nil
  161. }
  162. // 处理非流式响应
  163. func (c *ChatController) handleNonStreamResponse(resp *http.Response) (string, error) {
  164. // 定义非流式响应结构(与测试文件中的Qwen3ChatResponse保持一致)
  165. type Qwen3ChatResponse struct {
  166. ID string `json:"id"`
  167. Object string `json:"object"`
  168. Created int64 `json:"created"`
  169. Model string `json:"model"`
  170. Choices []struct {
  171. Index int `json:"index"`
  172. Message struct {
  173. Role string `json:"role"`
  174. Content string `json:"content"`
  175. Refusal *string `json:"refusal"`
  176. Annotations *string `json:"annotations"`
  177. Audio *string `json:"audio"`
  178. FunctionCall *string `json:"function_call"`
  179. ToolCalls []interface{} `json:"tool_calls"`
  180. ReasoningContent *string `json:"reasoning_content"`
  181. } `json:"message"`
  182. Logprobs *string `json:"logprobs"`
  183. FinishReason string `json:"finish_reason"`
  184. StopReason *string `json:"stop_reason"`
  185. } `json:"choices"`
  186. ServiceTier *string `json:"service_tier"`
  187. SystemFingerprint *string `json:"system_fingerprint"`
  188. Usage struct {
  189. PromptTokens int `json:"prompt_tokens"`
  190. TotalTokens int `json:"total_tokens"`
  191. CompletionTokens int `json:"completion_tokens"`
  192. PromptTokensDetails *string `json:"prompt_tokens_details"`
  193. } `json:"usage"`
  194. PromptLogprobs *string `json:"prompt_logprobs"`
  195. KvTransferParams *string `json:"kv_transfer_params"`
  196. }
  197. // 读取完整的响应内容
  198. responseBody, err := io.ReadAll(resp.Body)
  199. if err != nil {
  200. return "", fmt.Errorf("读取响应失败: %v", err)
  201. }
  202. // 解析JSON响应
  203. var response Qwen3ChatResponse
  204. if err := json.Unmarshal(responseBody, &response); err != nil {
  205. return "", fmt.Errorf("响应解析失败: %v", err)
  206. }
  207. // 验证响应
  208. if response.ID == "" {
  209. return "", fmt.Errorf("响应ID为空")
  210. }
  211. if len(response.Choices) == 0 {
  212. return "", fmt.Errorf("响应中没有选择项")
  213. }
  214. return response.Choices[0].Message.Content, nil
  215. }
  216. // sendIntentMessage 发送意图识别消息到新的模型接口
  217. func (c *ChatController) sendIntentMessage(userMessage string) (string, error) {
  218. // 从Beego配置读取意图识别模型配置
  219. apiURL, err := web.AppConfig.String("intent_api_url")
  220. if err != nil || apiURL == "" {
  221. return "", fmt.Errorf("配置文件中未找到intent_api_url")
  222. }
  223. model, err := web.AppConfig.String("intent_model")
  224. if err != nil || model == "" {
  225. return "", fmt.Errorf("配置文件中未找到intent_model")
  226. }
  227. // 创建意图识别请求
  228. intentRequest := map[string]interface{}{
  229. "model": model,
  230. "stream": false,
  231. "messages": []map[string]string{
  232. {"role": "user", "content": userMessage},
  233. },
  234. }
  235. // 序列化请求
  236. requestBody, err := json.Marshal(intentRequest)
  237. if err != nil {
  238. return "", fmt.Errorf("请求序列化失败: %v", err)
  239. }
  240. // 发送HTTP请求到意图识别模型
  241. req, err := http.NewRequest("POST", apiURL+"/v1/chat/completions", bytes.NewBuffer(requestBody))
  242. if err != nil {
  243. return "", fmt.Errorf("创建HTTP请求失败: %v", err)
  244. }
  245. // 设置请求头
  246. req.Header.Set("Content-Type", "application/json")
  247. // 发送请求
  248. client := &http.Client{Timeout: 60 * time.Second}
  249. resp, err := client.Do(req)
  250. if err != nil {
  251. return "", fmt.Errorf("请求发送失败: %v", err)
  252. }
  253. defer resp.Body.Close()
  254. // 检查HTTP状态码
  255. if resp.StatusCode != http.StatusOK {
  256. responseBody, err := io.ReadAll(resp.Body)
  257. if err != nil {
  258. return "", fmt.Errorf("意图识别API错误: 状态码 %d,读取响应失败: %v", resp.StatusCode, err)
  259. }
  260. return "", fmt.Errorf("意图识别API错误: %s", string(responseBody))
  261. }
  262. // 处理非流式响应
  263. return c.handleIntentResponse(resp)
  264. }
  265. // handleIntentResponse 处理意图识别响应
  266. func (c *ChatController) handleIntentResponse(resp *http.Response) (string, error) {
  267. // 定义意图识别响应结构
  268. type IntentResponse struct {
  269. ID string `json:"id"`
  270. Object string `json:"object"`
  271. Created int64 `json:"created"`
  272. Model string `json:"model"`
  273. Choices []struct {
  274. Index int `json:"index"`
  275. Message struct {
  276. Role string `json:"role"`
  277. Content string `json:"content"`
  278. Refusal *string `json:"refusal"`
  279. Annotations *string `json:"annotations"`
  280. Audio *string `json:"audio"`
  281. FunctionCall *string `json:"function_call"`
  282. ToolCalls []interface{} `json:"tool_calls"`
  283. ReasoningContent *string `json:"reasoning_content"`
  284. } `json:"message"`
  285. Logprobs *string `json:"logprobs"`
  286. FinishReason string `json:"finish_reason"`
  287. StopReason *string `json:"stop_reason"`
  288. } `json:"choices"`
  289. ServiceTier *string `json:"service_tier"`
  290. SystemFingerprint *string `json:"system_fingerprint"`
  291. Usage struct {
  292. PromptTokens int `json:"prompt_tokens"`
  293. TotalTokens int `json:"total_tokens"`
  294. CompletionTokens int `json:"completion_tokens"`
  295. PromptTokensDetails *string `json:"prompt_tokens_details"`
  296. } `json:"usage"`
  297. PromptLogprobs *string `json:"prompt_logprobs"`
  298. PromptTokenIds *string `json:"prompt_token_ids"`
  299. KvTransferParams *string `json:"kv_transfer_params"`
  300. }
  301. // 读取完整的响应内容
  302. responseBody, err := io.ReadAll(resp.Body)
  303. if err != nil {
  304. return "", fmt.Errorf("读取响应失败: %v", err)
  305. }
  306. // 解析JSON响应
  307. var response IntentResponse
  308. if err := json.Unmarshal(responseBody, &response); err != nil {
  309. return "", fmt.Errorf("响应解析失败: %v", err)
  310. }
  311. // 验证响应
  312. if response.ID == "" {
  313. return "", fmt.Errorf("响应ID为空")
  314. }
  315. if len(response.Choices) == 0 {
  316. return "", fmt.Errorf("响应中没有选择项")
  317. }
  318. if response.Choices[0].Message.Content == "" {
  319. return "", fmt.Errorf("响应内容为空")
  320. }
  321. return response.Choices[0].Message.Content, nil
  322. }
  323. // estimateTokens 估算文本的token数量(基于Qwen官方BPE分词规则)
  324. func (c *ChatController) estimateTokens(text string) int {
  325. // 基于Qwen官方BPE分词规则的token估算
  326. // 根据官方文档:中文字符通常一个汉字对应一个或多个Token
  327. // 英文单词通常一个单词或其部分对应一个Token
  328. // 计算中文字符数量
  329. chineseChars := 0
  330. englishWords := 0
  331. punctuationChars := 0
  332. jsonChars := 0
  333. whitespaceChars := 0
  334. // 统计各种字符类型
  335. for _, r := range text {
  336. if r >= 0x4e00 && r <= 0x9fff {
  337. chineseChars++
  338. } else if r == '{' || r == '}' || r == '[' || r == ']' || r == '"' || r == ':' || r == ',' {
  339. jsonChars++
  340. } else if r == '.' || r == ',' || r == ';' || r == '!' || r == '?' || r == ':' || r == '(' || r == ')' {
  341. punctuationChars++
  342. } else if r == ' ' || r == '\n' || r == '\t' || r == '\r' {
  343. whitespaceChars++
  344. }
  345. }
  346. // 计算英文单词数量(简单按空格分割)
  347. words := strings.Fields(text)
  348. for _, word := range words {
  349. // 检查是否包含英文字符
  350. hasEnglish := false
  351. for _, r := range word {
  352. if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
  353. hasEnglish = true
  354. break
  355. }
  356. }
  357. if hasEnglish {
  358. englishWords++
  359. }
  360. }
  361. // 基于Qwen BPE分词规则的token估算:
  362. // - 中文字符:每个约1.2-1.5个token(根据官方文档,一个汉字可能对应一个或多个token)
  363. // - 英文单词:每个约1-2个token(取决于单词长度和复杂度)
  364. // - 标点符号:每个约0.5-1个token
  365. // - JSON结构字符:每个约0.5个token
  366. // - 空白字符:每个约0.1个token
  367. tokens := int(float64(chineseChars)*1.35 + float64(englishWords)*1.5 + float64(punctuationChars)*0.75 + float64(jsonChars)*0.5 + float64(whitespaceChars)*0.1)
  368. return tokens
  369. }
  370. // truncateContextToFitTokens 截断context内容以适应token限制
  371. func (c *ChatController) truncateContextToFitTokens(contextJSON []byte, maxTokens int, promptPrefix string) []byte {
  372. // 估算prompt前缀的token数量
  373. promptTokens := c.estimateTokens(promptPrefix)
  374. // 预留一些token给AI回复(大约5000个token,更保守)
  375. reservedTokens := 5000
  376. // 计算可用于context的最大token数量
  377. availableTokens := maxTokens - promptTokens - reservedTokens
  378. if availableTokens <= 0 {
  379. // 如果连prompt前缀都不够,返回空context
  380. return []byte("[]")
  381. }
  382. // 解析context JSON
  383. var results []interface{}
  384. if err := json.Unmarshal(contextJSON, &results); err != nil {
  385. fmt.Printf("解析context JSON失败: %v\n", err)
  386. return contextJSON
  387. }
  388. // 从后往前删除文档,直到满足token限制
  389. for len(results) > 0 {
  390. // 估算当前context的token数量
  391. currentContextJSON, _ := json.Marshal(results)
  392. currentTokens := c.estimateTokens(string(currentContextJSON))
  393. if currentTokens <= availableTokens {
  394. fmt.Printf("Context截断完成,最终token数量: %d,文档数量: %d\n", currentTokens, len(results))
  395. return currentContextJSON
  396. }
  397. // 尝试截断最后一个文档的内容而不是完全删除
  398. if len(results) > 0 {
  399. lastDoc := results[len(results)-1]
  400. if docMap, ok := lastDoc.(map[string]interface{}); ok {
  401. if content, exists := docMap["content"].(string); exists && len(content) > 500 {
  402. // 截断文档内容到500字符
  403. docMap["content"] = content[:500] + "..."
  404. fmt.Printf("截断最后一个文档内容,剩余文档数量: %d\n", len(results))
  405. continue
  406. }
  407. }
  408. }
  409. // 如果无法截断,则删除最后一个文档
  410. results = results[:len(results)-1]
  411. fmt.Printf("删除一个文档,剩余文档数量: %d\n", len(results))
  412. }
  413. // 如果所有文档都删除了,返回空数组
  414. return []byte("[]")
  415. }
  416. // 发送deepseek消息
  417. // 构造一下message、ai_conversation_id的结构体(user_id从token中获取)
  418. type SendDeepSeekMessageRequest struct {
  419. Message string `json:"message"`
  420. AIConversationId uint64 `json:"ai_conversation_id"`
  421. BusinessType int `json:"business_type"`
  422. ExamName string `json:"exam_name"`
  423. AIMessageId uint64 `json:"ai_message_id"`
  424. }
  425. // cleanNaturalLanguageAnswer 清洗natural_language_answer中的溯源信息
  426. func (c *ChatController) cleanNaturalLanguageAnswer(naturalAnswer string) string {
  427. // 匹配三个规范段落,如果包含"暂未检索"但后面还有来源,就清空来源
  428. patterns := []string{
  429. `(\*\*1\.\s*国家规范\*\*[^*]*?暂未检索[^*]*?)(\[[^\]]+\])`,
  430. `(\*\*2\.\s*地方规范\*\*[^*]*?暂未检索[^*]*?)(\[[^\]]+\])`,
  431. `(\*\*3\.\s*企业规范\*\*[^*]*?暂未检索[^*]*?)(\[[^\]]+\])`,
  432. }
  433. cleaned := naturalAnswer
  434. for _, pattern := range patterns {
  435. re := regexp.MustCompile(pattern)
  436. cleaned = re.ReplaceAllStringFunc(cleaned, func(match string) string {
  437. // 提取段落内容和来源部分
  438. parts := re.FindStringSubmatch(match)
  439. if len(parts) >= 3 {
  440. // 只保留段落内容,移除来源部分
  441. fmt.Printf("清洗了包含'暂未检索'的段落来源: %s\n", parts[2])
  442. return parts[1]
  443. }
  444. return match
  445. })
  446. }
  447. return cleaned
  448. }
  449. // cleanStructuredDataSources 清洗structured_data:如果content包含"暂未检索",清空对应的sources
  450. func (c *ChatController) cleanStructuredDataSources(aiResponse map[string]interface{}) {
  451. if structuredData, ok := aiResponse["structured_data"].(map[string]interface{}); ok {
  452. levels := []string{"national_level", "local_level", "enterprise_level"}
  453. for _, level := range levels {
  454. if levelData, exists := structuredData[level].(map[string]interface{}); exists {
  455. if content, ok := levelData["content"].(string); ok {
  456. if strings.Contains(content, "暂未检索") {
  457. levelData["sources"] = []string{}
  458. fmt.Printf("清洗%s的sources,因为content包含'暂未检索'\n", level)
  459. }
  460. }
  461. }
  462. }
  463. }
  464. }
  465. // replaceSourcesInNaturalAnswer 使用structured_data中的sources替换natural_language_answer中的溯源信息
  466. func (c *ChatController) replaceSourcesInNaturalAnswer(naturalAnswer string, aiResponse map[string]interface{}) string {
  467. // 获取structured_data
  468. structuredData, ok := aiResponse["structured_data"].(map[string]interface{})
  469. if !ok {
  470. fmt.Printf("structured_data字段不存在或类型错误,返回原始natural_language_answer\n")
  471. return naturalAnswer
  472. }
  473. // 创建level到sources的映射
  474. levelSources := make(map[string][]string)
  475. levels := []string{"national_level", "local_level", "enterprise_level"}
  476. for _, level := range levels {
  477. if levelData, exists := structuredData[level].(map[string]interface{}); exists {
  478. if sources, ok := levelData["sources"].([]interface{}); ok {
  479. var levelSourcesList []string
  480. for _, source := range sources {
  481. if sourceStr, ok := source.(string); ok && sourceStr != "" {
  482. levelSourcesList = append(levelSourcesList, sourceStr)
  483. }
  484. }
  485. levelSources[level] = levelSourcesList
  486. }
  487. }
  488. }
  489. // 检查是否有任何有效的sources
  490. hasValidSources := false
  491. for _, sources := range levelSources {
  492. if len(sources) > 0 {
  493. hasValidSources = true
  494. break
  495. }
  496. }
  497. if !hasValidSources {
  498. fmt.Printf("未找到有效的sources,返回原始natural_language_answer\n")
  499. return naturalAnswer
  500. }
  501. fmt.Printf("找到有效sources: %v\n", levelSources)
  502. // 第一步:完全删除natural_language_answer中所有的溯源标记
  503. result := naturalAnswer
  504. // 匹配并删除所有方括号中的内容(溯源信息)
  505. re := regexp.MustCompile(`\[([^\]]+)\]`)
  506. result = re.ReplaceAllString(result, "")
  507. fmt.Printf("删除所有原始溯源后的内容长度: %d\n", len(result))
  508. // 第二步:使用简单的字符串分割方法为每个level的段落添加对应的sources
  509. levelHeaders := map[string]string{
  510. "national_level": "**1. 国家规范**",
  511. "local_level": "**2. 地方规范**",
  512. "enterprise_level": "**3. 企业规范**",
  513. }
  514. // 按双换行符分割段落
  515. sections := strings.Split(result, "\n\n")
  516. fmt.Printf("总共分割出%d个段落\n", len(sections))
  517. for level, header := range levelHeaders {
  518. if sources, exists := levelSources[level]; exists && len(sources) > 0 {
  519. fmt.Printf("处理%s,sources: %v\n", level, sources)
  520. // 查找包含目标标题的段落
  521. for i, section := range sections {
  522. if strings.Contains(section, header) {
  523. fmt.Printf("找到%s段落%d,长度: %d\n", level, i+1, len(section))
  524. // 检查段落是否已经包含溯源信息
  525. if strings.Contains(section, "[") && strings.Contains(section, "]") {
  526. fmt.Printf("%s段落%d已包含溯源信息,跳过\n", level, i+1)
  527. continue
  528. }
  529. // 构建sources文本
  530. sourceText := ""
  531. for _, source := range sources {
  532. sourceText += "[" + source + "]"
  533. }
  534. // 在段落末尾添加溯源信息
  535. sections[i] = section + "\n" + sourceText
  536. fmt.Printf("为%s段落%d添加溯源: %s\n", level, i+1, sourceText)
  537. break // 只处理第一个匹配的段落
  538. }
  539. }
  540. } else {
  541. fmt.Printf("%s没有sources或sources为空\n", level)
  542. }
  543. }
  544. // 重新组合所有段落
  545. result = strings.Join(sections, "\n\n")
  546. fmt.Printf("溯源替换完成,新长度: %d\n", len(result))
  547. return result
  548. }
  549. func (c *ChatController) SendDeepSeekMessage() {
  550. // 从token中获取用户信息
  551. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  552. if err != nil {
  553. c.Data["json"] = map[string]interface{}{
  554. "statusCode": 401,
  555. "msg": "获取用户信息失败: " + err.Error(),
  556. }
  557. c.ServeJSON()
  558. return
  559. }
  560. user_id := uint64(userInfo.ID)
  561. if user_id == 0 {
  562. user_id = 1
  563. }
  564. // 从请求体获取消息
  565. var requestData SendDeepSeekMessageRequest
  566. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  567. c.Data["json"] = map[string]interface{}{
  568. "statusCode": 400,
  569. "msg": "请求数据解析失败",
  570. }
  571. c.ServeJSON()
  572. return
  573. }
  574. fmt.Println("请求数据:", requestData)
  575. userMessage := requestData.Message
  576. var userMessage1 string
  577. userMessage1 = userMessage
  578. ai_conversation_id := requestData.AIConversationId
  579. tx := models.DB.Begin()
  580. if ai_conversation_id == 0 {
  581. //新建对话
  582. ai_conversation := models.AIConversation{
  583. UserId: user_id,
  584. Content: userMessage,
  585. BusinessType: requestData.BusinessType,
  586. ExamName: requestData.ExamName,
  587. }
  588. if err := tx.Create(&ai_conversation).Error; err != nil {
  589. tx.Rollback()
  590. c.Data["json"] = map[string]interface{}{
  591. "statusCode": 500,
  592. "msg": "新建对话失败: " + err.Error(),
  593. }
  594. c.ServeJSON()
  595. return
  596. }
  597. ai_conversation_id = uint64(ai_conversation.ID)
  598. }
  599. business_type := requestData.BusinessType
  600. ai_message := models.AIMessage{
  601. UserId: user_id,
  602. Content: userMessage,
  603. Type: "user",
  604. AIConversationId: ai_conversation_id,
  605. }
  606. if err := tx.Create(&ai_message).Error; err != nil {
  607. tx.Rollback()
  608. c.Data["json"] = map[string]interface{}{
  609. "statusCode": 500,
  610. "msg": "新建消息失败: " + err.Error(),
  611. }
  612. c.ServeJSON()
  613. return
  614. }
  615. //安全培训
  616. if business_type == 1 {
  617. // Prompt := models.Prompt{}
  618. // models.DB.Model(&Prompt).Where("business_type = ? AND is_deleted = ?", business_type, 0).First(&Prompt)
  619. //userMessage 去向量数据库取30份文档传入下方的<context>中
  620. contextJSON := c.getChromaDBDocumentFunction(userMessage)
  621. prompt := ``
  622. userMessage1 = prompt
  623. }
  624. //AI写作
  625. if business_type == 2 {
  626. contextJSON := c.getChromaDBDocumentFunction(userMessage)
  627. prompt := ``
  628. userMessage1 = prompt
  629. }
  630. //如果是考试工坊则更新ai_conversation表中的content和exam_name
  631. if business_type == 3 {
  632. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("content", userMessage).Update("exam_name", requestData.ExamName).Error; err != nil {
  633. tx.Rollback()
  634. c.Data["json"] = map[string]interface{}{
  635. "statusCode": 500,
  636. "msg": "更新内容失败: " + err.Error(),
  637. }
  638. c.ServeJSON()
  639. return
  640. }
  641. }
  642. var reply string
  643. // 使用阿里大模型替代DeepSeek
  644. if business_type != 0 {
  645. reply, err = c.sendQwen3Message(userMessage1, false) // 使用流式响应
  646. if err != nil {
  647. tx.Rollback()
  648. c.Data["json"] = map[string]interface{}{
  649. "statusCode": 500,
  650. "msg": "阿里大模型调用失败: " + err.Error(),
  651. }
  652. c.ServeJSON()
  653. return
  654. }
  655. } else {
  656. //这里写完成呃rag请求逻辑
  657. prompt := ``
  658. // reply, err = c.sendIntentMessage(prompt) // 使用新的意图识别模型
  659. //使用deepseek
  660. reply, err = c.sendQwen3Message(prompt, false) // 使用流式响应
  661. if err != nil {
  662. tx.Rollback()
  663. c.Data["json"] = map[string]interface{}{
  664. "statusCode": 500,
  665. "msg": "意图识别模型调用失败: " + err.Error(),
  666. }
  667. c.ServeJSON()
  668. return
  669. }
  670. fmt.Println("reply:", reply)
  671. // 解析AI返回的JSON响应
  672. var aiResponse map[string]interface{}
  673. // 清理回复中的换行符和多余空白字符
  674. cleanReply := strings.TrimSpace(reply)
  675. // 移除可能的markdown代码块标记
  676. cleanReply = strings.TrimPrefix(cleanReply, "```json")
  677. cleanReply = strings.TrimSuffix(cleanReply, "```")
  678. cleanReply = strings.TrimSpace(cleanReply)
  679. if err := json.Unmarshal([]byte(cleanReply), &aiResponse); err != nil {
  680. // 如果解析失败,可能是AI直接返回了文本格式(greeting、faq、out_of_scope)
  681. fmt.Printf("JSON解析失败,AI返回了文本格式回复: %s\n", reply)
  682. fmt.Printf("清理后回复: %s\n", cleanReply)
  683. fmt.Printf("解析错误: %v\n", err)
  684. // 直接使用AI的原始回复,不做格式检查
  685. fmt.Printf("直接使用AI的原始回复\n")
  686. } else {
  687. intent, ok := aiResponse["intent"].(string)
  688. if !ok {
  689. reply = "解析失败2"
  690. } else {
  691. // 根据intent类型决定返回内容
  692. if intent == "greeting" || intent == "faq" || intent == "out_of_scope" {
  693. // 对于greeting、faq、out_of_scope,AI应该直接返回自然回复
  694. // 检查是否有direct_answer字段,如果没有则使用原始回复
  695. if directAnswer, exists := aiResponse["direct_answer"].(string); exists && directAnswer != "" {
  696. reply = directAnswer
  697. } else {
  698. // 如果没有direct_answer字段,直接使用AI的原始回复
  699. fmt.Printf("intent为%s,直接使用AI的原始回复\n", intent)
  700. }
  701. } else {
  702. // reply = "复杂问题,进入下一步"
  703. //取出里面的数组search_queries
  704. search_queries, ok := aiResponse["search_queries"].([]interface{})
  705. if !ok || len(search_queries) == 0 {
  706. reply = "解析失败4"
  707. } else {
  708. // 将search_queries转换为字符串数组
  709. var queries []string
  710. for _, query := range search_queries {
  711. if queryStr, ok := query.(string); ok {
  712. queries = append(queries, queryStr)
  713. }
  714. }
  715. // 使用第一个查询进行搜索
  716. if len(queries) > 0 {
  717. // 构建搜索请求
  718. searchRequest := map[string]interface{}{
  719. "query": queries[0], // 使用第一个查询
  720. "n_results": 25, // 返回3个结果
  721. }
  722. requestBody, err := json.Marshal(searchRequest)
  723. if err != nil {
  724. reply = "解析失败5"
  725. } else {
  726. // 从配置文件中读取搜索API地址
  727. searchAPIURL, err := web.AppConfig.String("search_api_url")
  728. if err != nil || searchAPIURL == "" {
  729. reply = "配置文件中未找到search_api_url"
  730. } else {
  731. // 发送HTTP请求到本地Python服务
  732. req, err := http.NewRequest("POST", searchAPIURL, bytes.NewBuffer(requestBody))
  733. if err != nil {
  734. reply = "解析失败6"
  735. } else {
  736. req.Header.Set("Content-Type", "application/json")
  737. client := &http.Client{Timeout: 30 * time.Second}
  738. resp, err := client.Do(req)
  739. if err != nil {
  740. reply = "解析失败7" + err.Error()
  741. } else {
  742. defer resp.Body.Close()
  743. responseBody, err := io.ReadAll(resp.Body)
  744. if err != nil {
  745. reply = "解析失败8"
  746. } else if resp.StatusCode != http.StatusOK {
  747. reply = fmt.Sprintf("搜索API错误: 状态码 %d", resp.StatusCode)
  748. } else {
  749. // 解析搜索响应
  750. var searchResponse map[string]interface{}
  751. if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
  752. reply = "解析失败10"
  753. } else {
  754. // 检查响应状态
  755. // fmt.Println("searchResponse11111111:", searchResponse)
  756. status, ok := searchResponse["status"].(string)
  757. if !ok || status != "success" {
  758. message, _ := searchResponse["message"].(string)
  759. reply = fmt.Sprintf("搜索失败: %s", message)
  760. } else {
  761. // 获取搜索结果
  762. results, ok := searchResponse["results"].([]interface{})
  763. // fmt.Println("results:", results)
  764. if !ok || len(results) == 0 {
  765. reply = "未找到相关文档"
  766. } else {
  767. // 直接将原始搜索结果转换为JSON字符串作为上下文
  768. // 获取历史对话(前两轮,如果只有1轮就到1轮,没有就不导入)
  769. var historyContext string
  770. if ai_conversation_id > 0 {
  771. var historyMessages []models.AIMessage
  772. // 获取当前对话的历史消息,按时间排序,排除当前消息
  773. models.DB.Model(&models.AIMessage{}).
  774. Where("user_id = ? AND ai_conversation_id = ? AND is_deleted = ? AND id < ?",
  775. user_id, ai_conversation_id, 0, ai_message.ID).
  776. Order("updated_at ASC").
  777. Find(&historyMessages)
  778. // 限制为前两轮对话(每轮包含用户消息和AI回复)
  779. if len(historyMessages) > 0 {
  780. // 计算轮数:每2条消息为1轮(用户消息+AI回复)
  781. maxRounds := 2
  782. maxMessages := maxRounds * 2
  783. if len(historyMessages) > maxMessages {
  784. historyMessages = historyMessages[len(historyMessages)-maxMessages:]
  785. }
  786. // 构建历史对话上下文
  787. historyContext = "\n\n# 历史对话上下文\n"
  788. for _, msg := range historyMessages {
  789. if msg.Type == "user" {
  790. historyContext += "用户: " + msg.Content + "\n"
  791. } else if msg.Type == "ai" {
  792. historyContext += "蜀安AI助手: " + msg.Content + "\n"
  793. }
  794. }
  795. historyContext += "\n"
  796. }
  797. //根据用户意图投入搜索来源数据
  798. }
  799. contextJSON, err := json.Marshal(results)
  800. // fmt.Println("contextJSON:", string(contextJSON))
  801. // fmt.Println("historyContext:", historyContext)
  802. if err != nil {
  803. reply = "处理搜索结果失败: " + err.Error()
  804. } else {
  805. // 获取联网搜索内容
  806. onlineSearchContent := c.getOnlineSearchContent(userMessage)
  807. // fmt.Println("联网数据:", onlineSearchContent)
  808. // 构建新的JSON格式提示词
  809. finalPrompt := ``
  810. finalReply, err := c.sendQwen3Message(finalPrompt, false) // 使用流式响应
  811. if err != nil {
  812. reply = "生成最终回答失败: " + err.Error()
  813. } else {
  814. // 解析AI返回的JSON响应
  815. fmt.Printf("AI原始回复: %s\n", finalReply)
  816. // 尝试清理JSON字符串
  817. cleanedReply := strings.TrimSpace(finalReply)
  818. // 移除可能的markdown代码块标记
  819. cleanedReply = strings.TrimPrefix(cleanedReply, "```json")
  820. cleanedReply = strings.TrimPrefix(cleanedReply, "```")
  821. cleanedReply = strings.TrimSuffix(cleanedReply, "```")
  822. cleanedReply = strings.TrimSpace(cleanedReply)
  823. var aiResponse map[string]interface{}
  824. if err := json.Unmarshal([]byte(cleanedReply), &aiResponse); err != nil {
  825. // 如果解析失败,尝试提取natural_language_answer字段的正则表达式
  826. fmt.Printf("JSON解析失败,尝试正则提取: %v\n", err)
  827. if strings.Contains(finalReply, "natural_language_answer") {
  828. // 使用正则表达式提取natural_language_answer的内容
  829. re := regexp.MustCompile(`"natural_language_answer"\s*:\s*"([^"]*(?:\\.[^"]*)*)"`)
  830. matches := re.FindStringSubmatch(finalReply)
  831. if len(matches) > 1 {
  832. naturalAnswer := matches[1]
  833. // 处理转义字符
  834. naturalAnswer = strings.ReplaceAll(naturalAnswer, "\\n", "\n")
  835. naturalAnswer = strings.ReplaceAll(naturalAnswer, "\\\"", "\"")
  836. fmt.Printf("正则提取成功,长度: %d\n", len(naturalAnswer))
  837. // 清洗natural_language_answer中的溯源信息
  838. naturalAnswer = c.cleanNaturalLanguageAnswer(naturalAnswer)
  839. // 尝试解析structured_data进行溯源替换
  840. var tempResponse map[string]interface{}
  841. if err := json.Unmarshal([]byte(cleanedReply), &tempResponse); err == nil {
  842. correctedAnswer := c.replaceSourcesInNaturalAnswer(naturalAnswer, tempResponse)
  843. reply = correctedAnswer
  844. } else {
  845. reply = naturalAnswer
  846. }
  847. } else {
  848. fmt.Printf("正则提取失败,使用原始回复\n")
  849. reply = finalReply
  850. }
  851. } else {
  852. fmt.Printf("未找到natural_language_answer字段,使用原始回复\n")
  853. reply = finalReply
  854. }
  855. } else {
  856. // 提取natural_language_answer字段
  857. if naturalAnswer, ok := aiResponse["natural_language_answer"].(string); ok {
  858. fmt.Printf("成功提取natural_language_answer,长度: %d\n", len(naturalAnswer))
  859. // 清洗natural_language_answer中的溯源信息
  860. naturalAnswer = c.cleanNaturalLanguageAnswer(naturalAnswer)
  861. // 使用structured_data中的sources替换natural_language_answer中的溯源信息
  862. correctedAnswer := c.replaceSourcesInNaturalAnswer(naturalAnswer, aiResponse)
  863. reply = correctedAnswer
  864. } else {
  865. // 如果字段不存在,使用原始回复
  866. fmt.Printf("natural_language_answer字段不存在或类型错误\n")
  867. reply = finalReply
  868. }
  869. }
  870. }
  871. }
  872. }
  873. }
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. } else {
  881. reply = "未找到有效的查询内容"
  882. }
  883. }
  884. }
  885. }
  886. }
  887. }
  888. //新建AI回复
  889. ai_reply := models.AIMessage{
  890. UserId: user_id,
  891. Content: reply,
  892. Type: "ai",
  893. AIConversationId: ai_conversation_id,
  894. PrevUserId: uint64(ai_message.ID),
  895. }
  896. if err := tx.Create(&ai_reply).Error; err != nil {
  897. tx.Rollback()
  898. c.Data["json"] = map[string]interface{}{
  899. "statusCode": 500,
  900. "msg": "新建消息失败: " + err.Error(),
  901. }
  902. c.ServeJSON()
  903. return
  904. }
  905. //更新AIConversation编辑时间
  906. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  907. tx.Rollback()
  908. c.Data["json"] = map[string]interface{}{
  909. "statusCode": 500,
  910. "msg": "更新编辑时间失败: " + err.Error(),
  911. }
  912. c.ServeJSON()
  913. return
  914. }
  915. tx.Commit()
  916. // 返回成功响应(保持与原来相同的格式)
  917. // fmt.Printf("最终返回的reply内容长度: %d\n", len(reply))
  918. // fmt.Printf("最终返回的reply内容: %s\n", reply)
  919. // if len(reply) > 100 {
  920. // fmt.Printf("最终返回的reply前100字符: %s\n", reply[:100])
  921. // } else {
  922. // fmt.Printf("最终返回的reply内容: %s\n", reply)
  923. // }
  924. c.Data["json"] = map[string]interface{}{
  925. "statusCode": 200,
  926. "msg": "success",
  927. "data": map[string]interface{}{
  928. "reply": reply,
  929. // "user_message": userMessage,
  930. "ai_conversation_id": ai_conversation_id,
  931. "ai_message_id": ai_reply.ID,
  932. },
  933. }
  934. c.ServeJSON()
  935. }
  936. // 删除对话
  937. type DeleteConversationRequest struct {
  938. AIConversationID uint64 `json:"ai_conversation_id"`
  939. AIMessageID uint64 `json:"ai_message_id"`
  940. }
  941. func (c *ChatController) DeleteConversation() {
  942. var requestData DeleteConversationRequest
  943. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  944. c.Data["json"] = map[string]interface{}{
  945. "statusCode": 400,
  946. "msg": "请求数据解析失败",
  947. }
  948. c.ServeJSON()
  949. return
  950. }
  951. ai_message_id := requestData.AIMessageID
  952. fmt.Println("ai_message_id:", ai_message_id)
  953. tx := models.DB.Begin()
  954. //这里除了要删除这条ai消息,还要查询到prev_user_id这条消息,并删除
  955. if err := tx.Model(&models.AIMessage{}).Where("id = ?", ai_message_id).Update("is_deleted", 1).Error; err != nil {
  956. tx.Rollback()
  957. c.Data["json"] = map[string]interface{}{
  958. "statusCode": 500,
  959. "msg": "删除消息失败",
  960. }
  961. c.ServeJSON()
  962. return
  963. }
  964. var ai_message_user models.AIMessage
  965. models.DB.Where("id = ?", ai_message_id).First(&ai_message_user)
  966. prev_user_id := ai_message_user.PrevUserId
  967. if err := tx.Model(&models.AIMessage{}).Where("id = ?", prev_user_id).Update("is_deleted", 1).Error; err != nil {
  968. tx.Rollback()
  969. c.Data["json"] = map[string]interface{}{
  970. "statusCode": 500,
  971. "msg": "删除消息失败",
  972. }
  973. c.ServeJSON()
  974. return
  975. }
  976. //更新ai_conversation表中的编辑时间
  977. ai_conversation_id := ai_message_user.AIConversationId
  978. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  979. tx.Rollback()
  980. c.Data["json"] = map[string]interface{}{
  981. "statusCode": 500,
  982. "msg": "更新编辑时间失败",
  983. }
  984. c.ServeJSON()
  985. return
  986. }
  987. tx.Commit()
  988. c.Data["json"] = map[string]interface{}{
  989. "statusCode": 200,
  990. "msg": "success",
  991. }
  992. c.ServeJSON()
  993. }
  994. // ppt大纲存主表
  995. type SavePPTOutlineRequest struct {
  996. AIConversationID uint64 `json:"ai_conversation_id"`
  997. PPTOutline string `json:"ppt_outline"`
  998. PPTContent string `json:"ppt_content"`
  999. }
  1000. func (c *ChatController) SavePPTOutline() {
  1001. var requestData SavePPTOutlineRequest
  1002. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1003. c.Data["json"] = map[string]interface{}{
  1004. "statusCode": 400,
  1005. "msg": "请求数据解析失败",
  1006. }
  1007. c.ServeJSON()
  1008. return
  1009. }
  1010. ai_conversation_id := requestData.AIConversationID
  1011. ppt_content := requestData.PPTContent
  1012. fmt.Println("ppt_content", ppt_content)
  1013. // ppt_outline := requestData.PPTOutline
  1014. tx := models.DB.Begin()
  1015. //更新到AIMessage表中的ppt_content
  1016. if err := tx.Model(&models.AIMessage{}).Where("ai_conversation_id = ? AND type = 'ai'", ai_conversation_id).Update("content", ppt_content).Error; err != nil {
  1017. tx.Rollback()
  1018. c.Data["json"] = map[string]interface{}{
  1019. "statusCode": 500,
  1020. "msg": "保存ppt内容失败",
  1021. }
  1022. }
  1023. //ai_conversation表中的p更新编辑时间
  1024. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1025. tx.Rollback()
  1026. c.Data["json"] = map[string]interface{}{
  1027. "statusCode": 500,
  1028. "msg": "更新编辑时间失败",
  1029. }
  1030. }
  1031. tx.Commit()
  1032. c.Data["json"] = map[string]interface{}{
  1033. "statusCode": 200,
  1034. "msg": "success",
  1035. }
  1036. c.ServeJSON()
  1037. }
  1038. // 返回历史记录
  1039. func (c *ChatController) GetHistoryRecord() {
  1040. // 从token中获取用户信息
  1041. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  1042. fmt.Println("userInfo", userInfo)
  1043. if err != nil {
  1044. c.Data["json"] = map[string]interface{}{
  1045. "statusCode": 401,
  1046. "msg": "获取用户信息失败: " + err.Error(),
  1047. }
  1048. c.ServeJSON()
  1049. return
  1050. }
  1051. user_id := int64(userInfo.ID)
  1052. if user_id == 0 {
  1053. user_id = 1
  1054. }
  1055. ai_conversation_id, _ := c.GetInt64("ai_conversation_id")
  1056. business_type, _ := c.GetInt64("business_type")
  1057. //返回详情
  1058. if ai_conversation_id > 0 {
  1059. var ppt_outline string
  1060. var ppt_json_content string
  1061. //如果是ppt
  1062. if business_type == 1 {
  1063. var ai_conversation models.AIConversation
  1064. models.DB.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).First(&ai_conversation)
  1065. ppt_outline = ai_conversation.PPTOutline
  1066. ppt_json_content = ai_conversation.PPTJsonContent
  1067. }
  1068. var ai_message []models.AIMessage
  1069. models.DB.Model(&models.AIMessage{}).Where("user_id = ? AND ai_conversation_id = ? AND is_deleted = ?", user_id, ai_conversation_id, 0).Order("updated_at").Find(&ai_message)
  1070. c.Data["json"] = map[string]interface{}{
  1071. "statusCode": 200,
  1072. "msg": "success",
  1073. "data": ai_message,
  1074. "ppt_outline": ppt_outline,
  1075. "ppt_json_content": ppt_json_content,
  1076. }
  1077. fmt.Println("ppt_outline", ppt_outline)
  1078. c.ServeJSON()
  1079. return
  1080. }
  1081. // 检查数据库连接
  1082. sqlDB, err := models.DB.DB()
  1083. if err != nil {
  1084. c.Data["json"] = map[string]interface{}{
  1085. "statusCode": 500,
  1086. "msg": "数据库连接失败: " + err.Error(),
  1087. }
  1088. c.ServeJSON()
  1089. return
  1090. }
  1091. // 测试数据库连接
  1092. if err := sqlDB.Ping(); err != nil {
  1093. c.Data["json"] = map[string]interface{}{
  1094. "statusCode": 500,
  1095. "msg": "数据库连接测试失败: " + err.Error(),
  1096. }
  1097. c.ServeJSON()
  1098. return
  1099. }
  1100. var ai_conversation []models.AIConversation
  1101. models.DB.Model(&models.AIConversation{}).Where("user_id = ? AND is_deleted = ? AND business_type = ?", user_id, 0, business_type).Order("-updated_at").Find(&ai_conversation)
  1102. //计算返回的总共的数据数量
  1103. var total int64
  1104. models.DB.Model(&models.AIConversation{}).Where("user_id = ? AND is_deleted = ? AND business_type = ?", user_id, 0, business_type).Count(&total)
  1105. c.Data["json"] = map[string]interface{}{
  1106. "statusCode": 200,
  1107. "msg": "success",
  1108. "data": ai_conversation,
  1109. "total": total,
  1110. }
  1111. c.ServeJSON()
  1112. }
  1113. // 点赞和点踩post请求
  1114. func (c *ChatController) LikeAndDislike() {
  1115. var requestData models.AIMessage
  1116. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1117. c.Data["json"] = map[string]interface{}{
  1118. "statusCode": 400,
  1119. "msg": "请求数据解析失败",
  1120. }
  1121. c.ServeJSON()
  1122. return
  1123. }
  1124. id := requestData.ID
  1125. user_feedback := requestData.UserFeedback
  1126. tx := models.DB.Begin()
  1127. if err := tx.Model(&models.AIMessage{}).Where("id = ?", id).Update("user_feedback", user_feedback).Error; err != nil {
  1128. tx.Rollback()
  1129. c.Data["json"] = map[string]interface{}{
  1130. "statusCode": 500,
  1131. "msg": "点赞和点踩失败",
  1132. }
  1133. c.ServeJSON()
  1134. return
  1135. }
  1136. tx.Commit()
  1137. c.Data["json"] = map[string]interface{}{
  1138. "statusCode": 200,
  1139. "msg": "success",
  1140. }
  1141. c.ServeJSON()
  1142. }
  1143. // 直接问问题
  1144. func (c *ChatController) ReProduceSingleQuestion() {
  1145. // 从请求体获取消息
  1146. var requestData SendDeepSeekMessageRequest
  1147. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1148. c.Data["json"] = map[string]interface{}{
  1149. "statusCode": 400,
  1150. "msg": "请求数据解析失败",
  1151. }
  1152. c.ServeJSON()
  1153. return
  1154. }
  1155. fmt.Println("请求数据:", requestData)
  1156. userMessage := requestData.Message
  1157. // 使用阿里大模型替代DeepSeek
  1158. reply, err := c.sendQwen3Message(userMessage, false) // 使用流式响应
  1159. if err != nil {
  1160. c.Data["json"] = map[string]interface{}{
  1161. "statusCode": 500,
  1162. "msg": "阿里大模型调用失败: " + err.Error(),
  1163. }
  1164. c.ServeJSON()
  1165. return
  1166. }
  1167. // 返回成功响应(保持与原来相同的格式)
  1168. c.Data["json"] = map[string]interface{}{
  1169. "statusCode": 200,
  1170. "msg": "success",
  1171. "data": map[string]interface{}{
  1172. "reply": reply,
  1173. },
  1174. }
  1175. fmt.Println("回复:", reply)
  1176. c.ServeJSON()
  1177. }
  1178. // 猜你想问
  1179. func (c *ChatController) GuessYouWant() {
  1180. // 从请求体获取消息
  1181. var requestData SendDeepSeekMessageRequest
  1182. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1183. c.Data["json"] = map[string]interface{}{
  1184. "statusCode": 400,
  1185. "msg": "请求数据解析失败",
  1186. }
  1187. c.ServeJSON()
  1188. return
  1189. }
  1190. fmt.Println("请求数据:", requestData)
  1191. userMessage := requestData.Message
  1192. // 构建带有专业问题判断规则的提示词
  1193. promptWithRules := fmt.Sprintf(`你是蜀道安全管理AI智能助手,请根据用户的问题生成3个相关的后续问题建议(猜你想问)。
  1194. ## 用户问题
  1195. %s
  1196. ## 生成问题规则(最高优先级)
  1197. 1. 严禁生成任何政治敏感信息,包含重要国家领导人,重要国际事件等
  1198. 2. 严禁在生成的问题中包含人名信息,任何人名都不行
  1199. 3. 严禁生成色情敏感信息
  1200. 4. 严禁生成超长文本,最多只能30个字
  1201. ## 你的回答(仅输出3个问题,每行一个,或返回空)`, userMessage)
  1202. // 使用阿里大模型替代DeepSeek
  1203. reply, err := c.sendQwen3Message(promptWithRules, false)
  1204. if err != nil {
  1205. c.Data["json"] = map[string]interface{}{
  1206. "statusCode": 500,
  1207. "msg": "阿里大模型调用失败: " + err.Error(),
  1208. }
  1209. c.ServeJSON()
  1210. return
  1211. }
  1212. ai_message_id := requestData.AIMessageId
  1213. // fmt.Println("猜你想问的ai_message_id", ai_message_id)
  1214. tx := models.DB.Begin()
  1215. if err := tx.Model(&models.AIMessage{}).Where("id = ?", ai_message_id).Update("guess_you_want", reply).Error; err != nil {
  1216. tx.Rollback()
  1217. c.Data["json"] = map[string]interface{}{
  1218. "statusCode": 500,
  1219. "msg": "保存猜你想问失败",
  1220. }
  1221. }
  1222. tx.Commit()
  1223. // 返回成功响应(保持与原来相同的格式)
  1224. c.Data["json"] = map[string]interface{}{
  1225. "statusCode": 200,
  1226. "msg": "success",
  1227. "data": map[string]interface{}{
  1228. "reply": reply,
  1229. },
  1230. }
  1231. fmt.Println("猜你想问:", reply)
  1232. c.ServeJSON()
  1233. }
  1234. // 用户在输入框中每输入一个字,就调用一次阿里大模型返回推荐问题
  1235. func (c *ChatController) GetUserRecommendQuestion() {
  1236. // 从token中获取用户信息(GET请求也需要token)
  1237. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  1238. if err != nil {
  1239. c.Data["json"] = map[string]interface{}{
  1240. "statusCode": 401,
  1241. "msg": "获取用户信息失败: " + err.Error(),
  1242. }
  1243. c.ServeJSON()
  1244. return
  1245. }
  1246. user_id := int64(userInfo.ID)
  1247. if user_id == 0 {
  1248. user_id = 1
  1249. }
  1250. userMessage1 := c.GetString("user_message")
  1251. // 直接从QA表中模糊查询问题
  1252. var qaList []models.QA
  1253. models.DB.Model(&models.QA{}).Where("question LIKE ? AND is_deleted = ?", "%"+userMessage1+"%", 0).Limit(10).Find(&qaList)
  1254. if len(qaList) == 0 {
  1255. c.Data["json"] = map[string]interface{}{
  1256. "statusCode": 200,
  1257. "msg": "success",
  1258. }
  1259. c.ServeJSON()
  1260. return
  1261. }
  1262. // 提取问题列表
  1263. var questions []string
  1264. for _, qa := range qaList {
  1265. questions = append(questions, qa.Question)
  1266. }
  1267. c.Data["json"] = map[string]interface{}{
  1268. "statusCode": 200,
  1269. "msg": "success",
  1270. "data": map[string]interface{}{
  1271. "questions": questions,
  1272. },
  1273. }
  1274. c.ServeJSON()
  1275. }
  1276. // 用户传文件名取数据库寻找链接(使用编辑距离算法匹配最相似的文件名)
  1277. func (c *ChatController) GetFileLink() {
  1278. fileName := c.GetString("fileName")
  1279. fmt.Println("查询文件名:", fileName)
  1280. // 获取所有未删除的文件记录
  1281. var indexFiles []models.IndexFile
  1282. models.DB.Model(&models.IndexFile{}).Where("is_deleted = ?", 0).Find(&indexFiles)
  1283. if len(indexFiles) == 0 {
  1284. c.Data["json"] = map[string]interface{}{
  1285. "statusCode": 404,
  1286. "msg": "数据库中没有找到任何文件",
  1287. "data": "",
  1288. }
  1289. c.ServeJSON()
  1290. return
  1291. }
  1292. // 提取所有文件名作为候选列表
  1293. var candidates []string
  1294. for _, file := range indexFiles {
  1295. candidates = append(candidates, file.FileName)
  1296. }
  1297. // 使用编辑距离算法找到最相似的文件名
  1298. bestMatch, bestScore := utils.FindBestMatch(fileName, candidates)
  1299. fmt.Printf("最佳匹配: %s (相似度: %.3f)\n", bestMatch, bestScore)
  1300. // 找到对应的文件记录
  1301. var matchedFile models.IndexFile
  1302. for _, file := range indexFiles {
  1303. if file.FileName == bestMatch {
  1304. matchedFile = file
  1305. break
  1306. }
  1307. }
  1308. fmt.Println("匹配的文件记录:", matchedFile)
  1309. fmt.Println("文件链接:", matchedFile.FilePath)
  1310. // 如果相似度太低,可以设置阈值
  1311. threshold := 0.3 // 相似度阈值,可以根据需要调整
  1312. if bestScore < threshold {
  1313. c.Data["json"] = map[string]interface{}{
  1314. "statusCode": 200,
  1315. "msg": fmt.Sprintf("没有找到相似度 >= %.1f 的文件,最佳匹配相似度: %.3f", threshold, bestScore),
  1316. "data": "",
  1317. "bestMatch": bestMatch,
  1318. "bestScore": bestScore,
  1319. }
  1320. c.ServeJSON()
  1321. return
  1322. }
  1323. // 检查文件路径是否已经是代理URL格式,如果不是则转换为代理URL
  1324. var fileURL string
  1325. if matchedFile.FilePath != "" {
  1326. if !strings.Contains(matchedFile.FilePath, "/apiv1/oss/parse/?url=") {
  1327. fileURL = utils.GetProxyURL(matchedFile.FilePath)
  1328. } else {
  1329. fileURL = matchedFile.FilePath
  1330. }
  1331. }
  1332. // 返回代理URL
  1333. fmt.Println("代理URL:", fileURL)
  1334. c.Data["json"] = map[string]interface{}{
  1335. "statusCode": 200,
  1336. "msg": "success",
  1337. "data": fileURL,
  1338. "bestMatch": bestMatch,
  1339. "bestScore": bestScore,
  1340. "fileName": fileName,
  1341. }
  1342. c.ServeJSON()
  1343. }
  1344. // 删除历史记录
  1345. type DeleteHistoryRecordRequest struct {
  1346. AIConversationID uint64 `json:"ai_conversation_id"`
  1347. }
  1348. func (c *ChatController) DeleteHistoryRecord() {
  1349. var requestData DeleteHistoryRecordRequest
  1350. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1351. c.Data["json"] = map[string]interface{}{
  1352. "statusCode": 400,
  1353. "msg": "请求数据解析失败",
  1354. }
  1355. c.ServeJSON()
  1356. return
  1357. }
  1358. ai_conversation_id := requestData.AIConversationID
  1359. tx := models.DB.Begin()
  1360. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("is_deleted", 1).Error; err != nil {
  1361. tx.Rollback()
  1362. c.Data["json"] = map[string]interface{}{
  1363. "statusCode": 500,
  1364. "msg": "删除历史记录失败",
  1365. }
  1366. }
  1367. tx.Commit()
  1368. c.Data["json"] = map[string]interface{}{
  1369. "statusCode": 200,
  1370. "msg": "success",
  1371. }
  1372. c.ServeJSON()
  1373. }
  1374. // 删除隐患识别的历史记录
  1375. type DeleteRecognitionRecordRequest struct {
  1376. RecognitionRecordID uint64 `json:"recognition_record_id"`
  1377. }
  1378. func (c *ChatController) DeleteRecognitionRecord() {
  1379. var requestData DeleteRecognitionRecordRequest
  1380. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1381. c.Data["json"] = map[string]interface{}{
  1382. "statusCode": 400,
  1383. "msg": "请求数据解析失败",
  1384. }
  1385. c.ServeJSON()
  1386. return
  1387. }
  1388. recognition_record_id := requestData.RecognitionRecordID
  1389. tx := models.DB.Begin()
  1390. if err := tx.Model(&models.RecognitionRecord{}).Where("id = ?", recognition_record_id).Update("is_deleted", 1).Error; err != nil {
  1391. tx.Rollback()
  1392. c.Data["json"] = map[string]interface{}{
  1393. "statusCode": 500,
  1394. "msg": "删除隐患识别的历史记录失败",
  1395. }
  1396. c.ServeJSON()
  1397. return
  1398. }
  1399. tx.Commit()
  1400. c.Data["json"] = map[string]interface{}{
  1401. "statusCode": 200,
  1402. "msg": "success",
  1403. }
  1404. c.ServeJSON()
  1405. }
  1406. // AI写作保存编辑文档内容
  1407. func (c *ChatController) SaveEditDocument() {
  1408. var requestData models.AIMessage
  1409. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1410. c.Data["json"] = map[string]interface{}{
  1411. "statusCode": 400,
  1412. "msg": "请求数据解析失败",
  1413. }
  1414. }
  1415. ai_conversation_id := requestData.AIConversationId
  1416. fmt.Println("ai_conversation_id", ai_conversation_id)
  1417. content := requestData.Content
  1418. tx := models.DB.Begin()
  1419. if err := tx.Model(&models.AIMessage{}).Where("ai_conversation_id = ? AND type = 'ai' AND is_deleted = ?", ai_conversation_id, 0).Update("content", content).Error; err != nil {
  1420. tx.Rollback()
  1421. c.Data["json"] = map[string]interface{}{
  1422. "statusCode": 500,
  1423. "msg": "保存编辑文档内容失败",
  1424. }
  1425. }
  1426. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1427. tx.Rollback()
  1428. c.Data["json"] = map[string]interface{}{
  1429. "statusCode": 500,
  1430. "msg": "更新编辑时间失败",
  1431. }
  1432. }
  1433. tx.Commit()
  1434. c.Data["json"] = map[string]interface{}{
  1435. "statusCode": 200,
  1436. "msg": "success",
  1437. "data": content,
  1438. }
  1439. c.ServeJSON()
  1440. }
  1441. // 联网搜索
  1442. func (c *ChatController) OnlineSearch() {
  1443. // 获取请求参数
  1444. keywords := c.GetString("keywords")
  1445. // 参数验证
  1446. if keywords == "" {
  1447. c.Data["json"] = map[string]interface{}{
  1448. "statusCode": 400,
  1449. "error": "参数错误:keywords不能为空",
  1450. }
  1451. c.ServeJSON()
  1452. return
  1453. }
  1454. // 在关键词前加入检索策略提示词:
  1455. // 1) 若用户意图属于土木工程/路桥隧轨/施工安全等相关领域,则直接按该意图搜索
  1456. // 2) 若与上述领域无关,则根据用户表达猜测一个最可能的土木工程相关问题再进行搜索
  1457. combinedKeywords := fmt.Sprintf("【搜索策略】先识别用户意图:若问题属于土木工程/路桥隧轨/施工安全等领域,则按此意图联网搜索;若非上述领域,请根据用户表达猜测一个最可能的土木工程相关问题并据此搜索。确保检索聚焦专业资料。确保回复字数在20字内。【用户问题】%s", keywords)
  1458. //给AI发送消息
  1459. reply, err := c.sendQwen3Message(combinedKeywords, false)
  1460. if err != nil {
  1461. c.Data["json"] = map[string]interface{}{
  1462. "statusCode": 500,
  1463. "msg": "阿里大模型调用失败: " + err.Error(),
  1464. }
  1465. c.ServeJSON()
  1466. return
  1467. }
  1468. fmt.Println("联网搜索回复:", reply)
  1469. // 构建请求体
  1470. requestBody := map[string]interface{}{
  1471. "workflow_id": "4wfh1PPDderMtCeb",
  1472. "inputs": map[string]interface{}{
  1473. "keywords": reply,
  1474. "num": 10, // 默认参数
  1475. "max_text_len": 150,
  1476. },
  1477. "response_mode": "blocking", // 默认参数
  1478. "user": "user_001",
  1479. }
  1480. // 序列化请求体
  1481. jsonData, err := json.Marshal(requestBody)
  1482. if err != nil {
  1483. c.Data["json"] = map[string]interface{}{
  1484. "statusCode": 500,
  1485. "error": "请求参数序列化失败: " + err.Error(),
  1486. }
  1487. c.ServeJSON()
  1488. return
  1489. }
  1490. // 创建HTTP请求
  1491. req, err := http.NewRequest("POST", utils.GetDifyWorkflowURL(), bytes.NewBuffer(jsonData))
  1492. if err != nil {
  1493. c.Data["json"] = map[string]interface{}{
  1494. "statusCode": 500,
  1495. "error": "创建请求失败: " + err.Error(),
  1496. }
  1497. c.ServeJSON()
  1498. return
  1499. }
  1500. // 设置请求头
  1501. req.Header.Set("Authorization", "Bearer app-55CyO4lmDv1VeXK4QmFpt4ng")
  1502. req.Header.Set("Content-Type", "application/json")
  1503. // 发送请�?
  1504. client := &http.Client{Timeout: 30 * time.Second}
  1505. resp, err := client.Do(req)
  1506. if err != nil {
  1507. c.Data["json"] = map[string]interface{}{
  1508. "statusCode": 500,
  1509. "error": "请求失败: " + err.Error(),
  1510. }
  1511. c.ServeJSON()
  1512. return
  1513. }
  1514. defer resp.Body.Close()
  1515. // 读取响应
  1516. responseBody, err := io.ReadAll(resp.Body)
  1517. if err != nil {
  1518. c.Data["json"] = map[string]interface{}{
  1519. "statusCode": 500,
  1520. "error": "读取响应失败: " + err.Error(),
  1521. }
  1522. c.ServeJSON()
  1523. return
  1524. }
  1525. // 检查HTTP状态码
  1526. if resp.StatusCode != http.StatusOK {
  1527. c.Data["json"] = map[string]interface{}{
  1528. "statusCode": 500,
  1529. "error": fmt.Sprintf("API请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(responseBody)),
  1530. }
  1531. c.ServeJSON()
  1532. return
  1533. }
  1534. // 解析响应
  1535. var apiResponse map[string]interface{}
  1536. if err := json.Unmarshal(responseBody, &apiResponse); err != nil {
  1537. c.Data["json"] = map[string]interface{}{
  1538. "statusCode": 500,
  1539. "error": "解析响应失败: " + err.Error(),
  1540. }
  1541. c.ServeJSON()
  1542. return
  1543. }
  1544. fmt.Println("apiResponse", apiResponse)
  1545. // 检查工作流状态
  1546. data, ok := apiResponse["data"].(map[string]interface{})
  1547. if !ok {
  1548. c.Data["json"] = map[string]interface{}{
  1549. "statusCode": 500,
  1550. "error": "响应格式错误:缺少data字段",
  1551. }
  1552. c.ServeJSON()
  1553. return
  1554. }
  1555. status, ok := data["status"].(string)
  1556. if !ok || status != "succeeded" {
  1557. errorMsg, _ := data["error"].(string)
  1558. c.Data["json"] = map[string]interface{}{
  1559. "statusCode": 500,
  1560. "error": fmt.Sprintf("工作流执行失败,状态: %s, 错误: %s", status, errorMsg),
  1561. }
  1562. c.ServeJSON()
  1563. return
  1564. }
  1565. // 提取results字段
  1566. outputs, ok := data["outputs"].(map[string]interface{})
  1567. if !ok {
  1568. c.Data["json"] = map[string]interface{}{
  1569. "statusCode": 500,
  1570. "error": "响应格式错误:缺少outputs字段",
  1571. }
  1572. c.ServeJSON()
  1573. return
  1574. }
  1575. // 优先:解析 outputs.text(先直接解析;失败时再做清洗重试)
  1576. var parsedFromText []interface{}
  1577. if textResult, ok := outputs["text"].(string); ok && textResult != "" {
  1578. // 1) 直接解析(适配已是标准JSON字符串的场景�?
  1579. if err := json.Unmarshal([]byte(strings.TrimSpace(textResult)), &parsedFromText); err == nil {
  1580. c.Data["json"] = map[string]interface{}{
  1581. "statusCode": 200,
  1582. "results": parsedFromText,
  1583. }
  1584. c.ServeJSON()
  1585. return
  1586. }
  1587. // 2) 清洗再解析(适配Python风格字符串场景)
  1588. cleaned := strings.ReplaceAll(textResult, "'", "\"")
  1589. cleaned = strings.ReplaceAll(cleaned, "None", "null")
  1590. cleaned = strings.ReplaceAll(cleaned, "\\xa0", " ")
  1591. cleaned = strings.ReplaceAll(cleaned, "\\u0026", "&")
  1592. if err := json.Unmarshal([]byte(strings.TrimSpace(cleaned)), &parsedFromText); err == nil {
  1593. c.Data["json"] = map[string]interface{}{
  1594. "statusCode": 200,
  1595. "results": parsedFromText,
  1596. }
  1597. c.ServeJSON()
  1598. return
  1599. }
  1600. }
  1601. // 回退:如果存�?outputs.json[0].results,则按旧逻辑返回(字符串化数组)
  1602. if jsonArray, ok := outputs["json"].([]interface{}); ok && len(jsonArray) > 0 {
  1603. if firstResult, ok := jsonArray[0].(map[string]interface{}); ok {
  1604. if results, ok := firstResult["results"].([]interface{}); ok {
  1605. resultsStr, err := json.Marshal(results)
  1606. if err != nil {
  1607. c.Data["json"] = map[string]interface{}{
  1608. "statusCode": 500,
  1609. "error": "结果序列化失败: " + err.Error(),
  1610. }
  1611. c.ServeJSON()
  1612. return
  1613. }
  1614. c.Data["json"] = map[string]interface{}{
  1615. "statusCode": 200,
  1616. "results": string(resultsStr),
  1617. }
  1618. c.ServeJSON()
  1619. return
  1620. }
  1621. }
  1622. }
  1623. c.Data["json"] = map[string]interface{}{
  1624. "statusCode": 500,
  1625. "error": "响应格式错误:无法从outputs.text或outputs.json解析results",
  1626. }
  1627. c.ServeJSON()
  1628. }
  1629. // 联网搜索结果存入AIMessage表
  1630. func (c *ChatController) SaveOnlineSearchResult() {
  1631. var requestData models.AIMessage
  1632. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1633. c.Data["json"] = map[string]interface{}{
  1634. "statusCode": 400,
  1635. "msg": "请求数据解析失败",
  1636. }
  1637. c.ServeJSON()
  1638. return
  1639. }
  1640. search_source := requestData.SearchSource
  1641. ai_conversation_id := requestData.AIConversationId
  1642. id := requestData.ID
  1643. tx := models.DB.Begin()
  1644. fmt.Println("search_source", search_source)
  1645. fmt.Println("ai_conversation_id", ai_conversation_id)
  1646. fmt.Println("ai_message_id", id)
  1647. // 更新AIMessage的search_source
  1648. if err := tx.Model(&models.AIMessage{}).Where("id = ?", id).Update("search_source", search_source).Error; err != nil {
  1649. tx.Rollback()
  1650. c.Data["json"] = map[string]interface{}{
  1651. "statusCode": 500,
  1652. "msg": "保存联网搜索结果失败",
  1653. }
  1654. c.ServeJSON()
  1655. return
  1656. }
  1657. // 更新AIConversation的updated_at
  1658. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1659. tx.Rollback()
  1660. c.Data["json"] = map[string]interface{}{
  1661. "statusCode": 500,
  1662. "msg": "更新编辑时间失败",
  1663. }
  1664. c.ServeJSON()
  1665. return
  1666. }
  1667. // 提交事务
  1668. if err := tx.Commit().Error; err != nil {
  1669. c.Data["json"] = map[string]interface{}{
  1670. "statusCode": 500,
  1671. "msg": "事务提交失败",
  1672. }
  1673. c.ServeJSON()
  1674. return
  1675. }
  1676. c.Data["json"] = map[string]interface{}{
  1677. "statusCode": 200,
  1678. "msg": "success",
  1679. }
  1680. c.ServeJSON()
  1681. }
  1682. // 意图识别请求结构体(user_id从token中获取)
  1683. type IntentRecognitionRequest struct {
  1684. Message string `json:"message"`
  1685. AIConversationId uint64 `json:"ai_conversation_id"`
  1686. BusinessType int `json:"business_type"`
  1687. }
  1688. // 意图识别模型,用于识别用户意图
  1689. func (c *ChatController) IntentRecognition() {
  1690. // 从token中获取用户信息
  1691. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  1692. if err != nil {
  1693. c.Data["json"] = map[string]interface{}{
  1694. "statusCode": 401,
  1695. "msg": "获取用户信息失败: " + err.Error(),
  1696. }
  1697. c.ServeJSON()
  1698. return
  1699. }
  1700. user_id := uint64(userInfo.ID)
  1701. if user_id == 0 {
  1702. user_id = 1
  1703. }
  1704. // 从请求体获取消息
  1705. var requestData IntentRecognitionRequest
  1706. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1707. c.Data["json"] = map[string]interface{}{
  1708. "statusCode": 400,
  1709. "msg": "请求数据解析失败",
  1710. }
  1711. c.ServeJSON()
  1712. return
  1713. }
  1714. fmt.Println("意图识别请求数据:", requestData)
  1715. userMessage := requestData.Message
  1716. ai_conversation_id := requestData.AIConversationId
  1717. business_type := requestData.BusinessType
  1718. // 复用意图识别提示词
  1719. prompt := `
  1720. `
  1721. // 调用模型
  1722. reply, err := c.sendQwen3Message(prompt, false)
  1723. if err != nil {
  1724. c.Data["json"] = map[string]interface{}{
  1725. "statusCode": 500,
  1726. "msg": "意图识别模型调用失败: " + err.Error(),
  1727. }
  1728. c.ServeJSON()
  1729. return
  1730. }
  1731. // 清洗与解析
  1732. cleanReply := strings.TrimSpace(reply)
  1733. cleanReply = strings.TrimPrefix(cleanReply, "```json")
  1734. cleanReply = strings.TrimPrefix(cleanReply, "```")
  1735. cleanReply = strings.TrimSuffix(cleanReply, "```")
  1736. cleanReply = strings.TrimSpace(cleanReply)
  1737. var aiResponse map[string]interface{}
  1738. if err := json.Unmarshal([]byte(cleanReply), &aiResponse); err != nil {
  1739. // 解析失败:将文本包装为标准结构返回
  1740. aiResponse = map[string]interface{}{
  1741. "intent": "faq",
  1742. "confidence": 0.5,
  1743. "search_queries": []string{userMessage},
  1744. "direct_answer": reply,
  1745. }
  1746. }
  1747. fmt.Println("aiResponse:", aiResponse)
  1748. // 获取意图类型
  1749. intent, ok := aiResponse["intent"].(string)
  1750. if !ok {
  1751. intent = "faq"
  1752. }
  1753. // 根据意图类型处理数据库操作
  1754. if intent != "query_knowledge_base" {
  1755. // 对于greeting和faq类型,需要保存到数据库
  1756. tx := models.DB.Begin()
  1757. // 如果ai_conversation_id为0,新建对话
  1758. if ai_conversation_id == 0 {
  1759. ai_conversation := models.AIConversation{
  1760. UserId: user_id,
  1761. Content: userMessage,
  1762. BusinessType: business_type,
  1763. }
  1764. if err := tx.Create(&ai_conversation).Error; err != nil {
  1765. tx.Rollback()
  1766. c.Data["json"] = map[string]interface{}{
  1767. "statusCode": 500,
  1768. "msg": "新建对话失败: " + err.Error(),
  1769. }
  1770. c.ServeJSON()
  1771. return
  1772. }
  1773. ai_conversation_id = uint64(ai_conversation.ID)
  1774. }
  1775. // 保存用户消息
  1776. ai_message := models.AIMessage{
  1777. UserId: user_id,
  1778. Content: userMessage,
  1779. Type: "user",
  1780. AIConversationId: ai_conversation_id,
  1781. }
  1782. if err := tx.Create(&ai_message).Error; err != nil {
  1783. tx.Rollback()
  1784. c.Data["json"] = map[string]interface{}{
  1785. "statusCode": 500,
  1786. "msg": "新建消息失败: " + err.Error(),
  1787. }
  1788. c.ServeJSON()
  1789. return
  1790. }
  1791. // 获取direct_answer
  1792. directAnswer := ""
  1793. if directAnswerValue, exists := aiResponse["direct_answer"].(string); exists {
  1794. directAnswer = directAnswerValue
  1795. } else {
  1796. // 如果没有direct_answer字段,使用AI的原始回复
  1797. directAnswer = reply
  1798. }
  1799. // 保存AI回复
  1800. ai_reply := models.AIMessage{
  1801. UserId: user_id,
  1802. Content: directAnswer,
  1803. Type: "ai",
  1804. AIConversationId: ai_conversation_id,
  1805. PrevUserId: uint64(ai_message.ID),
  1806. }
  1807. if err := tx.Create(&ai_reply).Error; err != nil {
  1808. tx.Rollback()
  1809. c.Data["json"] = map[string]interface{}{
  1810. "statusCode": 500,
  1811. "msg": "新建AI回复失败: " + err.Error(),
  1812. }
  1813. c.ServeJSON()
  1814. return
  1815. }
  1816. // 更新AIConversation编辑时间
  1817. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1818. tx.Rollback()
  1819. c.Data["json"] = map[string]interface{}{
  1820. "statusCode": 500,
  1821. "msg": "更新编辑时间失败: " + err.Error(),
  1822. }
  1823. c.ServeJSON()
  1824. return
  1825. }
  1826. tx.Commit()
  1827. // 返回成功响应
  1828. c.Data["json"] = map[string]interface{}{
  1829. "statusCode": 200,
  1830. "msg": "success",
  1831. "data": map[string]interface{}{
  1832. "intent_result": aiResponse,
  1833. "direct_answer": directAnswer,
  1834. "ai_conversation_id": ai_conversation_id,
  1835. "ai_message_id": ai_reply.ID,
  1836. "is_online_search": 0, // 不需要联网搜索
  1837. },
  1838. }
  1839. } else {
  1840. // 对于query_knowledge_base类型,只返回意图识别结果
  1841. c.Data["json"] = map[string]interface{}{
  1842. "statusCode": 200,
  1843. "msg": "success",
  1844. "data": map[string]interface{}{
  1845. "intent_result": aiResponse,
  1846. "is_online_search": 1, // 需要联网搜索
  1847. },
  1848. }
  1849. }
  1850. c.ServeJSON()
  1851. }
  1852. // 获取chromadb的文档
  1853. func (c *ChatController) GetChromaDBDocument() {
  1854. // 从GET参数获取消息
  1855. userMessage := c.GetString("message")
  1856. // 构建搜索请求
  1857. searchRequest := map[string]interface{}{
  1858. "query": userMessage,
  1859. "n_results": 25, // 返回25个结果
  1860. }
  1861. requestBody, err := json.Marshal(searchRequest)
  1862. if err != nil {
  1863. c.Data["json"] = map[string]interface{}{
  1864. "statusCode": 500,
  1865. "msg": "构建搜索请求失败: " + err.Error(),
  1866. }
  1867. c.ServeJSON()
  1868. return
  1869. }
  1870. // 从配置文件中读取搜索API地址
  1871. searchAPIURL, err := web.AppConfig.String("search_api_url")
  1872. if err != nil || searchAPIURL == "" {
  1873. c.Data["json"] = map[string]interface{}{
  1874. "statusCode": 500,
  1875. "msg": "配置文件中未找到search_api_url",
  1876. }
  1877. c.ServeJSON()
  1878. return
  1879. }
  1880. // 发送HTTP请求到Chroma搜索服务
  1881. req, err := http.NewRequest("POST", searchAPIURL, bytes.NewBuffer(requestBody))
  1882. if err != nil {
  1883. c.Data["json"] = map[string]interface{}{
  1884. "statusCode": 500,
  1885. "msg": "创建搜索请求失败: " + err.Error(),
  1886. }
  1887. c.ServeJSON()
  1888. return
  1889. }
  1890. req.Header.Set("Content-Type", "application/json")
  1891. client := &http.Client{Timeout: 30 * time.Second}
  1892. resp, err := client.Do(req)
  1893. if err != nil {
  1894. c.Data["json"] = map[string]interface{}{
  1895. "statusCode": 500,
  1896. "msg": "搜索请求失败: " + err.Error(),
  1897. }
  1898. c.ServeJSON()
  1899. return
  1900. }
  1901. defer resp.Body.Close()
  1902. responseBody, err := io.ReadAll(resp.Body)
  1903. if err != nil {
  1904. c.Data["json"] = map[string]interface{}{
  1905. "statusCode": 500,
  1906. "msg": "读取搜索响应失败: " + err.Error(),
  1907. }
  1908. c.ServeJSON()
  1909. return
  1910. }
  1911. if resp.StatusCode != http.StatusOK {
  1912. c.Data["json"] = map[string]interface{}{
  1913. "statusCode": 500,
  1914. "msg": fmt.Sprintf("搜索API错误: 状态码 %d", resp.StatusCode),
  1915. }
  1916. c.ServeJSON()
  1917. return
  1918. }
  1919. // 解析搜索响应
  1920. var searchResponse map[string]interface{}
  1921. if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
  1922. c.Data["json"] = map[string]interface{}{
  1923. "statusCode": 500,
  1924. "msg": "解析搜索响应失败: " + err.Error(),
  1925. }
  1926. c.ServeJSON()
  1927. return
  1928. }
  1929. // 检查响应状态
  1930. status, ok := searchResponse["status"].(string)
  1931. if !ok || status != "success" {
  1932. message, _ := searchResponse["message"].(string)
  1933. c.Data["json"] = map[string]interface{}{
  1934. "statusCode": 500,
  1935. "msg": fmt.Sprintf("搜索失败: %s", message),
  1936. }
  1937. c.ServeJSON()
  1938. return
  1939. }
  1940. // 获取搜索结果
  1941. results, ok := searchResponse["results"].([]interface{})
  1942. if !ok || len(results) == 0 {
  1943. c.Data["json"] = map[string]interface{}{
  1944. "statusCode": 200,
  1945. "msg": "success",
  1946. "data": map[string]interface{}{
  1947. "reply": "未找到相关文档",
  1948. },
  1949. }
  1950. c.ServeJSON()
  1951. return
  1952. }
  1953. // 将搜索结果转换为JSON字符串作为上下文
  1954. contextJSON, err := json.Marshal(results)
  1955. if err != nil {
  1956. c.Data["json"] = map[string]interface{}{
  1957. "statusCode": 500,
  1958. "msg": "处理搜索结果失败: " + err.Error(),
  1959. }
  1960. c.ServeJSON()
  1961. return
  1962. }
  1963. fmt.Println("contextJSON:", string(contextJSON))
  1964. // 返回成功响应
  1965. c.Data["json"] = map[string]interface{}{
  1966. "statusCode": 200,
  1967. "msg": "success",
  1968. "data": map[string]interface{}{
  1969. "reply": string(contextJSON),
  1970. },
  1971. }
  1972. c.ServeJSON()
  1973. }
  1974. // 获取chromadb的函数
  1975. func (c *ChatController) getChromaDBDocumentFunction(userMessage string) string {
  1976. // 构建搜索请求
  1977. searchRequest := map[string]interface{}{
  1978. "query": userMessage,
  1979. "n_results": 25, // 返回25个结果
  1980. }
  1981. requestBody, err := json.Marshal(searchRequest)
  1982. if err != nil {
  1983. return "构建搜索请求失败: " + err.Error()
  1984. }
  1985. // 从配置文件中读取搜索API地址
  1986. searchAPIURL, err := web.AppConfig.String("search_api_url")
  1987. if err != nil || searchAPIURL == "" {
  1988. return "配置文件中未找到search_api_url"
  1989. }
  1990. // 发送HTTP请求到Chroma搜索服务
  1991. req, err := http.NewRequest("POST", searchAPIURL, bytes.NewBuffer(requestBody))
  1992. if err != nil {
  1993. return "构建搜索请求失败: " + err.Error()
  1994. }
  1995. req.Header.Set("Content-Type", "application/json")
  1996. client := &http.Client{Timeout: 30 * time.Second}
  1997. resp, err := client.Do(req)
  1998. if err != nil {
  1999. return "搜索请求失败: " + err.Error()
  2000. }
  2001. defer resp.Body.Close()
  2002. responseBody, err := io.ReadAll(resp.Body)
  2003. if err != nil {
  2004. return "读取搜索响应失败: " + err.Error()
  2005. }
  2006. if resp.StatusCode != http.StatusOK {
  2007. return "搜索API错误: " + resp.Status
  2008. }
  2009. // 解析搜索响应
  2010. var searchResponse map[string]interface{}
  2011. if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
  2012. return "解析搜索响应失败: " + err.Error()
  2013. }
  2014. // 检查响应状态
  2015. status, ok := searchResponse["status"].(string)
  2016. if !ok || status != "success" {
  2017. message, _ := searchResponse["message"].(string)
  2018. return fmt.Sprintf("搜索失败: %s", message)
  2019. }
  2020. // 获取搜索结果
  2021. results, ok := searchResponse["results"].([]interface{})
  2022. if !ok || len(results) == 0 {
  2023. return "未找到相关文档"
  2024. }
  2025. // 将搜索结果转换为JSON字符串作为上下文
  2026. contextJSON, err := json.Marshal(results)
  2027. if err != nil {
  2028. return "处理搜索结果失败: " + err.Error()
  2029. }
  2030. fmt.Println("contextJSON:", string(contextJSON))
  2031. return string(contextJSON)
  2032. }
  2033. // getOnlineSearchContent 获取联网搜索内容
  2034. func (c *ChatController) getOnlineSearchContent(userMessage string) string {
  2035. // 在关键词前加入检索策略提示词:
  2036. // 1) 若用户意图属于土木工程/路桥隧轨/施工安全等相关领域,则直接按该意图搜索
  2037. // 2) 若与上述领域无关,则根据用户表达猜测一个最可能的土木工程相关问题再进行搜索
  2038. combinedKeywords := fmt.Sprintf("【搜索策略】先识别用户意图:若问题属于土木工程/路桥隧轨/施工安全等领域,则按此意图联网搜索;若非上述领域,请根据用户表达猜测一个最可能的土木工程相关问题并据此搜索。确保检索聚焦专业资料。确保回复字数在20字内。【用户问题】%s", userMessage)
  2039. //给AI发送消息
  2040. reply, err := c.sendQwen3Message(combinedKeywords, false)
  2041. if err != nil {
  2042. fmt.Printf("联网搜索AI调用失败: %v\n", err)
  2043. return ""
  2044. }
  2045. fmt.Println("联网搜索回复:", reply)
  2046. // 构建请求体
  2047. requestBody := map[string]interface{}{
  2048. "workflow_id": "4wfh1PPDderMtCeb",
  2049. "inputs": map[string]interface{}{
  2050. "keywords": reply,
  2051. "num": 10, // 默认参数
  2052. "max_text_len": 150,
  2053. },
  2054. "response_mode": "blocking", // 默认参数
  2055. "user": "user_001",
  2056. }
  2057. // 序列化请求体
  2058. jsonData, err := json.Marshal(requestBody)
  2059. if err != nil {
  2060. fmt.Printf("联网搜索请求参数序列化失败: %v\n", err)
  2061. return ""
  2062. }
  2063. // 创建HTTP请求
  2064. req, err := http.NewRequest("POST", utils.GetDifyWorkflowURL(), bytes.NewBuffer(jsonData))
  2065. if err != nil {
  2066. fmt.Printf("联网搜索创建请求失败: %v\n", err)
  2067. return ""
  2068. }
  2069. // 设置请求头
  2070. req.Header.Set("Authorization", "Bearer app-55CyO4lmDv1VeXK4QmFpt4ng")
  2071. req.Header.Set("Content-Type", "application/json")
  2072. // 发送请求
  2073. client := &http.Client{Timeout: 30 * time.Second}
  2074. resp, err := client.Do(req)
  2075. if err != nil {
  2076. fmt.Printf("联网搜索请求失败: %v\n", err)
  2077. return ""
  2078. }
  2079. defer resp.Body.Close()
  2080. // 读取响应
  2081. responseBody, err := io.ReadAll(resp.Body)
  2082. if err != nil {
  2083. fmt.Printf("联网搜索读取响应失败: %v\n", err)
  2084. return ""
  2085. }
  2086. // 检查HTTP状态码
  2087. if resp.StatusCode != http.StatusOK {
  2088. fmt.Printf("联网搜索API请求失败,状态码: %d, 响应: %s\n", resp.StatusCode, string(responseBody))
  2089. return ""
  2090. }
  2091. // 解析响应
  2092. var apiResponse map[string]interface{}
  2093. if err := json.Unmarshal(responseBody, &apiResponse); err != nil {
  2094. fmt.Printf("联网搜索解析响应失败: %v\n", err)
  2095. return ""
  2096. }
  2097. fmt.Println("联网搜索apiResponse", apiResponse)
  2098. // 检查工作流状态
  2099. data, ok := apiResponse["data"].(map[string]interface{})
  2100. if !ok {
  2101. fmt.Printf("联网搜索响应格式错误:缺少data字段\n")
  2102. return ""
  2103. }
  2104. status, ok := data["status"].(string)
  2105. if !ok || status != "succeeded" {
  2106. errorMsg, _ := data["error"].(string)
  2107. fmt.Printf("联网搜索工作流执行失败,状态: %s, 错误: %s\n", status, errorMsg)
  2108. return ""
  2109. }
  2110. // 提取results字段
  2111. outputs, ok := data["outputs"].(map[string]interface{})
  2112. if !ok {
  2113. fmt.Printf("联网搜索响应格式错误:缺少outputs字段\n")
  2114. return ""
  2115. }
  2116. // 优先:解析 outputs.text(先直接解析;失败时再做清洗重试)
  2117. var parsedFromText []interface{}
  2118. if textResult, ok := outputs["text"].(string); ok && textResult != "" {
  2119. // 1) 直接解析(适配已是标准JSON字符串的场景)
  2120. if err := json.Unmarshal([]byte(strings.TrimSpace(textResult)), &parsedFromText); err == nil {
  2121. // 将联网搜索结果转换为字符串格式
  2122. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2123. for i, result := range parsedFromText {
  2124. if resultMap, ok := result.(map[string]interface{}); ok {
  2125. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2126. }
  2127. }
  2128. return onlineSearchStr
  2129. }
  2130. // 2) 清洗再解析(适配Python风格字符串场景)
  2131. cleaned := strings.ReplaceAll(textResult, "'", "\"")
  2132. cleaned = strings.ReplaceAll(cleaned, "None", "null")
  2133. cleaned = strings.ReplaceAll(cleaned, "\\xa0", " ")
  2134. cleaned = strings.ReplaceAll(cleaned, "\\u0026", "&")
  2135. if err := json.Unmarshal([]byte(strings.TrimSpace(cleaned)), &parsedFromText); err == nil {
  2136. // 将联网搜索结果转换为字符串格式
  2137. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2138. for i, result := range parsedFromText {
  2139. if resultMap, ok := result.(map[string]interface{}); ok {
  2140. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2141. }
  2142. }
  2143. return onlineSearchStr
  2144. }
  2145. }
  2146. // 回退:如果存在outputs.json[0].results,则按旧逻辑返回(字符串化数组)
  2147. if jsonArray, ok := outputs["json"].([]interface{}); ok && len(jsonArray) > 0 {
  2148. if firstResult, ok := jsonArray[0].(map[string]interface{}); ok {
  2149. if results, ok := firstResult["results"].([]interface{}); ok {
  2150. // 将联网搜索结果转换为字符串格式
  2151. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2152. for i, result := range results {
  2153. if resultMap, ok := result.(map[string]interface{}); ok {
  2154. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2155. }
  2156. }
  2157. return onlineSearchStr
  2158. }
  2159. }
  2160. }
  2161. fmt.Printf("联网搜索响应格式错误:无法从outputs.text或outputs.json解析results\n")
  2162. return ""
  2163. }