tavily.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package websearch
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. )
  10. const (
  11. tavilySearchEndpoint = "https://api.tavily.com/search"
  12. tavilyProviderName = "tavily"
  13. tavilySearchDepthBasic = "basic"
  14. )
  15. // TavilyProvider implements web search via the Tavily Search API.
  16. type TavilyProvider struct {
  17. apiKey string
  18. httpClient *http.Client
  19. }
  20. // NewTavilyProvider creates a Tavily Search provider.
  21. // The caller is responsible for configuring the http.Client with proxy/timeouts.
  22. func NewTavilyProvider(apiKey string, httpClient *http.Client) *TavilyProvider {
  23. if httpClient == nil {
  24. httpClient = http.DefaultClient
  25. }
  26. return &TavilyProvider{apiKey: apiKey, httpClient: httpClient}
  27. }
  28. func (t *TavilyProvider) Name() string { return tavilyProviderName }
  29. func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) {
  30. maxResults := req.MaxResults
  31. if maxResults <= 0 {
  32. maxResults = defaultMaxResults
  33. }
  34. payload := tavilyRequest{
  35. APIKey: t.apiKey,
  36. Query: req.Query,
  37. MaxResults: maxResults,
  38. SearchDepth: tavilySearchDepthBasic,
  39. }
  40. bodyBytes, err := json.Marshal(payload)
  41. if err != nil {
  42. return nil, fmt.Errorf("tavily: encode request: %w", err)
  43. }
  44. httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, tavilySearchEndpoint, bytes.NewReader(bodyBytes))
  45. if err != nil {
  46. return nil, fmt.Errorf("tavily: build request: %w", err)
  47. }
  48. httpReq.Header.Set("Content-Type", "application/json")
  49. resp, err := t.httpClient.Do(httpReq)
  50. if err != nil {
  51. return nil, fmt.Errorf("tavily: request failed: %w", err)
  52. }
  53. defer func() { _ = resp.Body.Close() }()
  54. body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize))
  55. if err != nil {
  56. return nil, fmt.Errorf("tavily: read body: %w", err)
  57. }
  58. if resp.StatusCode != http.StatusOK {
  59. return nil, fmt.Errorf("tavily: status %d: %s", resp.StatusCode, truncateBody(body))
  60. }
  61. var raw tavilyResponse
  62. if err := json.Unmarshal(body, &raw); err != nil {
  63. return nil, fmt.Errorf("tavily: decode response: %w", err)
  64. }
  65. results := make([]SearchResult, 0, len(raw.Results))
  66. for _, r := range raw.Results {
  67. results = append(results, SearchResult{
  68. URL: r.URL,
  69. Title: r.Title,
  70. Snippet: r.Content,
  71. })
  72. }
  73. return &SearchResponse{Results: results, Query: req.Query}, nil
  74. }
  75. type tavilyRequest struct {
  76. APIKey string `json:"api_key"`
  77. Query string `json:"query"`
  78. MaxResults int `json:"max_results"`
  79. SearchDepth string `json:"search_depth"`
  80. }
  81. type tavilyResponse struct {
  82. Results []tavilyResult `json:"results"`
  83. }
  84. type tavilyResult struct {
  85. URL string `json:"url"`
  86. Title string `json:"title"`
  87. Content string `json:"content"`
  88. Score float64 `json:"score"`
  89. }