-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathsearch.go
293 lines (257 loc) · 7.06 KB
/
search.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/google/safehtml/template"
"golang.org/x/oscar/internal/llm"
"golang.org/x/oscar/internal/search"
)
// a searchPage holds the fields needed to display the results
// of a search.
type searchPage struct {
CommonPage
Params searchParams // the raw query parameters
Results []search.Result // the search results to display
Error error // if non-nil, the error to display instead of results
}
func (g *Gaby) handleSearch(w http.ResponseWriter, r *http.Request) {
handlePage(w, g.populateSearchPage(r), searchPageTmpl)
}
func handlePage(w http.ResponseWriter, p page, tmpl *template.Template) {
b, err := Exec(tmpl, p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, _ = w.Write(b)
}
// populateSearchPage returns the contents of the vector search page.
func (g *Gaby) populateSearchPage(r *http.Request) *searchPage {
var pm searchParams
pm.parseParams(r)
p := &searchPage{
Params: pm,
}
p.setCommonPage()
opts, err := pm.toOptions()
if err != nil {
p.Error = fmt.Errorf("invalid form value: %w", err)
return p
}
q := trim(pm.Query)
results, err := g.search(r.Context(), q, *opts)
if err != nil {
p.Error = fmt.Errorf("search: %w", err)
return p
}
p.Results = results
return p
}
// search performs a search on the query and options.
//
// If the query is an exact match for an ID in the vector database,
// it looks up the vector for that ID and performs a search for the
// nearest neighbors of that vector.
// Otherwise, it embeds the query and performs a nearest neighbor
// search for the embedding.
//
// It returns an error if search fails.
func (g *Gaby) search(ctx context.Context, q string, opts search.Options) (results []search.Result, err error) {
if q == "" {
return nil, nil
}
if vec, ok := g.vector.Get(q); ok {
results = search.Vector(g.vector, g.docs,
&search.VectorRequest{
Options: opts,
Vector: vec,
})
} else {
if results, err = search.Query(ctx, g.vector, g.docs, g.embed,
&search.QueryRequest{
EmbedDoc: llm.EmbedDoc{Text: q},
Options: opts,
}); err != nil {
return nil, err
}
}
for i := range results {
results[i].Round()
}
return results, nil
}
// searchParams holds the raw query parameters.
type searchParams struct {
Query string // a text query, or an ID of a document in the database
// String representations of the fields of [search.Options]
Threshold string
Limit string
Allow, Deny string // comma separated lists
}
// parseParams parses the query params from the request.
func (pm *searchParams) parseParams(r *http.Request) {
pm.Query = r.FormValue(paramQuery)
pm.Threshold = r.FormValue(paramThreshold)
pm.Limit = r.FormValue(paramLimit)
pm.Allow = r.FormValue(paramAllow)
pm.Deny = r.FormValue(paramDeny)
}
func (p *searchPage) setCommonPage() {
p.CommonPage = CommonPage{
ID: searchID,
Description: "Search Oscar's database of GitHub issues, Go documentation, and other documents.",
FeedbackURL: "https://github.com/golang/oscar/issues/60#issuecomment-new",
Form: Form{
Inputs: p.Params.inputs(),
SubmitText: "search",
},
}
}
const (
paramQuery = "q"
paramThreshold = "threshold"
paramLimit = "limit"
paramAllow = "allow_kind"
paramDeny = "deny_kind"
)
var (
safeQuery = toSafeID(paramQuery)
safeThreshold = toSafeID(paramThreshold)
safeLimit = toSafeID(paramLimit)
safeAllow = toSafeID(paramAllow)
safeDeny = toSafeID(paramDeny)
)
// inputs converts the params into HTML form inputs.
func (pm *searchParams) inputs() []FormInput {
return []FormInput{
{
Label: "query",
Type: "string",
Description: "the text to search for neigbors of OR the ID (usually a URL) of a document in the vector database",
Name: safeQuery,
Required: true,
Typed: TextInput{
ID: safeQuery,
Value: pm.Query,
},
},
{
Label: "min similarity",
Type: "float64 between 0 and 1",
Description: "similarity cutoff (default: 0, allow all)",
Name: safeThreshold,
Typed: TextInput{
ID: safeThreshold,
Value: pm.Threshold,
},
},
{
Label: "max results",
Type: "int",
Description: "maximum number of results to display (default: 20)",
Name: safeLimit,
Typed: TextInput{
ID: safeLimit,
Value: pm.Limit,
},
},
{
Label: "include types",
Type: "comma-separated list",
Description: "document types to include, e.g `GitHubIssue,GoBlog` (default: empty, include all)",
Name: safeAllow,
Typed: TextInput{
ID: safeAllow,
Value: pm.Allow,
},
},
{
Label: "exclude types",
Type: "comma-separated list",
Description: "document types to filter out, e.g `GitHubIssue,GoBlog` (default: empty, exclude none)",
Name: safeDeny,
Typed: TextInput{
ID: safeDeny,
Value: pm.Deny,
},
},
}
}
var trim = strings.TrimSpace
// toSearchOptions converts a searchParams into a [search.Options],
// trimming any leading/trailing spaces.
//
// It returns an error if any of the form inputs is invalid.
func (f *searchParams) toOptions() (_ *search.Options, err error) {
opts := &search.Options{}
splitAndTrim := func(s string) []string {
vs := strings.Split(s, ",")
for i, v := range vs {
vs[i] = trim(v)
}
return vs
}
if l := trim(f.Limit); l != "" {
opts.Limit, err = strconv.Atoi(l)
if err != nil {
return nil, fmt.Errorf("limit: %w", err)
}
}
if t := trim(f.Threshold); t != "" {
opts.Threshold, err = strconv.ParseFloat(t, 64)
if err != nil {
return nil, fmt.Errorf("threshold: %w", err)
}
}
if a := trim(f.Allow); a != "" {
opts.AllowKind = splitAndTrim(a)
}
if d := trim(f.Deny); d != "" {
opts.DenyKind = splitAndTrim(d)
}
if err := opts.Validate(); err != nil {
return nil, err
}
return opts, nil
}
var searchPageTmpl = newTemplate(searchPageTmplFile, nil)
func (g *Gaby) handleSearchAPI(w http.ResponseWriter, r *http.Request) {
sreq, err := readJSONBody[search.QueryRequest](r)
if err != nil {
// The error could also come from failing to read the body, but then the
// connection is probably broken so it doesn't matter what status we send.
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
sres, err := search.Query(r.Context(), g.vector, g.docs, g.embed, sreq)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.Marshal(sres)
if err != nil {
http.Error(w, "json.Marshal: "+err.Error(), http.StatusInternalServerError)
return
}
_, _ = w.Write(data)
}
func readJSONBody[T any](r *http.Request) (*T, error) {
defer r.Body.Close()
data, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
t := new(T)
if err := json.Unmarshal(data, t); err != nil {
return nil, err
}
return t, nil
}