serper.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package search
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. const (
  12. serperBaseURL = "https://google.serper.dev/search"
  13. defaultTimeout = 15 * time.Second
  14. )
  15. // SerperProvider 使用 Serper API 的联网搜索实现(项目内直接调用,无需代理)。
  16. type SerperProvider struct {
  17. apiKey string
  18. client *http.Client
  19. }
  20. // NewSerperProvider 创建 Serper 搜索提供方。apiKey 为空时 Search 返回空字符串与 nil error(调用方回退)。
  21. func NewSerperProvider(apiKey string) *SerperProvider {
  22. return &SerperProvider{
  23. apiKey: strings.TrimSpace(apiKey),
  24. client: &http.Client{Timeout: defaultTimeout},
  25. }
  26. }
  27. // Search 执行搜索并返回格式化后的文本摘要,供 LLM 使用。未配置 apiKey 或请求失败时返回空字符串。
  28. func (p *SerperProvider) Search(ctx context.Context, query string) (string, error) {
  29. if p.apiKey == "" {
  30. return "", nil
  31. }
  32. reqBody := map[string]interface{}{"q": query}
  33. bodyBytes, _ := json.Marshal(reqBody)
  34. req, err := http.NewRequestWithContext(ctx, http.MethodPost, serperBaseURL, strings.NewReader(string(bodyBytes)))
  35. if err != nil {
  36. return "", fmt.Errorf("serper request: %w", err)
  37. }
  38. req.Header.Set("X-API-KEY", p.apiKey)
  39. req.Header.Set("Content-Type", "application/json")
  40. resp, err := p.client.Do(req)
  41. if err != nil {
  42. return "", fmt.Errorf("serper http: %w", err)
  43. }
  44. defer resp.Body.Close()
  45. if resp.StatusCode != http.StatusOK {
  46. bs, _ := io.ReadAll(resp.Body)
  47. return "", fmt.Errorf("serper api %d: %s", resp.StatusCode, string(bs))
  48. }
  49. var result serperResponse
  50. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  51. return "", fmt.Errorf("serper decode: %w", err)
  52. }
  53. return result.FormatOrganic(), nil
  54. }
  55. type serperResponse struct {
  56. Organic []struct {
  57. Title string `json:"title"`
  58. Link string `json:"link"`
  59. Snippet string `json:"snippet"`
  60. } `json:"organic"`
  61. }
  62. func (r *serperResponse) FormatOrganic() string {
  63. if len(r.Organic) == 0 {
  64. return ""
  65. }
  66. var b strings.Builder
  67. for i, o := range r.Organic {
  68. if i > 0 {
  69. b.WriteString("\n\n")
  70. }
  71. b.WriteString(o.Title)
  72. b.WriteString("\n")
  73. b.WriteString(o.Link)
  74. b.WriteString("\n")
  75. b.WriteString(o.Snippet)
  76. }
  77. return b.String()
  78. }