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
}
+27
View File
@@ -24,6 +24,7 @@ type Config struct {
StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"`
ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"`
Agent *AgentGlobalConfig `yaml:"agent" json:"agent"`
WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"`
}
type DocReaderConfig struct {
@@ -198,3 +199,29 @@ type AgentGlobalConfig struct {
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
DefaultTools []string `yaml:"default_tools" json:"default_tools"`
}
// WebSearchConfig represents the web search configuration
type WebSearchConfig struct {
Providers []WebSearchProviderConfig `yaml:"providers" json:"providers"`
Default WebSearchDefaultConfig `yaml:"default" json:"default"`
Timeout int `yaml:"timeout" json:"timeout"` // 超时时间(秒)
}
// WebSearchProviderConfig represents configuration for a web search provider
type WebSearchProviderConfig struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Free bool `yaml:"free" json:"free"`
RequiresAPIKey bool `yaml:"requires_api_key" json:"requires_api_key"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
APIURL string `yaml:"api_url,omitempty" json:"api_url,omitempty"`
}
// WebSearchDefaultConfig represents the default web search configuration
type WebSearchDefaultConfig struct {
Provider string `yaml:"provider" json:"provider"`
MaxResults int `yaml:"max_results" json:"max_results"`
IncludeDate bool `yaml:"include_date" json:"include_date"`
CompressionMethod string `yaml:"compression_method" json:"compression_method"`
Blacklist []string `yaml:"blacklist" json:"blacklist"`
}
+8
View File
@@ -119,6 +119,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Session service (depends on agent service)
must(container.Provide(service.NewSessionService))
// Web search service
must(container.Provide(service.NewWebSearchService))
// Register WebSearchService as interface for dependency injection
must(container.Provide(func(ws *service.WebSearchService) interfaces.WebSearchService {
return ws
}))
// Chat pipeline components for processing chat requests
must(container.Provide(chatpipline.NewEventManager))
must(container.Invoke(chatpipline.NewPluginTracing))
@@ -148,6 +155,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewAuthHandler))
must(container.Provide(handler.NewSystemHandler))
must(container.Provide(handler.NewMCPServiceHandler))
must(container.Provide(handler.NewWebSearchHandler))
// Router configuration
must(container.Provide(router.NewRouter))
+4 -3
View File
@@ -118,7 +118,7 @@ func (h *Handler) KnowledgeQA(c *gin.Context) {
}
// Use shared function to handle KnowledgeQA request
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, true, request.SummaryModelID)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, true, request.SummaryModelID, request.WebSearchEnabled)
}
// AgentQA handles agent-based question answering with conversation history and streaming
@@ -256,7 +256,7 @@ func (h *Handler) AgentQA(c *gin.Context) {
logger.Infof(ctx, "Delegating to KnowledgeQA with knowledge bases: %v", knowledgeBaseIDs)
// Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, false, request.SummaryModelID)
h.handleKnowledgeQARequest(ctx, c, session, request.Query, knowledgeBaseIDs, assistantMessage, false, request.SummaryModelID, request.WebSearchEnabled)
return
}
@@ -353,6 +353,7 @@ func (h *Handler) handleKnowledgeQARequest(
assistantMessage *types.Message,
generateTitle bool, // Whether to generate title if session has no title
summaryModelID string, // Optional summary model ID (overrides session default)
webSearchEnabled bool, // Whether web search is enabled
) {
sessionID := session.ID
requestID := getRequestID(c)
@@ -421,7 +422,7 @@ func (h *Handler) handleKnowledgeQARequest(
logger.ErrorWithFields(asyncCtx, errors.NewInternalServerError("Knowledge QA service panicked"), nil)
}
}()
err := h.sessionService.KnowledgeQA(asyncCtx, session, query, knowledgeBaseIDs, assistantMessage.ID, summaryModelID, eventBus)
err := h.sessionService.KnowledgeQA(asyncCtx, session, query, knowledgeBaseIDs, assistantMessage.ID, summaryModelID, webSearchEnabled, eventBus)
if err != nil {
logger.ErrorWithFields(asyncCtx, err, nil)
// Emit error event to dedicated EventBus
+1
View File
@@ -56,6 +56,7 @@ type CreateKnowledgeQARequest struct {
Query string `json:"query" binding:"required"` // Query text for knowledge base search
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MCPServiceIDs []string `json:"mcp_service_ids"` // Optional MCP service IDs to use in agent mode
}
+142
View File
@@ -410,3 +410,145 @@ func (h *TenantHandler) UpdateTenantAgentConfig(c *gin.Context) {
"message": "Agent configuration updated successfully",
})
}
// GetTenantWebSearchConfig returns the web search configuration for a tenant
// Tenant ID is obtained from the authentication context
func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start getting tenant web search config")
// Get tenant ID from authentication context
tenantID := c.GetUint(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
// Get tenant
tenant, err := h.service.GetTenantByID(ctx, tenantID)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve tenant").WithDetails(err.Error()))
}
return
}
// Hide API key in response
var responseConfig *types.WebSearchConfig
if tenant.WebSearchConfig != nil {
responseConfig = &types.WebSearchConfig{
Provider: tenant.WebSearchConfig.Provider,
APIKey: "", // Hide API key
MaxResults: tenant.WebSearchConfig.MaxResults,
IncludeDate: tenant.WebSearchConfig.IncludeDate,
CompressionMethod: tenant.WebSearchConfig.CompressionMethod,
Blacklist: tenant.WebSearchConfig.Blacklist,
EmbeddingModelID: tenant.WebSearchConfig.EmbeddingModelID,
EmbeddingDimension: tenant.WebSearchConfig.EmbeddingDimension,
RerankModelID: tenant.WebSearchConfig.RerankModelID,
DocumentFragments: tenant.WebSearchConfig.DocumentFragments,
}
// If API key exists, show a masked version
if tenant.WebSearchConfig.APIKey != "" {
responseConfig.APIKey = "***" // Masked API key
}
}
logger.Infof(ctx, "Tenant web search config retrieved successfully, Tenant ID: %d", tenantID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": responseConfig,
})
}
// UpdateTenantWebSearchConfig updates the web search configuration for a tenant
// Tenant ID is obtained from the authentication context
func (h *TenantHandler) UpdateTenantWebSearchConfig(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating tenant web search config")
// Get tenant ID from authentication context
tenantID := c.GetUint(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
var req types.WebSearchConfig
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
// Validate configuration
if req.MaxResults < 1 || req.MaxResults > 50 {
c.Error(errors.NewBadRequestError("max_results must be between 1 and 50"))
return
}
// Get existing tenant
tenant, err := h.service.GetTenantByID(ctx, tenantID)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve tenant").WithDetails(err.Error()))
}
return
}
// Update web search configuration
// If API key is "***", keep the existing API key
if req.APIKey == "***" && tenant.WebSearchConfig != nil {
req.APIKey = tenant.WebSearchConfig.APIKey
}
tenant.WebSearchConfig = &req
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant web search config").WithDetails(err.Error()))
}
return
}
// Hide API key in response
responseConfig := &types.WebSearchConfig{
Provider: updatedTenant.WebSearchConfig.Provider,
APIKey: "", // Hide API key
MaxResults: updatedTenant.WebSearchConfig.MaxResults,
IncludeDate: updatedTenant.WebSearchConfig.IncludeDate,
CompressionMethod: updatedTenant.WebSearchConfig.CompressionMethod,
Blacklist: updatedTenant.WebSearchConfig.Blacklist,
EmbeddingModelID: updatedTenant.WebSearchConfig.EmbeddingModelID,
EmbeddingDimension: updatedTenant.WebSearchConfig.EmbeddingDimension,
RerankModelID: updatedTenant.WebSearchConfig.RerankModelID,
DocumentFragments: updatedTenant.WebSearchConfig.DocumentFragments,
}
if updatedTenant.WebSearchConfig.APIKey != "" {
responseConfig.APIKey = "***" // Masked API key
}
logger.Infof(ctx, "Tenant web search config updated successfully, Tenant ID: %d", tenantID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": responseConfig,
"message": "Web search configuration updated successfully",
})
}
+63
View File
@@ -0,0 +1,63 @@
package handler
import (
"net/http"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// WebSearchHandler handles web search related requests
type WebSearchHandler struct {
cfg *config.Config
}
// NewWebSearchHandler creates a new web search handler
func NewWebSearchHandler(cfg *config.Config) *WebSearchHandler {
return &WebSearchHandler{
cfg: cfg,
}
}
// GetProviders returns the list of available web search providers
// @Summary Get available web search providers
// @Description Returns the list of available web search providers from configuration
// @Tags web-search
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "List of providers"
// @Router /api/v1/web-search/providers [get]
func (h *WebSearchHandler) GetProviders(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Getting web search providers")
if h.cfg.WebSearch == nil || len(h.cfg.WebSearch.Providers) == 0 {
logger.Warn(ctx, "No web search providers configured")
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []types.WebSearchProviderInfo{},
})
return
}
// Convert config providers to API response format
providers := make([]types.WebSearchProviderInfo, 0, len(h.cfg.WebSearch.Providers))
for _, provider := range h.cfg.WebSearch.Providers {
providers = append(providers, types.WebSearchProviderInfo{
ID: provider.ID,
Name: provider.Name,
Free: provider.Free,
RequiresAPIKey: provider.RequiresAPIKey,
Description: provider.Description,
APIURL: provider.APIURL,
})
}
logger.Infof(ctx, "Returning %d web search providers", len(providers))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": providers,
})
}
+16
View File
@@ -40,6 +40,7 @@ type RouterParams struct {
InitializationHandler *handler.InitializationHandler
SystemHandler *handler.SystemHandler
MCPServiceHandler *handler.MCPServiceHandler
WebSearchHandler *handler.WebSearchHandler
}
// NewRouter 创建新的路由
@@ -87,6 +88,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterInitializationRoutes(v1, params.InitializationHandler)
RegisterSystemRoutes(v1, params.SystemHandler)
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
}
return r
@@ -224,6 +226,10 @@ func RegisterTenantRoutes(r *gin.RouterGroup, handler *handler.TenantHandler) {
// Tenant ID is obtained from authentication context
tenantRoutes.GET("/agent-config", handler.GetTenantAgentConfig)
tenantRoutes.PUT("/agent-config", handler.UpdateTenantAgentConfig)
// Web search configuration management (tenant-level)
// Tenant ID is obtained from authentication context
tenantRoutes.GET("/web-search-config", handler.GetTenantWebSearchConfig)
tenantRoutes.PUT("/web-search-config", handler.UpdateTenantWebSearchConfig)
}
}
@@ -319,3 +325,13 @@ func RegisterMCPServiceRoutes(r *gin.RouterGroup, handler *handler.MCPServiceHan
mcpServices.GET("/:id/resources", handler.GetMCPServiceResources)
}
}
// RegisterWebSearchRoutes registers web search routes
func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSearchHandler) {
// Web search providers
webSearch := r.Group("/web-search")
{
// Get available providers
webSearch.GET("/providers", webSearchHandler.GetProviders)
}
}
+4
View File
@@ -37,6 +37,10 @@ type ChatManage struct {
// Event system for streaming responses
EventBus EventBusInterface `json:"-"` // EventBus for emitting streaming events
MessageID string `json:"-"` // Assistant message ID for event emission
// Web search configuration (internal use)
TenantID uint `json:"-"` // Tenant ID for retrieving web search config
WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request
}
// Clone creates a deep copy of the ChatManage object
+1
View File
@@ -20,6 +20,7 @@ const (
MatchTypeParentChunk // 父Chunk匹配类型
MatchTypeRelationChunk // 关系Chunk匹配类型
MatchTypeGraph
MatchTypeWebSearch // 网络搜索匹配类型
)
// IndexInfo contains information about indexed content
+2 -1
View File
@@ -29,9 +29,10 @@ type SessionService interface {
// KnowledgeQA performs knowledge-based question answering
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
// summaryModelID: optional summary model ID override (if empty, uses session/KB default)
// webSearchEnabled: whether to enable web search to supplement knowledge base results
// Events are emitted through eventBus (references, answer chunks, completion)
KnowledgeQA(ctx context.Context,
session *types.Session, query string, knowledgeBaseIDs []string, assistantMessageID string, summaryModelID string, eventBus *event.EventBus,
session *types.Session, query string, knowledgeBaseIDs []string, assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus,
) error
// KnowledgeQAByEvent performs knowledge-based question answering by event
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
+12
View File
@@ -0,0 +1,12 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// WebSearchService defines the interface for web search service
type WebSearchService interface {
Search(ctx context.Context, config *types.WebSearchConfig, query string) ([]*types.WebSearchResult, error)
}
+2
View File
@@ -32,6 +32,8 @@ type Tenant struct {
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
// Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time
+59
View File
@@ -0,0 +1,59 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
)
// WebSearchConfig represents the web search configuration for a tenant
type WebSearchConfig struct {
Provider string `json:"provider"` // 搜索引擎提供商ID
APIKey string `json:"api_key"` // API密钥(如果需要)
MaxResults int `json:"max_results"` // 最大搜索结果数
IncludeDate bool `json:"include_date"` // 是否包含日期
CompressionMethod string `json:"compression_method"` // 压缩方法:none, summary, extract, rag
Blacklist []string `json:"blacklist"` // 黑名单规则列表
// RAG压缩相关配置
EmbeddingModelID string `json:"embedding_model_id,omitempty"` // 嵌入模型ID(用于RAG压缩)
EmbeddingDimension int `json:"embedding_dimension,omitempty"` // 嵌入维度(用于RAG压缩)
RerankModelID string `json:"rerank_model_id,omitempty"` // 重排模型ID(用于RAG压缩)
DocumentFragments int `json:"document_fragments,omitempty"` // 文档片段数量(用于RAG压缩)
}
// Value implements driver.Valuer interface for WebSearchConfig
func (c WebSearchConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements sql.Scanner interface for WebSearchConfig
func (c *WebSearchConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// WebSearchResult represents a single web search result
type WebSearchResult struct {
Title string `json:"title"` // 搜索结果标题
URL string `json:"url"` // 结果URL
Snippet string `json:"snippet"` // 摘要片段
Content string `json:"content"` // 完整内容(可选,需要额外抓取)
Source string `json:"source"` // 来源(如:kuaisou, baidu等)
PublishedAt *time.Time `json:"published_at,omitempty"` // 发布时间(如果有)
}
// WebSearchProviderInfo represents information about a web search provider
type WebSearchProviderInfo struct {
ID string `json:"id"` // 提供商ID
Name string `json:"name"` // 提供商名称
Free bool `json:"free"` // 是否免费
RequiresAPIKey bool `json:"requires_api_key"` // 是否需要API密钥
Description string `json:"description"` // 描述
APIURL string `json:"api_url,omitempty"` // API地址(可选)
}