Files
magpie/internal/provider/test_test.go
T
JoeyWu-tech 32ea16c5a4 gateway, provider: a model AgentRouter turns away on chat in Chinese is asked, and tested, on the next API (#3766)
char1eslu (#3766): AgentRouter answers gpt-5.6-sol, gpt-6-astra and
gpt-6.1-sol on chat completions with a 400, "模型 gpt-5.6-sol 不支持
/v1/chat/completions 接口,请改用 /v1/responses(OpenAI Responses API)。",
and serves them on Responses (gpt-5.6-sol on Messages too: the report's
provider test has ✓ anthropic). wrongEndpoint, the gateway's word that a
model is served on another API, which has the request asked there when
the provider has a URL for it (and remembers it in unfit), read English
alone. So while the provider had a Chat URL, a Chat client's request for
these models got that 400 back, whatever other URLs it had. The report's
200 ("/v1/chat/completions → /v1/responses") is a request translated
past chat, which d03779cc does for this host only while chat isn't
usable for the model, as after the report's url=. A Messages client's
request goes to the reporter's Anthropic URL and is answered there.

wrongEndpoint now also reads the message's two clauses, "不支持
/v1/chat/completions 接口" and "改用 /v1/responses", and asksResponses
the second, so a provider with its Chat URL alone gets the note that the
model is served on /v1/responses, which it has no URL for. Both read the
body's JSON strings decoded too (wordsOf), as the gateway's other words
are (#1669): the report quotes the message, not the body, and a relay
whose JSON escapes it (模型 ...) says the same. Neither clause
names a model, so the other two models' refusals match if their
messages differ only in the name (the report shows their 400 rows, not
their words). The routing page says so.

The same words now reach the group's checks, as retryable and
shapeRefused read wrongEndpoint. In a routing group (chat, drawing,
video, System One), a member answering this 400 ended the request there
on d03779cc: it was neither retryable nor shapeRefused, as
unservedWords' 模型.{0,12}不支持 misses these model ids by one
character. Now the next member is asked and this one isn't rested, as
for the English words. The image-tool and cache-key retries, which ask
again on a 400, don't on this one.

Not changed: a model's test, which still asks one API (the next
commit). Other relays' wordings: only the report's two clauses are
added, nor AgentRouter's other way round (a chat-only model asked on
/v1/responses), which the report has no words for.

What was run (tree 4e5bb297, on origin/main d03779cc, go1.26.8,
linux/amd64):
- TestChineseRefusalFallsBackToResponses, new: a provider with a Chat
  and a Responses URL whose chat completions answers the report's 400
  (its message verbatim; the JSON around it is a guess), as it is and
  escaped as Python's json.dumps escapes it. A request on
  /v1/chat/completions and one on /v1/messages each get the reply from
  Responses, chat asked once and Responses once.
- TestWrongEndpoint: the report's 400, escaped too, and each of its
  clauses alone are the wrong endpoint; "当前分组 default 下对于模型 gone
  无可用渠道" (new-api's wording for a model no channel serves, written
  from memory, not from the report) is not.
- TestWrongAPINote: AgentRouter with its Chat URL alone and the report's
  400, as it is and escaped, gets " (asked at
  https://agentrouter.org/v1/chat/completions; gpt-5.6-sol is served on
  /v1/responses, which AgentRouter has no URL for)".
- The three, -count=50 -v: 150 PASS. -race -count=20 -cpu 1,2 over them
  and the fallback tests beside them (WrongEndpoint, WrongAPINote,
  FallsBack, OpenCodeGo, OtherRelayKeepsItsOneAPI): ok, no race.
- Broken by hand, each red:
  - wrongEndpoint without the two clauses: every case of
    TestChineseRefusalFallsBackToResponses, and TestWrongEndpoint's
    rows of the whole message.
  - wrongEndpoint with one clause of the two: TestWrongEndpoint's row of
    the other clause alone (each).
  - wrongEndpoint reading the body as it came: the escaped cases of
    TestChineseRefusalFallsBackToResponses and TestWrongEndpoint's
    escaped row.
  - asksResponses without its clause: TestWrongAPINote, both bodies;
    reading the body as it came: its escaped one.
- A real run: magpie built at d03779cc and at this tree (go build -tags
  nogui -buildvcs=false), in a sandbox HOME, a local server standing in
  for AgentRouter (its /v1/models lists gpt-5.6-sol, chat completions
  answers the report's 400, /v1/responses and /v1/messages answer), set
  up as the report has it: magpie provider add agentrouter url=...
  key=... models=gpt-5.6-sol and anthropic=..., then responses=..., then
  url= (the chat URL cleared). At each step magpie serve, and curl on
  /v1/chat/completions (whole and streamed) and /v1/messages:
  - Chat and Anthropic URLs: d03779cc answers both chat requests with
    the 400; this tree 200, chat asked once and /v1/messages after it.
  - Chat, Responses and Anthropic URLs: d03779cc answers both chat
    requests with the 400; this tree 200, chat asked once and Responses
    after it (the streamed one went to Responses at once: unfit).
  - The chat URL cleared: both builds 200, the chat requests answered
    on Responses.
  - /v1/messages: 200 at every step on both, from /v1/messages.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit
  1 (this box has no GTK or WebKitGTK dev packages).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  67 ok, and 7 red, none in what this changes: agent
  TestInstalledVersion, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync TestSync
  (#3420); edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram
  (#3640); gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632), so the
  package's tests after it didn't run: go test ./internal/provider
  -skip '^TestUnreadLoginsWriteErrorsKeepCredentials$', Bun 1.4.2 on
  PATH: ok.

Not tried: the real AgentRouter (no account here), macOS, an agent's
own requests (curl's stood in).

---- provider (second commit of the branch) ----

provider: a model turned away on one API is tested on the next (#3766)

char1eslu (#3766): after Test models, the three models AgentRouter
turns away on chat completions were red in the provider's Models list,
and Working only hid them, while the gateway answered them on
Responses. Their usage rows (kind provider_test, source probe: the
editor's test) were each a 400 on /v1/chat/completions, "模型
gpt-5.6-sol 不支持 /v1/chat/completions 接口,请改用 /v1/responses(OpenAI
Responses API)。". They stayed red after the reporter cleared the chat
URL (magpie provider set agentrouter url=), with their provider test
printing only ✓ responses and ✓ anthropic.

A model's test (testOne) asked one API, the first the provider speaks
unless the vendor's list, the user's pick or the client names another,
and took its answer as the model's. The editor's Test models sends the
editor's form, whose fields that aren't empty win over the saved
provider (typed), so a form that still names a chat URL the saved
provider no longer has asks chat: in the real run below that is red at
d03779cc, as the report's rows are.

Now, when the vendor says the model isn't served there
(catalog.WrongEndpoint: the gateway's wrongEndpoint, moved with its
words so both read the same), the test asks the next API the provider
has a URL for that may serve the model, by the gateway's rule (usable:
the model's listed or picked APIs, else each API the provider isn't
named-only on), with a key that sees the model on that API (keySeeing,
testOne's pick taken out as it was). That API's answer is the model's.
One that says the same has the next asked; when none is left the first
answer stays, so a provider with its Chat URL alone still shows the
vendor's message. Test models, a model's own test and Test as in the
editor, and magpie provider test <id> <model> (--as too), go through
it. As Codex the next API is asked with Codex's headers, as the gateway
sends them on Responses and Chat; as Claude Code the test isn't moved,
since the gateway sends Claude Code's headers on Messages alone.
docs/subsystems/providers-accounts.md says so, and the routing page
points there.

Not changed: which API is asked first, so a model that moved is asked
on chat again at each test before the API that serves it (the
gateway's unfit is its own). magpie provider test <id> with no model,
which tests each endpoint with a model of its own pick (testModel), is
as it was: its chat row can be red for a model the vendor serves
elsewhere, #3844.

What was run (tree 519dee3b, on origin/main d03779cc, go1.26.8,
linux/amd64):
- TestTestModelsMovesToTheAPIServingIt, new: AgentRouter with a Chat
  and a Responses URL and a key for each (sk-chat made for Chat,
  sk-responses for Responses), its chat completions answering the
  report's 400 (its message verbatim; the JSON around it is a guess), as
  it is and escaped. gpt-5.6-sol is OK on Responses, asked on chat with
  sk-chat and then on responses with sk-responses, and nothing else. A
  model chat turns away with new-api's "无可用渠道" (written from memory,
  not from the report) is red after one ask. With the Chat URL alone,
  gpt-5.6-sol is red after one ask, its error the vendor's message. When
  both APIs say it, both are asked and chat's answer stays.
- TestTestModelsKeepsAModelOnItsAPI, new: a model the user picked chat
  for, and one the vendor's list names on chat alone, is red on chat
  after one ask, as the gateway keeps its request there.
- TestTestModelsAsAClientMovesAsTheGatewayDoes, new: turned away on
  Responses with the word, a test as Codex is green on chat, asked with
  Codex's User-Agent; a test as Claude Code is red on Messages after one
  ask.
- The three, -count=50: 150 PASS; the gateway's
  TestChineseRefusalFallsBackToResponses, TestWrongEndpoint and
  TestWrongAPINote at this tree, -count=50: 150 PASS.
- -race -count=20 -cpu 1,2, internal/provider's TestTest and TestDetect
  tests and internal/gateway's WrongEndpoint, WrongAPINote, FallsBack,
  OpenCodeGo and OtherRelayKeepsItsOneAPI ones: ok, no race.
- Broken by hand, each red:
  - the test never hearing the vendor's word, as at the previous
    commit: TestTestModelsMovesToTheAPIServingIt, and
    TestTestModelsAsAClientMovesAsTheGatewayDoes as Codex;
  - the next API asked with the first one's key:
    TestTestModelsMovesToTheAPIServingIt, red on responses;
  - the next API asked whatever API the model is picked or listed on:
    TestTestModelsKeepsAModelOnItsAPI, both models green on responses
    after two asks;
  - a test as Claude Code moved too:
    TestTestModelsAsAClientMovesAsTheGatewayDoes, green on chat;
  - the words in English alone, as at d03779cc:
    TestTestModelsMovesToTheAPIServingIt, the report's message as it is
    and escaped;
  - the words matched in the body as it came:
    TestTestModelsMovesToTheAPIServingIt, escaped.
  The previous commit's own breaks of the words are red at this tree
  too, in the gateway's tests.
- A real run: magpie built at d03779cc, at the previous commit and at
  this tree (go build -tags nogui -buildvcs=false), in a sandbox HOME,
  the previous commit's stand-in and steps. magpie provider test
  agentrouter gpt-5.6-sol:
  - Chat and Anthropic URLs: "✗ chat gpt-5.6-sol · 400 · 模型
    gpt-5.6-sol 不支持 ..." at d03779cc and the previous commit, chat
    asked alone; "✓ anthropic" at this tree, chat asked and then
    /v1/messages.
  - Chat, Responses and Anthropic URLs: the same ✗ chat, then; "✓
    responses" at this tree, chat asked and then /v1/responses.
  - The chat URL cleared: "✓ responses" at all three, responses asked
    alone.
  Then, the chat URL cleared, magpie web's /api/provider/test (the
  editor's Test models) for gpt-5.6-sol: with the form naming the old
  chat URL, red on chat with the vendor's message at d03779cc and the
  previous commit, green on responses at this tree (chat asked, then
  responses); with the form's chat empty, green on responses at all
  three. The gateway answered as at the previous commit.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit
  1 (this box has no GTK or WebKitGTK dev packages).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  67 ok, and 7 red, none in what this changes: agent
  TestCodexDriftReached and TestCodexBehindReverseProxy (#3398);
  TestInstalledVersion, TestHowInstalled,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync
  TestSyncTeraCloudStillSeesOtherWrites (#3420); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (#3640);
  gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632), so the
  package's tests after it didn't run: go test ./internal/provider
  -skip '^TestUnreadLoginsWriteErrorsKeepCredentials$', Bun 1.4.2 on
  PATH: ok.

Not tried: the editor itself (magpie web's route, which its Test models
posts to, stood in), macOS, the real AgentRouter (no account here).

Review (yetone/magpie maintainer agent): the two commits of
JoeyWu-tech's branch (387191d5a, f8fcf936e, patch sha256 15d451ff…,
as the issue says) squashed into one, one commit per issue. Read every
line. The only other place reading these words, asksResponses (the
note that a provider lacks a Responses URL), reads the Chinese and the
escaped body too; no other matcher of a wrong-API refusal is left
(grep for the English phrases outside catalog.go).

Run at this tree on 6cb1cfb79, macOS, go1.27:
- red by hand: the two Chinese phrases taken out of WrongEndpoint:
  TestChineseRefusalFallsBackToResponses (all four subtests) and
  TestTestModelsMovesToTheAPIServingIt red. The next-API loop in
  testOne off: TestTestModelsMovesToTheAPIServingIt and
  TestTestModelsAsAClientMovesAsTheGatewayDoes red. Green restored.
- real run, macOS: base and patched builds in a sandbox HOME, a fake
  AgentRouter (chat answers the report's literal 400, Responses
  answers), magpie provider add agentrouter url=… responses=…, then
  magpie provider test agentrouter gpt-5.6-sol and magpie serve with a
  /v1/chat/completions request. Base: "✗ chat … 400 · 模型 gpt-5.6-sol
  不支持 …" and the client gets the 400. Patched: "✓ responses", and
  the client gets the answer from /v1/responses (vendor log: chat,
  responses, chat, responses).
- at the pushed head (rebased on 5f3146be0; the docs conflict with
  #3696's sentences merged, both kept): go build ./..., go test
  ./internal/catalog ok; gateway -run
  'WrongEndpoint|WrongAPI|Fallback|FallsBack|Chinese|OtherAPI|Endpoint|OpenCode'
  ok (50s); provider -run 'TestTestModels|TestTest|TestOne|Probe' ok;
  vet linux and windows of the three packages ok; gofmt -l clean.
  The whole gateway and provider packages were not run at this head:
  another session's go test ./... held the machine (one suite at a
  time).

Not tried: the real AgentRouter, the GUI editor itself.
2026-10-27 16:23:20 +08:00

414 lines
16 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
)
// Each endpoint is tried with a key made for it, and the Anthropic one
// with a model its key sees even when the exposed one is another's.
func TestTestUsesEachEndpointsKey(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
seen := map[string]string{} // path → key and model it got
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { // each key sees its own group's models
if r.Header.Get("Authorization") == "Bearer sk-anthropic" {
_, _ = rw.Write([]byte(`{"data":[{"id":"claude-opus-5"}]}`))
} else {
_, _ = rw.Write([]byte(`{"data":[{"id":"gpt-6-sol"}]}`))
}
return
}
var in struct{ Model string }
_ = json.NewDecoder(r.Body).Decode(&in)
seen[r.URL.Path] = r.Header.Get("Authorization") + " " + in.Model
_, _ = rw.Write([]byte(`{}`))
}))
defer srv.Close()
p := Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Anthropic: srv.URL,
Key: "sk-chat", KeyProtocol: Chat, Models: []string{"gpt-6-sol"},
Keys: []KeyAccount{{Key: "sk-anthropic", Protocol: Anthropic}}}
for _, r := range p.Test(context.Background()) {
if !r.OK {
t.Errorf("%s: %+v", r.Protocol, r)
}
}
if got := seen["/v1/chat/completions"]; got != "Bearer sk-chat gpt-6-sol" {
t.Errorf("chat got %q", got)
}
if got := seen["/v1/messages"]; got != "Bearer sk-anthropic claude-opus-5" {
t.Errorf("anthropic got %q", got)
}
ms := p.Available()
if len(ms) != 2 {
t.Fatalf("merged list %+v", ms)
}
chat, anth := p.first(), p.Keys[0]
if !p.Serves(chat, "gpt-6-sol") || p.Serves(chat, "claude-opus-5") || !p.Serves(anth, "claude-opus-5") || p.Serves(anth, "gpt-6-sol") {
t.Error("each key serves only its own list")
}
if !p.Serves(anth, "some-unlisted-model") {
t.Error("a model no list has is anyone's")
}
}
// Each model is asked on its own, with a key that sees it: one the vendor
// doesn't serve fails while the others answer.
func TestTestModels(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
var mu sync.Mutex
seen := map[string]string{} // model → path and key it came with
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
if r.Header.Get("Authorization") == "Bearer sk-anthropic" {
_, _ = rw.Write([]byte(`{"data":[{"id":"claude-opus-5"}]}`))
} else {
_, _ = rw.Write([]byte(`{"data":[{"id":"gpt-6-sol"},{"id":"gone"}]}`))
}
return
}
var in struct{ Model string }
_ = json.NewDecoder(r.Body).Decode(&in)
mu.Lock()
seen[in.Model] = r.URL.Path + " " + r.Header.Get("Authorization")
mu.Unlock()
if in.Model == "gone" {
rw.WriteHeader(http.StatusNotFound)
_, _ = rw.Write([]byte(`{"error":{"message":"no channel for model gone"}}`))
return
}
_, _ = rw.Write([]byte(`{}`))
}))
defer srv.Close()
p := Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Anthropic: srv.URL,
Key: "sk-chat", KeyProtocol: Chat,
Keys: []KeyAccount{{Key: "sk-anthropic", Protocol: Anthropic}}}
p.Fetch(context.Background())
rs := p.TestModels(context.Background(), []string{"gpt-6-sol", "claude-opus-5", "gone"})
if len(rs) != 3 || !rs[0].OK || !rs[1].OK || rs[2].OK || rs[2].Status != 404 || rs[2].Error != "no channel for model gone" {
t.Fatalf("results %+v", rs)
}
if rs[0].Model != "gpt-6-sol" || rs[1].Protocol != Anthropic || rs[2].Model != "gone" {
t.Fatalf("order %+v", rs)
}
if seen["gpt-6-sol"] != "/v1/chat/completions Bearer sk-chat" || seen["claude-opus-5"] != "/v1/messages Bearer sk-anthropic" {
t.Fatalf("seen %v", seen)
}
}
// An image model is tested as the gateway draws with it, on the images
// API with one small picture — a chat request it would turn away — while a
// chat model is still asked in chat. The vendor-wide Test picks the chat one.
func TestTestModelsDraws(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
var mu sync.Mutex
seen := map[string]string{} // model → path it was asked on
bodies := map[string]map[string]any{}
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
rw.WriteHeader(http.StatusNotFound)
return
}
var in map[string]any
_ = json.NewDecoder(r.Body).Decode(&in)
model, _ := in["model"].(string)
mu.Lock()
seen[model] = r.URL.Path
bodies[model] = in
mu.Unlock()
draws := strings.Contains(model, "image") || strings.Contains(model, "flux")
switch {
case r.URL.Path == "/v1/images/generations" && draws:
_, _ = rw.Write([]byte(`{"data":[{"url":"https://img.example/1.png"}]}`))
case r.URL.Path == "/v1/chat/completions" && !draws:
_, _ = rw.Write([]byte(`{"choices":[{"message":{"content":"hi"}}]}`))
default:
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"error":{"message":"wrong endpoint for ` + model + `"}}`))
}
}))
defer srv.Close()
p := Provider{ID: "custom", Name: "Custom", Chat: srv.URL + "/v1", Key: "sk-x",
Models: []string{"gpt-image-1", "flux-kontext-pro", "gpt-6-sol"}}
rs := p.TestModels(context.Background(), []string{"gpt-image-1", "flux-kontext-pro", "gpt-6-sol"})
for _, r := range rs {
if !r.OK {
t.Fatalf("results %+v", rs)
}
}
if seen["gpt-image-1"] != "/v1/images/generations" || seen["flux-kontext-pro"] != "/v1/images/generations" || seen["gpt-6-sol"] != "/v1/chat/completions" {
t.Fatalf("seen %v", seen)
}
if b := bodies["gpt-image-1"]; b["n"] != float64(1) || b["quality"] != "low" || b["prompt"] == "" {
t.Fatalf("gpt-image body %v", b)
}
if b := bodies["flux-kontext-pro"]; b["quality"] != nil || b["messages"] != nil {
t.Fatalf("flux body %v", b)
}
// the vendor-wide Test asks the chat model, though an image one is first
mu.Lock()
clear(seen)
mu.Unlock()
if rs := p.Test(context.Background()); len(rs) != 1 || !rs[0].OK || rs[0].Model != "gpt-6-sol" {
t.Fatalf("Test %+v", rs)
}
}
// #1837: an image model whose name doesn't place it on the images API
// (agnes-image-2.5-flash reads like gemini's -flash image models, which
// chat) is turned away in chat with the vendor naming the images API; the
// gateway draws with it there, so its test passes there too, and a chat
// model the vendor turns away the same way stays failed.
func TestTestModelsGoesWhereTheVendorPointsIt(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
var mu sync.Mutex
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
rw.WriteHeader(http.StatusNotFound)
return
}
var in map[string]any
_ = json.NewDecoder(r.Body).Decode(&in)
model, _ := in["model"].(string)
mu.Lock()
paths = append(paths, model+" "+r.URL.Path)
mu.Unlock()
if r.URL.Path == "/v1/images/generations" && model == "agnes-image-2.5-flash" {
_, _ = rw.Write([]byte(`{"created":1,"data":[{"url":"https://img.example/1.png"}]}`))
return
}
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"error":{"message":"Model ` + model + ` is an image model. Use /v1/images/generations","type":"invalid_request_error"}}`))
}))
defer srv.Close()
p := Provider{ID: "agnes", Name: "Agnes", Chat: srv.URL + "/v1", Key: "sk-x",
Models: []string{"agnes-image-2.5-flash", "agnes-chat"}}
rs := p.TestModels(context.Background(), []string{"agnes-image-2.5-flash", "agnes-chat"})
if len(rs) != 2 || !rs[0].OK || rs[1].OK {
t.Fatalf("results %+v", rs)
}
mu.Lock()
defer mu.Unlock()
slices.Sort(paths)
want := []string{"agnes-chat /v1/chat/completions", "agnes-image-2.5-flash /v1/chat/completions", "agnes-image-2.5-flash /v1/images/generations"}
if !slices.Equal(paths, want) {
t.Fatalf("asked %v, want %v", paths, want)
}
}
// #3766 (char1eslu): AgentRouter serves gpt-5.6-sol on /v1/responses and
// turns it away on /v1/chat/completions, in Chinese. Test models asked
// chat only, so the model stayed red while the gateway answered it on
// Responses. On that word the test now asks the next API the provider has,
// with that API's key, as the gateway would; another refusal stays as it
// was, and so does the word when no other API is left or every API says
// it, the first API's answer then.
func TestTestModelsMovesToTheAPIServingIt(t *testing.T) {
oneHome(t)
said := "模型 gpt-5.6-sol 不支持 /v1/chat/completions 接口,请改用 /v1/responses(OpenAI Responses API)。"
// the report has the message only: the JSON around it is a guess, and
// so is how it is encoded (escaped as Python's json.dumps writes it)
refusal := `{"error":{"message":"` + said + `","type":"invalid_request_error"}}`
escaped := `{"error":{"message":` + strconv.QuoteToASCII(said) + `,"type":"invalid_request_error"}}`
var mu sync.Mutex
var asked []string
chatSays := refusal
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Model string }
_ = json.NewDecoder(r.Body).Decode(&in)
mu.Lock()
asked = append(asked, in.Model+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
chat := chatSays
mu.Unlock()
switch {
case in.Model == "gone":
// new-api's words for a model no channel serves, written from
// memory, not from the report
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"error":{"message":"当前分组 default 下对于模型 gone 无可用渠道"}}`))
case r.URL.Path == "/v1/chat/completions":
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(chat))
case in.Model == "nowhere":
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"error":{"message":"This model is not supported in the v1/responses endpoint."}}`))
default:
_, _ = rw.Write([]byte(`{}`))
}
}))
defer srv.Close()
took := func() []string {
mu.Lock()
defer mu.Unlock()
out := asked
asked = nil
return out
}
p := Provider{ID: "agentrouter", Name: "AgentRouter", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1",
Key: "sk-chat", KeyProtocol: Chat, Keys: []KeyAccount{{Key: "sk-responses", Protocol: Responses}}}
for _, chat := range []string{refusal, escaped} {
mu.Lock()
chatSays = chat
mu.Unlock()
rs := p.TestModels(context.Background(), []string{"gpt-5.6-sol"})
if len(rs) != 1 || !rs[0].OK || rs[0].Protocol != Responses {
t.Fatalf("%s: results %+v", chat, rs)
}
want := []string{"gpt-5.6-sol /v1/chat/completions Bearer sk-chat", "gpt-5.6-sol /v1/responses Bearer sk-responses"}
if got := took(); !slices.Equal(got, want) {
t.Fatalf("%s: asked %v, want %v", chat, got, want)
}
}
mu.Lock()
chatSays = refusal
mu.Unlock()
// a refusal about the model is its answer, on the first API alone
rs := p.TestModels(context.Background(), []string{"gone"})
if len(rs) != 1 || rs[0].OK || rs[0].Protocol != Chat || rs[0].Status != 400 {
t.Fatalf("gone: results %+v", rs)
}
if got := took(); len(got) != 1 {
t.Fatalf("gone: asked %v, want chat once", got)
}
// with chat alone the vendor's word is the answer
chatOnly := Provider{ID: "agentrouter", Name: "AgentRouter", Chat: srv.URL + "/v1", Key: "sk-chat"}
rs = chatOnly.TestModels(context.Background(), []string{"gpt-5.6-sol"})
if len(rs) != 1 || rs[0].OK || rs[0].Protocol != Chat || rs[0].Status != 400 || !strings.Contains(rs[0].Error, "请改用 /v1/responses") {
t.Fatalf("chat only: results %+v", rs)
}
if got := took(); len(got) != 1 {
t.Fatalf("chat only: asked %v, want chat once", got)
}
// every API says it: each is asked, and the first one's answer stays
rs = p.TestModels(context.Background(), []string{"nowhere"})
if len(rs) != 1 || rs[0].OK || rs[0].Protocol != Chat || !strings.Contains(rs[0].Error, "请改用 /v1/responses") {
t.Fatalf("nowhere: results %+v", rs)
}
if got := took(); len(got) != 2 {
t.Fatalf("nowhere: asked %v, want chat and responses", got)
}
}
// The API the user picked for a model, or the only one the vendor's list
// names, keeps its test there, as usable keeps the gateway's request:
// chat turning it away is the answer, not a reason to ask Responses
// (#3766).
func TestTestModelsKeepsAModelOnItsAPI(t *testing.T) {
oneHome(t)
const refusal = `{"error":{"message":"模型 gpt-5.6-sol 不支持 /v1/chat/completions 接口,请改用 /v1/responses(OpenAI Responses API)。","type":"invalid_request_error"}}`
var mu sync.Mutex
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.URL.Path)
mu.Unlock()
if r.URL.Path == "/v1/chat/completions" {
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(refusal))
return
}
_, _ = rw.Write([]byte(`{}`))
}))
defer srv.Close()
p := Provider{ID: "agentrouter", Name: "AgentRouter", Key: "k", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1", Models: []string{"picked", "listed"}}
if err := Save(p); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive(p.ID, p.Chat, []catalog.Model{{ID: "picked"}, {ID: "listed", APIs: []string{"chat"}}}); err != nil {
t.Fatal(err)
}
if err := SetModelAPI("agentrouter/picked", "chat"); err != nil {
t.Fatal(err)
}
q, err := Find(p.ID)
if err != nil {
t.Fatal(err)
}
for _, m := range []string{"picked", "listed"} {
mu.Lock()
asked = nil
mu.Unlock()
rs := q.TestModels(context.Background(), []string{m})
mu.Lock()
n := len(asked)
mu.Unlock()
if len(rs) != 1 || rs[0].OK || rs[0].Protocol != Chat || n != 1 {
t.Errorf("%s: results %+v after %d asks, want red on chat after one", m, rs, n)
}
}
}
// Asked as Codex, a model the vendor turns away on Responses with its word
// that Chat serves it is asked there with Codex's headers, as the gateway
// sends them on both; asked as Claude Code it stays red on Messages, where
// alone the gateway sends Claude Code's (#3766).
func TestTestModelsAsAClientMovesAsTheGatewayDoes(t *testing.T) {
oneHome(t)
SawClient(ClientClaudeCode, http.Header{"User-Agent": {"claude-cli/2.1.0 (external, cli)"}, "X-App": {"cli"}})
var mu sync.Mutex
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.URL.Path+" "+r.Header.Get("User-Agent"))
mu.Unlock()
switch r.URL.Path {
case "/v1/responses":
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"error":{"message":"This model is not supported in the v1/responses endpoint. Use v1/chat/completions."}}`))
case "/v1/messages":
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"Model gpt-x is not supported for format anthropic"}}`))
default:
rw.Header().Set("Content-Type", "text/event-stream")
_, _ = rw.Write([]byte("data: {}\n\n"))
}
}))
defer srv.Close()
p := Provider{ID: "relay", Name: "Relay", Key: "k", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1", Anthropic: srv.URL}
took := func() []string {
mu.Lock()
defer mu.Unlock()
out := asked
asked = nil
return out
}
rs := p.TestModels(TestAs(context.Background(), ClientCodex), []string{"gpt-x"})
got := took()
if len(rs) != 1 || !rs[0].OK || rs[0].Protocol != Chat || len(got) != 2 || !strings.HasPrefix(got[0], "/v1/responses ") ||
!strings.HasPrefix(got[1], "/v1/chat/completions codex_cli_rs/") {
t.Errorf("as Codex: results %+v, asked %q", rs, got)
}
rs = p.TestModels(TestAs(context.Background(), ClientClaudeCode), []string{"gpt-x"})
got = took()
if len(rs) != 1 || rs[0].OK || rs[0].Protocol != Anthropic || len(got) != 1 || got[0] != "/v1/messages claude-cli/2.1.0 (external, cli)" {
t.Errorf("as Claude Code: results %+v, asked %q", rs, got)
}
}