From 0d1f71b3928655e8cdbb909e44554971eb34782a Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Wed, 25 Nov 2026 13:51:10 +0000 Subject: [PATCH] feat(router): decision model assist near tier boundaries --- routes_unified.go | 2 +- routes_unified_router_test.go | 6 +- smart_router_bandit_test.go | 13 +- smart_router_classify.go | 92 +++++++++++-- smart_router_decision_assist_test.go | 185 +++++++++++++++++++++++++++ smart_router_eval_test.go | 2 +- smart_router_features.go | 27 ++-- smart_router_learn_test.go | 11 +- smart_router_metrics.go | 2 +- smart_router_plan.go | 16 ++- smart_router_plan_test.go | 15 ++- smart_router_session.go | 17 ++- smart_router_session_test.go | 7 +- smart_router_shadow_test.go | 7 +- smart_router_shared.go | 4 +- tools/yaegi-bench/main.go | 2 +- 16 files changed, 346 insertions(+), 62 deletions(-) create mode 100644 smart_router_decision_assist_test.go diff --git a/routes_unified.go b/routes_unified.go index 37362c6..6b902fd 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -290,7 +290,7 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop var candidates []resolveCandidate if rt := g.registry.routers[requestedModel]; rt != nil { var planErr error - plan, planErr = g.planSmartRouter(rt, req, endpoint, r.Header, grp, scopes) + plan, planErr = g.planSmartRouter(r.Context(), rt, req, endpoint, r.Header, grp, scopes) if planErr != nil { writeModelResolveErrorEnvelope(sw, planErr, envelope) return diff --git a/routes_unified_router_test.go b/routes_unified_router_test.go index 8bc5663..8e08246 100644 --- a/routes_unified_router_test.go +++ b/routes_unified_router_test.go @@ -464,9 +464,9 @@ func TestPlanSmartRouter_HashSelectionDedupeAndCap(t *testing.T) { first := map[string]bool{} for _, prompt := range []string{"alpha one", "beta two", "gamma three", "delta four", "epsilon five", "zeta six", "eta seven", "theta eight"} { req := map[string]any{"messages": []any{map[string]any{"role": "user", "content": prompt}}} - p1, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, grp, nil) + p1, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, grp, nil) require.NoError(t, err) - p2, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, grp, nil) + p2, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, grp, nil) require.NoError(t, err) require.Equal(t, p1.candidates(), p2.candidates(), "hash selection must be deterministic") first[p1.entries[0].cand.canonical] = true @@ -481,7 +481,7 @@ func TestPlanSmartRouter_HashSelectionDedupeAndCap(t *testing.T) { rt.maxAttempts = 2 req := map[string]any{"messages": []any{map[string]any{"role": "user", "content": "hi"}}} - p, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, grp, nil) + p, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, grp, nil) require.NoError(t, err) assert.Len(t, p.entries, 2, "plan must be capped at maxAttempts") } diff --git a/smart_router_bandit_test.go b/smart_router_bandit_test.go index dc6e237..773c6b6 100644 --- a/smart_router_bandit_test.go +++ b/smart_router_bandit_test.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "errors" "sort" "strconv" @@ -56,7 +57,7 @@ func TestBanditPermutationOnly(t *testing.T) { adGw, adRt := banditGateway(t, smartSelectionAdaptive, nil) adRt.bandit.rnd = newSmartRandom(7) for _, ask := range []string{"hi", "please review the architecture trade-offs of this distributed system design and prove its invariant"} { - want, err := ordGw.planSmartRouter(ordRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + want, err := ordGw.planSmartRouter(context.Background(), ordRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) wantKeys := planShape(want) sort.Strings(wantKeys) @@ -65,7 +66,7 @@ func TestBanditPermutationOnly(t *testing.T) { wantTiers = append(wantTiers, e.tier) } for i := 0; i < 100; i++ { - got, err := adGw.planSmartRouter(adRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + got, err := adGw.planSmartRouter(context.Background(), adRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) gotKeys := planShape(got) sort.Strings(gotKeys) @@ -87,10 +88,10 @@ func TestBanditOrderedUnchangedWhenOff(t *testing.T) { require.Nil(t, plainRt.bandit) require.Nil(t, hashRt.bandit, "adaptive settings alone never enable the bandit") for _, ask := range []string{"hi", "hello there", "summarize this"} { - a, err := plain.planSmartRouter(plainRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + a, err := plain.planSmartRouter(context.Background(), plainRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Nil(t, a.bandit) - b, err := hash.planSmartRouter(hashRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + b, err := hash.planSmartRouter(context.Background(), hashRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.ElementsMatch(t, planShape(a), planShape(b)) } @@ -227,7 +228,7 @@ func TestBanditLearnsFromCounters(t *testing.T) { func TestBanditObserveCountsReward(t *testing.T) { gw, rt := banditGateway(t, smartSelectionAdaptive, &SmartRouterAdaptiveConfig{ExplorePct: zeroPct()}) - plan, err := gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) require.NotNil(t, plan.bandit) read := func(i int) (int64, int64) { @@ -381,7 +382,7 @@ func TestBanditSelectionValidationAndAdminView(t *testing.T) { func TestBanditStartsLearningTicker(t *testing.T) { gw, rt := banditGateway(t, smartSelectionAdaptive, nil) - _, err := gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) + _, err := gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.True(t, gw.routerLearn.running) require.NoError(t, gw.Close()) diff --git a/smart_router_classify.go b/smart_router_classify.go index a62efc8..3673853 100644 --- a/smart_router_classify.go +++ b/smart_router_classify.go @@ -4,6 +4,7 @@ import "strings" const ( smartReasonScore = "score" + smartReasonModel = "model" smartReasonKeyword = "keyword" smartReasonFloor = "floor" smartReasonDefault = "default" @@ -62,14 +63,70 @@ type smartExtract struct { type smartClassification struct { reason string scoredText string - rank int + // decisionOutcome is the decision-model outcome; empty when no call was made. + decisionOutcome string + rank int // shadowRank is the rank the router's shadowWeights would have chosen, or -1 when unset. shadowRank int // score is the router's score before any risk margin, and hardRank the highest floor or keyword // rank; the saturation downgrade reads both. hardRank is 0 when nothing floors the request and includes the session pin. score int hardRank int - hasImage bool + // decisionTier is the rank the decision model answered, or -1 when it gave none. + decisionTier int + // heuristicRank is the rank before the decision model; meaningful only when decisionOutcome is set. + heuristicRank int + hasImage bool +} + +// smartAssist returns the model's view for a near-boundary request; nil means no assist. +type smartAssist func(f *smartFeatures) decisionAnswer + +// smartNearBoundary reports whether score sits within the decision band of a tier boundary. +func smartNearBoundary(rt *smartRouter, score int) bool { + for i := 1; i < len(rt.tiers); i++ { + d := score - rt.tierMin(i) + if d < 0 { + d = -d + } + if d <= rt.decision.band { + return true + } + } + return false +} + +// applyDecision folds a model answer into the heuristic rank, moving at most one tier toward the model. +func applyDecision(rt *smartRouter, rank int, ans decisionAnswer) (int, string) { + switch ans.outcome { + case decisionTimeout, decisionError, decisionBreaker: + return rank, ans.outcome + } + outcome := ans.outcome + if outcome == "" { + outcome = decisionOverride + } + newRank := rank + switch { + case ans.prob < rt.decision.minProb: + if ans.outcome == "" { + outcome = decisionLowConf + } + case ans.rank == rank: + if ans.outcome == "" { + outcome = decisionAgree + } + case ans.rank > rank: + newRank = rank + 1 + default: + newRank = rank - 1 + } + return newRank, outcome +} + +// smartTransportOutcome reports whether the outcome says the model gave no answer. +func smartTransportOutcome(outcome string) bool { + return outcome == decisionTimeout || outcome == decisionError || outcome == decisionBreaker } // classifySmartRequest scores req and returns the starting tier rank, why that @@ -84,14 +141,14 @@ func classifySmartRequest(rt *smartRouter, req map[string]any, endpoint string) // classifySmart is classifySmartRequest plus the shadow rank. The shadow pass // reuses the extracted features and only re-weights them. func classifySmart(rt *smartRouter, req map[string]any, endpoint string) smartClassification { - return classifySmartWith(rt, req, endpoint, nil, nil) + return classifySmartWith(rt, req, endpoint, nil, nil, nil) } -// classifySmartWith classifies with optional pre-extracted v2 features and session state. -// A v1 router passes the session to the shadow pass only, so it never routes on it. -func classifySmartWith(rt *smartRouter, req map[string]any, endpoint string, f *smartFeatures, sc *smartSessionRun) smartClassification { +// classifySmartWith classifies with optional pre-extracted v2 features, session state and decision assist. +// A v1 router passes the session to the shadow pass only, so it never routes on it or asks the assist. +func classifySmartWith(rt *smartRouter, req map[string]any, endpoint string, f *smartFeatures, sc *smartSessionRun, assist smartAssist) smartClassification { if rt.classifier == smartClassifierV2 { - out := classifySmartV2With(rt, req, endpoint, f, sc) + out := classifySmartV2With(rt, req, endpoint, f, sc, assist) if rt.shadowV2 { out.shadowRank = out.rank } @@ -99,7 +156,7 @@ func classifySmartWith(rt *smartRouter, req map[string]any, endpoint string, f * } out := classifySmartV1(rt, req, endpoint) if rt.shadowV2 { - out.shadowRank = classifySmartV2With(rt, req, endpoint, f, sc).rank + out.shadowRank = classifySmartV2With(rt, req, endpoint, f, sc, nil).rank } return out } @@ -107,7 +164,7 @@ func classifySmartWith(rt *smartRouter, req map[string]any, endpoint string, f * func classifySmartV1(rt *smartRouter, req map[string]any, endpoint string) smartClassification { ex := extractSmartRequest(req, endpoint) top := len(rt.tiers) - 1 - out := smartClassification{shadowRank: -1, hasImage: ex.hasImage} + out := smartClassification{shadowRank: -1, hasImage: ex.hasImage, decisionTier: -1, heuristicRank: -1} floorRank := 0 if ex.hasTools || ex.toolHist { @@ -446,14 +503,14 @@ func smartContentSize(content any, depth int) (chars, images int) { // classifySmartV2With is the v2 counterpart of classifySmartV1: it scores the prose of // the newest ask with an uncertainty margin, then raises the tier for floors and // keyword rules. It never lowers a rank. -// It takes optional pre-extracted features and session state. -func classifySmartV2With(rt *smartRouter, req map[string]any, endpoint string, f *smartFeatures, sc *smartSessionRun) smartClassification { +// It takes optional pre-extracted features, session state and decision assist. +func classifySmartV2With(rt *smartRouter, req map[string]any, endpoint string, f *smartFeatures, sc *smartSessionRun, assist smartAssist) smartClassification { if f == nil { ext := extractSmartV2(req, endpoint) f = &ext } top := len(rt.tiers) - 1 - out := smartClassification{shadowRank: -1, hasImage: f.hasImage} + out := smartClassification{shadowRank: -1, hasImage: f.hasImage, decisionTier: -1, heuristicRank: -1} floorRank := 0 if f.hasTools || f.toolHist { @@ -506,6 +563,17 @@ func classifySmartV2With(rt *smartRouter, req map[string]any, endpoint string, f rank, reason, next = smartSessionRoute(&rt.session, top, f, sc.sess, verdict, sc.now, askHash) out.hardRank = smartMaxInt(out.hardRank, next.pin) } + if assist != nil && reason == smartReasonScore && f.found && smartNearBoundary(rt, verdict.score) { + ans := assist(f) + newRank, outcome := applyDecision(rt, rank, ans) + out.heuristicRank, out.decisionOutcome = rank, outcome + if !smartTransportOutcome(ans.outcome) { + out.decisionTier = ans.rank + } + if rt.decision.live && newRank != rank { + rank, reason = newRank, smartReasonModel + } + } out.rank, out.reason = smartRaiseRank(rank, reason, kwRank, floorRank) if sc != nil { sc.finish(next, out.rank) diff --git a/smart_router_decision_assist_test.go b/smart_router_decision_assist_test.go new file mode 100644 index 0000000..3800d50 --- /dev/null +++ b/smart_router_decision_assist_test.go @@ -0,0 +1,185 @@ +package traefikllmgateway + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func assistRouter(t *testing.T, band int, live bool, session bool) *smartRouter { + t.Helper() + rt := newClassifyTestRouter(t, func(c *SmartRouterConfig) { + c.Classifier = smartClassifierV2 + c.Tiers = []SmartRouterTier{ + {Name: "cheap", MinScore: 0, Models: []string{"openai/gpt-mini"}}, + {Name: "mid", MinScore: 350, Models: []string{"openai/gpt-mid"}}, + {Name: "top", MinScore: 600, Models: []string{"openai/gpt-top"}}, + } + if session { + c.Session = &SmartRouterSessionConfig{Enabled: true} + } + }) + rt.decision = &smartDecisionCfg{band: band, minProb: 700, live: live} + return rt +} + +type stubAssist struct { + ans decisionAnswer + calls int +} + +func (s *stubAssist) fn(*smartFeatures) decisionAnswer { + s.calls++ + return s.ans +} + +const assistAsk = "hello there" + +func TestSmartNearBoundary(t *testing.T) { + rt := assistRouter(t, 100, true, false) + assert.True(t, smartNearBoundary(rt, 300)) + assert.False(t, smartNearBoundary(rt, 120)) + assert.True(t, smartNearBoundary(rt, 690)) +} + +func TestApplyDecision(t *testing.T) { + rt := assistRouter(t, 100, true, false) + tests := []struct { + name string + wantOutcome string + ans decisionAnswer + rank int + wantRank int + }{ + {"override up one step", decisionOverride, decisionAnswer{rank: 2, prob: 900}, 0, 1}, + {"override down one step", decisionOverride, decisionAnswer{rank: 0, prob: 900}, 2, 1}, + {"agree", decisionAgree, decisionAnswer{rank: 1, prob: 800}, 1, 1}, + {"low confidence", decisionLowConf, decisionAnswer{rank: 0, prob: 650}, 1, 1}, + {"breaker", decisionBreaker, decisionAnswer{outcome: decisionBreaker}, 1, 1}, + {"timeout", decisionTimeout, decisionAnswer{outcome: decisionTimeout, rank: 2, prob: 999}, 1, 1}, + {"cache override", decisionCache, decisionAnswer{outcome: decisionCache, rank: 1, prob: 900}, 0, 1}, + {"cache low confidence keeps rank", decisionCache, decisionAnswer{outcome: decisionCache, rank: 2, prob: 100}, 0, 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotRank, gotOutcome := applyDecision(rt, tt.rank, tt.ans) + assert.Equal(t, tt.wantRank, gotRank) + assert.Equal(t, tt.wantOutcome, gotOutcome) + }) + } +} + +func TestClassifyDecisionLiveOverrides(t *testing.T) { + rt := assistRouter(t, 1000, true, false) + plain := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, nil) + stub := &stubAssist{ans: decisionAnswer{rank: 2, prob: 900}} + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, stub.fn) + assert.Equal(t, 1, stub.calls) + assert.Equal(t, plain.rank+1, cls.rank) + assert.Equal(t, smartReasonModel, cls.reason) + assert.Equal(t, decisionOverride, cls.decisionOutcome) + assert.Equal(t, 2, cls.decisionTier) + assert.Equal(t, plain.rank, cls.heuristicRank) +} + +func TestClassifyDecisionShadowKeepsRank(t *testing.T) { + rt := assistRouter(t, 1000, false, false) + plain := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, nil) + stub := &stubAssist{ans: decisionAnswer{rank: 2, prob: 900}} + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, stub.fn) + assert.Equal(t, 1, stub.calls) + assert.Equal(t, plain.rank, cls.rank) + assert.Equal(t, plain.reason, cls.reason) + assert.Equal(t, decisionOverride, cls.decisionOutcome) + assert.Equal(t, 2, cls.decisionTier) +} + +func TestClassifyDecisionTransportFailureHasNoTier(t *testing.T) { + rt := assistRouter(t, 1000, true, false) + plain := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, nil) + stub := &stubAssist{ans: decisionAnswer{outcome: decisionTimeout}} + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, stub.fn) + assert.Equal(t, plain.rank, cls.rank) + assert.Equal(t, plain.reason, cls.reason) + assert.Equal(t, decisionTimeout, cls.decisionOutcome) + assert.Equal(t, -1, cls.decisionTier) +} + +func TestClassifyDecisionFarFromBoundarySkips(t *testing.T) { + rt := assistRouter(t, 100, true, false) + stub := &stubAssist{ans: decisionAnswer{rank: 2, prob: 900}} + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, stub.fn) + require.Less(t, cls.score, 100, "the greeting must score far from the first boundary") + assert.Equal(t, 0, stub.calls) + assert.Equal(t, -1, cls.decisionTier) + assert.Equal(t, "", cls.decisionOutcome) +} + +func TestClassifyDecisionNoAssistKeepsDefaults(t *testing.T) { + rt := assistRouter(t, 100, true, false) + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, nil, nil, nil) + assert.Equal(t, -1, cls.decisionTier) + assert.Equal(t, "", cls.decisionOutcome) +} + +func TestClassifyDecisionSessionPinnedSkips(t *testing.T) { + rt := assistRouter(t, 1000, true, true) + stub := &stubAssist{ans: decisionAnswer{rank: 0, prob: 900}} + f := extractSmartV2(userReq(assistAsk), cacheEndpointChat) + sc := &smartSessionRun{rt: rt, key: "k", now: 1010, sess: smartSession{found: true, pin: 2, loop: 2, seenAt: 1000, askAt: 1000, askHash: 1, msgCount: 1}} + cls := classifySmartWith(rt, userReq(assistAsk), cacheEndpointChat, &f, sc, stub.fn) + require.Equal(t, smartReasonSession, cls.reason) + assert.Equal(t, 0, stub.calls) + assert.Equal(t, -1, cls.decisionTier) +} + +func TestClassifyDecisionFloorStillRaises(t *testing.T) { + rt := assistRouter(t, 1000, true, false) + req := userReq(assistAsk) + req["reasoning_effort"] = "high" + stub := &stubAssist{ans: decisionAnswer{rank: 0, prob: 990}} + cls := classifySmartWith(rt, req, cacheEndpointChat, nil, nil, stub.fn) + assert.Equal(t, 2, cls.rank) + assert.Equal(t, smartReasonFloor, cls.reason) +} + +func TestExtractSmartV2KeepsRawAsk(t *testing.T) { + f := extractSmartV2(userReq("Fix this:\n```\ncode\n```"), cacheEndpointChat) + assert.Equal(t, "Fix this:\n```\ncode\n```", f.ask) +} + +func TestRouterReasonNamesIncludeModel(t *testing.T) { + assert.Equal(t, 11, routerReasonsMax) + assert.Equal(t, smartReasonBump, routerReasonNames[7]) + assert.Equal(t, smartReasonModel, routerReasonNames[8]) + assert.Equal(t, routerReasonFallback, routerReasonNames[routerReasonsMax-1]) +} + +func TestPlanSmartRouterDecisionTimeoutFallsBack(t *testing.T) { + slow := func(w http.ResponseWriter, r *http.Request) { + select { + case <-time.After(400 * time.Millisecond): + case <-r.Context().Done(): + } + okHandler(w, r) + } + f := newDecisionFixture(t, 3, "50ms", slow) + f.rt.decision.live = true + f.rt.decision.band = 1000 + base := newDecisionFixture(t, 3, "50ms", slow) + base.rt.decision = nil + + req := userReq(assistAsk) + got, err := f.g.planSmartRouter(context.Background(), f.rt, req, cacheEndpointChat, nil, &group{}, nil) + require.NoError(t, err) + want, err := base.g.planSmartRouter(context.Background(), base.rt, req, cacheEndpointChat, nil, &group{}, nil) + require.NoError(t, err) + assert.Equal(t, want.startTier, got.startTier) + assert.Equal(t, decisionTimeout, got.decisionOutcome) + assert.Equal(t, got.startTier, got.heuristicTier) + assert.Equal(t, "", got.decisionTier) +} diff --git a/smart_router_eval_test.go b/smart_router_eval_test.go index c53ca89..a705234 100644 --- a/smart_router_eval_test.go +++ b/smart_router_eval_test.go @@ -322,7 +322,7 @@ func evalSessionRouter(tb testing.TB, mins [3]int) *smartRouter { func classifyInSession(rt *smartRouter, req map[string]any, endpoint string, st smartSession, now int64) (smartClassification, *smartSessionRun) { f := extractSmartV2(req, endpoint) sc := &smartSessionRun{rt: rt, key: "eval", sess: st, now: now} - return classifySmartWith(rt, req, endpoint, &f, sc), sc + return classifySmartWith(rt, req, endpoint, &f, sc, nil), sc } // replaySession runs every earlier user ask of the fixture's conversation through the router in order. diff --git a/smart_router_features.go b/smart_router_features.go index 1c0fdf6..98e8d2f 100644 --- a/smart_router_features.go +++ b/smart_router_features.go @@ -76,18 +76,20 @@ type smartFeatures struct { // prose is the ask without fenced code and paste paragraphs; lower is its lowercase form. prose, lower string system string - intent int - hard int - codeBytes int - logBytes int - msgCount int - questions int - toolSeen int - lists int - promptBytes int - outTokens int64 - jsonMode int - nonLatin bool + // ask is the raw newest ask, bounded, for the decision model. + ask string + intent int + hard int + codeBytes int + logBytes int + msgCount int + questions int + toolSeen int + lists int + promptBytes int + outTokens int64 + jsonMode int + nonLatin bool // foreign marks prose the English markers cannot classify. foreign bool truncated bool @@ -150,6 +152,7 @@ func extractSmartV2(req map[string]any, endpoint string) smartFeatures { f.truncated = len(msgs) > smartAskScanMax return f } + f.ask = boundSmartText(ask, smartTextCap) f.splitAsk(ask) f.classifyIntent() return f diff --git a/smart_router_learn_test.go b/smart_router_learn_test.go index 3da052d..dad14ad 100644 --- a/smart_router_learn_test.go +++ b/smart_router_learn_test.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "testing" "time" @@ -115,9 +116,9 @@ func TestCalibShadowNoEffect(t *testing.T) { assert.Equal(t, 300, shadowRt.tierMin(1)) req := userReq(sessionLongAsk()) - a, err := shadowGw.planSmartRouter(shadowRt, req, cacheEndpointChat, nil, &group{}, nil) + a, err := shadowGw.planSmartRouter(context.Background(), shadowRt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) - b, err := offGw.planSmartRouter(offRt, req, cacheEndpointChat, nil, &group{}, nil) + b, err := offGw.planSmartRouter(context.Background(), offRt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, planShape(b), planShape(a)) assert.Equal(t, b.reason, a.reason) @@ -185,7 +186,7 @@ func TestCalibCountsOnlyScoreOutcomes(t *testing.T) { func TestCalibOffWritesNothing(t *testing.T) { gw, rt := calibGateway(t, nil) require.Nil(t, rt.calibState) - plan, err := gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.False(t, plan.calibrate) gw.countCalibration(plan, 0, true, true) @@ -346,9 +347,9 @@ func TestCalibOffPlansIdentical(t *testing.T) { plain, plainRt := calibGateway(t, nil) off, offRt := calibGateway(t, &SmartRouterCalibrationConfig{Mode: smartCalibOff}) for _, ask := range []string{"hi", sessionLongAsk(), "prove the lemma and derive the invariant for this scheduler", "summarize this"} { - a, err := plain.planSmartRouter(plainRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + a, err := plain.planSmartRouter(context.Background(), plainRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) - b, err := off.planSmartRouter(offRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) + b, err := off.planSmartRouter(context.Background(), offRt, userReq(ask), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, planShape(a), planShape(b), ask) assert.Equal(t, a.reason, b.reason, ask) diff --git a/smart_router_metrics.go b/smart_router_metrics.go index c09ceef..fbd68ff 100644 --- a/smart_router_metrics.go +++ b/smart_router_metrics.go @@ -262,7 +262,7 @@ func (g *Gateway) writeRouterMetrics(m *metricWriter) { return x.reason < y.reason }) m.family("llmgateway_router_requests_total", "counter", - "Smart router requests by router, first attempted tier and routing reason (score, keyword, floor, default, or skipped when lower tiers had no usable target)."+aggregationNotePerProcess) + "Smart router requests by router, first attempted tier and routing reason (score, keyword, floor, model, default, or skipped when lower tiers had no usable target)."+aggregationNotePerProcess) for _, k := range keys { m.sampleInt("llmgateway_router_requests_total", []metricLabel{{"router", k.router}, {"tier", k.tier}, {"reason", k.reason}}, reqs[k]) diff --git a/smart_router_plan.go b/smart_router_plan.go index 9f4276f..387a2f2 100644 --- a/smart_router_plan.go +++ b/smart_router_plan.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "fmt" "hash/fnv" "net/http" @@ -44,6 +45,10 @@ type routerPlan struct { startTier string // shadowTier is the tier the router's shadowWeights chose; empty when unset. shadowTier string + // heuristicTier, decisionTier and decisionOutcome describe the decision-model call; empty when none was made. + heuristicTier string + decisionTier string + decisionOutcome string // downgradedFrom is the classified tier a saturation downgrade started below; empty when not downgraded. downgradedFrom string router string @@ -109,7 +114,7 @@ func smartTextHash(s string) int { // Invariants plan_bounded (at most maxAttempts entries) and downgrade_gated (a lower start needs the // saturation gate) have one runtime exception: with timeoutFallback, addTimeoutFallback appends one // lower-tier entry after an all-slow plan, so entries can reach maxAttempts+1. -func (g *Gateway) planSmartRouter(rt *smartRouter, req map[string]any, endpoint string, hdr http.Header, grp *group, scopes []limitScope) (*routerPlan, error) { +func (g *Gateway) planSmartRouter(ctx context.Context, rt *smartRouter, req map[string]any, endpoint string, hdr http.Header, grp *group, scopes []limitScope) (*routerPlan, error) { if !grp.allowsModelName(rt.name) { return nil, errModelDenied } @@ -119,7 +124,7 @@ func (g *Gateway) planSmartRouter(rt *smartRouter, req map[string]any, endpoint g.registry.noteRouterShadow(rt.name, grp) g.touchRouterLearning(rt) - cls, sess := g.classifyWithSession(rt, req, endpoint, hdr, scopes) + cls, sess := g.classifyWithSession(ctx, rt, req, endpoint, hdr, scopes) start, reason, scored, hasImage := cls.rank, cls.reason, cls.scoredText, cls.hasImage promptBytes, imageTokens := smartPromptBytes(req, endpoint) facts := routerRequestFacts{ @@ -133,6 +138,13 @@ func (g *Gateway) planSmartRouter(rt *smartRouter, req map[string]any, endpoint if cls.shadowRank >= 0 { plan.shadowTier = rt.tiers[cls.shadowRank].name } + if cls.decisionOutcome != "" { + plan.decisionOutcome = cls.decisionOutcome + plan.heuristicTier = rt.tiers[cls.heuristicRank].name + if cls.decisionTier >= 0 { + plan.decisionTier = rt.tiers[cls.decisionTier].name + } + } seen := make(map[string]bool) var skips routerSkips diff --git a/smart_router_plan_test.go b/smart_router_plan_test.go index 6064d77..73708ac 100644 --- a/smart_router_plan_test.go +++ b/smart_router_plan_test.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "strings" "testing" @@ -36,7 +37,7 @@ func TestPlanSmartRouter_ContextEstimateIgnoresImageBytes(t *testing.T) { map[string]any{"type": "text", "text": "what is this"}, map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64," + huge}}, }) - plan, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, "alpha/a1", plan.entries[0].cand.canonical, "image bytes must not count as prompt tokens") } @@ -51,7 +52,7 @@ func TestPlanSmartRouter_ContextEstimateCountsWholeConversation(t *testing.T) { map[string]any{"role": "assistant", "content": "ok"}, map[string]any{"role": "user", "content": "hi"}, }} - plan, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, "gamma/c1", plan.entries[0].cand.canonical, "earlier turns must count toward the context estimate") } @@ -61,7 +62,7 @@ func TestPlanSmartRouter_ContextSkipsEliminatingEverythingFallBackToLargest(t *t c.ModelMeta = map[string]*ModelMetaConfig{"a1": {ContextTokens: 50}, "c1": {ContextTokens: 80}} twoTiers(c, "a1") }) - plan, err := gw.planSmartRouter(rt, userReq(strings.Repeat("word ", 400)), cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, userReq(strings.Repeat("word ", 400)), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err, "context skips alone must not 404") require.Len(t, plan.entries, 1) assert.Equal(t, "gamma/c1", plan.entries[0].cand.canonical) @@ -78,7 +79,7 @@ func TestPlanSmartRouter_ReservesSlotForHigherTier(t *testing.T) { c.SmartRouters[routerName].KeywordRules = nil c.SmartRouters[routerName].MaxAttempts = 3 }) - plan, err := gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) var tiers []string for _, e := range plan.entries { @@ -87,7 +88,7 @@ func TestPlanSmartRouter_ReservesSlotForHigherTier(t *testing.T) { assert.Equal(t, []string{"t0", "t0", "t1"}, tiers, "the last slot must stay reachable for the higher tier") rt.maxAttempts = 1 - plan, err = gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) + plan, err = gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) require.Len(t, plan.entries, 1) assert.Equal(t, "t0", plan.entries[0].tier, "a single attempt still starts at the classified tier") @@ -103,7 +104,7 @@ func TestPlanSmartRouter_NoUsableTargetMessageHidesDeniedCount(t *testing.T) { c.SmartRouters[routerName].KeywordRules = nil }) grp := &group{models: []string{routerName, "b1"}} - _, err := gw.planSmartRouter(rt, userReq("hi"), cacheEndpointChat, nil, grp, nil) + _, err := gw.planSmartRouter(context.Background(), rt, userReq("hi"), cacheEndpointChat, nil, grp, nil) rerr, ok := err.(*routerTargetError) require.True(t, ok, "got %v", err) assert.Equal(t, 404, rerr.status) @@ -162,7 +163,7 @@ func TestModelRegistry_ListFor_RouterHidesBareDiscoveredIDForEveryCaller(t *test func firstPlanModel(t *testing.T, gw *Gateway, rt *smartRouter, req map[string]any, endpoint string) string { t.Helper() - plan, err := gw.planSmartRouter(rt, req, endpoint, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, req, endpoint, nil, &group{}, nil) require.NoError(t, err) return plan.entries[0].cand.canonical } diff --git a/smart_router_session.go b/smart_router_session.go index cd1c736..544b70a 100644 --- a/smart_router_session.go +++ b/smart_router_session.go @@ -2,6 +2,7 @@ package traefikllmgateway import ( "container/list" + "context" "crypto/sha256" "encoding/hex" "fmt" @@ -589,13 +590,23 @@ func (rs *routerSessions) open(rt *smartRouter, req map[string]any, f *smartFeat } // classifyWithSession classifies the request, with session state when the router uses it. -func (g *Gateway) classifyWithSession(rt *smartRouter, req map[string]any, endpoint string, hdr http.Header, scopes []limitScope) (smartClassification, *smartSessionRun) { +func (g *Gateway) classifyWithSession(ctx context.Context, rt *smartRouter, req map[string]any, endpoint string, hdr http.Header, scopes []limitScope) (smartClassification, *smartSessionRun) { + var assist smartAssist + if rt.decision != nil { + assist = func(f *smartFeatures) decisionAnswer { + return g.askDecisionModel(ctx, rt, decisionState(f.system, f.ask)) + } + } if !rt.session.active() || g.routerSessions == nil { - return classifySmart(rt, req, endpoint), nil + if assist == nil { + return classifySmart(rt, req, endpoint), nil + } + f := extractSmartV2(req, endpoint) + return classifySmartWith(rt, req, endpoint, &f, nil, assist), nil } f := extractSmartV2(req, endpoint) sc := g.routerSessions.open(rt, req, &f, hdr, scopes) - cls := classifySmartWith(rt, req, endpoint, &f, sc) + cls := classifySmartWith(rt, req, endpoint, &f, sc, assist) return cls, sc } diff --git a/smart_router_session_test.go b/smart_router_session_test.go index 113665d..2a8385c 100644 --- a/smart_router_session_test.go +++ b/smart_router_session_test.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "errors" "net/http" "reflect" @@ -93,7 +94,7 @@ func sessionReq(userID string, asks ...string) map[string]any { func planOf(t *testing.T, gw *Gateway, rt *smartRouter, req map[string]any) *routerPlan { t.Helper() - plan, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) return plan } @@ -489,7 +490,7 @@ func TestSessionRedisDownFailsUp(t *testing.T) { stateless, rtStateless := planTestGateway(t, func(c *Config) { c.SmartRouters[routerName].Classifier = smartClassifierV2 }) for i := 0; i < 3; i++ { req := sessionReq("u1", routerKeyword, "thanks") - plan, err := gw.planSmartRouter(rt, req, cacheEndpointChat, nil, &group{}, nil) + plan, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err, "a Redis outage must never fail a request") want := planOf(t, stateless, rtStateless, req) assert.GreaterOrEqual(t, rt.rankOf(plan.startTier), rt.rankOf(want.startTier), "a miss fails up, never below the stateless rank") @@ -523,7 +524,7 @@ func TestNoPromptTextStored(t *testing.T) { hdr := http.Header{} hdr.Set("X-Session-Id", secrets[3]) send := func(req map[string]any, h http.Header) { - plan, err := gw.planSmartRouter(rt, req, cacheEndpointChat, h, &group{}, []limitScope{{kind: "user", id: "alice"}}) + plan, err := gw.planSmartRouter(context.Background(), rt, req, cacheEndpointChat, h, &group{}, []limitScope{{kind: "user", id: "alice"}}) require.NoError(t, err) gw.onRouterOutcome(plan, 0, true, true) } diff --git a/smart_router_shadow_test.go b/smart_router_shadow_test.go index 3ef1731..717be2f 100644 --- a/smart_router_shadow_test.go +++ b/smart_router_shadow_test.go @@ -1,6 +1,7 @@ package traefikllmgateway import ( + "context" "strings" "testing" @@ -65,9 +66,9 @@ func TestPlanSmartRouter_ShadowNeverChangesRouting(t *testing.T) { withShadow, rtShadow := planTestGateway(t, func(c *Config) { c.SmartRouters[routerName].ShadowWeights = zeroCodeShadow() }) without, rtPlain := planTestGateway(t, nil) for _, text := range []string{shadowCodeAsk, strongAsk, "hello"} { - a, err := withShadow.planSmartRouter(rtShadow, userReq(text), cacheEndpointChat, nil, &group{}, nil) + a, err := withShadow.planSmartRouter(context.Background(), rtShadow, userReq(text), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) - b, err := without.planSmartRouter(rtPlain, userReq(text), cacheEndpointChat, nil, &group{}, nil) + b, err := without.planSmartRouter(context.Background(), rtPlain, userReq(text), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, b.startTier, a.startTier, text) assert.Equal(t, b.reason, a.reason, text) @@ -77,7 +78,7 @@ func TestPlanSmartRouter_ShadowNeverChangesRouting(t *testing.T) { assert.Equal(t, b.entries[i].tier, a.entries[i].tier, text) } } - p, err := withShadow.planSmartRouter(rtShadow, userReq(shadowCodeAsk), cacheEndpointChat, nil, &group{}, nil) + p, err := withShadow.planSmartRouter(context.Background(), rtShadow, userReq(shadowCodeAsk), cacheEndpointChat, nil, &group{}, nil) require.NoError(t, err) assert.Equal(t, "t1", p.startTier) assert.Equal(t, "t0", p.shadowTier) diff --git a/smart_router_shared.go b/smart_router_shared.go index 239560b..3bb9563 100644 --- a/smart_router_shared.go +++ b/smart_router_shared.go @@ -12,10 +12,10 @@ const ( metricRouterShd = "rshd" metricRouterOut = "rout" routerKeySep = "/" - routerReasonsMax = 10 + routerReasonsMax = 11 ) -var routerReasonNames = [routerReasonsMax]string{smartReasonScore, smartReasonKeyword, smartReasonFloor, smartReasonDefault, routerReasonSkipped, smartReasonSession, smartReasonLoop, smartReasonBump, smartReasonSaturated, routerReasonFallback} +var routerReasonNames = [routerReasonsMax]string{smartReasonScore, smartReasonKeyword, smartReasonFloor, smartReasonDefault, routerReasonSkipped, smartReasonSession, smartReasonLoop, smartReasonBump, smartReasonModel, smartReasonSaturated, routerReasonFallback} func routerReqKeyFor(k routerRequestKey, bucket string) string { return windowKeyForBucket(kindRouter, k.router, metricRouterReq+routerKeySep+k.tier+routerKeySep+k.reason, windowMonth, bucket) diff --git a/tools/yaegi-bench/main.go b/tools/yaegi-bench/main.go index eaba81c..b80586b 100644 --- a/tools/yaegi-bench/main.go +++ b/tools/yaegi-bench/main.go @@ -444,7 +444,7 @@ func BenchRun(n int) int { if benchSessions != nil { f := extractSmartV2(fx.Request, endpoint) sc := benchSessions.open(benchRouter, fx.Request, &f, nil, nil) - sum += classifySmartWith(benchRouter, fx.Request, endpoint, &f, sc).rank + 1 + sum += classifySmartWith(benchRouter, fx.Request, endpoint, &f, sc, nil).rank + 1 if sc.dirty { benchSessions.put(sc.key, sc.next, time.Hour) }