From 8991a00e1751e9f6323095cc18d68da70d4d9257 Mon Sep 17 00:00:00 2001 From: yvan <8574526@qq.com> Date: Wed, 10 Sep 2025 20:40:06 +0800 Subject: [PATCH] wechat --- server/api/v1/pet/user/pet_assistant_api.go | 4 +- server/go.mod | 8 +- server/go.sum | 16 +++- server/model/pet/response/chat_response.go | 42 +++++------ server/service/pet/pet_chat_service.go | 81 ++++++++++++--------- server/utils/sensitive_word.go | 10 +-- server/utils/volcengine_llm.go | 36 +++------ 7 files changed, 101 insertions(+), 96 deletions(-) diff --git a/server/api/v1/pet/user/pet_assistant_api.go b/server/api/v1/pet/user/pet_assistant_api.go index e11bd951..57cc1cfb 100644 --- a/server/api/v1/pet/user/pet_assistant_api.go +++ b/server/api/v1/pet/user/pet_assistant_api.go @@ -177,14 +177,14 @@ func (p *PetAssistantApi) StreamAskPetAssistant(ctx *gin.Context) { // GetAssistantHistory 获取宠物助手对话历史 // @Tags PetAssistant -// @Summary 获取宠物助手对话历史记录 +// @Summary 获取宠物助手对话历史记录(简化版本,只返回必要字段) // @Security ApiKeyAuth // @Accept application/json // @Produce application/json // @Param sessionId query string false "会话ID" // @Param page query int false "页码" default(1) // @Param pageSize query int false "每页数量" default(20) -// @Success 200 {object} response.Response{data=[]pet.PetAiAssistantConversations,msg=string} "获取成功" +// @Success 200 {object} response.Response{data=[]petResponse.ChatHistoryItem,msg=string} "获取成功" // @Router /api/v1/pet/user/assistant/history [get] func (p *PetAssistantApi) GetAssistantHistory(ctx *gin.Context) { // 创建业务用Context diff --git a/server/go.mod b/server/go.mod index f53451d0..e9681b0d 100644 --- a/server/go.mod +++ b/server/go.mod @@ -7,6 +7,7 @@ require ( github.com/aws/aws-sdk-go v1.55.6 github.com/casbin/casbin/v2 v2.103.0 github.com/casbin/gorm-adapter/v3 v3.32.0 + github.com/dzwvip/gorm-oracle v0.1.2 github.com/fsnotify/fsnotify v1.8.0 github.com/gin-gonic/gin v1.10.0 github.com/glebarez/sqlite v1.11.0 @@ -17,6 +18,7 @@ require ( github.com/gookit/color v1.5.4 github.com/huaweicloud/huaweicloud-sdk-go-obs v3.24.9+incompatible github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible + github.com/kirklin/go-swd v0.0.3 github.com/mark3labs/mcp-go v0.31.0 github.com/mholt/archives v0.1.1 github.com/minio/minio-go/v7 v7.0.84 @@ -75,6 +77,7 @@ require ( github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/emirpasic/gods v1.12.0 // indirect github.com/fatih/structs v1.1.0 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect github.com/gammazero/toposort v0.1.1 // indirect @@ -96,6 +99,7 @@ require ( github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/go-querystring v1.1.0 // indirect + github.com/gorilla/websocket v1.5.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect @@ -109,7 +113,6 @@ require ( github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/kirklin/go-swd v0.0.3 // indirect github.com/klauspost/compress v1.17.11 // indirect github.com/klauspost/cpuid/v2 v2.2.9 // indirect github.com/klauspost/pgzip v1.2.6 // indirect @@ -129,6 +132,7 @@ require ( github.com/mozillazg/go-httpheader v0.4.0 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect github.com/nwaples/rardecode/v2 v2.1.0 // indirect + github.com/olahol/melody v1.3.0 // indirect github.com/otiai10/mint v1.6.3 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pierrec/lz4/v4 v4.1.22 // indirect @@ -141,6 +145,7 @@ require ( github.com/sagikazarmark/locafero v0.7.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect + github.com/sijms/go-ora/v2 v2.7.17 // indirect github.com/sirupsen/logrus v1.9.0 // indirect github.com/sorairolake/lzip-go v0.3.5 // indirect github.com/sourcegraph/conc v0.3.0 // indirect @@ -149,6 +154,7 @@ require ( github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/therootcompany/xz v1.0.1 // indirect + github.com/thoas/go-funk v0.7.0 // indirect github.com/tidwall/gjson v1.14.1 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect diff --git a/server/go.sum b/server/go.sum index 54465190..8700cee3 100644 --- a/server/go.sum +++ b/server/go.sum @@ -115,6 +115,10 @@ github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707/go.mod h1:qssHWj6 github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dzwvip/gorm-oracle v0.1.2 h1:811aFDY7oDfKWHc0Z0lHdXzzr89EmKBSwc/jLJ8GU5g= +github.com/dzwvip/gorm-oracle v0.1.2/go.mod h1:TbF7idnO9UgGpJ0qJpDZby1/wGquzP5GYof88ScBITE= +github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= +github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= @@ -253,6 +257,8 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -291,6 +297,7 @@ github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJk github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -389,6 +396,8 @@ github.com/nwaples/rardecode/v2 v2.1.0/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsR github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/olahol/melody v1.3.0 h1:n7UlKiQnxVrgxKoM0d7usZiN+Z0y2lVENtYLgKtXS6s= +github.com/olahol/melody v1.3.0/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= @@ -457,6 +466,8 @@ github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFt github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= +github.com/sijms/go-ora/v2 v2.7.17 h1:M/pYIqjaMUeBxyzOWp2oj4ntF6fHSBloJWGNH9vbmsU= +github.com/sijms/go-ora/v2 v2.7.17/go.mod h1:EHxlY6x7y9HAsdfumurRfTd+v8NrEOTR3Xl4FWlH6xk= github.com/silenceper/wechat/v2 v2.1.9 h1:wc092gUkGbbBRTdzPxROhQhOH5iE98stnfzKA73mnTo= github.com/silenceper/wechat/v2 v2.1.9/go.mod h1:7Iu3EhQYVtDUJAj+ZVRy8yom75ga7aDWv8RurLkVm0s= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= @@ -508,6 +519,8 @@ github.com/tencentyun/cos-go-sdk-v5 v0.7.60 h1:/e/tmvRmfKexr/QQIBzWhOkZWsmY3EK72 github.com/tencentyun/cos-go-sdk-v5 v0.7.60/go.mod h1:8+hG+mQMuRP/OIS9d83syAvXvrMj9HhkND6Q1fLghw0= github.com/therootcompany/xz v1.0.1 h1:CmOtsn1CbtmyYiusbfmhmkpAAETj0wBIH6kCYaX+xzw= github.com/therootcompany/xz v1.0.1/go.mod h1:3K3UH1yCKgBneZYhuQUvJ9HPD19UEXEI0BWbMn8qNMY= +github.com/thoas/go-funk v0.7.0 h1:GmirKrs6j6zJbhJIficOsz2aAI7700KsU/5YrdHRM1Y= +github.com/thoas/go-funk v0.7.0/go.mod h1:+IWnUfUmFO1+WVYQWQtIJHeRRdaIyyYglZN7xzUPe4Q= github.com/tidwall/gjson v1.14.1 h1:iymTbGkQBhveq21bEvAQ81I0LEBork8BFe1CUZXdyuo= github.com/tidwall/gjson v1.14.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= @@ -529,8 +542,6 @@ github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbW github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/volcengine/volc-sdk-golang v1.0.23 h1:anOslb2Qp6ywnsbyq9jqR0ljuO63kg9PY+4OehIk5R8= github.com/volcengine/volc-sdk-golang v1.0.23/go.mod h1:AfG/PZRUkHJ9inETvbjNifTDgut25Wbkm2QoYBTbvyU= -github.com/volcengine/volcengine-go-sdk v1.1.25 h1:wwR2DTJGw2sOZ1wTWaQLn03PGO0O+motGvsoVvAp5Zk= -github.com/volcengine/volcengine-go-sdk v1.1.25/go.mod h1:EyKoi6t6eZxoPNGr2GdFCZti2Skd7MO3eUzx7TtSvNo= github.com/volcengine/volcengine-go-sdk v1.1.31 h1:qrNd/fu+ZWzH93EBSPBSntGwgwo7cHITxxv1IdvLxls= github.com/volcengine/volcengine-go-sdk v1.1.31/go.mod h1:EyKoi6t6eZxoPNGr2GdFCZti2Skd7MO3eUzx7TtSvNo= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= @@ -894,6 +905,7 @@ gorm.io/driver/sqlserver v1.5.4 h1:xA+Y1KDNspv79q43bPyjDMUgHoYHLhXYmdFcYPobg8g= gorm.io/driver/sqlserver v1.5.4/go.mod h1:+frZ/qYmuna11zHPlh5oc2O6ZA/lS88Keb0XSH1Zh/g= gorm.io/gen v0.3.26 h1:sFf1j7vNStimPRRAtH4zz5NiHM+1dr6eA9aaRdplyhY= gorm.io/gen v0.3.26/go.mod h1:a5lq5y3w4g5LMxBcw0wnO6tYUCdNutWODq5LrIt75LE= +gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA= gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= diff --git a/server/model/pet/response/chat_response.go b/server/model/pet/response/chat_response.go index c4e0dd9b..932edeb8 100644 --- a/server/model/pet/response/chat_response.go +++ b/server/model/pet/response/chat_response.go @@ -2,8 +2,6 @@ package response import ( "time" - - "github.com/flipped-aurora/gin-vue-admin/server/model/pet" ) // ChatResponse 宠物助手聊天响应结构体 @@ -26,37 +24,37 @@ type StreamEvent struct { Data interface{} `json:"data"` // 事件数据 } -// StreamMessageData 流式消息数据结构体 +// StreamMessageData 流式消息数据结构体(简化版) type StreamMessageData struct { - Delta string `json:"delta"` // 增量消息内容 - SessionId string `json:"sessionId"` // 会话ID - RequestId string `json:"requestId"` // 请求ID + Delta string `json:"delta"` // 增量消息内容 } -// StreamErrorData 流式错误数据结构体 +// StreamErrorData 流式错误数据结构体(简化版) type StreamErrorData struct { - Error string `json:"error"` // 错误信息 - Code string `json:"code"` // 错误代码 - RequestId string `json:"requestId"` // 请求ID + Error string `json:"error"` // 错误信息 } -// StreamDoneData 流式完成数据结构体 +// StreamDoneData 流式完成数据结构体(简化版) type StreamDoneData struct { - Message string `json:"message"` // 完整消息内容 - SessionId string `json:"sessionId"` // 会话ID - RequestId string `json:"requestId"` // 请求ID - TokenCount int `json:"tokenCount"` // Token消耗数量 - ResponseTime int64 `json:"responseTime"` // 响应时间(毫秒) - IsSensitive bool `json:"isSensitive"` // 是否包含敏感词 - FinishReason string `json:"finishReason"` // 完成原因 + Message string `json:"message"` // 完整消息内容 + SessionId string `json:"sessionId"` // 会话ID +} + +// ChatHistoryItem 聊天历史项结构体(简化版) +type ChatHistoryItem struct { + ID uint `json:"id"` // 消息ID + Role string `json:"role"` // 角色:user/assistant + Message string `json:"message"` // 消息内容 + SessionId string `json:"sessionId"` // 会话ID + CreatedAt time.Time `json:"createdAt"` // 创建时间 } // ChatHistoryResponse 聊天历史响应结构体 type ChatHistoryResponse struct { - List []pet.PetAiAssistantConversations `json:"list"` // 对话记录列表 - Total int64 `json:"total"` // 总记录数 - Page int `json:"page"` // 当前页码 - PageSize int `json:"pageSize"` // 每页大小 + List []ChatHistoryItem `json:"list"` // 对话记录列表 + Total int64 `json:"total"` // 总记录数 + Page int `json:"page"` // 当前页码 + PageSize int `json:"pageSize"` // 每页大小 } // SessionInfo 会话信息结构体 diff --git a/server/service/pet/pet_chat_service.go b/server/service/pet/pet_chat_service.go index 49d613ec..ad4e1cca 100644 --- a/server/service/pet/pet_chat_service.go +++ b/server/service/pet/pet_chat_service.go @@ -140,8 +140,8 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe global.GVA_LOG.Error("敏感词检测失败", zap.Error(err)) eventChan <- StreamEvent{ Event: "error", - Data: map[string]interface{}{ - "error": "敏感词检测失败", + Data: petResponse.StreamErrorData{ + Error: "敏感词检测失败", }, } return err @@ -158,18 +158,17 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe eventChan <- StreamEvent{ Event: "message", - Data: ChatResponse{ - Message: "您的消息包含不当内容,请重新输入。", - SessionId: req.SessionId, - IsSensitive: true, - TokenCount: 0, - ResponseTime: time.Since(startTime).Milliseconds(), + Data: petResponse.StreamMessageData{ + Delta: "您的消息包含不当内容,请重新输入。", }, } eventChan <- StreamEvent{ Event: "done", - Data: map[string]interface{}{"finished": true}, + Data: petResponse.StreamDoneData{ + Message: "您的消息包含不当内容,请重新输入。", + SessionId: req.SessionId, + }, } return nil } @@ -186,8 +185,8 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe global.GVA_LOG.Error("获取对话历史失败", zap.Error(err)) eventChan <- StreamEvent{ Event: "error", - Data: map[string]interface{}{ - "error": "获取对话历史失败", + Data: petResponse.StreamErrorData{ + Error: "获取对话历史失败", }, } return err @@ -215,8 +214,8 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe global.GVA_LOG.Error("LLM流式调用失败", zap.Error(err)) eventChan <- StreamEvent{ Event: "error", - Data: map[string]interface{}{ - "error": "LLM调用失败", + Data: petResponse.StreamErrorData{ + Error: "LLM调用失败", }, } } @@ -246,9 +245,8 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe // 转发消息给客户端 eventChan <- StreamEvent{ Event: "message", - Data: map[string]interface{}{ - "delta": delta, - "sessionId": sessionId, + Data: petResponse.StreamMessageData{ + Delta: delta, }, } } @@ -284,13 +282,9 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe // 发送完成事件 eventChan <- StreamEvent{ Event: "done", - Data: ChatResponse{ - Message: fullMessage, - SessionId: sessionId, - IsSensitive: aiHasSensitive, - TokenCount: tokenCount, - ResponseTime: responseTime, - RequestId: llmReq.RequestID, + Data: petResponse.StreamDoneData{ + Message: fullMessage, + SessionId: sessionId, }, } return nil @@ -300,8 +294,8 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe global.GVA_LOG.Error("LLM流式响应错误", zap.Any("error", llmEvent.Data.Error)) eventChan <- StreamEvent{ Event: "error", - Data: map[string]interface{}{ - "error": "LLM响应错误", + Data: petResponse.StreamErrorData{ + Error: "LLM响应错误", }, } return fmt.Errorf("LLM响应错误") @@ -311,7 +305,7 @@ func (p *PetChatService) StreamChat(ctx context.Context, userId uint, req ChatRe } // GetChatHistory 获取对话历史 -func (p *PetChatService) GetChatHistory(ctx context.Context, userId uint, sessionId string, limit int) ([]pet.PetAiAssistantConversations, error) { +func (p *PetChatService) GetChatHistory(ctx context.Context, userId uint, sessionId string, limit int) ([]petResponse.ChatHistoryItem, error) { var conversations []pet.PetAiAssistantConversations query := global.GVA_DB.WithContext(ctx).Where("user_id = ?", userId) @@ -331,7 +325,28 @@ func (p *PetChatService) GetChatHistory(ctx context.Context, userId uint, sessio conversations[i], conversations[j] = conversations[j], conversations[i] } - return conversations, nil + // 转换为简化结构 + items := make([]petResponse.ChatHistoryItem, 0, len(conversations)) + for _, conv := range conversations { + if conv.MessageContent != nil && conv.Role != nil { + item := petResponse.ChatHistoryItem{ + ID: conv.ID, + Role: *conv.Role, + Message: *conv.MessageContent, + SessionId: "", + CreatedAt: conv.CreatedAt, + } + + // 设置会话ID(如果存在) + if conv.SessionId != nil { + item.SessionId = *conv.SessionId + } + + items = append(items, item) + } + } + + return items, nil } // SaveConversation 保存对话记录 @@ -368,7 +383,7 @@ func (p *PetChatService) GetChatSessions(ctx context.Context, userId uint) ([]ma } // buildMessages 构建LLM请求消息 -func (p *PetChatService) buildMessages(history []pet.PetAiAssistantConversations, userMessage string) []utils.LLMMessage { +func (p *PetChatService) buildMessages(history []petResponse.ChatHistoryItem, userMessage string) []utils.LLMMessage { messages := []utils.LLMMessage{ { Role: "system", @@ -378,12 +393,10 @@ func (p *PetChatService) buildMessages(history []pet.PetAiAssistantConversations // 添加历史对话 for _, conv := range history { - if conv.MessageContent != nil && conv.Role != nil { - messages = append(messages, utils.LLMMessage{ - Role: *conv.Role, - Content: *conv.MessageContent, - }) - } + messages = append(messages, utils.LLMMessage{ + Role: conv.Role, + Content: conv.Message, + }) } // 添加当前用户消息 diff --git a/server/utils/sensitive_word.go b/server/utils/sensitive_word.go index 5df970b8..3fc05fbf 100644 --- a/server/utils/sensitive_word.go +++ b/server/utils/sensitive_word.go @@ -34,17 +34,11 @@ func (s *SensitiveWordUtil) InitDetector() error { detector, err := swd.New() if err != nil { s.initErr = err - // 只有在global.GVA_LOG不为nil时才记录日志 - if global.GVA_LOG != nil { - global.GVA_LOG.Error("Failed to initialize sensitive word detector", zap.Error(err)) - } + global.GVA_LOG.Error("Failed to initialize sensitive word detector", zap.Error(err)) return } s.detector = detector - // 只有在global.GVA_LOG不为nil时才记录日志 - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Sensitive word detector initialized successfully") - } + global.GVA_LOG.Info("Sensitive word detector initialized successfully") }) return s.initErr } diff --git a/server/utils/volcengine_llm.go b/server/utils/volcengine_llm.go index 6b95ee7a..b2a2e8df 100644 --- a/server/utils/volcengine_llm.go +++ b/server/utils/volcengine_llm.go @@ -98,18 +98,14 @@ func (v *VolcengineLLMUtil) InitClient() error { // 验证配置 if config.ApiKey == "" { v.initErr = fmt.Errorf("volcengine api key is empty") - if global.GVA_LOG != nil { - global.GVA_LOG.Error("Volcengine configuration error", zap.Error(v.initErr)) - } + global.GVA_LOG.Error("Volcengine configuration error", zap.Error(v.initErr)) return } // 创建ARK Runtime客户端,使用API Key v.client = arkruntime.NewClientWithApiKey(config.ApiKey) - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Volcengine LLM client initialized successfully") - } + global.GVA_LOG.Info("Volcengine LLM client initialized successfully") }) return v.initErr } @@ -165,9 +161,7 @@ func (v *VolcengineLLMUtil) ChatCompletion(req LLMRequest) (*LLMResponse, error) // 调用API resp, err := v.client.CreateChatCompletion(context.Background(), chatReq) if err != nil { - if global.GVA_LOG != nil { - global.GVA_LOG.Error("Chat completion failed", zap.Error(err), zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Error("Chat completion failed", zap.Error(err), zap.String("requestID", req.RequestID)) return nil, err } @@ -199,9 +193,7 @@ func (v *VolcengineLLMUtil) ChatCompletion(req LLMRequest) (*LLMResponse, error) Usage: usage, } - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Chat completion successful", zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Info("Chat completion successful", zap.String("requestID", req.RequestID)) return chatResp, nil } @@ -264,16 +256,12 @@ func (v *VolcengineLLMUtil) StreamChatCompletion(req LLMRequest, eventChan chan< // 调用流式API stream_resp, err := v.client.CreateChatCompletionStream(ctx, chatReq) if err != nil { - if global.GVA_LOG != nil { - global.GVA_LOG.Error("Stream chat completion failed", zap.Error(err), zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Error("Stream chat completion failed", zap.Error(err), zap.String("requestID", req.RequestID)) return err } defer stream_resp.Close() - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Stream chat completion started", zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Info("Stream chat completion started", zap.String("requestID", req.RequestID)) // 处理流式响应 for { @@ -293,14 +281,10 @@ func (v *VolcengineLLMUtil) StreamChatCompletion(req LLMRequest, eventChan chan< Object: "chat.completion.chunk", }, } - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Stream chat completion finished", zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Info("Stream chat completion finished", zap.String("requestID", req.RequestID)) return nil } - if global.GVA_LOG != nil { - global.GVA_LOG.Error("Stream receive error", zap.Error(err), zap.String("requestID", req.RequestID)) - } + global.GVA_LOG.Error("Stream receive error", zap.Error(err), zap.String("requestID", req.RequestID)) eventChan <- LLMStreamEvent{ Event: "error", Data: LLMResponse{ @@ -359,9 +343,7 @@ func (v *VolcengineLLMUtil) StopGeneration(requestID string) error { if cancelFunc, ok := cancel.(context.CancelFunc); ok { cancelFunc() v.activeSessions.Delete(requestID) - if global.GVA_LOG != nil { - global.GVA_LOG.Info("Generation stopped", zap.String("requestID", requestID)) - } + global.GVA_LOG.Info("Generation stopped", zap.String("requestID", requestID)) return nil } }