provider, gateway: a backend that only streams is tested and served (Cyrus_4433 on X: claude-relay-service "400 · Stream must be set to true")
A CRS Responses endpoint, like Codex's own backend, turns away a request that doesn't ask for stream:true. The editor's Test models and protocol detection send one small body, so every model of such a relay was red; an agent that sent stream:false got the same 400 through the gateway. Probe: probeAt asks once more with stream:true when a 400/422 says the stream must be set (provider.StreamRequired, WithStream). Chosen over streaming every probe so a vendor that takes one body keeps being asked for one; every probe (model test, per-model check, detect, key check) goes through probeAt. Gateway: passthrough marks the model stream-only on that 400 for a request asking one body and returns done=false; attempt then translates on the same API (always streamed upstream, whole reply to the client), and asks so at once from then on, as a refused custom tool is. Run (mote): new tests built from the reporter's literal error, red on the old code (TestProbeStreamsWhereTheBackendOnlyStreams, TestDetectFindsAStreamOnlyBackend, TestWholeReplyFromAStreamOnlyBackend), green on the new; go vet darwin, windows, linux nogui; go test ./internal/provider ./internal/gateway ok. Each fix broken by hand (probe retry stashed, gateway hook stashed): red. Not tried: a real CRS relay; the rest of ./... (started after the tag).
This commit is contained in:
@@ -5624,6 +5624,12 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
if relay && !keep && customOff() {
|
||||
relay, ownAPI = false, true
|
||||
}
|
||||
// and a backend that turned a request for one body away because it
|
||||
// only streams (stream_only.go) is asked streamed, translated
|
||||
streamOnly := (from == provider.Chat || from == provider.Responses) && !streamOf(body) && !s.fits(p.ID, streamOnlyRefused(model), from)
|
||||
if relay && !keep && streamOnly {
|
||||
relay, ownAPI = false, true
|
||||
}
|
||||
if keep && relayable {
|
||||
relay, ownAPI = true, false
|
||||
}
|
||||
@@ -5644,7 +5650,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
// the model isn't served on the client's own API: speak another;
|
||||
// or it turned the custom tools away just now: speak it translated,
|
||||
// except a compaction, which a translation would leave out
|
||||
if customOff() {
|
||||
if customOff() || !s.fits(p.ID, streamOnlyRefused(model), from) && !streamOf(body) {
|
||||
if keep {
|
||||
return writeError(w, from, status, msg), msg
|
||||
}
|
||||
@@ -6797,6 +6803,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
s.markUnfit(p.ID, customToolRefused(model), proto)
|
||||
return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false
|
||||
}
|
||||
if gather == nil && refusesWhole(proto, body, b) {
|
||||
// a backend that only streams (stream_only.go): the request
|
||||
// is translated on the same API, which asks it streamed and
|
||||
// gives the client one body, and so from then on
|
||||
res.Body.Close()
|
||||
s.markUnfit(p.ID, streamOnlyRefused(model), proto)
|
||||
return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false
|
||||
}
|
||||
fs := refusedOptional(res.StatusCode, b, body)
|
||||
// and an earlier turn's thinking sent back inside messages, which
|
||||
// DeepSeek and Kimi want and a stricter vendor turns away (#494)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A backend that only streams (claude-relay-service's Responses endpoint,
|
||||
// like Codex's own ChatGPT backend) turns a request that asks for one body
|
||||
// away: "Stream must be set to true" (Cyrus_4433 on X). An agent that sent
|
||||
// stream:false got that 400. The request is then translated on the same
|
||||
// API, which always asks the upstream streamed and gives the client its
|
||||
// whole reply (translate), and so from then on, as a custom tool turned
|
||||
// away is (custom_tool.go).
|
||||
|
||||
// streamOnlyRefused is how unfit remembers model's backend answering only
|
||||
// streamed requests.
|
||||
func streamOnlyRefused(model string) string { return "stream only\x00" + model }
|
||||
|
||||
// refusesWhole is whether a 400's body says the request must ask for a
|
||||
// stream, while the client's body asked for one whole reply.
|
||||
func refusesWhole(proto provider.Protocol, body, reply []byte) bool {
|
||||
return (proto == provider.Chat || proto == provider.Responses) && !streamOf(body) && provider.StreamRequired(wordsOf(reply))
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A claude-relay-service Responses endpoint answers a request for one body
|
||||
// 400 "Stream must be set to true" (Cyrus_4433 on X). An agent that sent
|
||||
// stream:false gets its whole reply all the same: the request is asked
|
||||
// again streamed, and the next one is asked so at once.
|
||||
func TestWholeReplyFromAStreamOnlyBackend(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
var bodies []string
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
bodies = append(bodies, string(b))
|
||||
mu.Unlock()
|
||||
if !gjson.GetBytes(b, "stream").Bool() {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, `{"error":{"message":"Stream must be set to true","type":"invalid_request_error"}}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
|
||||
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[]}}`,
|
||||
`data: {"type":"response.output_text.delta","output_index":0,"item_id":"m1","content_index":0,"delta":"pong"}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"pong"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"pong"}]}],"usage":{"input_tokens":3,"output_tokens":1}}}`,
|
||||
))
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "My Relay", Key: "k", Responses: up.URL + "/v1", Models: []string{"gpt-6-sol"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := New().Handler()
|
||||
for i := range 2 {
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"relay/gpt-6-sol","stream":false,"input":"hi"}`)))
|
||||
if rec.Code != 200 || gjson.Get(rec.Body.String(), "output.0.content.0.text").String() != "pong" {
|
||||
t.Fatalf("ask %d: HTTP %d: %s", i, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
// the first is refused once, then asked streamed; the second is asked
|
||||
// streamed at once
|
||||
if len(bodies) != 3 || gjson.Get(bodies[0], "stream").Bool() || !gjson.Get(bodies[1], "stream").Bool() || !gjson.Get(bodies[2], "stream").Bool() {
|
||||
t.Fatalf("asked %d times: %q", len(bodies), bodies)
|
||||
}
|
||||
}
|
||||
|
||||
// Another 400 is the client's, as before: a request for one body that is
|
||||
// refused for something else is asked once.
|
||||
func TestOtherRefusalsAreNotStreamOnly(t *testing.T) {
|
||||
fresh(t)
|
||||
n := 0
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n++
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, `{"error":{"message":"input is too long"}}`)
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "My Relay", Key: "k", Responses: up.URL + "/v1", Models: []string{"gpt-6-sol"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"relay/gpt-6-sol","input":"hi"}`)))
|
||||
if rec.Code != 400 || n != 1 {
|
||||
t.Fatalf("HTTP %d after %d asks: %s", rec.Code, n, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A backend that only streams (claude-relay-service's Responses endpoint,
|
||||
// like Codex's own ChatGPT backend) turns a request without stream:true
|
||||
// away with a 400: "Stream must be set to true" (Cyrus_4433 on X: every
|
||||
// model of a CRS relay red in the editor's test).
|
||||
//
|
||||
// The probe asks once more streamed when it hears this, rather than
|
||||
// streaming every probe: a vendor that takes one body keeps being asked
|
||||
// for one, and only a backend that says so is asked otherwise.
|
||||
var streamRequired = lazyre.New(`(?i)\bstream(ing)?\b[^.\n]{0,40}\b(must|need|needs|should|has to|have to)\b[^.\n]{0,30}\btrue\b|\bonly\s+(supports?|accepts?|allows?|serves?)\s+(requests\s+(with|in)\s+)?stream|\brequires?\s+stream|\bstream(ing)?\s+(is\s+)?(required|mandatory)\b`)
|
||||
|
||||
// StreamRequired is whether a 400's words say the request must ask for a
|
||||
// stream.
|
||||
func StreamRequired(msg []byte) bool { return streamRequired.Match(msg) }
|
||||
|
||||
// WithStream is body, a JSON object that doesn't ask for a stream, asking
|
||||
// for one, and whether it changed. Its other fields keep their bytes.
|
||||
func WithStream(body []byte) ([]byte, bool) {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &m) != nil || m == nil || streams(body) {
|
||||
return body, false
|
||||
}
|
||||
m["stream"] = json.RawMessage("true")
|
||||
out, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return body, false
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// crsStreamOnly is a claude-relay-service Responses endpoint as
|
||||
// Cyrus_4433 on X met it: "2 个模型中有 2 个没有响应;gpt-6-sol: 400 ·
|
||||
// Stream must be set to true", for a request that didn't ask for a stream.
|
||||
func crsStreamOnly(t *testing.T, plain bool) (*httptest.Server, func() []string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
got = append(got, string(b))
|
||||
mu.Unlock()
|
||||
if !gjson.GetBytes(b, "stream").Bool() {
|
||||
rw.WriteHeader(http.StatusBadRequest)
|
||||
if plain {
|
||||
_, _ = io.WriteString(rw, "Stream must be set to true")
|
||||
} else {
|
||||
_, _ = io.WriteString(rw, `{"error":{"message":"Stream must be set to true","type":"invalid_request_error"}}`)
|
||||
}
|
||||
return
|
||||
}
|
||||
rw.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = io.WriteString(rw, "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"id\":\"r\"}}\n\n"+
|
||||
"event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}\n\n")
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), got...) }
|
||||
}
|
||||
|
||||
func sandboxHome(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"))
|
||||
}
|
||||
|
||||
// A model's test on a backend that only streams is asked once more
|
||||
// streamed, and is green: the editor's Test models, one model at a time.
|
||||
func TestProbeStreamsWhereTheBackendOnlyStreams(t *testing.T) {
|
||||
for _, plain := range []bool{false, true} {
|
||||
sandboxHome(t)
|
||||
srv, asked := crsStreamOnly(t, plain)
|
||||
p := Provider{ID: "relay", Name: "My Relay", Responses: srv.URL + "/v1", Key: "k", Models: []string{"gpt-6-sol", "gpt-6.1-sol"}}
|
||||
rs := p.TestModels(context.Background(), []string{"gpt-6-sol", "gpt-6.1-sol"})
|
||||
if len(rs) == 0 {
|
||||
t.Fatalf("plain=%v: no results", plain)
|
||||
}
|
||||
for _, r := range rs {
|
||||
if !r.OK {
|
||||
t.Errorf("plain=%v: %+v", plain, r)
|
||||
}
|
||||
}
|
||||
on, off := 0, 0
|
||||
for _, b := range asked() {
|
||||
if gjson.Get(b, "stream").Bool() {
|
||||
on++
|
||||
} else {
|
||||
off++
|
||||
}
|
||||
}
|
||||
if on != 2 || off != 2 {
|
||||
t.Errorf("plain=%v: %d streamed, %d not: %v", plain, on, off, asked())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Protocol detection probes the same way, so a stream-only Responses
|
||||
// endpoint is found.
|
||||
func TestDetectFindsAStreamOnlyBackend(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
srv, _ := crsStreamOnly(t, false)
|
||||
p := Provider{ID: "relay", Name: "My Relay", Responses: srv.URL + "/v1", Key: "k"}
|
||||
ds, err := p.Detect(context.Background(), srv.URL+"/v1", "gpt-6-sol")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ok := false
|
||||
for _, d := range ds {
|
||||
if d.Protocol == Responses && d.OK {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
t.Errorf("%+v", ds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamRequired(t *testing.T) {
|
||||
for msg, want := range map[string]bool{
|
||||
"Stream must be set to true": true,
|
||||
`{"error":{"message":"stream must be true"}}`: true,
|
||||
"400 · Stream must be set to true": true,
|
||||
"This endpoint only supports streaming": true,
|
||||
"streaming is required": true,
|
||||
"max_tokens must be at most 8": false,
|
||||
"stream_options is only allowed when stream is true.": false,
|
||||
"model not found": false,
|
||||
} {
|
||||
if got := StreamRequired([]byte(msg)); got != want {
|
||||
t.Errorf("%q: %v", msg, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -814,6 +814,14 @@ func probeAt(ctx context.Context, p Provider, proto Protocol, url string, body [
|
||||
return probeOnce(ctx, p, proto, url, b, model, wait)
|
||||
}
|
||||
}
|
||||
if (r.Status == http.StatusBadRequest || r.Status == http.StatusUnprocessableEntity) && StreamRequired([]byte(r.Error)) {
|
||||
// a backend that only streams (a claude-relay-service's
|
||||
// Responses, Cyrus_4433 on X: "Stream must be set to true") is
|
||||
// asked once more streamed, as the gateway asks it
|
||||
if b, ok := WithStream(body); ok {
|
||||
return probeOnce(ctx, p, proto, url, b, model, wait)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user