chat.go 73 KB

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