-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcapability_router.go
More file actions
288 lines (243 loc) · 6.99 KB
/
Copy pathcapability_router.go
File metadata and controls
288 lines (243 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package model
import (
"context"
"strings"
"github.com/hupe1980/agentmesh/pkg/message"
)
// CapabilityRouter routes requests to models based on required capabilities.
// It inspects the request to determine what capabilities are needed and
// selects a model that supports all of them.
type CapabilityRouter struct {
models []Model
fallback Model
detector CapabilityDetector
}
// CapabilityRouterOption configures a CapabilityRouter.
type CapabilityRouterOption func(*CapabilityRouter)
// WithCapabilityDetector sets a custom capability detector.
func WithCapabilityDetector(d CapabilityDetector) CapabilityRouterOption {
return func(r *CapabilityRouter) {
r.detector = d
}
}
// WithCapabilityFallback sets a fallback model when no model matches.
func WithCapabilityFallback(m Model) CapabilityRouterOption {
return func(r *CapabilityRouter) {
r.fallback = m
}
}
// NewCapabilityRouter creates a new capability-based router.
// Models are checked in order; the first one satisfying all requirements is selected.
func NewCapabilityRouter(models []Model, opts ...CapabilityRouterOption) *CapabilityRouter {
r := &CapabilityRouter{
models: models,
detector: &DefaultCapabilityDetector{},
}
for _, opt := range opts {
opt(r)
}
return r
}
// Route selects a model based on required capabilities.
func (r *CapabilityRouter) Route(ctx context.Context, req *Request) (Model, error) {
required, err := r.detector.Detect(ctx, req)
if err != nil {
if r.fallback != nil {
return r.fallback, nil
}
return nil, err
}
// Find first model that supports all required capabilities
for _, m := range r.models {
caps := m.Capabilities()
if satisfies(caps, required) {
return m, nil
}
}
if r.fallback != nil {
return r.fallback, nil
}
return nil, ErrNoModelAvailable
}
// satisfies checks if 'has' capabilities satisfy 'needs' requirements.
func satisfies(has, needs Capabilities) bool {
// Check boolean capability requirements
boolChecks := []struct {
needed, provided bool
}{
{needs.Vision, has.Vision},
{needs.Tools, has.Tools},
{needs.NativeReasoning, has.NativeReasoning},
{needs.StructuredOutput, has.StructuredOutput},
{needs.Streaming, has.Streaming},
{needs.Audio, has.Audio},
{needs.Logprobs, has.Logprobs},
}
for _, check := range boolChecks {
if check.needed && !check.provided {
return false
}
}
// Check context window requirements
if needs.MaxContextTokens > 0 && has.MaxContextTokens > 0 {
if needs.MaxContextTokens > has.MaxContextTokens {
return false
}
}
return true
}
// CapabilityDetector detects required capabilities from a request.
type CapabilityDetector interface {
// Detect returns the capabilities required to handle the request.
Detect(ctx context.Context, req *Request) (Capabilities, error)
}
// DefaultCapabilityDetector detects capabilities from request content.
type DefaultCapabilityDetector struct {
// ReasoningKeywords are words that indicate reasoning capability is needed.
ReasoningKeywords []string
// TokensPerWord is used to estimate token count (default: 1.3)
TokensPerWord float64
}
// defaultReasoningKeywords indicate complex reasoning is needed.
var defaultReasoningKeywords = []string{
"step by step", "think through", "reason about", "chain of thought",
"explain your reasoning", "show your work", "logical", "deduce",
"prove", "derive", "theorem", "proof",
}
// Detect analyzes the request to determine required capabilities.
func (d *DefaultCapabilityDetector) Detect(ctx context.Context, req *Request) (Capabilities, error) {
var caps Capabilities
tokensPerWord := d.TokensPerWord
if tokensPerWord == 0 {
tokensPerWord = 1.3
}
keywords := d.ReasoningKeywords
if len(keywords) == 0 {
keywords = defaultReasoningKeywords
}
totalWords := 0
for _, msg := range req.Messages {
// Check parts for file content (images, audio, etc.)
for _, part := range msg.Parts() {
if fp, ok := part.(message.FilePart); ok {
// Check MIME type to determine capability needed
if strings.HasPrefix(fp.MimeType, "image/") {
caps.Vision = true
}
if strings.HasPrefix(fp.MimeType, "audio/") {
caps.Audio = true
}
}
// Check for function/tool calls in message parts
if _, ok := part.(message.FunctionCallPart); ok {
caps.Tools = true
}
}
// Count words for token estimation
text := msg.String()
totalWords += len(strings.Fields(text))
lowerText := strings.ToLower(text)
// Check for reasoning indicators
for _, kw := range keywords {
if strings.Contains(lowerText, kw) {
caps.NativeReasoning = true
break
}
}
}
// Check if tools are provided in the request
if len(req.Tools) > 0 {
caps.Tools = true
}
// Check if structured output is requested
if req.OutputSchema != nil {
caps.StructuredOutput = true
}
// Check if streaming is requested
if req.Stream {
caps.Streaming = true
}
// Estimate token count for context window requirement
estimatedTokens := int(float64(totalWords) * tokensPerWord)
if estimatedTokens > 8000 {
caps.MaxContextTokens = estimatedTokens
}
return caps, nil
}
// CapabilityScore calculates a score for how well a model matches requirements.
// Higher score means better match. Returns 0 if requirements are not met.
func CapabilityScore(has, needs Capabilities) int {
if !satisfies(has, needs) {
return 0
}
score := 100 // Base score for meeting requirements
// Bonus for extra capabilities
if has.Vision && !needs.Vision {
score += 5
}
if has.Tools && !needs.Tools {
score += 5
}
if has.NativeReasoning && !needs.NativeReasoning {
score += 10
}
if has.StructuredOutput && !needs.StructuredOutput {
score += 5
}
// Bonus for larger context window
if has.MaxContextTokens > needs.MaxContextTokens {
score += 5
}
return score
}
// BestMatchRouter routes to the model with the highest capability score.
type BestMatchRouter struct {
models []Model
fallback Model
detector CapabilityDetector
}
// NewBestMatchRouter creates a router that selects the best matching model.
func NewBestMatchRouter(models []Model, opts ...CapabilityRouterOption) *BestMatchRouter {
r := &BestMatchRouter{
models: models,
detector: &DefaultCapabilityDetector{},
}
// Apply same options as CapabilityRouter
for _, opt := range opts {
// Type assertion hack to reuse options
cr := &CapabilityRouter{}
opt(cr)
r.detector = cr.detector
if cr.fallback != nil {
r.fallback = cr.fallback
}
}
return r
}
// Route selects the model with the highest capability score.
func (r *BestMatchRouter) Route(ctx context.Context, req *Request) (Model, error) {
required, err := r.detector.Detect(ctx, req)
if err != nil {
if r.fallback != nil {
return r.fallback, nil
}
return nil, err
}
var bestModel Model
bestScore := 0
for _, m := range r.models {
caps := m.Capabilities()
score := CapabilityScore(caps, required)
if score > bestScore {
bestScore = score
bestModel = m
}
}
if bestModel != nil {
return bestModel, nil
}
if r.fallback != nil {
return r.fallback, nil
}
return nil, ErrNoModelAvailable
}