Files
jules/search/brave/brave.go
T

125 lines
2.6 KiB
Go

package brave
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
const (
BaseURL = "https://api.search.brave.com/res/v1"
httpTimeout = 10 * time.Second
)
type Client struct {
apiKey string
baseURL string
httpClient *http.Client
}
func New(apiKey, baseURL string) *Client {
return &Client{
apiKey: apiKey,
baseURL: baseURL,
httpClient: &http.Client{
Timeout: httpTimeout,
},
}
}
type webSearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description"`
}
type webSearchResponse struct {
Web struct {
Results []webSearchResult `json:"results"`
} `json:"web"`
Summarizer struct {
Key string `json:"key"`
} `json:"summarizer"`
}
type summaryMessage struct {
Type string `json:"type"`
Data string `json:"data"`
}
type summarizerResponse struct {
Summary []summaryMessage `json:"summary"`
}
func (c *Client) Search(ctx context.Context, query string) (string, error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/web/search", nil)
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", c.apiKey)
q := req.URL.Query()
q.Add("q", query)
q.Add("summary", "1")
req.URL.RawQuery = q.Encode()
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var body []byte
body, err = io.ReadAll(resp.Body)
return "", errors.Join(fmt.Errorf("status %d: %s", resp.StatusCode, body), err)
}
var webResp webSearchResponse
if err = json.NewDecoder(resp.Body).Decode(&webResp); err != nil {
return "", err
}
if webResp.Summarizer.Key == "" {
if len(webResp.Web.Results) > 0 {
return webResp.Web.Results[0].Description, nil
}
return "", errors.New("no results")
}
req, _ = http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/summarizer/search", nil)
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", c.apiKey)
q = req.URL.Query()
q.Add("key", webResp.Summarizer.Key)
req.URL.RawQuery = q.Encode()
resp, err = c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var body []byte
body, err = io.ReadAll(resp.Body)
return "", errors.Join(fmt.Errorf("status %d: %s", resp.StatusCode, body), err)
}
var sumResp summarizerResponse
if err = json.NewDecoder(resp.Body).Decode(&sumResp); err != nil {
return "", err
}
for _, msg := range sumResp.Summary {
if msg.Type == "token" {
return msg.Data, nil
}
}
return "", errors.New("no token in summary")
}