-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathweb_tool_website_text.go
64 lines (57 loc) · 1.34 KB
/
web_tool_website_text.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
package tools
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
"golang.org/x/net/html"
)
type WebsiteTextTool UserFunction
var WebsiteText = WebsiteTextTool{
Name: "website_text",
Description: "Get the text content of a website by stripping all non-text tags and trimming whitespace.",
Inputs: &InputSchema{
Type: "object",
Properties: map[string]ParameterObject{
"url": {
Type: "string",
Description: "The URL of the website to retrieve the text content from.",
},
},
Required: []string{"url"},
},
}
func (w WebsiteTextTool) Call(input Input) (string, error) {
url, ok := input["url"].(string)
if !ok {
return "", fmt.Errorf("url must be a string")
}
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch website: %w", err)
}
defer resp.Body.Close()
var text strings.Builder
tokenizer := html.NewTokenizer(resp.Body)
for {
tt := tokenizer.Next()
if tt == html.ErrorToken {
if tokenizer.Err() == io.EOF {
break
}
return "", fmt.Errorf("tokenizer error: %w", tokenizer.Err())
}
if tt == html.TextToken {
trimmed := bytes.TrimSpace(tokenizer.Text())
if len(trimmed) > 0 {
text.Write(trimmed)
text.WriteRune('\n')
}
}
}
return text.String(), nil
}
func (w WebsiteTextTool) UserFunction() UserFunction {
return UserFunction(WebsiteText)
}