chat.go 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  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. promptWithRules := fmt.Sprintf(`你是蜀道安全管理AI智能助手,请根据用户的问题生成3个相关的后续问题建议(猜你想问)。
  1193. ## 用户问题
  1194. %s
  1195. ## 生成问题规则(最高优先级)
  1196. 1. 严禁生成任何政治敏感信息,包含重要国家领导人,重要国际事件等
  1197. 2. 严禁在生成的问题中包含人名信息,任何人名都不行
  1198. 3. 严禁生成色情敏感信息
  1199. 4. 严禁生成超长文本,最多只能30个字
  1200. ## 你的回答(仅输出3个问题,每行一个,或返回空)`, userMessage)
  1201. >>>>>>> origin/dev
  1202. promptWithRules := fmt.Sprintf(`你是蜀道安全管理AI智能助手,请根据用户的问题生成3个相关的后续问题建议(猜你想问)。
  1203. ## 用户问题
  1204. %s
  1205. ## 生成问题规则(最高优先级)
  1206. 1. 严禁生成任何政治敏感信息,包含重要国家领导人,重要国际事件等
  1207. 2. 严禁在生成的问题中包含人名信息,任何人名都不行
  1208. 3. 严禁生成色情敏感信息
  1209. 4. 严禁生成超长文本,最多只能30个字
  1210. ## 你的回答(仅输出3个问题,每行一个,或返回空)`, userMessage)
  1211. =======
  1212. promptWithRules := fmt.Sprintf(`你是蜀道安全管理AI智能助手,请根据用户的问题生成3个相关的后续问题建议(猜你想问)。
  1213. ## 用户问题
  1214. %s
  1215. ## 生成问题规则(最高优先级)
  1216. 1. 严禁生成任何政治敏感信息,包含重要国家领导人,重要国际事件等
  1217. 2. 严禁在生成的问题中包含人名信息,任何人名都不行
  1218. 3. 严禁生成色情敏感信息
  1219. 4. 严禁生成超长文本,最多只能30个字
  1220. ## 你的回答(仅输出3个问题,每行一个,或返回空)`, userMessage)
  1221. >>>>>>> origin/dev
  1222. // 使用阿里大模型替代DeepSeek
  1223. reply, err := c.sendQwen3Message(promptWithRules, false)
  1224. if err != nil {
  1225. c.Data["json"] = map[string]interface{}{
  1226. "statusCode": 500,
  1227. "msg": "阿里大模型调用失败: " + err.Error(),
  1228. }
  1229. c.ServeJSON()
  1230. return
  1231. }
  1232. ai_message_id := requestData.AIMessageId
  1233. // fmt.Println("猜你想问的ai_message_id", ai_message_id)
  1234. tx := models.DB.Begin()
  1235. if err := tx.Model(&models.AIMessage{}).Where("id = ?", ai_message_id).Update("guess_you_want", reply).Error; err != nil {
  1236. tx.Rollback()
  1237. c.Data["json"] = map[string]interface{}{
  1238. "statusCode": 500,
  1239. "msg": "保存猜你想问失败",
  1240. }
  1241. }
  1242. tx.Commit()
  1243. // 返回成功响应(保持与原来相同的格式)
  1244. c.Data["json"] = map[string]interface{}{
  1245. "statusCode": 200,
  1246. "msg": "success",
  1247. "data": map[string]interface{}{
  1248. "reply": reply,
  1249. },
  1250. }
  1251. fmt.Println("猜你想问:", reply)
  1252. c.ServeJSON()
  1253. }
  1254. // 用户在输入框中每输入一个字,就调用一次阿里大模型返回推荐问题
  1255. func (c *ChatController) GetUserRecommendQuestion() {
  1256. // 从token中获取用户信息(GET请求也需要token)
  1257. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  1258. if err != nil {
  1259. c.Data["json"] = map[string]interface{}{
  1260. "statusCode": 401,
  1261. "msg": "获取用户信息失败: " + err.Error(),
  1262. }
  1263. c.ServeJSON()
  1264. return
  1265. }
  1266. user_id := int64(userInfo.ID)
  1267. if user_id == 0 {
  1268. user_id = 1
  1269. }
  1270. userMessage1 := c.GetString("user_message")
  1271. // 直接从QA表中模糊查询问题
  1272. var qaList []models.QA
  1273. models.DB.Model(&models.QA{}).Where("question LIKE ? AND is_deleted = ?", "%"+userMessage1+"%", 0).Limit(10).Find(&qaList)
  1274. if len(qaList) == 0 {
  1275. c.Data["json"] = map[string]interface{}{
  1276. "statusCode": 200,
  1277. "msg": "success",
  1278. }
  1279. c.ServeJSON()
  1280. return
  1281. }
  1282. // 提取问题列表
  1283. var questions []string
  1284. for _, qa := range qaList {
  1285. questions = append(questions, qa.Question)
  1286. }
  1287. c.Data["json"] = map[string]interface{}{
  1288. "statusCode": 200,
  1289. "msg": "success",
  1290. "data": map[string]interface{}{
  1291. "questions": questions,
  1292. },
  1293. }
  1294. c.ServeJSON()
  1295. }
  1296. // 用户传文件名取数据库寻找链接(使用编辑距离算法匹配最相似的文件名)
  1297. func (c *ChatController) GetFileLink() {
  1298. fileName := c.GetString("fileName")
  1299. fmt.Println("查询文件名:", fileName)
  1300. // 获取所有未删除的文件记录
  1301. var indexFiles []models.IndexFile
  1302. models.DB.Model(&models.IndexFile{}).Where("is_deleted = ?", 0).Find(&indexFiles)
  1303. if len(indexFiles) == 0 {
  1304. c.Data["json"] = map[string]interface{}{
  1305. "statusCode": 404,
  1306. "msg": "数据库中没有找到任何文件",
  1307. "data": "",
  1308. }
  1309. c.ServeJSON()
  1310. return
  1311. }
  1312. // 提取所有文件名作为候选列表
  1313. var candidates []string
  1314. for _, file := range indexFiles {
  1315. candidates = append(candidates, file.FileName)
  1316. }
  1317. // 使用编辑距离算法找到最相似的文件名
  1318. bestMatch, bestScore := utils.FindBestMatch(fileName, candidates)
  1319. fmt.Printf("最佳匹配: %s (相似度: %.3f)\n", bestMatch, bestScore)
  1320. // 找到对应的文件记录
  1321. var matchedFile models.IndexFile
  1322. for _, file := range indexFiles {
  1323. if file.FileName == bestMatch {
  1324. matchedFile = file
  1325. break
  1326. }
  1327. }
  1328. fmt.Println("匹配的文件记录:", matchedFile)
  1329. fmt.Println("文件链接:", matchedFile.FilePath)
  1330. // 如果相似度太低,可以设置阈值
  1331. threshold := 0.3 // 相似度阈值,可以根据需要调整
  1332. if bestScore < threshold {
  1333. c.Data["json"] = map[string]interface{}{
  1334. "statusCode": 200,
  1335. "msg": fmt.Sprintf("没有找到相似度 >= %.1f 的文件,最佳匹配相似度: %.3f", threshold, bestScore),
  1336. "data": "",
  1337. "bestMatch": bestMatch,
  1338. "bestScore": bestScore,
  1339. }
  1340. c.ServeJSON()
  1341. return
  1342. }
  1343. // 检查文件路径是否已经是代理URL格式,如果不是则转换为代理URL
  1344. var fileURL string
  1345. if matchedFile.FilePath != "" {
  1346. if !strings.Contains(matchedFile.FilePath, "/apiv1/oss/parse/?url=") {
  1347. fileURL = utils.GetProxyURL(matchedFile.FilePath)
  1348. } else {
  1349. fileURL = matchedFile.FilePath
  1350. }
  1351. }
  1352. // 返回代理URL
  1353. fmt.Println("代理URL:", fileURL)
  1354. c.Data["json"] = map[string]interface{}{
  1355. "statusCode": 200,
  1356. "msg": "success",
  1357. "data": fileURL,
  1358. "bestMatch": bestMatch,
  1359. "bestScore": bestScore,
  1360. "fileName": fileName,
  1361. }
  1362. c.ServeJSON()
  1363. }
  1364. // 删除历史记录
  1365. type DeleteHistoryRecordRequest struct {
  1366. AIConversationID uint64 `json:"ai_conversation_id"`
  1367. }
  1368. func (c *ChatController) DeleteHistoryRecord() {
  1369. var requestData DeleteHistoryRecordRequest
  1370. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1371. c.Data["json"] = map[string]interface{}{
  1372. "statusCode": 400,
  1373. "msg": "请求数据解析失败",
  1374. }
  1375. c.ServeJSON()
  1376. return
  1377. }
  1378. ai_conversation_id := requestData.AIConversationID
  1379. tx := models.DB.Begin()
  1380. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("is_deleted", 1).Error; err != nil {
  1381. tx.Rollback()
  1382. c.Data["json"] = map[string]interface{}{
  1383. "statusCode": 500,
  1384. "msg": "删除历史记录失败",
  1385. }
  1386. }
  1387. tx.Commit()
  1388. c.Data["json"] = map[string]interface{}{
  1389. "statusCode": 200,
  1390. "msg": "success",
  1391. }
  1392. c.ServeJSON()
  1393. }
  1394. // 删除隐患识别的历史记录
  1395. type DeleteRecognitionRecordRequest struct {
  1396. RecognitionRecordID uint64 `json:"recognition_record_id"`
  1397. }
  1398. func (c *ChatController) DeleteRecognitionRecord() {
  1399. var requestData DeleteRecognitionRecordRequest
  1400. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1401. c.Data["json"] = map[string]interface{}{
  1402. "statusCode": 400,
  1403. "msg": "请求数据解析失败",
  1404. }
  1405. c.ServeJSON()
  1406. return
  1407. }
  1408. recognition_record_id := requestData.RecognitionRecordID
  1409. tx := models.DB.Begin()
  1410. if err := tx.Model(&models.RecognitionRecord{}).Where("id = ?", recognition_record_id).Update("is_deleted", 1).Error; err != nil {
  1411. tx.Rollback()
  1412. c.Data["json"] = map[string]interface{}{
  1413. "statusCode": 500,
  1414. "msg": "删除隐患识别的历史记录失败",
  1415. }
  1416. c.ServeJSON()
  1417. return
  1418. }
  1419. tx.Commit()
  1420. c.Data["json"] = map[string]interface{}{
  1421. "statusCode": 200,
  1422. "msg": "success",
  1423. }
  1424. c.ServeJSON()
  1425. }
  1426. // AI写作保存编辑文档内容
  1427. func (c *ChatController) SaveEditDocument() {
  1428. var requestData models.AIMessage
  1429. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1430. c.Data["json"] = map[string]interface{}{
  1431. "statusCode": 400,
  1432. "msg": "请求数据解析失败",
  1433. }
  1434. }
  1435. ai_conversation_id := requestData.AIConversationId
  1436. fmt.Println("ai_conversation_id", ai_conversation_id)
  1437. content := requestData.Content
  1438. tx := models.DB.Begin()
  1439. 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 {
  1440. tx.Rollback()
  1441. c.Data["json"] = map[string]interface{}{
  1442. "statusCode": 500,
  1443. "msg": "保存编辑文档内容失败",
  1444. }
  1445. }
  1446. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1447. tx.Rollback()
  1448. c.Data["json"] = map[string]interface{}{
  1449. "statusCode": 500,
  1450. "msg": "更新编辑时间失败",
  1451. }
  1452. }
  1453. tx.Commit()
  1454. c.Data["json"] = map[string]interface{}{
  1455. "statusCode": 200,
  1456. "msg": "success",
  1457. "data": content,
  1458. }
  1459. c.ServeJSON()
  1460. }
  1461. // 联网搜索
  1462. func (c *ChatController) OnlineSearch() {
  1463. // 获取请求参数
  1464. keywords := c.GetString("keywords")
  1465. // 参数验证
  1466. if keywords == "" {
  1467. c.Data["json"] = map[string]interface{}{
  1468. "statusCode": 400,
  1469. "error": "参数错误:keywords不能为空",
  1470. }
  1471. c.ServeJSON()
  1472. return
  1473. }
  1474. // 在关键词前加入检索策略提示词:
  1475. // 1) 若用户意图属于土木工程/路桥隧轨/施工安全等相关领域,则直接按该意图搜索
  1476. // 2) 若与上述领域无关,则根据用户表达猜测一个最可能的土木工程相关问题再进行搜索
  1477. combinedKeywords := fmt.Sprintf("【搜索策略】先识别用户意图:若问题属于土木工程/路桥隧轨/施工安全等领域,则按此意图联网搜索;若非上述领域,请根据用户表达猜测一个最可能的土木工程相关问题并据此搜索。确保检索聚焦专业资料。确保回复字数在20字内。【用户问题】%s", keywords)
  1478. //给AI发送消息
  1479. reply, err := c.sendQwen3Message(combinedKeywords, false)
  1480. if err != nil {
  1481. c.Data["json"] = map[string]interface{}{
  1482. "statusCode": 500,
  1483. "msg": "阿里大模型调用失败: " + err.Error(),
  1484. }
  1485. c.ServeJSON()
  1486. return
  1487. }
  1488. fmt.Println("联网搜索回复:", reply)
  1489. // 构建请求体
  1490. requestBody := map[string]interface{}{
  1491. "workflow_id": "4wfh1PPDderMtCeb",
  1492. "inputs": map[string]interface{}{
  1493. "keywords": reply,
  1494. "num": 10, // 默认参数
  1495. "max_text_len": 150,
  1496. },
  1497. "response_mode": "blocking", // 默认参数
  1498. "user": "user_001",
  1499. }
  1500. // 序列化请求体
  1501. jsonData, err := json.Marshal(requestBody)
  1502. if err != nil {
  1503. c.Data["json"] = map[string]interface{}{
  1504. "statusCode": 500,
  1505. "error": "请求参数序列化失败: " + err.Error(),
  1506. }
  1507. c.ServeJSON()
  1508. return
  1509. }
  1510. // 创建HTTP请求
  1511. req, err := http.NewRequest("POST", utils.GetDifyWorkflowURL(), bytes.NewBuffer(jsonData))
  1512. if err != nil {
  1513. c.Data["json"] = map[string]interface{}{
  1514. "statusCode": 500,
  1515. "error": "创建请求失败: " + err.Error(),
  1516. }
  1517. c.ServeJSON()
  1518. return
  1519. }
  1520. // 设置请求头
  1521. req.Header.Set("Authorization", "Bearer app-55CyO4lmDv1VeXK4QmFpt4ng")
  1522. req.Header.Set("Content-Type", "application/json")
  1523. // 发送请�?
  1524. client := &http.Client{Timeout: 30 * time.Second}
  1525. resp, err := client.Do(req)
  1526. if err != nil {
  1527. c.Data["json"] = map[string]interface{}{
  1528. "statusCode": 500,
  1529. "error": "请求失败: " + err.Error(),
  1530. }
  1531. c.ServeJSON()
  1532. return
  1533. }
  1534. defer resp.Body.Close()
  1535. // 读取响应
  1536. responseBody, err := io.ReadAll(resp.Body)
  1537. if err != nil {
  1538. c.Data["json"] = map[string]interface{}{
  1539. "statusCode": 500,
  1540. "error": "读取响应失败: " + err.Error(),
  1541. }
  1542. c.ServeJSON()
  1543. return
  1544. }
  1545. // 检查HTTP状态码
  1546. if resp.StatusCode != http.StatusOK {
  1547. c.Data["json"] = map[string]interface{}{
  1548. "statusCode": 500,
  1549. "error": fmt.Sprintf("API请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(responseBody)),
  1550. }
  1551. c.ServeJSON()
  1552. return
  1553. }
  1554. // 解析响应
  1555. var apiResponse map[string]interface{}
  1556. if err := json.Unmarshal(responseBody, &apiResponse); err != nil {
  1557. c.Data["json"] = map[string]interface{}{
  1558. "statusCode": 500,
  1559. "error": "解析响应失败: " + err.Error(),
  1560. }
  1561. c.ServeJSON()
  1562. return
  1563. }
  1564. fmt.Println("apiResponse", apiResponse)
  1565. // 检查工作流状态
  1566. data, ok := apiResponse["data"].(map[string]interface{})
  1567. if !ok {
  1568. c.Data["json"] = map[string]interface{}{
  1569. "statusCode": 500,
  1570. "error": "响应格式错误:缺少data字段",
  1571. }
  1572. c.ServeJSON()
  1573. return
  1574. }
  1575. status, ok := data["status"].(string)
  1576. if !ok || status != "succeeded" {
  1577. errorMsg, _ := data["error"].(string)
  1578. c.Data["json"] = map[string]interface{}{
  1579. "statusCode": 500,
  1580. "error": fmt.Sprintf("工作流执行失败,状态: %s, 错误: %s", status, errorMsg),
  1581. }
  1582. c.ServeJSON()
  1583. return
  1584. }
  1585. // 提取results字段
  1586. outputs, ok := data["outputs"].(map[string]interface{})
  1587. if !ok {
  1588. c.Data["json"] = map[string]interface{}{
  1589. "statusCode": 500,
  1590. "error": "响应格式错误:缺少outputs字段",
  1591. }
  1592. c.ServeJSON()
  1593. return
  1594. }
  1595. // 优先:解析 outputs.text(先直接解析;失败时再做清洗重试)
  1596. var parsedFromText []interface{}
  1597. if textResult, ok := outputs["text"].(string); ok && textResult != "" {
  1598. // 1) 直接解析(适配已是标准JSON字符串的场景�?
  1599. if err := json.Unmarshal([]byte(strings.TrimSpace(textResult)), &parsedFromText); err == nil {
  1600. c.Data["json"] = map[string]interface{}{
  1601. "statusCode": 200,
  1602. "results": parsedFromText,
  1603. }
  1604. c.ServeJSON()
  1605. return
  1606. }
  1607. // 2) 清洗再解析(适配Python风格字符串场景)
  1608. cleaned := strings.ReplaceAll(textResult, "'", "\"")
  1609. cleaned = strings.ReplaceAll(cleaned, "None", "null")
  1610. cleaned = strings.ReplaceAll(cleaned, "\\xa0", " ")
  1611. cleaned = strings.ReplaceAll(cleaned, "\\u0026", "&")
  1612. if err := json.Unmarshal([]byte(strings.TrimSpace(cleaned)), &parsedFromText); err == nil {
  1613. c.Data["json"] = map[string]interface{}{
  1614. "statusCode": 200,
  1615. "results": parsedFromText,
  1616. }
  1617. c.ServeJSON()
  1618. return
  1619. }
  1620. }
  1621. // 回退:如果存�?outputs.json[0].results,则按旧逻辑返回(字符串化数组)
  1622. if jsonArray, ok := outputs["json"].([]interface{}); ok && len(jsonArray) > 0 {
  1623. if firstResult, ok := jsonArray[0].(map[string]interface{}); ok {
  1624. if results, ok := firstResult["results"].([]interface{}); ok {
  1625. resultsStr, err := json.Marshal(results)
  1626. if err != nil {
  1627. c.Data["json"] = map[string]interface{}{
  1628. "statusCode": 500,
  1629. "error": "结果序列化失败: " + err.Error(),
  1630. }
  1631. c.ServeJSON()
  1632. return
  1633. }
  1634. c.Data["json"] = map[string]interface{}{
  1635. "statusCode": 200,
  1636. "results": string(resultsStr),
  1637. }
  1638. c.ServeJSON()
  1639. return
  1640. }
  1641. }
  1642. }
  1643. c.Data["json"] = map[string]interface{}{
  1644. "statusCode": 500,
  1645. "error": "响应格式错误:无法从outputs.text或outputs.json解析results",
  1646. }
  1647. c.ServeJSON()
  1648. }
  1649. // 联网搜索结果存入AIMessage表
  1650. func (c *ChatController) SaveOnlineSearchResult() {
  1651. var requestData models.AIMessage
  1652. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1653. c.Data["json"] = map[string]interface{}{
  1654. "statusCode": 400,
  1655. "msg": "请求数据解析失败",
  1656. }
  1657. c.ServeJSON()
  1658. return
  1659. }
  1660. search_source := requestData.SearchSource
  1661. ai_conversation_id := requestData.AIConversationId
  1662. id := requestData.ID
  1663. tx := models.DB.Begin()
  1664. fmt.Println("search_source", search_source)
  1665. fmt.Println("ai_conversation_id", ai_conversation_id)
  1666. fmt.Println("ai_message_id", id)
  1667. // 更新AIMessage的search_source
  1668. if err := tx.Model(&models.AIMessage{}).Where("id = ?", id).Update("search_source", search_source).Error; err != nil {
  1669. tx.Rollback()
  1670. c.Data["json"] = map[string]interface{}{
  1671. "statusCode": 500,
  1672. "msg": "保存联网搜索结果失败",
  1673. }
  1674. c.ServeJSON()
  1675. return
  1676. }
  1677. // 更新AIConversation的updated_at
  1678. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1679. tx.Rollback()
  1680. c.Data["json"] = map[string]interface{}{
  1681. "statusCode": 500,
  1682. "msg": "更新编辑时间失败",
  1683. }
  1684. c.ServeJSON()
  1685. return
  1686. }
  1687. // 提交事务
  1688. if err := tx.Commit().Error; err != nil {
  1689. c.Data["json"] = map[string]interface{}{
  1690. "statusCode": 500,
  1691. "msg": "事务提交失败",
  1692. }
  1693. c.ServeJSON()
  1694. return
  1695. }
  1696. c.Data["json"] = map[string]interface{}{
  1697. "statusCode": 200,
  1698. "msg": "success",
  1699. }
  1700. c.ServeJSON()
  1701. }
  1702. // 意图识别请求结构体(user_id从token中获取)
  1703. type IntentRecognitionRequest struct {
  1704. Message string `json:"message"`
  1705. AIConversationId uint64 `json:"ai_conversation_id"`
  1706. BusinessType int `json:"business_type"`
  1707. }
  1708. // 意图识别模型,用于识别用户意图
  1709. func (c *ChatController) IntentRecognition() {
  1710. // 从token中获取用户信息
  1711. userInfo, err := utils.GetUserInfoFromContext(c.Ctx.Input.GetData("userInfo"))
  1712. if err != nil {
  1713. c.Data["json"] = map[string]interface{}{
  1714. "statusCode": 401,
  1715. "msg": "获取用户信息失败: " + err.Error(),
  1716. }
  1717. c.ServeJSON()
  1718. return
  1719. }
  1720. user_id := uint64(userInfo.ID)
  1721. if user_id == 0 {
  1722. user_id = 1
  1723. }
  1724. // 从请求体获取消息
  1725. var requestData IntentRecognitionRequest
  1726. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
  1727. c.Data["json"] = map[string]interface{}{
  1728. "statusCode": 400,
  1729. "msg": "请求数据解析失败",
  1730. }
  1731. c.ServeJSON()
  1732. return
  1733. }
  1734. fmt.Println("意图识别请求数据:", requestData)
  1735. userMessage := requestData.Message
  1736. ai_conversation_id := requestData.AIConversationId
  1737. business_type := requestData.BusinessType
  1738. // 复用意图识别提示词
  1739. prompt := `
  1740. `
  1741. // 调用模型
  1742. reply, err := c.sendQwen3Message(prompt, false)
  1743. if err != nil {
  1744. c.Data["json"] = map[string]interface{}{
  1745. "statusCode": 500,
  1746. "msg": "意图识别模型调用失败: " + err.Error(),
  1747. }
  1748. c.ServeJSON()
  1749. return
  1750. }
  1751. // 清洗与解析
  1752. cleanReply := strings.TrimSpace(reply)
  1753. cleanReply = strings.TrimPrefix(cleanReply, "```json")
  1754. cleanReply = strings.TrimPrefix(cleanReply, "```")
  1755. cleanReply = strings.TrimSuffix(cleanReply, "```")
  1756. cleanReply = strings.TrimSpace(cleanReply)
  1757. var aiResponse map[string]interface{}
  1758. if err := json.Unmarshal([]byte(cleanReply), &aiResponse); err != nil {
  1759. // 解析失败:将文本包装为标准结构返回
  1760. aiResponse = map[string]interface{}{
  1761. "intent": "faq",
  1762. "confidence": 0.5,
  1763. "search_queries": []string{userMessage},
  1764. "direct_answer": reply,
  1765. }
  1766. }
  1767. fmt.Println("aiResponse:", aiResponse)
  1768. // 获取意图类型
  1769. intent, ok := aiResponse["intent"].(string)
  1770. if !ok {
  1771. intent = "faq"
  1772. }
  1773. // 根据意图类型处理数据库操作
  1774. if intent != "query_knowledge_base" {
  1775. // 对于greeting和faq类型,需要保存到数据库
  1776. tx := models.DB.Begin()
  1777. // 如果ai_conversation_id为0,新建对话
  1778. if ai_conversation_id == 0 {
  1779. ai_conversation := models.AIConversation{
  1780. UserId: user_id,
  1781. Content: userMessage,
  1782. BusinessType: business_type,
  1783. }
  1784. if err := tx.Create(&ai_conversation).Error; err != nil {
  1785. tx.Rollback()
  1786. c.Data["json"] = map[string]interface{}{
  1787. "statusCode": 500,
  1788. "msg": "新建对话失败: " + err.Error(),
  1789. }
  1790. c.ServeJSON()
  1791. return
  1792. }
  1793. ai_conversation_id = uint64(ai_conversation.ID)
  1794. }
  1795. // 保存用户消息
  1796. ai_message := models.AIMessage{
  1797. UserId: user_id,
  1798. Content: userMessage,
  1799. Type: "user",
  1800. AIConversationId: ai_conversation_id,
  1801. }
  1802. if err := tx.Create(&ai_message).Error; err != nil {
  1803. tx.Rollback()
  1804. c.Data["json"] = map[string]interface{}{
  1805. "statusCode": 500,
  1806. "msg": "新建消息失败: " + err.Error(),
  1807. }
  1808. c.ServeJSON()
  1809. return
  1810. }
  1811. // 获取direct_answer
  1812. directAnswer := ""
  1813. if directAnswerValue, exists := aiResponse["direct_answer"].(string); exists {
  1814. directAnswer = directAnswerValue
  1815. } else {
  1816. // 如果没有direct_answer字段,使用AI的原始回复
  1817. directAnswer = reply
  1818. }
  1819. // 保存AI回复
  1820. ai_reply := models.AIMessage{
  1821. UserId: user_id,
  1822. Content: directAnswer,
  1823. Type: "ai",
  1824. AIConversationId: ai_conversation_id,
  1825. PrevUserId: uint64(ai_message.ID),
  1826. }
  1827. if err := tx.Create(&ai_reply).Error; err != nil {
  1828. tx.Rollback()
  1829. c.Data["json"] = map[string]interface{}{
  1830. "statusCode": 500,
  1831. "msg": "新建AI回复失败: " + err.Error(),
  1832. }
  1833. c.ServeJSON()
  1834. return
  1835. }
  1836. // 更新AIConversation编辑时间
  1837. if err := tx.Model(&models.AIConversation{}).Where("id = ?", ai_conversation_id).Update("updated_at", time.Now().Unix()).Error; err != nil {
  1838. tx.Rollback()
  1839. c.Data["json"] = map[string]interface{}{
  1840. "statusCode": 500,
  1841. "msg": "更新编辑时间失败: " + err.Error(),
  1842. }
  1843. c.ServeJSON()
  1844. return
  1845. }
  1846. tx.Commit()
  1847. // 返回成功响应
  1848. c.Data["json"] = map[string]interface{}{
  1849. "statusCode": 200,
  1850. "msg": "success",
  1851. "data": map[string]interface{}{
  1852. "intent_result": aiResponse,
  1853. "direct_answer": directAnswer,
  1854. "ai_conversation_id": ai_conversation_id,
  1855. "ai_message_id": ai_reply.ID,
  1856. "is_online_search": 0, // 不需要联网搜索
  1857. },
  1858. }
  1859. } else {
  1860. // 对于query_knowledge_base类型,只返回意图识别结果
  1861. c.Data["json"] = map[string]interface{}{
  1862. "statusCode": 200,
  1863. "msg": "success",
  1864. "data": map[string]interface{}{
  1865. "intent_result": aiResponse,
  1866. "is_online_search": 1, // 需要联网搜索
  1867. },
  1868. }
  1869. }
  1870. c.ServeJSON()
  1871. }
  1872. // 获取chromadb的文档
  1873. func (c *ChatController) GetChromaDBDocument() {
  1874. // 从GET参数获取消息
  1875. userMessage := c.GetString("message")
  1876. // 构建搜索请求
  1877. searchRequest := map[string]interface{}{
  1878. "query": userMessage,
  1879. "n_results": 25, // 返回25个结果
  1880. }
  1881. requestBody, err := json.Marshal(searchRequest)
  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. // 从配置文件中读取搜索API地址
  1891. searchAPIURL, err := web.AppConfig.String("search_api_url")
  1892. if err != nil || searchAPIURL == "" {
  1893. c.Data["json"] = map[string]interface{}{
  1894. "statusCode": 500,
  1895. "msg": "配置文件中未找到search_api_url",
  1896. }
  1897. c.ServeJSON()
  1898. return
  1899. }
  1900. // 发送HTTP请求到Chroma搜索服务
  1901. req, err := http.NewRequest("POST", searchAPIURL, bytes.NewBuffer(requestBody))
  1902. if err != nil {
  1903. c.Data["json"] = map[string]interface{}{
  1904. "statusCode": 500,
  1905. "msg": "创建搜索请求失败: " + err.Error(),
  1906. }
  1907. c.ServeJSON()
  1908. return
  1909. }
  1910. req.Header.Set("Content-Type", "application/json")
  1911. client := &http.Client{Timeout: 30 * time.Second}
  1912. resp, err := client.Do(req)
  1913. if err != nil {
  1914. c.Data["json"] = map[string]interface{}{
  1915. "statusCode": 500,
  1916. "msg": "搜索请求失败: " + err.Error(),
  1917. }
  1918. c.ServeJSON()
  1919. return
  1920. }
  1921. defer resp.Body.Close()
  1922. responseBody, err := io.ReadAll(resp.Body)
  1923. if err != nil {
  1924. c.Data["json"] = map[string]interface{}{
  1925. "statusCode": 500,
  1926. "msg": "读取搜索响应失败: " + err.Error(),
  1927. }
  1928. c.ServeJSON()
  1929. return
  1930. }
  1931. if resp.StatusCode != http.StatusOK {
  1932. c.Data["json"] = map[string]interface{}{
  1933. "statusCode": 500,
  1934. "msg": fmt.Sprintf("搜索API错误: 状态码 %d", resp.StatusCode),
  1935. }
  1936. c.ServeJSON()
  1937. return
  1938. }
  1939. // 解析搜索响应
  1940. var searchResponse map[string]interface{}
  1941. if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
  1942. c.Data["json"] = map[string]interface{}{
  1943. "statusCode": 500,
  1944. "msg": "解析搜索响应失败: " + err.Error(),
  1945. }
  1946. c.ServeJSON()
  1947. return
  1948. }
  1949. // 检查响应状态
  1950. status, ok := searchResponse["status"].(string)
  1951. if !ok || status != "success" {
  1952. message, _ := searchResponse["message"].(string)
  1953. c.Data["json"] = map[string]interface{}{
  1954. "statusCode": 500,
  1955. "msg": fmt.Sprintf("搜索失败: %s", message),
  1956. }
  1957. c.ServeJSON()
  1958. return
  1959. }
  1960. // 获取搜索结果
  1961. results, ok := searchResponse["results"].([]interface{})
  1962. if !ok || len(results) == 0 {
  1963. c.Data["json"] = map[string]interface{}{
  1964. "statusCode": 200,
  1965. "msg": "success",
  1966. "data": map[string]interface{}{
  1967. "reply": "未找到相关文档",
  1968. },
  1969. }
  1970. c.ServeJSON()
  1971. return
  1972. }
  1973. // 将搜索结果转换为JSON字符串作为上下文
  1974. contextJSON, err := json.Marshal(results)
  1975. if err != nil {
  1976. c.Data["json"] = map[string]interface{}{
  1977. "statusCode": 500,
  1978. "msg": "处理搜索结果失败: " + err.Error(),
  1979. }
  1980. c.ServeJSON()
  1981. return
  1982. }
  1983. fmt.Println("contextJSON:", string(contextJSON))
  1984. // 返回成功响应
  1985. c.Data["json"] = map[string]interface{}{
  1986. "statusCode": 200,
  1987. "msg": "success",
  1988. "data": map[string]interface{}{
  1989. "reply": string(contextJSON),
  1990. },
  1991. }
  1992. c.ServeJSON()
  1993. }
  1994. // 获取chromadb的函数
  1995. func (c *ChatController) getChromaDBDocumentFunction(userMessage string) string {
  1996. // 构建搜索请求
  1997. searchRequest := map[string]interface{}{
  1998. "query": userMessage,
  1999. "n_results": 25, // 返回25个结果
  2000. }
  2001. requestBody, err := json.Marshal(searchRequest)
  2002. if err != nil {
  2003. return "构建搜索请求失败: " + err.Error()
  2004. }
  2005. // 从配置文件中读取搜索API地址
  2006. searchAPIURL, err := web.AppConfig.String("search_api_url")
  2007. if err != nil || searchAPIURL == "" {
  2008. return "配置文件中未找到search_api_url"
  2009. }
  2010. // 发送HTTP请求到Chroma搜索服务
  2011. req, err := http.NewRequest("POST", searchAPIURL, bytes.NewBuffer(requestBody))
  2012. if err != nil {
  2013. return "构建搜索请求失败: " + err.Error()
  2014. }
  2015. req.Header.Set("Content-Type", "application/json")
  2016. client := &http.Client{Timeout: 30 * time.Second}
  2017. resp, err := client.Do(req)
  2018. if err != nil {
  2019. return "搜索请求失败: " + err.Error()
  2020. }
  2021. defer resp.Body.Close()
  2022. responseBody, err := io.ReadAll(resp.Body)
  2023. if err != nil {
  2024. return "读取搜索响应失败: " + err.Error()
  2025. }
  2026. if resp.StatusCode != http.StatusOK {
  2027. return "搜索API错误: " + resp.Status
  2028. }
  2029. // 解析搜索响应
  2030. var searchResponse map[string]interface{}
  2031. if err := json.Unmarshal(responseBody, &searchResponse); err != nil {
  2032. return "解析搜索响应失败: " + err.Error()
  2033. }
  2034. // 检查响应状态
  2035. status, ok := searchResponse["status"].(string)
  2036. if !ok || status != "success" {
  2037. message, _ := searchResponse["message"].(string)
  2038. return fmt.Sprintf("搜索失败: %s", message)
  2039. }
  2040. // 获取搜索结果
  2041. results, ok := searchResponse["results"].([]interface{})
  2042. if !ok || len(results) == 0 {
  2043. return "未找到相关文档"
  2044. }
  2045. // 将搜索结果转换为JSON字符串作为上下文
  2046. contextJSON, err := json.Marshal(results)
  2047. if err != nil {
  2048. return "处理搜索结果失败: " + err.Error()
  2049. }
  2050. fmt.Println("contextJSON:", string(contextJSON))
  2051. return string(contextJSON)
  2052. }
  2053. // getOnlineSearchContent 获取联网搜索内容
  2054. func (c *ChatController) getOnlineSearchContent(userMessage string) string {
  2055. // 在关键词前加入检索策略提示词:
  2056. // 1) 若用户意图属于土木工程/路桥隧轨/施工安全等相关领域,则直接按该意图搜索
  2057. // 2) 若与上述领域无关,则根据用户表达猜测一个最可能的土木工程相关问题再进行搜索
  2058. combinedKeywords := fmt.Sprintf("【搜索策略】先识别用户意图:若问题属于土木工程/路桥隧轨/施工安全等领域,则按此意图联网搜索;若非上述领域,请根据用户表达猜测一个最可能的土木工程相关问题并据此搜索。确保检索聚焦专业资料。确保回复字数在20字内。【用户问题】%s", userMessage)
  2059. //给AI发送消息
  2060. reply, err := c.sendQwen3Message(combinedKeywords, false)
  2061. if err != nil {
  2062. fmt.Printf("联网搜索AI调用失败: %v\n", err)
  2063. return ""
  2064. }
  2065. fmt.Println("联网搜索回复:", reply)
  2066. // 构建请求体
  2067. requestBody := map[string]interface{}{
  2068. "workflow_id": "4wfh1PPDderMtCeb",
  2069. "inputs": map[string]interface{}{
  2070. "keywords": reply,
  2071. "num": 10, // 默认参数
  2072. "max_text_len": 150,
  2073. },
  2074. "response_mode": "blocking", // 默认参数
  2075. "user": "user_001",
  2076. }
  2077. // 序列化请求体
  2078. jsonData, err := json.Marshal(requestBody)
  2079. if err != nil {
  2080. fmt.Printf("联网搜索请求参数序列化失败: %v\n", err)
  2081. return ""
  2082. }
  2083. // 创建HTTP请求
  2084. req, err := http.NewRequest("POST", utils.GetDifyWorkflowURL(), bytes.NewBuffer(jsonData))
  2085. if err != nil {
  2086. fmt.Printf("联网搜索创建请求失败: %v\n", err)
  2087. return ""
  2088. }
  2089. // 设置请求头
  2090. req.Header.Set("Authorization", "Bearer app-55CyO4lmDv1VeXK4QmFpt4ng")
  2091. req.Header.Set("Content-Type", "application/json")
  2092. // 发送请求
  2093. client := &http.Client{Timeout: 30 * time.Second}
  2094. resp, err := client.Do(req)
  2095. if err != nil {
  2096. fmt.Printf("联网搜索请求失败: %v\n", err)
  2097. return ""
  2098. }
  2099. defer resp.Body.Close()
  2100. // 读取响应
  2101. responseBody, err := io.ReadAll(resp.Body)
  2102. if err != nil {
  2103. fmt.Printf("联网搜索读取响应失败: %v\n", err)
  2104. return ""
  2105. }
  2106. // 检查HTTP状态码
  2107. if resp.StatusCode != http.StatusOK {
  2108. fmt.Printf("联网搜索API请求失败,状态码: %d, 响应: %s\n", resp.StatusCode, string(responseBody))
  2109. return ""
  2110. }
  2111. // 解析响应
  2112. var apiResponse map[string]interface{}
  2113. if err := json.Unmarshal(responseBody, &apiResponse); err != nil {
  2114. fmt.Printf("联网搜索解析响应失败: %v\n", err)
  2115. return ""
  2116. }
  2117. fmt.Println("联网搜索apiResponse", apiResponse)
  2118. // 检查工作流状态
  2119. data, ok := apiResponse["data"].(map[string]interface{})
  2120. if !ok {
  2121. fmt.Printf("联网搜索响应格式错误:缺少data字段\n")
  2122. return ""
  2123. }
  2124. status, ok := data["status"].(string)
  2125. if !ok || status != "succeeded" {
  2126. errorMsg, _ := data["error"].(string)
  2127. fmt.Printf("联网搜索工作流执行失败,状态: %s, 错误: %s\n", status, errorMsg)
  2128. return ""
  2129. }
  2130. // 提取results字段
  2131. outputs, ok := data["outputs"].(map[string]interface{})
  2132. if !ok {
  2133. fmt.Printf("联网搜索响应格式错误:缺少outputs字段\n")
  2134. return ""
  2135. }
  2136. // 优先:解析 outputs.text(先直接解析;失败时再做清洗重试)
  2137. var parsedFromText []interface{}
  2138. if textResult, ok := outputs["text"].(string); ok && textResult != "" {
  2139. // 1) 直接解析(适配已是标准JSON字符串的场景)
  2140. if err := json.Unmarshal([]byte(strings.TrimSpace(textResult)), &parsedFromText); err == nil {
  2141. // 将联网搜索结果转换为字符串格式
  2142. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2143. for i, result := range parsedFromText {
  2144. if resultMap, ok := result.(map[string]interface{}); ok {
  2145. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2146. }
  2147. }
  2148. return onlineSearchStr
  2149. }
  2150. // 2) 清洗再解析(适配Python风格字符串场景)
  2151. cleaned := strings.ReplaceAll(textResult, "'", "\"")
  2152. cleaned = strings.ReplaceAll(cleaned, "None", "null")
  2153. cleaned = strings.ReplaceAll(cleaned, "\\xa0", " ")
  2154. cleaned = strings.ReplaceAll(cleaned, "\\u0026", "&")
  2155. if err := json.Unmarshal([]byte(strings.TrimSpace(cleaned)), &parsedFromText); err == nil {
  2156. // 将联网搜索结果转换为字符串格式
  2157. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2158. for i, result := range parsedFromText {
  2159. if resultMap, ok := result.(map[string]interface{}); ok {
  2160. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2161. }
  2162. }
  2163. return onlineSearchStr
  2164. }
  2165. }
  2166. // 回退:如果存在outputs.json[0].results,则按旧逻辑返回(字符串化数组)
  2167. if jsonArray, ok := outputs["json"].([]interface{}); ok && len(jsonArray) > 0 {
  2168. if firstResult, ok := jsonArray[0].(map[string]interface{}); ok {
  2169. if results, ok := firstResult["results"].([]interface{}); ok {
  2170. // 将联网搜索结果转换为字符串格式
  2171. onlineSearchStr := "\n\n# 联网搜索内容\n"
  2172. for i, result := range results {
  2173. if resultMap, ok := result.(map[string]interface{}); ok {
  2174. onlineSearchStr += fmt.Sprintf("联网搜索结果%d: %v\n", i+1, resultMap)
  2175. }
  2176. }
  2177. return onlineSearchStr
  2178. }
  2179. }
  2180. }
  2181. fmt.Printf("联网搜索响应格式错误:无法从outputs.text或outputs.json解析results\n")
  2182. return ""
  2183. }