diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 664114ce7..c6753501f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1699,6 +1699,33 @@ and `{vendor, on}` beside the add and remove it took before. Covered by `TestSearchAPIOrderAndOff`, `TestSearchCLIOffAndMove`, `TestBackupSearchAPIsOrderAndOff` and `search-order.test.cjs`. +## Asking several search APIs together (mix) + +Two or more search APIs marked `mix` (`SearchAPI.Mix`, #2845) are asked +first, at once (`askSearchAPIsTogether`), each with its own keys and +timeouts as when it is asked alone (`askSearchAPIKeys`). Their pages go to +the model in turn (`mixedPages`): each API's first in the saved order, +then each one's second, a page an earlier one gave left out by its address +(`pageKey`: host in lower case, http and https alike, without fragment or +closing slash), at most `searchMixMost`: two APIs' worth of the count the +search asks for (the one it named, else Settings' results per search, 6 by +default, so 12), never more than 20. One that +fails or finds nothing leaves the others' pages; when none finds anything, +the APIs not mixed are asked in order as before. With fewer than two mixed +APIs on and ready, a search goes in order as if none were. Nothing is +added to the pages to say which API found them, so the text a vendor sees +reads as before. `MixSearchAPIs` marks the vendors named (two or more, set +up, each once) and clears every other; none clears all. `SetSearchAPI` +keeps the mark, and backup and sync carry it with the rest of the entry. A +mixed search spends every mixed API's quota, takes as long as the slowest, +and gives the model up to twice the pages (20 at most). On the CLI, `magpie search mix +,` and `magpie search mix off` set it, and `magpie search` lists +a mixed one as mix. Settings' page doesn't show or set it yet. + +Covered by `TestSearchAPIsMixedAskedTogether`, `TestSearchAPIsMixedOneDown`, +`TestSearchAPIsMixedAllDownAsksTheRest`, `TestSearchAPIsMixedCapped`, +`TestMixSearchAPIs` and `TestSearchCLIMix`. + ## A search API's keys A search API's `key` may hold several keys, separated by commas (#1477). diff --git a/internal/cli/search_cli.go b/internal/cli/search_cli.go index cb50a56f9..358866d5b 100644 --- a/internal/cli/search_cli.go +++ b/internal/cli/search_cli.go @@ -26,6 +26,9 @@ const searchUsage = `usage: magpie search off keep one, key and all, but never ask it magpie search on ask it again magpie search move put one at place n in the order they are asked + magpie search mix ,[,…] ask these together, at once, and give the model their + pages merged, a page found twice once (at most 12) + magpie search mix off ask them one at a time again, in order magpie search rm take one away magpie search count [] how many results a search is answered with when the client names no count (Claude Code's WebSearch, @@ -59,6 +62,10 @@ const searchUsage = `usage: about twice as much for the model to read. Whether an API charges more for more results is its own pricing's. + Two or more mixed (magpie search mix) are asked first, together: a search then spends + each one's quota, takes as long as the slowest, and gives the model up to twice the + results (20 at most). The others are asked, in order, only when none of the mixed ones finds anything. + e.g. magpie search add tavily tvly-… magpie search add searxng url=https://searx.example.com magpie search add you` @@ -88,6 +95,9 @@ func searchCmd(args []string) error { if a.Off { line += " " + amber.Render("off") } + if a.Mix { + line += " " + green.Render("mix") + } fmt.Println(line) if gateway.CanReadSearchQuota(a) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) @@ -169,6 +179,30 @@ func searchCmd(args []string) error { return nil case "count": return searchCountCmd(args[1:]) + case "mix": + if len(args) != 2 { + return fmt.Errorf("magpie search mix ,[,…] | off") + } + var vendors []string + if strings.ToLower(args[1]) != "off" { + for _, v := range strings.Split(args[1], ",") { + if v = strings.ToLower(strings.TrimSpace(v)); v != "" { + vendors = append(vendors, v) + } + } + if len(vendors) < 2 { + return fmt.Errorf("magpie search mix ,[,…]: name two or more") + } + } + if err := provider.MixSearchAPIs(vendors); err != nil { + return err + } + if len(vendors) == 0 { + fmt.Println(green.Render("✓"), "search APIs asked one at a time, in order") + } else { + fmt.Println(green.Render("✓"), strings.Join(vendors, ", "), muted.Render("asked together")) + } + return nil case "rm", "remove": if len(args) != 2 { return fmt.Errorf("magpie search rm ") @@ -179,7 +213,7 @@ func searchCmd(args []string) error { fmt.Println(green.Render("✓"), "removed") return nil } - return fmt.Errorf("magpie search [add|on|off|move|rm|count] (magpie search help)") + return fmt.Errorf("magpie search [add|on|off|move|mix|rm|count] (magpie search help)") } // searchCountCmd is magpie search count (#5545, mdwsk88): with no word it diff --git a/internal/cli/search_cli_test.go b/internal/cli/search_cli_test.go index 18b627337..08fcbb5e3 100644 --- a/internal/cli/search_cli_test.go +++ b/internal/cli/search_cli_test.go @@ -182,3 +182,44 @@ func TestSearchCLICount(t *testing.T) { t.Error("settings took a count of 21") } } + +// magpie search mix names two or more search APIs to ask together, and +// off puts them back in order (#2845). +func TestSearchCLIMix(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + for _, args := range [][]string{{"add", "brave", "b-1"}, {"add", "exa", "e-1"}, {"add", "you"}} { + if err := searchCmd(args); err != nil { + t.Fatalf("%v: %v", args, err) + } + } + for _, bad := range [][]string{{"mix"}, {"mix", "brave"}, {"mix", "brave,google"}, {"mix", "brave,brave"}} { + if err := searchCmd(bad); err == nil { + t.Errorf("%v taken", bad) + } + } + mixed := func() (out []string) { + for _, a := range provider.StoredSearchAPIs() { + if a.Mix { + out = append(out, a.Vendor) + } + } + return out + } + if err := searchCmd([]string{"mix", "You, Brave"}); err != nil { + t.Fatal(err) + } + if got := mixed(); !slices.Equal(got, []string{"brave", "you"}) { + t.Fatalf("mixed %v", got) + } + if err := searchCmd(nil); err != nil { + t.Fatal(err) + } + if err := searchCmd([]string{"mix", "off"}); err != nil { + t.Fatal(err) + } + if got := mixed(); len(got) != 0 { + t.Fatalf("after mix off %v", got) + } +} diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index 3fcf6c8b4..cfde1c786 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -11,8 +11,10 @@ import ( "net/http" "net/url" "regexp" + "slices" "strconv" "strings" + "sync" "time" "unicode/utf8" @@ -134,14 +136,27 @@ func SearcherUnused() string { return why } -// apiSearch asks the search APIs, in their order, until one answers. +// apiSearch asks the search APIs, in their order, until one answers. Two +// or more marked mix (SearchAPI.Mix, #2845) are asked first, together, +// and what they found is merged (askSearchAPIsTogether); the others are +// asked, in order, only when none of those found anything. func (s *Server) apiSearch(ctx context.Context, query string) (string, []Hit, error) { query, err := maskedQuery(ctx, query, nil) if err != nil { return "", nil, err } var errs []error - for _, a := range provider.SearchAPIs() { + apis := provider.SearchAPIs() + if mixed := slices.DeleteFunc(slices.Clone(apis), func(a provider.SearchAPI) bool { return !a.Mix }); len(mixed) > 1 { + pages, err := s.askSearchAPIsTogether(ctx, mixed, query) + if len(pages) > 0 { + said, hits := pagesSaid(pages) + return said, hits, nil + } + errs = append(errs, err) + apis = slices.DeleteFunc(apis, func(a provider.SearchAPI) bool { return a.Mix }) + } + for _, a := range apis { pages, err := s.askSearchAPIKeys(ctx, a, query) if err != nil { errs = append(errs, fmt.Errorf("%s: %w", a.Name(), err)) @@ -157,6 +172,78 @@ func (s *Server) apiSearch(ctx context.Context, query string) (string, []Hit, er return "", nil, errors.Join(errs...) } +// searchMixMost is the most pages a mixed search gives the model: two +// search APIs' worth of the count the search asks for (searchCount: the +// one it named, else the user's, 6 by default), never more than one +// search may name (searchHitsMost). +func searchMixMost(ctx context.Context) int { + return min(2*searchCount(ctx), searchHitsMost) +} + +// askSearchAPIsTogether asks each search API at once, each with its own +// keys and timeouts as when it is asked alone (askSearchAPIKeys), and +// merges what they found (mixedPages). One that fails or finds nothing +// leaves the others' pages; the error says what each of those said. +func (s *Server) askSearchAPIsTogether(ctx context.Context, apis []provider.SearchAPI, query string) ([]foundPage, error) { + found := make([][]foundPage, len(apis)) + errs := make([]error, len(apis)) + var wg sync.WaitGroup + for i, a := range apis { + wg.Add(1) + go func() { + defer wg.Done() + pages, err := s.askSearchAPIKeys(ctx, a, query) + switch { + case err != nil: + errs[i] = fmt.Errorf("%s: %w", a.Name(), err) + case len(pages) == 0: + errs[i] = fmt.Errorf("%s found nothing", a.Name()) + } + found[i] = pages + }() + } + wg.Wait() + return mixedPages(found, searchMixMost(ctx)), errors.Join(errs...) +} + +// mixedPages takes the search APIs' pages in turn, in the APIs' order: +// each one's first, then each one's second. A page an earlier one gave is +// left out (by pageKey), and there are at most most of them. +func mixedPages(found [][]foundPage, most int) []foundPage { + var out []foundPage + seen := map[string]bool{} + for rank := 0; len(out) < most; rank++ { + more := false + for _, pages := range found { + if rank >= len(pages) { + continue + } + more = true + if k := pageKey(pages[rank].URL); !seen[k] && len(out) < most { + seen[k] = true + out = append(out, pages[rank]) + } + } + if !more { + break + } + } + return out +} + +// pageKey is a page's address as two search APIs may write it apart: host +// in lower case, http and https alike, without its fragment or a closing +// slash. +func pageKey(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Host == "" { + return strings.TrimSpace(raw) + } + u.Scheme, u.Host, u.Fragment, u.RawFragment = "https", strings.ToLower(u.Host), "", "" + u.Path, u.RawPath = strings.TrimSuffix(u.Path, "/"), "" + return u.String() +} + // askSearchAPIKeys asks a search API with its keys, in searchKeyOrder: // on to the next while one is refused (out of credit, rate limited, // turned away; #1477), which then rests (searchRestFor). Anything else, such as diff --git a/internal/gateway/search_mix_test.go b/internal/gateway/search_mix_test.go new file mode 100644 index 000000000..a0ad487e1 --- /dev/null +++ b/internal/gateway/search_mix_test.go @@ -0,0 +1,247 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// mixAPIs is a fake of Tavily, Exa and Brave, each finding the pages set +// for it. The vendors in together each wait, a while at most, until all of +// them have been asked, so only APIs asked at once answer in time. +type mixAPIs struct { + *httptest.Server + mu sync.Mutex + asked []string + pages map[string][]string // vendor: the URLs of the pages it finds + down map[string]bool + together []string + arrived int + all chan struct{} +} + +func newMixAPIs(t *testing.T) *mixAPIs { + f := &mixAPIs{pages: map[string][]string{}, down: map[string]bool{}, all: make(chan struct{})} + f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + vendor, _, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") + f.mu.Lock() + f.asked = append(f.asked, vendor) + pages, down := f.pages[vendor], f.down[vendor] + wait := slices.Contains(f.together, vendor) + if wait { + if f.arrived++; f.arrived == len(f.together) { + close(f.all) + } + } + f.mu.Unlock() + if wait { + select { + case <-f.all: + case <-r.Context().Done(): + return + case <-time.After(5 * time.Second): + http.Error(w, `{"error":"asked alone"}`, http.StatusInternalServerError) + return + } + } + if down { + http.Error(w, `{"error":"down"}`, http.StatusInternalServerError) + return + } + var items []string + for i, u := range pages { + items = append(items, fmt.Sprintf(`{"title":"%s %d","url":%q,"content":"found","text":"found","description":"found"}`, vendor, i+1, u)) + } + list := "[" + strings.Join(items, ",") + "]" + w.Header().Set("Content-Type", "application/json") + if vendor == "brave" { + io.WriteString(w, `{"web":{"results":`+list+`}}`) + } else { + io.WriteString(w, `{"results":`+list+`}`) + } + })) + t.Cleanup(f.Close) + return f +} + +// set adds the vendors' search APIs at the fake, in that order. +func (f *mixAPIs) set(t *testing.T, vendors ...string) { + t.Helper() + keys := map[string]string{"tavily": "tvly-k", "exa": "exa-k", "brave": "brave-k"} + for _, v := range vendors { + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: v, Key: keys[v], URL: f.URL + "/" + v}); err != nil { + t.Fatal(err) + } + } +} + +func (f *mixAPIs) askedOf() []string { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.asked) +} + +func mixSet(t *testing.T, vendors ...string) { + t.Helper() + if err := provider.MixSearchAPIs(vendors); err != nil { + t.Fatal(err) + } +} + +func mixHitURLs(hits []Hit) []string { + var out []string + for _, h := range hits { + out = append(out, h.URL) + } + return out +} + +// Search APIs marked mix are asked at once (#2845). The model gets their +// pages in turn, in the APIs' order, a page two of them found once; one +// not mixed isn't asked while they find something. +func TestSearchAPIsMixedAskedTogether(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + f := newMixAPIs(t) + f.pages["tavily"] = []string{"https://a.example/1", "https://go.dev/dl/", "https://a.example/3"} + f.pages["exa"] = []string{"https://b.example/1", "https://GO.dev/dl#files", "https://b.example/3"} + f.pages["brave"] = []string{"https://c.example/1"} + f.together = []string{"tavily", "exa"} + f.set(t, "tavily", "exa", "brave") + mixSet(t, "exa", "tavily") + said, hits, err := New().apiSearch(context.Background(), "latest go") + if err != nil { + t.Fatal(err) + } + want := []string{"https://a.example/1", "https://b.example/1", "https://go.dev/dl/", "https://a.example/3", "https://b.example/3"} + if got := mixHitURLs(hits); !slices.Equal(got, want) { + t.Fatalf("pages %v, want %v\n%s", got, want, said) + } + if asked := f.askedOf(); len(asked) != 2 || slices.Contains(asked, "brave") { + t.Errorf("asked %v", asked) + } +} + +// One mixed API down leaves the other's pages, with no error. +func TestSearchAPIsMixedOneDown(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + f := newMixAPIs(t) + f.pages["tavily"] = []string{"https://a.example/1"} + f.pages["exa"] = []string{"https://b.example/1"} + f.down["tavily"] = true + f.set(t, "tavily", "exa") + mixSet(t, "tavily", "exa") + _, hits, err := New().apiSearch(context.Background(), "latest go") + if err != nil || !slices.Equal(mixHitURLs(hits), []string{"https://b.example/1"}) { + t.Fatalf("%v %v", mixHitURLs(hits), err) + } +} + +// With every mixed API down, the ones not mixed are asked, in order. +func TestSearchAPIsMixedAllDownAsksTheRest(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + f := newMixAPIs(t) + f.pages["brave"] = []string{"https://c.example/1"} + f.down["tavily"], f.down["exa"] = true, true + f.set(t, "tavily", "exa", "brave") + mixSet(t, "tavily", "exa") + _, hits, err := New().apiSearch(context.Background(), "latest go") + if err != nil || !slices.Equal(mixHitURLs(hits), []string{"https://c.example/1"}) { + t.Fatalf("%v %v", mixHitURLs(hits), err) + } + if asked := f.askedOf(); len(asked) != 3 || asked[2] != "brave" { + t.Errorf("asked %v", asked) + } +} + +// A mixed search gives the model two APIs' worth of the count it asks for +// at most, each API's first ones first: 12 by default, twice the count the +// user set (#5545) or the search named, and never more than one search may +// name (20). +func TestSearchAPIsMixedCapped(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + // the package's tests share one settings.json: the count is put back + was := settings.Load().SearchCount + t.Cleanup(func() { + s := settings.Load() + s.SearchCount = was + settings.Save(s) + }) + f := newMixAPIs(t) + for _, v := range []string{"tavily", "exa", "brave"} { + for i := range searchHitsMost { + f.pages[v] = append(f.pages[v], fmt.Sprintf("https://%s.example/%d", v, i+1)) + } + } + f.set(t, "tavily", "exa", "brave") + mixSet(t, "tavily", "exa", "brave") + for _, c := range []struct { + set, named, want int + }{{0, 0, 12}, {9, 0, 18}, {15, 0, 20}, {9, 3, 6}} { + s := settings.Load() + s.SearchCount = c.set + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + ctx := context.Background() + if c.named > 0 { + ctx = withSearchCount(ctx, c.named) + } + _, hits, err := New().apiSearch(ctx, "latest go") + if err != nil { + t.Fatal(err) + } + got := mixHitURLs(hits) + if len(got) != c.want || !slices.Equal(got[:3], []string{"https://tavily.example/1", "https://exa.example/1", "https://brave.example/1"}) { + t.Errorf("count set %d, named %d: %d pages, want %d: %v", c.set, c.named, len(got), c.want, got) + } + } +} + +// MixSearchAPIs takes two or more APIs set up, each named once, and a new +// key leaves the mark. A mixed API switched off isn't asked, and with one +// mixed left a search goes in order. None puts every one back. +func TestMixSearchAPIs(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + f := newMixAPIs(t) + f.pages["tavily"] = []string{"https://a.example/1"} + f.pages["exa"] = []string{"https://b.example/1"} + f.set(t, "tavily", "exa") + for _, bad := range [][]string{{"tavily"}, {"tavily", "tavily"}, {"tavily", "google"}} { + if err := provider.MixSearchAPIs(bad); err == nil { + t.Errorf("%v mixed", bad) + } + } + mixSet(t, "tavily", "exa") + // a new key, as Settings sends it, keeps the mark + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: "tvly-2", URL: f.URL + "/tavily"}); err != nil { + t.Fatal(err) + } + for _, a := range provider.StoredSearchAPIs() { + if !a.Mix { + t.Errorf("%s lost its mark", a.Vendor) + } + } + if err := provider.SwitchSearchAPI("exa", false); err != nil { + t.Fatal(err) + } + _, hits, err := New().apiSearch(context.Background(), "latest go") + if err != nil || !slices.Equal(mixHitURLs(hits), []string{"https://a.example/1"}) || slices.Contains(f.askedOf(), "exa") { + t.Fatalf("exa off: %v %v, asked %v", mixHitURLs(hits), err, f.askedOf()) + } + mixSet(t) + for _, a := range provider.StoredSearchAPIs() { + if a.Mix { + t.Errorf("%s still mixed", a.Vendor) + } + } +} diff --git a/internal/provider/search_api.go b/internal/provider/search_api.go index 15f778dbb..3cd3a918c 100644 --- a/internal/provider/search_api.go +++ b/internal/provider/search_api.go @@ -32,6 +32,12 @@ type SearchAPI struct { // on again (#2286): to try one API alone, or rest one whose credit is // nearly spent, without taking its key away. Off bool `json:"off,omitempty"` + // Mix asks it together with the other search APIs marked so, at once, + // and gives the model their pages merged, a page two of them found + // once (#2845): no one API was best on every kind of question, and + // their pages together found more than any alone. With fewer than two + // such APIs that can be asked, a search goes in order as before. + Mix bool `json:"mix,omitempty"` } // How a search picks among a search API's keys (SearchAPI.Pick). @@ -257,7 +263,7 @@ func StoredSearchAPIs() []SearchAPI { return load().Searches } // SetSearchAPI adds a search API, last, or changes the one of its vendor // where it is; a change with no key keeps the key it has, and one with no // Pick the pick it has ("turns" puts the default back). One switched off -// stays off. +// stays off, and one marked mix stays mixed. func SetSearchAPI(a SearchAPI) error { a.Vendor = strings.ToLower(strings.TrimSpace(a.Vendor)) a.Key, a.URL = strings.Join(a.Keys(), ","), strings.TrimSpace(a.URL) @@ -271,7 +277,7 @@ func SetSearchAPI(a SearchAPI) error { a.Key = f.Searches[i].Key } if i >= 0 { - a.Off = f.Searches[i].Off + a.Off, a.Mix = f.Searches[i].Off, f.Searches[i].Mix } switch { case pick == "turns": @@ -328,6 +334,31 @@ func SwitchSearchAPI(vendor string, on bool) error { return store(f) } +// MixSearchAPIs marks the vendors' search APIs to be asked together +// (SearchAPI.Mix, #2845), and every other one not: two or more, each set +// up and named once. None puts every one back to being asked in order. +func MixSearchAPIs(vendors []string) error { + if len(vendors) == 1 { + return fmt.Errorf("name two or more search APIs to ask together") + } + f, err := read() + if err != nil { + return err + } + for i, v := range vendors { + if !slices.ContainsFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == v }) { + return fmt.Errorf("no %s search API is set up", v) + } + if slices.Contains(vendors[:i], v) { + return fmt.Errorf("%s is named twice", v) + } + } + for i := range f.Searches { + f.Searches[i].Mix = slices.Contains(vendors, f.Searches[i].Vendor) + } + return store(f) +} + // ArrangeSearchAPIs puts the search APIs in the order of the vendors named // (#2286), the order they are tried in. One not named keeps its place // after them; a name of none set up is refused, so an order sent from a