Untitled conversation
- Usercode
- Assistant
func ChatHandler(c *gin.Context) {
conn, err := middleware.Upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
handleError(c, err)
return
}
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
userID := c.GetString("userid")
sendToClientChan := make(chan []byte)
// 协程,专注于发送消息到前端,自动销毁协程当这个函数退出
go processMessages(ctx, conn, sendToClientChan)
// 创建一个计时器,初始设置为10分钟,如果十分钟内没有新消息发过来就断开连接
inactivityTimer := time.NewTimer(10 * time.Minute)
// 创建一个新的计时器,初始设置为30秒 提醒学生发消息
thirtySecondTimer := time.NewTimer(50 * time.Second)
// 通知主循环消息已处理的通道
messageProcessed := make(chan struct{})
// 启动一个 goroutine 来处理消息
go func() {
defer close(messageProcessed)
for {
select {
case <-ctx.Done():
log.Println("father routine exit")
return
default:
if err := handleMessage(conn, sendToClientChan, userID); err != nil {
// 如果 handleMessage 出现错误,通知主循环并退出
log.Println("\n\nVery error occur", err)
return
}
log.Println("wait for next user message")
// 通知主循环消息已处理
messageProcessed <- struct{}{}
}
}
}()
for {
select {
case <-inactivityTimer.C:
// 如果计时器到期,关闭连接
log.Println("用户10分钟没有发送消息,关闭连接")
return
case <-thirtySecondTimer.C:
// 如果30秒计时器到期,发送一条消息给用户
log.Println("用户30秒没有发送消息,发送提示消息")
case _, ok := <-messageProcessed:
if !ok {
// 通道已关闭,退出循环
log.Println("处理消息时发生错误,退出循环")
return
}
// 收到消息处理通知,重置计时器
if !inactivityTimer.Stop() {
select {
case <-thirtySecondTimer.C:
default:
}
}
inactivityTimer.Reset(10 * time.Minute)
// 重置30秒计时器
if !thirtySecondTimer.Stop() {
select {
case <-thirtySecondTimer.C:
default:
}
}
thirtySecondTimer.Reset(50 * time.Second)
}
}
}
func handleError(c *gin.Context, err error) {
c.JSON(200, serializer.WsResponse(err.Error(), 1, "aiSaid", nil))
}
func processMessages(ctx context.Context, conn *websocket.Conn, sendToClientChan chan []byte) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
log.Println("发送消息到前端的协程创建成功!")
for {
select {
case <-ctx.Done():
log.Println("发消息到前端的协程退出了")
return
case msg := <-sendToClientChan:
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
return
}
case <-ticker.C:
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// handleMessage 用户每一次发送消息都由这个函数处理
//
// @param conn websocket 连接对象
// @param sendToClientChan 发送消息到这个chan 即可,不用关系如何给websocket 发送消息
// @param userid 用户id 用户获取conversation对象,这个对象内包含上面的message chan
// @return error 如果是nil 就不是错误,只是说明不知道要怎么处理这个错误。否则就是严重错误,需要断开websocket连接
func handleMessage(conn *websocket.Conn, sendToClientChan chan []byte, userid string) error {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("读取消息失败", err, message)
sendToClientChan <- utils.NewTextMessage("不好意思,希文没听清你说什么。你能再说一遍吗?", "")
return nil
}
log.Println("收到消息:", string(message))
// 绑定用户发送的消息到chatBody
var chatBody models.UserChatReq
if err := json.Unmarshal(message, &chatBody); err != nil {
log.Println("解码消息失败", string(message), err)
sendToClientChan <- utils.NewTextMessage("不好意思,希文没理解你的意思。你能再说一遍吗?", "")
return nil
}
// 获取对话对象,这里意味着每一次用户发送消息都要获取一遍,可能是一个优化点
conv := task.GetConversation(userid)
if conv == nil {
log.Println("获取会话失败")
sendToClientChan <- utils.NewTextMessage("不好意思,希文太忙了,忘了和你聊过啥了。你能再说一遍吗?", "")
return nil
}
// 绑定会话
conv.SendToClientChan = sendToClientChan
useridObj, _ := primitive.ObjectIDFromHex(userid)
// 这个chan 用来关闭下面运行新task 的协程的,对用户的一句话回复完了,这个handleMessage就退出了,运行新task 的init函数的协程就可以退出了
destoryListen := make(chan bool)
defer close(destoryListen)
// 每一个任务在初始化的时候都发送他初始化的消息给前端,在下面的协程中运行
// 这里接收到客户端消息之后走下面的协程运行task 的run 方法
// 如果在处理的过程中发现task 完成了,那就切换协程,然后自然的运行下面的task 的init 方法,
// 这样可能会导致协程泄露(每一次调用这个handleMessage 都会新建一个协程,这样会消耗很多内存)
// 下面的协程每运行一次就可以将这个协程关闭了,因为用户请求一次消息不会切换两次active task
go func(conv *task.Conversation, stop chan bool) {
select {
case <-stop:
return
case tmptask := <-conv.TaskQueue:
log.Println("recive new task, i'm going to run task init method")
tmptask.Init()
}
}(conv, destoryListen)
// 根据用户请求的路由,以及 taskID 来判断是不是要新建task,然后将获取到的task 设置到当前对话中的活跃task上
if chatBody.WApi == "userSaid" {
if chatBody.Data.TaskID == "" {
summaryService := service.NewUserSummaryService(useridObj)
var activeTask task.Task
// 查询以前是否做过评估任务
hasTest := summaryService.HasEvaTest()
stuProfile := summaryService.GetStuProfile()
if hasTest {
activeTask = task.NewAITask("", stuProfile, 180, nil, useridObj, models.STUDYTASK, conv)
} else {
// 以前没做过评估,从新开始
activeTask, _ = task.NewEvaTask("小学生", 180, nil, useridObj, conv)
}
// 只有新建的task 才能被放进task queue,然后被上面的协程监听,然后运行init 方法
conv.TaskQueue <- activeTask
return nil
} else {
// 获取到taskID,意味着这是继续进行的对话任务
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask.GetTaskType() == task.AI || activeTask.GetTaskType() == task.Eva {
// 成功获取到task对象,然后由task 处理需要返回什么数据
conv.ActiveTask = activeTask
} else {
resByte, _ := json.Marshal(serializer.WsResponse("任务ID与路由不匹配", 1, "aiSaid", nil))
sendToClientChan <- resByte
return errors.New("任务ID与路由不匹配expect aiSaid, but got " + chatBody.WApi)
}
}
} else if chatBody.WApi == "xObjSubmitReq" {
if chatBody.Data.TaskID == "" {
resByte, _ := json.Marshal(serializer.WsResponse("任务ID与路由不匹配,xObjSubmit 不应该由用户初始化", 1, "aiSaid", nil))
sendToClientChan <- resByte
return errors.New("unknown taskID expect one")
}
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask.GetTaskType() == task.Question {
conv.ActiveTask = activeTask
} else {
resByte, _ := json.Marshal(serializer.WsResponse("任务ID与路由不匹配", 1, "aiSaid", nil))
sendToClientChan <- resByte
return errors.New("任务ID与路由不匹配")
}
} else {
resByte, _ := json.Marshal(serializer.WsResponse("未知的路由", 1, "aiSaid", nil))
sendToClientChan <- resByte
return errors.New("未知的路由")
}
// 更新用户上一次说话时间
conv.ActiveTask.UpdateTaskLastUserSaid()
doneChan := make(chan string)
// 这里的Run 会正常运行完返回的
go conv.ActiveTask.Run(doneChan, chatBody.Data)
// 阻塞当前函数继续执行,知道协程中运行task 完毕,然后返回done 或者continue
result := <-doneChan
if result == "done" {
conv.SwitchTask(useridObj)
} else if result == "continue" {
// 继续执行这个task,不切换task
// 下面发送true 是取消监听创建新task 的协程,防止协程泄露
destoryListen <- true
return nil
} else {
log.Println("任务失败,因为:", result)
resByte, _ := json.Marshal(serializer.WsResponse(result, 1, "aiSaid", nil))
sendToClientChan <- resByte
return errors.New(result)
}
return nil
}
上面是我的golang项目的一部分代码,主要功能是接受用户的http 请求,然后升级到websocket连接,然后接受用户的消息并处理,以及任务完成之后会有任务切换的功能,其中task 和 conversation 部分代码已经实现,请你帮我更优雅的实现上面的功能。 其中conversation 的结构如下
type Conversation struct {
ID string `json:"id"`
UserID string `json:"userid"`
UserNode models.UserNode `json:"usernode"`
TasksID []string `json:"tasksID"`
thread openai.Thread `json:"-"`
assistant openai.Assistant `json:"-"`
AssistantID string `json:"assistantID"`
ThreadID string `json:"threadID"`
run openai.Run `json:"-"`
RunID string `json:"runID"`
TaskQueue chan Task `json:"taskqueue"`
ActiveTask Task `json:"activetask"`
SendToClientChan chan []byte `json:"-"`
Messages []openai.ChatCompletionMessage `json:"messages"`
}
我希望上面任务切换的时候是从conversation 中的TaskQueue 中消费一个,然后执行这个task 的init 方法,请你理解上面我的代码,然后优雅的帮我重构。谢谢。
Certainly! After analyzing your code, I understand that you want a more elegant solution for handling task switching within the Conversation. Specifically, you want to consume tasks from the TaskQueue and execute their Init methods without leaking goroutines or complicating the code.
Below, I have refactored your code to address these concerns. The main changes include:
Using a Dedicated Task Processor Goroutine: Instead of starting a new goroutine in handleMessage each time a message is received, we start a single goroutine when the Conversation is created to process tasks from the TaskQueue.
Simplifying handleMessage: The handleMessage function now focuses on handling user messages and interacting with the active task without managing goroutines for task initialization.
Managing Task Switching Elegantly: When a task is completed, it adds the next task to the TaskQueue, and the task processor goroutine picks it up and runs its Init method.
Below is the refactored code with explanations:
ChatHandler Function:func ChatHandler(c *gin.Context) {
conn, err := middleware.Upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
handleError(c, err)
return
}
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
userID := c.GetString("userid")
sendToClientChan := make(chan []byte)
// Start the conversation's task processor
conv := task.GetConversation(userID)
if conv == nil {
log.Println("Failed to get conversation")
handleError(c, errors.New("conversation not found"))
return
}
conv.SendToClientChan = sendToClientChan
conv.StartTaskProcessor()
// Start goroutine to send messages to the client
go processMessages(ctx, conn, sendToClientChan)
// Inactivity timers
inactivityTimer := time.NewTimer(10 * time.Minute)
thirtySecondTimer := time.NewTimer(50 * time.Second)
messageProcessed := make(chan struct{})
// Start goroutine to handle messages
go func() {
defer close(messageProcessed)
for {
select {
case <-ctx.Done():
log.Println("Exiting message handler goroutine")
return
default:
if err := handleMessage(conn, conv, userID); err != nil {
log.Println("Error occurred in handleMessage:", err)
return
}
messageProcessed <- struct{}{}
}
}
}()
for {
select {
case <-inactivityTimer.C:
log.Println("User inactive for 10 minutes, closing connection")
return
case <-thirtySecondTimer.C:
log.Println("User inactive for 50 seconds, sending reminder")
// Send reminder to the user via sendToClientChan
sendToClientChan <- utils.NewTextMessage("Are you still there?", "")
case _, ok := <-messageProcessed:
if !ok {
log.Println("Error processing message, exiting loop")
return
}
// Reset timers
if !inactivityTimer.Stop() {
<-inactivityTimer.C
}
inactivityTimer.Reset(10 * time.Minute)
if !thirtySecondTimer.Stop() {
<-thirtySecondTimer.C
}
thirtySecondTimer.Reset(50 * time.Second)
}
}
}
Explanation:
Conversation and start its task processor goroutine using StartTaskProcessor().handleMessage.handleMessage Function:Explanation:
Conversation handles task initialization by consuming tasks from TaskQueue.Conversation Struct and Methods:type Conversation struct {
ID string `json:"id"`
UserID string `json:"userid"`
UserNode models.UserNode `json:"usernode"`
TasksID []string `json:"tasksID"`
thread openai.Thread `json:"-"`
assistant openai.Assistant `json:"-"`
AssistantID string `json:"assistantID"`
ThreadID string `json:"threadID"`
run openai.Run `json:"-"`
RunID string `json:"runID"`
TaskQueue chan Task `json:"taskqueue"`
ActiveTask Task `json:"activetask"`
SendToClientChan chan []byte `json:"-"`
Messages []openai.ChatCompletionMessage `json:"messages"`
taskProcessorQuit chan struct{} `json:"-"`
}
// StartTaskProcessor starts the task processor goroutine
func (conv *Conversation) StartTaskProcessor() {
go func() {
for {
select {
case <-conv.taskProcessorQuit:
log.Println("Task processor goroutine exiting")
return
case task := <-conv.TaskQueue:
conv.ActiveTask = task
task.Init()
}
}
}()
}
// StopTaskProcessor stops the task processor goroutine
func (conv *Conversation) StopTaskProcessor() {
close(conv.taskProcessorQuit)
}
// SwitchTask adds a new task to the TaskQueue for processing
func (conv *Conversation) SwitchTask(useridObj primitive.ObjectID) {
var nextTask Task
// Logic to determine the next task
// For example:
nextTask = task.NewSomeOtherTask("parameters", conv)
conv.TaskQueue <- nextTask
}
Explanation:
taskProcessorQuit channel to gracefully stop the task processor goroutine when needed.StartTaskProcessor function starts the goroutine that listens on TaskQueue and processes tasks by calling their Init methods.SwitchTask function now adds the next task to the TaskQueue, which the task processor will pick up.processMessages Function (unchanged but included for completeness):func processMessages(ctx context.Context, conn *websocket.Conn, sendToClientChan chan []byte) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
log.Println("Message sending goroutine started")
for {
select {
case <-ctx.Done():
log.Println("Message sending goroutine exiting")
return
case msg := <-sendToClientChan:
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
return
}
case <-ticker.C:
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
Avoids Goroutine Leaks: By starting a single task processor goroutine per Conversation, we eliminate the risk of goroutine leaks that could occur when starting a goroutine in handleMessage every time a message is received.
Simplifies handleMessage: The handleMessage function is now focused solely on handling user messages and coordinating with the active task, making the code cleaner and easier to understand.
Centralizes Task Processing: All task initialization and switching logic is centralized within the Conversation's task processor goroutine, improving code organization.
Graceful Shutdown: The taskProcessorQuit channel allows for graceful shutdown of the task processor goroutine when the conversation ends, freeing up resources.
Enhanced Maintainability: The code is modular, with clear separation of concerns, making it easier to maintain and extend in the future.
Error Handling: Ensure that any errors within task methods (Init, Run, etc.) are properly handled and don't cause unexpected behavior.
Concurrency Considerations: If Conversation's fields are accessed by multiple goroutines, consider adding synchronization mechanisms (e.g., mutexes) to prevent data races.
Resource Cleanup: When the WebSocket connection is closed, make sure to call conv.StopTaskProcessor() to clean up the goroutine.
Task Interface: Ensure that all tasks implement a common interface with Init and Run methods, which the task processor goroutine can work with.
By refactoring your code in this way, we maintain the desired functionality while improving code elegance, preventing goroutine leaks, and enhancing maintainability. The task processor goroutine effectively manages task initialization, and handleMessage focuses on responding to user input.
Let me know if you have any questions or need further assistance!
Not yet included in a published release.
func handleMessage(conn *websocket.Conn, conv *task.Conversation, userid string) error {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Failed to read message:", err)
conv.SendToClientChan <- utils.NewTextMessage("Sorry, I didn't catch that. Could you please repeat?", "")
return nil
}
log.Println("Received message:", string(message))
// Parse user's message into chatBody
var chatBody models.UserChatReq
if err := json.Unmarshal(message, &chatBody); err != nil {
log.Println("Failed to decode message:", string(message), err)
conv.SendToClientChan <- utils.NewTextMessage("Sorry, I didn't understand that. Could you please rephrase?", "")
return nil
}
useridObj, _ := primitive.ObjectIDFromHex(userid)
// Determine if we need to create a new task
if chatBody.WApi == "userSaid" {
if chatBody.Data.TaskID == "" {
summaryService := service.NewUserSummaryService(useridObj)
var activeTask task.Task
// Check if evaluation test has been done before
hasTest := summaryService.HasEvaTest()
stuProfile := summaryService.GetStuProfile()
if hasTest {
activeTask = task.NewAITask("", stuProfile, 180, nil, useridObj, models.STUDYTASK, conv)
} else {
// If not done before, start anew
activeTask, _ = task.NewEvaTask("小学生", 180, nil, useridObj, conv)
}
// Add the new task to TaskQueue; the task processor will pick it up and run Init
conv.TaskQueue <- activeTask
return nil
} else {
// Get existing task
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask.GetTaskType() != task.AI && activeTask.GetTaskType() != task.Eva {
resByte, _ := json.Marshal(serializer.WsResponse("Task ID does not match API route", 1, "aiSaid", nil))
conv.SendToClientChan <- resByte
return errors.New("Task ID does not match API route, expected aiSaid")
}
conv.ActiveTask = activeTask
}
} else if chatBody.WApi == "xObjSubmitReq" {
if chatBody.Data.TaskID == "" {
resByte, _ := json.Marshal(serializer.WsResponse("Task ID is missing for xObjSubmitReq", 1, "aiSaid", nil))
conv.SendToClientChan <- resByte
return errors.New("Missing task ID for xObjSubmitReq")
}
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask.GetTaskType() != task.Question {
resByte, _ := json.Marshal(serializer.WsResponse("Task ID does not match API route", 1, "aiSaid", nil))
conv.SendToClientChan <- resByte
return errors.New("Task ID does not match API route")
}
conv.ActiveTask = activeTask
} else {
resByte, _ := json.Marshal(serializer.WsResponse("Unknown API route", 1, "aiSaid", nil))
conv.SendToClientChan <- resByte
return errors.New("Unknown API route")
}
// Update the user's last message time
conv.ActiveTask.UpdateTaskLastUserSaid()
doneChan := make(chan string)
// Run the task with the user's data
go conv.ActiveTask.Run(doneChan, chatBody.Data)
// Wait for the task to finish processing
result := <-doneChan
if result == "done" {
// Task is done; switch to the next task
conv.SwitchTask(useridObj)
} else if result == "continue" {
// The task continues; no action needed
return nil
} else {
log.Println("Task failed due to:", result)
resByte, _ := json.Marshal(serializer.WsResponse(result, 1, "aiSaid", nil))
conv.SendToClientChan <- resByte
return errors.New(result)
}
return nil
}