|
1
|
package llm |
|
2
|
|
|
3
|
import ( |
|
4
|
"fmt" |
|
5
|
"regexp" |
|
6
|
) |
|
7
|
|
|
8
|
// ModelFilter applies allow/block regex patterns to a slice of ModelInfo. |
|
9
|
// Patterns are matched against model ID. |
|
10
|
type ModelFilter struct { |
|
11
|
allowlist []*regexp.Regexp |
|
12
|
blocklist []*regexp.Regexp |
|
13
|
} |
|
14
|
|
|
15
|
// NewModelFilter compiles regex allow/block patterns. |
|
16
|
// Returns an error if any pattern is invalid. |
|
17
|
func NewModelFilter(allow, block []string) (*ModelFilter, error) { |
|
18
|
f := &ModelFilter{} |
|
19
|
for _, pat := range allow { |
|
20
|
r, err := regexp.Compile(pat) |
|
21
|
if err != nil { |
|
22
|
return nil, fmt.Errorf("llm: allow pattern %q: %w", pat, err) |
|
23
|
} |
|
24
|
f.allowlist = append(f.allowlist, r) |
|
25
|
} |
|
26
|
for _, pat := range block { |
|
27
|
r, err := regexp.Compile(pat) |
|
28
|
if err != nil { |
|
29
|
return nil, fmt.Errorf("llm: block pattern %q: %w", pat, err) |
|
30
|
} |
|
31
|
f.blocklist = append(f.blocklist, r) |
|
32
|
} |
|
33
|
return f, nil |
|
34
|
} |
|
35
|
|
|
36
|
// Apply filters models: removes those matching any blocklist pattern, then |
|
37
|
// (if allowlist is non-empty) keeps only those matching at least one allowlist pattern. |
|
38
|
func (f *ModelFilter) Apply(models []ModelInfo) []ModelInfo { |
|
39
|
out := make([]ModelInfo, 0, len(models)) |
|
40
|
for _, m := range models { |
|
41
|
if f.blocked(m.ID) { |
|
42
|
continue |
|
43
|
} |
|
44
|
if len(f.allowlist) > 0 && !f.allowed(m.ID) { |
|
45
|
continue |
|
46
|
} |
|
47
|
out = append(out, m) |
|
48
|
} |
|
49
|
return out |
|
50
|
} |
|
51
|
|
|
52
|
func (f *ModelFilter) allowed(id string) bool { |
|
53
|
for _, r := range f.allowlist { |
|
54
|
if r.MatchString(id) { |
|
55
|
return true |
|
56
|
} |
|
57
|
} |
|
58
|
return false |
|
59
|
} |
|
60
|
|
|
61
|
func (f *ModelFilter) blocked(id string) bool { |
|
62
|
for _, r := range f.blocklist { |
|
63
|
if r.MatchString(id) { |
|
64
|
return true |
|
65
|
} |
|
66
|
} |
|
67
|
return false |
|
68
|
} |
|
69
|
|