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
@@ -2,8 +2,10 @@ package chatpipline
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
@@ -16,17 +18,23 @@ type PluginSearch struct {
knowledgeBaseService interfaces.KnowledgeBaseService
modelService interfaces.ModelService
config *config.Config
webSearchService interfaces.WebSearchService
tenantService interfaces.TenantService
}
func NewPluginSearch(eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
modelService interfaces.ModelService,
config *config.Config,
webSearchService interfaces.WebSearchService,
tenantService interfaces.TenantService,
) *PluginSearch {
res := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
modelService: modelService,
config: config,
webSearchService: webSearchService,
tenantService: tenantService,
}
eventManager.Register(res)
return res
@@ -135,6 +143,33 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
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)
@@ -180,3 +215,71 @@ func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult
}
return uniqueResults
}
// 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 {
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
// Use URL as ChunkID for web search results
chunkID := webResult.URL
if chunkID == "" {
chunkID = fmt.Sprintf("web_search_%d", i)
}
// Combine title and snippet as content
content := webResult.Title
if webResult.Snippet != "" {
if content != "" {
content += "\n\n" + webResult.Snippet
} else {
content = webResult.Snippet
}
}
if webResult.Content != "" {
if content != "" {
content += "\n\n" + webResult.Content
} else {
content = webResult.Content
}
}
// Set a default score for web search results (0.6, indicating medium relevance)
score := 0.6
result := &types.SearchResult{
ID: chunkID,
Content: content,
KnowledgeID: "", // Web search results don't have knowledge ID
ChunkIndex: 0,
KnowledgeTitle: webResult.Title,
StartAt: 0,
EndAt: len(content),
Seq: i,
Score: score,
MatchType: types.MatchTypeWebSearch,
SubChunkID: []string{},
Metadata: map[string]string{
"url": webResult.URL,
"source": webResult.Source,
"title": webResult.Title,
"snippet": webResult.Snippet,
},
ChunkType: "web_search",
ParentChunkID: "",
ImageInfo: "",
KnowledgeFilename: "",
KnowledgeSource: "web_search",
}
// Add published date to metadata if available
if webResult.PublishedAt != nil {
result.Metadata["published_at"] = webResult.PublishedAt.Format(time.RFC3339)
}
results = append(results, result)
}
return results
}
+7 -2
View File
@@ -400,8 +400,8 @@ func (s *sessionService) GenerateTitleAsync(ctx context.Context, session *types.
// KnowledgeQA performs knowledge base question answering with LLM summarization
// Events are emitted through eventBus (references, answer chunks, completion)
func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session, query string, knowledgeBaseIDs []string, assistantMessageID string, summaryModelID string, eventBus *event.EventBus) error {
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, query: %s", session.ID, query)
func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session, query string, knowledgeBaseIDs []string, assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus) error {
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v", session.ID, query, webSearchEnabled)
// If no knowledge base IDs provided, fall back to session's default
if len(knowledgeBaseIDs) == 0 {
@@ -456,6 +456,11 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
EventBus: eventBus.AsEventBusInterface(), // NEW: For pipeline to emit events directly
}
// Store web search configuration in chatManage for pipeline processing
// PluginSearch will handle web search integration
chatManage.TenantID = session.TenantID
chatManage.WebSearchEnabled = webSearchEnabled
// Start knowledge QA event processing
logger.Info(ctx, "Triggering knowledge base question answering event")
err = s.KnowledgeQAByEvent(ctx, chatManage, types.Pipline["rag_stream"])
+260
View File
@@ -0,0 +1,260 @@
package service
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// 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
config *config.WebSearchConfig
}
// 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) {
if config == nil {
return nil, fmt.Errorf("web search config is required")
}
provider, ok := s.providers[config.Provider]
if !ok {
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 {
timeout = 10 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Perform search
results, err := provider.Search(ctx, query, config.MaxResults, config.IncludeDate)
if err != nil {
return nil, fmt.Errorf("web search failed: %w", err)
}
// Apply blacklist filtering
results = s.filterBlacklist(results, config.Blacklist)
// Apply compression if needed
if config.CompressionMethod != "none" && config.CompressionMethod != "" {
// Compression will be handled later in the integration layer
// For now, we just return the results
}
return results, nil
}
// NewWebSearchService creates a new web search service
func NewWebSearchService(cfg *config.Config) (*WebSearchService, error) {
if cfg.WebSearch == nil {
return nil, fmt.Errorf("web search config is not available")
}
service := &WebSearchService{
providers: make(map[string]WebSearchProvider),
config: cfg.WebSearch,
}
// Initialize providers based on config
for _, providerConfig := range cfg.WebSearch.Providers {
var provider 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)
default:
logger.Warnf(context.Background(), "Unknown web search provider: %s", providerConfig.ID)
continue
}
if err != nil {
logger.Warnf(context.Background(), "Failed to initialize provider %s: %v", providerConfig.ID, err)
continue
}
service.providers[providerConfig.ID] = provider
logger.Infof(context.Background(), "Initialized web search provider: %s", providerConfig.ID)
}
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 {
return results
}
filtered := make([]*types.WebSearchResult, 0, len(results))
for _, result := range results {
shouldFilter := false
for _, rule := range blacklist {
if s.matchesBlacklistRule(result.URL, rule) {
shouldFilter = true
break
}
}
if !shouldFilter {
filtered = append(filtered, result)
}
}
return filtered
}
// matchesBlacklistRule checks if a URL matches a blacklist rule
// Supports both pattern matching (e.g., *://*.example.com/*) and regex patterns (e.g., /example\.(net|org)/)
func (s *WebSearchService) matchesBlacklistRule(url, rule string) bool {
// Check if it's a regex pattern (starts and ends with /)
if strings.HasPrefix(rule, "/") && strings.HasSuffix(rule, "/") {
pattern := rule[1 : len(rule)-1]
matched, err := regexp.MatchString(pattern, url)
if err != nil {
logger.Warnf(context.Background(), "Invalid regex pattern in blacklist: %s, error: %v", rule, err)
return false
}
return matched
}
// Pattern matching (e.g., *://*.example.com/*)
pattern := strings.ReplaceAll(rule, "*", ".*")
pattern = "^" + pattern + "$"
matched, err := regexp.MatchString(pattern, url)
if err != nil {
logger.Warnf(context.Background(), "Invalid pattern in blacklist: %s, error: %v", rule, err)
return false
}
return matched
}
// ConvertWebSearchResults converts WebSearchResult to SearchResult
func ConvertWebSearchResults(webResults []*types.WebSearchResult) []*types.SearchResult {
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
// Use URL as ChunkID for web search results
chunkID := webResult.URL
if chunkID == "" {
chunkID = fmt.Sprintf("web_search_%d", i)
}
// Combine title and snippet as content
content := webResult.Title
if webResult.Snippet != "" {
if content != "" {
content += "\n\n" + webResult.Snippet
} else {
content = webResult.Snippet
}
}
if webResult.Content != "" {
if content != "" {
content += "\n\n" + webResult.Content
} else {
content = webResult.Content
}
}
// Set a default score for web search results (0.6, indicating medium relevance)
score := 0.6
result := &types.SearchResult{
ID: chunkID,
Content: content,
KnowledgeID: "", // Web search results don't have knowledge ID
ChunkIndex: 0,
KnowledgeTitle: webResult.Title,
StartAt: 0,
EndAt: len(content),
Seq: i,
Score: score,
MatchType: types.MatchTypeWebSearch,
SubChunkID: []string{},
Metadata: map[string]string{
"url": webResult.URL,
"source": webResult.Source,
"title": webResult.Title,
"snippet": webResult.Snippet,
},
ChunkType: "web_search",
ParentChunkID: "",
ImageInfo: "",
KnowledgeFilename: "",
KnowledgeSource: "web_search",
}
// Add published date to metadata if available
if webResult.PublishedAt != nil {
result.Metadata["published_at"] = webResult.PublishedAt.Format(time.RFC3339)
}
results = append(results, result)
}
return results
}
@@ -0,0 +1,32 @@
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")
}
@@ -0,0 +1,32 @@
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")
}
@@ -0,0 +1,38 @@
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,38 @@
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
}
@@ -0,0 +1,40 @@
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
}
@@ -0,0 +1,112 @@
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
}
@@ -0,0 +1,32 @@
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")
}
@@ -0,0 +1,38 @@
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
}
@@ -0,0 +1,38 @@
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
}
@@ -0,0 +1,33 @@
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")
}
@@ -0,0 +1,33 @@
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")
}
@@ -0,0 +1,39 @@
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,39 @@
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
}
@@ -0,0 +1,41 @@
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
}
@@ -0,0 +1,113 @@
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
}
@@ -0,0 +1,33 @@
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")
}
@@ -0,0 +1,39 @@
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
}
@@ -0,0 +1,39 @@
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
}