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:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user