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.
This commit is contained in:
JoeyWu-tech
2026-10-27 16:23:20 +08:00
committed by yetone
parent 5f3146be09
commit 32ea16c5a4
9 changed files with 412 additions and 95 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -60,7 +60,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
| A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). `curlOf` reads it as a shell would (lines joined by `\`, cmd's `^` or PowerShell's backtick; `curl.exe`; quotes and escapes), and takes: the API its URL's endpoint names (`…/chat/completions` Chat, `…/messages` Anthropic Messages, `…/responses` Responses) with the base URL before it, spelled as that API wants it (`respellURL`: Anthropic at its root, `/v1` after a bare host); the key from `Authorization: Bearer`, `x-api-key` or `api-key`, unless it only stands for one (`$OPENAI_API_KEY`, `${X}`, `%X%`, `<token>`, `YOUR_API_KEY`), when the key's box is left empty and focused; and the `model` of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (`editorError`, kind `note`) says what was taken, a placeholder like `{WorkspaceId}` left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (`fixtures/curl`). | [`app.js`](../../internal/gui/assets/app.js) (`curlOf`, `fromCurl`), [`provider-curl-paste.test.cjs`](../../internal/gui/tests/provider-curl-paste.test.cjs) |
## Remote magpie
+82
View File
@@ -4,6 +4,7 @@
package catalog
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -1596,6 +1597,87 @@ func PointsToChat(text string) bool {
return strings.Contains(strings.ToLower(text), "chat/completions")
}
// WrongEndpoint recognizes the errors OpenAI-compatible servers give when a
// model exists but isn't served on the endpoint asked: the gateway asks the
// model on another API the provider has then, and so does a model's test.
func WrongEndpoint(status int, body []byte) bool {
if status < 400 || status >= 500 {
return false
}
// the words are matched decoded, too (#1669)
msg := strings.ToLower(string(Words(body)))
for _, phrase := range []string{
"not a chat model",
"not supported in the v1/chat/completions",
"not supported in /v1/chat/completions",
"not supported in the v1/responses",
"not supported in /v1/responses",
"only supported in v1/responses",
"only supported in /v1/responses",
"use v1/completions",
"use /v1/completions",
"use v1/responses",
"use /v1/responses",
"use v1/chat/completions",
"use /v1/chat/completions",
"not accessible via the", // Copilot
"unsupported_api_for_model",
// Copilot's /v1/messages, for a model it serves on other APIs
// alone (GPT-4.1, Gemini, GPT-5.6: #754); a model it doesn't
// serve at all is model_not_supported there
"no model endpoints available given user constraints",
"is not supported for format", // OpenCode: "Model grok-4.7 is not supported for format anthropic"
"does not support this protocol", // OpenCode, with a key: "Model does not support this protocol"
// a relay serving a model with tools on Responses alone (#1308:
// "gpt-6.1-sol requires Responses for tool calls; this account
// only supports Chat Completions")
"requires responses",
// a relay that says it in Chinese (#3766, char1eslu: AgentRouter's
// "模型 gpt-5.6-sol 不支持 /v1/chat/completions 接口,请改用
// /v1/responses(OpenAI Responses API)。")
"不支持 /v1/chat/completions 接口",
"改用 /v1/responses",
} {
if strings.Contains(msg, phrase) {
return true
}
}
return false
}
// Words is an error body as its words are matched: a JSON body that
// escapes what isn't ASCII as \uXXXX (Python's json.dumps does by default)
// has its strings decoded and put after it, one to a line, so "用量",
// "频率" or "将在 … 重置" are read whether the vendor escaped them or not
// (#1669). Any other body is matched as it is.
func Words(body []byte) []byte {
if !bytes.Contains(body, []byte(`\u`)) {
return body
}
var v any
if json.Unmarshal(body, &v) != nil {
return body
}
out := append([]byte(nil), body...)
var walk func(any)
walk = func(x any) {
switch x := x.(type) {
case string:
out = append(append(out, '\n'), x...)
case map[string]any:
for _, y := range x {
walk(y)
}
case []any:
for _, y := range x {
walk(y)
}
}
}
walk(v)
return out
}
// Drawers are the models of one models.dev provider that make images,
// newest first.
func Drawers(id string) []Model {
+5 -42
View File
@@ -6082,46 +6082,9 @@ func badRequest(status int) bool {
return status == http.StatusBadRequest || status == http.StatusUnprocessableEntity
}
// wrongEndpoint recognizes the errors OpenAI-compatible servers give when a
// model exists but isn't served on the endpoint asked.
func wrongEndpoint(status int, body []byte) bool {
if status < 400 || status >= 500 {
return false
}
msg := strings.ToLower(string(body))
for _, phrase := range []string{
"not a chat model",
"not supported in the v1/chat/completions",
"not supported in /v1/chat/completions",
"not supported in the v1/responses",
"not supported in /v1/responses",
"only supported in v1/responses",
"only supported in /v1/responses",
"use v1/completions",
"use /v1/completions",
"use v1/responses",
"use /v1/responses",
"use v1/chat/completions",
"use /v1/chat/completions",
"not accessible via the", // Copilot
"unsupported_api_for_model",
// Copilot's /v1/messages, for a model it serves on other APIs
// alone (GPT-4.1, Gemini, GPT-5.6: #754); a model it doesn't
// serve at all is model_not_supported there
"no model endpoints available given user constraints",
"is not supported for format", // OpenCode: "Model grok-4.7 is not supported for format anthropic"
"does not support this protocol", // OpenCode, with a key: "Model does not support this protocol"
// a relay serving a model with tools on Responses alone (#1308:
// "gpt-6.1-sol requires Responses for tool calls; this account
// only supports Chat Completions")
"requires responses",
} {
if strings.Contains(msg, phrase) {
return true
}
}
return false
}
// wrongEndpoint is catalog.WrongEndpoint, whose words a model's test
// reads too (#3766).
func wrongEndpoint(status int, body []byte) bool { return catalog.WrongEndpoint(status, body) }
// wrongAPINote goes after an upstream's word that the model isn't served
// on the API it was asked on (wrongEndpoint), when no other API is left to
@@ -6165,8 +6128,8 @@ func wrongAPINote(p provider.Provider, model string, res *http.Response, body []
// with what was asked, on OpenAI's Responses API: where a provider has no
// URL for it, wrongAPINote says to set one.
func asksResponses(body []byte) bool {
msg := strings.ToLower(string(body))
for _, phrase := range []string{"requires responses", "use v1/responses", "use /v1/responses", "only supported in v1/responses", "only supported in /v1/responses"} {
msg := strings.ToLower(string(wordsOf(body)))
for _, phrase := range []string{"requires responses", "use v1/responses", "use /v1/responses", "only supported in v1/responses", "only supported in /v1/responses", "改用 /v1/responses"} {
if strings.Contains(msg, phrase) {
return true
}
+59
View File
@@ -12,6 +12,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -127,6 +128,7 @@ func events(body string) []map[string]any {
}
type fallbackFake struct {
refusal string // chat's, an English one when empty
chatBody []byte
responsesBody []byte
chatCalls int
@@ -141,6 +143,10 @@ func (f *fallbackFake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.chatBody = body
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if f.refusal != "" {
io.WriteString(w, f.refusal)
return
}
io.WriteString(w, `{"error":{"message":"This model is not supported in the v1/chat/completions endpoint. Use v1/responses."}}`)
case "/v1/responses":
f.responseCalls++
@@ -240,6 +246,52 @@ func TestChatClientFallsBackToResponses(t *testing.T) {
}
}
// agentRouterSaid is AgentRouter's word that a model is served on
// /v1/responses, as #3766 quotes it.
const agentRouterSaid = "模型 gpt-5.6-sol 不支持 /v1/chat/completions 接口,请改用 /v1/responses(OpenAI Responses API)。"
// agentRouterRefusal is that word in an error body. The report has the
// message only, so the JSON around it is a guess, and so is how it is
// encoded: agentRouterEscaped has what isn't ASCII escaped, as Python's
// json.dumps writes it (#1669).
var (
agentRouterRefusal = `{"error":{"message":"` + agentRouterSaid + `","type":"invalid_request_error"}}`
agentRouterEscaped = `{"error":{"message":` + strconv.QuoteToASCII(agentRouterSaid) + `,"type":"invalid_request_error"}}`
)
// #3766 (char1eslu): AgentRouter turns its Responses-only models away on
// /v1/chat/completions in Chinese, which wrongEndpoint didn't read, so a
// provider with both URLs answered a Chat or a Messages client 400 though
// /v1/responses serves the model. Both now get its reply from there.
func TestChineseRefusalFallsBackToResponses(t *testing.T) {
for _, c := range []struct{ name, path, body, refusal string }{
{"chat", "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"hello"}]}`, agentRouterRefusal},
{"messages", "/v1/messages", `{"model":"m1","max_tokens":100,"messages":[{"role":"user","content":"hello"}]}`, agentRouterRefusal},
{"chat, escaped", "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"hello"}]}`, agentRouterEscaped},
{"messages, escaped", "/v1/messages", `{"model":"m1","max_tokens":100,"messages":[{"role":"user","content":"hello"}]}`, agentRouterEscaped},
} {
t.Run(c.name, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
f := &fallbackFake{refusal: c.refusal}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "agentrouter", Name: "AgentRouter", Key: "k", Models: []string{"m1"},
Chat: up.URL + "/v1", Responses: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.body)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "fallback ok") {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
if f.chatCalls != 1 || f.responseCalls != 1 {
t.Fatalf("calls: chat=%d responses=%d", f.chatCalls, f.responseCalls)
}
})
}
}
// The other way round: a model served only on /chat/completions (Copilot's
// Claude models), asked for by a Responses client (Codex).
func TestResponsesClientFallsBackToChat(t *testing.T) {
@@ -385,6 +437,13 @@ func TestWrongEndpoint(t *testing.T) {
{400, `{"type":"error","error":{"type":"invalid_request_error","message":"Model does not support this protocol."}}`, true},
{400, "no model endpoints available given user constraints\n", true}, // Copilot's /v1/messages (#754)
{400, toolsOnChatRefused, true}, // a relay (#1308)
{400, agentRouterRefusal, true}, // in Chinese (#3766)
{400, agentRouterEscaped, true}, // escaped (#1669)
{400, `{"error":{"message":"模型 gpt-5.6-sol 不支持 /v1/chat/completions 接口"}}`, true}, // its first clause alone
{400, `{"error":{"message":"请改用 /v1/responses(OpenAI Responses API)。"}}`, true}, // its second alone
// new-api's words for a model no channel serves (written from
// memory, not from the report): the model, not the API
{400, `{"error":{"message":"当前分组 default 下对于模型 gone 无可用渠道"}}`, false},
{400, `{"error":{"message":"The requested model is not supported.","code":"model_not_supported"}}`, false},
{429, `rate limit`, false},
{500, `use v1/responses`, false},
+10
View File
@@ -164,4 +164,14 @@ func TestWrongAPINote(t *testing.T) {
if got := wrongAPINote(p, "glm-5.3", res, nil); got != " (asked at https://opencode.ai/zen/go/v1/chat/completions)" {
t.Errorf("glm note %q", got)
}
// a relay with its chat URL alone that names Responses in Chinese:
// the note says to set that URL (#3766)
ar := provider.Provider{ID: "agentrouter", Name: "AgentRouter", Chat: "https://agentrouter.org/v1"}
u, _ = url.Parse("https://agentrouter.org/v1/chat/completions")
res = &http.Response{Request: &http.Request{URL: u}}
for _, body := range []string{agentRouterRefusal, agentRouterEscaped} {
if got := wrongAPINote(ar, "gpt-5.6-sol", res, []byte(body)); got != " (asked at https://agentrouter.org/v1/chat/completions; gpt-5.6-sol is served on /v1/responses, which AgentRouter has no URL for)" {
t.Errorf("AgentRouter note %q for %s", got, body)
}
}
}
+4 -32
View File
@@ -25,6 +25,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/routes"
"github.com/yetone/magpie/internal/usage"
@@ -339,38 +340,9 @@ const reloopedError = "the model's reasoning was stuck in a loop before it said
// over HTTP (proxyconnect) or SOCKS (socks connect).
var proxyDown = regexp.MustCompile(`proxyconnect |socks connect `)
// wordsOf is an error body as its words are matched: a JSON body that
// escapes what isn't ASCII as \uXXXX (Python's json.dumps does by default)
// has its strings decoded and put after it, one to a line, so "用量",
// "频率" or "将在 … 重置" are read whether the vendor escaped them or not
// (#1669). Any other body is matched as it is.
func wordsOf(body []byte) []byte {
if !bytes.Contains(body, []byte(`\u`)) {
return body
}
var v any
if json.Unmarshal(body, &v) != nil {
return body
}
out := append([]byte(nil), body...)
var walk func(any)
walk = func(x any) {
switch x := x.(type) {
case string:
out = append(append(out, '\n'), x...)
case map[string]any:
for _, y := range x {
walk(y)
}
case []any:
for _, y := range x {
walk(y)
}
}
}
walk(v)
return out
}
// wordsOf is catalog.Words: an error body as its words are matched, with
// the strings of a JSON body that escapes what isn't ASCII decoded (#1669).
func wordsOf(body []byte) []byte { return catalog.Words(body) }
// failure says why a reply failed.
func failure(status int, body []byte) string {
+58 -19
View File
@@ -30,6 +30,9 @@ type Result struct {
Millis int64 `json:"ms"`
Model string `json:"model,omitempty"`
Error string `json:"error,omitempty"`
// otherAPI: the vendor said the model isn't served on the API asked
// (catalog.WrongEndpoint), so another may be asked instead
otherAPI bool
}
// Test sends the smallest possible request to each endpoint the vendor
@@ -315,20 +318,7 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
proto = Anthropic
}
// a key made for that endpoint, else one made for any, that sees it
q, ok := p, true
if keys := p.KeysOn(); len(keys) > 0 {
ok = false
serves := p.Serving(model)
pick:
for _, want := range []Protocol{proto, ""} {
for _, k := range keys {
if k.Protocol == want && serves(k) {
q, ok = p.WithKey(k), true
break pick
}
}
}
}
q, ok := p.keySeeing(proto, model)
if !ok {
return Result{Protocol: proto, Model: model, Error: "no key that's on sees this model"}
}
@@ -350,11 +340,7 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
}
return r
}
url, body := tiny(q, proto, UpstreamName(p, model))
if client != "" {
body = asClient(client, proto, body)
}
r := probe(ctx, q, proto, url, q.tested(body), model, testWait)
r := q.testOn(ctx, client, proto, model, UpstreamName(p, model))
if !r.OK && client == "" && proto == Chat && r.Status == 400 && catalog.DrawsID(model) && catalog.PointsToImagesAPI(r.Error) {
// an image model its name doesn't place on the images API
// (agnes-image-2.5-flash, #1837), which the vendor turns away in
@@ -365,9 +351,61 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
return d
}
}
if !r.OK && r.otherAPI && client != ClientClaudeCode {
// the vendor's word that the model isn't served on that API: it
// is asked on the next one that may serve it, as the gateway asks
// a request there (usable), and that one's answer is the model's
// (#3766, char1eslu: models AgentRouter turns away on chat
// completions were red there while the gateway answered them on
// Responses). As Codex it is asked with Codex's headers, as the
// gateway sends them on Responses and Chat; as Claude Code it
// stays, since the gateway sends Claude Code's on Messages alone.
apis := p.APIs(model)
for _, next := range protos {
if next == proto || !(apis == nil && !p.NamedOnlyOn(next) || slices.Contains(apis, next)) {
continue
}
q, ok := p.keySeeing(next, model)
if !ok {
continue
}
if n := q.testOn(ctx, client, next, model, UpstreamName(p, model)); n.OK || !n.otherAPI {
return n
}
}
}
return r
}
// keySeeing is p with the key a test of model on proto goes with: one made
// for that API, else one made for any, that sees the model. A provider
// without keys is left as it is.
func (p Provider) keySeeing(proto Protocol, model string) (Provider, bool) {
keys := p.KeysOn()
if len(keys) == 0 {
return p, true
}
serves := p.Serving(model)
for _, want := range []Protocol{proto, ""} {
for _, k := range keys {
if k.Protocol == want && serves(k) {
return p.WithKey(k), true
}
}
}
return p, false
}
// testOn is model's test on proto's endpoint with p's key, asked for by
// its upstream name, as client would ask it when one is named (TestAs).
func (p Provider) testOn(ctx context.Context, client string, proto Protocol, model, upstream string) Result {
url, body := tiny(p, proto, upstream)
if client != "" {
body = asClient(client, proto, body)
}
return probe(ctx, p, proto, url, p.tested(body), model, testWait)
}
// keyFor is p using the first key on that works with proto: one made for
// it, else one made for any. A provider without keys is left as it is.
func (p Provider) keyFor(proto Protocol) (Provider, bool) {
@@ -567,6 +605,7 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b
}
b, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
r.Error = APIError(b, res.Status)
r.otherAPI = catalog.WrongEndpoint(res.StatusCode, b)
return r
}
+192
View File
@@ -7,9 +7,12 @@ import (
"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
@@ -219,3 +222,192 @@ func TestTestModelsGoesWhereTheVendorPointsIt(t *testing.T) {
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)
}
}