provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.
Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.
- Listed by the local id: Available, liveIDs/liveByID, Serving and
ListPrice translate through OwnModelID. /v1/models, agents' lists,
Resolve, routing groups and found groups (auto/<local>, merged with
every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
account's or a plugin's request is built from its list's id, which no
wire reaches.
- Two variants of one provider given one id: the latest given it wins,
and the earlier one is listed by its own id again. The CLI names it.
The editor refuses two rows given one id in one save. A model of the
provider's own id that a variant is listed by (plain grok-4.6 beside
grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
classifier/pick, the pickers' lists, every per-model setting
(Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
set by access) to the new id, but only where nothing is under the new
id yet. Agents' own files are not rewritten: an old provider/<own id>
still resolves and is sent as it is. Group match patterns and key
patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
The price is the own id's first.
CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.
Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
usage and cli: ok. internal/gui: ok but for
TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
458 with 400 (main 459), searcherModel within its 50. Reading
Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
per file change, the settings path is built again only when what it is
built from changes, and Serving looks up the own id only when a key is
listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
provider-detect in Chromium on mote and WebKit on the Linux box (mote's
WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -198,6 +198,38 @@ it may be a variant's (`deepseek-v4.1-flash[fast]`), and a tagged id is
|
||||
never priced. `TestUserSameGivesTheSpecs`, `TestTaggedIDHasTheModelsSpecs`,
|
||||
`TestSameAsGivesAnUnlistedModelItsSpecs`.
|
||||
|
||||
A model can also be listed by an id the user gives it at its provider
|
||||
(zeewell on X: a relay's `deepseek-v4.1-flash-1017` as
|
||||
`deepseek-v4.1-flash`, `grok-4.6@500k` as `grok-4.6`): the editor's
|
||||
Names & levels "Listed as" box beside Same as, `magpie model id
|
||||
<provider/model> <id>` (`--reset` takes it back, `magpie model ids` lists
|
||||
them), settings' `ModelIDs` (`"<pid>/<id>": "<own id>"`,
|
||||
`provider.SetModelID`, [`localid.go`](../../internal/provider/localid.go)).
|
||||
Same as only lends specs and joins found groups; this id is what magpie
|
||||
lists, picks, groups, finds groups by (`auto/<id>` with every other
|
||||
provider serving it), limits gateway keys to and records usage under,
|
||||
while the vendor is asked for its own id: `Settings.Wires()` turns each
|
||||
entry round into a wire name, so every place a `ModelWires` name goes out
|
||||
sends it, and an explicit `ModelWires` entry for the same id wins. Only a
|
||||
provider of the user's own takes one (`TakesModelIDs`); an account's or a
|
||||
plugin's requests are built from its own list's id, which no wire name
|
||||
reaches. One id is one model of a provider: the latest given it has it,
|
||||
and the one before is listed by its own id again (the CLI names it; the
|
||||
editor refuses two rows given one id in one save). A model of the
|
||||
provider's own id that another is listed by (`grok-4.6` beside
|
||||
`grok-4.6@500k`) is not listed while it is. Giving the id moves what the
|
||||
user set of the model (picks, contexts, fallbacks, routing groups'
|
||||
members and rules, the pickers' lists, every per-model setting, gateway
|
||||
keys' models through `provider.ModelMoved`) to it, but never over a value
|
||||
the user already has under the new id (`Settings.MoveModel`). Agents'
|
||||
files are not rewritten: an old `provider/<own id>` still resolves and is
|
||||
asked for as it is. A gateway key held to either id passes for both
|
||||
(`modelAllowed`). A group's `match` pattern is left as the user wrote it.
|
||||
Usage records the model by the listed id and `served` by the vendor's;
|
||||
the price is the own id's first (`ListPrice`). `TestModelIDListedAndAskedForByOwn`,
|
||||
`TestModelIDLatestWins`, `TestModelIDMovesTheUsersRefs`,
|
||||
`TestLocalModelIDOnEveryRoute`.
|
||||
|
||||
## Constraints and failure behavior
|
||||
|
||||
An allowance deliberately not requested (a saved Claude account outside
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A key held to a provider's model is held to it under the id it is
|
||||
// listed by (provider.SetModelID): the key's own "<provider>/<model>"
|
||||
// moves to the new id with the model, as the provider's picks and the
|
||||
// routing groups' refs do, so the user's limit keeps meaning that model.
|
||||
func init() { provider.ModelMoved = MoveModel }
|
||||
|
||||
// MoveModel gives every key's models that name from ("<provider>/<model>",
|
||||
// letter case aside) to instead. A pattern ("relay/*") is the user's own
|
||||
// and is left as written.
|
||||
func MoveModel(from, to string) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
keys, err := load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
changed := false
|
||||
for i := range keys {
|
||||
ms := keys[i].Models
|
||||
var out []string
|
||||
moved := false
|
||||
for _, m := range ms {
|
||||
if strings.EqualFold(m, from) {
|
||||
m, moved = to, true
|
||||
}
|
||||
if !containsFold(out, m) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
if moved {
|
||||
keys[i].Models, changed = out, true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
return save(keys)
|
||||
}
|
||||
|
||||
func containsFold(ms []string, m string) bool {
|
||||
for _, x := range ms {
|
||||
if strings.EqualFold(x, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -59,6 +59,17 @@ const modelUsage = `usage:
|
||||
id of its own for a provider that has since been deleted,
|
||||
and says when there was no name of its own to take away
|
||||
magpie model wires the names your vendors are asked for models by
|
||||
magpie model id <provider/model> the id magpie lists the model by, and the provider's own
|
||||
magpie model id <provider/model> <id> list the model by this id at that provider, e.g.
|
||||
relay-a/deepseek-v4.1-flash-1017 deepseek-v4.1-flash: agents,
|
||||
/v1/models, routing groups, the groups magpie finds, gateway keys
|
||||
and Usage all use it, and relay-a is still asked for
|
||||
deepseek-v4.1-flash-1017. One id is one model of a provider: the
|
||||
latest model given an id has it, and a model of the provider's
|
||||
own with that id is not listed while another is. A provider of
|
||||
your own (a key) only
|
||||
magpie model id <provider/model> --reset list it by the provider's own id again
|
||||
magpie model ids the models you list by an id of your own
|
||||
magpie model names the models you named or narrowed
|
||||
magpie model alias <model> <name> count the model's usage under another model id in Usage,
|
||||
Sessions and the usage summaries, e.g. deepseek-v4.1-flash
|
||||
@@ -139,6 +150,10 @@ func modelCmd(args []string) error {
|
||||
return modelSpec(args[1:])
|
||||
case "specs":
|
||||
return modelSpecs()
|
||||
case "id":
|
||||
return modelID(args[1:])
|
||||
case "ids":
|
||||
return modelIDs()
|
||||
case "alias":
|
||||
return modelUsageAlias(args[1:])
|
||||
case "aliases":
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// modelID is `magpie model id`: the id a provider's model is listed,
|
||||
// routed and counted by in magpie, while the provider is asked for it by
|
||||
// its own (provider.SetModelID).
|
||||
func modelID(args []string) error {
|
||||
if len(args) == 0 || len(args) > 2 {
|
||||
return fmt.Errorf("%s", modelUsage)
|
||||
}
|
||||
if slices.Contains([]string{"-h", "--help", "help"}, args[0]) {
|
||||
fmt.Println(modelUsage)
|
||||
return nil
|
||||
}
|
||||
p, model, err := modelRef(args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(args) == 1 {
|
||||
own := p.OwnModelID(model)
|
||||
if own == model {
|
||||
if local, ok := localOf(p, model); ok {
|
||||
fmt.Println(bold.Render(p.ID+"/"+local), muted.Render("· listed as "+local+" · "+p.ID+" is asked for "+model))
|
||||
return nil
|
||||
}
|
||||
fmt.Println(bold.Render(p.ID+"/"+model), muted.Render("· listed by its own id"))
|
||||
return nil
|
||||
}
|
||||
fmt.Println(bold.Render(p.ID+"/"+model), muted.Render("· "+p.ID+" is asked for "+own))
|
||||
return nil
|
||||
}
|
||||
id := strings.TrimSpace(args[1])
|
||||
if isReset(args[1:]) {
|
||||
id = ""
|
||||
}
|
||||
// the provider's own id of it, before it is listed anew
|
||||
own := p.OwnModelID(model)
|
||||
replaced, changed, err := provider.SetModelID(args[0], id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !changed {
|
||||
fmt.Println(muted.Render(p.ID + "/" + model + " is listed so already"))
|
||||
return nil
|
||||
}
|
||||
if id == "" || id == own {
|
||||
fmt.Println(bold.Render(p.ID+"/"+own), muted.Render("· listed by its own id again"))
|
||||
return nil
|
||||
}
|
||||
fmt.Println(bold.Render(p.ID+"/"+id), muted.Render("· listed, routed and counted so; "+p.ID+" is still asked for "+own))
|
||||
if replaced != "" {
|
||||
fmt.Println(muted.Render(" " + replaced + " had that id: it is listed by its own again"))
|
||||
}
|
||||
if n := strings.TrimSpace(settings.Load().ModelWires[p.ID+"/"+id]); n != "" {
|
||||
fmt.Println(muted.Render(" a wire name of yours is set for " + p.ID + "/" + id + ": it is asked for as " + n + " (magpie model wire --reset takes it off)"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// localOf is the id the user lists p's model of its own id own by.
|
||||
func localOf(p *provider.Provider, own string) (string, bool) {
|
||||
for local, o := range p.ModelIDs() {
|
||||
if o == own {
|
||||
return local, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// modelIDs is `magpie model ids`: every model listed by an id the user
|
||||
// gave it, with the provider's own.
|
||||
func modelIDs() error {
|
||||
ids := settings.Load().ModelIDs
|
||||
keys := slices.Sorted(maps.Keys(ids))
|
||||
w := 0
|
||||
for _, k := range keys {
|
||||
w = max(w, len(k))
|
||||
}
|
||||
n := 0
|
||||
for _, k := range keys {
|
||||
own := strings.TrimSpace(ids[k])
|
||||
if own == "" {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
fmt.Printf("%-*s %s\n", w, k, muted.Render("is asked for as ")+own)
|
||||
}
|
||||
if n == 0 {
|
||||
fmt.Println(muted.Render("no model is listed by an id of yours yet · magpie model id <provider/model> <id>"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// magpie model id lists a provider's model by an id of the user's, shows
|
||||
// it, lists every one under ids and takes it off with --reset; it refuses
|
||||
// a flag or a bad id taken as one, and a model the provider doesn't have.
|
||||
func TestModelIDCmd(t *testing.T) {
|
||||
groupsHome(t)
|
||||
out, err := runOut(t, "model", "ids")
|
||||
if err != nil || !strings.Contains(out, "no model is listed by an id of yours yet") {
|
||||
t.Fatalf("empty list: %q %v", out, err)
|
||||
}
|
||||
if out, err = runOut(t, "model", "id", "a/only-a", "solo"); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "still asked for only-a") {
|
||||
t.Fatalf("set: %q %v", out, err)
|
||||
}
|
||||
if got := settings.Load().ModelIDs; got["a/solo"] != "only-a" || len(got) != 1 {
|
||||
t.Fatalf("settings: %v", got)
|
||||
}
|
||||
p, err := provider.Find("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := provider.UpstreamName(*p, "solo"); got != "only-a" {
|
||||
t.Fatalf("a/solo is asked for as %s", got)
|
||||
}
|
||||
for _, ref := range []string{"a/solo", "a/only-a"} {
|
||||
if out, err = runOut(t, "model", "id", ref); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "asked for only-a") {
|
||||
t.Fatalf("show %s: %q %v", ref, out, err)
|
||||
}
|
||||
}
|
||||
if out, err = runOut(t, "model", "ids"); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "only-a") {
|
||||
t.Fatalf("list: %q %v", out, err)
|
||||
}
|
||||
for _, bad := range [][]string{
|
||||
{"model", "id", "a/solo", "--force"},
|
||||
{"model", "id", "a/solo", "two words"},
|
||||
{"model", "id", "a/nope", "x"},
|
||||
{"model", "id", "solo", "x"},
|
||||
} {
|
||||
if _, err := runOut(t, bad...); err == nil {
|
||||
t.Fatalf("took %v", bad)
|
||||
}
|
||||
}
|
||||
if out, err = runOut(t, "model", "id", "--help"); err != nil || !strings.Contains(out, "magpie model id <provider/model> <id>") {
|
||||
t.Fatalf("--help: %q %v", out, err)
|
||||
}
|
||||
if got := settings.Load().ModelIDs; len(got) != 1 {
|
||||
t.Fatalf("a refused id was written: %v", got)
|
||||
}
|
||||
if out, err = runOut(t, "model", "id", "a/solo", "--reset"); err != nil || !strings.Contains(out, "its own id again") {
|
||||
t.Fatalf("reset: %q %v", out, err)
|
||||
}
|
||||
if got := settings.Load().ModelIDs; got != nil {
|
||||
t.Fatalf("after reset: %v", got)
|
||||
}
|
||||
if out, err = runOut(t, "model", "id", "a/only-a"); err != nil || !strings.Contains(out, "listed by its own id") {
|
||||
t.Fatalf("show after reset: %q %v", out, err)
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ type wiresKey struct{}
|
||||
// only where something asks for one: a request refused before any name is
|
||||
// looked up pays for nothing.
|
||||
func withWires(r *http.Request) *http.Request {
|
||||
load := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires })
|
||||
load := sync.OnceValue(func() map[string]string { return settings.Shared().Wires() })
|
||||
return r.WithContext(context.WithValue(r.Context(), wiresKey{}, load))
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ func wiresOf(ctx context.Context) map[string]string {
|
||||
if load, ok := ctx.Value(wiresKey{}).(func() map[string]string); ok {
|
||||
return load()
|
||||
}
|
||||
return settings.Shared().ModelWires
|
||||
return settings.Shared().Wires()
|
||||
}
|
||||
|
||||
// standIn is StandIn's model for one magpie shows no entry for: not a
|
||||
@@ -1545,7 +1545,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov
|
||||
}
|
||||
// the names in force, read at most once however many candidates are
|
||||
// counted, and not at all where there are none
|
||||
wires := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires })
|
||||
wires := sync.OnceValue(func() map[string]string { return settings.Shared().Wires() })
|
||||
for i, c := range counts {
|
||||
res, err := s.forward(r.Context(), c.p, provider.Anthropic, "/v1/messages/count_tokens", rewriteModel(body, provider.UpstreamNameIn(wires(), c.p.ID, model)), r.Header)
|
||||
if tooMany := (*errRPM)(nil); errors.As(err, &tooMany) {
|
||||
|
||||
@@ -79,15 +79,27 @@ func allows(who access.Identity, ids ...string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// modelAllowed says the key may use provider p's model.
|
||||
// modelAllowed says the key may use provider p's model. A model the user lists by an id of their own (provider.SetModelID) is
|
||||
// the one model by either id, so a key held to one may use the other:
|
||||
// one written before the id was given, or an agent's old ref to the
|
||||
// provider's own id.
|
||||
func modelAllowed(who access.Identity, p provider.Provider, model string) bool {
|
||||
return allows(who, p.ID+"/"+model)
|
||||
if allows(who, p.ID+"/"+model) {
|
||||
return true
|
||||
}
|
||||
if own := p.OwnModelID(model); own != model {
|
||||
return allows(who, p.ID+"/"+own)
|
||||
}
|
||||
if local := p.ListedModelID(model); local != model {
|
||||
return allows(who, p.ID+"/"+local)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// memberAllowed says the key may use a routing group's member: the model,
|
||||
// or a group it is reached through that the key names.
|
||||
func memberAllowed(who access.Identity, m provider.Member) bool {
|
||||
return allows(who, append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...)
|
||||
return modelAllowed(who, m.Provider, m.Model) || len(m.Path) > 0 && allows(who, m.Path...)
|
||||
}
|
||||
|
||||
// groupNamed says the key names the routing group g itself.
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// listing is a relay that lists ids and answers each request with the
|
||||
// model it was asked for, recording it.
|
||||
func listing(t *testing.T, a *asked, ids ...string) *httptest.Server {
|
||||
t.Helper()
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/models") {
|
||||
var l struct {
|
||||
Data []map[string]string `json:"data"`
|
||||
}
|
||||
for _, id := range ids {
|
||||
l.Data = append(l.Data, map[string]string{"id": id})
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(l)
|
||||
return
|
||||
}
|
||||
var b struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&b)
|
||||
a.add(b.Model)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, `data: {"id":"x","model":`+strconv.Quote(b.Model)+
|
||||
`,"choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],`+
|
||||
`"usage":{"prompt_tokens":5,"completion_tokens":3}}`+"\n\n")
|
||||
io.WriteString(w, "data: [DONE]\n\n")
|
||||
}))
|
||||
t.Cleanup(s.Close)
|
||||
return s
|
||||
}
|
||||
|
||||
// A model the user lists by an id of their own (zeewell on X:
|
||||
// deepseek-v4.1-flash-1017 as deepseek-v4.1-flash, grok-4.6@500k as
|
||||
// grok-4.6) is that id on every route an agent reaches it by — the model
|
||||
// list, a request by provider/model, by the bare id through the group
|
||||
// magpie finds, both protocols, a gateway key held to it — and the relay
|
||||
// is asked for it by its own id, which the usage record keeps as served.
|
||||
func TestLocalModelIDOnEveryRoute(t *testing.T) {
|
||||
fresh(t)
|
||||
var seenA, seenB asked
|
||||
a := listing(t, &seenA, "deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k")
|
||||
b := listing(t, &seenB, "deepseek-v4.1-flash")
|
||||
for _, r := range []struct {
|
||||
id string
|
||||
url string
|
||||
ids []string
|
||||
}{
|
||||
{"relay-a", a.URL, []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}},
|
||||
{"relay-b", b.URL, []string{"deepseek-v4.1-flash"}},
|
||||
} {
|
||||
if err := provider.Save(provider.Provider{ID: r.id, Name: r.id, Key: "k", Chat: r.url}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ms []catalog.Model
|
||||
for _, id := range r.ids {
|
||||
ms = append(ms, catalog.Model{ID: id})
|
||||
}
|
||||
if err := catalog.SaveLive(r.id, r.url, ms); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
keys, secrets := newCaller(t, "Held")
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay-a/grok-4.6@500k"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for ref, id := range map[string]string{
|
||||
"relay-a/deepseek-v4.1-flash-1017": "deepseek-v4.1-flash",
|
||||
"relay-a/grok-4.6@500k": "grok-4.6",
|
||||
} {
|
||||
if _, _, err := provider.SetModelID(ref, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// the key's model went to the id it is listed by
|
||||
if ks, _ := access.List(); !slices.Equal(ks[len(ks)-1].Models, []string{"relay-a/grok-4.6"}) {
|
||||
t.Fatalf("the held key's models: %v", ks[len(ks)-1].Models)
|
||||
}
|
||||
|
||||
h := New().Handler()
|
||||
do := func(secret, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if secret != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
listed := func(secret string) []string {
|
||||
t.Helper()
|
||||
var l struct{ Data []struct{ ID string } }
|
||||
w := do(secret, "GET", "/v1/models", "")
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &l); err != nil {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
var ids []string
|
||||
for _, m := range l.Data {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
ids := listed("")
|
||||
for _, want := range []string{"relay-a/deepseek-v4.1-flash", "relay-a/grok-4.6", "relay-b/deepseek-v4.1-flash", "auto/deepseek-v4.1-flash"} {
|
||||
if !slices.Contains(ids, want) {
|
||||
t.Errorf("/v1/models has no %s: %v", want, ids)
|
||||
}
|
||||
}
|
||||
for _, own := range []string{"relay-a/deepseek-v4.1-flash-1017", "relay-a/grok-4.6@500k"} {
|
||||
if slices.Contains(ids, own) {
|
||||
t.Errorf("/v1/models lists %s by its own id: %v", own, ids)
|
||||
}
|
||||
}
|
||||
|
||||
chat := func(secret, model string) *httptest.ResponseRecorder {
|
||||
return do(secret, "POST", "/v1/chat/completions", `{"model":"`+model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
}
|
||||
messages := func(model string) *httptest.ResponseRecorder {
|
||||
return do("", "POST", "/v1/messages", `{"model":"`+model+`","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
what string
|
||||
send func() *httptest.ResponseRecorder
|
||||
seen *asked
|
||||
asked string
|
||||
model string // recorded
|
||||
}{
|
||||
{"chat relay-a/deepseek-v4.1-flash", func() *httptest.ResponseRecorder { return chat("", "relay-a/deepseek-v4.1-flash") }, &seenA, "deepseek-v4.1-flash-1017", "deepseek-v4.1-flash"},
|
||||
{"messages relay-a/grok-4.6", func() *httptest.ResponseRecorder { return messages("relay-a/grok-4.6") }, &seenA, "grok-4.6@500k", "grok-4.6"},
|
||||
{"an old ref by the own id", func() *httptest.ResponseRecorder { return chat("", "relay-a/deepseek-v4.1-flash-1017") }, &seenA, "deepseek-v4.1-flash-1017", "deepseek-v4.1-flash-1017"},
|
||||
{"relay-b's own", func() *httptest.ResponseRecorder { return chat("", "relay-b/deepseek-v4.1-flash") }, &seenB, "deepseek-v4.1-flash", "deepseek-v4.1-flash"},
|
||||
{"the held key's model", func() *httptest.ResponseRecorder { return chat(secrets[0], "relay-a/grok-4.6") }, &seenA, "grok-4.6@500k", "grok-4.6"},
|
||||
} {
|
||||
if w := c.send(); w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", c.what, w.Code, w.Body.String())
|
||||
}
|
||||
c.seen.wire(t, c.what, []string{c.asked})
|
||||
if u := lastUsage(t); u.Provider == "" || u.Model != c.model || u.Served != c.asked {
|
||||
t.Errorf("%s recorded as %s %s served %s, want %s served %s", c.what, u.Provider, u.Model, u.Served, c.model, c.asked)
|
||||
}
|
||||
}
|
||||
|
||||
// the bare id is the group magpie found over both relays
|
||||
gid, ok := provider.GroupFor("deepseek-v4.1-flash")
|
||||
if !ok {
|
||||
t.Fatal("no found group for deepseek-v4.1-flash")
|
||||
}
|
||||
_, ms, _ := provider.FindGroup(gid)
|
||||
var members []string
|
||||
for _, m := range ms {
|
||||
members = append(members, m.Provider.ID+"/"+m.Model)
|
||||
}
|
||||
slices.Sort(members)
|
||||
if want := []string{"relay-a/deepseek-v4.1-flash", "relay-b/deepseek-v4.1-flash"}; !slices.Equal(members, want) {
|
||||
t.Fatalf("%s has %v, want %v", gid, members, want)
|
||||
}
|
||||
if w := chat("", "deepseek-v4.1-flash"); w.Code != 200 {
|
||||
t.Fatalf("the bare id: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
got := append(seenA.all(), seenB.all()...)
|
||||
if len(got) != 1 || got[0] != "deepseek-v4.1-flash-1017" && got[0] != "deepseek-v4.1-flash" {
|
||||
t.Fatalf("the bare id asked %v", got)
|
||||
}
|
||||
|
||||
// the held key: shown only its model, refused another
|
||||
if ids := listed(secrets[0]); !slices.Contains(ids, "relay-a/grok-4.6") || slices.Contains(ids, "relay-a/deepseek-v4.1-flash") {
|
||||
t.Fatalf("the held key lists %v", ids)
|
||||
}
|
||||
if w := chat(secrets[0], "relay-a/deepseek-v4.1-flash"); w.Code == 200 {
|
||||
t.Fatal("the held key used a model it may not")
|
||||
}
|
||||
// a key held to the own id (written by hand, or before) is held to
|
||||
// the model by either id
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay-a/deepseek-v4.1-flash-1017"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := chat(secrets[0], "relay-a/deepseek-v4.1-flash"); w.Code != 200 {
|
||||
t.Fatalf("a key held to the own id: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w := chat(secrets[0], "relay-a/grok-4.6"); w.Code == 200 {
|
||||
t.Fatal("a key held to deepseek used grok")
|
||||
}
|
||||
}
|
||||
@@ -11580,6 +11580,24 @@ function renderModels(p) {
|
||||
same.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") same.blur(); else if (e.key === "Escape") { same.value = sameNow(); same.blur(); } };
|
||||
sameBox.append(el("span", "", t("Same as")), same);
|
||||
row.append(sameBox);
|
||||
// the id it is listed by here, asked for by its own (zeewell on X)
|
||||
const savedID = m.vendor ? m.id : "";
|
||||
const idNow = () => prefs[id]?.id ?? savedID;
|
||||
let idInput = null;
|
||||
if (m.ids) {
|
||||
const idBox = el("label", "msame mlocal");
|
||||
idInput = input(idNow(), m.vendor || m.id);
|
||||
idInput.title = t("The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id", { id: m.id, own: m.vendor || m.id });
|
||||
idInput.spellcheck = false;
|
||||
idInput.onchange = () => {
|
||||
const v = idInput.value.trim();
|
||||
if (v === savedID) delete pref().id; else pref().id = v;
|
||||
drawReset();
|
||||
};
|
||||
idInput.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") idInput.blur(); else if (e.key === "Escape") { idInput.value = idNow(); idInput.blur(); } };
|
||||
idBox.append(el("span", "", t("Listed as")), idInput);
|
||||
row.append(idBox);
|
||||
}
|
||||
// its cost to the user, $ per million tokens, as Usage counts it
|
||||
// (#819): a box empty is its list price. The 1-hour cache write,
|
||||
// empty, is 2× input as Anthropic bills it, and only a Claude model
|
||||
@@ -11781,7 +11799,7 @@ function renderModels(p) {
|
||||
const unsaved = el("span", "hint munsaved", t("unsaved"));
|
||||
unsaved.title = t("Made when the provider is saved; Cancel drops it");
|
||||
const reset = el("button", "text action", t("Restore default"));
|
||||
reset.title = t("Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price");
|
||||
reset.title = t("Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price");
|
||||
reset.onclick = () => {
|
||||
prefs[id] = {};
|
||||
if (draft.priceTyped) delete draft.priceTyped[id];
|
||||
@@ -11796,6 +11814,8 @@ function renderModels(p) {
|
||||
if (m.api) prefs[id].api = "";
|
||||
if (m.same) prefs[id].same = "";
|
||||
same.value = sameNow();
|
||||
if (savedID) prefs[id].id = "";
|
||||
if (idInput) idInput.value = idNow();
|
||||
if (m.price) prefs[id].ownPrice = true;
|
||||
showPrice();
|
||||
if (apiSeg) { for (const b of apiSeg.querySelectorAll(".opt")) b.classList.toggle("on", b.dataset.api === apiNow()); slide(apiSeg, "api"); }
|
||||
@@ -11807,7 +11827,7 @@ function renderModels(p) {
|
||||
unsaved.hidden = !prefs[id] && !draft.priceTyped?.[id];
|
||||
// staged back to its own already, there is nothing to restore
|
||||
const images = prefs[id]?.ownImages ? false : prefs[id]?.images !== undefined ? prefs[id].images !== !!m.ownImages : !!m.imageSet;
|
||||
const custom = nameNow() !== "" || noneNow() || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id];
|
||||
const custom = nameNow() !== "" || noneNow() || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || idNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id];
|
||||
reset.hidden = !custom;
|
||||
};
|
||||
row.append(unsaved, reset);
|
||||
|
||||
@@ -2450,7 +2450,7 @@ const I18N = {
|
||||
"Its reasoning levels aren't known: tick the ones it takes": "推理档位未知:勾选它支持的档位",
|
||||
"{id}: {levels}": "{id}:{levels}",
|
||||
"Restore default": "恢复默认",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢复默认名称、全部推理档位、是否支持图片、请求所用的协议、它等同的模型,以及官方价格",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "恢复默认名称、全部推理档位、是否支持图片、请求所用的协议、它等同的模型、它自己的 ID,以及官方价格",
|
||||
"What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} 的价格,单位为美元 / 百万 tokens,用量页按它计费;留空即官方价格(灰字所示)。这里设的价格不再乘以供应商的价格倍率",
|
||||
"Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "闲时价(官方价格或在此设置的价格):周一至周五 UTC 01:00–04:00 与 06:00–10:00{x},用量页按两倍计",
|
||||
", except on Chinese public holidays": "(中国法定节假日除外)",
|
||||
@@ -2459,6 +2459,8 @@ const I18N = {
|
||||
"{id} has no list price: give its input and output prices": "{id} 没有官方价格:请填写输入和输出价格",
|
||||
"A price is a number of dollars, 0 or more": "价格是 0 或以上的美元数",
|
||||
"Same as": "等同于",
|
||||
"Listed as": "列为",
|
||||
"The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie 在这个提供商列出 {id} 所用的 ID:智能体、路由组、magpie 找到的路由组、网关密钥和用量都用它,向提供商请求时仍用 {own}。留空:用它自己的 ID",
|
||||
"The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} 等同于其他供应商的哪个模型:自动发现的路由组会将它们合并;任何列表都没给出的 {id} 信息(上下文窗口、回复上限、推理档位、图片输入和标价)都按那个模型的来。留空则按自身 ID 合并",
|
||||
"The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} 请求所用的协议。自动:按供应商模型列表,否则依次尝试已填的各个地址;供应商仅在某协议上提供它时,选择该协议",
|
||||
"{id} is as its provider has it again": "{id} 已恢复为供应商的默认设置",
|
||||
@@ -6664,7 +6666,7 @@ const I18N = {
|
||||
"Its reasoning levels aren't known: tick the ones it takes": "推理檔位未知:勾選它支援的檔位",
|
||||
"{id}: {levels}": "{id}:{levels}",
|
||||
"Restore default": "恢復預設",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢復預設名稱、全部推理檔位、是否支援圖片、請求所用的協議、它等同的模型,以及官方價格",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "恢復預設名稱、全部推理檔位、是否支援圖片、請求所用的協議、它等同的模型、它自己的 ID,以及官方價格",
|
||||
"What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} 的價格,單位為美元 / 百萬 tokens,用量頁按它計費;留空即官方價格(灰字所示)。這裡設的價格不再乘以供應商的價格倍率",
|
||||
"Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "離峰價(官方價格或在此設定的價格):週一至週五 UTC 01:00–04:00 與 06:00–10:00{x},用量頁按兩倍計",
|
||||
", except on Chinese public holidays": "(中國法定節假日除外)",
|
||||
@@ -6673,6 +6675,8 @@ const I18N = {
|
||||
"{id} has no list price: give its input and output prices": "{id} 沒有官方價格:請填寫輸入和輸出價格",
|
||||
"A price is a number of dollars, 0 or more": "價格是 0 或以上的美元數",
|
||||
"Same as": "等同於",
|
||||
"Listed as": "列為",
|
||||
"The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie 在這個供應商列出 {id} 所用的 ID:智慧體、路由組、magpie 找到的路由組、閘道金鑰和用量都用它,向供應商請求時仍用 {own}。留空:用它自己的 ID",
|
||||
"The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} 等同於其他供應商的哪個模型:自動發現的路由組會將它們合併;任何列表都沒給出的 {id} 資訊(上下文視窗、回覆上限、推理檔位、圖片輸入和標價)都按那個模型的來。留空則按自身 ID 合併",
|
||||
"The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} 請求所用的協議。自動:按供應商模型列表,否則依次嘗試已填的各個位址;供應商僅在某協議上提供它時,選擇該協議",
|
||||
"{id} is as its provider has it again": "{id} 已恢復為供應商的預設設定",
|
||||
@@ -10896,7 +10900,7 @@ const I18N = {
|
||||
"Its reasoning levels aren't known: tick the ones it takes": "推論レベルが不明です。対応するものにチェックを入れてください",
|
||||
"{id}: {levels}": "{id}:{levels}",
|
||||
"Restore default": "デフォルトに戻す",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "元の名前、すべての推論レベル、画像対応の有無、リクエストに使う API、同じモデルの指定、公式価格",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "元の名前、すべての推論レベル、画像対応の有無、リクエストに使う API、同じモデルの指定、元の ID、公式価格",
|
||||
"What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} の価格(米ドル / 100 万トークン)。使用量ページはこれで計算します。空欄なら公式価格(灰色で表示)。ここで設定した価格にはプロバイダーの価格倍率は掛かりません",
|
||||
"Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "公式価格もここで設定した価格もオフピーク料金です。月曜から金曜の UTC 01:00–04:00 と 06:00–10:00{x}は、使用量ページで 2 倍として計算します",
|
||||
", except on Chinese public holidays": "(中国の法定休日を除く)",
|
||||
@@ -10905,6 +10909,8 @@ const I18N = {
|
||||
"{id} has no list price: give its input and output prices": "{id} には公式価格がありません:入力と出力の価格を入力してください",
|
||||
"A price is a number of dollars, 0 or more": "価格は 0 以上のドル金額です",
|
||||
"Same as": "同じモデル",
|
||||
"Listed as": "表示 ID",
|
||||
"The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie がこのプロバイダで {id} を一覧に出す ID:エージェント、ルーティンググループ、magpie が見つけるグループ、ゲートウェイキー、使用量はすべてこれを使い、プロバイダへのリクエストは {own} のままです。空欄:元の ID",
|
||||
"The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} と同じである、他のプロバイダが提供するモデルです。magpie が見つけるルーティンググループでまとめられ、どの一覧にもない {id} の情報(コンテキスト長、応答の上限、推論レベル、画像入力、定価)はそのモデルのものを使います。空欄:自身の ID で",
|
||||
"The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} へのリクエストに使う API です。自動:ベンダーの一覧に従い、なければプロバイダの各 URL を使います。ベンダーが特定の API でのみ提供している場合はそれを選んでください",
|
||||
"{id} is as its provider has it again": "{id} はプロバイダの設定どおりに戻りました",
|
||||
@@ -15139,7 +15145,7 @@ const I18N = {
|
||||
"Its reasoning levels aren't known: tick the ones it takes": "Seine Reasoning-Stufen sind unbekannt: Kreuzen Sie die unterstützten an",
|
||||
"{id}: {levels}": "{id}: {levels}",
|
||||
"Restore default": "Standard wiederherstellen",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "Eigener Name, alle Reasoning-Stufen, Bildunterstützung, die angefragte API, das Modell, dem es entspricht, und der Listenpreis",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "Eigener Name, alle Reasoning-Stufen, Bildunterstützung, die angefragte API, das Modell, dem es entspricht, die eigene ID und der Listenpreis",
|
||||
"What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "Was {id} kostet, in US-Dollar pro Million Tokens, wie die Nutzungsseite rechnet; leer: der Listenpreis (grau). Ein hier gesetzter Preis wird nicht mit dem Preisfaktor des Anbieters multipliziert",
|
||||
"Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "Listenpreis oder hier gesetzter Preis gilt außerhalb der Spitzenzeit: Montag bis Freitag von 01:00 bis 04:00 und 06:00 bis 10:00 UTC{x} zählt ihn die Nutzungsseite doppelt",
|
||||
", except on Chinese public holidays": ", außer an chinesischen Feiertagen,",
|
||||
@@ -15148,6 +15154,8 @@ const I18N = {
|
||||
"{id} has no list price: give its input and output prices": "{id} hat keinen Listenpreis: gib Eingabe- und Ausgabepreis an",
|
||||
"A price is a number of dollars, 0 or more": "Ein Preis ist ein Dollarbetrag ab 0",
|
||||
"Same as": "Entspricht",
|
||||
"Listed as": "Gelistet als",
|
||||
"The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "Die ID, unter der magpie {id} bei diesem Anbieter listet: Agenten, Routing-Gruppen, die von magpie gefundenen Gruppen, Gateway-Schlüssel und die Nutzung verwenden sie, und beim Anbieter wird weiterhin {own} angefragt. Leer: die eigene ID",
|
||||
"The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "Das Modell anderer Anbieter, dem {id} entspricht: Die von magpie gefundenen Weiterleitungsgruppen fassen sie zusammen, und was keine Liste für {id} angibt, wird von diesem Modell übernommen: Kontextfenster, Antwortlimit, Denkstufen, Bildeingabe und Listenpreis. Leer: nach eigener ID",
|
||||
"The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "Die API, über die {id} angefragt wird. Automatisch: laut Modellliste des Anbieters, sonst jede hinterlegte URL; wählen Sie eine, wenn der Anbieter es nur dort bereitstellt",
|
||||
"{id} is as its provider has it again": "{id} entspricht wieder der Vorgabe seines Anbieters",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -57,6 +57,11 @@ type modelJSON struct {
|
||||
Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583)
|
||||
Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing
|
||||
Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399)
|
||||
// Vendor is the provider's own id of a model the user lists by
|
||||
// another (provider.SetModelID), "" for one listed by its own; IDs
|
||||
// says the provider's models can be given ids at all (a key's)
|
||||
Vendor string `json:"vendor,omitempty"`
|
||||
IDs bool `json:"ids,omitempty"`
|
||||
// Desktop is the number Claude Desktop's menu says beside this model
|
||||
// (gateway.DesktopNumber), so a row of that menu can be matched to its
|
||||
// provider (#2578): only for a model Claude Desktop, installed here,
|
||||
@@ -822,6 +827,10 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string
|
||||
}
|
||||
j.NoAPI = p.NoAPIFor(m.ID)
|
||||
j.Same = sames[p.ID+"/"+m.ID]
|
||||
if own := p.OwnModelID(m.ID); own != m.ID {
|
||||
j.Vendor = own
|
||||
}
|
||||
j.IDs = p.TakesModelIDs()
|
||||
j.Kind = p.ModelKind(m.ID)
|
||||
j.Merge = provider.MergeName(m.ID)
|
||||
j.Desktop = desktop[p.ID+"/"+m.ID]
|
||||
|
||||
@@ -133,6 +133,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
ModelWires: map[string]string{"p/m": "vendor-c/m"},
|
||||
ModelAPIs: map[string]string{"p/m": "anthropic"},
|
||||
ModelSameAs: map[string]string{"p/m": "deepseek-v4.1-flash"},
|
||||
ModelIDs: map[string]string{"p/flash": "deepseek-v4.1-flash-1017"},
|
||||
UsageAliases: map[string]string{"deepseek-v4.1-flash": "deepseek-flash"},
|
||||
UsageCleared: []settings.UsageClear{{Provider: "p", Model: "m", At: 1761600000000}},
|
||||
ModelKinds: map[string]string{"p/m": "video"},
|
||||
|
||||
@@ -151,7 +151,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
"Taken · save to keep", "Ask {model} on {api} only", "Staged in Names & levels and made with the Save; Auto there gives it back", "{model} is asked on {api} once saved",
|
||||
"no URL to ask", "no model to try: type one the vendor serves", "no key is on for this endpoint",
|
||||
"The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price",
|
||||
].filter((k) => !I18N.zh[k]));
|
||||
assert.deepEqual(missing, [], "every string has its Chinese");
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// A relay's model can be listed by an id of the user's (zeewell on X:
|
||||
// deepseek-v4.1-flash-1017 as deepseek-v4.1-flash), in the provider
|
||||
// editor's Names & levels beside Same as: magpie lists, routes and counts
|
||||
// it by that id, and the relay is still asked for its own. It is staged
|
||||
// and made with the editor's Save, as the rest of Names & levels is;
|
||||
// Restore default and an emptied box list it by its own id again. A
|
||||
// signed-in account's models (ids false) have no such box.
|
||||
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 assets = path.resolve(__dirname, "../assets");
|
||||
const levels = ["none", "low", "medium", "high"];
|
||||
|
||||
function serve(lang, posts) {
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
const models = [
|
||||
{ id: "deepseek-v4.1-flash-1017", name: "deepseek-v4.1-flash-1017", on: true, efforts: levels, images: false, merge: "deepseek-v4-1-flash-1017", ids: true },
|
||||
{ id: "grok-4.6", name: "grok-4.6", on: true, efforts: levels, images: false, merge: "grok-4-6", ids: true, vendor: "grok-4.6@500k" },
|
||||
];
|
||||
const relay = { id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example/v1", responses: "", anthropic: "", models, agents: [], key: { set: true, masked: "sk-…1234" }, ready: true };
|
||||
const acct = { id: "acct", name: "Acct", icon: "generic", chat: "https://acct.example/v1", responses: "", anthropic: "", models: [{ id: "m1", name: "m1", on: true, efforts: levels, images: false, merge: "m1" }], agents: [], key: { set: true, masked: "sk-…9999" }, ready: true };
|
||||
const providers = { providers: [relay, acct], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/")) {
|
||||
posts.push({ path: url.pathname, body: route.request().postDataJSON() });
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
|
||||
};
|
||||
}
|
||||
|
||||
const keys = ["Names & levels", "Listed as", "unsaved", "Save", "Restore default"];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
test(`${engine} ${lang}: the id a model is listed by is staged and made with the provider's Save`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 720 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.waitForFunction(() => typeof I18N === "object");
|
||||
const L = Object.fromEntries(await page.evaluate(([lang, keys]) => keys.map((k) => [k, lang === "en" ? k : I18N[lang][k]]), [lang, keys]));
|
||||
for (const k of keys) assert(L[k], `${lang} has ${k}`);
|
||||
const open = async (id) => {
|
||||
await page.locator(`.row.provider[data-id="${id}"]`).click();
|
||||
if (!(await page.locator(".mnames:not([hidden])").count())) await page.getByRole("button", { name: L["Names & levels"], exact: true }).click();
|
||||
};
|
||||
const row = (id) => page.locator(".mname", { has: page.locator("code", { hasText: id }) });
|
||||
const box = (id) => row(id).getByRole("textbox", { name: L["Listed as"], exact: true });
|
||||
await open("relay");
|
||||
// empty, it is its own id; one given shows, the own id beneath it
|
||||
assert.equal(await box("deepseek-v4.1-flash-1017").inputValue(), "");
|
||||
assert.equal(await box("deepseek-v4.1-flash-1017").getAttribute("placeholder"), "deepseek-v4.1-flash-1017");
|
||||
assert.equal(await box("grok-4.6").inputValue(), "grok-4.6");
|
||||
assert.equal(await box("grok-4.6").getAttribute("placeholder"), "grok-4.6@500k");
|
||||
const list = await page.locator(".mnames:not([hidden])").elementHandle();
|
||||
const y = await page.evaluate(() => scrollY);
|
||||
await box("deepseek-v4.1-flash-1017").fill("deepseek-v4.1-flash");
|
||||
await box("deepseek-v4.1-flash-1017").press("Enter");
|
||||
await row("grok-4.6").getByRole("button", { name: L["Restore default"] }).click();
|
||||
await page.waitForTimeout(200);
|
||||
assert.deepEqual(posts, [], "nothing is sent before the Save");
|
||||
assert(await list.evaluate((e) => e.isConnected), "the list is not redrawn");
|
||||
assert.equal(await page.evaluate(() => scrollY), y, "nothing scrolls the page");
|
||||
assert.equal(await box("grok-4.6").inputValue(), "", "Restore default empties it");
|
||||
for (const id of ["deepseek-v4.1-flash-1017", "grok-4.6"]) assert(await row(id).getByText(L.unsaved, { exact: true }).isVisible(), id + " says it is unsaved");
|
||||
// the box sits in the row as Same as does, no wider than the row
|
||||
const fits = await row("grok-4.6").evaluate((r) => [...r.querySelectorAll("input")].every((i) => i.getBoundingClientRect().right <= r.getBoundingClientRect().right + 1));
|
||||
assert(fits, "the box fits its row");
|
||||
await page.getByRole("button", { name: L.Save, exact: true }).click();
|
||||
await page.waitForFunction(() => !document.querySelector(".mnames"));
|
||||
assert.deepEqual(posts.map((p) => p.path), ["/api/provider/save"]);
|
||||
assert.deepEqual(posts[0].body.modelPrefs["deepseek-v4.1-flash-1017"], { id: "deepseek-v4.1-flash" });
|
||||
assert.equal(posts[0].body.modelPrefs["grok-4.6"].id, "");
|
||||
// an account's models take none
|
||||
await open("acct");
|
||||
assert.equal(await row("m1").getByRole("textbox", { name: L["Listed as"], exact: true }).count(), 0);
|
||||
const missing = await page.evaluate(() => ["Listed as",
|
||||
"The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price",
|
||||
].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => `${l}: ${k}`)));
|
||||
assert.deepEqual(missing, [], "every string has every language");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(posts[0].body.modelPrefs, { "deepseek-v4-1-flash-260910": { same: "deepseek-v4.1-flash" }, "ep-2026-sol": { same: "" } });
|
||||
const missing = await page.evaluate(() => ["Same as",
|
||||
"The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price",
|
||||
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price",
|
||||
].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => `${l}: ${k}`)));
|
||||
assert.deepEqual(missing, [], "every string has every language");
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A model can be listed at its provider by an id the user gives it
|
||||
// (settings' ModelIDs), for a provider that serves one model under ids of
|
||||
// its own (zeewell on X: deepseek-v4.1-flash-1017 at one relay,
|
||||
// grok-4.6@500k at another). Everything magpie lists, picks, groups, finds
|
||||
// routing groups by, limits a gateway key to and records usage under is
|
||||
// that id; a request for it goes out under the provider's own, through
|
||||
// the same wire names (settings' Wires) a ModelWires name goes out by.
|
||||
// It is ModelWires turned round: a wire keeps magpie's id and changes the
|
||||
// one sent, this keeps the one sent and changes magpie's.
|
||||
//
|
||||
// Only a provider of the user's own (a key) takes one: an account's or a
|
||||
// plugin's requests are built by its own backend or plugin from the id it
|
||||
// lists, which no wire name reaches.
|
||||
|
||||
// localIDs are the ids the user lists a provider's models by: from the
|
||||
// provider's own id to the one the user gave, and back.
|
||||
type localIDs struct {
|
||||
local map[string]string // own id → the id it is listed by
|
||||
own map[string]string // the id it is listed by → own id
|
||||
}
|
||||
|
||||
// modelIDsOf are the ids the user gave the provider pid's models.
|
||||
func modelIDsOf(pid string) localIDs {
|
||||
return idsIn(settings.SharedModelIDs(), pid)
|
||||
}
|
||||
|
||||
func idsIn(all map[string]string, pid string) localIDs {
|
||||
var l localIDs
|
||||
if len(all) == 0 {
|
||||
return l
|
||||
}
|
||||
for k, own := range all {
|
||||
model, ok := strings.CutPrefix(k, pid+"/")
|
||||
own = strings.TrimSpace(own)
|
||||
if !ok || model == "" || own == "" || own == model {
|
||||
continue
|
||||
}
|
||||
if l.local == nil {
|
||||
l.local, l.own = map[string]string{}, map[string]string{}
|
||||
}
|
||||
// two ids given one model (a hand-edited file): the first, in
|
||||
// order, is its
|
||||
if had, ok := l.local[own]; ok && had < model {
|
||||
continue
|
||||
}
|
||||
if had, ok := l.local[own]; ok {
|
||||
delete(l.own, had)
|
||||
}
|
||||
l.local[own], l.own[model] = model, own
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func (l localIDs) none() bool { return len(l.own) == 0 }
|
||||
|
||||
// ownOf is the provider's own id of the model listed as model.
|
||||
func (l localIDs) ownOf(model string) string {
|
||||
if own, ok := l.own[model]; ok {
|
||||
return own
|
||||
}
|
||||
return model
|
||||
}
|
||||
|
||||
// list is ms with each model given an id listed by the id the user gave
|
||||
// it, and a model of the provider's own id one of those is given left
|
||||
// out while the model given it is listed (the one id is one model).
|
||||
func (l localIDs) list(ms []catalog.Model) []catalog.Model {
|
||||
if l.none() || len(ms) == 0 {
|
||||
return ms
|
||||
}
|
||||
has := make(map[string]bool, len(ms))
|
||||
for _, m := range ms {
|
||||
has[m.ID] = true
|
||||
}
|
||||
out := make([]catalog.Model, 0, len(ms))
|
||||
seen := make(map[string]bool, len(ms))
|
||||
for _, m := range ms {
|
||||
if local, ok := l.local[m.ID]; ok {
|
||||
if m.Name == "" || m.Name == m.ID {
|
||||
m.Name = local
|
||||
}
|
||||
m.ID = local
|
||||
} else if own, ok := l.own[m.ID]; ok && has[own] {
|
||||
continue // listed by the model given its id
|
||||
}
|
||||
if seen[m.ID] {
|
||||
continue
|
||||
}
|
||||
seen[m.ID] = true
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ids is set (of the provider's own ids) with each given another id by it.
|
||||
func (l localIDs) ids(set map[string]bool) map[string]bool {
|
||||
if l.none() {
|
||||
return set
|
||||
}
|
||||
out := make(map[string]bool, len(set))
|
||||
for id := range set {
|
||||
if _, ok := l.local[id]; ok {
|
||||
continue
|
||||
}
|
||||
if own, ok := l.own[id]; ok && set[own] {
|
||||
continue
|
||||
}
|
||||
out[id] = true
|
||||
}
|
||||
for own, local := range l.local {
|
||||
if set[own] {
|
||||
out[local] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// takesModelIDs is whether the user can list p's models by ids of their
|
||||
// own: a provider of theirs, whose requests carry a wire name.
|
||||
func (p Provider) takesModelIDs() bool { return p.Account == nil }
|
||||
|
||||
// TakesModelIDs is whether p's models can be listed by ids the user gives
|
||||
// them (SetModelID): a provider of the user's own, not an account's or a
|
||||
// plugin's.
|
||||
func (p Provider) TakesModelIDs() bool { return p.takesModelIDs() }
|
||||
|
||||
// ids are the ids the user gave p's models, none for a provider that
|
||||
// takes none.
|
||||
func (p Provider) ids() localIDs {
|
||||
if !p.takesModelIDs() {
|
||||
return localIDs{}
|
||||
}
|
||||
return modelIDsOf(p.ID)
|
||||
}
|
||||
|
||||
// OwnModelID is the provider's own id of its model listed as model: the
|
||||
// id the vendor is asked for it by, the same as model unless the user
|
||||
// lists it by another (SetModelID).
|
||||
func (p Provider) OwnModelID(model string) string { return p.ids().ownOf(model) }
|
||||
|
||||
// ListedModelID is the id p lists its model of its own id own by: the one
|
||||
// the user gave it, else own.
|
||||
func (p Provider) ListedModelID(own string) string {
|
||||
if local, ok := p.ids().local[own]; ok {
|
||||
return local
|
||||
}
|
||||
return own
|
||||
}
|
||||
|
||||
// ModelIDs are the ids the user lists p's models by, from each one to the
|
||||
// provider's own id of it.
|
||||
func (p Provider) ModelIDs() map[string]string {
|
||||
out := map[string]string{}
|
||||
for local, own := range p.ids().own {
|
||||
out[local] = own
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// rawIDs are the ids of the models the provider itself lists for chat,
|
||||
// before any is listed by another id, and those the user picked that its
|
||||
// list doesn't have (typed in, or not fetched yet).
|
||||
func (p Provider) rawIDs() map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, m := range p.available() {
|
||||
out[m.ID] = true
|
||||
}
|
||||
for _, id := range p.Models {
|
||||
if _, given := p.ids().own[id]; !given {
|
||||
out[id] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// checkModelID is why id can't be one a model is listed by, if it can't.
|
||||
func checkModelID(id string) error {
|
||||
switch {
|
||||
case id == "*" || strings.Contains(id, "*"):
|
||||
return errors.New(`a model's id can't have "*" in it`)
|
||||
case strings.HasPrefix(id, "-"):
|
||||
return fmt.Errorf("a model's id can't start with -, not %q", id)
|
||||
case strings.IndexFunc(id, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0:
|
||||
return fmt.Errorf("a model's id has no spaces in it, not %q", id)
|
||||
case IsGroupRef(id):
|
||||
return errors.New("that is a routing group's id, not a model's")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetModelID lists a provider's model, spelled "provider/model" by the id
|
||||
// it is listed by now or by the provider's own, by id instead, and says
|
||||
// which of its models had the id before (replaced) and whether anything
|
||||
// changed: what
|
||||
// magpie lists, picks, groups, routes and records it by, while the
|
||||
// provider is still asked for it by its own id. A blank id, or the
|
||||
// provider's own, lists it by its own again.
|
||||
//
|
||||
// One id is one model of a provider, so an id already given another of its
|
||||
// models is that model's no more, which it answers (the latest one given
|
||||
// it wins): that model is listed by its own id again. A model of the
|
||||
// provider's own id is not listed while another is listed by it, and an
|
||||
// agent's or a group's ref to the id reaches the model given it.
|
||||
//
|
||||
// What the user picked, grouped, set and said of the model goes with it to
|
||||
// the new id: its picks, a key's models, its context, the routing groups'
|
||||
// refs and fallbacks, the pickers' lists and every per-model setting — but
|
||||
// a setting the user already has under the new id, which stays theirs.
|
||||
// Agents' own files are not rewritten: a "provider/<own id>" they still
|
||||
// name resolves, and is asked for under that id (Resolve).
|
||||
func SetModelID(ref, id string) (replaced string, changed bool, err error) {
|
||||
replaced, changed, err = setModelID(ref, id)
|
||||
return replaced, changed, touchedIf(changed, err)
|
||||
}
|
||||
|
||||
func setModelID(ref, id string) (string, bool, error) {
|
||||
p, model, err := splitRef(ref)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if !p.takesModelIDs() {
|
||||
return "", false, fmt.Errorf("%s is a signed-in account or a plugin's: its requests ask for the id its list gives, so its models can't be listed by another", p.Name)
|
||||
}
|
||||
id = strings.TrimSpace(id)
|
||||
if id != "" {
|
||||
if err := checkModelID(id); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
}
|
||||
s := settings.Load()
|
||||
ids := idsIn(s.ModelIDs, p.ID)
|
||||
raw := p.rawIDs()
|
||||
// model is the id it is listed by now, or the provider's own
|
||||
cur, own := model, ids.ownOf(model)
|
||||
if own == model {
|
||||
if local, ok := ids.local[model]; ok {
|
||||
cur = local
|
||||
} else if !raw[model] {
|
||||
return "", false, fmt.Errorf("%s has no model %s (magpie provider %s lists them)", p.ID, model, p.ID)
|
||||
}
|
||||
}
|
||||
if id == "" {
|
||||
id = own
|
||||
}
|
||||
if id == cur {
|
||||
return "", false, nil
|
||||
}
|
||||
var replaced string
|
||||
if had, ok := ids.own[id]; ok && had != own {
|
||||
// the latest model given the id has it
|
||||
replaced = had
|
||||
}
|
||||
if s.ModelIDs == nil {
|
||||
s.ModelIDs = map[string]string{}
|
||||
}
|
||||
delete(s.ModelIDs, p.ID+"/"+cur)
|
||||
for k, v := range s.ModelIDs {
|
||||
// any other id the model went by (a hand-edited file)
|
||||
if strings.HasPrefix(k, p.ID+"/") && strings.TrimSpace(v) == own {
|
||||
delete(s.ModelIDs, k)
|
||||
}
|
||||
}
|
||||
if id != own {
|
||||
s.ModelIDs[p.ID+"/"+id] = own
|
||||
}
|
||||
if len(s.ModelIDs) == 0 {
|
||||
s.ModelIDs = nil
|
||||
}
|
||||
if err := moveModelRefs(p.ID, cur, id); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
s.MoveModel(p.ID+"/"+cur, p.ID+"/"+id)
|
||||
moveModelLists(&s, p.ID+"/"+cur, p.ID+"/"+id)
|
||||
if err := settings.Save(s); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if ModelMoved != nil {
|
||||
if err := ModelMoved(p.ID+"/"+cur, p.ID+"/"+id); err != nil {
|
||||
return replaced, true, err
|
||||
}
|
||||
}
|
||||
return replaced, true, nil
|
||||
}
|
||||
|
||||
// ModelMoved, when set, gives what another package keeps of a provider's
|
||||
// model ("<provider>/<model>") the id it is listed by now (SetModelID): the
|
||||
// gateway keys' models (access), which this package can't reach.
|
||||
var ModelMoved func(from, to string) error
|
||||
|
||||
// moveModelRefs gives every ref the providers file keeps to the provider
|
||||
// pid's model from as to: its picks, those set aside and listed when
|
||||
// picked, a key's models and its context, the fallbacks and the routing
|
||||
// groups' refs.
|
||||
func moveModelRefs(pid, from, to string) error {
|
||||
f, err := read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(f.Providers, func(q Provider) bool { return q.ID == pid })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("no provider %q", pid)
|
||||
}
|
||||
q := &f.Providers[i]
|
||||
moved := func(ids []string) []string {
|
||||
if !slices.Contains(ids, from) {
|
||||
return ids
|
||||
}
|
||||
out := make([]string, 0, len(ids))
|
||||
for _, m := range ids {
|
||||
if m == from {
|
||||
m = to
|
||||
}
|
||||
if !slices.Contains(out, m) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
q.Models, q.PickedFrom, q.Delisted = moved(q.Models), moved(q.PickedFrom), moved(q.Delisted)
|
||||
for k, ms := range q.AccountModels {
|
||||
q.AccountModels[k] = moved(ms)
|
||||
}
|
||||
if n, ok := q.Contexts[from]; ok {
|
||||
if _, has := q.Contexts[to]; !has {
|
||||
q.Contexts[to] = n
|
||||
}
|
||||
delete(q.Contexts, from)
|
||||
}
|
||||
ref := func(m string) string {
|
||||
pre, rest := "", m
|
||||
if r, ok := strings.CutPrefix(m, "magpie/"); ok {
|
||||
pre, rest = "magpie/", r
|
||||
}
|
||||
if rest == pid+"/"+from {
|
||||
return pre + pid + "/" + to
|
||||
}
|
||||
return m
|
||||
}
|
||||
mapModelRefs(&f, ref)
|
||||
return store(f)
|
||||
}
|
||||
|
||||
// moveModelLists gives the pickers' lists of the settings (hidden, picked
|
||||
// for an agent, ordered, fast, Ultrafast) the model from as to.
|
||||
func moveModelLists(s *settings.Settings, from, to string) {
|
||||
for _, m := range []map[string][]string{s.HiddenModels, s.PickedModels, s.OrderedModels, s.FastPicks, s.UltraPicks} {
|
||||
for k, ids := range m {
|
||||
if !slices.Contains(ids, from) {
|
||||
continue
|
||||
}
|
||||
out := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id == from {
|
||||
id = to
|
||||
}
|
||||
if !slices.Contains(out, id) {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
m[k] = out
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// localIDHome is two relays of the user's own (zeewell on X): relay-a lists
|
||||
// deepseek-v4.1-flash-1017 and both grok-4.6 and grok-4.6@500k, relay-b
|
||||
// deepseek-v4.1-flash.
|
||||
func localIDHome(t *testing.T) {
|
||||
t.Helper()
|
||||
azureHome(t)
|
||||
for _, r := range []struct {
|
||||
id string
|
||||
ids []string
|
||||
}{
|
||||
{"relay-a", []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}},
|
||||
{"relay-b", []string{"deepseek-v4.1-flash"}},
|
||||
} {
|
||||
base := "https://" + r.id + ".example.invalid/v1"
|
||||
if err := Save(Provider{ID: r.id, Name: r.id, Key: "sk-" + r.id, Chat: base}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ms []catalog.Model
|
||||
for _, id := range r.ids {
|
||||
ms = append(ms, catalog.Model{ID: id})
|
||||
}
|
||||
if err := catalog.SaveLive(r.id, base, ms); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func findProvider(t *testing.T, id string) Provider {
|
||||
t.Helper()
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
func modelIDList(ms []catalog.Model) []string {
|
||||
var out []string
|
||||
for _, m := range ms {
|
||||
out = append(out, m.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func setID(t *testing.T, ref, id string) string {
|
||||
t.Helper()
|
||||
replaced, changed, err := SetModelID(ref, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !changed {
|
||||
t.Fatalf("SetModelID(%q, %q) changed nothing", ref, id)
|
||||
}
|
||||
return replaced
|
||||
}
|
||||
|
||||
// A model given an id is listed, resolved, found in a group with the
|
||||
// other relay's model of that id, and asked for by its own id.
|
||||
func TestModelIDListedAndAskedForByOwn(t *testing.T) {
|
||||
localIDHome(t)
|
||||
setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash")
|
||||
setID(t, "relay-a/grok-4.6@500k", "grok-4.6")
|
||||
|
||||
a := findProvider(t, "relay-a")
|
||||
// grok-4.6 of relay-a's own is not listed while @500k is listed by it
|
||||
if got, want := modelIDList(a.Available()), []string{"deepseek-v4.1-flash", "grok-4.6"}; !slices.Equal(got, want) {
|
||||
t.Fatalf("relay-a lists %v, want %v", got, want)
|
||||
}
|
||||
for local, own := range map[string]string{"deepseek-v4.1-flash": "deepseek-v4.1-flash-1017", "grok-4.6": "grok-4.6@500k"} {
|
||||
if got := a.OwnModelID(local); got != own {
|
||||
t.Errorf("OwnModelID(%s) = %s, want %s", local, got, own)
|
||||
}
|
||||
if got := UpstreamName(a, local); got != own {
|
||||
t.Errorf("UpstreamName(%s) = %s, want %s: the vendor is asked for its own id", local, got, own)
|
||||
}
|
||||
p, model, ok := Resolve("relay-a/" + local)
|
||||
if !ok || p.ID != "relay-a" || model != local {
|
||||
t.Errorf("Resolve(relay-a/%s) = %s %s %v", local, p.ID, model, ok)
|
||||
}
|
||||
}
|
||||
// an agent's old ref to the own id still resolves, asked for as is
|
||||
if p, model, ok := Resolve("relay-a/deepseek-v4.1-flash-1017"); !ok || p.ID != "relay-a" || UpstreamName(p, model) != "deepseek-v4.1-flash-1017" {
|
||||
t.Errorf("old ref: %s %s %v", p.ID, model, ok)
|
||||
}
|
||||
// relay-b's model of its own id is unchanged
|
||||
if got := UpstreamName(findProvider(t, "relay-b"), "deepseek-v4.1-flash"); got != "deepseek-v4.1-flash" {
|
||||
t.Errorf("relay-b asked for %s", got)
|
||||
}
|
||||
|
||||
// the found group has both relays under the one id
|
||||
gid, ok := GroupFor("deepseek-v4.1-flash")
|
||||
if !ok {
|
||||
t.Fatal("no found group for deepseek-v4.1-flash")
|
||||
}
|
||||
_, ms, ok := FindGroup(gid)
|
||||
if !ok {
|
||||
t.Fatalf("FindGroup(%s)", gid)
|
||||
}
|
||||
var members []string
|
||||
for _, m := range ms {
|
||||
members = append(members, m.Provider.ID+"/"+m.Model)
|
||||
}
|
||||
slices.Sort(members)
|
||||
if want := []string{"relay-a/deepseek-v4.1-flash", "relay-b/deepseek-v4.1-flash"}; !slices.Equal(members, want) {
|
||||
t.Fatalf("%s has %v, want %v", gid, members, want)
|
||||
}
|
||||
|
||||
// reset: listed by its own id again, nothing left in the settings
|
||||
if _, changed, err := SetModelID("relay-a/deepseek-v4.1-flash", ""); err != nil || !changed {
|
||||
t.Fatalf("reset: %v %v", changed, err)
|
||||
}
|
||||
if _, changed, err := SetModelID("relay-a/grok-4.6", "--reset"); err == nil || changed {
|
||||
t.Fatalf("a flag taken as an id: %v %v", changed, err)
|
||||
}
|
||||
setID(t, "relay-a/grok-4.6", "grok-4.6@500k")
|
||||
if got := modelIDList(findProvider(t, "relay-a").Available()); !slices.Equal(got, []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}) {
|
||||
t.Fatalf("after reset relay-a lists %v", got)
|
||||
}
|
||||
if ids := settings.Load().ModelIDs; len(ids) != 0 {
|
||||
t.Fatalf("after reset ModelIDs = %v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// One id is one model of a provider: the latest given it has it, and the
|
||||
// one before is listed by its own id again.
|
||||
func TestModelIDLatestWins(t *testing.T) {
|
||||
localIDHome(t)
|
||||
setID(t, "relay-a/grok-4.6@500k", "grok")
|
||||
if replaced := setID(t, "relay-a/deepseek-v4.1-flash-1017", "grok"); replaced != "grok-4.6@500k" {
|
||||
t.Fatalf("replaced %q, want grok-4.6@500k", replaced)
|
||||
}
|
||||
a := findProvider(t, "relay-a")
|
||||
if got, want := modelIDList(a.Available()), []string{"grok", "grok-4.6", "grok-4.6@500k"}; !slices.Equal(got, want) {
|
||||
t.Fatalf("relay-a lists %v, want %v", got, want)
|
||||
}
|
||||
if got := a.OwnModelID("grok"); got != "deepseek-v4.1-flash-1017" {
|
||||
t.Fatalf("grok is %s", got)
|
||||
}
|
||||
|
||||
// two rows of one save can't take one id
|
||||
if err := SetModelPrefs("relay-a", map[string]ModelPref{
|
||||
"grok-4.6": {ID: refOf("x")},
|
||||
"grok-4.6@500k": {ID: refOf("x")},
|
||||
}); err == nil || !strings.Contains(err.Error(), "can't both be listed as x") {
|
||||
t.Fatalf("SetModelPrefs with one id twice: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func refOf[T any](v T) *T { return &v }
|
||||
|
||||
// What the user picked, grouped and set of the model goes to its new id,
|
||||
// but a value they already have under that id stays theirs.
|
||||
func TestModelIDMovesTheUsersRefs(t *testing.T) {
|
||||
localIDHome(t)
|
||||
a := findProvider(t, "relay-a")
|
||||
a.Models = []string{"deepseek-v4.1-flash-1017", "grok-4.6"}
|
||||
a.Contexts = map[string]int{"deepseek-v4.1-flash-1017": 64000}
|
||||
if err := Save(a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := findProvider(t, "relay-b")
|
||||
b.Fallback = []string{"relay-a/deepseek-v4.1-flash-1017"}
|
||||
if err := Save(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveGroup(Group{ID: "flash", Name: "Flash", Members: []string{"relay-b/deepseek-v4.1-flash", "relay-a/deepseek-v4.1-flash-1017"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := settings.Load()
|
||||
s.HiddenModels = map[string][]string{"codex": {"relay-a/deepseek-v4.1-flash-1017"}}
|
||||
s.ModelOutputs = map[string]int{"relay-a/deepseek-v4.1-flash-1017": 8000}
|
||||
s.ModelNames = map[string]string{"relay-a/deepseek-v4.1-flash-1017": "old", "relay-a/deepseek-v4.1-flash": "Mine"}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var moved [][2]string
|
||||
old := ModelMoved
|
||||
ModelMoved = func(from, to string) error { moved = append(moved, [2]string{from, to}); return nil }
|
||||
t.Cleanup(func() { ModelMoved = old })
|
||||
|
||||
setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash")
|
||||
|
||||
a = findProvider(t, "relay-a")
|
||||
if !slices.Equal(a.Models, []string{"deepseek-v4.1-flash", "grok-4.6"}) {
|
||||
t.Errorf("picks %v", a.Models)
|
||||
}
|
||||
if a.Contexts["deepseek-v4.1-flash"] != 64000 || len(a.Contexts) != 1 {
|
||||
t.Errorf("contexts %v", a.Contexts)
|
||||
}
|
||||
if b := findProvider(t, "relay-b"); !slices.Equal(b.Fallback, []string{"relay-a/deepseek-v4.1-flash"}) {
|
||||
t.Errorf("fallback %v", b.Fallback)
|
||||
}
|
||||
g, _, ok := FindGroup(GroupPrefix + "flash")
|
||||
if !ok || !slices.Equal(g.Members, []string{"relay-b/deepseek-v4.1-flash", "relay-a/deepseek-v4.1-flash"}) {
|
||||
t.Errorf("group %v %v", g.Members, ok)
|
||||
}
|
||||
s = settings.Load()
|
||||
if got := s.HiddenModels["codex"]; !slices.Equal(got, []string{"relay-a/deepseek-v4.1-flash"}) {
|
||||
t.Errorf("hidden %v", got)
|
||||
}
|
||||
if s.ModelOutputs["relay-a/deepseek-v4.1-flash"] != 8000 {
|
||||
t.Errorf("outputs %v", s.ModelOutputs)
|
||||
}
|
||||
// the user's own value under the new id is never written over
|
||||
if s.ModelNames["relay-a/deepseek-v4.1-flash"] != "Mine" {
|
||||
t.Errorf("names %v", s.ModelNames)
|
||||
}
|
||||
if !slices.Equal(moved, [][2]string{{"relay-a/deepseek-v4.1-flash-1017", "relay-a/deepseek-v4.1-flash"}}) {
|
||||
t.Errorf("ModelMoved got %v", moved)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a provider of the user's own takes an id, and only one a model
|
||||
// can have.
|
||||
func TestModelIDRefused(t *testing.T) {
|
||||
localIDHome(t)
|
||||
for _, id := range []string{"a b", "x*", "-x", "group/flash"} {
|
||||
if _, changed, err := SetModelID("relay-a/grok-4.6", id); err == nil || changed {
|
||||
t.Errorf("id %q taken: %v", id, changed)
|
||||
}
|
||||
}
|
||||
if _, _, err := SetModelID("relay-a/nope", "x"); err == nil {
|
||||
t.Error("an unknown model took an id")
|
||||
}
|
||||
if (Provider{Account: &Account{}}).TakesModelIDs() {
|
||||
t.Error("an account takes ids")
|
||||
}
|
||||
if len(settings.Load().ModelIDs) != 0 {
|
||||
t.Fatalf("ModelIDs = %v", settings.Load().ModelIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// The picks of a provider's list (liveIDs) and its keys' models
|
||||
// (Serving) are read by the id the model is listed by.
|
||||
func TestModelIDServingAndPrice(t *testing.T) {
|
||||
localIDHome(t)
|
||||
setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash")
|
||||
ids := liveIDs("relay-a")
|
||||
if !ids["deepseek-v4.1-flash"] || ids["deepseek-v4.1-flash-1017"] {
|
||||
t.Fatalf("liveIDs %v", ids)
|
||||
}
|
||||
a := findProvider(t, "relay-a")
|
||||
if ms := a.liveByID("deepseek-v4.1-flash"); len(ms) != 1 || ms[0].ID != "deepseek-v4.1-flash" {
|
||||
t.Fatalf("liveByID %v", ms)
|
||||
}
|
||||
}
|
||||
@@ -512,6 +512,10 @@ type ModelPref struct {
|
||||
// Kind is what the model makes, as SetModelKind takes it: "image",
|
||||
// "video", or "" for what its vendor's list and name say (#1399)
|
||||
Kind *string `json:"kind,omitempty"`
|
||||
// ID is the id the model is listed by at its provider, as SetModelID
|
||||
// takes it: "" for the provider's own. It is applied after every
|
||||
// other change of the save, so those go with the model to its id.
|
||||
ID *string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// SetModelPrefs makes the changes to a provider's models, by model id, as
|
||||
@@ -581,11 +585,45 @@ func SetModelPrefs(pid string, prefs map[string]ModelPref) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return setModelIDs(pid, prefs, set)
|
||||
}()
|
||||
return touchedIf(changed, err)
|
||||
}
|
||||
|
||||
// setModelIDs gives the models of one save the ids it lists them by
|
||||
// (ModelPref.ID), after everything else it changed. Two of them given one
|
||||
// id are refused before either is: one id is one model of a provider.
|
||||
func setModelIDs(pid string, prefs map[string]ModelPref, set func(bool, error) error) error {
|
||||
to := map[string]string{}
|
||||
for _, model := range slices.Sorted(maps.Keys(prefs)) {
|
||||
id := prefs[model].ID
|
||||
if id == nil {
|
||||
continue
|
||||
}
|
||||
want := strings.TrimSpace(*id)
|
||||
if want == "" {
|
||||
continue
|
||||
}
|
||||
if other, ok := to[want]; ok {
|
||||
return fmt.Errorf("%s and %s can't both be listed as %s: one id is one model of a provider", other, model, want)
|
||||
}
|
||||
to[want] = model
|
||||
}
|
||||
for want, model := range to {
|
||||
if other := prefs[want].ID; other != nil && want != model && strings.TrimSpace(*other) != want {
|
||||
return fmt.Errorf("%s is listed as another id in the same save that gives its id to %s: save one, then the other", want, model)
|
||||
}
|
||||
}
|
||||
for _, model := range slices.Sorted(maps.Keys(prefs)) {
|
||||
if id := prefs[model].ID; id != nil {
|
||||
if _, c, err := setModelID(pid+"/"+model, *id); set(c, err) != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setModelSame says which model a provider's model, spelt "provider/model",
|
||||
// is the same as, for one a vendor names its own way (Volcengine Ark's
|
||||
// dated ids, kyzhouxu on #583): the routing groups magpie finds merge it
|
||||
@@ -939,7 +977,7 @@ func ServesModel(p Provider, model string) bool { return p.serves(model) }
|
||||
// model asked for by the name the vendor serves it under is not read as
|
||||
// another one.
|
||||
func UpstreamName(p Provider, model string) string {
|
||||
return UpstreamNameIn(settings.Load().ModelWires, p.ID, model)
|
||||
return UpstreamNameIn(settings.Load().Wires(), p.ID, model)
|
||||
}
|
||||
|
||||
// UpstreamNameIn is UpstreamName over a settings' ModelWires already read,
|
||||
@@ -969,7 +1007,7 @@ func UpstreamNameIn(wires map[string]string, pid, model string) string {
|
||||
// asks for gemini-3.7-flash-high and gemini-3.7-flash-low each by its own,
|
||||
// rather than for the one id whatever level the effort picked.
|
||||
func UpstreamNameAs(p Provider, model, sent string) string {
|
||||
return UpstreamNameAsIn(settings.Load().ModelWires, p.ID, model, sent)
|
||||
return UpstreamNameAsIn(settings.Load().Wires(), p.ID, model, sent)
|
||||
}
|
||||
|
||||
// UpstreamNameAsIn is UpstreamNameAs over a settings' ModelWires already
|
||||
|
||||
@@ -34,7 +34,8 @@ func (p Provider) Available() []catalog.Model {
|
||||
if p.DecideOnly() {
|
||||
return p.decideModels()
|
||||
}
|
||||
ms := p.available()
|
||||
// by the ids the user lists them by (SetModelID)
|
||||
ms := p.ids().list(p.available())
|
||||
if p.Decides() {
|
||||
// a gateway's Jev among its chat models, with its window and input
|
||||
ms = slices.Clone(ms)
|
||||
@@ -163,7 +164,18 @@ func (p Provider) liveByID(model string) []catalog.Model {
|
||||
if !p.lists() {
|
||||
return nil
|
||||
}
|
||||
return catalog.LiveByID(p.ID, model)
|
||||
// a model listed by an id the user gave it is in the vendor's list
|
||||
// under its own (SetModelID)
|
||||
own := p.OwnModelID(model)
|
||||
ms := catalog.LiveByID(p.ID, own)
|
||||
if own == model {
|
||||
return ms
|
||||
}
|
||||
out := slices.Clone(ms)
|
||||
for i := range out {
|
||||
out[i].ID = model
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// lists says whether the provider's fetched list is its own to read: not
|
||||
@@ -294,7 +306,8 @@ func liveIDs(id string) map[string]bool {
|
||||
for _, m := range ms {
|
||||
out[m.ID] = true
|
||||
}
|
||||
return out
|
||||
// picks are of the ids the user lists them by (SetModelID)
|
||||
return modelIDsOf(id).ids(out)
|
||||
}
|
||||
|
||||
// dropGonePicks takes out of the saved provider's picks those before had
|
||||
@@ -1444,10 +1457,13 @@ func (p Provider) Serves(k KeyAccount, model string) bool { return p.Serving(mod
|
||||
// thousand keys (@NetRozee on X).
|
||||
func (p Provider) Serving(model string) func(KeyAccount) bool {
|
||||
x, ok := p.keyLists()
|
||||
if !ok {
|
||||
if !ok || len(x.listed) == 0 {
|
||||
// no key is listed to any model: every key serves it, and the
|
||||
// model's own id needn't be looked up
|
||||
return func(KeyAccount) bool { return true }
|
||||
}
|
||||
keys, found := x.of[model]
|
||||
// the vendor's lists name the model by its own id (SetModelID)
|
||||
keys, found := x.of[p.OwnModelID(model)]
|
||||
return func(k KeyAccount) bool {
|
||||
id := keyID(k.Key)
|
||||
return !found || len(keys) == 0 || !x.listed[id] || keys[id]
|
||||
@@ -1877,6 +1893,13 @@ var makerCatalogs = sync.OnceValue(func() []string {
|
||||
// auto-review through the Codex subscription costs nothing too, as OpenAI
|
||||
// serves it a ChatGPT sign-in (codexReviewFree).
|
||||
func (p Provider) ListPrice(model string) (catalog.Price, bool) {
|
||||
if own := p.OwnModelID(model); own != model {
|
||||
// a model listed by an id the user gave it is priced as the
|
||||
// provider's own id of it first, then as the id it is listed by
|
||||
if pr, ok := p.ListPrice(own); ok {
|
||||
return pr, true
|
||||
}
|
||||
}
|
||||
if pr, ok := p.remotePrice(model); ok {
|
||||
return pr, true
|
||||
}
|
||||
|
||||
+35
-26
@@ -75,11 +75,7 @@ func Rename(from, to string) error {
|
||||
if !sub && !slices.Contains(p.Was, from) {
|
||||
p.Was = append(p.Was, from)
|
||||
}
|
||||
for j := range f.Providers {
|
||||
for k, m := range f.Providers[j].Fallback {
|
||||
f.Providers[j].Fallback[k] = renamedRef(m, from, to)
|
||||
}
|
||||
}
|
||||
mapModelRefs(&f, func(m string) string { return renamedRef(m, from, to) })
|
||||
for j, id := range f.Order {
|
||||
if id == from {
|
||||
f.Order[j] = to
|
||||
@@ -97,27 +93,6 @@ func Rename(from, to string) error {
|
||||
f.Deleted[j].Into = to
|
||||
}
|
||||
}
|
||||
for j := range f.Groups {
|
||||
g := &f.Groups[j]
|
||||
for k, m := range g.Members {
|
||||
g.Members[k] = renamedRef(m, from, to)
|
||||
}
|
||||
for k := range g.Rules {
|
||||
g.Rules[k].MapUses(func(u string) string { return renamedRef(u, from, to) })
|
||||
}
|
||||
for k, m := range g.Fast {
|
||||
g.Fast[k] = renamedRef(m, from, to)
|
||||
}
|
||||
for k, m := range g.Placed {
|
||||
g.Placed[k] = renamedRef(m, from, to)
|
||||
}
|
||||
for k, m := range g.Off {
|
||||
g.Off[k] = renamedRef(m, from, to)
|
||||
}
|
||||
g.Weights = renamedWeights(g.Weights, func(m string) string { return renamedRef(m, from, to) })
|
||||
g.Classifier = renamedRef(g.Classifier, from, to)
|
||||
g.Pick = renamedRef(g.Pick, from, to)
|
||||
}
|
||||
// the vendor's list last fetched goes with it
|
||||
os.Rename(catalog.LivePath(from), catalog.LivePath(to))
|
||||
os.Rename(catalog.LivePath(decisionsID(from)), catalog.LivePath(decisionsID(to)))
|
||||
@@ -143,6 +118,40 @@ func Rename(from, to string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapModelRefs gives every model ref the file keeps for routing — the
|
||||
// providers' fallbacks, and the routing groups' members, rules, fast and
|
||||
// placed members, those turned off, weights, classifiers and picks — as
|
||||
// to has it: what a provider's rename (Rename) and a model given another
|
||||
// id at its provider (SetModelID) both rewrite.
|
||||
func mapModelRefs(f *file, to func(string) string) {
|
||||
for j := range f.Providers {
|
||||
for k, m := range f.Providers[j].Fallback {
|
||||
f.Providers[j].Fallback[k] = to(m)
|
||||
}
|
||||
}
|
||||
for j := range f.Groups {
|
||||
g := &f.Groups[j]
|
||||
for k, m := range g.Members {
|
||||
g.Members[k] = to(m)
|
||||
}
|
||||
for k := range g.Rules {
|
||||
g.Rules[k].MapUses(to)
|
||||
}
|
||||
for k, m := range g.Fast {
|
||||
g.Fast[k] = to(m)
|
||||
}
|
||||
for k, m := range g.Placed {
|
||||
g.Placed[k] = to(m)
|
||||
}
|
||||
for k, m := range g.Off {
|
||||
g.Off[k] = to(m)
|
||||
}
|
||||
g.Weights = renamedWeights(g.Weights, to)
|
||||
g.Classifier = to(g.Classifier)
|
||||
g.Pick = to(g.Pick)
|
||||
}
|
||||
}
|
||||
|
||||
// renamedRef is a model id ("provider/model", "magpie/provider/model")
|
||||
// with the provider from named to instead.
|
||||
func renamedRef(ref, from, to string) string {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Wires is ModelWires with each model the user lists by an id of theirs
|
||||
// sent as the provider's own: a wire the user gave that id is theirs, a
|
||||
// provider's "*" wire wraps the own id, and the maps are read again when
|
||||
// they change in place.
|
||||
func TestWiresTakeModelIDs(t *testing.T) {
|
||||
s := Settings{
|
||||
ModelWires: map[string]string{"r/x": "vendor-x", "p/*": "acct/*"},
|
||||
ModelIDs: map[string]string{"r/flash": "flash-1017", "r/x": "x-own", "p/grok": "grok@500k", "r/blank": " "},
|
||||
}
|
||||
w := s.Wires()
|
||||
for k, want := range map[string]string{"r/flash": "flash-1017", "r/x": "vendor-x", "p/grok": "acct/grok@500k", "p/*": "acct/*"} {
|
||||
if w[k] != want {
|
||||
t.Errorf("Wires()[%s] = %q, want %q", k, w[k], want)
|
||||
}
|
||||
}
|
||||
if _, ok := w["r/blank"]; ok {
|
||||
t.Error("a blank own id is a wire")
|
||||
}
|
||||
s.ModelIDs["r/flash"] = "flash-1018"
|
||||
if got := s.Wires()["r/flash"]; got != "flash-1018" {
|
||||
t.Errorf("after a change in place: %q", got)
|
||||
}
|
||||
if got := (Settings{ModelWires: map[string]string{"a/b": "c"}}).Wires(); len(got) != 1 || got["a/b"] != "c" {
|
||||
t.Errorf("no ModelIDs: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// MoveModel moves every per-model setting but ModelIDs to the new key,
|
||||
// and keeps one the user already has there.
|
||||
func TestMoveModelKeepsTheUsersOwn(t *testing.T) {
|
||||
s := Settings{
|
||||
ModelNames: map[string]string{"r/old": "Old", "r/new": "Mine"},
|
||||
ModelOutputs: map[string]int{"r/old": 8000},
|
||||
ModelIDs: map[string]string{"r/old": "x"},
|
||||
}
|
||||
if !s.MoveModel("r/old", "r/new") {
|
||||
t.Fatal("nothing moved")
|
||||
}
|
||||
if s.ModelNames["r/new"] != "Mine" || s.ModelNames["r/old"] != "Old" {
|
||||
t.Errorf("names %v", s.ModelNames)
|
||||
}
|
||||
if s.ModelOutputs["r/new"] != 8000 || len(s.ModelOutputs) != 1 {
|
||||
t.Errorf("outputs %v", s.ModelOutputs)
|
||||
}
|
||||
if s.ModelIDs["r/old"] != "x" {
|
||||
t.Errorf("ids %v", s.ModelIDs)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ package settings
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
@@ -852,6 +853,17 @@ type Settings struct {
|
||||
// the routing groups, the usage records and what a call is priced at —
|
||||
// keeps the name magpie knows the model by.
|
||||
ModelWires map[string]string `json:"modelWires,omitempty"`
|
||||
// ModelIDs are the ids the user lists a provider's models by, from
|
||||
// "<provider id>/<the id magpie lists it by>" to the id the provider
|
||||
// itself serves it under (zeewell on X: deepseek-v4.1-flash-1017 known
|
||||
// as deepseek-v4.1-flash). The model is listed, picked, grouped, found
|
||||
// in routing groups, limited by gateway keys and recorded in usage by
|
||||
// that id, and a request for it goes out under the provider's own, as
|
||||
// a ModelWires name does (Wires). Keyed by the id it is known by, so one
|
||||
// id of a provider is one of its models; a model of the provider's own
|
||||
// with that id is not listed while another goes by it. Absent leaves
|
||||
// each model to the provider's id (provider.SetModelID).
|
||||
ModelIDs map[string]string `json:"modelIDs,omitempty"`
|
||||
// ModelAPIs is the one API a model is asked on at its provider, by
|
||||
// "<provider id>/<model id>": chat, responses or anthropic, for a relay
|
||||
// whose one key serves some models on one and others on another
|
||||
@@ -1279,6 +1291,70 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.RequestArchiveLocal, s.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB
|
||||
}
|
||||
|
||||
// Wires is ModelWires with the provider's own id of each model the user
|
||||
// lists by another (ModelIDs): what a request for "<provider>/<id>" goes out
|
||||
// under. A name the user gave the model itself in ModelWires is kept, and a
|
||||
// provider's "*" name is the provider's own id in its "*". With no ModelIDs
|
||||
// it is ModelWires itself; else it is made again only when either map holds
|
||||
// something else than the last time. It is read, never written to.
|
||||
func (s Settings) Wires() map[string]string {
|
||||
if len(s.ModelIDs) == 0 {
|
||||
return s.ModelWires
|
||||
}
|
||||
wiresMemo.Lock()
|
||||
defer wiresMemo.Unlock()
|
||||
if wiresMemo.out != nil && maps.Equal(wiresMemo.ids, s.ModelIDs) && maps.Equal(wiresMemo.wires, s.ModelWires) {
|
||||
return wiresMemo.out
|
||||
}
|
||||
out := make(map[string]string, len(s.ModelWires)+len(s.ModelIDs))
|
||||
maps.Copy(out, s.ModelWires)
|
||||
for k, own := range s.ModelIDs {
|
||||
pid, _, ok := strings.Cut(k, "/")
|
||||
own = strings.TrimSpace(own)
|
||||
if !ok || own == "" || strings.TrimSpace(s.ModelWires[k]) != "" {
|
||||
continue
|
||||
}
|
||||
if all := strings.TrimSpace(s.ModelWires[pid+"/*"]); all != "" {
|
||||
own = strings.ReplaceAll(all, "*", own)
|
||||
}
|
||||
out[k] = own
|
||||
}
|
||||
wiresMemo.ids, wiresMemo.wires, wiresMemo.out = maps.Clone(s.ModelIDs), maps.Clone(s.ModelWires), out
|
||||
return out
|
||||
}
|
||||
|
||||
// wiresMemo is the Wires last made, and copies of the two maps it was
|
||||
// made of: compared by what they hold, as a caller may change its own
|
||||
// settings' maps in place.
|
||||
var wiresMemo struct {
|
||||
sync.Mutex
|
||||
ids, wires, out map[string]string
|
||||
}
|
||||
|
||||
// MoveModel moves what the user said of the model keyed from
|
||||
// ("<provider>/<model>") to the key to, in every per-model map but
|
||||
// ModelIDs, and says whether anything moved. A map with something under
|
||||
// to already keeps it, and what from had there stays where it was: what
|
||||
// the user said of the model now keyed to is theirs and is not written
|
||||
// over.
|
||||
func (s *Settings) MoveModel(from, to string) bool {
|
||||
moved := false
|
||||
PerModelKeys(s, func(name string, m reflect.Value) {
|
||||
if name == "ModelIDs" || m.IsNil() {
|
||||
return
|
||||
}
|
||||
fk, tk := reflect.ValueOf(from).Convert(m.Type().Key()), reflect.ValueOf(to).Convert(m.Type().Key())
|
||||
v := m.MapIndex(fk)
|
||||
if !v.IsValid() || m.MapIndex(tk).IsValid() {
|
||||
return
|
||||
}
|
||||
m.SetMapIndex(fk, reflect.Value{})
|
||||
m.SetMapIndex(tk, v)
|
||||
moved = true
|
||||
})
|
||||
return moved
|
||||
}
|
||||
|
||||
// RenamePerModel moves what the user said of a provider's models to the id
|
||||
// it has now: in every per-model map (see ModelNames) each key beginning
|
||||
// with from+"/" is rewritten to to+"/", and it says whether any key moved at
|
||||
@@ -1393,6 +1469,52 @@ func Shared() Settings {
|
||||
return s
|
||||
}
|
||||
|
||||
// SharedModelIDs is Shared().ModelIDs, read for each model a list is
|
||||
// built of: only that field is parsed, once per change of the file, and a
|
||||
// missing file has none without the defaults Shared builds each time.
|
||||
// Unreadable or unparsable, it is what Shared says. It is shared: the
|
||||
// caller must not change it.
|
||||
func SharedModelIDs() map[string]string {
|
||||
fileMu.RLock()
|
||||
ids, err := filememo.Read("settings-model-ids", pathNow(), func(b []byte) (map[string]string, error) {
|
||||
var s struct {
|
||||
ModelIDs map[string]string `json:"modelIDs"`
|
||||
}
|
||||
err := json.Unmarshal(b, &s)
|
||||
return s.ModelIDs, err
|
||||
})
|
||||
fileMu.RUnlock()
|
||||
if err == nil {
|
||||
return ids
|
||||
}
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return Shared().ModelIDs
|
||||
}
|
||||
|
||||
// pathNow is Path, built again only when what it is built from changed:
|
||||
// SharedModelIDs is read several times for each list, and Path's joins
|
||||
// were most of what building one allocated.
|
||||
func pathNow() string {
|
||||
k := pathFrom{appdir.Portable(), os.Getenv("XDG_CONFIG_HOME"), os.Getenv("HOME"), os.Getenv("USERPROFILE")}
|
||||
if m := lastPath.Load(); m != nil && m.from == k {
|
||||
return m.path
|
||||
}
|
||||
path := Path()
|
||||
lastPath.Store(&pathMemo{k, path})
|
||||
return path
|
||||
}
|
||||
|
||||
type pathFrom struct{ portable, xdg, home, profile string }
|
||||
|
||||
type pathMemo struct {
|
||||
from pathFrom
|
||||
path string
|
||||
}
|
||||
|
||||
var lastPath atomic.Pointer[pathMemo]
|
||||
|
||||
// sharedFor is the shared Settings parse keeps for contents b, when it
|
||||
// keeps them.
|
||||
func sharedFor(b []byte) (Settings, bool) {
|
||||
|
||||
@@ -428,7 +428,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi
|
||||
// the upstream names in force now, read once for the lot: a row is
|
||||
// judged by the names standing today, which is what Ledger says, and
|
||||
// the rows here are what a reader compares a bill against
|
||||
wires := settings.Load().ModelWires
|
||||
wires := settings.Load().Wires()
|
||||
priceOf := Pricer()
|
||||
codexIdentities := sessions.CodexIdentities()
|
||||
rows = make([]Row, 0, len(recs)+len(logs))
|
||||
|
||||
@@ -750,7 +750,7 @@ func readRequestState(now time.Time) requestState {
|
||||
renamed := provider.UsageRenames().Key()
|
||||
cfg := settings.Load()
|
||||
prices, _ := json.Marshal(cfg.ModelPrices)
|
||||
wires, _ := json.Marshal(cfg.ModelWires)
|
||||
wires, _ := json.Marshal(cfg.Wires())
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey(), clearedKey())
|
||||
h := sha256.New()
|
||||
for _, current := range provider.All() {
|
||||
@@ -1056,7 +1056,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle
|
||||
return func(r Record, source string) Row {
|
||||
sent := r.Model
|
||||
if source == "" {
|
||||
sent = provider.SentNameIn(cfg.ModelWires, r.priceID(), r.Model, r.Effort)
|
||||
sent = provider.SentNameIn(cfg.Wires(), r.priceID(), r.Model, r.Effort)
|
||||
}
|
||||
row := Row{Record: r, Source: source, Routed: GroupRouted(sent, r.Served)}
|
||||
if r.Served != "" {
|
||||
@@ -1088,7 +1088,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle
|
||||
// cache budget every query priced the whole history again.
|
||||
var gateways []*rowChunk
|
||||
renames := provider.UsageRenames()
|
||||
priced := newBlockPricer(renames, cfg.ModelWires, price)
|
||||
priced := newBlockPricer(renames, cfg.Wires(), price)
|
||||
meta := sha256.Sum256([]byte(st.root + "|" + st.meta))
|
||||
priced.share(meta)
|
||||
for _, packed := range snapshot.blocks {
|
||||
|
||||
@@ -171,6 +171,7 @@
|
||||
<h3>1 つのモデルを複数のプロバイダで</h3>
|
||||
<p>グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの <em>Routing groups</em> の下に <code>group/<id></code> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。<span class="ui">Routing</span> タブの <span class="ui">New group</span> では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。</p>
|
||||
<div class="callout"><b>何もしなくてもできるグループ。</b> すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ <code>auto/<model></code>(モデル自身の ID。例: <code>auto/claude-opus-4.6</code>。以前の <code>group/auto-…</code> も引き続き使えます)を自動で作ります。名前はベンダーごとの表記の違い(<code>deepseek/deepseek-chat</code>、<code>deepseek-chat</code>)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは <code>magpie group rm</code> で非表示にできます。</div>
|
||||
<div class="callout"><b>プロバイダ独自の id に自分の id を。</b> プロバイダによっては <code>deepseek-v4.1-flash-1017</code> や <code>grok-4.6@500k</code> のような独自の id でモデルを提供します。プロバイダの編集画面の <span class="ui">名前と推論レベル</span> で、<span class="ui">同じモデル</span> の隣の <span class="ui">表示 ID</span> に使いたい id を入れて <span class="ui">保存</span>、または <code>magpie model id relay/grok-4.6@500k grok-4.6</code> を実行します。以後 magpie は一覧、ルーティング、他のプロバイダの <code>grok-4.6</code> とまとめた <code>auto/grok-4.6</code> グループ、ゲートウェイキーの制限、使用量の記録をすべて <code>grok-4.6</code> で行い、プロバイダには <code>grok-4.6@500k</code> で問い合わせます。1 つのプロバイダで 1 つの id は 1 つのモデルです。最後に付けたものが有効で、その間プロバイダ自身のその id のモデルは一覧から外れます。<code>magpie model id relay/grok-4.6 --reset</code> で元に戻し、<code>magpie model ids</code> で一覧を表示します。キーで追加したプロバイダ向けで、サブスクリプションやプラグインのモデルは元の id のままです。</div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>ルーティング</th><th>先に使われるもの</th></tr>
|
||||
<tr><td>スマート <code>smart</code></td><td>デフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。同時に更新されるアカウント(無料アカウントはすべて月末)は、その後に残りのクレジットが先に失効するものが先になります。失敗後に休止中のものは最後に回ります。</td></tr>
|
||||
|
||||
@@ -171,6 +171,7 @@
|
||||
<h3>One model over several providers</h3>
|
||||
<p>A group is several models, from one provider or many, that an agent picks as one: <code>group/<id></code>, under <em>Routing groups</em> in the picker. A model two of your providers serve under the same name becomes a group on its own; <span class="ui">New group</span> in the <span class="ui">Routing</span> tab makes one of any models you like. The first model answers for what the group can do.</p>
|
||||
<div class="callout"><b>Groups you get without doing anything.</b> Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, <code>auto/<model></code> (the model's own id, as in <code>auto/claude-opus-4.6</code>; the older <code>group/auto-…</code> id still works), over every provider that serves it. The name is matched however each vendor spells it (<code>deepseek/deepseek-chat</code>, <code>deepseek-chat</code>). Pick it for an agent to spread its requests over all of them; <code>magpie group rm</code> hides one you don’t want.</div>
|
||||
<div class="callout"><b>One model under the provider's odd id.</b> Some providers serve a model under an id of their own, <code>deepseek-v4.1-flash-1017</code> or <code>grok-4.6@500k</code>. Give it the id you want in the provider's editor, under <span class="ui">Names & levels</span>, in <span class="ui">Listed as</span> beside <span class="ui">Same as</span>, then <span class="ui">Save</span>; or run <code>magpie model id relay/grok-4.6@500k grok-4.6</code>. magpie then lists it, routes it, joins it to the <code>auto/grok-4.6</code> group with your other providers' <code>grok-4.6</code>, holds gateway keys to it and counts its usage as <code>grok-4.6</code>, and still asks the provider for <code>grok-4.6@500k</code>. One id is one model of a provider: the last one you give it to has it, and the provider's own model of that id is left out of the list while it does. <code>magpie model id relay/grok-4.6 --reset</code> takes it back, and <code>magpie model ids</code> lists them. It is for providers you added with a key; a subscription's or a plugin's models keep their ids.</div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>Routing</th><th>What goes first</th></tr>
|
||||
<tr><td>Smart <code>smart</code></td><td>The default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first; accounts renewing together (free ones at the month’s end) go by whose credits left end first after that. One resting after a failure goes last.</td></tr>
|
||||
|
||||
@@ -171,6 +171,7 @@
|
||||
<h3>跨供应商的同一个模型</h3>
|
||||
<p>路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:<code>group/<id></code>,在选择列表的 <em>路由组</em> 下面。两个供应商用同一个名字提供的模型会自动成组;在 <span class="ui">路由</span> 标签页点 <span class="ui">新建组</span> 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。</p>
|
||||
<div class="callout"><b>不用手动建的组。</b>再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:<code>auto/<模型></code>(模型自己的 id,比如 <code>auto/claude-opus-4.6</code>;以前的 <code>group/auto-…</code> 也照样能用),包含所有提供这个模型的供应商。名字按各家不同的写法匹配(<code>deepseek/deepseek-chat</code> 和 <code>deepseek-chat</code> 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 <code>magpie group rm</code> 隐藏。</div>
|
||||
<div class="callout"><b>给供应商的怪名字起个自己的 id。</b>有的供应商用自己的 id 提供模型,比如 <code>deepseek-v4.1-flash-1017</code>、<code>grok-4.6@500k</code>。在供应商编辑页的 <span class="ui">名称与推理档位</span> 里,<span class="ui">等同于</span> 旁边的 <span class="ui">列为</span> 填上你想要的 id,再点 <span class="ui">保存</span>;或者运行 <code>magpie model id relay/grok-4.6@500k grok-4.6</code>。之后 magpie 列出、路由、把它和其他供应商的 <code>grok-4.6</code> 合进 <code>auto/grok-4.6</code> 组、限制网关密钥、记录用量,都用 <code>grok-4.6</code>,向供应商请求时仍然发 <code>grok-4.6@500k</code>。一个供应商里一个 id 只对应一个模型:最后设上的那个生效,期间供应商自己叫这个 id 的模型不再列出。<code>magpie model id relay/grok-4.6 --reset</code> 改回来,<code>magpie model ids</code> 列出全部。只适用于用密钥添加的供应商;订阅和插件的模型保持原 id。</div>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>路由</th><th>谁排在前面</th></tr>
|
||||
<tr><td>智能 <code>smart</code></td><td>默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一;同时重置的账号(免费账号都在月底)再看剩余积分哪个先过期。失败后在休息的排最后。</td></tr>
|
||||
|
||||
Reference in New Issue
Block a user