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.
171 lines
5.8 KiB
Go
171 lines
5.8 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// The web search APIs, from the terminal: magpie search (#419).
|
|
|
|
const searchUsage = `usage:
|
|
magpie search the search APIs a model's web search goes to
|
|
magpie search add <api> <key> [url=<address>] [pick=turns|order]
|
|
add one, or give one a new key
|
|
(several keys as k1,k2: searches take them in turn,
|
|
or with pick=order the first until it is refused)
|
|
magpie search add searxng url=<address> [<key>]
|
|
magpie search add you [<key>] You.com: free with no key (100 searches a day)
|
|
magpie search rm <api> take one away
|
|
|
|
apis: tavily, brave, exa, firecrawl, you, searxng
|
|
|
|
url= is the API's base URL, for an endpoint of your own that answers as that API
|
|
does (e.g. url=https://search.example.com/tavily). Without it the vendor's own is
|
|
used; a new key alone keeps the url set before, and url= with nothing after it puts
|
|
the vendor's own back. The key is sent only to that url.
|
|
|
|
With several keys, a key the API refused lately (turned away, out of credit, rate
|
|
limited) rests and is asked only after the others: a rate limit for as long as the API
|
|
says (30s to 10m), a key turned away for 10 minutes, one out of credit for an hour.
|
|
For Tavily, magpie search shows what each key has used of its limit (GET /usage).
|
|
|
|
A client's web search (Claude Code's WebSearch, Codex's web_search) is done by the
|
|
model's provider when it can search, then by a provider that can (a Claude or ChatGPT
|
|
account, OpenAI, Anthropic, OpenRouter…), and then by these, in the order they were
|
|
added: what they find goes to the model as it is, and no model is asked to read it.
|
|
Without any of them, the client's search is left out.
|
|
|
|
e.g. magpie search add tavily tvly-…
|
|
magpie search add searxng url=https://searx.example.com
|
|
magpie search add you`
|
|
|
|
func searchCmd(args []string) error {
|
|
if len(args) == 0 {
|
|
as := provider.StoredSearchAPIs()
|
|
if len(as) == 0 {
|
|
fmt.Println(muted.Render(" no search API · magpie search add <tavily|brave|exa|firecrawl|you|searxng> <key>"))
|
|
return nil
|
|
}
|
|
for i, a := range as {
|
|
what := a.MaskedKey()
|
|
if a.Key == "" {
|
|
what = "no key"
|
|
}
|
|
if a.URL != "" {
|
|
what += " " + a.URL
|
|
}
|
|
if len(a.Keys()) > 1 {
|
|
what += map[bool]string{true: " in order", false: " in turn"}[a.Pick == provider.SearchPickOrder]
|
|
}
|
|
line := fmt.Sprintf(" %d. %s %s", i+1, pad(a.Name(), 14), muted.Render(what))
|
|
if !a.Ready() {
|
|
line += " " + faint.Render("needs its key")
|
|
}
|
|
fmt.Println(line)
|
|
if gateway.CanReadSearchQuota(a) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
for _, q := range gateway.SearchQuotas(ctx, a, true) {
|
|
fmt.Println(" " + pad(q.Key, 14) + " " + quotaLine(q))
|
|
}
|
|
cancel()
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
switch args[0] {
|
|
case "help", "-h", "--help":
|
|
fmt.Println(searchUsage)
|
|
return nil
|
|
case "add", "set":
|
|
if len(args) < 2 {
|
|
return fmt.Errorf("magpie search add <api> <key> [url=<address>]")
|
|
}
|
|
a := provider.SearchAPI{Vendor: strings.ToLower(args[1])}
|
|
// a new key alone keeps the address set before (#1580); url= with
|
|
// nothing after it puts the vendor's own back
|
|
urlGiven := false
|
|
for _, v := range args[2:] {
|
|
if u, ok := strings.CutPrefix(v, "url="); ok {
|
|
a.URL, urlGiven = u, true
|
|
} else if p, ok := strings.CutPrefix(v, "pick="); ok {
|
|
if a.Pick = p; p == "" {
|
|
a.Pick = "turns"
|
|
}
|
|
} else if a.Key == "" {
|
|
a.Key = v
|
|
} else {
|
|
return fmt.Errorf("magpie search add <api> <key> [url=<address>] [pick=turns|order]")
|
|
}
|
|
}
|
|
if i := slices.IndexFunc(provider.StoredSearchAPIs(), func(x provider.SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 && !urlGiven {
|
|
a.URL = provider.StoredSearchAPIs()[i].URL
|
|
}
|
|
if err := provider.SetSearchAPI(a); err != nil {
|
|
return err
|
|
}
|
|
as := provider.StoredSearchAPIs()
|
|
i := slices.IndexFunc(as, func(x provider.SearchAPI) bool { return x.Vendor == a.Vendor })
|
|
fmt.Println(green.Render("✓"), as[i].Name(), muted.Render(fmt.Sprintf("search API %d of %d", i+1, len(as))))
|
|
return nil
|
|
case "rm", "remove":
|
|
if len(args) != 2 {
|
|
return fmt.Errorf("magpie search rm <api>")
|
|
}
|
|
if err := provider.RemoveSearchAPI(strings.ToLower(args[1])); err != nil {
|
|
return err
|
|
}
|
|
fmt.Println(green.Render("✓"), "removed")
|
|
return nil
|
|
}
|
|
return fmt.Errorf("magpie search [add|rm] (magpie search help)")
|
|
}
|
|
|
|
// quotaLine is what one key has used of its limit, as magpie search lists
|
|
// it: unknown, with why, when it couldn't be read, and never 0.
|
|
func quotaLine(q gateway.SearchKeyQuota) string {
|
|
var line string
|
|
switch {
|
|
case !q.Known:
|
|
line = amber.Render("unknown") + muted.Render(" · "+q.Err)
|
|
case q.Unlimited:
|
|
line = fmt.Sprintf("%s used · no limit", thousands(q.Used))
|
|
default:
|
|
line = fmt.Sprintf("%s / %s used", thousands(q.Used), thousands(q.Limit))
|
|
if q.Of == "plan" && q.Plan != "" {
|
|
line += muted.Render(" (" + q.Plan + " plan)")
|
|
} else if q.Of == "plan" {
|
|
line += muted.Render(" (plan)")
|
|
}
|
|
if q.PaygoLeft > 0 {
|
|
line += muted.Render(fmt.Sprintf(" · %s pay-as-you-go left", thousands(q.PaygoLeft)))
|
|
}
|
|
if q.UsedUp {
|
|
line += " " + amber.Render("used up")
|
|
}
|
|
}
|
|
if q.Resting != "" {
|
|
line += faint.Render(fmt.Sprintf(" · %s, asked last until %s", q.Resting, q.RestUntil.Local().Format("15:04")))
|
|
}
|
|
return line
|
|
}
|
|
|
|
// thousands is n with its thousands split by commas.
|
|
func thousands(n int64) string {
|
|
s := fmt.Sprint(n)
|
|
neg := strings.HasPrefix(s, "-")
|
|
s = strings.TrimPrefix(s, "-")
|
|
for i := len(s) - 3; i > 0; i -= 3 {
|
|
s = s[:i] + "," + s[i:]
|
|
}
|
|
if neg {
|
|
s = "-" + s
|
|
}
|
|
return s
|
|
}
|