Files
magpie/internal/provider/groupmatch.go
T
yetone 5569275465 group: a routing group's members can be patterns, so a group follows a provider's catalog (#766: magpie group add my-free-pool models='openrouter/*:free,opencode-zen/*-free') — a group names its models one by one, so a pool of a vendor's free models went stale as the vendor added and dropped them. A group now keeps patterns apart from the models it names (Group.Match): a glob, * any run of characters (/ too) over the provider/model id in any case, or re:<regexp> over the whole id. groupsIn, which every reader goes through (Groups, FindGroup, /v1/models, MemberGroups, GroupsWith, RenameGroup, rules, Off, Pick, the GUI, TUI and CLI), puts after the named models every enabled provider's model a pattern matches, in catalog order, deduplicated, the named one keeping its place; a pattern never matches a group. What was matched is derived (Group.Matched) and never stored: store() and SaveGroup keep only the named members, so a save never freezes matches. Off and rules may name a matched model. A group with only patterns is allowed; one matching nothing routes nowhere and says so: magpie group <id> lists each pattern with how many models it matches now ("matches nothing now" in amber), the group list and the TUI too, and the GUI card shows a line per pattern with its count. CLI: models= takes patterns among the ids, models+= adds them (naming a matched model moves it to where it is named), models-=<pattern> drops one, models-= of a matched model is refused naming its pattern; the help documents patterns. GUI: the editor has a Patterns box (Add pattern / Remove, validated as the server does), matched models follow those named marked "by pattern" with their off switch and no Remove, and saves send members without the matched ones plus match; zh strings added. Tests: TestGroupPatterns, TestGroupPatternMembersOffAndRules, TestGroupPatternMatchingNothing, TestPatternSyntax (provider), TestPatternGroupRoutes (gateway: a request reaches a matched model, a model a provider adds joins, Off on a matched one, /v1/models lists the group), TestGroupPatternsCLI, and group-patterns.test.cjs (WebKit, en+zh); they fail on the old code (the Go ones don't build, the GUI one finds no pattern lines). GUI: group-patterns, group-found-off, group-member-fast, group-member-off, settings-groups, agent-model-groups, remote-group-served, routing-manual pass on WebKit; group-from-model-add has the same 2 failures (600x420) as origin/main. A request to a group whose patterns match nothing now is a 404 naming the group and its patterns (emptyGroupError), not 'magpie knows no model' and every model; TestEmptyPatternGroupSaysSo. With the owner's real config under a sandbox HOME: group/ds-pool of models='deepseek/*' listed deepseek-flash and deepseek-v4-pro by pattern, stored only the pattern, was in /v1/models and answered from deepseek-flash; none-pool of 'nobody/*' said its pattern matches nothing. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-04 16:52:15 +08:00

184 lines
5.8 KiB
Go

package provider
// A routing group may name its members by pattern as well as by id (#766):
// "openrouter/*:free" is every free model OpenRouter lists, today's and
// next week's, where a list of ids goes stale as the vendor's catalog
// changes and a member left out is lost unsaid.
//
// The patterns are kept beside the members (Group.Match), never written
// into them: what they match is worked out each time the groups are read
// (groupsIn), from the models magpie serves now, so a model the vendor adds
// joins the group and one it drops leaves it without the group being saved
// again. Every reader — the gateway's routing, /v1/models, rules, the
// Routing view, the TUI and the CLI — gets the group from there, so all of
// them see the same members: those the user named, in their order, then
// those the patterns match, in the catalog's order. A model named and
// matched both keeps the place it was named at.
import (
"fmt"
"regexp"
"slices"
"strings"
)
// RegexpPrefix starts a member that is a regular expression over the whole
// "provider/model" id: "re:openrouter/.*:(free|beta)".
const RegexpPrefix = "re:"
// IsPattern reports whether a member as typed is a pattern rather than a
// model's id: a regular expression ("re:…") or a glob with "*" in it. No
// vendor's model id has a "*" in it, so a glob can't be taken for one.
func IsPattern(s string) bool {
s = strings.TrimSpace(s)
return strings.HasPrefix(s, RegexpPrefix) || strings.Contains(s, "*")
}
// compilePattern is a pattern as the regexp it means. A glob's "*" is any
// run of characters, "/" too, and the rest is the id as spelt, in any case
// ("openrouter/*:free", "*-free"); a regexp must match the whole id.
func compilePattern(p string) (*regexp.Regexp, error) {
if re, ok := strings.CutPrefix(p, RegexpPrefix); ok {
if strings.TrimSpace(re) == "" {
return nil, fmt.Errorf("%q has no regular expression after %s", p, RegexpPrefix)
}
x, err := regexp.Compile("^(?:" + re + ")$")
if err != nil {
return nil, fmt.Errorf("%q is not a regular expression magpie can read: %v", p, err)
}
return x, nil
}
parts := strings.Split(p, "*")
for i, s := range parts {
parts[i] = regexp.QuoteMeta(s)
}
return regexp.Compile("(?i)^" + strings.Join(parts, ".*") + "$")
}
// CleanPatterns are a group's patterns as they are kept: trimmed, each
// once, every one one magpie can read.
func CleanPatterns(in []string) ([]string, error) {
var out []string
for _, p := range in {
p = strings.TrimPrefix(strings.TrimSpace(p), "magpie/")
if p == "" || slices.Contains(out, p) {
continue
}
if !IsPattern(p) {
return nil, fmt.Errorf("%q is a model's id, not a pattern: a pattern has a * in it, or starts with %s", p, RegexpPrefix)
}
if _, err := compilePattern(p); err != nil {
return nil, err
}
out = append(out, p)
}
return out, nil
}
// PatternMatches reports whether a pattern matches a "provider/model" id.
func PatternMatches(pattern, id string) bool {
x, err := compilePattern(pattern)
return err == nil && x.MatchString(id)
}
// matchesIn are the models g's patterns match among entries — the models
// served now, never a group — in the catalog's order, but those the group
// names itself: a model named at an effort of its own is not matched again
// at the group's.
func matchesIn(entries []Entry, g Group) []string {
if len(g.Match) == 0 {
return nil
}
var res []*regexp.Regexp
for _, p := range g.Match {
if x, err := compilePattern(p); err == nil {
res = append(res, x)
}
}
named := map[string]bool{}
for _, id := range g.Members {
m, _ := memberEffortIn(entries, id)
named[m] = true
}
var out []string
for _, e := range entries {
if named[e.ID] || slices.Contains(out, e.ID) {
continue
}
if slices.ContainsFunc(res, func(x *regexp.Regexp) bool { return x.MatchString(e.ID) }) {
out = append(out, e.ID)
}
}
return out
}
// withMatches is a stored group as it is read: the members its patterns
// match now after those it names (Matched says which they are).
func withMatches(entries []Entry, g Group) Group {
if len(g.Match) == 0 {
return g
}
g.Matched = matchesIn(entries, g)
g.Members = append(slices.Clone(g.Members), g.Matched...)
return g
}
// ownMembers are the members a group names itself and its patterns, from a
// group as it was read: the members its patterns matched (Matched) are
// left out, so that saving a group never writes today's matches into it,
// and a pattern typed among the members is taken as one.
func ownMembers(g Group) (members, match []string) {
match = slices.Clone(g.Match)
for _, m := range g.Members {
switch m = strings.TrimSpace(m); {
case slices.Contains(g.Matched, m):
case IsPattern(m):
match = append(match, m)
default:
members = append(members, m)
}
}
return members, match
}
// stored is the group as providers.json keeps it: without what its
// patterns matched when it was read.
func (g Group) stored() Group {
if len(g.Matched) == 0 {
return g
}
g.Members = slices.DeleteFunc(slices.Clone(g.Members), func(m string) bool { return slices.Contains(g.Matched, m) })
g.Matched = nil
return g
}
// PatternHit is one of a group's patterns and how many of the models
// served now it matches.
type PatternHit struct {
Pattern string `json:"pattern"`
Models int `json:"models"`
}
// PatternHits are the group's patterns, each with the number of models it
// matches now — those the group names itself as well — so that one that
// matches nothing is said, not left an empty group.
func PatternHits(g Group) []PatternHit {
if len(g.Match) == 0 {
return nil
}
entries := providerEntries()
out := make([]PatternHit, 0, len(g.Match))
for _, p := range g.Match {
h := PatternHit{Pattern: p}
if x, err := compilePattern(p); err == nil {
for _, e := range entries {
if x.MatchString(e.ID) {
h.Models++
}
}
}
out = append(out, h)
}
return out
}