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.
This commit is contained in:
@@ -249,6 +249,7 @@ Find them under Plugins › Discover › Gateway middleware. See [Gateway middle
|
||||
### Also
|
||||
|
||||
- **Library**: write instructions, MCP servers and skills once; magpie writes them into each agent's files in its format, and removes only what it wrote.
|
||||
- **Web search for any model**: a model that can't search gets magpie's search: a provider that can, or search APIs (Tavily, Brave, Exa, Firecrawl, You.com, SearXNG). An API can hold several keys: searches take turns over them (or use them in order with `pick=order`), a key refused lately is asked last, and Tavily keys show what each has used of its limit, in Settings and in `magpie search`.
|
||||
- **Images and video**: an image tool for any agent over MCP, with the model you choose, and videos with a Grok subscription.
|
||||
- **Agents kept current**: the Agents page shows each CLI's version, updates it the way it was installed, and gives the commands for the ones you don't have.
|
||||
- **WSL**: on Windows, agents inside WSL distros are wired too, and their sessions counted.
|
||||
|
||||
@@ -249,6 +249,7 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
|
||||
### 还有
|
||||
|
||||
- **资料库**:指令、MCP 服务器和技能只写一次,magpie 按每个 Agent 的格式写进它的文件,删除时只删自己写的部分。
|
||||
- **任何模型都能联网搜索**:不能搜索的模型由 magpie 代为搜索,用能搜索的 provider 或搜索 API(Tavily、Brave、Exa、Firecrawl、You.com、SearXNG)。一个 API 可以填多个密钥:搜索默认轮流使用(`pick=order` 则按顺序),最近被拒的密钥最后才用;Tavily 的每个密钥用了多少额度,在设置页和 `magpie search` 里都能看到。
|
||||
- **图片和视频**:通过 MCP 给任何 Agent 一个生图工具,用你选的模型;有 Grok 订阅还能生成视频。
|
||||
- **Agent 保持最新**:Agents 页显示每个 CLI 的版本,按当初的安装方式更新,没装的也给出安装命令。
|
||||
- **WSL**:在 Windows 上,WSL 发行版里的 Agent 一样能配置,会话也一样统计。
|
||||
|
||||
@@ -366,6 +366,48 @@ Covered by `TestSearchAPIAtItsOwnBaseURL`, `TestSearchKeyStaysAtItsBaseURL`,
|
||||
`TestSearchAPIBaseURLFromSettings`, `TestSearchCLI` and
|
||||
`search-api.test.cjs`.
|
||||
|
||||
## A search API's keys
|
||||
|
||||
A search API's `key` may hold several keys, separated by commas (#1477).
|
||||
`askSearchAPIKeys` asks them in the order `searchKeyOrder` gives
|
||||
([`search_keys.go`](../../internal/gateway/search_keys.go)), each with a
|
||||
quarter of the search's time. By default they take turns (SlouchyQuill on
|
||||
Discord, after dsh-tavily-pool): a counter per vendor moves the first key
|
||||
asked on by one each search. `pick` `order` (`provider.SearchPickOrder`,
|
||||
`magpie search add … pick=order`, In order in Settings) always starts from
|
||||
the first. Only a refusal (`searchRefused`: 401, 402, 403, 429, 432, 433)
|
||||
goes on to the next key; any other error ends the search there.
|
||||
|
||||
A refused key rests (`searchRestFor`): 401 and 403 ten minutes ("turned
|
||||
away"), 402 an hour ("out of credit"), a rate limit its `Retry-After` held
|
||||
to 30 seconds through 10 minutes (a minute without one). 432 and 433 are
|
||||
Tavily's plan and pay-as-you-go limits, out of credit from Tavily only; from
|
||||
any other vendor they rest as a rate limit. A resting key is not dropped:
|
||||
it is asked after every key that isn't, the one back soonest first, so a
|
||||
search still has every key to fall back on. A key that answers wakes.
|
||||
Rests are held by vendor and a hash of the key (`searchKeyID`), never the
|
||||
key itself, and the vendor's error has the key masked
|
||||
(`provider.MaskSearchKey`, `tvly-…abcd`) before it is logged or returned.
|
||||
|
||||
What each Tavily key has used is read from `GET /usage` with that key
|
||||
([`search_quota.go`](../../internal/gateway/search_quota.go),
|
||||
`readTavilyUsage`): the key's own `limit` when it has one, else its account
|
||||
plan's `plan_limit` and `plan_usage`, shared by the account's keys (a free
|
||||
account's keys have `limit` null); both null is no limit. A read that fails
|
||||
or a reply missing those fields is unknown, with why, never 0 used. A read
|
||||
is kept two minutes (Tavily allows /usage 10 times in 10 minutes) unless
|
||||
asked fresh. A key at its limit with no pay-as-you-go credit left rests an
|
||||
hour as "used up"; a later read that finds credit wakes a key resting for
|
||||
that or for being out of credit. Settings › Models › Web search shows a row
|
||||
of the keys under an API with several or with Tavily's (In turn / In order,
|
||||
each key masked with what it has used, Check again), and `magpie search`
|
||||
lists the same, read fresh.
|
||||
|
||||
Covered by `TestReadTavilyUsage`, `TestSearchKeysTakeTurnsRoundRobin`,
|
||||
`TestSearchKeyRefusedRests`, `TestSearchRestFor`, `TestSearchQuotas`,
|
||||
`TestSearchKeyNeverInFull`, `TestSearchAPIKeysTakeTurns` and
|
||||
`search-keys.test.cjs`.
|
||||
|
||||
## Web search as an MCP server
|
||||
|
||||
`SearchMCPPath`, `/mcp/magpie/web-search`, serves the same `webSearch` a
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -12,8 +15,10 @@ import (
|
||||
|
||||
const searchUsage = `usage:
|
||||
magpie search the search APIs a model's web search goes to
|
||||
magpie search add <api> <key> [url=<address>] add one, or give one a new key
|
||||
(several keys as k1,k2: the next is tried when one is refused)
|
||||
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
|
||||
@@ -25,6 +30,11 @@ const searchUsage = `usage:
|
||||
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
|
||||
@@ -50,11 +60,21 @@ func searchCmd(args []string) error {
|
||||
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
|
||||
}
|
||||
@@ -73,10 +93,14 @@ func searchCmd(args []string) error {
|
||||
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>]")
|
||||
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 {
|
||||
@@ -101,3 +125,46 @@ func searchCmd(args []string) error {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -118,42 +118,37 @@ func (s *Server) apiSearch(ctx context.Context, query string) (string, []Hit, er
|
||||
return "", nil, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// searchKeyAt is, by vendor, the key of its several (SearchAPI.Keys) that
|
||||
// last answered, so each search doesn't first spend a request on one
|
||||
// that is out of credit.
|
||||
var searchKeyAt sync.Map
|
||||
|
||||
// askSearchAPIKeys asks a search API with its keys: from the one that last
|
||||
// answered, on to the next while one is refused (out of credit, rate
|
||||
// limited, turned away; #1477). Anything else, such as no answer in time,
|
||||
// isn't about the key, and the next isn't tried.
|
||||
// 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
|
||||
// no answer in time, isn't about the key, and the next isn't tried.
|
||||
func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, query string) ([]foundPage, error) {
|
||||
keys := a.Keys()
|
||||
if len(keys) == 0 {
|
||||
keys = []string{""}
|
||||
}
|
||||
start := 0
|
||||
if v, ok := searchKeyAt.Load(a.Vendor); ok {
|
||||
start = v.(int) % len(keys)
|
||||
}
|
||||
var errs []error
|
||||
for n := range keys {
|
||||
i := (start + n) % len(keys)
|
||||
for _, i := range searchKeyOrder(a, keys, time.Now()) {
|
||||
one := a
|
||||
one.Key = keys[i]
|
||||
ctx, cancel := context.WithTimeout(ctx, searchTimeout/4)
|
||||
pages, err := s.askSearchAPI(ctx, one, query)
|
||||
cancel()
|
||||
if err == nil {
|
||||
searchKeyAt.Store(a.Vendor, i)
|
||||
wakeSearchKey(a.Vendor, keys[i])
|
||||
return pages, nil
|
||||
}
|
||||
var r searchRefused
|
||||
refused := errors.As(err, &r)
|
||||
if refused && keys[i] != "" {
|
||||
d, why := searchRestFor(a.Vendor, r.status, r.retryAfter, time.Now())
|
||||
restSearchKey(a.Vendor, keys[i], d, why, time.Now())
|
||||
}
|
||||
if len(keys) > 1 {
|
||||
err = fmt.Errorf("key %d: %w", i+1, err)
|
||||
err = fmt.Errorf("%s: %w", keyLabel(i, keys[i]), err)
|
||||
}
|
||||
errs = append(errs, err)
|
||||
var r searchRefused
|
||||
if !errors.As(err, &r) {
|
||||
if !refused {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -164,8 +159,9 @@ func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, que
|
||||
// by its status: 401/403 turned away, 402/432/433 out of credit (Tavily's
|
||||
// plan and pay-as-you-go limits), 429 rate limited.
|
||||
type searchRefused struct {
|
||||
status int
|
||||
msg string
|
||||
status int
|
||||
msg string
|
||||
retryAfter string // its Retry-After, "" when it said none
|
||||
}
|
||||
|
||||
func (e searchRefused) Error() string { return e.msg }
|
||||
@@ -291,8 +287,13 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s
|
||||
msg = e.Message
|
||||
}
|
||||
}
|
||||
// an API that says the key back in its error doesn't get it into
|
||||
// magpie's logs or the model's turn
|
||||
if a.Key != "" {
|
||||
msg = strings.ReplaceAll(msg, a.Key, provider.MaskSearchKey(a.Key))
|
||||
}
|
||||
if keyRefusal(res.StatusCode) {
|
||||
return nil, searchRefused{res.StatusCode, msg}
|
||||
return nil, searchRefused{res.StatusCode, msg, res.Header.Get("Retry-After")}
|
||||
}
|
||||
return nil, errors.New(msg)
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
)
|
||||
|
||||
// A search API given several keys (#1477) goes on to the next when one is
|
||||
// out of credit (Tavily's 432), and starts the next search from the one
|
||||
// that answered. A failure that isn't about the key (a 500) doesn't spend
|
||||
// out of credit (Tavily's 432), and the next search doesn't start from the
|
||||
// keys refused, which rest (search_pool_test.go). A failure that isn't about the key (a 500) doesn't spend
|
||||
// the other keys.
|
||||
func TestSearchAPIKeysTakeTurns(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
@@ -55,7 +55,7 @@ func TestSearchAPIKeysTakeTurns(t *testing.T) {
|
||||
}
|
||||
took := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(asked) }
|
||||
|
||||
searchKeyAt.Delete("tavily")
|
||||
forgetSearchKeys()
|
||||
if said, err := search("tvly-spent, tvly-bad\ntvly-good"); err != nil || !strings.Contains(said, "go1.27.1") {
|
||||
t.Fatalf("spent, bad, good: %q, %v", said, err)
|
||||
}
|
||||
@@ -66,10 +66,10 @@ func TestSearchAPIKeysTakeTurns(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := took(); !slices.Equal(got, []string{"tvly-good"}) {
|
||||
t.Errorf("the next search asked with %v, want the key that answered first", got)
|
||||
t.Errorf("the next search asked with %v, want the key that answered, the others resting", got)
|
||||
}
|
||||
|
||||
searchKeyAt.Delete("tavily")
|
||||
forgetSearchKeys()
|
||||
if _, err := search("tvly-down,tvly-good"); err == nil {
|
||||
t.Error("a 500 on the first key went on to the next")
|
||||
}
|
||||
@@ -77,9 +77,9 @@ func TestSearchAPIKeysTakeTurns(t *testing.T) {
|
||||
t.Errorf("asked with %v after a 500, want the first key alone", got)
|
||||
}
|
||||
|
||||
searchKeyAt.Delete("tavily")
|
||||
forgetSearchKeys()
|
||||
_, err := search("tvly-spent,tvly-bad")
|
||||
if err == nil || !strings.Contains(err.Error(), "key 1:") || !strings.Contains(err.Error(), "usage limit") || !strings.Contains(err.Error(), "key 2:") {
|
||||
if err == nil || !strings.Contains(err.Error(), "key 1 (") || !strings.Contains(err.Error(), "usage limit") || !strings.Contains(err.Error(), "key 2 (") {
|
||||
t.Errorf("every key refused: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A search API given several keys (#1477) spreads its searches over them
|
||||
// (SlouchyQuill on Discord, after dsh-tavily-pool): each search starts
|
||||
// from the next key, or from the first when the API is set to use them in
|
||||
// order (provider.SearchPickOrder). A key the API refused lately, or one a
|
||||
// quota read found used up, rests: it is asked only after every key that
|
||||
// isn't resting, the one whose rest ends first before the others, so a
|
||||
// search still has every key to fall back on.
|
||||
|
||||
// keyRest is why a key rests, and until when.
|
||||
type keyRest struct {
|
||||
Until time.Time
|
||||
Why string // "turned away", "out of credit", "rate limited", "used up"
|
||||
}
|
||||
|
||||
var (
|
||||
// searchRests is, by searchKeyID, the keyRest of each key resting
|
||||
searchRests sync.Map
|
||||
// searchTurns is, by vendor, how many searches have taken a turn: the
|
||||
// key the next one starts from
|
||||
searchTurns sync.Map
|
||||
)
|
||||
|
||||
// searchKeyID is how a key is known here: its vendor and a hash, so no
|
||||
// map, log or dump holds the key itself.
|
||||
func searchKeyID(vendor, key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return vendor + " " + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
// The rests a refusal earns. A rate limit says when to come back
|
||||
// (Retry-After), held between its bounds; a key turned away (401/403) may
|
||||
// be fixed by the user, so it is tried again in a few minutes; one out of
|
||||
// credit gets its credit back no sooner than a top-up, so it rests longer.
|
||||
const (
|
||||
rateLimitRest = time.Minute
|
||||
rateLimitRestMin = 30 * time.Second
|
||||
rateLimitRestMax = 10 * time.Minute
|
||||
turnedAwayRest = 10 * time.Minute
|
||||
outOfCreditRest = time.Hour
|
||||
)
|
||||
|
||||
// searchRestFor is how long a key a search API refused with this status rests,
|
||||
// and why. 432 and 433 are Tavily's own (its plan's and its pay-as-you-go
|
||||
// limit), out of credit there; from any other API they are only a refusal,
|
||||
// and rest as a rate limit does.
|
||||
func searchRestFor(vendor string, status int, retryAfter string, now time.Time) (time.Duration, string) {
|
||||
switch {
|
||||
case status == 401 || status == 403:
|
||||
return turnedAwayRest, "turned away"
|
||||
case status == 402, vendor == "tavily" && (status == 432 || status == 433):
|
||||
return outOfCreditRest, "out of credit"
|
||||
}
|
||||
d := rateLimitRest
|
||||
if s, err := strconv.Atoi(retryAfter); err == nil && s >= 0 {
|
||||
d = time.Duration(s) * time.Second
|
||||
} else if at, err := http.ParseTime(retryAfter); err == nil {
|
||||
d = at.Sub(now)
|
||||
}
|
||||
return min(max(d, rateLimitRestMin), rateLimitRestMax), "rate limited"
|
||||
}
|
||||
|
||||
// restSearchKey sets a key resting for d; a rest it has that ends later
|
||||
// is kept.
|
||||
func restSearchKey(vendor, key string, d time.Duration, why string, now time.Time) {
|
||||
r := keyRest{Until: now.Add(d), Why: why}
|
||||
if was, ok := searchKeyRest(vendor, key, now); ok && was.Until.After(r.Until) {
|
||||
return
|
||||
}
|
||||
searchRests.Store(searchKeyID(vendor, key), r)
|
||||
}
|
||||
|
||||
// wakeSearchKey ends a key's rest: it answered, or a quota read found it
|
||||
// has credit.
|
||||
func wakeSearchKey(vendor, key string) { searchRests.Delete(searchKeyID(vendor, key)) }
|
||||
|
||||
// searchKeyRest is the rest a key is in now, if it is.
|
||||
func searchKeyRest(vendor, key string, now time.Time) (keyRest, bool) {
|
||||
v, ok := searchRests.Load(searchKeyID(vendor, key))
|
||||
if !ok {
|
||||
return keyRest{}, false
|
||||
}
|
||||
r := v.(keyRest)
|
||||
if !now.Before(r.Until) {
|
||||
return keyRest{}, false
|
||||
}
|
||||
return r, true
|
||||
}
|
||||
|
||||
// searchKeyOrder is the order a search asks a's keys in, by their index:
|
||||
// from the key whose turn it is (the first, for SearchPickOrder), each
|
||||
// key resting put after those that aren't, the soonest awake first.
|
||||
// Taking turns, each call moves the next search on by one.
|
||||
func searchKeyOrder(a provider.SearchAPI, keys []string, now time.Time) []int {
|
||||
n := len(keys)
|
||||
start := 0
|
||||
if a.Pick != provider.SearchPickOrder && n > 1 {
|
||||
v, _ := searchTurns.LoadOrStore(a.Vendor, new(atomic.Uint64))
|
||||
start = int((v.(*atomic.Uint64).Add(1) - 1) % uint64(n))
|
||||
}
|
||||
order := make([]int, 0, n)
|
||||
var resting []int
|
||||
until := map[int]time.Time{}
|
||||
for k := range n {
|
||||
i := (start + k) % n
|
||||
if r, ok := searchKeyRest(a.Vendor, keys[i], now); ok {
|
||||
resting, until[i] = append(resting, i), r.Until
|
||||
continue
|
||||
}
|
||||
order = append(order, i)
|
||||
}
|
||||
slices.SortStableFunc(resting, func(x, y int) int { return until[x].Compare(until[y]) })
|
||||
return append(order, resting...)
|
||||
}
|
||||
|
||||
// forgetSearchKeys forgets every rest and turn: a test's fresh start.
|
||||
func forgetSearchKeys() {
|
||||
searchRests.Clear()
|
||||
searchTurns.Clear()
|
||||
}
|
||||
|
||||
// keyLabel is how an error names one of several keys: its place in the
|
||||
// list and the key masked.
|
||||
func keyLabel(i int, key string) string {
|
||||
return "key " + strconv.Itoa(i+1) + " (" + cmp.Or(provider.MaskSearchKey(key), "none") + ")"
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// tavilyUsageDoc is GET /usage's 200 reply as Tavily's API reference
|
||||
// (docs.tavily.com/documentation/api-reference/endpoint/usage) gives it.
|
||||
const tavilyUsageDoc = `{
|
||||
"key": {
|
||||
"usage": 150,
|
||||
"limit": 1000,
|
||||
"search_usage": 100,
|
||||
"extract_usage": 25,
|
||||
"crawl_usage": 15,
|
||||
"map_usage": 7,
|
||||
"research_usage": 3
|
||||
},
|
||||
"account": {
|
||||
"current_plan": "Bootstrap",
|
||||
"plan_usage": 500,
|
||||
"plan_limit": 15000,
|
||||
"paygo_usage": 25,
|
||||
"paygo_limit": 100,
|
||||
"search_usage": 350,
|
||||
"extract_usage": 75,
|
||||
"crawl_usage": 50,
|
||||
"map_usage": 15,
|
||||
"research_usage": 10
|
||||
}
|
||||
}`
|
||||
|
||||
// tavilyUnauthorized is Tavily's 401, as its real API answered an invalid
|
||||
// key at /search and /usage on 2026-10-14.
|
||||
const tavilyUnauthorized = `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`
|
||||
|
||||
// A Tavily /usage reply is read into what the key has used of its limit:
|
||||
// the key's own limit when it has one; else, as a free account's key has
|
||||
// none (key.limit null), its plan's, with the plan's usage; with neither,
|
||||
// no limit. A reply that leaves out what it takes is unknown, never 0.
|
||||
func TestReadTavilyUsage(t *testing.T) {
|
||||
q, err := readTavilyUsage([]byte(tavilyUsageDoc))
|
||||
if err != nil || !q.Known || q.Used != 150 || q.Limit != 1000 || q.Of != "key" || q.Plan != "Bootstrap" || q.PaygoLeft != 75 || q.UsedUp {
|
||||
t.Errorf("the documented reply: %+v, %v", q, err)
|
||||
}
|
||||
free := strings.NewReplacer(`"limit": 1000`, `"limit": null`, `"plan_limit": 15000`, `"plan_limit": 1000`,
|
||||
`"paygo_usage": 25`, `"paygo_usage": 0`, `"paygo_limit": 100`, `"paygo_limit": null`, `"Bootstrap"`, `"Researcher"`).Replace(tavilyUsageDoc)
|
||||
if q, err := readTavilyUsage([]byte(free)); err != nil || !q.Known || q.Used != 500 || q.Limit != 1000 || q.Of != "plan" || q.Plan != "Researcher" || q.UsedUp {
|
||||
t.Errorf("a free account's key, its limit the plan's: %+v, %v", q, err)
|
||||
}
|
||||
spent := strings.Replace(free, `"plan_usage": 500`, `"plan_usage": 1000`, 1)
|
||||
if q, _ := readTavilyUsage([]byte(spent)); !q.Known || !q.UsedUp {
|
||||
t.Errorf("a plan used up with no pay-as-you-go: %+v", q)
|
||||
}
|
||||
paygo := strings.NewReplacer(`"plan_usage": 500`, `"plan_usage": 1000`, `"paygo_limit": null`, `"paygo_limit": 100`).Replace(free)
|
||||
if q, _ := readTavilyUsage([]byte(paygo)); !q.Known || q.UsedUp || q.PaygoLeft != 100 {
|
||||
t.Errorf("a plan used up with pay-as-you-go left is not used up: %+v", q)
|
||||
}
|
||||
keySpent := strings.Replace(tavilyUsageDoc, `"usage": 150`, `"usage": 1000`, 1)
|
||||
if q, _ := readTavilyUsage([]byte(keySpent)); !q.UsedUp {
|
||||
t.Errorf("a key at its own limit: %+v", q)
|
||||
}
|
||||
unlimited := strings.NewReplacer(`"limit": 1000`, `"limit": null`, `"plan_limit": 15000`, `"plan_limit": null`).Replace(tavilyUsageDoc)
|
||||
if q, err := readTavilyUsage([]byte(unlimited)); err != nil || !q.Known || !q.Unlimited || q.Used != 150 || q.UsedUp {
|
||||
t.Errorf("no limit anywhere: %+v, %v", q, err)
|
||||
}
|
||||
for name, b := range map[string]string{
|
||||
"key.limit left out": strings.Replace(tavilyUsageDoc, `"limit": 1000,`, ``, 1),
|
||||
"plan_limit left out": strings.NewReplacer(`"limit": 1000`, `"limit": null`, `"plan_limit": 15000,`, ``).Replace(tavilyUsageDoc),
|
||||
"key.usage null": strings.Replace(tavilyUsageDoc, `"usage": 150`, `"usage": null`, 1),
|
||||
"no key": `{"account":{"plan_usage":1,"plan_limit":2}}`,
|
||||
"a string limit": strings.Replace(tavilyUsageDoc, `"limit": 1000`, `"limit": "1000"`, 1),
|
||||
"the 401's body": tavilyUnauthorized,
|
||||
"not JSON": `<html>502 Bad Gateway</html>`,
|
||||
"empty": ``,
|
||||
"truncated": tavilyUsageDoc[:80],
|
||||
} {
|
||||
if q, err := readTavilyUsage([]byte(b)); err == nil || q.Known {
|
||||
t.Errorf("%s: read as %+v, want unknown", name, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// keyedTavily is a fake Tavily that answers each key as answers says
|
||||
// ("ok", or a status), and records the keys it was asked with.
|
||||
type keyedTavily struct {
|
||||
*httptest.Server
|
||||
mu sync.Mutex
|
||||
asked []string
|
||||
answers map[string]int
|
||||
usage map[string]string // /usage's reply by key; none is a 401
|
||||
}
|
||||
|
||||
func newKeyedTavily(t *testing.T, answers map[string]int) *keyedTavily {
|
||||
f := &keyedTavily{answers: answers, usage: map[string]string{}}
|
||||
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/usage" {
|
||||
f.mu.Lock()
|
||||
b, ok := f.usage[key]
|
||||
f.mu.Unlock()
|
||||
if !ok {
|
||||
// as an API that says the key back would
|
||||
w.WriteHeader(401)
|
||||
fmt.Fprintf(w, `{"detail":{"error":"Unauthorized: invalid API key %s"}}`, key)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, b)
|
||||
return
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.asked = append(f.asked, key)
|
||||
status := f.answers[key]
|
||||
f.mu.Unlock()
|
||||
switch status {
|
||||
case 0, 200:
|
||||
io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1 from `+key+`","score":0.9}]}`)
|
||||
case 401:
|
||||
w.WriteHeader(401)
|
||||
fmt.Fprintf(w, `{"detail":{"error":"Unauthorized: missing or invalid API key %s."}}`, key)
|
||||
case 429:
|
||||
w.Header().Set("Retry-After", "120")
|
||||
w.WriteHeader(429)
|
||||
io.WriteString(w, `{"detail":{"error":"Too many requests"}}`)
|
||||
default:
|
||||
w.WriteHeader(status)
|
||||
io.WriteString(w, `{"detail":{"error":"This request exceeds your plan's set usage limit."}}`)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(f.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *keyedTavily) took() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := f.asked
|
||||
f.asked = nil
|
||||
return out
|
||||
}
|
||||
|
||||
func setTavily(t *testing.T, url, keys, pick string) provider.SearchAPI {
|
||||
t.Helper()
|
||||
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: keys, URL: url, Pick: pick}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return provider.StoredSearchAPIs()[0]
|
||||
}
|
||||
|
||||
// Several keys take turns: each search starts from the next, so the
|
||||
// searches are spread over them; set to "order", every search asks the
|
||||
// first.
|
||||
func TestSearchKeysTakeTurnsRoundRobin(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
forgetSearchKeys()
|
||||
t.Cleanup(forgetSearchKeys)
|
||||
f := newKeyedTavily(t, map[string]int{})
|
||||
setTavily(t, f.URL, "tvly-a,tvly-b,tvly-c", "")
|
||||
s := New()
|
||||
var got []string
|
||||
for range 7 {
|
||||
if _, _, err := s.apiSearch(context.Background(), "latest go"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, f.took()...)
|
||||
}
|
||||
if want := []string{"tvly-a", "tvly-b", "tvly-c", "tvly-a", "tvly-b", "tvly-c", "tvly-a"}; !slices.Equal(got, want) {
|
||||
t.Errorf("in turn: asked %v, want %v", got, want)
|
||||
}
|
||||
|
||||
setTavily(t, f.URL, "", "order")
|
||||
got = nil
|
||||
for range 3 {
|
||||
if _, _, err := s.apiSearch(context.Background(), "latest go"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, f.took()...)
|
||||
}
|
||||
if want := []string{"tvly-a", "tvly-a", "tvly-a"}; !slices.Equal(got, want) {
|
||||
t.Errorf("in order: asked %v, want %v", got, want)
|
||||
}
|
||||
if a := setTavily(t, f.URL, "tvly-a,tvly-b", ""); a.Pick != provider.SearchPickOrder {
|
||||
t.Errorf("a new key alone changed the pick to %q", a.Pick)
|
||||
}
|
||||
if a := setTavily(t, f.URL, "", "turns"); a.Pick != provider.SearchPickTurns {
|
||||
t.Errorf("pick=turns left %q", a.Pick)
|
||||
}
|
||||
}
|
||||
|
||||
// A key refused (Tavily's real 401) rests: the search goes on to the next
|
||||
// key, and the searches after it don't ask it while another key answers,
|
||||
// until its rest ends. A key that isn't refused (a 500) isn't rested.
|
||||
func TestSearchKeyRefusedRests(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
forgetSearchKeys()
|
||||
t.Cleanup(forgetSearchKeys)
|
||||
f := newKeyedTavily(t, map[string]int{"tvly-bad": 401})
|
||||
setTavily(t, f.URL, "tvly-bad,tvly-b,tvly-c", "")
|
||||
s := New()
|
||||
if _, _, err := s.apiSearch(context.Background(), "q"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := f.took(); !slices.Equal(got, []string{"tvly-bad", "tvly-b"}) {
|
||||
t.Fatalf("first search asked %v, want the refused key then the next", got)
|
||||
}
|
||||
r, ok := searchKeyRest("tavily", "tvly-bad", time.Now())
|
||||
if !ok || r.Why != "turned away" || time.Until(r.Until) < 9*time.Minute {
|
||||
t.Fatalf("the 401's key rests %+v, %v", r, ok)
|
||||
}
|
||||
var got []string
|
||||
for range 6 {
|
||||
if _, _, err := s.apiSearch(context.Background(), "q"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, f.took()...)
|
||||
}
|
||||
if slices.Contains(got, "tvly-bad") {
|
||||
t.Errorf("a resting key was asked while others answered: %v", got)
|
||||
}
|
||||
if !slices.Contains(got, "tvly-b") || !slices.Contains(got, "tvly-c") {
|
||||
t.Errorf("the searches weren't spread over the others: %v", got)
|
||||
}
|
||||
|
||||
// its rest over, it is asked again in its turn
|
||||
searchRests.Store(searchKeyID("tavily", "tvly-bad"), keyRest{Until: time.Now().Add(-time.Second), Why: "turned away"})
|
||||
got = nil
|
||||
for range 3 {
|
||||
s.apiSearch(context.Background(), "q")
|
||||
got = append(got, f.took()...)
|
||||
}
|
||||
if !slices.Contains(got, "tvly-bad") {
|
||||
t.Errorf("a key whose rest ended wasn't asked again: %v", got)
|
||||
}
|
||||
|
||||
// every key resting: each is still asked, the soonest awake first
|
||||
forgetSearchKeys()
|
||||
f.answers["tvly-b"], f.answers["tvly-c"] = 432, 429
|
||||
setTavily(t, f.URL, "tvly-bad,tvly-b,tvly-c", "")
|
||||
_, _, err := s.apiSearch(context.Background(), "q")
|
||||
if err == nil {
|
||||
t.Fatal("every key refused, and the search said nothing")
|
||||
}
|
||||
f.took()
|
||||
if r, _ := searchKeyRest("tavily", "tvly-b", time.Now()); r.Why != "out of credit" || time.Until(r.Until) < 59*time.Minute {
|
||||
t.Errorf("Tavily's 432 rests %+v", r)
|
||||
}
|
||||
if r, _ := searchKeyRest("tavily", "tvly-c", time.Now()); r.Why != "rate limited" || time.Until(r.Until) < 110*time.Second || time.Until(r.Until) > 125*time.Second {
|
||||
t.Errorf("a 429 with Retry-After: 120 rests %+v", r)
|
||||
}
|
||||
f.answers["tvly-c"] = 200
|
||||
if _, _, err := s.apiSearch(context.Background(), "q"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := f.took(); !slices.Equal(got, []string{"tvly-c"}) {
|
||||
t.Errorf("all resting, asked %v, want the one whose rest ends first", got)
|
||||
}
|
||||
if _, ok := searchKeyRest("tavily", "tvly-c", time.Now()); ok {
|
||||
t.Error("a key that answered still rests")
|
||||
}
|
||||
|
||||
// a 500 isn't about the key
|
||||
forgetSearchKeys()
|
||||
f.answers["tvly-bad"] = 500
|
||||
s.apiSearch(context.Background(), "q")
|
||||
if _, ok := searchKeyRest("tavily", "tvly-bad", time.Now()); ok {
|
||||
t.Error("a 500 rested the key")
|
||||
}
|
||||
}
|
||||
|
||||
// How long a refusal rests a key: Retry-After held within its bounds,
|
||||
// and 432/433 out of credit only from Tavily, whose codes they are.
|
||||
func TestSearchRestFor(t *testing.T) {
|
||||
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||
for _, c := range []struct {
|
||||
vendor string
|
||||
status int
|
||||
retryAfter string
|
||||
d time.Duration
|
||||
why string
|
||||
}{
|
||||
{"tavily", 401, "", turnedAwayRest, "turned away"},
|
||||
{"brave", 403, "", turnedAwayRest, "turned away"},
|
||||
{"exa", 402, "", outOfCreditRest, "out of credit"},
|
||||
{"tavily", 432, "", outOfCreditRest, "out of credit"},
|
||||
{"tavily", 433, "", outOfCreditRest, "out of credit"},
|
||||
{"brave", 432, "", rateLimitRest, "rate limited"},
|
||||
{"tavily", 429, "", rateLimitRest, "rate limited"},
|
||||
{"tavily", 429, "120", 2 * time.Minute, "rate limited"},
|
||||
{"tavily", 429, "1", rateLimitRestMin, "rate limited"},
|
||||
{"tavily", 429, "86400", rateLimitRestMax, "rate limited"},
|
||||
{"tavily", 429, now.Add(3 * time.Minute).Format(http.TimeFormat), 3 * time.Minute, "rate limited"},
|
||||
{"tavily", 429, "soon", rateLimitRest, "rate limited"},
|
||||
} {
|
||||
if d, why := searchRestFor(c.vendor, c.status, c.retryAfter, now); d != c.d || why != c.why {
|
||||
t.Errorf("%s %d %q: %v %q, want %v %q", c.vendor, c.status, c.retryAfter, d, why, c.d, c.why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What each key has used is read from Tavily's /usage, in the order of
|
||||
// the keys; one whose read fails is unknown with why, never 0 used. A key
|
||||
// it finds used up rests, and wakes when a later read finds credit.
|
||||
func TestSearchQuotas(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
forgetSearchKeys()
|
||||
searchQuotas.Clear()
|
||||
t.Cleanup(func() { forgetSearchKeys(); searchQuotas.Clear() })
|
||||
f := newKeyedTavily(t, map[string]int{})
|
||||
good, spent, bad := "tvly-dev-good0000000001234", "tvly-dev-spent000000005678", "tvly-dev-bad00000000009abc"
|
||||
f.usage[good] = tavilyUsageDoc
|
||||
f.usage[spent] = strings.Replace(tavilyUsageDoc, `"usage": 150`, `"usage": 1000`, 1)
|
||||
a := setTavily(t, f.URL, good+","+spent+","+bad, "")
|
||||
if CanReadSearchQuota(provider.SearchAPI{Vendor: "brave", Key: "b"}) || !CanReadSearchQuota(a) {
|
||||
t.Error("only Tavily's quota is read")
|
||||
}
|
||||
qs := SearchQuotas(context.Background(), a, true)
|
||||
if len(qs) != 3 {
|
||||
t.Fatalf("%d quotas for 3 keys", len(qs))
|
||||
}
|
||||
if q := qs[0]; q.Key != "tvly-…1234" || !q.Known || q.Used != 150 || q.Limit != 1000 || q.UsedUp || q.Resting != "" {
|
||||
t.Errorf("good: %+v", q)
|
||||
}
|
||||
if q := qs[1]; q.Key != "tvly-…5678" || !q.UsedUp || q.Resting != "used up" {
|
||||
t.Errorf("used up: %+v", q)
|
||||
}
|
||||
if q := qs[2]; q.Key != "tvly-…9abc" || q.Known || q.Err == "" || !strings.Contains(q.Err, "401") {
|
||||
t.Errorf("a 401 is unknown: %+v", q)
|
||||
}
|
||||
// the used-up key is asked last
|
||||
s := New()
|
||||
for range 4 {
|
||||
s.apiSearch(context.Background(), "q")
|
||||
}
|
||||
if got := f.took(); slices.Contains(got, spent) {
|
||||
t.Errorf("a used-up key was asked while others answered: %v", got)
|
||||
}
|
||||
// topped up: read again, it wakes
|
||||
f.mu.Lock()
|
||||
f.usage[spent] = tavilyUsageDoc
|
||||
f.mu.Unlock()
|
||||
if q := SearchQuotas(context.Background(), a, false)[1]; !q.UsedUp {
|
||||
t.Errorf("a read kept for %v was read again unasked: %+v", searchQuotaKeep, q)
|
||||
}
|
||||
if q := SearchQuotas(context.Background(), a, true)[1]; q.UsedUp || q.Resting != "" {
|
||||
t.Errorf("topped up, read fresh: %+v", q)
|
||||
}
|
||||
// no answer: unknown, not 0
|
||||
f.Close()
|
||||
if q := SearchQuotas(context.Background(), a, true)[0]; q.Known || q.Err == "" {
|
||||
t.Errorf("no answer: %+v", q)
|
||||
}
|
||||
}
|
||||
|
||||
// No key is ever said in full: not in a search's error (an API that says
|
||||
// the key back in its own), a quota's, the log, or the state magpie keeps
|
||||
// of the keys.
|
||||
func TestSearchKeyNeverInFull(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
forgetSearchKeys()
|
||||
searchQuotas.Clear()
|
||||
t.Cleanup(func() { forgetSearchKeys(); searchQuotas.Clear() })
|
||||
var logged bytes.Buffer
|
||||
was := log.Writer()
|
||||
log.SetOutput(&logged)
|
||||
t.Cleanup(func() { log.SetOutput(was) })
|
||||
k1, k2 := "tvly-dev-SECRETone00000000aaaa", "tvly-dev-SECRETtwo00000000bbbb"
|
||||
f := newKeyedTavily(t, map[string]int{k1: 401, k2: 401})
|
||||
a := setTavily(t, f.URL, k1+","+k2, "")
|
||||
s := New()
|
||||
_, _, err := s.apiSearch(context.Background(), "q")
|
||||
if err == nil {
|
||||
t.Fatal("both keys refused, and no error")
|
||||
}
|
||||
said := []string{err.Error(), logged.String(), a.MaskedKey()}
|
||||
for _, q := range SearchQuotas(context.Background(), a, true) {
|
||||
said = append(said, fmt.Sprintf("%+v", q))
|
||||
}
|
||||
for _, m := range []*sync.Map{&searchRests, &searchQuotas, &searchTurns} {
|
||||
m.Range(func(k, v any) bool { said = append(said, fmt.Sprintf("%v %+v", k, v)); return true })
|
||||
}
|
||||
all := strings.Join(said, "\n")
|
||||
for _, k := range []string{k1, k2, "SECRET"} {
|
||||
if strings.Contains(all, k) {
|
||||
t.Errorf("%q is said in full:\n%s", k, all)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(err.Error(), "tvly-…aaaa") || !strings.Contains(err.Error(), "key 2 (tvly-…bbbb)") {
|
||||
t.Errorf("the error doesn't name the keys masked: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// What each of a search API's keys has left (SlouchyQuill on Discord):
|
||||
// Tavily says it at GET /usage, by the key it is asked with. A read that
|
||||
// fails is said as unknown with why, never as 0 used.
|
||||
|
||||
// SearchKeyQuota is what one key of a search API has used of its limit.
|
||||
type SearchKeyQuota struct {
|
||||
Key string `json:"key"` // masked (provider.MaskSearchKey)
|
||||
// Known: Used and Limit were read. Unlimited: read, and the key and
|
||||
// its plan have no limit (Used is what the key has used).
|
||||
Known bool `json:"known"`
|
||||
Unlimited bool `json:"unlimited,omitempty"`
|
||||
Used int64 `json:"used"`
|
||||
Limit int64 `json:"limit"`
|
||||
// Of is what Limit is the limit of: "key", a limit set on the key
|
||||
// itself, or "plan", its account's plan (which every key of the
|
||||
// account spends)
|
||||
Of string `json:"of,omitempty"`
|
||||
Plan string `json:"plan,omitempty"` // the plan's name
|
||||
// PaygoLeft is the pay-as-you-go credit still there past the plan's
|
||||
// limit, 0 when there is none
|
||||
PaygoLeft int64 `json:"paygoLeft,omitempty"`
|
||||
// UsedUp: Used reached Limit, with no pay-as-you-go credit left
|
||||
UsedUp bool `json:"usedUp,omitempty"`
|
||||
// Err is why it couldn't be read: Known is false
|
||||
Err string `json:"err,omitempty"`
|
||||
// Resting is why searches ask the key last now (searchKeyOrder), and
|
||||
// RestUntil until when; "" when they don't
|
||||
Resting string `json:"resting,omitempty"`
|
||||
RestUntil time.Time `json:"restUntil,omitzero"`
|
||||
}
|
||||
|
||||
// readTavilyUsage reads Tavily's GET /usage reply into what the key has
|
||||
// left: the key's own limit when it has one, else its account plan's (the
|
||||
// plan's usage beside it, not the key's, as the account's other keys spend
|
||||
// it too). key.limit is null for a key with no limit of its own, which a
|
||||
// free account's keys are; with plan_limit null too it has none. A reply
|
||||
// missing what it takes, or saying it in a way not known, is an error:
|
||||
// unknown, never 0.
|
||||
func readTavilyUsage(b []byte) (SearchKeyQuota, error) {
|
||||
var u struct {
|
||||
Key, Account map[string]json.RawMessage
|
||||
}
|
||||
if err := json.Unmarshal(b, &u); err != nil {
|
||||
return SearchKeyQuota{}, err
|
||||
}
|
||||
if u.Key == nil {
|
||||
return SearchKeyQuota{}, errors.New("no key in the reply")
|
||||
}
|
||||
// num is a field's number; null is whether it is null; ok is false
|
||||
// when it is missing or neither
|
||||
num := func(o map[string]json.RawMessage, f string) (n int64, null, ok bool) {
|
||||
v, there := o[f]
|
||||
if !there {
|
||||
return 0, false, false
|
||||
}
|
||||
if string(v) == "null" {
|
||||
return 0, true, true
|
||||
}
|
||||
var x float64
|
||||
if json.Unmarshal(v, &x) != nil {
|
||||
return 0, false, false
|
||||
}
|
||||
return int64(x), false, true
|
||||
}
|
||||
var q SearchKeyQuota
|
||||
json.Unmarshal(u.Account["current_plan"], &q.Plan)
|
||||
if pl, null, ok := num(u.Account, "paygo_limit"); ok && !null {
|
||||
if pu, null, ok := num(u.Account, "paygo_usage"); ok && !null {
|
||||
q.PaygoLeft = max(0, pl-pu)
|
||||
}
|
||||
}
|
||||
keyUsed, keyUsedNull, keyUsedOK := num(u.Key, "usage")
|
||||
keyLimit, keyLimitNull, ok := num(u.Key, "limit")
|
||||
if !ok {
|
||||
return SearchKeyQuota{}, errors.New("no key limit in the reply")
|
||||
}
|
||||
switch planLimit, planLimitNull, planOK := num(u.Account, "plan_limit"); {
|
||||
case !keyLimitNull:
|
||||
if !keyUsedOK || keyUsedNull {
|
||||
return SearchKeyQuota{}, errors.New("no key usage in the reply")
|
||||
}
|
||||
q.Used, q.Limit, q.Of = keyUsed, keyLimit, "key"
|
||||
case planOK && !planLimitNull:
|
||||
planUsed, null, ok := num(u.Account, "plan_usage")
|
||||
if !ok || null {
|
||||
return SearchKeyQuota{}, errors.New("no plan usage in the reply")
|
||||
}
|
||||
q.Used, q.Limit, q.Of = planUsed, planLimit, "plan"
|
||||
case planOK && planLimitNull:
|
||||
q.Unlimited, q.Used = true, keyUsed
|
||||
default:
|
||||
return SearchKeyQuota{}, errors.New("no plan limit in the reply")
|
||||
}
|
||||
q.Known = true
|
||||
// a key's own limit is a hard stop; a plan's goes on into
|
||||
// pay-as-you-go while there is some
|
||||
q.UsedUp = !q.Unlimited && q.Used >= q.Limit && (q.Of == "key" || q.PaygoLeft == 0)
|
||||
return q, nil
|
||||
}
|
||||
|
||||
// searchQuotaKeep is how long a quota read is kept before it is read
|
||||
// again: Tavily allows /usage 10 times in 10 minutes.
|
||||
const searchQuotaKeep = 2 * time.Minute
|
||||
|
||||
type keptQuota struct {
|
||||
at time.Time
|
||||
q SearchKeyQuota
|
||||
}
|
||||
|
||||
// searchQuotas is, by searchKeyID, the last quota read of each key.
|
||||
var searchQuotas sync.Map
|
||||
|
||||
// quotaClient asks for quotas through the proxy settings searches use.
|
||||
var quotaClient = &http.Client{Transport: upstreamTransport()}
|
||||
|
||||
// CanReadSearchQuota is whether magpie can read what a search API's keys
|
||||
// have left: Tavily's, with a key.
|
||||
func CanReadSearchQuota(a provider.SearchAPI) bool {
|
||||
return a.Vendor == "tavily" && len(a.Keys()) > 0
|
||||
}
|
||||
|
||||
// SearchQuotas reads what each of a search API's keys has left, in the
|
||||
// order of its keys, nil for an API magpie can't ask (CanReadSearchQuota).
|
||||
// A read newer than searchQuotaKeep is used again unless fresh is set. A
|
||||
// key it finds used up rests (a search asks it last); one with credit
|
||||
// that rests for being out of it wakes.
|
||||
func SearchQuotas(ctx context.Context, a provider.SearchAPI, fresh bool) []SearchKeyQuota {
|
||||
if !CanReadSearchQuota(a) {
|
||||
return nil
|
||||
}
|
||||
keys := a.Keys()
|
||||
out := make([]SearchKeyQuota, len(keys))
|
||||
var wg sync.WaitGroup
|
||||
for i, k := range keys {
|
||||
wg.Go(func() { out[i] = searchQuota(ctx, a, k, fresh) })
|
||||
}
|
||||
wg.Wait()
|
||||
now := time.Now()
|
||||
for i, k := range keys {
|
||||
if r, ok := searchKeyRest(a.Vendor, k, now); ok {
|
||||
out[i].Resting, out[i].RestUntil = r.Why, r.Until
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// searchQuota is one key's quota, read or kept.
|
||||
func searchQuota(ctx context.Context, a provider.SearchAPI, key string, fresh bool) SearchKeyQuota {
|
||||
id := searchKeyID(a.Vendor+" "+a.Base(), key)
|
||||
if v, ok := searchQuotas.Load(id); ok && !fresh && time.Since(v.(keptQuota).at) < searchQuotaKeep {
|
||||
return v.(keptQuota).q
|
||||
}
|
||||
q, err := askTavilyUsage(ctx, a, key)
|
||||
if err != nil {
|
||||
msg := strings.ReplaceAll(err.Error(), key, provider.MaskSearchKey(key))
|
||||
q = SearchKeyQuota{Err: msg}
|
||||
}
|
||||
q.Key = provider.MaskSearchKey(key)
|
||||
searchQuotas.Store(id, keptQuota{time.Now(), q})
|
||||
switch {
|
||||
case q.UsedUp:
|
||||
restSearchKey(a.Vendor, key, outOfCreditRest, "used up", time.Now())
|
||||
case q.Known:
|
||||
if r, ok := searchKeyRest(a.Vendor, key, time.Now()); ok && (r.Why == "used up" || r.Why == "out of credit") {
|
||||
wakeSearchKey(a.Vendor, key)
|
||||
}
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// askTavilyUsage asks Tavily's /usage with one key; the key goes only to
|
||||
// the address the API is set at, as a search's does.
|
||||
func askTavilyUsage(ctx context.Context, a provider.SearchAPI, key string) (SearchKeyQuota, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
r, err := http.NewRequestWithContext(ctx, http.MethodGet, a.Base()+"/usage", nil)
|
||||
if err != nil {
|
||||
return SearchKeyQuota{}, err
|
||||
}
|
||||
r.Header.Set("Authorization", "Bearer "+key)
|
||||
r.Header.Set("Accept", "application/json")
|
||||
r.Header.Set("User-Agent", SearchAgent)
|
||||
c := *quotaClient
|
||||
c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
res, err := c.Do(r)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return SearchKeyQuota{}, errors.New("no answer in time")
|
||||
}
|
||||
return SearchKeyQuota{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return SearchKeyQuota{}, errors.New(provider.APIError(b, res.Status))
|
||||
}
|
||||
q, err := readTavilyUsage(b)
|
||||
if err != nil {
|
||||
return SearchKeyQuota{}, fmt.Errorf("unexpected reply: %w", err)
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
+33
-4
@@ -487,6 +487,12 @@ type searchAPIJSON struct {
|
||||
Key string `json:"key,omitempty"` // masked
|
||||
URL string `json:"url,omitempty"`
|
||||
Ready bool `json:"ready"`
|
||||
// Keys is how many keys it has, Pick how a search picks among them
|
||||
// (provider.SearchPick*), and Quota whether what each has left can be
|
||||
// read (gateway.SearchQuotas)
|
||||
Keys int `json:"keys,omitempty"`
|
||||
Pick string `json:"pick,omitempty"`
|
||||
Quota bool `json:"quota,omitempty"`
|
||||
}
|
||||
|
||||
// searchChoiceJSON is a provider that can search for a model that can't,
|
||||
@@ -523,7 +529,7 @@ func searchState(s *settingsJSON) {
|
||||
}
|
||||
s.SearchAPIs, s.SearchVendors = []searchAPIJSON{}, []searchVendorJSON{}
|
||||
for _, a := range provider.StoredSearchAPIs() {
|
||||
j := searchAPIJSON{Vendor: a.Vendor, Name: a.Name(), URL: a.URL, Ready: a.Ready()}
|
||||
j := searchAPIJSON{Vendor: a.Vendor, Name: a.Name(), URL: a.URL, Ready: a.Ready(), Keys: len(a.Keys()), Pick: a.Pick, Quota: gateway.CanReadSearchQuota(a)}
|
||||
if a.Key != "" {
|
||||
j.Key = a.MaskedKey()
|
||||
}
|
||||
@@ -2023,8 +2029,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
// a web search API added, given a new key or address, or taken away
|
||||
mux.HandleFunc("POST /api/settings/search-api", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Vendor, Key, URL string
|
||||
Remove bool
|
||||
Vendor, Key, URL, Pick string
|
||||
Remove bool
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
@@ -2034,7 +2040,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
if in.Remove {
|
||||
err = provider.RemoveSearchAPI(in.Vendor)
|
||||
} else {
|
||||
err = provider.SetSearchAPI(provider.SearchAPI{Vendor: in.Vendor, Key: in.Key, URL: in.URL})
|
||||
err = provider.SetSearchAPI(provider.SearchAPI{Vendor: in.Vendor, Key: in.Key, URL: in.URL, Pick: in.Pick})
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
@@ -2058,6 +2064,29 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
fail(rw, fmt.Errorf("no search API %q", in.Vendor))
|
||||
})
|
||||
// what each of a search API's keys has used of its limit (SlouchyQuill
|
||||
// on Discord), the keys masked; fresh reads again what was read lately
|
||||
mux.HandleFunc("POST /api/settings/search-quota", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Vendor string
|
||||
Fresh bool
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
for _, a := range provider.StoredSearchAPIs() {
|
||||
if a.Vendor == in.Vendor {
|
||||
qs := gateway.SearchQuotas(r.Context(), a, in.Fresh)
|
||||
if qs == nil {
|
||||
qs = []gateway.SearchKeyQuota{}
|
||||
}
|
||||
writeJSON(rw, map[string]any{"keys": qs})
|
||||
return
|
||||
}
|
||||
}
|
||||
fail(rw, fmt.Errorf("no search API %q", in.Vendor))
|
||||
})
|
||||
// the config folder only: the page names no path, so it can't open others
|
||||
mux.HandleFunc("POST /api/settings/reveal", func(rw http.ResponseWriter, r *http.Request) {
|
||||
if err := w.OpenFolder(settings.Dir()); err != nil {
|
||||
|
||||
@@ -3056,6 +3056,16 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
|
||||
/* a search API's key, shown: selectable, and broken anywhere rather than widening the row */
|
||||
.search-api .sub.revealed { font-family: var(--code-font, var(--code)); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; }
|
||||
:where(html[data-fonts]) .search-api .sub.revealed { font-style: var(--code-style, inherit); font-weight: var(--code-weight, inherit); font-stretch: var(--code-stretch, 100%); }
|
||||
/* a search API's keys and what each has used of its limit */
|
||||
/* how its searches pick a key, and Check again: wrapped, right-aligned, on a
|
||||
narrow window in a long language rather than past its edge */
|
||||
.row.pref.search-keys .val { flex-wrap: wrap; justify-content: flex-end; gap: 4px; }
|
||||
.search-quota { display: flex; flex-direction: column; gap: 3px; margin-top: 6px; font-size: 12px; min-width: 0; }
|
||||
.search-quota .quota-key { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; min-width: 0; }
|
||||
.search-quota code { font-family: var(--code-font, var(--code)); color: var(--muted); }
|
||||
.search-quota .faint { color: var(--muted); overflow-wrap: anywhere; }
|
||||
.search-quota .err { color: var(--red); overflow-wrap: anywhere; }
|
||||
.search-quota .warn { color: var(--amber); }
|
||||
.prefs .val.rule-add .segs { margin-left: 0; }
|
||||
/* a rule open to edit (nf1qaz2w on Discord): laid out as the add row; a
|
||||
narrow window puts the match, Save and Cancel on a line of their own under
|
||||
|
||||
@@ -22388,6 +22388,7 @@ function renderSearch(s, keep) {
|
||||
}
|
||||
const r = row(`${n + 1}. ${a.name}`, what, ...tools);
|
||||
r.classList.add("search-api");
|
||||
if (a.keys > 1 || a.quota) searchKeysRow(s, a, row, set);
|
||||
});
|
||||
// which goes first when both a provider and a search API can search
|
||||
// (#928); with only one of them there is nothing to choose
|
||||
@@ -22405,6 +22406,70 @@ function renderSearch(s, keep) {
|
||||
mcp.id = "searchMcpRow";
|
||||
}
|
||||
|
||||
// searchKeysRow: under a search API with several keys, or one whose keys
|
||||
// quota magpie can read (Tavily's), a row of its keys (SlouchyQuill on
|
||||
// Discord): how a search picks among them, in turn (the default) or in
|
||||
// order, and what each has used of its limit, read once as the page is
|
||||
// drawn and again on Check again. A read that fails says unknown and why,
|
||||
// never 0; a key a search set aside lately says why and until when.
|
||||
const searchQuotaSeen = {};
|
||||
function searchKeysRow(s, a, row, set) {
|
||||
const tools = [];
|
||||
if (a.keys > 1) tools.push(segs([["", t("In turn")], ["order", t("In order")]], a.pick || "",
|
||||
(v) => set({ vendor: a.vendor, pick: v || "turns" })));
|
||||
const mine = el("div", "search-quota");
|
||||
const seenAs = [a.key, a.url].join(" ");
|
||||
const ask = (fresh) => {
|
||||
searchQuotaSeen[a.vendor] = { as: seenAs, loading: true };
|
||||
draw();
|
||||
api("settings/search-quota", { vendor: a.vendor, fresh })
|
||||
.then((r) => { searchQuotaSeen[a.vendor] = { as: seenAs, keys: r.keys || [] }; })
|
||||
.catch((e) => { searchQuotaSeen[a.vendor] = { as: seenAs, err: e.message }; })
|
||||
.finally(draw);
|
||||
};
|
||||
// the list in the page now: Settings may have been drawn again while
|
||||
// the read was out
|
||||
const draw = () => {
|
||||
const list = document.querySelector(`.search-keys[data-vendor="${a.vendor}"] .search-quota`) || mine;
|
||||
const seen = searchQuotaSeen[a.vendor];
|
||||
list.replaceChildren();
|
||||
if (!seen || seen.loading) return list.append(el("div", "faint", t("Reading what each key has used…")));
|
||||
if (seen.err) return list.append(el("div", "err", t("Unknown: {why}", { why: seen.err })));
|
||||
const num = (n) => Number(n).toLocaleString(intlLang());
|
||||
for (const q of seen.keys) {
|
||||
const line = el("div", "quota-key");
|
||||
const said = !q.known ? t("Unknown: {why}", { why: q.err || "" })
|
||||
: q.unlimited ? t("{used} used, no limit", { used: num(q.used) })
|
||||
: t("{used} of {limit} used", { used: num(q.used), limit: num(q.limit) });
|
||||
const notes = [];
|
||||
if (q.known && q.of === "plan") notes.push(q.plan ? t("{plan} plan, shared by its account's keys", { plan: q.plan }) : t("the plan's, shared by its account's keys"));
|
||||
if (q.paygoLeft > 0) notes.push(t("{n} pay-as-you-go left", { n: num(q.paygoLeft) }));
|
||||
if (q.resting) notes.push(t("asked last until {time}: {why}", { time: new Date(q.restUntil).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }),
|
||||
why: { "turned away": t("turned away"), "out of credit": t("out of credit"), "rate limited": t("rate limited"), "used up": t("used up") }[q.resting] || q.resting }));
|
||||
const used = el("span", q.known ? (q.usedUp ? "used warn" : "used") : "used err", said);
|
||||
line.append(el("code", "", q.key), used);
|
||||
if (q.usedUp) line.append(el("span", "warn", t("used up")));
|
||||
if (notes.length) line.append(el("span", "faint", notes.join(" · ")));
|
||||
list.append(line);
|
||||
}
|
||||
};
|
||||
if (a.quota) {
|
||||
const again = el("button", "text search-quota-again", t("Check again"));
|
||||
again.onclick = () => ask(true);
|
||||
tools.push(again);
|
||||
}
|
||||
const r = row(t("Keys of {name}", { name: a.name }),
|
||||
a.keys > 1 ? t("In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.") : t("What the key has used of its limit"),
|
||||
...tools);
|
||||
r.classList.add("search-keys");
|
||||
r.dataset.vendor = a.vendor;
|
||||
if (a.quota) {
|
||||
r.querySelector(".who").append(mine);
|
||||
if (searchQuotaSeen[a.vendor]?.as !== seenAs) ask(false);
|
||||
else draw();
|
||||
}
|
||||
}
|
||||
|
||||
// renderSearcher: the provider that searches the web for a model that
|
||||
// can't — the one magpie picks, or one named, by itself (its small model)
|
||||
// or with a model of it. One named that is gone, off or can't search gives
|
||||
|
||||
@@ -1122,6 +1122,19 @@ const I18N = {
|
||||
"Base URL": "API 地址",
|
||||
"Base URL, empty for {url}": "API 地址,留空则用 {url}",
|
||||
"A new key, or empty to keep {key}": "新的密钥,留空则保留 {key}",
|
||||
"Reading what each key has used…": "正在读取每个密钥的用量…",
|
||||
"Unknown: {why}": "未知:{why}",
|
||||
"{used} used, no limit": "已用 {used},无上限",
|
||||
"{used} of {limit} used": "已用 {used} / {limit}",
|
||||
"{plan} plan, shared by its account's keys": "{plan} 套餐,同账号的密钥共用",
|
||||
"the plan's, shared by its account's keys": "套餐额度,同账号的密钥共用",
|
||||
"{n} pay-as-you-go left": "按量付费还剩 {n}",
|
||||
"asked last until {time}: {why}": "{time} 前最后才用:{why}",
|
||||
"turned away": "被拒绝",
|
||||
"used up": "已用完",
|
||||
"Keys of {name}": "{name} 的密钥",
|
||||
"In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.": "轮流:搜索分摊到各个密钥;按顺序:先用第一个,被拒后才用下一个。最近被拒的密钥最后才用。",
|
||||
"What the key has used of its limit": "该密钥已用了多少额度",
|
||||
"your own": "自建",
|
||||
"needs its key": "缺少密钥",
|
||||
"{name} added back": "已加回 {name}",
|
||||
@@ -5859,6 +5872,19 @@ const I18N = {
|
||||
"Base URL": "API 位址",
|
||||
"Base URL, empty for {url}": "API 位址,留空則用 {url}",
|
||||
"A new key, or empty to keep {key}": "新的金鑰,留空則保留 {key}",
|
||||
"Reading what each key has used…": "正在讀取每個金鑰的用量…",
|
||||
"Unknown: {why}": "未知:{why}",
|
||||
"{used} used, no limit": "已用 {used},無上限",
|
||||
"{used} of {limit} used": "已用 {used} / {limit}",
|
||||
"{plan} plan, shared by its account's keys": "{plan} 方案,同帳號的金鑰共用",
|
||||
"the plan's, shared by its account's keys": "方案額度,同帳號的金鑰共用",
|
||||
"{n} pay-as-you-go left": "按量付費還剩 {n}",
|
||||
"asked last until {time}: {why}": "{time} 前最後才用:{why}",
|
||||
"turned away": "被拒絕",
|
||||
"used up": "已用完",
|
||||
"Keys of {name}": "{name} 的金鑰",
|
||||
"In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.": "輪流:搜尋分攤到各個金鑰;按順序:先用第一個,被拒後才用下一個。最近被拒的金鑰最後才用。",
|
||||
"What the key has used of its limit": "該金鑰已用了多少額度",
|
||||
"your own": "自建",
|
||||
"needs its key": "缺少金鑰",
|
||||
"{name} added back": "已加回 {name}",
|
||||
@@ -10564,6 +10590,19 @@ const I18N = {
|
||||
"Base URL": "ベース URL",
|
||||
"Base URL, empty for {url}": "ベース URL(空なら {url})",
|
||||
"A new key, or empty to keep {key}": "新しいキー(空なら {key} のまま)",
|
||||
"Reading what each key has used…": "各キーの使用量を読み込み中…",
|
||||
"Unknown: {why}": "不明:{why}",
|
||||
"{used} used, no limit": "{used} 使用、上限なし",
|
||||
"{used} of {limit} used": "{limit} 中 {used} 使用",
|
||||
"{plan} plan, shared by its account's keys": "{plan} プラン(同じアカウントのキーで共有)",
|
||||
"the plan's, shared by its account's keys": "プランの上限(同じアカウントのキーで共有)",
|
||||
"{n} pay-as-you-go left": "従量課金の残り {n}",
|
||||
"asked last until {time}: {why}": "{time} まで最後に使用:{why}",
|
||||
"turned away": "拒否",
|
||||
"used up": "使い切り",
|
||||
"Keys of {name}": "{name} のキー",
|
||||
"In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.": "交互:検索を各キーに分散します。順番:最初のキーを拒否されるまで使います。最近拒否されたキーは最後に使います。",
|
||||
"What the key has used of its limit": "このキーが上限のうちどれだけ使ったか",
|
||||
"your own": "独自",
|
||||
"needs its key": "キーが必要",
|
||||
"{name} added back": "{name} を再追加しました",
|
||||
@@ -15289,6 +15328,19 @@ const I18N = {
|
||||
"Base URL": "Basis-URL",
|
||||
"Base URL, empty for {url}": "Basis-URL, leer für {url}",
|
||||
"A new key, or empty to keep {key}": "Neuer Schlüssel, leer lässt {key}",
|
||||
"Reading what each key has used…": "Lese, was jeder Schlüssel verbraucht hat…",
|
||||
"Unknown: {why}": "Unbekannt: {why}",
|
||||
"{used} used, no limit": "{used} verbraucht, kein Limit",
|
||||
"{used} of {limit} used": "{used} von {limit} verbraucht",
|
||||
"{plan} plan, shared by its account's keys": "Tarif {plan}, geteilt von den Schlüsseln des Kontos",
|
||||
"the plan's, shared by its account's keys": "Limit des Tarifs, geteilt von den Schlüsseln des Kontos",
|
||||
"{n} pay-as-you-go left": "{n} Pay-as-you-go übrig",
|
||||
"asked last until {time}: {why}": "bis {time} zuletzt gefragt: {why}",
|
||||
"turned away": "abgewiesen",
|
||||
"used up": "aufgebraucht",
|
||||
"Keys of {name}": "Schlüssel von {name}",
|
||||
"In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.": "Abwechselnd verteilt Suchen auf die Schlüssel; der Reihe nach nutzt den ersten, bis er abgewiesen wird. Ein kürzlich abgewiesener Schlüssel wird zuletzt gefragt.",
|
||||
"What the key has used of its limit": "Was der Schlüssel von seinem Limit verbraucht hat",
|
||||
"your own": "eigener",
|
||||
"needs its key": "Schlüssel fehlt",
|
||||
"{name} added back": "{name} wieder hinzugefügt",
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings' Web search section, a search API with several keys
|
||||
// (SlouchyQuill on Discord, after dsh-tavily-pool): under it a row of its
|
||||
// keys, In turn (the default) or In order, sent as pick "turns" or "order";
|
||||
// for Tavily, what each key has used of its limit, read once as the page
|
||||
// is drawn and again, fresh, on Check again. Each key is shown masked; a
|
||||
// read that failed says Unknown and why, never 0; a key used up says so,
|
||||
// and one asked last says until when and why. An API with one key that
|
||||
// magpie can't read gets no row. In five languages, Chromium and WebKit,
|
||||
// 1100px and 420px wide, with the API faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
// the words as i18n.js has them
|
||||
const I18N = (() => {
|
||||
const src = require("node:fs").readFileSync(path.join(assets, "i18n.js"), "utf8");
|
||||
return new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
|
||||
})();
|
||||
const tr = (lang, s, vars = {}) => {
|
||||
const got = lang === "en" ? s : I18N[lang][s];
|
||||
assert(got, `"${s}" has no ${lang} translation`);
|
||||
return got.replace(/\{(\w+)\}/g, (_, k) => String(vars[k]));
|
||||
};
|
||||
|
||||
const vendors = [
|
||||
{ id: "tavily", name: "Tavily", keysURL: "https://app.tavily.com/home", base: "https://api.tavily.com" },
|
||||
{ id: "brave", name: "Brave Search", keysURL: "https://api-dashboard.search.brave.com/app/keys", base: "https://api.search.brave.com" },
|
||||
];
|
||||
const restUntil = new Date(Date.now() + 50 * 60 * 1000).toISOString();
|
||||
const quotas = (used) => [
|
||||
{ key: "tvly-…aaaa", known: true, used, limit: 1000, of: "key" },
|
||||
{ key: "tvly-…bbbb", known: true, used: 1000, limit: 1000, of: "plan", plan: "Researcher", usedUp: true, resting: "used up", restUntil },
|
||||
{ key: "tvly-…cccc", known: false, used: 0, limit: 0, err: "401 Unauthorized" },
|
||||
];
|
||||
|
||||
function serve(lang, posted) {
|
||||
let pick = "";
|
||||
let reads = 0;
|
||||
const settings = () => ({
|
||||
lang, theme: "light", searchVendors: vendors,
|
||||
searchAPIs: [
|
||||
{ vendor: "tavily", name: "Tavily", key: "tvly-…aaaa, tvly-…bbbb, tvly-…cccc", keys: 3, quota: true, pick, ready: true },
|
||||
{ vendor: "brave", name: "Brave Search", key: "BSA…wxyz", keys: 1, ready: true },
|
||||
],
|
||||
});
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data, status = 200) => r.fulfill({ status, json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() });
|
||||
if (url.pathname === "/api/settings") return json(settings());
|
||||
if (url.pathname === "/api/settings/search-api") {
|
||||
const b = JSON.parse(r.request().postData());
|
||||
posted.push(b);
|
||||
if (b.pick) pick = b.pick === "turns" ? "" : b.pick;
|
||||
return json(settings());
|
||||
}
|
||||
if (url.pathname === "/api/settings/search-quota") {
|
||||
const b = JSON.parse(r.request().postData());
|
||||
posted.push({ quota: b });
|
||||
reads++;
|
||||
return json({ keys: quotas(reads > 1 ? 813 : 812) });
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of LANGS) for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: a search API's keys take turns and say what each has used`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posted = [];
|
||||
await page.route("**/*", serve(lang, posted));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=settings&tab=models");
|
||||
await settingsDrawn(page);
|
||||
const keys = page.locator("#searchList .row.search-keys");
|
||||
await keys.first().waitFor();
|
||||
// Tavily's only: Brave has one key and no quota magpie can read
|
||||
assert.equal(await keys.count(), 1);
|
||||
assert.equal(await keys.getAttribute("data-vendor"), "tavily");
|
||||
assert.equal(await keys.locator(".name").innerText(), tr(lang, "Keys of {name}", { name: "Tavily" }));
|
||||
|
||||
const lines = keys.locator(".search-quota .quota-key");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .quota-key").length === 3);
|
||||
assert.deepEqual(await lines.locator("code").allInnerTexts(), ["tvly-…aaaa", "tvly-…bbbb", "tvly-…cccc"]);
|
||||
assert.equal(await lines.nth(0).locator(".used").innerText(), tr(lang, "{used} of {limit} used", { used: "812", limit: await page.evaluate(() => (1000).toLocaleString(intlLang())) }));
|
||||
// used up: said, with the plan it is of and why it is asked last
|
||||
assert.equal(await lines.nth(1).locator(".warn").last().innerText(), tr(lang, "used up"));
|
||||
const note = await lines.nth(1).locator(".faint").innerText();
|
||||
assert(note.includes(tr(lang, "{plan} plan, shared by its account's keys", { plan: "Researcher" })), note);
|
||||
const until = await page.evaluate((u) => new Date(u).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }), restUntil);
|
||||
assert(note.includes(tr(lang, "asked last until {time}: {why}", { time: until, why: tr(lang, "used up") })), note);
|
||||
// a failed read: unknown and why, never 0
|
||||
const unknown = await lines.nth(2).locator(".used").innerText();
|
||||
assert.equal(unknown, tr(lang, "Unknown: {why}", { why: "401 Unauthorized" }));
|
||||
assert(!/(^|\D)0(\D|$)/.test(unknown.replace("401", "")), unknown);
|
||||
assert.equal(await lines.nth(2).locator(".used.err").count(), 1);
|
||||
assert.deepEqual(posted, [{ quota: { vendor: "tavily", fresh: false } }]);
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
// the page clips what is past its edge, so each control is measured
|
||||
const past = await keys.evaluate((r) => [...r.querySelectorAll("button, code, .used")]
|
||||
.filter((e) => e.getBoundingClientRect().right > innerWidth + 0.5).map((e) => e.textContent));
|
||||
assert.deepEqual(past, [], "nothing past the window's edge");
|
||||
|
||||
const where = () => page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop, document.querySelector("#view-settings")?.scrollTop]);
|
||||
// Settings is drawn again after each change: a box is taken from the
|
||||
// row that stays
|
||||
const click = async (loc) => {
|
||||
let b = null;
|
||||
for (let i = 0; i < 20 && !b; i++) b = await loc.boundingBox().catch(() => null) || (await page.waitForTimeout(50), null);
|
||||
assert(b, "the button is in the page");
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
};
|
||||
// the row's foot is past the window's at 420px: the reader wheels down
|
||||
// to it before the clicks, which then must not move the page
|
||||
await reach(page, keys.locator("button.search-quota-again"));
|
||||
const before = await where();
|
||||
// Check again: read fresh
|
||||
await click(keys.locator("button.search-quota-again", { hasText: tr(lang, "Check again") }));
|
||||
await page.waitForFunction(() => /813/.test(document.querySelector("#searchList .search-keys .quota-key .used")?.innerText || ""));
|
||||
assert.deepEqual(posted.at(-1), { quota: { vendor: "tavily", fresh: true } });
|
||||
// In order, then In turn again
|
||||
const segs = keys.locator(".segs .opt");
|
||||
assert.deepEqual(await segs.allInnerTexts(), [tr(lang, "In turn"), tr(lang, "In order")]);
|
||||
assert.equal(await segs.nth(0).getAttribute("aria-pressed"), "true");
|
||||
await click(segs.nth(1));
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .segs .opt")[1]?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(posted.filter((p) => p.pick), [{ vendor: "tavily", pick: "order" }]);
|
||||
await click(keys.locator(".segs .opt").nth(0));
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .segs .opt")[0]?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(posted.filter((p) => p.pick), [{ vendor: "tavily", pick: "order" }, { vendor: "tavily", pick: "turns" }]);
|
||||
// redrawn with the same keys, it isn't read again
|
||||
assert.equal(posted.filter((p) => p.quota).length, 2);
|
||||
assert.equal(await keys.locator(".quota-key").count(), 3);
|
||||
assert.deepEqual(await where(), before, "a click doesn't scroll");
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,22 @@ type SearchAPI struct {
|
||||
// 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
|
||||
@@ -68,16 +79,26 @@ func (a SearchAPI) Keys() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// MaskedKey is Key as shown: each of its keys masked (Mask), so a list of
|
||||
// them shows no more of any one than a single key does.
|
||||
// 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] = Mask(k)
|
||||
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 {
|
||||
@@ -123,6 +144,9 @@ func (a SearchAPI) check() error {
|
||||
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://…")
|
||||
}
|
||||
@@ -142,10 +166,12 @@ func SearchAPIs() []SearchAPI {
|
||||
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.
|
||||
// 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
|
||||
@@ -154,6 +180,14 @@ func SetSearchAPI(a SearchAPI) error {
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user