feat: Add web search functionality and enhance agent mode integration

- Introduced web search configuration in config.yaml, allowing multiple providers with specific settings.
- Updated InputField component to manage agent mode and web search toggles, improving user interaction.
- Enhanced chat API to include web search status in requests, enabling dynamic query handling.
- Implemented backend support for web search integration, merging results with knowledge base queries.
- Added tenant-level web search configuration management, allowing customization per tenant.
This commit is contained in:
wizardchen
2025-11-10 03:14:12 +08:00
parent 1313f4dfbb
commit 07a8c1de4c
46 changed files with 2574 additions and 56 deletions
+4 -3
View File
@@ -118,7 +118,7 @@ func (h *Handler) KnowledgeQA(c *gin.Context) {
}
// Use shared function to handle KnowledgeQA request
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, true, request.SummaryModelID)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, true, request.SummaryModelID, request.WebSearchEnabled)
}
// AgentQA handles agent-based question answering with conversation history and streaming
@@ -256,7 +256,7 @@ func (h *Handler) AgentQA(c *gin.Context) {
logger.Infof(ctx, "Delegating to KnowledgeQA with knowledge bases: %v", knowledgeBaseIDs)
// Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, false, request.SummaryModelID)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, false, request.SummaryModelID, request.WebSearchEnabled)
return
}
@@ -353,6 +353,7 @@ func (h *Handler) handleKnowledgeQARequest(
assistantMessage *types.Message,
generateTitle bool, // Whether to generate title if session has no title
summaryModelID string, // Optional summary model ID (overrides session default)
webSearchEnabled bool, // Whether web search is enabled
) {
sessionID := session.ID
requestID := getRequestID(c)
@@ -421,7 +422,7 @@ func (h *Handler) handleKnowledgeQARequest(
logger.ErrorWithFields(asyncCtx, errors.NewInternalServerError("Knowledge QA service panicked"), nil)
}
}()
err := h.sessionService.KnowledgeQA(asyncCtx, session, query, knowledgeBaseIDs, assistantMessage.ID, summaryModelID, eventBus)
err := h.sessionService.KnowledgeQA(asyncCtx, session, query, knowledgeBaseIDs, assistantMessage.ID, summaryModelID, webSearchEnabled, eventBus)
if err != nil {
logger.ErrorWithFields(asyncCtx, err, nil)
// Emit error event to dedicated EventBus
+1
View File
@@ -56,6 +56,7 @@ type CreateKnowledgeQARequest struct {
Query string `json:"query" binding:"required"` // Query text for knowledge base search
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MCPServiceIDs []string `json:"mcp_service_ids"` // Optional MCP service IDs to use in agent mode
}
+142
View File
@@ -410,3 +410,145 @@ func (h *TenantHandler) UpdateTenantAgentConfig(c *gin.Context) {
"message": "Agent configuration updated successfully",
})
}
// GetTenantWebSearchConfig returns the web search configuration for a tenant
// Tenant ID is obtained from the authentication context
func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start getting tenant web search config")
// Get tenant ID from authentication context
tenantID := c.GetUint(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
// Get tenant
tenant, err := h.service.GetTenantByID(ctx, tenantID)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve tenant").WithDetails(err.Error()))
}
return
}
// Hide API key in response
var responseConfig *types.WebSearchConfig
if tenant.WebSearchConfig != nil {
responseConfig = &types.WebSearchConfig{
Provider: tenant.WebSearchConfig.Provider,
APIKey: "", // Hide API key
MaxResults: tenant.WebSearchConfig.MaxResults,
IncludeDate: tenant.WebSearchConfig.IncludeDate,
CompressionMethod: tenant.WebSearchConfig.CompressionMethod,
Blacklist: tenant.WebSearchConfig.Blacklist,
EmbeddingModelID: tenant.WebSearchConfig.EmbeddingModelID,
EmbeddingDimension: tenant.WebSearchConfig.EmbeddingDimension,
RerankModelID: tenant.WebSearchConfig.RerankModelID,
DocumentFragments: tenant.WebSearchConfig.DocumentFragments,
}
// If API key exists, show a masked version
if tenant.WebSearchConfig.APIKey != "" {
responseConfig.APIKey = "***" // Masked API key
}
}
logger.Infof(ctx, "Tenant web search config retrieved successfully, Tenant ID: %d", tenantID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": responseConfig,
})
}
// UpdateTenantWebSearchConfig updates the web search configuration for a tenant
// Tenant ID is obtained from the authentication context
func (h *TenantHandler) UpdateTenantWebSearchConfig(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating tenant web search config")
// Get tenant ID from authentication context
tenantID := c.GetUint(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
var req types.WebSearchConfig
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
// Validate configuration
if req.MaxResults < 1 || req.MaxResults > 50 {
c.Error(errors.NewBadRequestError("max_results must be between 1 and 50"))
return
}
// Get existing tenant
tenant, err := h.service.GetTenantByID(ctx, tenantID)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve tenant").WithDetails(err.Error()))
}
return
}
// Update web search configuration
// If API key is "***", keep the existing API key
if req.APIKey == "***" && tenant.WebSearchConfig != nil {
req.APIKey = tenant.WebSearchConfig.APIKey
}
tenant.WebSearchConfig = &req
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant web search config").WithDetails(err.Error()))
}
return
}
// Hide API key in response
responseConfig := &types.WebSearchConfig{
Provider: updatedTenant.WebSearchConfig.Provider,
APIKey: "", // Hide API key
MaxResults: updatedTenant.WebSearchConfig.MaxResults,
IncludeDate: updatedTenant.WebSearchConfig.IncludeDate,
CompressionMethod: updatedTenant.WebSearchConfig.CompressionMethod,
Blacklist: updatedTenant.WebSearchConfig.Blacklist,
EmbeddingModelID: updatedTenant.WebSearchConfig.EmbeddingModelID,
EmbeddingDimension: updatedTenant.WebSearchConfig.EmbeddingDimension,
RerankModelID: updatedTenant.WebSearchConfig.RerankModelID,
DocumentFragments: updatedTenant.WebSearchConfig.DocumentFragments,
}
if updatedTenant.WebSearchConfig.APIKey != "" {
responseConfig.APIKey = "***" // Masked API key
}
logger.Infof(ctx, "Tenant web search config updated successfully, Tenant ID: %d", tenantID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": responseConfig,
"message": "Web search configuration updated successfully",
})
}
+63
View File
@@ -0,0 +1,63 @@
package handler
import (
"net/http"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// WebSearchHandler handles web search related requests
type WebSearchHandler struct {
cfg *config.Config
}
// NewWebSearchHandler creates a new web search handler
func NewWebSearchHandler(cfg *config.Config) *WebSearchHandler {
return &WebSearchHandler{
cfg: cfg,
}
}
// GetProviders returns the list of available web search providers
// @Summary Get available web search providers
// @Description Returns the list of available web search providers from configuration
// @Tags web-search
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "List of providers"
// @Router /api/v1/web-search/providers [get]
func (h *WebSearchHandler) GetProviders(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Getting web search providers")
if h.cfg.WebSearch == nil || len(h.cfg.WebSearch.Providers) == 0 {
logger.Warn(ctx, "No web search providers configured")
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []types.WebSearchProviderInfo{},
})
return
}
// Convert config providers to API response format
providers := make([]types.WebSearchProviderInfo, 0, len(h.cfg.WebSearch.Providers))
for _, provider := range h.cfg.WebSearch.Providers {
providers = append(providers, types.WebSearchProviderInfo{
ID: provider.ID,
Name: provider.Name,
Free: provider.Free,
RequiresAPIKey: provider.RequiresAPIKey,
Description: provider.Description,
APIURL: provider.APIURL,
})
}
logger.Infof(ctx, "Returning %d web search providers", len(providers))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": providers,
})
}