The issue you're experiencing is because, after adding a new Task to conv.TaskQueue in the SwitchTask method, there isn't any goroutine consuming tasks from conv.TaskQueue and executing them. To fix this, we need to implement a task processor that listens to conv.TaskQueue and runs the tasks as they arrive.
Here's how you can modify your code to address this:
1. Add a Task Processor to the Conversation Struct
First, let's add a method StartTaskProcessor to your Conversation struct that starts a goroutine to listen to TaskQueue and process tasks.
func (conv *Conversation) StartTaskProcessor() {
go func() {
for {
select {
case task := <-conv.TaskQueue:
conv.ActiveTask = task
task.Init()
}
}
}()
}
This goroutine continuously listens to conv.TaskQueue. When a Task is received, it sets it as the ActiveTask and calls its Init method to start it.
2. Initialize the Task Processor
Ensure that the task processor is started when the Conversation is created. You can modify your NewConversation constructor like this:
func NewConversation(userID string, sendToClientChan chan []byte) *Conversation {
conv := &Conversation{
ID: generateConversationID(),
UserID: userID,
TaskQueue: make(chan Task),
SendToClientChan: sendToClientChan,
}
conv.StartTaskProcessor()
return conv
}
Now, whenever a new Conversation is created, the task processor will start automatically.
3. Modify the ChatHandler to Use the Modified Conversation
In your ChatHandler, ensure that you're creating or retrieving the Conversation correctly:
func ChatHandler(c *gin.Context) {
// ... (existing code)
// Get or create the Conversation object
conv := task.GetConversation(userID)
if conv == nil {
// Create new Conversation and start the task processor
conv = task.NewConversation(userID, sendToClientChan)
} else {
conv.SendToClientChan = sendToClientChan
}
// ... (existing code)
}
This way, you ensure that the Conversation has the task processor running whether it's a new or existing conversation.
4. Adjust the SwitchTask Method
Your SwitchTask method seems to correctly add the new task to conv.TaskQueue. Ensure it continues to do so:
func (conv *Conversation) SwitchTask(uid primitive.ObjectID) {
log.Println("step into switch task")
currentTaskType := conv.ActiveTask.GetTaskType()
summaryService := service.NewUserSummaryService(uid)
stuProfile := summaryService.GetStuProfile()
switch currentTaskType {
case Question:
newTask := NewAITask("", stuProfile, 180, nil, uid, models.CHITCHATTASK, conv)
conv.TaskQueue <- newTask
// You can add other cases as needed
}
}
5. Review the runActiveTask Function
Since you're now handling task execution via the task processor, you might want to adjust how runActiveTask works. However, if runActiveTask is intended to handle the currently active task, you can leave it as is. Just ensure that when SwitchTask is called, the new task is added to the queue and will be processed by the task processor.
6. Ensure Task Implementations are Correct
Make sure that your Task implementations (e.g., AITask, EvaTask) have the Init method properly defined to initialize and run the task.
Complete Code Adjustments
Here's what your adjusted code might look like:
Conversation Struct:
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"`
}
func NewConversation(userID string, sendToClientChan chan []byte) *Conversation {
conv := &Conversation{
ID: generateConversationID(),
UserID: userID,
TaskQueue: make(chan Task),
SendToClientChan: sendToClientChan,
}
conv.StartTaskProcessor()
return conv
}
func (conv *Conversation) StartTaskProcessor() {
go func() {
for {
select {
case task := <-conv.TaskQueue:
conv.ActiveTask = task
task.Init()
}
}
}()
}
ChatHandler Adjustments:
func ChatHandler(c *gin.Context) {
// ... (existing code)
// Get or create the Conversation object
conv := task.GetConversation(userID)
if conv == nil {
// Create new Conversation and start the task processor
conv = task.NewConversation(userID, sendToClientChan)
} else {
conv.SendToClientChan = sendToClientChan
}
// ... (rest of your code)
}
Additional Considerations
-
Handling Multiple Tasks: If you expect multiple tasks to be processed in order, this setup will handle that as tasks are processed sequentially by the task processor.
-
Error Handling: Make sure to include error handling within your task processor and task Init methods to handle any unexpected issues during task execution.
-
Stopping the Task Processor: If you need to stop the task processor (e.g., when the conversation ends), you might want to include a mechanism to exit the goroutine gracefully.
Here's a modified StartTaskProcessor method with a context to handle cancellation:
func (conv *Conversation) StartTaskProcessor(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
log.Println("Task processor shutting down")
return
case task := <-conv.TaskQueue:
conv.ActiveTask = task
task.Init()
}
}
}()
}
Then, when you start the task processor, you can provide a context that can be cancelled when needed.
Example Usage with Context:
In ChatHandler, create a context and pass it to StartTaskProcessor:
func ChatHandler(c *gin.Context) {
// ... (existing code)
// Create a context that can be cancelled
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Get or create the Conversation object
conv := task.GetConversation(userID)
if conv == nil {
// Create new Conversation and start the task processor
conv = task.NewConversation(userID, sendToClientChan)
conv.StartTaskProcessor(ctx)
} else {
conv.SendToClientChan = sendToClientChan
}
// ... (rest of your code)
// When the connection is closed, cancel the context
defer cancel()
}
Make sure to manage the lifecycle of the context appropriately to avoid leaks or unintended cancellations.
Testing
After making these changes, test your application thoroughly:
-
Start a Conversation: Ensure that a new conversation starts correctly and the task processor is running.
-
Switching Tasks: Verify that when SwitchTask is called, the new task is added to the queue and executed by the task processor.
-
Multiple Tasks: If you queue multiple tasks, ensure they are processed in the correct order.
Debugging Tips
- Logging: Add logging statements in the task processor to trace when tasks are received and started.
func (conv *Conversation) StartTaskProcessor(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
log.Println("Task processor shutting down")
return
case task := <-conv.TaskQueue:
log.Println("Received new task:", task.GetTaskType())
conv.ActiveTask = task
task.Init()
}
}
}()
}
- Channel Buffering: Depending on your use case, you might want to make
TaskQueue a buffered channel to prevent blocking when adding tasks.
TaskQueue: make(chan Task, 10), // Buffer size of 10
Be cautious with buffered channels as they can hold tasks that might not be processed if the processor is stopped.
By adding a task processor to consume tasks from conv.TaskQueue, your application should now execute tasks added via conv.SwitchTask() correctly. This allows for better task management and scalability in your conversation handling logic.
Let me know if you need further assistance or if you encounter any other issues.