kefu/controller/ai/intent.go

100 lines
2.7 KiB
Go
Raw Permalink Normal View History

2024-12-10 02:50:12 +00:00
package ai
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"io"
"kefu/lib"
"kefu/models"
"log"
"net/http"
)
func PostAiIntent(c *gin.Context) {
entId, _ := c.Get("ent_id")
visitorId := c.Query("visitor_id")
config := models.GetEntConfigsMap(entId.(string), "chatGPTUrl", "chatGPTSecret")
gpt := lib.NewChatGptTool(config["chatGPTUrl"], config["chatGPTSecret"])
visitorInfo := models.FindVisitorByVistorId(visitorId)
messageList := ""
messages := models.FindMessageByQueryPage(0, 200, "visitor_id = ?", visitorId)
for i := len(messages) - 1; i >= 0; i-- {
reqContent := messages[i].Content
sendTime := messages[i].CreatedAt
if messages[i].MesType == "visitor" {
messageList += fmt.Sprintf("顾客:%s %s\n", reqContent, sendTime.Format("2006-01-02 15:04:05"))
} else {
messageList += fmt.Sprintf("客服:%s %s\n", reqContent, sendTime.Format("2006-01-02 15:04:05"))
}
}
system := fmt.Sprintf(`假设你是一个消费者行为心理分析师你正在分析客服系统中访客的消费心理我提供给你以下顾客资料
该顾客来访%d次首次访问时间%s最后访问时间%sIP归属地是%s
我提供给你如下聊天记录
%s
`, visitorInfo.VisitNum,
visitorInfo.CreatedAt.Format("2006-01-02 15:04:05"),
visitorInfo.UpdatedAt.Format("2006-01-02 15:04:05"),
visitorInfo.City,
messageList)
userPrompt := fmt.Sprintf(`
请根据顾客资料分析用户心理按如下格式输出
1.意图辨别
2.情绪辨别
3.购买力辨别
4.分析原因分条列出
`)
message := []lib.Gpt3Dot5Message{
{
Role: "system",
Content: system,
},
{
Role: "user",
Content: userPrompt,
},
}
log.Println("消费者意图分析:", message)
//res, err := gpt.ChatGPT3Dot5Turbo(message)
// 将响应头中的Content-Type设置为text/plain表示响应内容为文本
c.Header("Content-Type", "text/html;charset=utf-8;")
// 关闭输出缓冲,使得每次写入的数据能够立即发送给客户端
f, _ := c.Writer.(http.Flusher)
stream, err := gpt.ChatGPT3Dot5TurboStream(message, "")
if err != nil {
log.Printf("\ngpt3 stream error: %v\n", err)
return
}
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("\nStream finished", err)
break
} else if err != nil {
log.Printf("\nStream error: %v,%v\n", err, response)
break
} else {
data := response.Choices[0].Delta.Content
log.Println(data)
c.Writer.Write([]byte(data))
f.Flush()
}
}
stream.Close()
//if err != nil {
// c.JSON(200, gin.H{
// "code": types.ApiCode.FAILED,
// "msg": err.Error(),
// })
// return
//}
//c.JSON(200, gin.H{
// "code": types.ApiCode.SUCCESS,
// "msg": "ok",
// "result": res,
//})
}