feat(web-search): refactor web search provider

- Updated relevant files to include provider registration, implementation, and metadata.
- Enhanced frontend components to support provider management and configuration.
- Added localization for new provider settings and messages.
- Implemented backend repository methods for CRUD operations on web search providers.
This commit is contained in:
wizardchen
2026-03-31 20:14:26 +08:00
committed by lyingbug
parent c59ae84157
commit a5ca9a2784
46 changed files with 2311 additions and 1499 deletions
+1
View File
@@ -25,6 +25,7 @@ type AgentConfig struct {
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
WebSearchProviderID string `json:"web_search_provider_id,omitempty"` // WebSearchProviderEntity ID (resolved from agent config)
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
+10 -3
View File
@@ -46,9 +46,12 @@ type PipelineRequest struct {
ChatModelSupportsVision bool `json:"-"`
// Misc request-scoped config
TenantID uint64 `json:"-"`
WebSearchEnabled bool `json:"-"`
Language string `json:"-"`
TenantID uint64 `json:"-"`
WebSearchEnabled bool `json:"-"`
WebSearchProviderID string `json:"-"` // Resolved from agent config or tenant default
WebFetchEnabled bool `json:"-"` // Auto-fetch full page content for web search results after rerank
WebFetchTopN int `json:"-"` // Max pages to fetch (default 3)
Language string `json:"-"`
}
// QueryIntent represents the classified intent of a user query.
@@ -183,6 +186,9 @@ func (c *ChatManage) Clone() *ChatManage {
ChatModelSupportsVision: c.ChatModelSupportsVision,
TenantID: c.TenantID,
WebSearchEnabled: c.WebSearchEnabled,
WebSearchProviderID: c.WebSearchProviderID,
WebFetchEnabled: c.WebFetchEnabled,
WebFetchTopN: c.WebFetchTopN,
Language: c.Language,
},
PipelineState: PipelineState{
@@ -205,6 +211,7 @@ const (
CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel"
ENTITY_SEARCH EventType = "entity_search"
CHUNK_RERANK EventType = "chunk_rerank"
WEB_FETCH EventType = "web_fetch"
CHUNK_MERGE EventType = "chunk_merge"
DATA_ANALYSIS EventType = "data_analysis"
INTO_CHAT_MESSAGE EventType = "into_chat_message"
+7
View File
@@ -141,6 +141,13 @@ type CustomAgentConfig struct {
WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"`
// Maximum web search results
WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"`
// WebSearchProviderID references a specific WebSearchProviderEntity.
// If empty, the tenant's default provider (is_default=true) is used.
WebSearchProviderID string `yaml:"web_search_provider_id" json:"web_search_provider_id,omitempty"`
// Whether to auto-fetch full page content for reranked web search results
WebFetchEnabled bool `yaml:"web_fetch_enabled" json:"web_fetch_enabled"`
// Max number of pages to fetch after rerank (default: 3)
WebFetchTopN int `yaml:"web_fetch_top_n" json:"web_fetch_top_n,omitempty"`
// ===== Multi-turn Conversation Settings =====
// Whether multi-turn conversation is enabled
+3 -2
View File
@@ -16,8 +16,9 @@ type WebSearchProvider interface {
// WebSearchService defines the interface for web search services
type WebSearchService interface {
// Search performs a web search
Search(ctx context.Context, config *types.WebSearchConfig, query string) ([]*types.WebSearchResult, error)
// Search performs a web search using the provider entity identified by providerID.
// If providerID is empty, it falls back to the deprecated config.Provider field for backward compatibility.
Search(ctx context.Context, providerID string, config *types.WebSearchConfig, query string) ([]*types.WebSearchResult, error)
// CompressWithRAG performs RAG-based compression using a temporary, hidden knowledge base
// The temporary knowledge base is deleted after use. The UI will not list it due to repo filtering.
CompressWithRAG(ctx context.Context, sessionID string, tempKBID string, questions []string,
@@ -0,0 +1,39 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// WebSearchProviderRepository defines the repository interface for web search provider CRUD
type WebSearchProviderRepository interface {
// Create creates a new web search provider
Create(ctx context.Context, provider *types.WebSearchProviderEntity) error
// GetByID retrieves a web search provider by ID within a tenant scope
GetByID(ctx context.Context, tenantID uint64, id string) (*types.WebSearchProviderEntity, error)
// GetDefault retrieves the default provider (is_default=true) for a tenant, or nil if none.
GetDefault(ctx context.Context, tenantID uint64) (*types.WebSearchProviderEntity, error)
// List lists all web search providers for a tenant
List(ctx context.Context, tenantID uint64) ([]*types.WebSearchProviderEntity, error)
// Update updates a web search provider
Update(ctx context.Context, provider *types.WebSearchProviderEntity) error
// Delete deletes a web search provider (soft delete)
Delete(ctx context.Context, tenantID uint64, id string) error
// ClearDefault clears the default flag for all providers of a tenant, optionally excluding one
ClearDefault(ctx context.Context, tenantID uint64, excludeID string) error
}
// WebSearchProviderService defines the service interface for web search provider management.
// Tenant isolation is enforced by the handler layer (getOwned pattern).
// Service methods operate on entities whose TenantID is already verified.
type WebSearchProviderService interface {
// CreateProvider creates a new web search provider.
// provider.TenantID must be set by the caller (handler).
CreateProvider(ctx context.Context, provider *types.WebSearchProviderEntity) error
// UpdateProvider updates an existing provider.
// provider.TenantID must be set by the caller (handler) for the repository WHERE clause.
UpdateProvider(ctx context.Context, provider *types.WebSearchProviderEntity) error
// DeleteProvider deletes a provider by tenant + id.
DeleteProvider(ctx context.Context, tenantID uint64, id string) error
}
+5 -2
View File
@@ -8,8 +8,11 @@ import (
// WebSearchConfig represents the web search configuration for a tenant
type WebSearchConfig struct {
Provider string `json:"provider"` // 搜索引擎提供商ID
APIKey string `json:"api_key"` // API密钥(如果需要)
// Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.
Provider string `json:"provider,omitempty"`
// Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.
APIKey string `json:"api_key,omitempty"`
MaxResults int `json:"max_results"` // 最大搜索结果数
IncludeDate bool `json:"include_date"` // 是否包含日期
CompressionMethod string `json:"compression_method"` // 压缩方法:none, summary, extract, rag
+157
View File
@@ -0,0 +1,157 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
"gorm.io/gorm"
)
// WebSearchProviderType represents the type of web search provider
type WebSearchProviderType string
const (
WebSearchProviderTypeBing WebSearchProviderType = "bing"
WebSearchProviderTypeGoogle WebSearchProviderType = "google"
WebSearchProviderTypeDuckDuckGo WebSearchProviderType = "duckduckgo"
WebSearchProviderTypeTavily WebSearchProviderType = "tavily"
)
// WebSearchProviderEntity represents a configured web search provider instance for a tenant.
// This is a CRUD entity stored in the database, similar to the Model entity.
// Each tenant can create multiple provider configurations (e.g., "Production Bing", "Test Google").
// Agents reference these by ID.
type WebSearchProviderEntity struct {
// Unique identifier (UUID, auto-generated)
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for scoping
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// User-friendly name, e.g., "Production Bing Search"
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
// Provider type: bing, google, duckduckgo, tavily
Provider WebSearchProviderType `yaml:"provider" json:"provider" gorm:"type:varchar(50);not null"`
// Description
Description string `yaml:"description" json:"description" gorm:"type:text"`
// Provider-specific parameters (API key, engine ID, etc.) stored as encrypted JSON
Parameters WebSearchProviderParameters `yaml:"parameters" json:"parameters" gorm:"type:json"`
// Whether this is the default provider for the tenant
IsDefault bool `yaml:"is_default" json:"is_default" gorm:"default:false"`
// Timestamps
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
}
// TableName returns the table name for WebSearchProviderEntity
func (WebSearchProviderEntity) TableName() string {
return "web_search_providers"
}
// BeforeCreate is a GORM hook that runs before creating a new record.
// Automatically generates a UUID for new providers.
func (e *WebSearchProviderEntity) BeforeCreate(tx *gorm.DB) (err error) {
if e.ID == "" {
e.ID = uuid.New().String()
}
return nil
}
// WebSearchProviderParameters holds provider-specific configuration.
// API keys are encrypted at rest using AES-GCM.
// BaseURL is intentionally NOT included — each provider type uses a hardcoded
// official API endpoint to prevent SSRF attacks.
type WebSearchProviderParameters struct {
// API key for the search provider (encrypted in DB)
APIKey string `yaml:"api_key" json:"api_key,omitempty"`
// Google Custom Search Engine ID (only for Google provider)
EngineID string `yaml:"engine_id" json:"engine_id,omitempty"`
// Provider-specific extra configuration for future extensibility
ExtraConfig map[string]string `yaml:"extra_config" json:"extra_config,omitempty"`
}
// Value implements the driver.Valuer interface.
// Encrypts APIKey before persisting to database.
func (p WebSearchProviderParameters) Value() (driver.Value, error) {
if key := utils.GetAESKey(); key != nil && p.APIKey != "" {
if encrypted, err := utils.EncryptAESGCM(p.APIKey, key); err == nil {
p.APIKey = encrypted
}
}
return json.Marshal(p)
}
// Scan implements the sql.Scanner interface.
// Decrypts APIKey after loading from database.
func (p *WebSearchProviderParameters) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
if err := json.Unmarshal(b, p); err != nil {
return err
}
if key := utils.GetAESKey(); key != nil && p.APIKey != "" {
if decrypted, err := utils.DecryptAESGCM(p.APIKey, key); err == nil {
p.APIKey = decrypted
}
}
return nil
}
// WebSearchProviderTypeInfo describes the metadata of a provider type.
// Used by the GET /types endpoint so the frontend can dynamically render forms.
type WebSearchProviderTypeInfo struct {
// Provider type identifier
ID string `json:"id"`
// Human-readable name
Name string `json:"name"`
// Whether the provider requires an API key
RequiresAPIKey bool `json:"requires_api_key"`
// Whether the provider requires an engine ID (e.g., Google CSE)
RequiresEngineID bool `json:"requires_engine_id"`
// Description
Description string `json:"description"`
// URL to the provider's official website or documentation for obtaining credentials
DocsURL string `json:"docs_url,omitempty"`
}
// GetWebSearchProviderTypes returns metadata for all supported provider types.
func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo {
return []WebSearchProviderTypeInfo{
{
ID: "duckduckgo",
Name: "DuckDuckGo",
RequiresAPIKey: false,
Description: "DuckDuckGo Search (free, no API key required)",
DocsURL: "https://duckduckgo.com/",
},
{
ID: "bing",
Name: "Bing",
RequiresAPIKey: true,
Description: "Bing Search API (requires API key from Azure)",
DocsURL: "https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview",
},
{
ID: "google",
Name: "Google",
RequiresAPIKey: true,
RequiresEngineID: true,
Description: "Google Custom Search API (requires API key and engine ID)",
DocsURL: "https://developers.google.com/custom-search/v1/overview",
},
{
ID: "tavily",
Name: "Tavily",
RequiresAPIKey: true,
Description: "Tavily Search API (requires API key)",
DocsURL: "https://tavily.com/",
},
}
}