websearch.go 4.63 KB
Newer Older
1
2
3
4
package tools

import (
	"bytes"
5
	"context"
6
	"encoding/json"
7
	"errors"
8
9
10
	"fmt"
	"io"
	"net/http"
11
12
	"net/url"
	"strconv"
13
14
15
16
	"strings"
	"time"

	"github.com/ollama/ollama/api"
17
	"github.com/ollama/ollama/auth"
18
19
20
21
22
23
24
)

const (
	webSearchAPI     = "https://ollama.com/api/web_search"
	webSearchTimeout = 15 * time.Second
)

25
26
27
// ErrWebSearchAuthRequired is returned when web search requires authentication
var ErrWebSearchAuthRequired = errors.New("web search requires authentication")

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
// WebSearchTool implements web search using Ollama's hosted API.
type WebSearchTool struct{}

// Name returns the tool name.
func (w *WebSearchTool) Name() string {
	return "web_search"
}

// Description returns a description of the tool.
func (w *WebSearchTool) Description() string {
	return "Search the web for current information. Use this when you need up-to-date information that may not be in your training data."
}

// Schema returns the tool's parameter schema.
func (w *WebSearchTool) Schema() api.ToolFunction {
	props := api.NewToolPropertiesMap()
	props.Set("query", api.ToolProperty{
		Type:        api.PropertyType{"string"},
		Description: "The search query to look up on the web",
	})
	return api.ToolFunction{
		Name:        w.Name(),
		Description: w.Description(),
		Parameters: api.ToolFunctionParameters{
			Type:       "object",
			Properties: props,
			Required:   []string{"query"},
		},
	}
}

// webSearchRequest is the request body for the web search API.
type webSearchRequest struct {
	Query      string `json:"query"`
	MaxResults int    `json:"max_results,omitempty"`
}

// webSearchResponse is the response from the web search API.
type webSearchResponse struct {
	Results []webSearchResult `json:"results"`
}

// webSearchResult is a single search result.
type webSearchResult struct {
	Title   string `json:"title"`
	URL     string `json:"url"`
	Content string `json:"content"`
}

// Execute performs the web search.
78
// Uses Ollama key signing for authentication - this makes requests via ollama.com API.
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
func (w *WebSearchTool) Execute(args map[string]any) (string, error) {
	query, ok := args["query"].(string)
	if !ok || query == "" {
		return "", fmt.Errorf("query parameter is required")
	}

	// Prepare request
	reqBody := webSearchRequest{
		Query:      query,
		MaxResults: 5,
	}

	jsonBody, err := json.Marshal(reqBody)
	if err != nil {
		return "", fmt.Errorf("marshaling request: %w", err)
	}

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
	// Parse URL and add timestamp for signing
	searchURL, err := url.Parse(webSearchAPI)
	if err != nil {
		return "", fmt.Errorf("parsing search URL: %w", err)
	}

	q := searchURL.Query()
	q.Add("ts", strconv.FormatInt(time.Now().Unix(), 10))
	searchURL.RawQuery = q.Encode()

	// Sign the request using Ollama key (~/.ollama/id_ed25519)
	// This authenticates with ollama.com using the local signing key
	ctx := context.Background()
	data := fmt.Appendf(nil, "%s,%s", http.MethodPost, searchURL.RequestURI())
	signature, err := auth.Sign(ctx, data)
	if err != nil {
		return "", fmt.Errorf("signing request: %w", err)
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, searchURL.String(), bytes.NewBuffer(jsonBody))
116
117
118
119
120
	if err != nil {
		return "", fmt.Errorf("creating request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")
121
122
123
	if signature != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signature))
	}
124
125
126
127
128
129
130
131
132
133
134
135
136
137

	// Send request
	client := &http.Client{Timeout: webSearchTimeout}
	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("sending request: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("reading response: %w", err)
	}

138
139
140
	if resp.StatusCode == http.StatusUnauthorized {
		return "", ErrWebSearchAuthRequired
	}
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("web search API returned status %d: %s", resp.StatusCode, string(body))
	}

	// Parse response
	var searchResp webSearchResponse
	if err := json.Unmarshal(body, &searchResp); err != nil {
		return "", fmt.Errorf("parsing response: %w", err)
	}

	// Format results
	if len(searchResp.Results) == 0 {
		return "No results found for query: " + query, nil
	}

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("Search results for: %s\n\n", query))

	for i, result := range searchResp.Results {
		sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, result.Title))
		sb.WriteString(fmt.Sprintf("   URL: %s\n", result.URL))
		if result.Content != "" {
			// Truncate long content (UTF-8 safe)
			content := result.Content
			runes := []rune(content)
			if len(runes) > 300 {
				content = string(runes[:300]) + "..."
			}
			sb.WriteString(fmt.Sprintf("   %s\n", content))
		}
		sb.WriteString("\n")
	}

	return sb.String(), nil
}