Activate Captain AI features: config, RAG routes, conversation handler

Phase 1 of AI_FEATURE_ROADMAP.md:

1. config.yaml: Add captain configuration section (llm_provider, llm_model,
   llm_api_key, llm_base_url, embedding_model, embedding_dims, max_tokens,
   temperature). Secrets injected via GOCHAT_CAPTAIN_LLM_API_KEY env var.

2. RAG route registration:
   - bootstrap.go: instantiate RAGService + RAGHandler, add to Handlers
   - router.go: register POST /captain/rag/query + /captain/rag/index/:response_id
   - rag_handler.go: fix account_id param name (was "id", route uses "account_id")

3. CaptainConversationService activation:
   - Remove "_ = captainConversationService" ignore in bootstrap.go
   - Create CaptainConversationHandler with BuildResponse endpoint
   - Register POST /captain/conversations/:conversation_id/respond route
   - Fix account_id param name in handler

Verified:
- go build ./... passes
- go vet passes on all modified packages
- go test passes (llm + service packages)
- Server starts with captain config loaded
- RAG query/index routes return proper handler responses (not 404)
- Conversation respond route returns proper skip for non-pending conversations
- Existing captain routes unaffected (assistants list still works)
This commit is contained in:
2026-07-08 15:38:08 +08:00
parent e8d1876478
commit 42b8b6c7f9
5 changed files with 105 additions and 5 deletions
+15 -1
View File
@@ -69,6 +69,20 @@ saml:
clock_drift_tolerance: 180 # seconds of allowed clock drift for NotOnOrAfter validation
attribute_map:
email: "email" # SAML attribute → GoChat email field
display_name: "displayName" # SAML attribute → GoChat name field
display_name: "displayName" # SAML attribute → GoChat display name field
first_name: "firstName" # SAML attribute → first name component
last_name: "lastName" # SAML attribute → last name component
# Captain AI + Copilot feature configuration
# Reference: Chatwoot config/features.yml + ENV variables for Captain
# Secrets (llm_api_key) should be injected via .env: GOCHAT_CAPTAIN_LLM_API_KEY
captain:
enabled: true
llm_provider: "openai" # openai, azure, custom
llm_model: "gpt-4o-mini" # gpt-4o, gpt-3.5-turbo, etc.
llm_api_key: "" # inject via GOCHAT_CAPTAIN_LLM_API_KEY in .env
llm_base_url: "https://api.openai.com/v1" # custom endpoint for domestic providers
embedding_model: "text-embedding-3-small"
embedding_dims: 1536
max_tokens: 1024
temperature: 0.7
+7 -2
View File
@@ -14,7 +14,6 @@ import (
"github.com/gochat/gochat/internal/campaign"
"github.com/gochat/gochat/internal/canned"
"github.com/gochat/gochat/internal/channel"
"github.com/gochat/gochat/internal/wsevent"
emailchannel "github.com/gochat/gochat/internal/channel/email"
facebookchannel "github.com/gochat/gochat/internal/channel/facebook"
googlechannel "github.com/gochat/gochat/internal/channel/google"
@@ -42,6 +41,7 @@ import (
"github.com/gochat/gochat/internal/service"
"github.com/gochat/gochat/internal/worker"
wspkg "github.com/gochat/gochat/internal/ws"
"github.com/gochat/gochat/internal/wsevent"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/spf13/viper"
"gorm.io/gorm"
@@ -591,7 +591,6 @@ func Bootstrap(env string) (*App, error) {
copilotService.SetWorkerPool(workerPool)
captainConversationService := service.NewCaptainConversationService(db, llmProvider)
captainConversationService.SetWorkerPool(workerPool)
_ = captainConversationService
copilotContextService := service.NewCopilotContextService(messageRepo, conversationRepo, contactRepo, llmProvider)
captainTaskService := service.NewCaptainTaskService(captainAssistantRepo, captainAssistantResponseRepo, captainCustomToolRepo, conversationRepo, messageRepo, llmProvider, copilotContextService, copilotSuggestionRepo)
conversationInsightService := service.NewConversationInsightService(conversationRepo, messageRepo, captainAssistantRepo, llmProvider)
@@ -601,6 +600,10 @@ func Bootstrap(env string) (*App, error) {
captainBulkActionService := service.NewCaptainBulkActionService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider, captainTaskExtendedService, captainAssistantResponseService)
captainBulkActionService.SetCaptainResourceRepos(captainAssistantResponseRepo, captainDocumentRepo)
// RAG service — knowledge base Q&A (embedding search + LLM generation)
// Reference: M12 PRD §Captain AI — RAG Knowledge Base Q&A
ragService := service.NewRAGService(captainAssistantResponseRepo, captainAssistantRepo, llmProvider)
// Analytics services (P11 — Reports/Analytics)
analyticsService := service.NewAnalyticsService(reportingEventRepo, reportingEventsRollupRepo)
analyticsService.SetWorkerPool(workerPool)
@@ -791,6 +794,8 @@ func Bootstrap(env string) (*App, error) {
CaptainTaskExtended: v1.NewCaptainTaskExtendedHandler(captainTaskExtendedService),
CaptainAssistantResponse: v1.NewCaptainAssistantResponseHandler(captainAssistantResponseService),
CaptainBulkAction: v1.NewCaptainBulkActionHandler(captainBulkActionService),
RAG: v1.NewRAGHandler(ragService),
CaptainConversation: v1.NewCaptainConversationHandler(captainConversationService),
Copilot: v1.NewCopilotHandler(copilotService),
Analytics: v1.NewAnalyticsHandler(analyticsService),
LiveReport: v1.NewLiveReportHandler(analyticsService),
@@ -0,0 +1,67 @@
package v1
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/service"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/gochat/gochat/pkg/response"
)
// CaptainConversationHandler handles Captain conversation-level AI auto-response.
// Reference: M12 PRD §Captain AI — Conversation Auto-Response (handoff mode)
//
// This handler exposes the CaptainConversationService, which generates AI
// responses for conversations bound to a Captain Assistant. When the AI
// determines a handoff is needed, the conversation is transferred to a human
// agent instead of sending an AI-generated reply.
type CaptainConversationHandler struct {
svc *service.CaptainConversationService
}
// NewCaptainConversationHandler creates a new CaptainConversationHandler.
func NewCaptainConversationHandler(svc *service.CaptainConversationService) *CaptainConversationHandler {
return &CaptainConversationHandler{svc: svc}
}
// BuildResponse triggers AI response generation for a conversation.
// The assistant must be bound to the conversation's inbox via CaptainInbox.
//
// POST /api/v1/accounts/:account_id/captain/conversations/:conversation_id/respond
func (h *CaptainConversationHandler) BuildResponse(c *gin.Context) {
accountID, err := strconv.ParseUint(c.Param("account_id"), 10, 64)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, "invalid_account_id", "Invalid account ID")
return
}
conversationID, err := strconv.ParseUint(c.Param("conversation_id"), 10, 64)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, "invalid_conversation_id", "Invalid conversation ID")
return
}
var req struct {
AssistantID uint `json:"assistant_id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, "invalid_request", err.Error())
return
}
msg, err := h.svc.BuildConversationResponseByAccount(c.Request.Context(), uint(accountID), uint(conversationID), req.AssistantID)
if err != nil {
applogger.L().Errorf("CaptainConversationHandler.BuildResponse: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, "response_failed", "Failed to generate AI response")
return
}
if msg == nil {
response.OK(c, map[string]any{"status": "skipped", "message": "Conversation not eligible for AI response"})
return
}
response.OK(c, map[string]any{"status": "sent", "message_id": msg.ID})
}
@@ -24,7 +24,7 @@ func NewRAGHandler(svc *service.RAGService) *RAGHandler {
// Query performs a RAG query against the knowledge base.
// POST /api/v1/accounts/:account_id/captain/rag/query
func (h *RAGHandler) Query(c *gin.Context) {
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
accountID, err := strconv.ParseUint(c.Param("account_id"), 10, 64)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, "invalid_account_id", "Invalid account ID")
return
+15 -1
View File
@@ -61,6 +61,8 @@ type Handlers struct {
CaptainTaskExtended *v1.CaptainTaskExtendedHandler
CaptainAssistantResponse *v1.CaptainAssistantResponseHandler
CaptainBulkAction *v1.CaptainBulkActionHandler
RAG *v1.RAGHandler
CaptainConversation *v1.CaptainConversationHandler
BulkAction *v1.BulkActionHandler
Copilot *v1.CopilotHandler
WebWidget *v1.WebWidgetHandler
@@ -1486,6 +1488,19 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
{
bulkActions.POST("/", h.CaptainBulkAction.Execute)
}
// RAG Knowledge Base Q&A (embedding search + LLM generation)
// POST /captain/rag/query — query the knowledge base
// POST /captain/rag/index/:id — index/re-index a response embedding
rag := captain.Group("/rag")
{
rag.POST("/query", h.RAG.Query)
rag.POST("/index/:response_id", h.RAG.IndexResponse)
}
// Captain Conversation auto-response (handoff mode)
// POST /captain/conversations/:conversation_id/respond
captain.POST("/conversations/:conversation_id/respond", h.CaptainConversation.BuildResponse)
}
// Draft messages — account-scoped search & count
@@ -1494,7 +1509,6 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
draftMessages.GET("/search", h.DraftMessage.Search)
draftMessages.GET("/count", h.DraftMessage.Count)
}
// Reports/Analytics routes (P11 — Reports/Analytics)
// Reference: Chatwoot reports_controller.rb + live_reports_controller.rb + summary_reports_controller.rb
reports := accountScoped.Group("/reports")