Files
magpie/internal/provider/search_api.go
T
yetone a5d72a095b gateway, gui, cli: a search API's keys take turns, a refused one rests, and each Tavily key shows what it has used (SlouchyQuill)
SlouchyQuill on Discord asked for a Tavily key pool after
dsh-tavily-pool: several keys, each key's quota shown, keys rotated.
Before this, the comma-separated keys (#1477) always started from the
key that last answered, so one key took every search until it was
refused, a refused key kept no rest of its own, and nothing showed what
a key had left.

What changed:
- Turns (internal/gateway/search_keys.go). Searches take turns over the
  keys by default (round robin, a counter per vendor). pick=order (CLI)
  or In order (Settings) always starts from the first key; the pick is
  saved in SearchAPI.Pick.
- Rests. A refused key rests: 401/403 for 10m ("turned away"), 402 for
  1h ("out of credit"), 429 for its Retry-After held to 30s-10m (1m
  without one). 432/433 count as out of credit from Tavily only; from
  any other vendor they rest as a rate limit. A resting key is asked
  after the others, soonest back first, so failover is kept, and it
  wakes when it answers. Rests are keyed by a hash of the key.
- Quota (internal/gateway/search_quota.go). Each Tavily key's quota is
  read from GET /usage with that key. The fixture is the documented
  reply from docs.tavily.com. The key's own limit is used when it has
  one; otherwise its plan's plan_limit/plan_usage, which the account's
  keys share. A failed read, or a reply missing those fields, says
  unknown and why, never 0. A read is kept 2m unless asked fresh. A key
  found used up with no pay-as-you-go credit rests 1h; a later read
  with credit wakes it.
- Keys never appear in full. The vendor's error has the key masked
  (tvly-…abcd), and errors name "key N (tvly-…abcd)".
- GUI. Settings › Models › Web search adds a "Keys of <API>" row under
  an API with several keys or with Tavily's: In turn / In order, each
  key masked with what it has used and why it is asked last, and Check
  again. There is an API for it (POST /api/settings/search-quota), and
  13 strings in zh, zh-TW, ja and de.
- CLI. `magpie search` lists the pick and each Tavily key's quota, read
  fresh; `magpie search add … pick=turns|order`.
- Docs. gateway-routing.md has a new section "A search API's keys";
  both READMEs have a line on web search.

What was run:
- go test -tags nogui ./internal/gateway ./internal/provider
  ./internal/cli ./internal/gui: ok. After the last rebase, provider
  and cli again, and gateway -race -run Search.
- New tests: TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin,
  TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas and
  TestSearchKeyNeverInFull. Each guarantee was broken by hand and its
  tests went red:
  - turns pinned to the first key: RoundRobin and RefusedRests;
  - rests ignored: TestSearchAPIKeysTakeTurns, RefusedRests and
    TestSearchQuotas;
  - key masking removed: NeverInFull;
  - a failed read reported as known: TestSearchQuotas.
- gofmt -l; go vet -tags nogui for darwin, linux and windows on the
  four packages.
- GUI: search-keys.test.cjs covers en, zh, zh-TW, ja and de ×
  Chromium and WebKit × 1100 and 420px: 20/20. Without the new
  .search-keys .val wrap rule, de at 420px fails ("Erneut prüfen" went
  past the window's edge).
  - search-api, search-first, search-instead, search-mcp,
    searcher-pick, settings-search, provider-search, gui-de, gui-ja and
    i18n-keys: 56/56 in each engine.
  - Full suite in Chromium (concurrency 6, load ~40): 4498/4504. The
    files that failed (gateway-key-groups, rest-try-now,
    routing-wb-restricted, text-size, usage-sum-whole) were rerun
    alone. All pass except usage-sum-whole, which fails now and then
    on an origin/main worktree too under the same load (#1864, #2023;
    rest-try-now and routing-wb-restricted are #1905). None of them
    touch search.
- Real Tavily API with two invalid keys: /search returns 401
  {"detail":{"error":"Unauthorized: missing or invalid API key."}},
  which counts as a refusal. Both keys rest 10m as turned away, the
  error names them only masked, and both quotas read "unknown · 401".
  Checked through a test and through the nogui CLI binary in a sandbox
  HOME.

Not tried: a valid key's /usage against the real API. No Tavily key
was at hand, so the quota parsing is checked against the documented
bytes only.
2026-10-14 08:24:03 +08:00

265 lines
8.4 KiB
Go

package provider
// Search APIs answer a model's web search when no provider can (#419):
// Tavily, Brave Search, Exa, Firecrawl, You.com, a SearXNG of the user's. They are
// kept in providers.json beside the providers, their keys with theirs.
import (
"fmt"
"net/url"
"slices"
"strings"
)
// SearchAPI is a web search API the user gave magpie a key to.
type SearchAPI struct {
Vendor string `json:"vendor"` // one of SearchVendors
// Key is its key, or several separated by commas (Keys), each tried
// when the one before is refused (#1477).
Key string `json:"key,omitempty"`
// Pick is how a search picks among several keys: "" takes them in
// turn (SearchPickTurns), each search the next one; SearchPickOrder
// asks the first until it is refused, then the next (SlouchyQuill on
// Discord). Either way a key refused lately is asked last.
Pick string `json:"pick,omitempty"`
// URL is where it is: a SearXNG's own, or another address for one of
// the others (a Firecrawl run by the user); empty is the vendor's.
URL string `json:"url,omitempty"`
}
// How a search picks among a search API's keys (SearchAPI.Pick).
const (
SearchPickTurns = "" // in turn, each search the next key
SearchPickOrder = "order" // the first until it is refused
)
// SearchVendor is a search API magpie can ask.
type SearchVendor struct {
ID, Name string
Base string // its address, "" for one the user runs
KeysURL string // where its keys are made
// KeyOptional: it answers with no key too (a SearXNG; You.com's free
// search, YouFreeSearch)
KeyOptional bool
}
// YouFreeSearch is You.com's search that takes no key (#1626): 100
// searches a day for each address, then 429. With a key, You.com is
// asked at its Base, ydc-index.io, instead.
const YouFreeSearch = "https://api.you.com/v1/agents/search"
// SearchVendors are the search APIs magpie can ask, in the order offered.
var SearchVendors = []SearchVendor{
{ID: "tavily", Name: "Tavily", Base: "https://api.tavily.com", KeysURL: "https://app.tavily.com/home"},
{ID: "brave", Name: "Brave Search", Base: "https://api.search.brave.com", KeysURL: "https://api-dashboard.search.brave.com/app/keys"},
{ID: "exa", Name: "Exa", Base: "https://api.exa.ai", KeysURL: "https://dashboard.exa.ai/api-keys"},
{ID: "firecrawl", Name: "Firecrawl", Base: "https://api.firecrawl.dev", KeysURL: "https://www.firecrawl.dev/app/api-keys"},
{ID: "you", Name: "You.com", Base: "https://ydc-index.io", KeysURL: "https://you.com/platform", KeyOptional: true},
{ID: "searxng", Name: "SearXNG", KeyOptional: true},
}
// SearchVendorOf is the vendor by its id.
func SearchVendorOf(id string) (SearchVendor, bool) {
i := slices.IndexFunc(SearchVendors, func(v SearchVendor) bool { return v.ID == id })
if i < 0 {
return SearchVendor{}, false
}
return SearchVendors[i], true
}
// Keys are the keys in Key: one, or several the user gave separated by
// commas, spaces or lines, each once, in the order given.
func (a SearchAPI) Keys() []string {
var out []string
for _, k := range strings.FieldsFunc(a.Key, func(r rune) bool { return r == ',' || r == ';' || r == ' ' || r == '\t' || r == '\n' || r == '\r' }) {
if !slices.Contains(out, k) {
out = append(out, k)
}
}
return out
}
// MaskedKey is Key as shown: each of its keys masked (MaskSearchKey), so a
// list of them shows no more of any one than a single key does.
func (a SearchAPI) MaskedKey() string {
ks := a.Keys()
for i, k := range ks {
ks[i] = MaskSearchKey(k)
}
return strings.Join(ks, ", ")
}
// MaskSearchKey is one search API key as shown: as Mask, but a Tavily
// key keeps its whole "tvly-" tag (tvly-…abcd), which says what it is
// and nothing secret of it.
func MaskSearchKey(k string) string {
if strings.HasPrefix(k, "tvly-") && len(k) >= 16 {
return "tvly-…" + k[len(k)-4:]
}
return Mask(k)
}
// Name is the vendor's name.
func (a SearchAPI) Name() string {
if v, ok := SearchVendorOf(a.Vendor); ok {
return v.Name
}
return a.Vendor
}
// Base is the address it is asked at, without a slash at its end.
func (a SearchAPI) Base() string {
if a.URL != "" {
return strings.TrimRight(a.URL, "/")
}
v, _ := SearchVendorOf(a.Vendor)
return v.Base
}
// Ready is whether it can be asked: a vendor magpie knows, at an address,
// with a key where it needs one (a SearXNG, You.com, may not).
func (a SearchAPI) Ready() bool {
v, known := SearchVendorOf(a.Vendor)
return known && a.Base() != "" && (a.Key != "" || v.KeyOptional)
}
// check says what is wrong with a search API the user gives.
func (a SearchAPI) check() error {
v, ok := SearchVendorOf(a.Vendor)
if !ok {
var ids []string
for _, v := range SearchVendors {
ids = append(ids, v.ID)
}
return fmt.Errorf("no search API %q: one of %s", a.Vendor, strings.Join(ids, ", "))
}
if a.URL != "" {
u, err := url.Parse(a.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("%s: %q is not an http:// or https:// address", a.Name(), a.URL)
}
// the API's own paths go after it (/search), so it can't end in a
// query or a fragment
if u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return fmt.Errorf("%s: %q has a ?query or #fragment; give its base URL alone", a.Name(), a.URL)
}
}
if a.Pick != SearchPickTurns && a.Pick != SearchPickOrder {
return fmt.Errorf("%s: pick %q is not turns or order", a.Name(), a.Pick)
}
if a.Vendor == "searxng" && a.URL == "" {
return fmt.Errorf("SearXNG needs its address, as url=https://…")
}
if a.Key == "" && !v.KeyOptional {
return fmt.Errorf("%s needs its API key", a.Name())
}
return nil
}
// SearchAPIs are the search APIs that can be asked, in the order they are
// tried.
func SearchAPIs() []SearchAPI {
return slices.DeleteFunc(slices.Clone(load().Searches), func(a SearchAPI) bool { return !a.Ready() })
}
// StoredSearchAPIs are the search APIs as saved, keys and all.
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).
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)
pick := strings.ToLower(strings.TrimSpace(a.Pick))
f, err := read()
if err != nil {
return err
}
i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor })
if i >= 0 && a.Key == "" {
a.Key = f.Searches[i].Key
}
switch {
case pick == "turns":
a.Pick = SearchPickTurns
case pick == "" && i >= 0:
a.Pick = f.Searches[i].Pick
default:
a.Pick = pick
}
if err := a.check(); err != nil {
return err
}
if i >= 0 {
f.Searches[i] = a
} else {
f.Searches = append(f.Searches, a)
}
return store(f)
}
// RemoveSearchAPI takes the vendor's search API away.
func RemoveSearchAPI(vendor string) error {
f, err := read()
if err != nil {
return err
}
n := len(f.Searches)
f.Searches = slices.DeleteFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == vendor })
if len(f.Searches) == n {
return fmt.Errorf("no %s search API is set up", vendor)
}
return store(f)
}
// RestoreSearchAPIs puts search APIs from a backup in, each replacing the
// one of its vendor here; one that came without a key keeps the key here.
func RestoreSearchAPIs(as []SearchAPI) error {
if len(as) == 0 {
return nil
}
f, err := read()
if err != nil {
return err
}
for _, a := range as {
if _, ok := SearchVendorOf(a.Vendor); !ok {
continue
}
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 {
if a.Key == "" {
a.Key = f.Searches[i].Key
}
f.Searches[i] = a
} else {
f.Searches = append(f.Searches, a)
}
}
return store(f)
}
// MirrorSearchAPIs makes the search APIs exactly these, as sync brings
// them; one that came without a key keeps the key it has here.
func MirrorSearchAPIs(as []SearchAPI) error {
f, err := read()
if err != nil {
return err
}
out := []SearchAPI{}
for _, a := range as {
if _, ok := SearchVendorOf(a.Vendor); !ok {
continue
}
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 && a.Key == "" {
a.Key = f.Searches[i].Key
}
out = append(out, a)
}
if len(out) == 0 && len(f.Searches) == 0 {
return nil
}
f.Searches = out
return store(f)
}