-
-
Notifications
You must be signed in to change notification settings - Fork 537
/
serpapi.go
77 lines (60 loc) · 1.64 KB
/
serpapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package serpapi
import (
"context"
"errors"
"os"
"strings"
"github.com/tmc/langchaingo/callbacks"
"github.com/tmc/langchaingo/tools"
"github.com/tmc/langchaingo/tools/serpapi/internal"
)
var ErrMissingToken = errors.New("missing the serpapi API key, set it in the SERPAPI_API_KEY environment variable")
type Tool struct {
CallbacksHandler callbacks.Handler
client *internal.Client
}
var _ tools.Tool = Tool{}
// New creates a new serpapi tool to search on internet.
func New(opts ...Option) (*Tool, error) {
options := &options{
apiKey: os.Getenv("SERPAPI_API_KEY"),
}
for _, opt := range opts {
opt(options)
}
if options.apiKey == "" {
return nil, ErrMissingToken
}
return &Tool{
client: internal.New(options.apiKey),
}, nil
}
func (t Tool) Name() string {
return "GoogleSearch"
}
func (t Tool) Description() string {
return `
"A wrapper around Google Search. "
"Useful for when you need to answer questions about current events. "
"Always one of the first options when you need to find information on internet"
"Input should be a search query."`
}
func (t Tool) Call(ctx context.Context, input string) (string, error) {
if t.CallbacksHandler != nil {
t.CallbacksHandler.HandleToolStart(ctx, input)
}
result, err := t.client.Search(ctx, input)
if err != nil {
if errors.Is(err, internal.ErrNoGoodResult) {
return "No good Google Search Results was found", nil
}
if t.CallbacksHandler != nil {
t.CallbacksHandler.HandleToolError(ctx, err)
}
return "", err
}
if t.CallbacksHandler != nil {
t.CallbacksHandler.HandleToolEnd(ctx, result)
}
return strings.Join(strings.Fields(result), " "), nil
}