Compare commits
2 Commits
35733aa3e2
...
78f58a92a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78f58a92a1 | ||
|
|
0f9d9fb9c6 |
@@ -16,9 +16,6 @@ type Config struct {
|
||||
ContextSize int `yaml:"context_size"`
|
||||
APIKey string `yaml:"api_key"`
|
||||
|
||||
// SearXNG Configuration
|
||||
SearXNGURL string `yaml:"searxng_url"`
|
||||
|
||||
// System Prompt
|
||||
Prompt string `yaml:"prompt"`
|
||||
|
||||
@@ -73,9 +70,6 @@ func Load() (*Config, error) {
|
||||
if cfg.Model == "" {
|
||||
return nil, fmt.Errorf("model is required in config")
|
||||
}
|
||||
if cfg.SearXNGURL == "" {
|
||||
return nil, fmt.Errorf("searxng_url is required in config")
|
||||
}
|
||||
if cfg.Prompt == "" {
|
||||
return nil, fmt.Errorf("prompt is required in config")
|
||||
}
|
||||
|
||||
8
go.mod
8
go.mod
@@ -1,9 +1,10 @@
|
||||
module tell-me
|
||||
|
||||
go 1.23.0
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0
|
||||
github.com/PuerkitoBio/goquery v1.11.0
|
||||
github.com/jlubawy/go-boilerpipe v0.4.0
|
||||
github.com/modelcontextprotocol/go-sdk v1.1.0
|
||||
github.com/sashabaranov/go-openai v1.41.2
|
||||
@@ -11,10 +12,9 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/PuerkitoBio/goquery v1.9.2 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.2 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/google/jsonschema-go v0.3.0 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/oauth2 v0.30.0 // indirect
|
||||
)
|
||||
|
||||
30
go.sum
30
go.sum
@@ -1,11 +1,14 @@
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0 h1:04VXMiE50YYfCfLboJCLcgqF5x+rHJnb1ssNmqpLH/k=
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0/go.mod h1:NUI78lGg/a7vpEJTz/0uOcYMaibytE4BUOQS8k78yPQ=
|
||||
github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
|
||||
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
|
||||
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
|
||||
github.com/PuerkitoBio/goquery v1.11.0 h1:jZ7pwMQXIITcUXNH83LLk+txlaEy6NVOfTuP43xxfqw=
|
||||
github.com/PuerkitoBio/goquery v1.11.0/go.mod h1:wQHgxUOU3JGuj3oD/QFfxUdlzW6xPHfqyHre6VMY4DQ=
|
||||
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
|
||||
@@ -39,11 +42,16 @@ github.com/yuin/goldmark v1.7.1 h1:3bajkSilaCbjdKVsKdZjZCLBNPL9pYzrCakKaf4U49U=
|
||||
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190328230028-74de082e2cca/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
@@ -51,15 +59,22 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -68,28 +83,37 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -19,12 +19,11 @@ type Client struct {
|
||||
client *openai.Client
|
||||
model string
|
||||
contextSize int
|
||||
searxngURL string
|
||||
mcpManager *mcp.Manager
|
||||
}
|
||||
|
||||
// NewClient creates a new LLM client
|
||||
func NewClient(apiURL, apiKey, model string, contextSize int, searxngURL string, mcpManager *mcp.Manager) *Client {
|
||||
func NewClient(apiURL, apiKey, model string, contextSize int, mcpManager *mcp.Manager) *Client {
|
||||
config := openai.DefaultConfig(apiKey)
|
||||
config.BaseURL = apiURL
|
||||
|
||||
@@ -34,7 +33,6 @@ func NewClient(apiURL, apiKey, model string, contextSize int, searxngURL string,
|
||||
client: client,
|
||||
model: model,
|
||||
contextSize: contextSize,
|
||||
searxngURL: searxngURL,
|
||||
mcpManager: mcpManager,
|
||||
}
|
||||
}
|
||||
@@ -230,7 +228,7 @@ func (c *Client) handleToolCall(ctx context.Context, toolCall openai.ToolCall) s
|
||||
return fmt.Sprintf("Error parsing arguments: %v", err)
|
||||
}
|
||||
fmt.Printf("Searching: %s\n", args.Query)
|
||||
result, err := tools.WebSearch(c.searxngURL, args.Query)
|
||||
result, err := tools.WebSearch(args.Query)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("Search error: %v", err)
|
||||
}
|
||||
|
||||
2
main.go
2
main.go
@@ -45,7 +45,6 @@ func main() {
|
||||
cfg.APIKey,
|
||||
cfg.Model,
|
||||
cfg.ContextSize,
|
||||
cfg.SearXNGURL,
|
||||
mcpManager,
|
||||
)
|
||||
|
||||
@@ -84,7 +83,6 @@ func main() {
|
||||
fmt.Println("╚════════════════════════════════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
fmt.Printf("Using model: %s\n", cfg.Model)
|
||||
fmt.Printf("SearXNG: %s\n", cfg.SearXNGURL)
|
||||
|
||||
// Display MCP server status
|
||||
if len(cfg.MCPServers) > 0 {
|
||||
|
||||
233
tools/search.go
233
tools/search.go
@@ -1,12 +1,20 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
const (
|
||||
maxRetries = 3
|
||||
timeout = 60 * time.Second
|
||||
)
|
||||
|
||||
// SearchResult represents a single search result
|
||||
@@ -16,66 +24,199 @@ type SearchResult struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// SearchResponse represents the SearXNG API response
|
||||
type SearchResponse struct {
|
||||
Results []SearchResult `json:"results"`
|
||||
}
|
||||
// WebSearch performs a web search using Startpage
|
||||
func WebSearch(query string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
// WebSearch performs a web search using SearXNG
|
||||
func WebSearch(searxngURL, query string) (string, error) {
|
||||
// Build the search URL
|
||||
searchURL := fmt.Sprintf("%s/search", strings.TrimSuffix(searxngURL, "/"))
|
||||
// Create HTTP client with proxy support
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
}
|
||||
|
||||
// Create URL with query parameters
|
||||
params := url.Values{}
|
||||
params.Add("q", query)
|
||||
params.Add("format", "json")
|
||||
params.Add("language", "en")
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
fullURL := fmt.Sprintf("%s?%s", searchURL, params.Encode())
|
||||
|
||||
// Make the request
|
||||
resp, err := http.Get(fullURL)
|
||||
// Perform search with retry logic
|
||||
results, err := searchStartpage(ctx, client, query)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to perform search: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("search request failed with status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse the response
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
var searchResp SearchResponse
|
||||
if err := json.Unmarshal(body, &searchResp); err != nil {
|
||||
return "", fmt.Errorf("failed to parse search results: %w", err)
|
||||
return "", fmt.Errorf("Startpage search failed: %w", err)
|
||||
}
|
||||
|
||||
// Format results as text
|
||||
if len(searchResp.Results) == 0 {
|
||||
if len(results) == 0 {
|
||||
return "No results found.", nil
|
||||
}
|
||||
|
||||
var results strings.Builder
|
||||
results.WriteString(fmt.Sprintf("Found %d results:\n\n", len(searchResp.Results)))
|
||||
var output strings.Builder
|
||||
fmt.Fprintf(&output, "Found %d results:\n\n", len(results))
|
||||
|
||||
for i, result := range searchResp.Results {
|
||||
for i, result := range results {
|
||||
if i >= 10 { // Limit to top 10 results
|
||||
break
|
||||
}
|
||||
results.WriteString(fmt.Sprintf("%d. %s\n", i+1, result.Title))
|
||||
results.WriteString(fmt.Sprintf(" URL: %s\n", result.URL))
|
||||
fmt.Fprintf(&output, "%d. %s\n", i+1, result.Title)
|
||||
fmt.Fprintf(&output, " URL: %s\n", result.URL)
|
||||
if result.Content != "" {
|
||||
results.WriteString(fmt.Sprintf(" %s\n", result.Content))
|
||||
fmt.Fprintf(&output, " %s\n", result.Content)
|
||||
}
|
||||
results.WriteString("\n")
|
||||
fmt.Fprintf(&output, "\n")
|
||||
}
|
||||
|
||||
return results.String(), nil
|
||||
return output.String(), nil
|
||||
}
|
||||
|
||||
// searchStartpage performs the actual Startpage search
|
||||
func searchStartpage(ctx context.Context, client *http.Client, query string) ([]SearchResult, error) {
|
||||
// Build Startpage search URL
|
||||
searchURL := fmt.Sprintf("https://www.startpage.com/sp/search?query=%s", url.QueryEscape(query))
|
||||
|
||||
// Create request with proper headers
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", searchURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create search request: %w", err)
|
||||
}
|
||||
|
||||
// Set browser-like user agent
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
|
||||
|
||||
// Execute request with retry logic
|
||||
resp, err := executeWithRetry(ctx, client, req, "search Startpage")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check response status
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
|
||||
return nil, fmt.Errorf("search request failed with status: %d %s", resp.StatusCode, resp.Status)
|
||||
}
|
||||
|
||||
// Parse HTML response
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse search results: %w", err)
|
||||
}
|
||||
|
||||
// Extract search results from Startpage
|
||||
var results []SearchResult
|
||||
|
||||
// Find all search result links in the "Web results" section
|
||||
doc.Find("a[href]").Each(func(i int, s *goquery.Selection) {
|
||||
href, exists := s.Attr("href")
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
|
||||
// Skip internal Startpage links and Anonymous View links
|
||||
if strings.Contains(href, "startpage.com") ||
|
||||
strings.Contains(href, "/av/proxy") ||
|
||||
strings.HasPrefix(href, "#") ||
|
||||
strings.HasPrefix(href, "/") {
|
||||
return
|
||||
}
|
||||
|
||||
// Only process HTTP/HTTPS URLs
|
||||
if !strings.HasPrefix(href, "http://") && !strings.HasPrefix(href, "https://") {
|
||||
return
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(s.Text())
|
||||
if title == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// Skip very short titles (likely navigation or other non-content links)
|
||||
if len(title) < 10 {
|
||||
return
|
||||
}
|
||||
|
||||
// Try to find description text near the link
|
||||
var description string
|
||||
parent := s.Parent()
|
||||
for parent.Length() > 0 {
|
||||
// Look for text content in siblings or parent elements
|
||||
text := strings.TrimSpace(parent.Text())
|
||||
if len(text) > len(title)+20 { // Found longer text that includes description
|
||||
// Extract the part that's not the title
|
||||
if idx := strings.Index(text, title); idx >= 0 {
|
||||
remainder := strings.TrimSpace(text[idx+len(title):])
|
||||
if len(remainder) > 20 { // Good description length
|
||||
description = remainder
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
parent = parent.Parent()
|
||||
if parent.Length() == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Limit description length
|
||||
if len(description) > 200 {
|
||||
description = description[:200] + "..."
|
||||
}
|
||||
|
||||
// Check if we already have this URL (avoid duplicates)
|
||||
for _, existing := range results {
|
||||
if existing.URL == href {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
results = append(results, SearchResult{
|
||||
Title: title,
|
||||
URL: href,
|
||||
Content: description,
|
||||
})
|
||||
})
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// executeWithRetry executes an HTTP request with exponential backoff retry logic
|
||||
func executeWithRetry(ctx context.Context, client *http.Client, req *http.Request, operation string) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
|
||||
// Retry logic with exponential backoff
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
resp, err = client.Do(req)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Don't retry on the last attempt
|
||||
if attempt == maxRetries {
|
||||
break
|
||||
}
|
||||
|
||||
// Exponential backoff: 1s, 2s, 4s
|
||||
backoffDuration := time.Duration(1<<uint(attempt)) * time.Second
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("%s cancelled: %v", operation, ctx.Err())
|
||||
case <-time.After(backoffDuration):
|
||||
// Continue to next retry
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to %s after %d retries: %v", operation, maxRetries, err)
|
||||
}
|
||||
|
||||
// logProxyConfiguration logs the proxy configuration for debugging
|
||||
func init() {
|
||||
if httpsProxy := os.Getenv("HTTPS_PROXY"); httpsProxy != "" {
|
||||
fmt.Printf("Using HTTPS_PROXY: %s\n", httpsProxy)
|
||||
} else if httpProxy := os.Getenv("HTTP_PROXY"); httpProxy != "" {
|
||||
fmt.Printf("Using HTTP_PROXY: %s\n", httpProxy)
|
||||
} else if allProxy := os.Getenv("ALL_PROXY"); allProxy != "" {
|
||||
fmt.Printf("Using ALL_PROXY: %s\n", allProxy)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user