feat(captain): align task payload persistence
This commit is contained in:
@@ -565,10 +565,10 @@ func Bootstrap(env string) (*App, error) {
|
||||
captainCustomToolService := service.NewCaptainCustomToolService(captainCustomToolRepo)
|
||||
copilotService := service.NewCopilotService(copilotThreadRepo, copilotMessageRepo, copilotSuggestionRepo, llmProvider, captainAssistantRepo)
|
||||
copilotContextService := service.NewCopilotContextService(messageRepo, conversationRepo, contactRepo, llmProvider)
|
||||
captainTaskService := service.NewCaptainTaskService(captainAssistantRepo, captainAssistantResponseRepo, captainCustomToolRepo, conversationRepo, messageRepo, llmProvider, copilotContextService)
|
||||
captainTaskService := service.NewCaptainTaskService(captainAssistantRepo, captainAssistantResponseRepo, captainCustomToolRepo, conversationRepo, messageRepo, llmProvider, copilotContextService, copilotSuggestionRepo)
|
||||
conversationInsightService := service.NewConversationInsightService(conversationRepo, messageRepo, captainAssistantRepo, llmProvider)
|
||||
captainPreferenceService := service.NewCaptainPreferenceService(captainPreferenceRepo, accountRepo)
|
||||
captainTaskExtendedService := service.NewCaptainTaskExtendedService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider)
|
||||
captainTaskExtendedService := service.NewCaptainTaskExtendedService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider, copilotSuggestionRepo)
|
||||
captainAssistantResponseService := service.NewCaptainAssistantResponseService(captainAssistantRepo, captainAssistantResponseRepo, conversationRepo, messageRepo, captainPreferenceRepo, llmProvider)
|
||||
captainBulkActionService := service.NewCaptainBulkActionService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider, captainTaskExtendedService, captainAssistantResponseService)
|
||||
captainBulkActionService.SetCaptainResourceRepos(captainAssistantResponseRepo, captainDocumentRepo)
|
||||
|
||||
@@ -30,6 +30,22 @@ func (h *CaptainTaskExtendedHandler) LabelSuggestion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if c.Request.Method == http.MethodPost {
|
||||
var req service.ChatwootLabelSuggestionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid request body: "+err.Error())
|
||||
return
|
||||
}
|
||||
result, err := h.svc.LabelSuggestion(c.Request.Context(), uint(accountID), &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Label suggestion: %v", err)
|
||||
renderCaptainTaskError(c, err)
|
||||
return
|
||||
}
|
||||
renderCaptainExtendedTaskResult(c, result)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse conversation_ids from query param (comma-separated)
|
||||
convIDsStr := c.Query("conversation_ids")
|
||||
if convIDsStr == "" {
|
||||
@@ -69,6 +85,22 @@ func (h *CaptainTaskExtendedHandler) FollowUp(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if c.Request.Method == http.MethodPost {
|
||||
var req service.ChatwootFollowUpRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid request body: "+err.Error())
|
||||
return
|
||||
}
|
||||
result, err := h.svc.FollowUp(c.Request.Context(), uint(accountID), &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Follow-up: %v", err)
|
||||
renderCaptainTaskError(c, err)
|
||||
return
|
||||
}
|
||||
renderCaptainExtendedTaskResult(c, result)
|
||||
return
|
||||
}
|
||||
|
||||
convIDsStr := c.Query("conversation_ids")
|
||||
if convIDsStr == "" {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "conversation_ids required")
|
||||
@@ -98,6 +130,18 @@ func (h *CaptainTaskExtendedHandler) FollowUp(c *gin.Context) {
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func renderCaptainExtendedTaskResult(c *gin.Context, result *service.ChatwootTaskResult) {
|
||||
if result == nil || result.Message == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"message": nil})
|
||||
return
|
||||
}
|
||||
payload := gin.H{"message": *result.Message}
|
||||
if result.FollowUpContext != nil {
|
||||
payload["follow_up_context"] = result.FollowUpContext
|
||||
}
|
||||
c.JSON(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
// parseUintSlice parses a comma-separated string of uint values.
|
||||
func parseUintSlice(s string) ([]uint, error) {
|
||||
parts := strings.Split(s, ",")
|
||||
@@ -114,4 +158,4 @@ func parseUintSlice(s string) ([]uint, error) {
|
||||
result = append(result, uint(v))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -47,12 +48,14 @@ func setupTaskExtendedHandlerTest(t *testing.T, mockLLM llm.Provider) (*CaptainT
|
||||
&model.Message{},
|
||||
&model.Inbox{},
|
||||
&model.Contact{},
|
||||
&model.CopilotSuggestionMessage{},
|
||||
))
|
||||
convRepo := repository.NewConversationRepo(db)
|
||||
msgRepo := repository.NewMessageRepo(db)
|
||||
assistantRepo := repository.NewCaptainAssistantRepo(db)
|
||||
prefRepo := repository.NewCaptainPreferenceRepo(db)
|
||||
svc := service.NewCaptainTaskExtendedService(convRepo, msgRepo, assistantRepo, prefRepo, mockLLM)
|
||||
suggestionRepo := repository.NewCopilotSuggestionRepo(db)
|
||||
svc := service.NewCaptainTaskExtendedService(convRepo, msgRepo, assistantRepo, prefRepo, mockLLM, suggestionRepo)
|
||||
handler := NewCaptainTaskExtendedHandler(svc)
|
||||
return handler, db
|
||||
}
|
||||
@@ -103,6 +106,40 @@ func TestCaptainTaskExtendedHandler_LabelSuggestion_MissingConversationIDs(t *te
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainTaskExtendedHandler_LabelSuggestion_ChatwootPostRawPayload(t *testing.T) {
|
||||
mockLLM := &mockTaskExtHandlerLLM{
|
||||
response: &llm.ChatResponse{Choices: []llm.ChatChoice{{Message: llm.ChatMessage{Role: "assistant", Content: "billing, urgent"}}}},
|
||||
}
|
||||
handler, db := setupTaskExtendedHandlerTest(t, mockLLM)
|
||||
displayID := uint(77)
|
||||
inbox := &model.Inbox{AccountID: 1, Name: "Inbox", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
conv := &model.Conversation{AccountID: 1, InboxID: inbox.ID, DisplayID: &displayID, Status: "open", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conv).Error)
|
||||
msg := &model.Message{ConversationID: conv.ID, AccountID: 1, InboxID: inbox.ID, SenderType: "contact", Content: "billing help", ContentType: "text", MessageType: "incoming"}
|
||||
require.NoError(t, db.Create(msg).Error)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/tasks/label_suggestion", bytes.NewReader([]byte(`{"conversation_display_id":77}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.LabelSuggestion(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var resp map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
assert.Equal(t, "billing, urgent", resp["message"])
|
||||
assert.NotContains(t, resp, "success")
|
||||
require.Contains(t, resp, "follow_up_context")
|
||||
|
||||
var stored []model.CopilotSuggestionMessage
|
||||
require.NoError(t, db.Find(&stored).Error)
|
||||
require.Len(t, stored, 1)
|
||||
assert.Equal(t, "billing, urgent", stored[0].Content)
|
||||
}
|
||||
|
||||
func TestCaptainTaskExtendedHandler_FollowUp(t *testing.T) {
|
||||
mockLLM := &mockTaskExtHandlerLLM{
|
||||
response: &llm.ChatResponse{
|
||||
@@ -143,3 +180,42 @@ func TestCaptainTaskExtendedHandler_FollowUp_MissingConversationIDs(t *testing.T
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainTaskExtendedHandler_FollowUp_ChatwootPostUpdatesContext(t *testing.T) {
|
||||
mockLLM := &mockTaskExtHandlerLLM{
|
||||
response: &llm.ChatResponse{Choices: []llm.ChatChoice{{Message: llm.ChatMessage{Role: "assistant", Content: "Refined answer"}}}},
|
||||
}
|
||||
handler, db := setupTaskExtendedHandlerTest(t, mockLLM)
|
||||
displayID := uint(88)
|
||||
inbox := &model.Inbox{AccountID: 1, Name: "Inbox", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
conv := &model.Conversation{AccountID: 1, InboxID: inbox.ID, DisplayID: &displayID, Status: "open", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conv).Error)
|
||||
|
||||
body := []byte(`{
|
||||
"conversation_display_id": 88,
|
||||
"message": "Make it warmer",
|
||||
"follow_up_context": {
|
||||
"event_name": "professional",
|
||||
"original_context": "Original draft",
|
||||
"last_response": "Previous answer",
|
||||
"conversation_history": []
|
||||
}
|
||||
}`)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/tasks/follow_up", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.FollowUp(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var resp map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
assert.Equal(t, "Refined answer", resp["message"])
|
||||
ctx := resp["follow_up_context"].(map[string]interface{})
|
||||
assert.Equal(t, "Refined answer", ctx["last_response"])
|
||||
history := ctx["conversation_history"].([]interface{})
|
||||
require.Len(t, history, 2)
|
||||
}
|
||||
|
||||
@@ -45,11 +45,11 @@ func (h *CaptainTaskHandler) ReplySuggestion(c *gin.Context) {
|
||||
result, err := h.svc.ReplySuggestion(c.Request.Context(), uint(accountID), &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("ReplySuggestion: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to generate reply suggestions")
|
||||
renderCaptainTaskError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
renderCaptainTaskPayload(c, result.Message, result.FollowUpContext)
|
||||
}
|
||||
|
||||
// Summarize generates a concise summary of a conversation.
|
||||
@@ -70,11 +70,11 @@ func (h *CaptainTaskHandler) Summarize(c *gin.Context) {
|
||||
result, err := h.svc.Summarize(c.Request.Context(), uint(accountID), &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Summarize: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to summarize conversation")
|
||||
renderCaptainTaskError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
renderCaptainTaskPayload(c, result.Message, result.FollowUpContext)
|
||||
}
|
||||
|
||||
// Rewrite rewrites a draft message to improve tone, clarity, or language.
|
||||
@@ -95,11 +95,11 @@ func (h *CaptainTaskHandler) Rewrite(c *gin.Context) {
|
||||
result, err := h.svc.Rewrite(c.Request.Context(), uint(accountID), &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Rewrite: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to rewrite message")
|
||||
renderCaptainTaskError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
renderCaptainTaskPayload(c, result.Message, result.FollowUpContext)
|
||||
}
|
||||
|
||||
// --- SSE Streaming Endpoints (M12) ---
|
||||
@@ -280,3 +280,20 @@ func captainEscapeJSONString(s string) string {
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
|
||||
func renderCaptainTaskPayload(c *gin.Context, message string, followUpContext map[string]interface{}) {
|
||||
payload := gin.H{"message": message}
|
||||
if followUpContext != nil {
|
||||
payload["follow_up_context"] = followUpContext
|
||||
}
|
||||
c.JSON(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func renderCaptainTaskError(c *gin.Context, err error) {
|
||||
status, message, ok := service.CaptainTaskErrorStatus(err)
|
||||
if !ok {
|
||||
status = http.StatusUnprocessableEntity
|
||||
message = err.Error()
|
||||
}
|
||||
c.JSON(status, gin.H{"error": message})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/llm"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type mockCaptainTaskHandlerLLM struct {
|
||||
response *llm.ChatResponse
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *mockCaptainTaskHandlerLLM) ChatCompletion(_ context.Context, _ llm.ChatRequest) (*llm.ChatResponse, error) {
|
||||
return m.response, m.err
|
||||
}
|
||||
func (m *mockCaptainTaskHandlerLLM) CreateEmbedding(_ context.Context, _ llm.EmbeddingRequest) (*llm.EmbeddingResponse, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockCaptainTaskHandlerLLM) ChatCompletionStream(_ context.Context, _ llm.ChatRequest, _ func(llm.StreamChunk) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func setupCaptainTaskHandlerTest(t *testing.T, provider llm.Provider) (*CaptainTaskHandler, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Conversation{},
|
||||
&model.Message{},
|
||||
&model.CaptainAssistant{},
|
||||
&model.CaptainAssistantResponse{},
|
||||
&model.CaptainCustomTool{},
|
||||
&model.CaptainDocument{},
|
||||
&model.CopilotSuggestionMessage{},
|
||||
))
|
||||
assistantRepo := repository.NewCaptainAssistantRepo(db)
|
||||
responseRepo := repository.NewCaptainAssistantResponseRepo(db)
|
||||
customToolRepo := repository.NewCaptainCustomToolRepo(db)
|
||||
conversationRepo := repository.NewConversationRepo(db)
|
||||
messageRepo := repository.NewMessageRepo(db)
|
||||
suggestionRepo := repository.NewCopilotSuggestionRepo(db)
|
||||
svc := service.NewCaptainTaskService(assistantRepo, responseRepo, customToolRepo, conversationRepo, messageRepo, provider, nil, suggestionRepo)
|
||||
return NewCaptainTaskHandler(svc), db
|
||||
}
|
||||
|
||||
func TestCaptainTaskHandler_Summarize_ChatwootRawPayload(t *testing.T) {
|
||||
provider := &mockCaptainTaskHandlerLLM{response: &llm.ChatResponse{Choices: []llm.ChatChoice{{Message: llm.ChatMessage{Role: "assistant", Content: "Short summary"}}}}}
|
||||
handler, db := setupCaptainTaskHandlerTest(t, provider)
|
||||
displayID := uint(123)
|
||||
conv := &model.Conversation{AccountID: 1, DisplayID: &displayID, Status: "open", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conv).Error)
|
||||
require.NoError(t, db.Create(&model.Message{ConversationID: conv.ID, AccountID: 1, SenderType: "contact", MessageType: "incoming", Content: "Need help"}).Error)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/tasks/summarize", bytes.NewReader([]byte(`{"conversation_display_id":123}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Summarize(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var resp map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
assert.Equal(t, "Short summary", resp["message"])
|
||||
assert.NotContains(t, resp, "success")
|
||||
}
|
||||
|
||||
func TestCaptainTaskHandler_Rewrite_NoProviderRawDisabled(t *testing.T) {
|
||||
handler, _ := setupCaptainTaskHandlerTest(t, nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/tasks/rewrite", bytes.NewReader([]byte(`{"content":"hello","operation":"professional"}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Rewrite(c)
|
||||
|
||||
require.Equal(t, http.StatusUnprocessableEntity, w.Code)
|
||||
var resp map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
assert.Equal(t, "Captain is disabled", resp["error"])
|
||||
assert.NotContains(t, resp, "success")
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// --- Copilot Thread Model ---
|
||||
@@ -62,6 +65,30 @@ type CopilotMessage struct {
|
||||
|
||||
func (CopilotMessage) TableName() string { return "copilot_messages" }
|
||||
|
||||
// BeforeSave mirrors Chatwoot's CopilotMessage JSON key validation so
|
||||
// reloadable tool-call state stays compatible with the reused frontend.
|
||||
func (m *CopilotMessage) BeforeSave(tx *gorm.DB) error {
|
||||
if len(m.Message) == 0 {
|
||||
return nil
|
||||
}
|
||||
var msgMap map[string]interface{}
|
||||
if err := json.Unmarshal(m.Message, &msgMap); err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := map[string]bool{
|
||||
"content": true,
|
||||
"reasoning": true,
|
||||
"function_name": true,
|
||||
"reply_suggestion": true,
|
||||
}
|
||||
for key := range msgMap {
|
||||
if !allowed[key] {
|
||||
return fmt.Errorf("message contains invalid attribute: %s", key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMessageContent extracts the "content" field from the JSONB message.
|
||||
func (m *CopilotMessage) GetMessageContent() string {
|
||||
var msgMap map[string]interface{}
|
||||
|
||||
@@ -53,6 +53,47 @@ func TestCopilotMessageRepo_Create(t *testing.T) {
|
||||
assert.Equal(t, model.CopilotMessageTypeUser, msg.MessageType)
|
||||
}
|
||||
|
||||
func TestCopilotMessageRepo_Create_AllowsChatwootMessageKeys(t *testing.T) {
|
||||
db := setupTestDB(t, &model.CopilotThread{}, &model.CopilotMessage{})
|
||||
repo := NewCopilotMessageRepo(db)
|
||||
thread := createTestCopilotThread(t, db, 1, 1, "Tool Thread")
|
||||
message, _ := json.Marshal(map[string]interface{}{
|
||||
"content": "Looking up docs",
|
||||
"reasoning": "Need product data",
|
||||
"function_name": "search_documentation",
|
||||
"reply_suggestion": "Try this reply",
|
||||
})
|
||||
|
||||
err := repo.Create(context.Background(), &model.CopilotMessage{
|
||||
AccountID: 1,
|
||||
CopilotThreadID: thread.ID,
|
||||
MessageType: model.CopilotMessageTypeAssistant,
|
||||
Message: message,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestCopilotMessageRepo_Create_RejectsUnknownMessageKeys(t *testing.T) {
|
||||
db := setupTestDB(t, &model.CopilotThread{}, &model.CopilotMessage{})
|
||||
repo := NewCopilotMessageRepo(db)
|
||||
thread := createTestCopilotThread(t, db, 1, 1, "Bad Tool Thread")
|
||||
message, _ := json.Marshal(map[string]interface{}{
|
||||
"content": "hello",
|
||||
"unknown": "bad",
|
||||
})
|
||||
|
||||
err := repo.Create(context.Background(), &model.CopilotMessage{
|
||||
AccountID: 1,
|
||||
CopilotThreadID: thread.ID,
|
||||
MessageType: model.CopilotMessageTypeAssistant,
|
||||
Message: message,
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid attribute: unknown")
|
||||
}
|
||||
|
||||
// --- 2. GetByID ---
|
||||
func TestCopilotMessageRepo_GetByID(t *testing.T) {
|
||||
db := setupTestDB(t, &model.CopilotThread{}, &model.CopilotMessage{})
|
||||
@@ -181,4 +222,4 @@ func TestCopilotMessageRepo_DeleteByThread(t *testing.T) {
|
||||
require.NoError(t, errAfter)
|
||||
assert.Equal(t, int64(0), countAfter)
|
||||
assert.Len(t, msgsAfter, 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,10 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gochat/gochat/internal/llm"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
pkgvalidator "github.com/gochat/gochat/pkg/validator"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
pkgvalidator "github.com/gochat/gochat/pkg/validator"
|
||||
)
|
||||
|
||||
// CaptainTaskExtendedService provides label suggestion and follow-up features.
|
||||
@@ -20,6 +21,7 @@ type CaptainTaskExtendedService struct {
|
||||
messageRepo *repository.MessageRepo
|
||||
assistantRepo *repository.CaptainAssistantRepo
|
||||
preferenceRepo *repository.CaptainPreferenceRepo
|
||||
suggestionRepo *repository.CopilotSuggestionRepo
|
||||
llmProvider llm.Provider
|
||||
}
|
||||
|
||||
@@ -29,12 +31,18 @@ func NewCaptainTaskExtendedService(
|
||||
assistantRepo *repository.CaptainAssistantRepo,
|
||||
preferenceRepo *repository.CaptainPreferenceRepo,
|
||||
llmProvider llm.Provider,
|
||||
suggestionRepos ...*repository.CopilotSuggestionRepo,
|
||||
) *CaptainTaskExtendedService {
|
||||
var suggestionRepo *repository.CopilotSuggestionRepo
|
||||
if len(suggestionRepos) > 0 {
|
||||
suggestionRepo = suggestionRepos[0]
|
||||
}
|
||||
return &CaptainTaskExtendedService{
|
||||
conversationRepo: conversationRepo,
|
||||
messageRepo: messageRepo,
|
||||
assistantRepo: assistantRepo,
|
||||
preferenceRepo: preferenceRepo,
|
||||
suggestionRepo: suggestionRepo,
|
||||
llmProvider: llmProvider,
|
||||
}
|
||||
}
|
||||
@@ -81,6 +89,21 @@ type FollowUpResult struct {
|
||||
FollowUps []FollowUpTask `json:"follow_ups"`
|
||||
}
|
||||
|
||||
type ChatwootLabelSuggestionRequest struct {
|
||||
ConversationDisplayID uint `json:"conversation_display_id"`
|
||||
}
|
||||
|
||||
type ChatwootFollowUpRequest struct {
|
||||
FollowUpContext map[string]interface{} `json:"follow_up_context"`
|
||||
Message string `json:"message"`
|
||||
ConversationDisplayID uint `json:"conversation_display_id"`
|
||||
}
|
||||
|
||||
type ChatwootTaskResult struct {
|
||||
Message *string `json:"message"`
|
||||
FollowUpContext map[string]interface{} `json:"follow_up_context,omitempty"`
|
||||
}
|
||||
|
||||
// --- Helper: fetch conversation context for LLM ---
|
||||
|
||||
func (s *CaptainTaskExtendedService) fetchConversationMessages(ctx context.Context, conversationID uint) (string, error) {
|
||||
@@ -126,6 +149,85 @@ func (s *CaptainTaskExtendedService) buildAssistantContext(ctx context.Context,
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *CaptainTaskExtendedService) LabelSuggestion(ctx context.Context, accountID uint, req *ChatwootLabelSuggestionRequest) (*ChatwootTaskResult, error) {
|
||||
if s.llmProvider == nil {
|
||||
return nil, taskError(422, "Captain is disabled")
|
||||
}
|
||||
conversation, err := s.conversationRepo.FindByAccountAndDisplayIDOrID(ctx, accountID, req.ConversationDisplayID)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "Conversation not found")
|
||||
}
|
||||
msgs, err := s.fetchConversationMessages(ctx, conversation.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(msgs) == "" {
|
||||
return &ChatwootTaskResult{Message: nil}, nil
|
||||
}
|
||||
|
||||
llmResp, err := s.llmProvider.ChatCompletion(ctx, llm.ChatRequest{
|
||||
Messages: []llm.ChatMessage{
|
||||
{Role: "system", Content: `Suggest concise labels for this customer support conversation. Return only a comma-separated label list.`},
|
||||
{Role: "user", Content: msgs},
|
||||
},
|
||||
Temperature: 0.2,
|
||||
MaxTokens: 256,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if llmResp == nil || len(llmResp.Choices) == 0 {
|
||||
return &ChatwootTaskResult{Message: nil}, nil
|
||||
}
|
||||
message := strings.TrimSpace(llmResp.Choices[0].Message.Content)
|
||||
if message == "" {
|
||||
return &ChatwootTaskResult{Message: nil}, nil
|
||||
}
|
||||
s.persistChatwootTaskSuggestion(ctx, accountID, conversation.ID, message, model.CopilotSuggestionTypeSuggestion)
|
||||
return &ChatwootTaskResult{
|
||||
Message: &message,
|
||||
FollowUpContext: buildTaskFollowUpContext("label_suggestion", msgs, message, conversation.ChannelType),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *CaptainTaskExtendedService) FollowUp(ctx context.Context, accountID uint, req *ChatwootFollowUpRequest) (*ChatwootTaskResult, error) {
|
||||
if s.llmProvider == nil {
|
||||
return nil, taskError(422, "Captain is disabled")
|
||||
}
|
||||
if !validTaskFollowUpContext(req.FollowUpContext) {
|
||||
return nil, taskError(422, "Follow-up context missing")
|
||||
}
|
||||
conversation, err := s.conversationRepo.FindByAccountAndDisplayIDOrID(ctx, accountID, req.ConversationDisplayID)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "Conversation not found")
|
||||
}
|
||||
messages := []llm.ChatMessage{
|
||||
{Role: "system", Content: "You just performed a customer support assistant task. Refine the previous result based on the agent's feedback. Output only the refined reply."},
|
||||
{Role: "user", Content: fmt.Sprint(req.FollowUpContext["original_context"])},
|
||||
{Role: "assistant", Content: fmt.Sprint(req.FollowUpContext["last_response"])},
|
||||
}
|
||||
for _, historyMessage := range followUpHistory(req.FollowUpContext) {
|
||||
messages = append(messages, historyMessage)
|
||||
}
|
||||
messages = append(messages, llm.ChatMessage{Role: "user", Content: req.Message})
|
||||
|
||||
llmResp, err := s.llmProvider.ChatCompletion(ctx, llm.ChatRequest{
|
||||
Messages: messages,
|
||||
Temperature: 0.3,
|
||||
MaxTokens: 512,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if llmResp == nil || len(llmResp.Choices) == 0 {
|
||||
return nil, taskError(422, "No response from LLM")
|
||||
}
|
||||
message := llmResp.Choices[0].Message.Content
|
||||
updatedContext := updateTaskFollowUpContext(req.FollowUpContext, req.Message, message, conversation.ChannelType)
|
||||
s.persistChatwootTaskSuggestion(ctx, accountID, conversation.ID, message, model.CopilotSuggestionTypeSuggestion)
|
||||
return &ChatwootTaskResult{Message: &message, FollowUpContext: updatedContext}, nil
|
||||
}
|
||||
|
||||
// --- Label Suggestion (GET) ---
|
||||
// Reference: Chatwoot Captain::ConversationInsightController#suggest_labels
|
||||
|
||||
@@ -174,7 +276,7 @@ Respond in JSON format:
|
||||
}` + assistantCtx + promptSuffix
|
||||
|
||||
llmResp, err := s.llmProvider.ChatCompletion(ctx, llm.ChatRequest{
|
||||
Model: "",
|
||||
Model: "",
|
||||
Messages: []llm.ChatMessage{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: msgs},
|
||||
@@ -278,7 +380,7 @@ Respond in JSON format:
|
||||
}` + statusHint + assistantCtx + promptSuffix
|
||||
|
||||
llmResp, err := s.llmProvider.ChatCompletion(ctx, llm.ChatRequest{
|
||||
Model: "",
|
||||
Model: "",
|
||||
Messages: []llm.ChatMessage{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: msgs},
|
||||
@@ -321,3 +423,102 @@ Respond in JSON format:
|
||||
|
||||
return &FollowUpResult{FollowUps: followUps}, nil
|
||||
}
|
||||
|
||||
func buildTaskFollowUpContext(eventName, originalContext, lastResponse, channelType string) map[string]interface{} {
|
||||
ctx := map[string]interface{}{
|
||||
"event_name": eventName,
|
||||
"original_context": originalContext,
|
||||
"last_response": lastResponse,
|
||||
"conversation_history": []map[string]string{},
|
||||
}
|
||||
if channelType != "" {
|
||||
ctx["channel_type"] = channelType
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func validTaskFollowUpContext(ctx map[string]interface{}) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
eventName, _ := ctx["event_name"].(string)
|
||||
if !allowedTaskFollowUpEvent(eventName) {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(fmt.Sprint(ctx["original_context"])) != "" && strings.TrimSpace(fmt.Sprint(ctx["last_response"])) != ""
|
||||
}
|
||||
|
||||
func allowedTaskFollowUpEvent(eventName string) bool {
|
||||
switch eventName {
|
||||
case "professional", "casual", "friendly", "confident", "straightforward", "fix_spelling_grammar", "improve", "summarize", "reply_suggestion", "label_suggestion":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func followUpHistory(ctx map[string]interface{}) []llm.ChatMessage {
|
||||
raw, ok := ctx["conversation_history"].([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
messages := make([]llm.ChatMessage, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
m, ok := item.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
role := fmt.Sprint(m["role"])
|
||||
content := fmt.Sprint(m["content"])
|
||||
if role == "" || content == "" {
|
||||
continue
|
||||
}
|
||||
messages = append(messages, llm.ChatMessage{Role: role, Content: content})
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func updateTaskFollowUpContext(ctx map[string]interface{}, userMessage, assistantMessage, channelType string) map[string]interface{} {
|
||||
history := make([]map[string]string, 0)
|
||||
if raw, ok := ctx["conversation_history"].([]interface{}); ok {
|
||||
for _, item := range raw {
|
||||
m, ok := item.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
history = append(history, map[string]string{"role": fmt.Sprint(m["role"]), "content": fmt.Sprint(m["content"])})
|
||||
}
|
||||
}
|
||||
history = append(history,
|
||||
map[string]string{"role": "user", "content": userMessage},
|
||||
map[string]string{"role": "assistant", "content": assistantMessage},
|
||||
)
|
||||
updated := map[string]interface{}{
|
||||
"event_name": ctx["event_name"],
|
||||
"original_context": ctx["original_context"],
|
||||
"last_response": assistantMessage,
|
||||
"conversation_history": history,
|
||||
}
|
||||
if channelType != "" {
|
||||
updated["channel_type"] = channelType
|
||||
} else if value, ok := ctx["channel_type"]; ok {
|
||||
updated["channel_type"] = value
|
||||
}
|
||||
return updated
|
||||
}
|
||||
|
||||
func (s *CaptainTaskExtendedService) persistChatwootTaskSuggestion(ctx context.Context, accountID, conversationID uint, content string, suggestionType model.CopilotSuggestionType) {
|
||||
if s.suggestionRepo == nil || strings.TrimSpace(content) == "" {
|
||||
return
|
||||
}
|
||||
msg := &model.CopilotSuggestionMessage{
|
||||
AccountID: accountID,
|
||||
ConversationID: conversationID,
|
||||
Content: content,
|
||||
SuggestionType: suggestionType,
|
||||
Status: model.CopilotSuggestionStatusPending,
|
||||
}
|
||||
if err := s.suggestionRepo.Create(ctx, msg); err != nil {
|
||||
applogger.L().Warnf("Captain extended task suggestion persistence failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/pgvector/pgvector-go"
|
||||
|
||||
"github.com/gochat/gochat/internal/llm"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
)
|
||||
@@ -17,14 +18,15 @@ import (
|
||||
// These tasks (reply_suggestion, summarize, rewrite) are independent of
|
||||
// CopilotThread flow — they provide one-shot AI suggestions for agents.
|
||||
type CaptainTaskService struct {
|
||||
assistantRepo *repository.CaptainAssistantRepo
|
||||
responseRepo *repository.CaptainAssistantResponseRepo
|
||||
customToolRepo *repository.CaptainCustomToolRepo
|
||||
conversationRepo *repository.ConversationRepo
|
||||
messageRepo *repository.MessageRepo
|
||||
llmProvider llm.Provider
|
||||
promptBuilder *SystemPromptBuilder
|
||||
copilotContextSvc *CopilotContextService // M12: context enrichment for richer prompts
|
||||
assistantRepo *repository.CaptainAssistantRepo
|
||||
responseRepo *repository.CaptainAssistantResponseRepo
|
||||
customToolRepo *repository.CaptainCustomToolRepo
|
||||
conversationRepo *repository.ConversationRepo
|
||||
messageRepo *repository.MessageRepo
|
||||
suggestionRepo *repository.CopilotSuggestionRepo
|
||||
llmProvider llm.Provider
|
||||
promptBuilder *SystemPromptBuilder
|
||||
copilotContextSvc *CopilotContextService // M12: context enrichment for richer prompts
|
||||
}
|
||||
|
||||
// NewCaptainTaskService creates a new CaptainTaskService.
|
||||
@@ -36,16 +38,22 @@ func NewCaptainTaskService(
|
||||
messageRepo *repository.MessageRepo,
|
||||
llmProvider llm.Provider,
|
||||
copilotContextSvc *CopilotContextService,
|
||||
suggestionRepos ...*repository.CopilotSuggestionRepo,
|
||||
) *CaptainTaskService {
|
||||
var suggestionRepo *repository.CopilotSuggestionRepo
|
||||
if len(suggestionRepos) > 0 {
|
||||
suggestionRepo = suggestionRepos[0]
|
||||
}
|
||||
return &CaptainTaskService{
|
||||
assistantRepo: assistantRepo,
|
||||
responseRepo: responseRepo,
|
||||
customToolRepo: customToolRepo,
|
||||
conversationRepo: conversationRepo,
|
||||
messageRepo: messageRepo,
|
||||
llmProvider: llmProvider,
|
||||
promptBuilder: NewSystemPromptBuilder(),
|
||||
copilotContextSvc: copilotContextSvc,
|
||||
assistantRepo: assistantRepo,
|
||||
responseRepo: responseRepo,
|
||||
customToolRepo: customToolRepo,
|
||||
conversationRepo: conversationRepo,
|
||||
messageRepo: messageRepo,
|
||||
suggestionRepo: suggestionRepo,
|
||||
llmProvider: llmProvider,
|
||||
promptBuilder: NewSystemPromptBuilder(),
|
||||
copilotContextSvc: copilotContextSvc,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,40 +61,71 @@ func NewCaptainTaskService(
|
||||
|
||||
// TaskReplySuggestionRequest is the DTO for reply_suggestion task.
|
||||
type TaskReplySuggestionRequest struct {
|
||||
AssistantID uint `json:"assistant_id" validate:"required"`
|
||||
ConversationID uint `json:"conversation_id" validate:"required"`
|
||||
Tone string `json:"tone"` // e.g. "friendly", "formal", "professional"
|
||||
AssistantID uint `json:"assistant_id"`
|
||||
ConversationID uint `json:"conversation_id"`
|
||||
ConversationDisplayID uint `json:"conversation_display_id"`
|
||||
Tone string `json:"tone"` // legacy local compatibility
|
||||
}
|
||||
|
||||
// TaskSummarizeRequest is the DTO for summarize task.
|
||||
type TaskSummarizeRequest struct {
|
||||
ConversationID uint `json:"conversation_id" validate:"required"`
|
||||
Language string `json:"language"` // summary output language, default "zh-CN"
|
||||
ConversationID uint `json:"conversation_id"`
|
||||
ConversationDisplayID uint `json:"conversation_display_id"`
|
||||
Language string `json:"language"` // legacy local compatibility
|
||||
}
|
||||
|
||||
// TaskRewriteRequest is the DTO for rewrite task.
|
||||
type TaskRewriteRequest struct {
|
||||
Content string `json:"content" validate:"required"`
|
||||
Tone string `json:"tone"` // desired tone, e.g. "friendly", "formal"
|
||||
Language string `json:"language"` // desired output language
|
||||
AssistantID uint `json:"assistant_id"` // optional: use assistant style guidelines
|
||||
Content string `json:"content" validate:"required"`
|
||||
Operation string `json:"operation"`
|
||||
ConversationDisplayID uint `json:"conversation_display_id"`
|
||||
Tone string `json:"tone"` // legacy local compatibility
|
||||
Language string `json:"language"` // legacy local compatibility
|
||||
AssistantID uint `json:"assistant_id"` // legacy local compatibility
|
||||
}
|
||||
|
||||
// TaskReplySuggestionResult holds the reply suggestion result.
|
||||
type TaskReplySuggestionResult struct {
|
||||
Suggestions []string `json:"suggestions"`
|
||||
Source string `json:"source"` // "llm", "rag+llm"
|
||||
Message string `json:"message"`
|
||||
FollowUpContext map[string]interface{} `json:"follow_up_context,omitempty"`
|
||||
Suggestions []string `json:"suggestions"`
|
||||
Source string `json:"source"` // "llm", "rag+llm"
|
||||
}
|
||||
|
||||
// TaskSummarizeResult holds the conversation summary result.
|
||||
type TaskSummarizeResult struct {
|
||||
Summary string `json:"summary"`
|
||||
Message string `json:"message"`
|
||||
FollowUpContext map[string]interface{} `json:"follow_up_context,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
// TaskRewriteResult holds the rewritten content result.
|
||||
type TaskRewriteResult struct {
|
||||
RewrittenContent string `json:"rewritten_content"`
|
||||
Tone string `json:"tone"`
|
||||
Message string `json:"message"`
|
||||
FollowUpContext map[string]interface{} `json:"follow_up_context,omitempty"`
|
||||
RewrittenContent string `json:"rewritten_content"`
|
||||
Tone string `json:"tone"`
|
||||
}
|
||||
|
||||
type CaptainTaskError struct {
|
||||
Status int
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *CaptainTaskError) Error() string { return e.Message }
|
||||
|
||||
func taskError(status int, message string) error {
|
||||
return &CaptainTaskError{Status: status, Message: message}
|
||||
}
|
||||
|
||||
func CaptainTaskErrorStatus(err error) (int, string, bool) {
|
||||
if err == nil {
|
||||
return 0, "", false
|
||||
}
|
||||
if taskErr, ok := err.(*CaptainTaskError); ok {
|
||||
return taskErr.Status, taskErr.Message, true
|
||||
}
|
||||
return 0, "", false
|
||||
}
|
||||
|
||||
// --- Reply Suggestion Task ---
|
||||
@@ -100,14 +139,28 @@ type TaskRewriteResult struct {
|
||||
// 4. Build prompt with conversation context + relevant FAQ answers
|
||||
// 5. Call LLM to generate reply suggestions
|
||||
func (s *CaptainTaskService) ReplySuggestion(ctx context.Context, accountID uint, req *TaskReplySuggestionRequest) (*TaskReplySuggestionResult, error) {
|
||||
// Fetch assistant config for prompt building
|
||||
assistant, err := s.assistantRepo.GetByID(ctx, req.AssistantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assistant not found: %w", err)
|
||||
if s.llmProvider == nil {
|
||||
return nil, taskError(422, "Captain is disabled")
|
||||
}
|
||||
|
||||
// Fetch conversation messages as context
|
||||
messages, err := s.fetchConversationContext(ctx, req.ConversationID)
|
||||
var assistantCfg *model.CaptainAssistant
|
||||
var err error
|
||||
if req.AssistantID > 0 {
|
||||
assistantCfg, err = s.assistantRepo.GetByAccountAndID(ctx, accountID, req.AssistantID)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "assistant not found")
|
||||
}
|
||||
} else {
|
||||
assistantCfg = &model.CaptainAssistant{AccountID: accountID, Name: "Captain"}
|
||||
assistantCfg.Config = []byte(`{}`)
|
||||
}
|
||||
|
||||
conversation, err := s.resolveTaskConversation(ctx, accountID, req.ConversationDisplayID, req.ConversationID)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "Conversation not found")
|
||||
}
|
||||
|
||||
messages, err := s.fetchConversationContext(ctx, conversation.ID)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("ReplySuggestion: conversation context fetch failed: %v, proceeding without context", err)
|
||||
messages = ""
|
||||
@@ -115,17 +168,19 @@ func (s *CaptainTaskService) ReplySuggestion(ctx context.Context, accountID uint
|
||||
|
||||
// Search relevant documents via embedding similarity (RAG)
|
||||
ragContext, source := "", "llm"
|
||||
docContext, err := s.searchDocumentation(ctx, req.AssistantID, messages)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("ReplySuggestion: document search failed: %v, proceeding without RAG", err)
|
||||
} else if docContext != "" {
|
||||
ragContext = docContext
|
||||
source = "rag+llm"
|
||||
if req.AssistantID > 0 {
|
||||
docContext, err := s.searchDocumentation(ctx, req.AssistantID, messages)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("ReplySuggestion: document search failed: %v, proceeding without RAG", err)
|
||||
} else if docContext != "" {
|
||||
ragContext = docContext
|
||||
source = "rag+llm"
|
||||
}
|
||||
}
|
||||
|
||||
// Build system prompt using prompt builder
|
||||
cfg, _ := assistant.GetConfig()
|
||||
systemPrompt := s.promptBuilder.BuildReplySuggestionPrompt(assistant, cfg, req.Tone, ragContext)
|
||||
cfg, _ := assistantCfg.GetConfig()
|
||||
systemPrompt := s.promptBuilder.BuildReplySuggestionPrompt(assistantCfg, cfg, req.Tone, ragContext)
|
||||
|
||||
// Build messages for LLM
|
||||
chatMessages := []llm.ChatMessage{
|
||||
@@ -152,10 +207,17 @@ func (s *CaptainTaskService) ReplySuggestion(ctx context.Context, accountID uint
|
||||
|
||||
// Parse suggestions from LLM response
|
||||
suggestions := parseSuggestions(resp.Choices[0].Message.Content)
|
||||
message := strings.Join(suggestions, "\n")
|
||||
if message == "" {
|
||||
message = resp.Choices[0].Message.Content
|
||||
}
|
||||
s.persistTaskSuggestion(ctx, accountID, conversation.ID, message, model.CopilotSuggestionTypeReply)
|
||||
|
||||
return &TaskReplySuggestionResult{
|
||||
Suggestions: suggestions,
|
||||
Source: source,
|
||||
Message: message,
|
||||
FollowUpContext: s.buildFollowUpContext("reply_suggestion", messages, message, conversation),
|
||||
Suggestions: suggestions,
|
||||
Source: source,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -164,14 +226,21 @@ func (s *CaptainTaskService) ReplySuggestion(ctx context.Context, accountID uint
|
||||
|
||||
// Summarize generates a concise summary of a conversation.
|
||||
func (s *CaptainTaskService) Summarize(ctx context.Context, accountID uint, req *TaskSummarizeRequest) (*TaskSummarizeResult, error) {
|
||||
if s.llmProvider == nil {
|
||||
return nil, taskError(422, "Captain is disabled")
|
||||
}
|
||||
conversation, err := s.resolveTaskConversation(ctx, accountID, req.ConversationDisplayID, req.ConversationID)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "Conversation not found")
|
||||
}
|
||||
// Fetch conversation messages
|
||||
messages, err := s.fetchConversationContext(ctx, req.ConversationID)
|
||||
messages, err := s.fetchConversationContext(ctx, conversation.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch conversation context: %w", err)
|
||||
}
|
||||
|
||||
if messages == "" {
|
||||
return nil, fmt.Errorf("no messages found for conversation %d", req.ConversationID)
|
||||
return nil, taskError(422, fmt.Sprintf("no messages found for conversation %d", conversation.ID))
|
||||
}
|
||||
|
||||
// Determine output language
|
||||
@@ -204,8 +273,13 @@ func (s *CaptainTaskService) Summarize(ctx context.Context, accountID uint, req
|
||||
return nil, fmt.Errorf("no response from LLM")
|
||||
}
|
||||
|
||||
message := resp.Choices[0].Message.Content
|
||||
s.persistTaskSuggestion(ctx, accountID, conversation.ID, message, model.CopilotSuggestionTypeSummary)
|
||||
|
||||
return &TaskSummarizeResult{
|
||||
Summary: resp.Choices[0].Message.Content,
|
||||
Message: message,
|
||||
FollowUpContext: s.buildFollowUpContext("summarize", messages, message, conversation),
|
||||
Summary: message,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -214,9 +288,18 @@ func (s *CaptainTaskService) Summarize(ctx context.Context, accountID uint, req
|
||||
|
||||
// Rewrite rewrites a draft message to improve tone, clarity, or language.
|
||||
func (s *CaptainTaskService) Rewrite(ctx context.Context, accountID uint, req *TaskRewriteRequest) (*TaskRewriteResult, error) {
|
||||
tone := req.Tone
|
||||
if tone == "" {
|
||||
tone = "professional"
|
||||
if s.llmProvider == nil {
|
||||
return nil, taskError(422, "Captain is disabled")
|
||||
}
|
||||
operation := req.Operation
|
||||
if operation == "" {
|
||||
operation = req.Tone
|
||||
}
|
||||
if operation == "" {
|
||||
operation = "professional"
|
||||
}
|
||||
if !isAllowedRewriteOperation(operation) {
|
||||
return nil, taskError(422, "Invalid operation: "+operation)
|
||||
}
|
||||
|
||||
language := req.Language
|
||||
@@ -224,10 +307,22 @@ func (s *CaptainTaskService) Rewrite(ctx context.Context, accountID uint, req *T
|
||||
language = "zh-CN"
|
||||
}
|
||||
|
||||
// Optionally use assistant guidelines for style
|
||||
styleGuidelines := ""
|
||||
var conversation *model.Conversation
|
||||
conversationContext := ""
|
||||
if req.ConversationDisplayID > 0 {
|
||||
resolved, err := s.resolveTaskConversation(ctx, accountID, req.ConversationDisplayID, 0)
|
||||
if err != nil {
|
||||
return nil, taskError(422, "Conversation not found")
|
||||
}
|
||||
conversation = resolved
|
||||
if operation == "improve" {
|
||||
conversationContext, _ = s.fetchConversationContext(ctx, conversation.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if req.AssistantID > 0 {
|
||||
assistant, err := s.assistantRepo.GetByID(ctx, req.AssistantID)
|
||||
assistant, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, req.AssistantID)
|
||||
if err == nil {
|
||||
cfg, _ := assistant.GetConfig()
|
||||
if cfg.Instructions != "" {
|
||||
@@ -238,9 +333,12 @@ func (s *CaptainTaskService) Rewrite(ctx context.Context, accountID uint, req *T
|
||||
}
|
||||
}
|
||||
}
|
||||
if conversationContext != "" {
|
||||
styleGuidelines += "\nConversation context: " + conversationContext
|
||||
}
|
||||
|
||||
// Build rewrite prompt using prompt builder
|
||||
systemPrompt := s.promptBuilder.BuildRewritePrompt(tone, language, styleGuidelines)
|
||||
systemPrompt := s.promptBuilder.BuildRewritePrompt(operation, language, styleGuidelines)
|
||||
|
||||
chatMessages := []llm.ChatMessage{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
@@ -263,9 +361,16 @@ func (s *CaptainTaskService) Rewrite(ctx context.Context, accountID uint, req *T
|
||||
return nil, fmt.Errorf("no response from LLM")
|
||||
}
|
||||
|
||||
message := resp.Choices[0].Message.Content
|
||||
if conversation != nil {
|
||||
s.persistTaskSuggestion(ctx, accountID, conversation.ID, message, model.CopilotSuggestionTypeSuggestion)
|
||||
}
|
||||
|
||||
return &TaskRewriteResult{
|
||||
RewrittenContent: resp.Choices[0].Message.Content,
|
||||
Tone: tone,
|
||||
Message: message,
|
||||
FollowUpContext: s.buildFollowUpContext(operation, req.Content, message, conversation),
|
||||
RewrittenContent: message,
|
||||
Tone: operation,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -294,6 +399,54 @@ func (s *CaptainTaskService) fetchConversationContext(ctx context.Context, conve
|
||||
return builder.String(), nil
|
||||
}
|
||||
|
||||
func (s *CaptainTaskService) resolveTaskConversation(ctx context.Context, accountID, displayID, legacyID uint) (*model.Conversation, error) {
|
||||
if displayID > 0 {
|
||||
return s.conversationRepo.FindByAccountAndDisplayIDOrID(ctx, accountID, displayID)
|
||||
}
|
||||
if legacyID > 0 {
|
||||
return s.conversationRepo.FindByAccountAndDisplayIDOrID(ctx, accountID, legacyID)
|
||||
}
|
||||
return nil, fmt.Errorf("conversation_display_id required")
|
||||
}
|
||||
|
||||
func isAllowedRewriteOperation(operation string) bool {
|
||||
switch operation {
|
||||
case "fix_spelling_grammar", "improve", "casual", "professional", "friendly", "confident", "straightforward":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CaptainTaskService) buildFollowUpContext(eventName, originalContext, lastResponse string, conversation *model.Conversation) map[string]interface{} {
|
||||
ctx := map[string]interface{}{
|
||||
"event_name": eventName,
|
||||
"original_context": originalContext,
|
||||
"last_response": lastResponse,
|
||||
"conversation_history": []map[string]string{},
|
||||
}
|
||||
if conversation != nil {
|
||||
ctx["channel_type"] = conversation.ChannelType
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (s *CaptainTaskService) persistTaskSuggestion(ctx context.Context, accountID, conversationID uint, content string, suggestionType model.CopilotSuggestionType) {
|
||||
if s.suggestionRepo == nil || strings.TrimSpace(content) == "" || conversationID == 0 {
|
||||
return
|
||||
}
|
||||
msg := &model.CopilotSuggestionMessage{
|
||||
AccountID: accountID,
|
||||
ConversationID: conversationID,
|
||||
Content: content,
|
||||
SuggestionType: suggestionType,
|
||||
Status: model.CopilotSuggestionStatusPending,
|
||||
}
|
||||
if err := s.suggestionRepo.Create(ctx, msg); err != nil {
|
||||
applogger.L().Warnf("Captain task suggestion persistence failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// searchDocumentation performs embedding-based similarity search on assistant responses.
|
||||
// Reference: Chatwoot Captain::Llm::SearchReplyDocumentationService
|
||||
func (s *CaptainTaskService) searchDocumentation(ctx context.Context, assistantID uint, query string) (string, error) {
|
||||
|
||||
@@ -77,6 +77,7 @@ func setupCaptainTaskService(t *testing.T) (*gorm.DB, *mockLLMProvider, *Captain
|
||||
&model.CaptainAssistantResponse{},
|
||||
&model.CaptainCustomTool{},
|
||||
&model.CaptainDocument{},
|
||||
&model.CopilotSuggestionMessage{},
|
||||
); err != nil {
|
||||
t.Fatalf("无法自动迁移模型: %v", err)
|
||||
}
|
||||
@@ -92,12 +93,13 @@ func setupCaptainTaskService(t *testing.T) (*gorm.DB, *mockLLMProvider, *Captain
|
||||
customToolRepo := repository.NewCaptainCustomToolRepo(db)
|
||||
conversationRepo := repository.NewConversationRepo(db)
|
||||
messageRepo := repository.NewMessageRepo(db)
|
||||
suggestionRepo := repository.NewCopilotSuggestionRepo(db)
|
||||
contactRepo := repository.NewContactRepo(db)
|
||||
|
||||
// M12: CopilotContextService for context enrichment in streaming
|
||||
copilotContextSvc := NewCopilotContextService(messageRepo, conversationRepo, contactRepo, mockProvider)
|
||||
|
||||
svc := NewCaptainTaskService(assistantRepo, responseRepo, customToolRepo, conversationRepo, messageRepo, mockProvider, copilotContextSvc)
|
||||
svc := NewCaptainTaskService(assistantRepo, responseRepo, customToolRepo, conversationRepo, messageRepo, mockProvider, copilotContextSvc, suggestionRepo)
|
||||
|
||||
return db, mockProvider, svc
|
||||
}
|
||||
@@ -121,8 +123,10 @@ func createTestAssistant(t *testing.T, db *gorm.DB, accountID uint, name string)
|
||||
func createTestConversationWithMessages(t *testing.T, db *gorm.DB, accountID uint, msgs []struct{ sender, content string }) *model.Conversation {
|
||||
t.Helper()
|
||||
conv := &model.Conversation{
|
||||
AccountID: accountID,
|
||||
Status: "open",
|
||||
AccountID: accountID,
|
||||
Status: "open",
|
||||
ChannelType: "web_widget",
|
||||
Channel: "web_widget",
|
||||
}
|
||||
if err := db.Create(conv).Error; err != nil {
|
||||
t.Fatalf("无法创建测试会话: %v", err)
|
||||
@@ -199,6 +203,60 @@ func TestCaptainTaskService_Summarize_成功(t *testing.T) {
|
||||
assert.NotEmpty(t, result.Summary)
|
||||
}
|
||||
|
||||
func TestCaptainTaskService_Summarize_ChatwootDisplayIDPersistsSuggestion(t *testing.T) {
|
||||
db, mockProvider, svc := setupCaptainTaskService(t)
|
||||
account := createTestAccount(t, db)
|
||||
displayID := uint(42)
|
||||
conv := createTestConversationWithMessages(t, db, account.ID, []struct{ sender, content string }{
|
||||
{"contact", "I need help with my invoice"},
|
||||
{"agent", "I can help with billing"},
|
||||
})
|
||||
require.NoError(t, db.Model(conv).Update("display_id", displayID).Error)
|
||||
|
||||
mockProvider.chatResponse = makeChatResponse("Customer needs billing help")
|
||||
|
||||
result, err := svc.Summarize(context.Background(), account.ID, &TaskSummarizeRequest{
|
||||
ConversationDisplayID: displayID,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Customer needs billing help", result.Message)
|
||||
require.NotNil(t, result.FollowUpContext)
|
||||
assert.Equal(t, "summarize", result.FollowUpContext["event_name"])
|
||||
|
||||
var stored []model.CopilotSuggestionMessage
|
||||
require.NoError(t, db.Where("account_id = ? AND conversation_id = ?", account.ID, conv.ID).Find(&stored).Error)
|
||||
require.Len(t, stored, 1)
|
||||
assert.Equal(t, "Customer needs billing help", stored[0].Content)
|
||||
assert.Equal(t, model.CopilotSuggestionTypeSummary, stored[0].SuggestionType)
|
||||
}
|
||||
|
||||
func TestCaptainTaskService_Rewrite_InvalidOperation(t *testing.T) {
|
||||
_, _, svc := setupCaptainTaskService(t)
|
||||
|
||||
result, err := svc.Rewrite(context.Background(), 1, &TaskRewriteRequest{Content: "hello", Operation: "pirate"})
|
||||
|
||||
assert.Nil(t, result)
|
||||
status, message, ok := CaptainTaskErrorStatus(err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 422, status)
|
||||
assert.Equal(t, "Invalid operation: pirate", message)
|
||||
}
|
||||
|
||||
func TestCaptainTaskService_Rewrite_NoProviderDisabled(t *testing.T) {
|
||||
db, _, svc := setupCaptainTaskService(t)
|
||||
svc.llmProvider = nil
|
||||
account := createTestAccount(t, db)
|
||||
|
||||
result, err := svc.Rewrite(context.Background(), account.ID, &TaskRewriteRequest{Content: "hello", Operation: "professional"})
|
||||
|
||||
assert.Nil(t, result)
|
||||
status, message, ok := CaptainTaskErrorStatus(err)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 422, status)
|
||||
assert.Equal(t, "Captain is disabled", message)
|
||||
}
|
||||
|
||||
func TestCaptainTaskService_Summarize_无消息(t *testing.T) {
|
||||
db, _, svc := setupCaptainTaskService(t)
|
||||
account := createTestAccount(t, db)
|
||||
@@ -416,4 +474,4 @@ func TestParseSuggestions_空内容(t *testing.T) {
|
||||
content := ""
|
||||
result := parseSuggestions(content)
|
||||
assert.Len(t, result, 1)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user