feat(web-search): refactor web search provider

- Updated relevant files to include provider registration, implementation, and metadata.
- Enhanced frontend components to support provider management and configuration.
- Added localization for new provider settings and messages.
- Implemented backend repository methods for CRUD operations on web search providers.
This commit is contained in:
wizardchen
2026-03-31 20:14:26 +08:00
committed by lyingbug
parent c59ae84157
commit a5ca9a2784
46 changed files with 2311 additions and 1499 deletions
@@ -0,0 +1,171 @@
// Package web_fetch provides a public URL content fetcher with SSRF protection.
// It extracts core logic from the agent WebFetchTool so it can be used by the chat pipeline.
package web_fetch
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/utils"
)
const (
fetchTimeout = 15 * time.Second
maxBodySize = 100 * 1024 // 100KB
)
// FetchURLContent fetches a URL and returns its text content (HTML converted to clean text).
// Includes SSRF validation, DNS pinning, browser-like headers, and content size limits.
func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
if rawURL == "" {
return "", fmt.Errorf("url is empty")
}
// SSRF validation
if safe, reason := utils.IsSSRFSafeURL(rawURL); !safe {
return "", fmt.Errorf("URL rejected: %s", reason)
}
u, err := url.Parse(rawURL)
if err != nil {
return "", fmt.Errorf("invalid URL: %w", err)
}
hostname := u.Hostname()
port := u.Port()
if port == "" {
if u.Scheme == "https" {
port = "443"
} else {
port = "80"
}
}
// DNS pinning: resolve once, use pinned IP
ips, err := net.DefaultResolver.LookupIP(context.Background(), "ip", hostname)
if err != nil || len(ips) == 0 {
return "", fmt.Errorf("DNS lookup failed for %s: %w", hostname, err)
}
var pinnedIP net.IP
for _, ip := range ips {
if utils.IsPublicIP(ip) {
pinnedIP = ip
break
}
}
if pinnedIP == nil {
return "", fmt.Errorf("no public IP for host %s", hostname)
}
// Build request with pinned IP
hostPort := net.JoinHostPort(pinnedIP.String(), port)
fetchURL := *u
fetchURL.Host = hostPort
ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fetchURL.String(), nil)
if err != nil {
return "", err
}
req.Host = hostname
// Browser-like headers to reduce 403 rejections.
// These match a real Chrome browser fingerprint.
req.Header.Set("User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
req.Header.Set("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
req.Header.Set("Accept-Encoding", "identity") // no gzip to simplify reading
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Sec-Ch-Ua", `"Chromium";v="131", "Not_A Brand";v="24"`)
req.Header.Set("Sec-Ch-Ua-Mobile", "?0")
req.Header.Set("Sec-Ch-Ua-Platform", `"macOS"`)
req.Header.Set("Sec-Fetch-Dest", "document")
req.Header.Set("Sec-Fetch-Mode", "navigate")
req.Header.Set("Sec-Fetch-Site", "none")
req.Header.Set("Sec-Fetch-User", "?1")
req.Header.Set("Upgrade-Insecure-Requests", "1")
req.Header.Set("Referer", u.Scheme+"://"+hostname+"/")
// Custom transport: TLS ServerName for certificate validation with pinned IP.
client := &http.Client{
Timeout: fetchTimeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
ServerName: hostname,
},
},
// Follow redirects (default behavior), up to 10 hops
}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("fetch failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d %s", resp.StatusCode, resp.Status)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodySize))
if err != nil {
return "", fmt.Errorf("read failed: %w", err)
}
text := htmlToText(string(body))
logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(text))
return text, nil
}
// htmlToText extracts clean text from HTML, removing scripts/styles/nav.
func htmlToText(html string) string {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return stripTags(html)
}
doc.Find("script, style, nav, footer, header, iframe, noscript, svg, img").Remove()
var sb strings.Builder
doc.Find("body").Each(func(i int, s *goquery.Selection) {
sb.WriteString(s.Text())
})
text := sb.String()
// Normalize whitespace: collapse blank lines
lines := strings.Split(text, "\n")
var cleaned []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
cleaned = append(cleaned, line)
}
}
return strings.Join(cleaned, "\n")
}
func stripTags(s string) string {
var sb strings.Builder
inTag := false
for _, r := range s {
if r == '<' {
inTag = true
} else if r == '>' {
inTag = false
} else if !inTag {
sb.WriteRune(r)
}
}
return sb.String()
}
+198
View File
@@ -0,0 +1,198 @@
package web_search
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const (
// defaultBingSearchURL is the hardcoded Bing search API URL.
// Not configurable by tenants — prevents SSRF.
defaultBingSearchURL = "https://api.bing.microsoft.com/v7.0/search"
)
var (
defaultUserAgentHeader = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"
defaultBingTimeout = 10 * time.Second
)
type bingSafeSearch string
const (
bingSafeSearchOff bingSafeSearch = "Off"
bingSafeSearchModerate bingSafeSearch = "Moderate"
bingSafeSearchStrict bingSafeSearch = "Strict"
)
type bingFreshness string
const (
bingFreshnessDay = "Day"
bingFreshnessWeek = "Week"
bingFreshnessMonth = "Month"
)
// BingProvider implements web search using Bing Search API
type BingProvider struct {
client *http.Client
baseURL string
apiKey string
}
// NewBingProvider creates a new Bing provider from parameters (no environment variables).
func NewBingProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
if params.APIKey == "" {
return nil, fmt.Errorf("API key is required for Bing provider")
}
client := &http.Client{
Timeout: defaultBingTimeout,
}
return &BingProvider{
client: client,
baseURL: defaultBingSearchURL, // Hardcoded — not tenant-configurable
apiKey: params.APIKey,
}, 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) {
if len(query) == 0 {
return nil, fmt.Errorf("query is empty")
}
logger.Infof(ctx, "[WebSearch][Bing] query=%q maxResults=%d url=%s", query, maxResults, p.baseURL)
req, err := p.buildParams(ctx, query, maxResults, includeDate)
if err != nil {
return nil, err
}
results, err := p.doSearch(ctx, req)
if err != nil {
logger.Warnf(ctx, "[WebSearch][Bing] failed: %v", err)
return nil, err
}
logger.Infof(ctx, "[WebSearch][Bing] returned %d results", len(results))
return results, nil
}
func (p *BingProvider) doSearch(ctx context.Context, req *http.Request) ([]*types.WebSearchResult, error) {
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
logger.Warnf(ctx, "[WebSearch][Bing] API returned status %d: %s", resp.StatusCode, string(body))
return nil, fmt.Errorf("bing API returned status %d: %s", resp.StatusCode, string(body))
}
var respData bingSearchResponse
if err := json.Unmarshal(body, &respData); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
results := make([]*types.WebSearchResult, 0, len(respData.WebPages.Value))
for _, item := range respData.WebPages.Value {
results = append(results, &types.WebSearchResult{
Title: item.Name,
URL: item.URL,
Snippet: item.Snippet,
Source: "bing",
PublishedAt: &item.DateLastCrawled,
})
}
return results, nil
}
// bingSearchResponse defines the response structure for Bing search API.
type bingSearchResponse struct {
Type string `json:"_type"`
QueryContext struct {
OriginalQuery string `json:"originalQuery"`
} `json:"queryContext"`
WebPages struct {
WebSearchURL string `json:"webSearchUrl"`
TotalEstimatedMatches int `json:"totalEstimatedMatches"`
Value []struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
IsFamilyFriendly bool `json:"isFamilyFriendly"`
DisplayURL string `json:"displayUrl"`
Snippet string `json:"snippet"`
DateLastCrawled time.Time `json:"dateLastCrawled"`
SearchTags []struct {
Name string `json:"name"`
Content string `json:"content"`
} `json:"searchTags,omitempty"`
About []struct {
Name string `json:"name"`
} `json:"about,omitempty"`
} `json:"value"`
} `json:"webPages"`
RelatedSearches struct {
ID string `json:"id"`
Value []struct {
Text string `json:"text"`
DisplayText string `json:"displayText"`
WebSearchURL string `json:"webSearchUrl"`
} `json:"value"`
} `json:"relatedSearches"`
RankingResponse struct {
Mainline struct {
Items []struct {
AnswerType string `json:"answerType"`
ResultIndex int `json:"resultIndex"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"mainline"`
Sidebar struct {
Items []struct {
AnswerType string `json:"answerType"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"sidebar"`
} `json:"rankingResponse"`
}
func (p *BingProvider) buildParams(ctx context.Context, query string, maxResults int, includeDate bool) (*http.Request, error) {
params := url.Values{}
params.Set("q", query)
params.Set("count", strconv.Itoa(maxResults))
queryURL := fmt.Sprintf("%s?%s", p.baseURL, params.Encode())
req, err := http.NewRequestWithContext(ctx, "GET", queryURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", defaultUserAgentHeader)
req.Header.Set("Ocp-Apim-Subscription-Key", p.apiKey)
return req, nil
}
@@ -0,0 +1,254 @@
package web_search
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// DuckDuckGoProvider implements web search using DuckDuckGo (HTML first, API fallback)
type DuckDuckGoProvider struct {
client *http.Client
}
// NewDuckDuckGoProvider creates a new DuckDuckGo provider.
// DuckDuckGo is free and requires no API key or configuration.
func NewDuckDuckGoProvider(params types.WebSearchProviderParameters) (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)
}
// searchHTML performs a web search using DuckDuckGo HTML endpoint
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)
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)
}
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",
)
curlCommand := fmt.Sprintf(
"curl -X GET '%s' -H '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'",
req.URL.String(),
)
logger.Infof(ctx, "Curl of request: %s", secutils.SanitizeForLog(curlCommand))
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)
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
}
// searchAPI performs a web search using DuckDuckGo API endpoint
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
}
// cleanDDGURL cleans the URL from DuckDuckGo HTML endpoint
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
}
// extractTitle extracts the title from the text
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,88 @@
package web_search
import (
"context"
"fmt"
"google.golang.org/api/customsearch/v1"
"google.golang.org/api/option"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// GoogleProvider implements web search using Google Custom Search Engine API
type GoogleProvider struct {
srv *customsearch.Service
apiKey string
engineID string
}
// NewGoogleProvider creates a new Google provider from parameters (no environment variables).
// The API endpoint is the official Google Custom Search endpoint — not tenant-configurable.
func NewGoogleProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
if params.APIKey == "" {
return nil, fmt.Errorf("API key is required for Google provider")
}
if params.EngineID == "" {
return nil, fmt.Errorf("engine ID is required for Google provider")
}
clientOpts := []option.ClientOption{
option.WithAPIKey(params.APIKey),
}
srv, err := customsearch.NewService(context.Background(), clientOpts...)
if err != nil {
return nil, err
}
return &GoogleProvider{
srv: srv,
apiKey: params.APIKey,
engineID: params.EngineID,
}, nil
}
// Name returns the provider name
func (p *GoogleProvider) Name() string {
return "google"
}
// Search performs a web search using Google Custom Search Engine API
func (p *GoogleProvider) Search(
ctx context.Context,
query string,
maxResults int,
includeDate bool,
) ([]*types.WebSearchResult, error) {
if len(query) == 0 {
return nil, fmt.Errorf("query is empty")
}
logger.Infof(ctx, "[WebSearch][Google] query=%q maxResults=%d engineID=%s", query, maxResults, p.engineID)
cseCall := p.srv.Cse.List().Context(ctx).Cx(p.engineID).Q(query)
if maxResults > 0 {
cseCall = cseCall.Num(int64(maxResults))
} else {
cseCall = cseCall.Num(5)
}
cseCall = cseCall.Hl("ch-zh")
resp, err := cseCall.Do()
if err != nil {
logger.Warnf(ctx, "[WebSearch][Google] failed: %v", err)
return nil, err
}
results := make([]*types.WebSearchResult, 0)
for _, item := range resp.Items {
result := &types.WebSearchResult{
Title: item.Title,
URL: item.Link,
Snippet: item.Snippet,
Source: "google",
}
results = append(results, result)
}
logger.Infof(ctx, "[WebSearch][Google] returned %d results", len(results))
return results, nil
}
@@ -0,0 +1,45 @@
package web_search
import (
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ProviderFactory creates a new web search provider instance from parameters.
type ProviderFactory func(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error)
// Registry manages web search provider type registrations.
// It maps provider type IDs (e.g., "bing", "google") to their factory functions.
// Instances are created on-demand with tenant-specific parameters.
type Registry struct {
factories map[string]ProviderFactory
mu sync.RWMutex
}
// NewRegistry creates a new web search provider registry
func NewRegistry() *Registry {
return &Registry{
factories: make(map[string]ProviderFactory),
}
}
// Register registers a provider type factory by ID
func (r *Registry) Register(id string, factory ProviderFactory) {
r.mu.Lock()
defer r.mu.Unlock()
r.factories[id] = factory
}
// CreateProvider creates a provider instance by type with the given parameters.
func (r *Registry) CreateProvider(providerType string, params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
r.mu.RLock()
factory, ok := r.factories[providerType]
r.mu.RUnlock()
if !ok {
return nil, fmt.Errorf("web search provider type %s not registered", providerType)
}
return factory(params)
}
@@ -0,0 +1,141 @@
package web_search
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const (
// defaultTavilySearchURL is the hardcoded Tavily API URL.
// Not configurable by tenants — prevents SSRF.
defaultTavilySearchURL = "https://api.tavily.com/search"
)
var (
defaultTavilyTimeout = 15 * time.Second
)
// TavilyProvider implements web search using Tavily Search API
type TavilyProvider struct {
client *http.Client
baseURL string
apiKey string
}
// NewTavilyProvider creates a new Tavily provider from parameters (no environment variables).
func NewTavilyProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
if params.APIKey == "" {
return nil, fmt.Errorf("API key is required for Tavily provider")
}
client := &http.Client{
Timeout: defaultTavilyTimeout,
}
return &TavilyProvider{
client: client,
baseURL: defaultTavilySearchURL,
apiKey: params.APIKey,
}, nil
}
// Name returns the provider name
func (p *TavilyProvider) Name() string {
return "tavily"
}
// Search performs a web search using Tavily Search API
func (p *TavilyProvider) Search(
ctx context.Context,
query string,
maxResults int,
includeDate bool,
) ([]*types.WebSearchResult, error) {
if len(query) == 0 {
return nil, fmt.Errorf("query is empty")
}
logger.Infof(ctx, "[WebSearch][Tavily] query=%q maxResults=%d url=%s", query, maxResults, p.baseURL)
reqBody := tavilySearchRequest{
APIKey: p.apiKey,
Query: query,
MaxResults: maxResults,
}
bodyBytes, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", p.baseURL, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to execute request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
logger.Warnf(ctx, "[WebSearch][Tavily] API returned status %d: %s", resp.StatusCode, string(respBody))
return nil, fmt.Errorf("tavily API returned status %d: %s", resp.StatusCode, string(respBody))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var respData tavilySearchResponse
if err := json.Unmarshal(respBody, &respData); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
results := make([]*types.WebSearchResult, 0, len(respData.Results))
for _, item := range respData.Results {
result := &types.WebSearchResult{
Title: item.Title,
URL: item.URL,
Snippet: item.Content,
Source: "tavily",
}
if includeDate && item.PublishedDate != "" {
if t, err := time.Parse(time.RFC3339, item.PublishedDate); err == nil {
result.PublishedAt = &t
}
}
results = append(results, result)
}
logger.Infof(ctx, "[WebSearch][Tavily] returned %d results", len(results))
return results, nil
}
// tavilySearchRequest defines the request body for Tavily search API
type tavilySearchRequest struct {
APIKey string `json:"api_key"`
Query string `json:"query"`
MaxResults int `json:"max_results"`
}
// tavilySearchResponse defines the response structure for Tavily search API
type tavilySearchResponse struct {
Query string `json:"query"`
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Content string `json:"content"`
Score float64 `json:"score"`
PublishedDate string `json:"published_date,omitempty"`
} `json:"results"`
}