gateway, provider: Claude Desktop's requests to ModelScope go on its Responses API, which reports the cache and reasoning that its Chat API leaves out (#1578, sparrowbits)
What changed
- provider.ResponsesTellsCache: ModelScope's API-Inference (the
"modelscope" preset, or a provider whose Responses URL is
api-inference.modelscope.cn) with both a Chat and a Responses URL.
ResponsesFirst is true there for every model, so `usable` puts
Responses before Chat. A translated request (Claude Desktop / Claude
Code's /v1/messages, a Gemini client) goes to /responses, and
Provider.Native wires Pi, omp and droid to Responses. A Chat client's
request is still relayed on Chat, and Codex's on Responses, as before.
- forwardTranslated: when Responses is first only for the cache report,
a 404 there marks the model unfit on Responses and asks it on Chat. A
ModelScope model with no Responses route then works as it did before.
This fallback is scoped to ResponsesTellsCache.
- docs/subsystems/gateway-routing.md: the "One try" row names it.
Why
The reporter's usage.jsonl covers 202 Claude Desktop requests, all
/v1/messages -> /v1/chat/completions: 0 cache_read over 34.9M input
tokens, and reasoning 0/202. Codex on /v1/responses with the same model,
on the same day, read 94% from cache. Their direct calls show why.
ModelScope's /responses answers
input_tokens_details.cached_tokens = 12288 on the second identical
prompt. Its /chat/completions answers only prompt_tokens /
completion_tokens / total_tokens, though it is served from the same
cache. magpie already maps Chat's prompt_tokens_details.cached_tokens
(and prompt_cache_hit_tokens, cached_tokens, cache_read_input_tokens) to
cache_read_input_tokens (cUsage.usage). The new test
TestOtherChatAndResponsesKeepChat pins that. So the missing figure was
not a mapping gap: ModelScope's Chat API never sends one. The fix is to
ask on the API that does.
Scope: other presets with both Chat and Responses URLs keep Chat.
- DeepSeek, xAI, Zhipu, MiMo, Qianfan, Tencent TokenHub, Volcengine's
plans, OpenCode Zen/Go, Command Code, PipeLLM and CherryIn have an
Anthropic URL, so Claude-format requests are relayed on Messages as
they are.
- Groq's and Volcengine Ark's Chat APIs report
prompt_tokens_details.cached_tokens, and Groq's Responses API is a
partial beta.
- OpenAI keeps its existing OpenAI-model rule.
- Nothing is known of a custom relay's Responses API.
What was run
- New tests in internal/gateway/responses_tells_cache_test.go, against
an httptest fake that answers with the reporter's literal usage
bodies:
- TestModelScopeMessagesTellTheCache: streamed and whole Messages go
to /v1/responses, and the client gets cache_read_input_tokens 12288,
input_tokens 108 and output_tokens 32.
- TestModelScopeModelNotOnResponsesGoesToChat: a 404 on Responses
goes to Chat, and stays on Chat for the next request.
- TestOtherChatAndResponsesKeepChat
- TestModelScopeNativeIsResponses
- Broken by hand:
- Without the ResponsesTellsCache check in ResponsesFirst,
TestModelScopeMessagesTellTheCache fails ("Messages went to
[/v1/chat/completions], want /v1/responses"), and so do
TestModelScopeNativeIsResponses and the fallback test.
- Without the 404 fallback, TestModelScopeModelNotOnResponsesGoesToChat
fails with "404 ModelScope: Not Found".
- gofmt -l is clean. go vet, and GOOS=linux and GOOS=windows go vet
-tags nogui, pass on internal/gateway and internal/provider.
- Full suite: go test -tags nogui ./... under a temp HOME at base 1d016ee3f: rc=0, 48 packages ok.
Not tried
- Not tried against the real ModelScope API: no ModelScope token here.
The fake is built from the reporter's bodies.
- Which ModelScope models lack a /responses route, and what ModelScope
answers for them, isn't known. A 404 is assumed; any other error
reaches the client as ModelScope said it.
- Reasoning is counted from Responses' output_tokens_details, but the
reporter's excerpt doesn't show that field, so the test doesn't assert
on it.
This commit is contained in:
@@ -23,7 +23,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks. | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) |
|
||||
| Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. | [`sink.go`](../../internal/gateway/sink.go) |
|
||||
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |
|
||||
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`) and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. | [`trace.go`](../../internal/gateway/trace.go) |
|
||||
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). | [`prompt.go`](../../internal/gateway/prompt.go) |
|
||||
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
|
||||
|
||||
@@ -4083,7 +4083,11 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
continue
|
||||
}
|
||||
dropped = false
|
||||
if !wrongEndpoint(res.StatusCode, b) {
|
||||
// Responses is asked first there only for what it tells of the
|
||||
// cache, not because the model needs it: a model the vendor doesn't
|
||||
// serve on it (404) is asked on Chat, as before #1578
|
||||
cacheOnly := to == provider.Responses && res.StatusCode == http.StatusNotFound && p.ResponsesTellsCache()
|
||||
if !cacheOnly && !wrongEndpoint(res.StatusCode, b) {
|
||||
return res, to, nil
|
||||
}
|
||||
s.markUnfit(p.ID, model, to)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The usage bodies sparrowbits got from ModelScope's API-Inference for the
|
||||
// same ~12K-token prompt asked twice (#1578): Responses says 12288 of it
|
||||
// was read from the cache, Chat says nothing of the cache at all.
|
||||
const (
|
||||
modelScopeResponsesUsage = `{"input_tokens": 12396, "input_tokens_details": {"cached_tokens": 12288}, "output_tokens": 32, "total_tokens": 12428}`
|
||||
modelScopeChatUsage = `{"prompt_tokens": 12364, "completion_tokens": 293, "total_tokens": 12657}`
|
||||
)
|
||||
|
||||
// fakeModelScope answers on Chat and Responses with the reporter's usage,
|
||||
// streamed when asked, and records each request's path. A model in
|
||||
// notOnResponses is answered 404 on Responses.
|
||||
func fakeModelScope(t *testing.T, chatUsage string, notOnResponses ...string) (*httptest.Server, func() []string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var paths []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
paths = append(paths, r.URL.Path)
|
||||
mu.Unlock()
|
||||
var body struct{ Model string }
|
||||
json.Unmarshal(b, &body)
|
||||
stream := streamOf(b)
|
||||
switch {
|
||||
case r.URL.Path == "/v1/responses" && strings.Contains(strings.Join(notOnResponses, "\x00"), body.Model):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(404)
|
||||
io.WriteString(w, `{"error":{"message":"Not Found"}}`)
|
||||
case r.URL.Path == "/v1/responses" && stream:
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"item_id\":\"i\",\"output_index\":0,\"content_index\":0,\"delta\":\"ok\"}\n\n"+
|
||||
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"x\",\"output\":[{\"type\":\"message\",\"id\":\"i\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}],\"usage\":"+modelScopeResponsesUsage+"}}\n\n")
|
||||
case r.URL.Path == "/v1/responses":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"r","object":"response","status":"completed","model":"x","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":`+modelScopeResponsesUsage+`}`)
|
||||
case r.URL.Path == "/v1/chat/completions" && stream:
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, "data: {\"id\":\"c\",\"object\":\"chat.completion.chunk\",\"model\":\"x\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"}}]}\n\n"+
|
||||
"data: {\"id\":\"c\",\"object\":\"chat.completion.chunk\",\"model\":\"x\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":"+chatUsage+"}\n\ndata: [DONE]\n\n")
|
||||
case r.URL.Path == "/v1/chat/completions":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"c","object":"chat.completion","model":"x","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":`+chatUsage+`}`)
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p := paths
|
||||
paths = nil
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
// messagesUsage is the usage a Messages reply gave the client, whole or
|
||||
// streamed: the last value of each field the stream named.
|
||||
func messagesUsage(t *testing.T, reply string) map[string]int {
|
||||
t.Helper()
|
||||
out := map[string]int{}
|
||||
take := func(u map[string]any) {
|
||||
for k, v := range u {
|
||||
if n, ok := v.(float64); ok {
|
||||
out[k] = int(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
var whole struct {
|
||||
Usage map[string]any `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal([]byte(reply), &whole) == nil && whole.Usage != nil {
|
||||
take(whole.Usage)
|
||||
return out
|
||||
}
|
||||
for _, line := range strings.Split(reply, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var ev struct {
|
||||
Usage map[string]any `json:"usage"`
|
||||
Message struct {
|
||||
Usage map[string]any `json:"usage"`
|
||||
} `json:"message"`
|
||||
}
|
||||
if json.Unmarshal([]byte(data), &ev) != nil {
|
||||
continue
|
||||
}
|
||||
take(ev.Message.Usage)
|
||||
take(ev.Usage)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Claude Desktop's Messages to a ModelScope model are asked on ModelScope's
|
||||
// Responses API, which tells what its cache answered, not on Chat, which
|
||||
// doesn't (#1578, sparrowbits: 0 of 34.9M tokens read from cache over 202
|
||||
// requests on Chat, where Codex on Responses read 94%). The client is told
|
||||
// the 12288 tokens read from cache, streamed and whole.
|
||||
func TestModelScopeMessagesTellTheCache(t *testing.T) {
|
||||
srv, seen := fakeModelScope(t, modelScopeChatUsage)
|
||||
for _, stream := range []string{"true", "false"} {
|
||||
fresh(t)
|
||||
if err := provider.Save(provider.Provider{ID: "modelscope", Preset: "modelscope", Name: "ModelScope", Key: "k",
|
||||
Chat: srv.URL + "/v1", Responses: srv.URL + "/v1", Models: []string{"Qwen/Qwen3.8-Flash-Next"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen()
|
||||
code, reply := post(t, "/v1/messages", `{"model":"modelscope/Qwen/Qwen3.8-Flash-Next","max_tokens":100,"stream":`+stream+
|
||||
`,"system":[{"type":"text","text":"you are","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, reply)
|
||||
}
|
||||
if paths := seen(); len(paths) != 1 || paths[0] != "/v1/responses" {
|
||||
t.Fatalf("stream=%s: Messages went to %v, want /v1/responses", stream, paths)
|
||||
}
|
||||
if u := messagesUsage(t, reply); u["cache_read_input_tokens"] != 12288 || u["input_tokens"] != 108 || u["output_tokens"] != 32 {
|
||||
t.Errorf("stream=%s: usage %v, want 12288 read from cache, 108 input, 32 output\n%s", stream, u, reply)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A model ModelScope doesn't serve on Responses (404 there) is asked on
|
||||
// Chat, as before, and stays there.
|
||||
func TestModelScopeModelNotOnResponsesGoesToChat(t *testing.T) {
|
||||
srv, seen := fakeModelScope(t, modelScopeChatUsage, "Qwen/Qwen-Chat-Only")
|
||||
fresh(t)
|
||||
if err := provider.Save(provider.Provider{ID: "modelscope", Preset: "modelscope", Name: "ModelScope", Key: "k",
|
||||
Chat: srv.URL + "/v1", Responses: srv.URL + "/v1", Models: []string{"Qwen/Qwen-Chat-Only"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := New().Handler()
|
||||
ask := func() {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(
|
||||
`{"model":"modelscope/Qwen/Qwen-Chat-Only","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)))
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "ok") {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
seen()
|
||||
ask()
|
||||
if paths := seen(); len(paths) != 2 || paths[0] != "/v1/responses" || paths[1] != "/v1/chat/completions" {
|
||||
t.Fatalf("went to %v, want Responses then Chat", paths)
|
||||
}
|
||||
ask()
|
||||
if paths := seen(); len(paths) != 1 || paths[0] != "/v1/chat/completions" {
|
||||
t.Fatalf("second request went to %v, want Chat alone", paths)
|
||||
}
|
||||
}
|
||||
|
||||
// A provider with Chat and Responses that isn't ModelScope keeps Chat for a
|
||||
// translated request (nothing is known of its Responses API), and a Chat
|
||||
// API that tells its cache in prompt_tokens_details.cached_tokens reaches a
|
||||
// Messages client as cache_read_input_tokens.
|
||||
func TestOtherChatAndResponsesKeepChat(t *testing.T) {
|
||||
srv, seen := fakeModelScope(t, `{"prompt_tokens": 12364, "completion_tokens": 293, "total_tokens": 12657, "prompt_tokens_details": {"cached_tokens": 12288}}`)
|
||||
for _, stream := range []string{"true", "false"} {
|
||||
fresh(t)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k",
|
||||
Chat: srv.URL + "/v1", Responses: srv.URL + "/v1", Models: []string{"glm-5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen()
|
||||
code, reply := post(t, "/v1/messages", `{"model":"relay/glm-5","max_tokens":100,"stream":`+stream+`,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, reply)
|
||||
}
|
||||
if paths := seen(); len(paths) != 1 || paths[0] != "/v1/chat/completions" {
|
||||
t.Fatalf("stream=%s: went to %v, want Chat", stream, paths)
|
||||
}
|
||||
if u := messagesUsage(t, reply); u["cache_read_input_tokens"] != 12288 || u["input_tokens"] != 76 {
|
||||
t.Errorf("stream=%s: usage %v, want 12288 read from cache, 76 input", stream, u)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Agents that ask each model on one API (Pi, omp, droid) are wired to
|
||||
// ModelScope's Responses, by its preset or its host; another vendor with
|
||||
// both keeps Chat.
|
||||
func TestModelScopeNativeIsResponses(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
p provider.Provider
|
||||
want provider.Protocol
|
||||
}{
|
||||
{provider.Provider{Preset: "modelscope", Chat: "http://127.0.0.1:1/v1", Responses: "http://127.0.0.1:1/v1"}, provider.Responses},
|
||||
{provider.Provider{Chat: "https://api-inference.modelscope.cn/v1", Responses: "https://api-inference.modelscope.cn/v1"}, provider.Responses},
|
||||
{provider.Provider{Chat: "https://api-inference.modelscope.cn/v1"}, provider.Chat},
|
||||
{provider.Provider{Preset: "groq", Chat: "https://api.groq.com/openai/v1", Responses: "https://api.groq.com/openai/v1"}, provider.Chat},
|
||||
} {
|
||||
if got := c.p.Native("Qwen/Qwen3.8-Flash-Next"); got != c.want {
|
||||
t.Errorf("preset %q, chat %s, responses %s: Native %q, want %q", c.p.Preset, c.p.Chat, c.p.Responses, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1216,8 +1216,13 @@ func (p Provider) Speaks() []Protocol {
|
||||
func (p Provider) FactoryGemini() bool { return p.ID == "factory" && p.Account != nil }
|
||||
|
||||
// ResponsesFirst: an OpenAI model on OpenAI's API, Copilot's, PipeLLM's or Bedrock's,
|
||||
// which is best asked on the Responses API though Chat serves it too.
|
||||
// which is best asked on the Responses API though Chat serves it too; and
|
||||
// every model where only the Responses API tells what the vendor's cache
|
||||
// answered (ResponsesTellsCache).
|
||||
func (p Provider) ResponsesFirst(model string) bool {
|
||||
if p.ResponsesTellsCache() {
|
||||
return true
|
||||
}
|
||||
if p.Responses != "" && p.IsBedrock() {
|
||||
return bedrockGPT(model)
|
||||
}
|
||||
@@ -1229,6 +1234,24 @@ func (p Provider) ResponsesFirst(model string) bool {
|
||||
return openAIModel(model)
|
||||
}
|
||||
|
||||
// ResponsesTellsCache is a provider whose Responses API says how much of
|
||||
// the prompt its cache answered (input_tokens_details.cached_tokens) and
|
||||
// what the model reasoned, while its Chat API, served by the same cache,
|
||||
// says neither: ModelScope's API-Inference, by its preset or its host
|
||||
// (#1578, sparrowbits: Claude Desktop, translated to Chat, read 0 of 34.9M
|
||||
// tokens from cache; Codex on Responses, 94%). A translated request goes
|
||||
// there on Responses, and an agent that asks each model on one API is
|
||||
// wired to it. Other vendors with both URLs keep Chat: their Chat reports
|
||||
// its cache (Groq, Volcengine Ark), their Claude-format requests go to
|
||||
// their Anthropic URL as they are, or nothing is known of their Responses
|
||||
// API (a relay the user added).
|
||||
func (p Provider) ResponsesTellsCache() bool {
|
||||
if p.Responses == "" || p.Chat == "" {
|
||||
return false
|
||||
}
|
||||
return p.Preset == "modelscope" || HostOf(p.Responses) == "api-inference.modelscope.cn"
|
||||
}
|
||||
|
||||
// MessagesFirst: a Claude model where the provider has Anthropic's Messages
|
||||
// API, which is best asked there though its Chat or Responses API serves
|
||||
// it too — a relay that serves both drops cache_control on Chat, so every
|
||||
|
||||
Reference in New Issue
Block a user