gateway: a Copilot Gemini conversation past the model's 10 images goes on with its oldest left out (yuushabu_buyinn on X)
Copilot refuses a Gemini request whose conversation holds more images than
the model takes ("too many images: maximum allowed for model
gemini-4-carbon is 10, got 12"), and it counts every image in the
conversation, not one message's. A long chat with screenshots stopped
working for good.
Now, on that 400 from a Copilot account, the gateway learns the cap the
error states (per provider and model), replaces the oldest images outside
the latest user message with a one-line placeholder until the count fits,
and sends again once. Later turns are fitted before they are sent. A
request under the cap is never changed. If the latest user message alone
is over the cap, the refusal is passed on as it came. Other vendors are
untouched (imageCapped: Copilot accounts only).
The cap is learned from the 400, not from /models' max_prompt_images:
Copilot lists 1 for gpt-* and 5 for Claude models but took 3 images on
gpt-4.1 and 7 on claude-sonnet-5 live, so the list is enforced only for
Gemini and would strip images that are fine.
Run (suite at the pre-rebase tree 4649e2269; after rebasing on 58cf76453, internal/gateway ran again: ok, 923s; on b9c385286 the targeted gateway tests above plus Advisor: ok; and go vet ./internal/... plus linux and windows vet of gateway and provider: ok):
- Red on the old code: with the two gateway.go hooks taken out,
TestCopilotGeminiImagesOverCap and the follow-up turn fail with 400
"too many images"; green with them.
- go test ./internal/gateway -run 'ImageCap|CopilotGeminiImages|ByteCap|
OverByteCap|CopilotGemini|BodyCap|Compaction': ok.
- Full suite on mote (go test ./... -timeout 45m, one suite on the box):
101 packages ok, no FAIL (gateway 1049s, agent 447s, provider 277s).
- go vet for darwin, linux and windows: ok. gofmt -l: clean.
- Real Copilot (gh token, sandbox HOME, magpie serve -tags nogui on mote):
gemini-4-carbon with 12 images: 200 after one refusal and a resend with
10; the next turn with 12: 200, fitted before sending; 10 images: 200
unchanged; claude-sonnet-5 with 12 images: 200 unchanged.
Not tried: Copilot Gemini over Responses or Anthropic routes (Copilot
serves Gemini on /chat/completions only); a GUI path (none changed).
This commit is contained in:
@@ -167,7 +167,8 @@ eleven seconds); each callback uses the configured bounded hook timeout. Request
|
||||
requests magpie makes on its own call `serve` directly and run no hooks:
|
||||
Codex's compaction and its fallback turn, titles, System One's
|
||||
classifier, search and vision (#4847). A request over a provider's byte
|
||||
cap is fitted in the gateway itself, not by a hook (`body_cap.go`).
|
||||
cap is fitted in the gateway itself, not by a hook (`body_cap.go`), as is
|
||||
one over a Copilot model's image cap (`image_cap.go`).
|
||||
- `internal/gateway/gateway_hooks.go`: bounded response observation and
|
||||
`gatewayReply`, a stream made one reply.
|
||||
- `internal/gateway/signin_hooks.go`: sign-in events, and
|
||||
|
||||
@@ -124,8 +124,9 @@ func statedCap(errBody []byte, sent int) int {
|
||||
return least
|
||||
}
|
||||
|
||||
// bodyCaps are the byte caps providers refused requests over, by
|
||||
// provider id, for as long as magpie runs.
|
||||
// bodyCaps are the caps providers refused requests over, bytes by
|
||||
// provider id (or a model's images, image_cap.go), for as long as magpie
|
||||
// runs.
|
||||
type bodyCaps struct {
|
||||
mu sync.Mutex
|
||||
m map[string]int
|
||||
@@ -314,7 +315,12 @@ func historyOf(to provider.Protocol) string {
|
||||
// imageWith is the part an image of the protocol is replaced with, ""
|
||||
// when part is no image.
|
||||
func imageWith(to provider.Protocol, part gjson.Result) string {
|
||||
text, _ := json.Marshal(imageLeftOut)
|
||||
return imageWithText(to, part, imageLeftOut)
|
||||
}
|
||||
|
||||
// imageWithText is imageWith with the words said in the image's place.
|
||||
func imageWithText(to provider.Protocol, part gjson.Result, said string) string {
|
||||
text, _ := json.Marshal(said)
|
||||
switch to {
|
||||
case provider.Responses:
|
||||
if part.Get("type").String() == "input_image" {
|
||||
@@ -381,6 +387,13 @@ func latestUser(to provider.Protocol, items []gjson.Result) int {
|
||||
// be left out: inline ones (of 1 KB or more, which a link never is), not
|
||||
// the latest user message's.
|
||||
func historyImages(to provider.Protocol, body []byte) []capImage {
|
||||
return bodyImages(to, body, 1<<10, false, imageLeftOut)
|
||||
}
|
||||
|
||||
// bodyImages are the images of body's history, oldest first, each of
|
||||
// least bytes or more, with what said would put in its place; the latest
|
||||
// user message's only with all.
|
||||
func bodyImages(to provider.Protocol, body []byte, least int, all bool, said string) []capImage {
|
||||
var items []gjson.Result
|
||||
getIn(body, historyOf(to)).ForEach(func(_, it gjson.Result) bool {
|
||||
items = append(items, it)
|
||||
@@ -394,9 +407,9 @@ func historyImages(to provider.Protocol, body []byte) []capImage {
|
||||
return
|
||||
}
|
||||
if v.IsObject() {
|
||||
if with := imageWith(to, v); with != "" {
|
||||
if with := imageWithText(to, v, said); with != "" {
|
||||
end := v.Index + len(v.Raw)
|
||||
if len(v.Raw) >= 1<<10 && v.Index > 0 && end <= len(body) && string(body[v.Index:end]) == v.Raw {
|
||||
if len(v.Raw) >= least && v.Index > 0 && end <= len(body) && string(body[v.Index:end]) == v.Raw {
|
||||
out = append(out, capImage{at: v.Index, end: end, with: with})
|
||||
}
|
||||
return
|
||||
@@ -408,7 +421,7 @@ func historyImages(to provider.Protocol, body []byte) []capImage {
|
||||
})
|
||||
}
|
||||
for i, it := range items {
|
||||
if i != keep {
|
||||
if i != keep || all {
|
||||
walk(it, 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,6 +567,9 @@ type Server struct {
|
||||
// bodyCaps are the byte caps providers refused a request over
|
||||
// (body_cap.go)
|
||||
bodyCaps bodyCaps
|
||||
// imageCaps are the image caps a model refused a request over, by
|
||||
// provider id and model (image_cap.go)
|
||||
imageCaps bodyCaps
|
||||
// codexTurns is the model each Codex last had a turn of its own
|
||||
// answered on, by caller (codexMemoryStandIn)
|
||||
codexTurns sync.Map
|
||||
@@ -6122,6 +6125,11 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
|
||||
// oldest images left out, or said as a 413 (body_cap.go)
|
||||
res, err = s.refitOverCap(ctx, p, to, path, body, in, res)
|
||||
}
|
||||
if err == nil && res.StatusCode >= 400 {
|
||||
// more images than the model takes: asked again with its oldest
|
||||
// left out (image_cap.go)
|
||||
res, err = s.refitImageCap(ctx, p, to, path, body, in, res)
|
||||
}
|
||||
if err == nil && mantleRoutes(p, to) {
|
||||
res, err = s.mantleReroute(ctx, p, to, path, body, in, res)
|
||||
}
|
||||
@@ -6198,6 +6206,8 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
body = kimiLockedSampling(p, to, body)
|
||||
body = clinePin(p, to, body)
|
||||
body = codexImagesFit(p, to, body)
|
||||
// no more images than the model refused more over (image_cap.go)
|
||||
body = s.withinImageCap(p, to, path, body)
|
||||
// the tool turns' thinking a provider's model asked for before
|
||||
// (thinking_back.go)
|
||||
body = s.withThinkingBack(p, to, body)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A model's cap on the images of one request.
|
||||
//
|
||||
// Copilot's Gemini models take at most 10 images in a request, the whole
|
||||
// conversation's counted: past them every turn is refused 400 "too many
|
||||
// images: maximum allowed for model gemini-4-carbon is 10, got 12", and a
|
||||
// conversation that has shown the model ten screenshots can't go on
|
||||
// (yuushabu_buyinn on X). Copilot's /models lists a max_prompt_images
|
||||
// for every model, but only Gemini's is held to (probed live: gpt-4.1,
|
||||
// listed at 1, took 3; claude-sonnet-5, listed at 5, took 7), so the cap
|
||||
// is learned from the refusal, which names it, by account and model.
|
||||
//
|
||||
// The refused request is sent again with its oldest images each replaced
|
||||
// by a short text, as many as bring it to the cap, and the account's
|
||||
// later requests to that model are fitted the same way before they are
|
||||
// sent (forwardOnce). The latest user message is kept whole; when its own
|
||||
// images are over the cap, nothing is left out and the refusal goes on.
|
||||
// A request under the cap, and every other vendor's, goes as it came.
|
||||
|
||||
// imageCapWords are Copilot's words for a request over a model's image
|
||||
// cap, with the cap.
|
||||
var imageCapWords = lazyre.New(`(?i)too many images: maximum allowed for model \S+ is (\d+)`)
|
||||
|
||||
// imageOverCap stands where an image over the cap was left out. It goes
|
||||
// to the vendor, so it names neither magpie nor the vendor.
|
||||
const imageOverCap = "[An earlier image was omitted here to keep this request within the model's image limit.]"
|
||||
|
||||
// imageCapped is whether p's refusals of too many images are learned:
|
||||
// Copilot's alone say so.
|
||||
func imageCapped(p provider.Provider) bool {
|
||||
return p.Account != nil && p.Account.Agent == "copilot"
|
||||
}
|
||||
|
||||
// imageCapKey is where the cap of p's model is kept.
|
||||
func imageCapKey(p provider.Provider, body []byte) string {
|
||||
return p.ID + "\x00" + modelOf(body)
|
||||
}
|
||||
|
||||
// withinImageCap is body as it goes to p: its oldest images left out
|
||||
// down to the cap p's model refused more images over, when one is known
|
||||
// and body is over it.
|
||||
func (s *Server) withinImageCap(p provider.Provider, to provider.Protocol, path string, body []byte) []byte {
|
||||
if !imageCapped(p) || countsTokens(path) {
|
||||
return body
|
||||
}
|
||||
n := s.imageCaps.of(imageCapKey(p, body))
|
||||
if n <= 0 {
|
||||
return body
|
||||
}
|
||||
out, left, ok := withoutImagesOver(to, body, n)
|
||||
if ok && left > 0 {
|
||||
log.Printf("%s: the request has more images than the %d %s takes; the %d oldest left out", p.Name, n, modelOf(body), left)
|
||||
return out
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// withoutImagesOver is body with its oldest history images replaced by
|
||||
// imageOverCap, as many as bring it to most images; the rest of it byte
|
||||
// for byte as it came. ok is false, and body as it came, when leaving
|
||||
// every earlier one out doesn't bring it there.
|
||||
func withoutImagesOver(to provider.Protocol, body []byte, most int) (out []byte, left int, ok bool) {
|
||||
over := len(bodyImages(to, body, 0, true, imageOverCap)) - most
|
||||
if over <= 0 {
|
||||
return body, 0, true
|
||||
}
|
||||
imgs := bodyImages(to, body, 0, false, imageOverCap)
|
||||
if len(imgs) < over {
|
||||
return body, 0, false
|
||||
}
|
||||
var b bytes.Buffer
|
||||
b.Grow(len(body))
|
||||
last := 0
|
||||
for _, im := range imgs[:over] {
|
||||
b.Write(body[last:im.at])
|
||||
b.WriteString(im.with)
|
||||
last = im.end
|
||||
}
|
||||
b.Write(body[last:])
|
||||
return b.Bytes(), over, true
|
||||
}
|
||||
|
||||
// refitImageCap is forward's answer to res, Copilot's refusal of body for
|
||||
// too many images: the cap learned, and the request sent again with its
|
||||
// oldest images left out, when that brings it to the cap.
|
||||
func (s *Server) refitImageCap(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) {
|
||||
if res.StatusCode != http.StatusBadRequest || !imageCapped(p) || countsTokens(path) {
|
||||
return res, nil
|
||||
}
|
||||
b := peekError(res)
|
||||
m := imageCapWords.FindStringSubmatch(string(wordsOf(b)))
|
||||
if m == nil {
|
||||
return res, nil
|
||||
}
|
||||
n, err := strconv.Atoi(m[1])
|
||||
if err != nil || n <= 0 {
|
||||
return res, nil
|
||||
}
|
||||
n = s.imageCaps.learn(imageCapKey(p, body), n)
|
||||
if _, left, ok := withoutImagesOver(to, body, n); !ok || left == 0 {
|
||||
return res, nil
|
||||
}
|
||||
log.Printf("%s refused a request to %s for its images (HTTP %d: %s); asking again with no more than %d", p.Name, modelOf(body), res.StatusCode, provider.APIError(b, ""), n)
|
||||
res.Body.Close()
|
||||
// forwardOnce fits it to the cap just learned
|
||||
return s.forwardOnce(ctx, p, to, path, body, in)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// copilotImageCap is Copilot's refusal of a Gemini request over the
|
||||
// model's image cap, as it said it to twelve images (probed live
|
||||
// 2026-11-16, gemini-4-carbon on /chat/completions).
|
||||
const copilotImageCap = "too many images: maximum allowed for model gemini-4-carbon is 10, got 12"
|
||||
|
||||
// capShot is a small PNG's data URL, n in it so each is told apart.
|
||||
func capShot(n int) string {
|
||||
return fmt.Sprintf("data:image/png;base64,iVBORw0KGgoSHOT%02d", n) + strings.Repeat("A", 64)
|
||||
}
|
||||
|
||||
// imageChat is a chat conversation of n earlier turns with an image each,
|
||||
// then the latest user message with latest images of its own.
|
||||
func imageChat(model string, n, latest int) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, `{"model":%q,"stream":false,"messages":[`, model)
|
||||
for i := range n {
|
||||
fmt.Fprintf(&b, `{"role":"user","content":[{"type":"text","text":"look at screen %d"},{"type":"image_url","image_url":{"url":%q}}]},{"role":"assistant","content":"seen %d"},`, i, capShot(i), i)
|
||||
}
|
||||
b.WriteString(`{"role":"user","content":[{"type":"text","text":"the latest ask"}`)
|
||||
for i := range latest {
|
||||
fmt.Fprintf(&b, `,{"type":"image_url","image_url":{"url":%q}}`, capShot(90+i))
|
||||
}
|
||||
b.WriteString(`]}]}`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// overTen refuses a request of more than ten images, as Copilot's
|
||||
// Gemini does, counting the refusals.
|
||||
func overTen(refused *atomic.Int32) func(string, []byte) bool {
|
||||
return func(_ string, b []byte) bool {
|
||||
if strings.Count(string(b), `"type":"image_url"`) > 10 {
|
||||
refused.Add(1)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func postCapChat(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
// A Copilot Gemini conversation of twelve images was refused on every
|
||||
// turn (yuushabu_buyinn on X). Now the turn goes with its two oldest
|
||||
// images left out for a text saying so, the latest user message whole,
|
||||
// and the next turn goes fitted at once: the cap is learned.
|
||||
func TestCopilotGeminiImagesOverCap(t *testing.T) {
|
||||
var sent []string
|
||||
var refused atomic.Int32
|
||||
copilotTurnFake(t, map[string]string{"gemini-4-carbon": `["/chat/completions"]`}, nil,
|
||||
overTen(&refused), copilotImageCap, http.StatusBadRequest, &sent)
|
||||
s := New()
|
||||
rec := postCapChat(t, s, imageChat("copilot/gemini-4-carbon", 11, 1))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("the turn failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(sent) != 1 || refused.Load() != 1 {
|
||||
t.Fatalf("Copilot answered %d requests, refused %d", len(sent), refused.Load())
|
||||
}
|
||||
check := func(got string) {
|
||||
t.Helper()
|
||||
if n := strings.Count(got, `"type":"image_url"`); n != 10 {
|
||||
t.Errorf("sent %d images, not 10", n)
|
||||
}
|
||||
if strings.Contains(got, "SHOT00") || strings.Contains(got, "SHOT01") || !strings.Contains(got, "SHOT02") {
|
||||
t.Error("not the two oldest images left out")
|
||||
}
|
||||
if strings.Count(got, imageOverCap) != 2 {
|
||||
t.Errorf("the left-out images aren't said: %.300s", got)
|
||||
}
|
||||
if !strings.Contains(got, "SHOT90") || !strings.Contains(got, "the latest ask") {
|
||||
t.Error("the latest user message was changed")
|
||||
}
|
||||
for i := range 11 {
|
||||
if !strings.Contains(got, fmt.Sprintf("look at screen %d", i)) {
|
||||
t.Errorf("text %d is gone", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
check(sent[0])
|
||||
|
||||
// the next turn: asked once, fitted before it is sent
|
||||
rec = postCapChat(t, s, imageChat("copilot/gemini-4-carbon", 11, 1))
|
||||
if rec.Code != 200 || len(sent) != 2 || refused.Load() != 1 {
|
||||
t.Fatalf("the next turn: %d, %d answered, %d refused", rec.Code, len(sent), refused.Load())
|
||||
}
|
||||
check(sent[1])
|
||||
}
|
||||
|
||||
// A request at the cap goes byte for byte as it came, the cap known or
|
||||
// not; one whose latest message alone is over it has nothing to leave
|
||||
// out, and Copilot's refusal goes on, asked once.
|
||||
func TestCopilotGeminiImagesUnderCapUntouched(t *testing.T) {
|
||||
var sent []string
|
||||
var refused atomic.Int32
|
||||
copilotTurnFake(t, map[string]string{"gemini-4-carbon": `["/chat/completions"]`}, nil,
|
||||
overTen(&refused), copilotImageCap, http.StatusBadRequest, &sent)
|
||||
s := New()
|
||||
if rec := postCapChat(t, s, imageChat("copilot/gemini-4-carbon", 11, 1)); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
at := imageChat("copilot/gemini-4-carbon", 9, 1)
|
||||
if rec := postCapChat(t, s, at); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := sent[len(sent)-1]; strings.Contains(got, imageOverCap) || strings.Count(got, `"type":"image_url"`) != 10 {
|
||||
t.Fatalf("a request at the cap was changed: %.300s", got)
|
||||
}
|
||||
before := len(sent)
|
||||
rec := postCapChat(t, s, imageChat("copilot/gemini-4-carbon", 1, 12))
|
||||
if rec.Code == 200 || !strings.Contains(rec.Body.String(), "too many images") {
|
||||
t.Fatalf("the refusal didn't go on: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(sent) != before || refused.Load() != 2 {
|
||||
t.Fatalf("the latest user message's images were left out, or it was asked again (%d refused)", refused.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// Another vendor's refusal in the same words teaches nothing: its request
|
||||
// is sent once, as it came, and the refusal goes on.
|
||||
func TestImageCapOtherVendorUntouched(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &capped{proto: provider.Chat, most: 0, status: 400, ctype: "application/json",
|
||||
body: `{"error":{"message":"` + copilotImageCap + `","code":"invalid_request_body"}}`}
|
||||
cappedOn(t, up)
|
||||
body := imageChat("fake/m1", 11, 1)
|
||||
rec := postCapChat(t, New(), body)
|
||||
if rec.Code == 200 {
|
||||
t.Fatalf("refused upstream, yet 200: %s", rec.Body.String())
|
||||
}
|
||||
calls := up.calls()
|
||||
if len(calls) != 1 {
|
||||
t.Fatalf("asked %d times", len(calls))
|
||||
}
|
||||
if strings.Contains(string(calls[0]), imageOverCap) || strings.Count(string(calls[0]), `"type":"image_url"`) != 12 {
|
||||
t.Fatalf("another vendor's request was changed: %.300s", calls[0])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user