Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

12.8 KB
Raw Blame
//
//  Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

package handler

import (
	"encoding/json"
	"fmt"
	"net/http"
	"ragflow/internal/common"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"

	"ragflow/internal/service"

	"go.uber.org/zap"
)

// ChatHandler chat handler
type ChatHandler struct {
	chatService  *service.ChatService
	userService  *service.UserService
	searchSvc    *service.SearchService
	tenantSvc    *service.TenantService
	modelFactory *service.ModelFactory
	chunkSvc     service.Retriever
}

// NewChatHandler create chat handler
func NewChatHandler(chatService *service.ChatService, userService *service.UserService) *ChatHandler {
	return &ChatHandler{
		chatService: chatService,
		userService: userService,
	}
}

// SetMindMapDependencies sets dependencies used by POST /api/v1/chat/mindmap.
func (h *ChatHandler) SetMindMapDependencies(searchSvc *service.SearchService, tenantSvc *service.TenantService, modelFactory *service.ModelFactory, chunkSvc service.Retriever) {
	h.searchSvc = searchSvc
	h.tenantSvc = tenantSvc
	h.modelFactory = modelFactory
	h.chunkSvc = chunkSvc
}

// ChatMindMapRequest is the request body for POST /api/v1/chat/mindmap.
type ChatMindMapRequest struct {
	Question string             `json:"question" binding:"required"`
	KbIDs    common.StringSlice `json:"kb_ids" binding:"required"`
	SearchID string             `json:"search_id,omitempty"`
}

// ListChats list chats
// @Summary List Chats
// @Description Get list of chats (dialogs) for the current user
// @Tags chat
// @Success 200 {object} service.ListChatsResponse
// @Router /api/v1/chats [get]
func (h *ChatHandler) ListChats(c *gin.Context) {
	// Parse query parameters
	keywords := c.Query("keywords")
	// Exact id and name filters take precedence over the fuzzy keyword
	// search, as in the Python route and the API reference.
	id := c.Query("id")
	name := c.Query("name")
	if id != "" || name != "" {
		keywords = ""
	}

	page, pageSize, err := common.ParsePagination(c.Request.URL.Query())
	if err != nil {
		common.RespondError(c, common.CodeArgumentError, err.Error())
		return
	}

	// `sort` supersedes the older pair, so a request it can order is not rejected
	// for the spelling of an `orderby` that will not be read.
	sortTerms := sortTermsFromQuery(c)
	orderBy := c.DefaultQuery("orderby", "create_time")
	if len(sortTerms) == 0 {
		switch orderBy {
		case "create_time", "update_time", "name":
		default:
			common.RespondError(c, common.CodeArgumentError, fmt.Sprintf("invalid orderby field: %s", orderBy))
			return
		}
	}

	desc := true
	if descStr := c.Query("desc"); descStr != "" {
		desc = !strings.EqualFold(descStr, "false")
	}
	terms := orderTerms(sortTerms, orderBy, desc)

	ownerIDs := getOwnerIDs(c)
	ctx := c.Request.Context()

	// List chats - default to valid status "1" (same as Python StatusEnum.VALID.value)
	result, err := h.chatService.ListChats(ctx, "1", keywords, id, name, page, pageSize, terms, ownerIDs)
	if err != nil {
		if respondPermissionErrorIf(c, err, false) {
			return
		}
		common.Respond(c, http.StatusInternalServerError, 500, nil, err.Error())
		return
	}

	common.RespondSuccess(c, result, "success")
}

// Create creates a chat.
// @Summary Create Chat
// @Description Create a chat, aligned with Python POST /api/v1/chats.
// @Tags chat
// @Param request body service.CreateChatRequest true "chat configuration"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chats [post]
func (h *ChatHandler) Create(c *gin.Context) {
	user, errorCode, err := billingQuotaUser(c)
	if err != nil {
		common.RespondError(c, errorCode, err.Error())
		return
	}
	if !billingEnforceApps(c, user.ID) {
		return
	}

	var req map[string]interface{}
	decoder := json.NewDecoder(c.Request.Body)
	decoder.UseNumber()
	if err = decoder.Decode(&req); err != nil {
		common.RespondError(c, common.CodeArgumentError, err.Error())
		return
	}
	if req == nil {
		req = map[string]interface{}{}
	}

	ctx := c.Request.Context()
	result, code, err := h.chatService.Create(ctx, req)
	if err != nil {
		common.RespondError(c, code, err.Error())
		return
	}

	common.RespondSuccess(c, result, "success")
}

// MindMap generates a query mind map for chat search results.
// @Summary Generate Chat Mind Map
// @Description Retrieves related chunks and asks the configured chat model to summarize them into a mind map.
// @Tags chat
// @Param request body ChatMindMapRequest true "Mind map parameters"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chat/mindmap [post]
func (h *ChatHandler) MindMap(c *gin.Context) {

	var req ChatMindMapRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Respond(c, http.StatusBadRequest, common.CodeArgumentError, nil, err.Error())
		return
	}
	if strings.TrimSpace(req.Question) == "" {
		common.Respond(c, http.StatusBadRequest, common.CodeArgumentError, nil, "kb_ids and question are required")
		return
	}

	ctx := c.Request.Context()
	searchConfig := map[string]interface{}{}
	var modelTenantID string
	if req.SearchID != "" {
		if h.searchSvc == nil {
			jsonInternalError(c, fmt.Errorf("search service not configured"))
			return
		}
		detail, err := h.searchSvc.GetDetail(ctx, req.SearchID)
		if err != nil {
			if respondPermissionErrorIf(c, err, true) {
				return
			}
			jsonInternalError(c, err)
			return
		}
		searchConfig = searchConfigFromDetail(detail)
		if tenantID, ok := detail["tenant_id"].(string); ok && tenantID != "" {
			modelTenantID = tenantID
		}
	}

	kbIDs := mergeMindMapKbIDs(stringSliceFromConfig(searchConfig, "kb_ids"), req.KbIDs)
	if len(kbIDs) == 0 {
		common.Respond(c, http.StatusBadRequest, common.CodeArgumentError, nil, "kb_ids and question are required")
		return
	}

	mindMap, err := runMindMap(ctx, mindMapRunConfig{
		Question:      req.Question,
		KbIDs:         kbIDs,
		SearchID:      req.SearchID,
		SearchConfig:  searchConfig,
		ModelTenantID: modelTenantID,
		ChunkSvc:      h.chunkSvc,
		LLM:           h.modelFactory,
		TenantSvc:     h.tenantSvc,
	})
	if err != nil {
		common.Warn("mindmap failed", zap.String("error", err.Error()))
		common.RespondError(c, common.CodeOperatingError, err.Error())
		return
	}
	common.RespondSuccess(c, mindMap, "success")
}

func (h *ChatHandler) DeleteChat(c *gin.Context) {
	chatID := c.Param("chat_id")
	if chatID == "" {
		common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "chat_id is required")
		return
	}

	ctx := c.Request.Context()
	if err := h.chatService.DeleteChat(ctx, chatID); err != nil {
		if respondPermissionErrorIf(c, err, true) {
			return
		}
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}

	common.RespondSuccess(c, nil, "success")
}

// BulkDeleteChats soft deletes multiple chats owned by the current user.
func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
	if c.Request.Body == nil || c.Request.ContentLength == 0 {
		common.RespondSuccess(c, map[string]interface{}{}, "success")
		return
	}

	var req service.BulkDeleteChatsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
		return
	}

	ctx := c.Request.Context()
	if len(req.IDs) == 0 && !req.DeleteAll {
		if req.ChatID != "" {
			if err := h.chatService.DeleteChat(ctx, req.ChatID); err != nil {
				if respondPermissionErrorIf(c, err, true) {
					return
				}
				common.RespondError(c, common.CodeDataError, err.Error())
				return
			}

			common.RespondSuccess(c, nil, "success")
			return
		}

		common.RespondSuccess(c, map[string]interface{}{}, "success")
		return
	}

	result, err := h.chatService.BulkDeleteChats(ctx, &req)
	if err != nil {
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}

	message := "success"
	if errorsList, ok := result["errors"].([]string); ok && len(errorsList) > 0 {
		if successCount, ok := result["success_count"].(int); ok {
			message = "Partially deleted " + strconv.Itoa(successCount) + " chats with " + strconv.Itoa(len(errorsList)) + " errors"
		}
	}

	common.RespondSuccess(c, result, message)
}

// GetChat get chat detail
// @Summary Get Chat Detail
// @Description Get detail of a chat by ID
// @Tags chat
// @Param chat_id path string true "chat ID"
// @Success 200 {object} service.GetChatResponse
// @Router /api/v1/chats/{chat_id} [get]
// Reference: api/apps/restful_apis/chat_api.py::get_chat
// Python implementation details:
// - Route: @manager.route("/chats/<chat_id>", methods=["GET"])
func (h *ChatHandler) GetChat(c *gin.Context) {
	// Get chat_id from path parameter (same as Python <chat_id>)
	chatID := c.Param("chat_id")
	if chatID == "" {
		common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "chat_id is required")
		return
	}

	// Get chat detail with permission check
	ctx := c.Request.Context()
	chat, err := h.chatService.GetChat(ctx, chatID)
	if err != nil {
		if respondPermissionErrorIf(c, err, true) {
			return
		}
		// Not found error
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}

	// Build response (same as Python _build_chat_response)
	// The service already returns GetChatResponse with DatasetIDs and KBNames
	result := map[string]interface{}{
		"id":                         chat.ID,
		"tenant_id":                  chat.TenantID,
		"name":                       chat.Name,
		"description":                chat.Description,
		"icon":                       chat.Icon,
		"language":                   chat.Language,
		"llm_id":                     chat.LLMID,
		"llm_setting":                chat.LLMSetting,
		"prompt_type":                chat.PromptType,
		"prompt_config":              chat.PromptConfig,
		"meta_data_filter":           chat.MetaDataFilter,
		"keywords_similarity_weight": 1 - chat.VectorSimilarityWeight,
		"similarity_threshold":       chat.SimilarityThreshold,
		"top_n":                      chat.TopN,
		"rerank_candidates_count":    chat.RerankCandidatesCount,
		"top_k":                      chat.TopK,
		"do_refer":                   chat.DoRefer,
		"rerank_id":                  chat.RerankID,
		"dataset_ids":                chat.DatasetIDs,
		"kb_names":                   chat.KBNames,
		"status":                     chat.Status,
		"create_time":                chat.CreateTime,
		"create_date":                chat.CreateDate,
		"update_time":                chat.UpdateTime,
		"update_date":                chat.UpdateDate,
		"tenant_llm_id":              chat.TenantLLMID,
		"tenant_rerank_id":           chat.TenantRerankID,
		// The per-chat decision model override. Without it the settings form
		// resets to empty after saving and the field looks unset.
		"decision_id":        chat.DecisionID,
		"tenant_decision_id": chat.TenantDecisionID,
	}

	// Return success response
	common.RespondSuccess(c, result, "success")
}

// GetAgenticRAGConfig returns defaults and effective Agentic RAG settings.
func (h *ChatHandler) GetAgenticRAGConfig(c *gin.Context) {
	chatID := c.Param("chat_id")
	if chatID == "" {
		common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "chat_id is required")
		return
	}
	settings, err := h.chatService.GetAgenticRAGConfig(c.Request.Context(), chatID)
	if err != nil {
		if respondPermissionErrorIf(c, err, true) {
			return
		}
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}
	common.RespondSuccess(c, settings, "success")
}

// UpdateChat updates a chat by ID using REST PUT semantics.
func (h *ChatHandler) UpdateChat(c *gin.Context) {
	h.updateChatByMethod(c, false)
}

// PatchChat updates a chat by ID using REST PATCH semantics.
func (h *ChatHandler) PatchChat(c *gin.Context) {
	h.updateChatByMethod(c, true)
}

func (h *ChatHandler) updateChatByMethod(c *gin.Context, patch bool) {
	chatID := c.Param("chat_id")
	if chatID == "" {
		common.RespondError(c, common.CodeBadRequest, "chat_id is required")
		return
	}

	var req map[string]interface{}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}

	var result map[string]interface{}
	var err error
	ctx := c.Request.Context()
	if patch {
		result, err = h.chatService.PatchChat(ctx, chatID, req)
	} else {
		result, err = h.chatService.UpdateChat(ctx, chatID, req)
	}
	if err != nil {
		if respondPermissionErrorIf(c, err, false) {
			return
		}
		common.RespondError(c, common.CodeDataError, err.Error())
		return
	}

	common.RespondSuccess(c, result, "success")
}