feat: Update web search providers and enhance knowledge base management
- Added DuckDuckGo as a new web search provider in the configuration. - Removed deprecated web search providers (Baidu, Bing, Bocha, Exa, Google, Kuaisou, Searxng, Tavily, Zhipu) to streamline the codebase. - Enhanced knowledge base management by introducing temporary knowledge base handling in the session service. - Updated the web search service to support RAG-based compression for improved search result processing. - Refactored session and knowledge service interfaces to accommodate new functionalities.
This commit is contained in:
@@ -52,7 +52,7 @@ func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
|
||||
ctx context.Context, tenantID uint,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
var kbs []*types.KnowledgeBase
|
||||
if err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).
|
||||
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false).
|
||||
Order("created_at DESC").Find(&kbs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -11,30 +12,37 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// PluginSearch implements search functionality for chat pipeline
|
||||
type PluginSearch struct {
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
modelService interfaces.ModelService
|
||||
config *config.Config
|
||||
webSearchService interfaces.WebSearchService
|
||||
tenantService interfaces.TenantService
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
func NewPluginSearch(eventManager *EventManager,
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
modelService interfaces.ModelService,
|
||||
config *config.Config,
|
||||
webSearchService interfaces.WebSearchService,
|
||||
tenantService interfaces.TenantService,
|
||||
redisClient *redis.Client,
|
||||
) *PluginSearch {
|
||||
res := &PluginSearch{
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
modelService: modelService,
|
||||
config: config,
|
||||
webSearchService: webSearchService,
|
||||
tenantService: tenantService,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
eventManager.Register(res)
|
||||
return res
|
||||
@@ -62,44 +70,37 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
return ErrSearch.WithError(nil)
|
||||
}
|
||||
|
||||
// Run KB search and web search concurrently
|
||||
logger.Infof(ctx, "Searching across %d knowledge base(s): %v", len(knowledgeBaseIDs), knowledgeBaseIDs)
|
||||
|
||||
// Prepare search parameters
|
||||
searchParams := types.SearchParams{
|
||||
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
}
|
||||
logger.Infof(ctx, "Search parameters: %v", searchParams)
|
||||
|
||||
// Parallel search across multiple knowledge bases
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var allResults []*types.SearchResult
|
||||
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg.Done()
|
||||
|
||||
results, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, searchParams)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search KB %s: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KB %s search results count: %d", knowledgeBaseID, len(results))
|
||||
allResults := make([]*types.SearchResult, 0)
|
||||
|
||||
wg.Add(2)
|
||||
// Goroutine 1: Knowledge base search (rewrite + processed)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
kbResults := p.searchKnowledgeBases(ctx, knowledgeBaseIDs, chatManage)
|
||||
if len(kbResults) > 0 {
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
allResults = append(allResults, kbResults...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Goroutine 2: Web search (if enabled)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
webResults := p.searchWebIfEnabled(ctx, chatManage)
|
||||
if len(webResults) > 0 {
|
||||
mu.Lock()
|
||||
allResults = append(allResults, webResults...)
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
logger.Infof(ctx, "Total search results from all KBs: %d", len(allResults))
|
||||
chatManage.SearchResult = allResults
|
||||
|
||||
// Add relevant results from chat history
|
||||
@@ -109,67 +110,6 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, historyResult...)
|
||||
}
|
||||
|
||||
// Try search with processed query if different from rewrite query
|
||||
if chatManage.RewriteQuery != chatManage.ProcessedQuery {
|
||||
searchParams.QueryText = strings.TrimSpace(chatManage.ProcessedQuery)
|
||||
logger.Infof(ctx, "Searching with processed query: %s", searchParams.QueryText)
|
||||
|
||||
var wg2 sync.WaitGroup
|
||||
var mu2 sync.Mutex
|
||||
var processedResults []*types.SearchResult
|
||||
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg2.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg2.Done()
|
||||
|
||||
results, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, searchParams)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search KB %s with processed query: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KB %s processed query results count: %d", knowledgeBaseID, len(results))
|
||||
|
||||
mu2.Lock()
|
||||
processedResults = append(processedResults, results...)
|
||||
mu2.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
|
||||
wg2.Wait()
|
||||
|
||||
logger.Infof(ctx, "Total processed query results from all KBs: %d", len(processedResults))
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, processedResults...)
|
||||
}
|
||||
|
||||
// Perform web search if enabled and merge results with KB search results
|
||||
if chatManage.WebSearchEnabled && p.webSearchService != nil && p.tenantService != nil && chatManage.TenantID > 0 {
|
||||
// Get tenant to retrieve web search config
|
||||
tenant, err := p.tenantService.GetTenantByID(ctx, chatManage.TenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get tenant for web search: %v", err)
|
||||
} else if tenant != nil && tenant.WebSearchConfig != nil && tenant.WebSearchConfig.Provider != "" {
|
||||
// Perform web search in parallel with KB search (already completed)
|
||||
logger.Infof(ctx, "Performing web search with provider: %s", tenant.WebSearchConfig.Provider)
|
||||
webResults, err := p.webSearchService.Search(ctx, tenant.WebSearchConfig, chatManage.RewriteQuery)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Web search failed: %v", err)
|
||||
} else {
|
||||
// Convert web search results to SearchResult
|
||||
webSearchResults := convertWebSearchResults(webResults)
|
||||
logger.Infof(ctx, "Web search returned %d results", len(webSearchResults))
|
||||
// Merge web search results with KB search results
|
||||
if len(webSearchResults) > 0 {
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, webSearchResults...)
|
||||
logger.Infof(ctx, "Merged web search results, total results: %d", len(chatManage.SearchResult))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.Warnf(ctx, "Web search enabled but no valid configuration found for tenant %d", chatManage.TenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove duplicate results
|
||||
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
|
||||
|
||||
@@ -216,6 +156,136 @@ func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult
|
||||
return uniqueResults
|
||||
}
|
||||
|
||||
// searchKnowledgeBases performs KB searches for rewrite and processed queries across KB IDs
|
||||
func (p *PluginSearch) searchKnowledgeBases(ctx context.Context, knowledgeBaseIDs []string, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
// Build base params for rewrite query
|
||||
baseParams := types.SearchParams{
|
||||
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var results []*types.SearchResult
|
||||
|
||||
// Search with rewrite query
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg.Done()
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, baseParams)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search KB %s: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "KB %s search results count: %d", knowledgeBaseID, len(res))
|
||||
mu.Lock()
|
||||
results = append(results, res...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// If processed query differs, search again
|
||||
if chatManage.RewriteQuery != chatManage.ProcessedQuery {
|
||||
paramsProcessed := baseParams
|
||||
paramsProcessed.QueryText = strings.TrimSpace(chatManage.ProcessedQuery)
|
||||
logger.Infof(ctx, "Searching with processed query: %s", paramsProcessed.QueryText)
|
||||
|
||||
wg = sync.WaitGroup{}
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg.Done()
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, paramsProcessed)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search KB %s with processed query: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "KB %s processed query results count: %d", knowledgeBaseID, len(res))
|
||||
mu.Lock()
|
||||
results = append(results, res...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Total KB results (rewrite + processed): %d", len(results))
|
||||
return results
|
||||
}
|
||||
|
||||
// searchWebIfEnabled executes web search when enabled and returns converted results
|
||||
func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
if !(chatManage.WebSearchEnabled && p.webSearchService != nil && p.tenantService != nil && chatManage.TenantID > 0) {
|
||||
return nil
|
||||
}
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil || tenant.WebSearchConfig == nil || tenant.WebSearchConfig.Provider == "" {
|
||||
logger.Warnf(ctx, "Web search enabled but no valid configuration found for tenant %d", chatManage.TenantID)
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Performing web search with provider: %s", tenant.WebSearchConfig.Provider)
|
||||
webResults, err := p.webSearchService.Search(ctx, tenant.WebSearchConfig, chatManage.RewriteQuery)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Web search failed: %v", err)
|
||||
return nil
|
||||
}
|
||||
// Build questions (rewrite + processed if different)
|
||||
questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
|
||||
if chatManage.ProcessedQuery != "" && chatManage.ProcessedQuery != chatManage.RewriteQuery {
|
||||
questions = append(questions, strings.TrimSpace(chatManage.ProcessedQuery))
|
||||
}
|
||||
// Load session-scoped temp KB state from Redis
|
||||
var tempKBID string
|
||||
seen := map[string]bool{}
|
||||
ids := []string{}
|
||||
stateKey := fmt.Sprintf("tempkb:%s", chatManage.SessionID)
|
||||
if raw, getErr := p.redisClient.Get(ctx, stateKey).Bytes(); getErr == nil && len(raw) > 0 {
|
||||
var state struct {
|
||||
KBID string `json:"kbID"`
|
||||
KnowledgeIDs []string `json:"knowledgeIDs"`
|
||||
SeenURLs map[string]bool `json:"seenURLs"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &state); err == nil {
|
||||
tempKBID = state.KBID
|
||||
ids = state.KnowledgeIDs
|
||||
if state.SeenURLs != nil {
|
||||
seen = state.SeenURLs
|
||||
}
|
||||
}
|
||||
}
|
||||
compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
|
||||
ctx, chatManage.SessionID, tempKBID, questions, webResults, tenant.WebSearchConfig,
|
||||
p.knowledgeBaseService, p.knowledgeService, seen, ids,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "RAG compression failed, falling back to raw: %v", err)
|
||||
} else {
|
||||
webResults = compressed
|
||||
// Persist temp KB state back into Redis
|
||||
state := struct {
|
||||
KBID string `json:"kbID"`
|
||||
KnowledgeIDs []string `json:"knowledgeIDs"`
|
||||
SeenURLs map[string]bool `json:"seenURLs"`
|
||||
}{
|
||||
KBID: kbID,
|
||||
KnowledgeIDs: newIDs,
|
||||
SeenURLs: newSeen,
|
||||
}
|
||||
if b, mErr := json.Marshal(state); mErr == nil {
|
||||
_ = p.redisClient.Set(ctx, stateKey, b, 0).Err()
|
||||
}
|
||||
}
|
||||
res := convertWebSearchResults(webResults)
|
||||
logger.Infof(ctx, "Web search returned %d results", len(res))
|
||||
return res
|
||||
}
|
||||
|
||||
// convertWebSearchResults converts WebSearchResult to SearchResult
|
||||
// This is a duplicate of the function in service/web_search.go to avoid circular imports
|
||||
func convertWebSearchResults(webResults []*types.WebSearchResult) []*types.SearchResult {
|
||||
|
||||
@@ -351,7 +351,26 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
func (s *knowledgeService) CreateKnowledgeFromPassage(ctx context.Context,
|
||||
kbID string, passage []string,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start creating knowledge from passage")
|
||||
return s.createKnowledgeFromPassageInternal(ctx, kbID, passage, false)
|
||||
}
|
||||
|
||||
// CreateKnowledgeFromPassageSync creates a knowledge entry from text passages and waits for indexing to complete.
|
||||
func (s *knowledgeService) CreateKnowledgeFromPassageSync(ctx context.Context,
|
||||
kbID string, passage []string,
|
||||
) (*types.Knowledge, error) {
|
||||
return s.createKnowledgeFromPassageInternal(ctx, kbID, passage, true)
|
||||
}
|
||||
|
||||
// createKnowledgeFromPassageInternal consolidates the common logic for creating knowledge from passages.
|
||||
// When syncMode is true, chunk processing is performed synchronously; otherwise, it's processed asynchronously.
|
||||
func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Context,
|
||||
kbID string, passage []string, syncMode bool,
|
||||
) (*types.Knowledge, error) {
|
||||
if syncMode {
|
||||
logger.Info(ctx, "Start creating knowledge from passage (sync)")
|
||||
} else {
|
||||
logger.Info(ctx, "Start creating knowledge from passage")
|
||||
}
|
||||
logger.Infof(ctx, "Knowledge base ID: %s, passage count: %d", kbID, len(passage))
|
||||
|
||||
// 验证段落内容安全性
|
||||
@@ -374,7 +393,11 @@ func (s *knowledgeService) CreateKnowledgeFromPassage(ctx context.Context,
|
||||
}
|
||||
|
||||
// Create knowledge record
|
||||
logger.Info(ctx, "Creating knowledge record")
|
||||
if syncMode {
|
||||
logger.Info(ctx, "Creating knowledge record (sync)")
|
||||
} else {
|
||||
logger.Info(ctx, "Creating knowledge record")
|
||||
}
|
||||
knowledge := &types.Knowledge{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
|
||||
@@ -394,11 +417,16 @@ func (s *knowledgeService) CreateKnowledgeFromPassage(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Process passages asynchronously
|
||||
logger.Info(ctx, "Starting asynchronous passage processing")
|
||||
go s.processDocumentFromPassage(ctx, kb, knowledge, safePassages)
|
||||
|
||||
logger.Infof(ctx, "Knowledge from passage created successfully, ID: %s", knowledge.ID)
|
||||
// Process passages
|
||||
if syncMode {
|
||||
logger.Info(ctx, "Processing passage synchronously")
|
||||
s.processDocumentFromPassage(ctx, kb, knowledge, safePassages)
|
||||
logger.Infof(ctx, "Knowledge from passage created successfully (sync), ID: %s", knowledge.ID)
|
||||
} else {
|
||||
logger.Info(ctx, "Starting asynchronous passage processing")
|
||||
go s.processDocumentFromPassage(ctx, kb, knowledge, safePassages)
|
||||
logger.Infof(ctx, "Knowledge from passage created successfully, ID: %s", knowledge.ID)
|
||||
}
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
)
|
||||
@@ -36,6 +38,8 @@ type sessionService struct {
|
||||
eventManager *chatpipline.EventManager // Event manager for chat pipeline
|
||||
agentService interfaces.AgentService // Service for agent operations
|
||||
sessionStorage llmcontext.ContextStorage // Session storage
|
||||
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
|
||||
redisClient *redis.Client // Redis client for temp KB state
|
||||
}
|
||||
|
||||
// NewSessionService creates a new session service instance with all required dependencies
|
||||
@@ -43,22 +47,26 @@ func NewSessionService(cfg *config.Config,
|
||||
sessionRepo interfaces.SessionRepository,
|
||||
messageRepo interfaces.MessageRepository,
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
modelService interfaces.ModelService,
|
||||
tenantService interfaces.TenantService,
|
||||
eventManager *chatpipline.EventManager,
|
||||
agentService interfaces.AgentService,
|
||||
sessionStorage llmcontext.ContextStorage,
|
||||
redisClient *redis.Client,
|
||||
) interfaces.SessionService {
|
||||
return &sessionService{
|
||||
cfg: cfg,
|
||||
sessionRepo: sessionRepo,
|
||||
messageRepo: messageRepo,
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
modelService: modelService,
|
||||
tenantService: tenantService,
|
||||
eventManager: eventManager,
|
||||
agentService: agentService,
|
||||
sessionStorage: sessionStorage,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +210,30 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
logger.Infof(ctx, "Deleting session, ID: %s, tenant ID: %d", id, tenantID)
|
||||
|
||||
// Cleanup temporary KB stored in Redis for this session
|
||||
if s.redisClient != nil {
|
||||
stateKey := fmt.Sprintf("tempkb:%s", id)
|
||||
if raw, getErr := s.redisClient.Get(ctx, stateKey).Bytes(); getErr == nil && len(raw) > 0 {
|
||||
var state struct {
|
||||
KBID string `json:"kbID"`
|
||||
KnowledgeIDs []string `json:"knowledgeIDs"`
|
||||
SeenURLs map[string]bool `json:"seenURLs"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &state); err == nil && strings.TrimSpace(state.KBID) != "" {
|
||||
logger.Infof(ctx, "Cleaning temporary KB for session %s: %s", id, state.KBID)
|
||||
for _, kid := range state.KnowledgeIDs {
|
||||
if delErr := s.knowledgeService.DeleteKnowledge(ctx, kid); delErr != nil {
|
||||
logger.Warnf(ctx, "Failed to delete temp knowledge %s: %v", kid, delErr)
|
||||
}
|
||||
}
|
||||
if delErr := s.knowledgeBaseService.DeleteKnowledgeBase(ctx, state.KBID); delErr != nil {
|
||||
logger.Warnf(ctx, "Failed to delete temp knowledge base %s: %v", state.KBID, delErr)
|
||||
}
|
||||
_ = s.redisClient.Del(ctx, stateKey).Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete session from repository
|
||||
err := s.sessionRepo.Delete(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,23 +7,238 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/web_search"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// WebSearchProvider defines the interface for web search providers
|
||||
type WebSearchProvider interface {
|
||||
Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error)
|
||||
Name() string
|
||||
}
|
||||
|
||||
// WebSearchService provides web search functionality
|
||||
type WebSearchService struct {
|
||||
providers map[string]WebSearchProvider
|
||||
providers map[string]interfaces.WebSearchProvider
|
||||
config *config.WebSearchConfig
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (s *WebSearchService) CompressWithRAG(
|
||||
ctx context.Context, sessionID string, tempKBID string, questions []string,
|
||||
webSearchResults []*types.WebSearchResult, cfg *types.WebSearchConfig,
|
||||
kbSvc interfaces.KnowledgeBaseService, knowSvc interfaces.KnowledgeService,
|
||||
seenURLs map[string]bool, knowledgeIDs []string,
|
||||
) (compressed []*types.WebSearchResult, kbID string, newSeen map[string]bool, newIDs []string, err error) {
|
||||
if len(webSearchResults) == 0 || len(questions) == 0 {
|
||||
return
|
||||
}
|
||||
if cfg == nil {
|
||||
return nil, tempKBID, seenURLs, knowledgeIDs, fmt.Errorf("web search config is required for RAG compression")
|
||||
}
|
||||
if cfg.EmbeddingModelID == "" {
|
||||
return nil, tempKBID, seenURLs, knowledgeIDs, fmt.Errorf("embedding_model_id is required for RAG compression")
|
||||
}
|
||||
var createdKB *types.KnowledgeBase
|
||||
// reuse or create temp KB
|
||||
if strings.TrimSpace(tempKBID) != "" {
|
||||
createdKB, err = kbSvc.GetKnowledgeBaseByID(ctx, tempKBID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Temp KB %s not available, recreating: %v", tempKBID, err)
|
||||
createdKB = nil
|
||||
}
|
||||
}
|
||||
if createdKB == nil {
|
||||
kb := &types.KnowledgeBase{
|
||||
Name: fmt.Sprintf("tmp-websearch-%d", time.Now().UnixNano()),
|
||||
Description: "Ephemeral search compression KB",
|
||||
IsTemporary: true,
|
||||
EmbeddingModelID: cfg.EmbeddingModelID,
|
||||
RerankModelID: cfg.RerankModelID,
|
||||
}
|
||||
createdKB, err = kbSvc.CreateKnowledgeBase(ctx, kb)
|
||||
if err != nil {
|
||||
return nil, tempKBID, seenURLs, knowledgeIDs, fmt.Errorf("failed to create temporary knowledge base: %w", err)
|
||||
}
|
||||
tempKBID = createdKB.ID
|
||||
}
|
||||
|
||||
// Ingest all web results as passages synchronously
|
||||
// dedupe by URL across queries within the same temp KB for this request/session
|
||||
if seenURLs == nil {
|
||||
seenURLs = map[string]bool{}
|
||||
}
|
||||
for _, r := range webSearchResults {
|
||||
sourceURL := r.URL
|
||||
title := strings.TrimSpace(r.Title)
|
||||
snippet := strings.TrimSpace(r.Snippet)
|
||||
body := strings.TrimSpace(r.Content)
|
||||
// skip if already ingested for this KB
|
||||
if sourceURL != "" && seenURLs[sourceURL] {
|
||||
continue
|
||||
}
|
||||
contentLines := make([]string, 0, 4)
|
||||
contentLines = append(contentLines, fmt.Sprintf("[sourceUrl]: %s", sourceURL))
|
||||
if title != "" {
|
||||
contentLines = append(contentLines, title)
|
||||
}
|
||||
if snippet != "" {
|
||||
contentLines = append(contentLines, snippet)
|
||||
}
|
||||
if body != "" {
|
||||
contentLines = append(contentLines, body)
|
||||
}
|
||||
knowledge, err := knowSvc.CreateKnowledgeFromPassageSync(ctx, createdKB.ID, contentLines)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "failed to ingest passage into temp KB: %v", err)
|
||||
continue
|
||||
}
|
||||
if sourceURL != "" {
|
||||
seenURLs[sourceURL] = true
|
||||
}
|
||||
knowledgeIDs = append(knowledgeIDs, knowledge.ID)
|
||||
}
|
||||
|
||||
// Retrieve references for questions
|
||||
matchCount := cfg.DocumentFragments
|
||||
if matchCount <= 0 {
|
||||
matchCount = 3
|
||||
}
|
||||
var allRefs []*types.SearchResult
|
||||
for _, q := range questions {
|
||||
params := types.SearchParams{
|
||||
QueryText: q,
|
||||
VectorThreshold: 0.5,
|
||||
KeywordThreshold: 0.5,
|
||||
MatchCount: matchCount,
|
||||
}
|
||||
results, err := kbSvc.HybridSearch(ctx, tempKBID, params)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "hybrid search failed for temp KB: %v", err)
|
||||
continue
|
||||
}
|
||||
allRefs = append(allRefs, results...)
|
||||
}
|
||||
|
||||
// Round-robin select references across the original results by source URL
|
||||
selected := s.selectReferencesRoundRobin(webSearchResults, allRefs, matchCount*len(webSearchResults))
|
||||
// Consolidate by URL back into the web results
|
||||
compressedResults := s.consolidateReferencesByURL(webSearchResults, selected)
|
||||
return compressedResults, tempKBID, seenURLs, knowledgeIDs, nil
|
||||
}
|
||||
|
||||
// selectReferencesRoundRobin selects up to limit references, distributing fairly across source URLs.
|
||||
func (s *WebSearchService) selectReferencesRoundRobin(
|
||||
raw []*types.WebSearchResult,
|
||||
refs []*types.SearchResult,
|
||||
limit int,
|
||||
) []*types.SearchResult {
|
||||
if limit <= 0 || len(refs) == 0 {
|
||||
return nil
|
||||
}
|
||||
// group refs by url marker in content
|
||||
urlToRefs := map[string][]*types.SearchResult{}
|
||||
for _, r := range refs {
|
||||
url := extractSourceURLFromContent(r.Content)
|
||||
if url == "" {
|
||||
continue
|
||||
}
|
||||
urlToRefs[url] = append(urlToRefs[url], r)
|
||||
}
|
||||
// preserve order based on raw results
|
||||
order := make([]string, 0, len(raw))
|
||||
seen := map[string]bool{}
|
||||
for _, r := range raw {
|
||||
if r.URL != "" && !seen[r.URL] {
|
||||
order = append(order, r.URL)
|
||||
seen[r.URL] = true
|
||||
}
|
||||
}
|
||||
var out []*types.SearchResult
|
||||
for len(out) < limit {
|
||||
progress := false
|
||||
for _, url := range order {
|
||||
if len(out) >= limit {
|
||||
break
|
||||
}
|
||||
list := urlToRefs[url]
|
||||
if len(list) == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, list[0])
|
||||
urlToRefs[url] = list[1:]
|
||||
progress = true
|
||||
}
|
||||
if !progress {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// consolidateReferencesByURL merges selected references back into the original results grouped by URL.
|
||||
func (s *WebSearchService) consolidateReferencesByURL(
|
||||
raw []*types.WebSearchResult,
|
||||
selected []*types.SearchResult,
|
||||
) []*types.WebSearchResult {
|
||||
if len(selected) == 0 {
|
||||
return raw
|
||||
}
|
||||
agg := map[string][]string{}
|
||||
for _, ref := range selected {
|
||||
url := extractSourceURLFromContent(ref.Content)
|
||||
if url == "" {
|
||||
continue
|
||||
}
|
||||
// strip the first marker line to avoid duplication
|
||||
agg[url] = append(agg[url], stripMarker(ref.Content))
|
||||
}
|
||||
// build outputs, preserving raw ordering and metadata
|
||||
out := make([]*types.WebSearchResult, 0, len(raw))
|
||||
for _, r := range raw {
|
||||
parts := agg[r.URL]
|
||||
if len(parts) == 0 {
|
||||
out = append(out, r)
|
||||
continue
|
||||
}
|
||||
merged := strings.Join(parts, "\n---\n")
|
||||
out = append(out, &types.WebSearchResult{
|
||||
Title: r.Title,
|
||||
URL: r.URL,
|
||||
Snippet: r.Snippet,
|
||||
Content: merged,
|
||||
Source: r.Source,
|
||||
PublishedAt: r.PublishedAt,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func extractSourceURLFromContent(content string) string {
|
||||
if content == "" {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(content, "\n")
|
||||
if len(lines) == 0 {
|
||||
return ""
|
||||
}
|
||||
first := strings.TrimSpace(lines[0])
|
||||
const prefix = "[sourceUrl]: "
|
||||
if strings.HasPrefix(first, prefix) {
|
||||
return strings.TrimSpace(strings.TrimPrefix(first, prefix))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func stripMarker(content string) string {
|
||||
lines := strings.Split(content, "\n")
|
||||
if len(lines) == 0 {
|
||||
return content
|
||||
}
|
||||
if strings.HasPrefix(strings.TrimSpace(lines[0]), "[sourceUrl]: ") {
|
||||
return strings.Join(lines[1:], "\n")
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
// Search performs web search using the specified provider
|
||||
// This method implements the interface expected by PluginSearch
|
||||
func (s *WebSearchService) Search(ctx context.Context, config *types.WebSearchConfig, query string) ([]*types.WebSearchResult, error) {
|
||||
@@ -36,11 +251,6 @@ func (s *WebSearchService) Search(ctx context.Context, config *types.WebSearchCo
|
||||
return nil, fmt.Errorf("web search provider %s is not available", config.Provider)
|
||||
}
|
||||
|
||||
// Set API key for providers that need it
|
||||
if config.APIKey != "" {
|
||||
s.setProviderAPIKey(config.Provider, provider, config)
|
||||
}
|
||||
|
||||
// Set timeout
|
||||
timeout := time.Duration(s.config.Timeout) * time.Second
|
||||
if timeout == 0 {
|
||||
@@ -75,44 +285,24 @@ func NewWebSearchService(cfg *config.Config) (*WebSearchService, error) {
|
||||
}
|
||||
|
||||
service := &WebSearchService{
|
||||
providers: make(map[string]WebSearchProvider),
|
||||
providers: make(map[string]interfaces.WebSearchProvider),
|
||||
config: cfg.WebSearch,
|
||||
}
|
||||
|
||||
// Initialize providers based on config
|
||||
for _, providerConfig := range cfg.WebSearch.Providers {
|
||||
var provider WebSearchProvider
|
||||
var provider interfaces.WebSearchProvider
|
||||
var err error
|
||||
|
||||
switch providerConfig.ID {
|
||||
case "kuaisou":
|
||||
provider, err = NewKuaisouProvider(providerConfig)
|
||||
case "baidu":
|
||||
provider, err = NewBaiduProvider(providerConfig)
|
||||
case "google":
|
||||
provider, err = NewGoogleProvider(providerConfig)
|
||||
case "bing":
|
||||
provider, err = NewBingProvider(providerConfig)
|
||||
case "bocha":
|
||||
provider, err = NewBochaProvider(providerConfig)
|
||||
case "zhipu":
|
||||
provider, err = NewZhipuProvider(providerConfig)
|
||||
case "tavily":
|
||||
provider, err = NewTavilyProvider(providerConfig)
|
||||
case "searxng":
|
||||
provider, err = NewSearxngProvider(providerConfig)
|
||||
case "exa":
|
||||
provider, err = NewExaProvider(providerConfig)
|
||||
case "duckduckgo":
|
||||
provider, err = web_search.NewDuckDuckGoProvider(providerConfig)
|
||||
default:
|
||||
logger.Warnf(context.Background(), "Unknown web search provider: %s", providerConfig.ID)
|
||||
continue
|
||||
return nil, fmt.Errorf("unknown web search provider: %s", providerConfig.ID)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(), "Failed to initialize provider %s: %v", providerConfig.ID, err)
|
||||
continue
|
||||
return nil, fmt.Errorf("failed to initialize provider %s: %v", providerConfig.ID, err)
|
||||
}
|
||||
|
||||
service.providers[providerConfig.ID] = provider
|
||||
logger.Infof(context.Background(), "Initialized web search provider: %s", providerConfig.ID)
|
||||
}
|
||||
@@ -120,27 +310,6 @@ func NewWebSearchService(cfg *config.Config) (*WebSearchService, error) {
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// setProviderAPIKey sets the API key for a provider based on its type
|
||||
func (s *WebSearchService) setProviderAPIKey(providerID string, provider WebSearchProvider, config *types.WebSearchConfig) {
|
||||
switch p := provider.(type) {
|
||||
case *KuaisouProvider:
|
||||
p.SetAPIKey(config.APIKey)
|
||||
case *BochaProvider:
|
||||
p.SetAPIKey(config.APIKey)
|
||||
case *ZhipuProvider:
|
||||
p.SetAPIKey(config.APIKey)
|
||||
case *TavilyProvider:
|
||||
p.SetAPIKey(config.APIKey)
|
||||
case *ExaProvider:
|
||||
p.SetAPIKey(config.APIKey)
|
||||
case *GoogleProvider:
|
||||
// Google needs both API key and search engine ID
|
||||
// For now, we'll use API key as search engine ID if not provided separately
|
||||
// This can be extended later to support separate fields
|
||||
p.SetAPIKey(config.APIKey, config.APIKey) // TODO: Add search engine ID to config
|
||||
}
|
||||
}
|
||||
|
||||
// filterBlacklist filters results based on blacklist rules
|
||||
func (s *WebSearchService) filterBlacklist(results []*types.WebSearchResult, blacklist []string) []*types.WebSearchResult {
|
||||
if len(blacklist) == 0 {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BaiduProvider implements web search using Baidu API
|
||||
type BaiduProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBaiduProvider creates a new Baidu provider
|
||||
func NewBaiduProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BaiduProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BaiduProvider) Name() string {
|
||||
return "baidu"
|
||||
}
|
||||
|
||||
// Search performs a web search using Baidu API
|
||||
func (p *BaiduProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Baidu search API
|
||||
return nil, fmt.Errorf("baidu search provider is not yet implemented")
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BingProvider implements web search using Bing Search API
|
||||
type BingProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBingProvider creates a new Bing provider
|
||||
func NewBingProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BingProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BingProvider) Name() string {
|
||||
return "bing"
|
||||
}
|
||||
|
||||
// Search performs a web search using Bing Search API
|
||||
func (p *BingProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Bing Search API
|
||||
return nil, fmt.Errorf("bing search provider is not yet implemented")
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BochaProvider implements web search using Bocha API
|
||||
type BochaProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBochaProvider creates a new Bocha provider
|
||||
func NewBochaProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BochaProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BochaProvider) Name() string {
|
||||
return "bocha"
|
||||
}
|
||||
|
||||
// Search performs a web search using Bocha API
|
||||
func (p *BochaProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Bocha search API
|
||||
return nil, fmt.Errorf("bocha search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *BochaProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package web_search
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// DuckDuckGoProvider implements web search using DuckDuckGo (HTML first, API fallback)
|
||||
type DuckDuckGoProvider struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewDuckDuckGoProvider creates a new DuckDuckGo provider
|
||||
func NewDuckDuckGoProvider(_ config.WebSearchProviderConfig) (interfaces.WebSearchProvider, error) {
|
||||
return &DuckDuckGoProvider{
|
||||
client: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *DuckDuckGoProvider) Name() string {
|
||||
return "duckduckgo"
|
||||
}
|
||||
|
||||
// Search performs a web search using DuckDuckGo HTML endpoint with API fallback
|
||||
func (p *DuckDuckGoProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
if maxResults <= 0 {
|
||||
maxResults = 5
|
||||
}
|
||||
// Try HTML scraping first (more reliable for general results)
|
||||
htmlResults, err := p.searchHTML(ctx, query, maxResults)
|
||||
if err == nil && len(htmlResults) > 0 {
|
||||
return htmlResults, nil
|
||||
}
|
||||
// Fallback to Instant Answer API
|
||||
apiResults, apiErr := p.searchAPI(ctx, query, maxResults)
|
||||
if apiErr == nil && len(apiResults) > 0 {
|
||||
return apiResults, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("duckduckgo HTML search failed: %w", err)
|
||||
}
|
||||
return nil, fmt.Errorf("duckduckgo API search failed: %w", apiErr)
|
||||
}
|
||||
|
||||
func (p *DuckDuckGoProvider) searchHTML(ctx context.Context, query string, maxResults int) ([]*types.WebSearchResult, error) {
|
||||
baseURL := "https://html.duckduckgo.com/html/"
|
||||
params := url.Values{}
|
||||
params.Set("q", query)
|
||||
// Prefer Chinese results if applicable; otherwise DDG will auto-detect
|
||||
params.Set("kl", "cn-zh")
|
||||
|
||||
reqURL := baseURL + "?" + params.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
// Use a realistic UA to avoid blocks
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to perform request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
|
||||
return nil, fmt.Errorf("duckduckgo HTML returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse HTML: %w", err)
|
||||
}
|
||||
|
||||
results := make([]*types.WebSearchResult, 0, maxResults)
|
||||
// Structure based on DDG HTML page
|
||||
doc.Find(".web-result").Each(func(i int, s *goquery.Selection) {
|
||||
if len(results) >= maxResults {
|
||||
return
|
||||
}
|
||||
titleNode := s.Find(".result__a")
|
||||
title := strings.TrimSpace(titleNode.Text())
|
||||
var link string
|
||||
if href, exists := titleNode.Attr("href"); exists {
|
||||
link = cleanDDGURL(href)
|
||||
}
|
||||
snippet := strings.TrimSpace(s.Find(".result__snippet").Text())
|
||||
if title != "" && link != "" {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: title,
|
||||
URL: link,
|
||||
Snippet: snippet,
|
||||
Source: "duckduckgo",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
logger.Infof(ctx, "DuckDuckGo HTML search returned %d results for query: %s", len(results), query)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (p *DuckDuckGoProvider) searchAPI(ctx context.Context, query string, maxResults int) ([]*types.WebSearchResult, error) {
|
||||
baseURL := "https://api.duckduckgo.com/"
|
||||
params := url.Values{}
|
||||
params.Set("q", query)
|
||||
params.Set("format", "json")
|
||||
params.Set("no_html", "1")
|
||||
params.Set("skip_disambig", "1")
|
||||
|
||||
reqURL := baseURL + "?" + params.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
req.Header.Set("User-Agent", "WeKnora/1.0")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to perform request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("duckduckgo API returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var apiResponse struct {
|
||||
AbstractText string `json:"AbstractText"`
|
||||
AbstractURL string `json:"AbstractURL"`
|
||||
Heading string `json:"Heading"`
|
||||
RelatedTopics []struct {
|
||||
FirstURL string `json:"FirstURL"`
|
||||
Text string `json:"Text"`
|
||||
} `json:"RelatedTopics"`
|
||||
Results []struct {
|
||||
FirstURL string `json:"FirstURL"`
|
||||
Text string `json:"Text"`
|
||||
} `json:"Results"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode API response: %w", err)
|
||||
}
|
||||
|
||||
results := make([]*types.WebSearchResult, 0, maxResults)
|
||||
if apiResponse.AbstractText != "" && apiResponse.AbstractURL != "" {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: apiResponse.Heading,
|
||||
URL: apiResponse.AbstractURL,
|
||||
Snippet: apiResponse.AbstractText,
|
||||
Source: "duckduckgo",
|
||||
})
|
||||
}
|
||||
for _, topic := range apiResponse.RelatedTopics {
|
||||
if len(results) >= maxResults {
|
||||
break
|
||||
}
|
||||
if topic.Text != "" && topic.FirstURL != "" {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: extractTitle(topic.Text),
|
||||
URL: topic.FirstURL,
|
||||
Snippet: topic.Text,
|
||||
Source: "duckduckgo",
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, r := range apiResponse.Results {
|
||||
if len(results) >= maxResults {
|
||||
break
|
||||
}
|
||||
if r.Text != "" && r.FirstURL != "" {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: extractTitle(r.Text),
|
||||
URL: r.FirstURL,
|
||||
Snippet: r.Text,
|
||||
Source: "duckduckgo",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "DuckDuckGo API search returned %d results for query: %s", len(results), query)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func cleanDDGURL(urlStr string) string {
|
||||
if strings.HasPrefix(urlStr, "//duckduckgo.com/l/?uddg=") {
|
||||
trimmed := strings.TrimPrefix(urlStr, "//duckduckgo.com/l/?uddg=")
|
||||
if idx := strings.Index(trimmed, "&rut="); idx != -1 {
|
||||
decodedStr, err := url.PathUnescape(trimmed[:idx])
|
||||
if err == nil {
|
||||
return decodedStr
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(urlStr, "https://duckduckgo.com/l/?uddg=") {
|
||||
if parsedURL, err := url.Parse(urlStr); err == nil {
|
||||
if uddg := parsedURL.Query().Get("uddg"); uddg != "" {
|
||||
return uddg
|
||||
}
|
||||
}
|
||||
}
|
||||
return urlStr
|
||||
}
|
||||
|
||||
func extractTitle(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
if len(lines) > 0 {
|
||||
title := strings.TrimSpace(lines[0])
|
||||
if len(title) > 100 {
|
||||
title = title[:100] + "..."
|
||||
}
|
||||
return title
|
||||
}
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package web_search
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
)
|
||||
|
||||
// testRoundTripper rewrites outgoing requests that target DuckDuckGo hosts
|
||||
// to the provided test server, preserving path and query.
|
||||
type testRoundTripper struct {
|
||||
base *url.URL
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// Only rewrite requests to duckduckgo hosts used by the provider
|
||||
if req.URL.Host == "html.duckduckgo.com" || req.URL.Host == "api.duckduckgo.com" {
|
||||
cloned := *req
|
||||
u := *req.URL
|
||||
u.Scheme = t.base.Scheme
|
||||
u.Host = t.base.Host
|
||||
// Keep original path; our test server handlers should register for the same paths.
|
||||
cloned.URL = &u
|
||||
req = &cloned
|
||||
}
|
||||
return t.next.RoundTrip(req)
|
||||
}
|
||||
|
||||
func newTestClient(ts *httptest.Server) *http.Client {
|
||||
baseURL, _ := url.Parse(ts.URL)
|
||||
return &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
Transport: &testRoundTripper{
|
||||
base: baseURL,
|
||||
next: http.DefaultTransport,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuckDuckGoProvider_Name(t *testing.T) {
|
||||
p, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{})
|
||||
if p.Name() != "duckduckgo" {
|
||||
t.Fatalf("expected provider name duckduckgo, got %s", p.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuckDuckGoProvider_Search_HTMLSuccess(t *testing.T) {
|
||||
// Minimal HTML page with two results, matching selectors used in searchHTML
|
||||
html := `
|
||||
<html>
|
||||
<body>
|
||||
<div class="web-result">
|
||||
<a class="result__a" href="https://duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage1&rut=">Example One</a>
|
||||
<div class="result__snippet">Snippet one</div>
|
||||
</div>
|
||||
<div class="web-result">
|
||||
<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.org%2Fpage2&rut=">Example Two</a>
|
||||
<div class="result__snippet">Snippet two</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Provider requests GET https://html.duckduckgo.com/html/?q=...&kl=...
|
||||
if r.URL.Path == "/html/" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(html))
|
||||
return
|
||||
}
|
||||
t.Fatalf("unexpected request path: %s", r.URL.Path)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
// Build provider and inject our test client
|
||||
prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{})
|
||||
dp := prov.(*DuckDuckGoProvider)
|
||||
dp.client = newTestClient(ts)
|
||||
|
||||
ctx := context.Background()
|
||||
results, err := dp.Search(ctx, "weknora", 5, false)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("expected 2 results, got %d", len(results))
|
||||
}
|
||||
if results[0].Title != "Example One" || !strings.HasPrefix(results[0].URL, "https://example.com/") || results[0].Snippet != "Snippet one" {
|
||||
t.Fatalf("unexpected first result: %+v", results[0])
|
||||
}
|
||||
if results[1].Title != "Example Two" || !strings.HasPrefix(results[1].URL, "https://example.org/") || results[1].Snippet != "Snippet two" {
|
||||
t.Fatalf("unexpected second result: %+v", results[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuckDuckGoProvider_Search_APIFallback(t *testing.T) {
|
||||
// Simulate HTML returning non-OK to force API fallback, then a minimal API JSON
|
||||
apiResp := struct {
|
||||
AbstractText string `json:"AbstractText"`
|
||||
AbstractURL string `json:"AbstractURL"`
|
||||
Heading string `json:"Heading"`
|
||||
Results []struct {
|
||||
FirstURL string `json:"FirstURL"`
|
||||
Text string `json:"Text"`
|
||||
} `json:"Results"`
|
||||
}{
|
||||
AbstractText: "Abstract snippet",
|
||||
AbstractURL: "https://example.com/abstract",
|
||||
Heading: "Abstract Heading",
|
||||
Results: []struct {
|
||||
FirstURL string `json:"FirstURL"`
|
||||
Text string `json:"Text"`
|
||||
}{
|
||||
{FirstURL: "https://example.net/x", Text: "Title X - Detail X"},
|
||||
},
|
||||
}
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/html/":
|
||||
// Force fallback by returning 500
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
default:
|
||||
// API endpoint path "/"
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
enc := json.NewEncoder(w)
|
||||
_ = enc.Encode(apiResp)
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{})
|
||||
dp := prov.(*DuckDuckGoProvider)
|
||||
dp.client = newTestClient(ts)
|
||||
|
||||
ctx := context.Background()
|
||||
results, err := dp.Search(ctx, "weknora", 3, false)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(results) == 0 {
|
||||
t.Fatalf("expected some results from API fallback")
|
||||
}
|
||||
if results[0].URL != "https://example.com/abstract" || results[0].Title != "Abstract Heading" {
|
||||
t.Fatalf("unexpected first API result: %+v", results[0])
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ExaProvider implements web search using Exa API
|
||||
type ExaProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewExaProvider creates a new Exa provider
|
||||
func NewExaProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &ExaProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *ExaProvider) Name() string {
|
||||
return "exa"
|
||||
}
|
||||
|
||||
// Search performs a web search using Exa API
|
||||
func (p *ExaProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Exa search API
|
||||
return nil, fmt.Errorf("exa search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *ExaProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// GoogleProvider implements web search using Google Custom Search API
|
||||
type GoogleProvider struct {
|
||||
apiKey string
|
||||
searchEngineID string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewGoogleProvider creates a new Google provider
|
||||
func NewGoogleProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &GoogleProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *GoogleProvider) Name() string {
|
||||
return "google"
|
||||
}
|
||||
|
||||
// Search performs a web search using Google Custom Search API
|
||||
func (p *GoogleProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Google Custom Search API
|
||||
return nil, fmt.Errorf("google search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key and search engine ID
|
||||
func (p *GoogleProvider) SetAPIKey(apiKey, searchEngineID string) {
|
||||
p.apiKey = apiKey
|
||||
p.searchEngineID = searchEngineID
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// KuaisouProvider implements web search using Kuaisou API
|
||||
type KuaisouProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewKuaisouProvider creates a new Kuaisou provider
|
||||
func NewKuaisouProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
if cfg.APIURL == "" {
|
||||
return nil, fmt.Errorf("kuaisou API URL is required")
|
||||
}
|
||||
|
||||
return &KuaisouProvider{
|
||||
apiKey: "", // Will be set from tenant config
|
||||
apiURL: cfg.APIURL,
|
||||
client: &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *KuaisouProvider) Name() string {
|
||||
return "kuaisou"
|
||||
}
|
||||
|
||||
// Search performs a web search using Kuaisou API
|
||||
func (p *KuaisouProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
if p.apiKey == "" {
|
||||
return nil, fmt.Errorf("kuaisou API key is required")
|
||||
}
|
||||
|
||||
// Prepare request
|
||||
reqBody := map[string]interface{}{
|
||||
"query": query,
|
||||
"max_results": maxResults,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", p.apiURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+p.apiKey)
|
||||
|
||||
// Send request
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("kuaisou API returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var response struct {
|
||||
Results []struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Snippet string `json:"snippet"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
// Convert to WebSearchResult
|
||||
results := make([]*types.WebSearchResult, 0, len(response.Results))
|
||||
for _, item := range response.Results {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: item.Title,
|
||||
URL: item.URL,
|
||||
Snippet: item.Snippet,
|
||||
Source: "kuaisou",
|
||||
})
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Kuaisou search returned %d results for query: %s", len(results), query)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *KuaisouProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SearxngProvider implements web search using Searxng API
|
||||
type SearxngProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewSearxngProvider creates a new Searxng provider
|
||||
func NewSearxngProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &SearxngProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *SearxngProvider) Name() string {
|
||||
return "searxng"
|
||||
}
|
||||
|
||||
// Search performs a web search using Searxng API
|
||||
func (p *SearxngProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Searxng search API
|
||||
return nil, fmt.Errorf("searxng search provider is not yet implemented")
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TavilyProvider implements web search using Tavily API
|
||||
type TavilyProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewTavilyProvider creates a new Tavily provider
|
||||
func NewTavilyProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &TavilyProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *TavilyProvider) Name() string {
|
||||
return "tavily"
|
||||
}
|
||||
|
||||
// Search performs a web search using Tavily API
|
||||
func (p *TavilyProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Tavily search API
|
||||
return nil, fmt.Errorf("tavily search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *TavilyProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ZhipuProvider implements web search using Zhipu API
|
||||
type ZhipuProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewZhipuProvider creates a new Zhipu provider
|
||||
func NewZhipuProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &ZhipuProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *ZhipuProvider) Name() string {
|
||||
return "zhipu"
|
||||
}
|
||||
|
||||
// Search performs a web search using Zhipu API
|
||||
func (p *ZhipuProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Zhipu search API
|
||||
return nil, fmt.Errorf("zhipu search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *ZhipuProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BaiduProvider implements web search using Baidu API
|
||||
type BaiduProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBaiduProvider creates a new Baidu provider
|
||||
func NewBaiduProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BaiduProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BaiduProvider) Name() string {
|
||||
return "baidu"
|
||||
}
|
||||
|
||||
// Search performs a web search using Baidu API
|
||||
func (p *BaiduProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Baidu search API
|
||||
return nil, fmt.Errorf("baidu search provider is not yet implemented")
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BingProvider implements web search using Bing Search API
|
||||
type BingProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBingProvider creates a new Bing provider
|
||||
func NewBingProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BingProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BingProvider) Name() string {
|
||||
return "bing"
|
||||
}
|
||||
|
||||
// Search performs a web search using Bing Search API
|
||||
func (p *BingProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Bing Search API
|
||||
return nil, fmt.Errorf("bing search provider is not yet implemented")
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// BochaProvider implements web search using Bocha API
|
||||
type BochaProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewBochaProvider creates a new Bocha provider
|
||||
func NewBochaProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &BochaProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *BochaProvider) Name() string {
|
||||
return "bocha"
|
||||
}
|
||||
|
||||
// Search performs a web search using Bocha API
|
||||
func (p *BochaProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Bocha search API
|
||||
return nil, fmt.Errorf("bocha search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *BochaProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ExaProvider implements web search using Exa API
|
||||
type ExaProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewExaProvider creates a new Exa provider
|
||||
func NewExaProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &ExaProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *ExaProvider) Name() string {
|
||||
return "exa"
|
||||
}
|
||||
|
||||
// Search performs a web search using Exa API
|
||||
func (p *ExaProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Exa search API
|
||||
return nil, fmt.Errorf("exa search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *ExaProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// GoogleProvider implements web search using Google Custom Search API
|
||||
type GoogleProvider struct {
|
||||
apiKey string
|
||||
searchEngineID string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewGoogleProvider creates a new Google provider
|
||||
func NewGoogleProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &GoogleProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *GoogleProvider) Name() string {
|
||||
return "google"
|
||||
}
|
||||
|
||||
// Search performs a web search using Google Custom Search API
|
||||
func (p *GoogleProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Google Custom Search API
|
||||
return nil, fmt.Errorf("google search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key and search engine ID
|
||||
func (p *GoogleProvider) SetAPIKey(apiKey, searchEngineID string) {
|
||||
p.apiKey = apiKey
|
||||
p.searchEngineID = searchEngineID
|
||||
}
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// KuaisouProvider implements web search using Kuaisou API
|
||||
type KuaisouProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewKuaisouProvider creates a new Kuaisou provider
|
||||
func NewKuaisouProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
if cfg.APIURL == "" {
|
||||
return nil, fmt.Errorf("kuaisou API URL is required")
|
||||
}
|
||||
|
||||
return &KuaisouProvider{
|
||||
apiKey: "", // Will be set from tenant config
|
||||
apiURL: cfg.APIURL,
|
||||
client: &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *KuaisouProvider) Name() string {
|
||||
return "kuaisou"
|
||||
}
|
||||
|
||||
// Search performs a web search using Kuaisou API
|
||||
func (p *KuaisouProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
if p.apiKey == "" {
|
||||
return nil, fmt.Errorf("kuaisou API key is required")
|
||||
}
|
||||
|
||||
// Prepare request
|
||||
reqBody := map[string]interface{}{
|
||||
"query": query,
|
||||
"max_results": maxResults,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", p.apiURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+p.apiKey)
|
||||
|
||||
// Send request
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("kuaisou API returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var response struct {
|
||||
Results []struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Snippet string `json:"snippet"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
// Convert to WebSearchResult
|
||||
results := make([]*types.WebSearchResult, 0, len(response.Results))
|
||||
for _, item := range response.Results {
|
||||
results = append(results, &types.WebSearchResult{
|
||||
Title: item.Title,
|
||||
URL: item.URL,
|
||||
Snippet: item.Snippet,
|
||||
Source: "kuaisou",
|
||||
})
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Kuaisou search returned %d results for query: %s", len(results), query)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *KuaisouProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SearxngProvider implements web search using Searxng API
|
||||
type SearxngProvider struct {
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewSearxngProvider creates a new Searxng provider
|
||||
func NewSearxngProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &SearxngProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *SearxngProvider) Name() string {
|
||||
return "searxng"
|
||||
}
|
||||
|
||||
// Search performs a web search using Searxng API
|
||||
func (p *SearxngProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Searxng search API
|
||||
return nil, fmt.Errorf("searxng search provider is not yet implemented")
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TavilyProvider implements web search using Tavily API
|
||||
type TavilyProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewTavilyProvider creates a new Tavily provider
|
||||
func NewTavilyProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &TavilyProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *TavilyProvider) Name() string {
|
||||
return "tavily"
|
||||
}
|
||||
|
||||
// Search performs a web search using Tavily API
|
||||
func (p *TavilyProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Tavily search API
|
||||
return nil, fmt.Errorf("tavily search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *TavilyProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ZhipuProvider implements web search using Zhipu API
|
||||
type ZhipuProvider struct {
|
||||
apiKey string
|
||||
apiURL string
|
||||
}
|
||||
|
||||
// NewZhipuProvider creates a new Zhipu provider
|
||||
func NewZhipuProvider(cfg config.WebSearchProviderConfig) (WebSearchProvider, error) {
|
||||
return &ZhipuProvider{
|
||||
apiURL: cfg.APIURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider name
|
||||
func (p *ZhipuProvider) Name() string {
|
||||
return "zhipu"
|
||||
}
|
||||
|
||||
// Search performs a web search using Zhipu API
|
||||
func (p *ZhipuProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
// TODO: Implement Zhipu search API
|
||||
return nil, fmt.Errorf("zhipu search provider is not yet implemented")
|
||||
}
|
||||
|
||||
// SetAPIKey sets the API key for the provider
|
||||
func (p *ZhipuProvider) SetAPIKey(apiKey string) {
|
||||
p.apiKey = apiKey
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user