Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions acceleration/internal/api/fallback_answer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package api

import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/llm"
"github.com/GetStream/Vision-Agents/acceleration/internal/llm/anthropic"
"github.com/GetStream/Vision-Agents/acceleration/internal/llm/openai"
"github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter"
"github.com/GetStream/Vision-Agents/acceleration/internal/options"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
"github.com/GetStream/Vision-Agents/acceleration/internal/search"
"github.com/GetStream/Vision-Agents/acceleration/internal/searchrouter"
)

// FallbackAnswerSuite is what a caller is told when a model failed and its fallbacks were
// refused: only a refusal's own text, or that something went wrong.
type FallbackAnswerSuite struct {
suite.Suite
}

func TestFallbackAnswerSuite(t *testing.T) {
suite.Run(t, new(FallbackAnswerSuite))
}

// allowingOnly is a customer whose policies allow only the models named.
type allowingOnly []string

func (a allowingOnly) Admit(context.Context, routing.Owner) (routing.Admission, error) {
return routing.Admission{Models: a}, nil
}

// erringSearch is a search vendor that fails every query with err.
type erringSearch struct{ err error }

func (f erringSearch) Search(context.Context, search.Query) (search.Result, error) {
return search.Result{}, f.err
}
func (erringSearch) Start(context.Context) error { return nil }
func (erringSearch) Close() error { return nil }
func (erringSearch) Provider() string { return "stub" }
func (erringSearch) Model() string { return "fast" }

func (s *FallbackAnswerSuite) TestATurnWhoseFallbackThePolicyDoesNotAllowAnswersSomethingWentWrong() {
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprint(w, `{"error":{"message":"vendor-internal-body","type":"server_error"}}`)
}))
s.T().Cleanup(vendor.Close)
registry := llmrouter.NewRegistry()
registry.Register("openai", func(spec routing.Spec) (llmrouter.Provider, error) {
return llmrouter.Started(openai.New(openai.Options{APIKey: "test", BaseURL: vendor.URL, Model: spec.Model}))
})
registry.Register("anthropic", func(spec routing.Spec) (llmrouter.Provider, error) {
return llmrouter.Started(anthropic.New(anthropic.Options{APIKey: "test", BaseURL: vendor.URL, Model: spec.Model}))
})
router, err := llmrouter.New(llmrouter.Options{Registry: registry, Gate: allowingOnly{"openai/gpt-5.6-luna"}, Config: routing.ModalityConfig{
Providers: []routing.ProviderConfig{
{Provider: "openai", Model: "gpt-5.6-luna", Languages: []string{"en"}},
{Provider: "anthropic", Model: "claude-opus-5", Languages: []string{"en"}},
},
}})
s.Require().NoError(err)
s.T().Cleanup(router.Close)
session, err := router.Start(s.T().Context(), llmrouter.Request{CustomerID: "acme", Providers: []string{"openai/gpt-5.6-luna", "anthropic/claude-opus-5"}})
s.Require().NoError(err)
s.T().Cleanup(func() { _ = session.Close() })

_, err = session.Create(s.T().Context(), llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}})

s.Require().Error(err)
s.Equal(somethingWentWrong, refusalText(err))
}

// searched is the error a search on a priority list of quick/fast and spare/fast answers,
// quick failing with quickErr and spare with spareErr; allowed, when set, is every model the
// customer's policies allow.
func (s *FallbackAnswerSuite) searched(quickErr, spareErr error, allowed ...string) error {
registry := searchrouter.NewRegistry()
registry.Register("quick", func(routing.Spec) (search.Provider, error) { return erringSearch{err: quickErr}, nil })
registry.Register("spare", func(routing.Spec) (search.Provider, error) { return erringSearch{err: spareErr}, nil })
opts := searchrouter.Options{Registry: registry, Config: routing.ModalityConfig{
Providers: []routing.ProviderConfig{
{Provider: "quick", Model: "fast", Languages: []string{"en"}},
{Provider: "spare", Model: "fast", Languages: []string{"en"}},
},
}}
if len(allowed) > 0 {
opts.Gate = allowingOnly(allowed)
}
router, err := searchrouter.New(opts)
s.Require().NoError(err)
s.T().Cleanup(router.Close)
session, err := router.Start(s.T().Context(), searchrouter.Request{CustomerID: "acme", Target: "quick/fast",
Options: options.Search{Providers: []string{"quick/fast", "spare/fast"}}})
s.Require().NoError(err)

_, err = session.Search(s.T().Context(), search.Query{Text: "traffic"})
s.Require().Error(err)
return searchFailed(s.T().Context(), err)
}

func (s *FallbackAnswerSuite) TestASearchWhoseFallbackThePolicyDoesNotAllowAnswersSomethingWentWrong() {
answer := s.searched(errors.New(`GET "https://vendor.example.com/search": 502 vendor-internal-body`), nil, "quick/fast")

_, refused := answer.(interface{ apiError() APIError })
s.False(refused, "a failure goes on as is, and the caller is told only that something went wrong")
}

func (s *FallbackAnswerSuite) TestASearchEveryModelRefusedAnswersTheirTexts() {
answer := s.searched(routing.Refused(errors.New("the query is too long")), routing.Refused(errors.New("the query is too long")))

refused, ok := answer.(interface{ apiError() APIError })
s.Require().True(ok)
s.Equal("quick/fast: the query is too long\nspare/fast: the query is too long\nsearchrouter: no fallback provider available",
refused.apiError().Message)
}
39 changes: 39 additions & 0 deletions acceleration/internal/api/session_create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,45 @@ func (s *SessionCreateSuite) TestASessionOnAModelOfTheCustomersOwnIsAnsweredByIt
s.Equal("https://8.8.8.8/v1 acme/tuned-27b sk-own", s.answerTo(opened.Id, "Hello?"))
}

// priorityListAgent is an agent config whose llm is first and whose llm_fallbacks follow it, so a
// session opened on it starts a priority list.
func (s *SessionCreateSuite) priorityListAgent(first string, fallbacks ...string) *string {
var created AgentConfig
s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/configs", AgentConfigRequest{
Name: "agent-" + s.utils.uuid(), Llm: pointerTo(first), LlmFallbacks: &fallbacks,
}, &created))
return &created.Id
}

func (s *SessionCreateSuite) TestAPriorityListWhoseModelKeyFailsToOpenAnswersSomethingWentWrong() {
name := "broken-" + s.utils.uuid()
sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.utils.uuid()))
s.Require().NoError(err)
s.Require().NoError(s.store.CustomModels.Insert(context.Background(), &store.CustomModel{
CustomerID: s.customerID(), Name: name, BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned-27b",
APIKeySealed: sealed, KEKVersion: s.sealer.CurrentVersion(),
}))
request := textSession(nil)
request.ConfigId = s.priorityListAgent("custom/"+name, "custom/not-there-"+s.utils.uuid())

status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", request)

s.Equal(http.StatusInternalServerError, status)
s.Equal(somethingWentWrong, failure, "the key's failure is the router's, and a refused entry beside it does not make it the caller's")
}

func (s *SessionCreateSuite) TestAPriorityListOfModelsTheCustomerDoesNotHoldIsRefusedWithTheirNames() {
first, second := "not-there-"+s.utils.uuid(), "gone-"+s.utils.uuid()
request := textSession(nil)
request.ConfigId = s.priorityListAgent("custom/"+first, "custom/"+second)

status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", request)

s.Equal(http.StatusBadRequest, status)
s.Contains(failure, "custom/"+first+`" is not one of this customer's models`)
s.Contains(failure, "custom/"+second+`" is not one of this customer's models`)
}

func (s *SessionCreateSuite) TestARoleOutsideUserAndAssistantIsRefused() {
status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", map[string]any{
"text": true, "incognito": true, "llm": "recites/recites-model",
Expand Down
35 changes: 35 additions & 0 deletions acceleration/internal/api/streams_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,41 @@ func (s *StreamsSuite) TestAnotherCustomersModelIsNotOneThisCustomerCanName() {
s.Contains(refused["error"], "not one of this customer's models")
}

// brokenKeyModel stores a custom model whose key was sealed for another row, so opening it fails.
func (s *StreamsSuite) brokenKeyModel() string {
name := "broken-" + s.utils.uuid()
sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.utils.uuid()))
s.Require().NoError(err)
s.Require().NoError(s.store.CustomModels.Insert(context.Background(), &store.CustomModel{
CustomerID: s.customerID(), Name: name, BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned-27b",
APIKeySealed: sealed, KEKVersion: s.sealer.CurrentVersion(),
}))
return name
}

func (s *StreamsSuite) TestAPriorityListWhoseModelKeyFailsToOpenAnswersSomethingWentWrong() {
broken := s.brokenKeyModel()

answering := s.start("/v1/llm/stream", frame{"target": "custom/" + broken, "llm": frame{"providers": []string{
"custom/" + broken, "custom/not-there-" + s.utils.uuid()}}})

failed := s.nextFrame(answering)
s.Equal("error", failed["type"])
s.Equal(somethingWentWrong, failed["error"], "the key's failure is the router's, and a refused entry beside it does not make it the caller's")
}

func (s *StreamsSuite) TestAPriorityListOfModelsTheCustomerDoesNotHoldIsRefusedWithTheirNames() {
first, second := "not-there-"+s.utils.uuid(), "gone-"+s.utils.uuid()

answering := s.start("/v1/llm/stream", frame{"target": "custom/" + first,
"llm": frame{"providers": []string{"custom/" + first, "custom/" + second}}})

refused := s.nextFrame(answering)
s.Equal("error", refused["type"])
s.Contains(refused["error"], "custom/"+first+`" is not one of this customer's models`)
s.Contains(refused["error"], "custom/"+second+`" is not one of this customer's models`)
}

func (s *StreamsSuite) TestAPictureAModelCannotSeeIsRefusedRatherThanSentAnyway() {
answering := s.start("/v1/llm/stream", frame{"target": "llm-flow"})
s.Equal("started", s.nextFrame(answering)["type"])
Expand Down
70 changes: 70 additions & 0 deletions acceleration/internal/llmrouter/fallback_class_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package llmrouter

import (
"errors"

"github.com/GetStream/Vision-Agents/acceleration/internal/llm"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
)

// errVendorDown is a failure on the vendor's side, whose text the caller is never sent.
var errVendorDown = errors.New(`POST "https://vendor.example.com/responses": 503 vendor-internal-body`)

// turnFailing asks one turn of a session started on the priority list of models, each of
// which fails the turn with its error in fails; allowed, when set, is every model the
// customer's policies allow.
func (s *LLMRouterSuite) turnFailing(fails map[string]error, providers []string, allowed ...string) error {
registry := NewRegistry()
var configs []routing.ProviderConfig
for _, name := range providers {
provider := newStubLLM()
provider.createErr = fails[name]
registry.Register(name, func(routing.Spec) (Provider, error) { return Started[llm.LLM](provider, nil) })
configs = append(configs, routing.ProviderConfig{Provider: name, Model: "m", Languages: []string{"en"}})
}
options := Options{Registry: registry, Config: routing.ModalityConfig{Providers: configs}}
if len(allowed) > 0 {
options.Gate = allowing(allowed)
}
router, err := New(options)
s.Require().NoError(err)
s.T().Cleanup(router.Close)
var list []string
for _, name := range providers {
list = append(list, name+"/m")
}
session, err := router.Start(s.ctx, Request{CustomerID: "acme", Providers: list})
s.Require().NoError(err)
s.T().Cleanup(func() { _ = session.Close() })

_, err = session.Create(s.ctx, llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}})
s.Require().Error(err)
return err
}

func (s *LLMRouterSuite) TestATurnAFallbackFailedOnIsNotTheCallersMistakeForTheOthersRefusingIt() {
err := s.turnFailing(map[string]error{
"first": routing.Refused(errors.New("first: the prompt is too long")),
"second": routing.Refused(errors.New("second: the prompt is too long")),
"third": errVendorDown,
}, []string{"first", "second", "third"})

s.NotErrorIs(err, routing.ErrRequest)
}

func (s *LLMRouterSuite) TestATurnThatFailedIsNotTheCallersMistakeForAFallbackThePolicyDoesNotAllow() {
err := s.turnFailing(map[string]error{"first": errVendorDown}, []string{"first", "second"}, "first/m")

s.NotErrorIs(err, routing.ErrModelNotAllowed)
s.NotErrorIs(err, routing.ErrRequest)
}

func (s *LLMRouterSuite) TestATurnEveryModelRefusedIsRefusedWithTheirTexts() {
err := s.turnFailing(map[string]error{
"first": routing.Refused(errors.New("first: the prompt is too long")),
"second": routing.Refused(errors.New("second: the prompt is too long")),
}, []string{"first", "second"})

s.ErrorIs(err, routing.ErrRequest)
s.Equal("first: the prompt is too long\nsecond: the prompt is too long\nllmrouter: no fallback provider available", err.Error())
}
4 changes: 3 additions & 1 deletion acceleration/internal/llmrouter/fallback_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@ func TestAFallbackNeverReachesAModelThePolicyDoesNotAllow(t *testing.T) {

_, err = session.Create(t.Context(), llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}})

require.ErrorIs(t, err, routing.ErrModelNotAllowed)
// The turn failed at its vendor, so it is not refused for the policy: the policy is only
// why no fallback answered.
require.ErrorContains(t, err, routing.ErrModelNotAllowed.Error())
require.Zero(t, asked.Load(), "the model the policy does not allow was never asked")
}

Expand Down
4 changes: 3 additions & 1 deletion acceleration/internal/llmrouter/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,9 @@ func (r *Router) Start(ctx context.Context, request Request) (*Session, error) {
}
}), nil
}
return nil, stack.Wrap(errors.Join(append(failures, errors.New("llmrouter: no fallback provider available"))...))
// The last line is no candidate's error, so it stays out of the join that decides
// whether the candidates refused the request or failed it.
return nil, stack.Wrap(errors.Join(routing.Join(failures...), errors.New("llmrouter: no fallback provider available")))
}
return session, nil
}
Expand Down
73 changes: 73 additions & 0 deletions acceleration/internal/routing/chain_class_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package routing

import (
"context"
"errors"
"log/slog"
)

// heldModels is a customer with two models: "held" works, and "unreadable" fails because its
// lookup breaks on the deployment's side. Every other name is refused.
type heldModels struct{}

var errStoreDown = errors.New("store: custom model: connection refused to db.internal:5432")

func (heldModels) CustomModel(_ context.Context, _, name string) (ProviderConfig, Endpoint, error) {
switch name {
case "held":
return ProviderConfig{Provider: CustomProvider, Model: name}, Endpoint{BaseURL: "https://models.example.com/v1", Model: name}, nil
case "unreadable":
return ProviderConfig{}, Endpoint{}, errStoreDown
}
return ProviderConfig{}, Endpoint{}, Refused(errors.New(`routing: "custom/` + name + `" is not one of this customer's models`))
}

func (s *RoutingSuite) TestAPriorityListKeepsTheClassOfEachEntrysError() {
registry := NewRegistry[*stubProvider]()
registry.Register(CustomProvider, func(spec Spec) (*stubProvider, error) { return &stubProvider{model: spec.Model}, nil })
router, err := New(Options[*stubProvider]{
Modality: LLM, Config: s.config(), Registry: registry, Models: heldModels{}, Logger: slog.New(slog.DiscardHandler),
})
s.Require().NoError(err)
s.T().Cleanup(router.Close)
start := func(providers ...string) error {
_, _, err := router.Select(s.ctx, Request{CustomerID: "acme", Target: providers[0], Providers: providers})
return err
}

for name, test := range map[string]struct {
providers []string
refused bool
}{
"an entry that failed beside one that was refused": {[]string{"custom/unreadable", "custom/absent"}, false},
"a refused entry before one that failed": {[]string{"custom/absent", "custom/unreadable"}, false},
"an entry that failed alone": {[]string{"custom/unreadable"}, false},
"every entry refused": {[]string{"custom/absent", "custom/missing"}, true},
} {
err := start(test.providers...)
s.Require().Error(err, name)
s.Equal(test.refused, errors.Is(err, ErrRequest), name)
}
s.NoError(start("custom/absent", "custom/held"), "a model the customer holds serves a list whose first entry is refused")
}

// An empty entry, and a model of the customer's own on a router that serves none, are the
// caller's to correct. Beside an entry nothing answers to, the list is still refused with
// every entry's text.
func (s *RoutingSuite) TestAPriorityListEntryTheCallerGotWrongIsRefusedBesideAnother() {
router := s.newRouter()
for name, test := range map[string]struct {
providers []string
text string
}{
"an empty entry": {[]string{"", "unknown"}, "routing: nothing in the priority list , unknown can serve this request: " +
"routing: target is required\nrouting: unknown target \"unknown\""},
"a model of the customer's own": {[]string{"custom/mine", "unknown"}, "routing: nothing in the priority list custom/mine, unknown can serve this request: " +
"routing: \"custom/mine\" was asked for, and this deployment has no models of a customer's own\nrouting: unknown target \"unknown\""},
} {
_, _, err := router.Select(s.ctx, Request{CustomerID: "acme", Target: test.providers[0], Providers: test.providers})
s.Require().Error(err, name)
s.ErrorIs(err, ErrRequest, name)
s.Equal(test.text, err.Error(), name)
}
}
9 changes: 6 additions & 3 deletions acceleration/internal/routing/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,14 @@ func (r refused) Unwrap() []error { return []error{r.err, ErrRequest} }
func Refused(err error) error { return refused{err: err} }

// Join joins the errors of the candidates a request was tried on. Once one of them failed
// on its own account, the request is not the caller's mistake for another one refusing it:
// the join says every error but is only the ones that are not refusals.
// on its own account, the request is not the caller's mistake for another one refusing it,
// or for the customer's policies not allowing another one: the join says every error but is
// only the ones that are neither.
func Join(errs ...error) error {
joined := errors.Join(errs...)
failures := slices.DeleteFunc(slices.Clone(errs), func(err error) bool { return errors.Is(err, ErrRequest) })
failures := slices.DeleteFunc(slices.Clone(errs), func(err error) bool {
return errors.Is(err, ErrRequest) || errors.Is(err, ErrModelNotAllowed)
})
if len(failures) == 0 || len(failures) == len(errs) {
return joined
}
Expand Down
Loading
Loading