Yuu_jiang_ on X (#6849): 100milionseek and Coarena take at most 8 images a request, counted over the whole conversation, tool results included, and every turn after the ninth screenshot failed with no way on but /clear. ID-VerNe's max-images (the commit before) set one number from the CLI. This builds on it: - The cap is per provider, and optionally per model: max-images=8, or max-images=8,gemini-3-flash=10. The exact model is looked up first, then its upstream name, then "*" for all. The provider's cap moves with a model's local id like the other per-model limits. - 100milionseek's "At most 8 images per request (MAX_IMAGES)." and Coarena's "A request may carry at most 8 images." are learned as Copilot's words are, by provider and model, so the first refusal is the last. A user's own number is fitted before any refusal; a learned one that is smaller still lowers it. - Images are counted everywhere, a tool_result's too; the oldest are left out first and the latest user turn keeps its own. Only the request sent changes; session files are not touched. A request with no cap, or within it, goes out byte for byte as it came. - The provider editor's Advanced (folded unless set) has Images per request under Max output, in maximages.js, imported as that field is drawn, in every language. A GUI save keeps the value when the field isn't drawn. An editor opened and closed is not dirty (the draft takes the value only when typed), and the import, like keyrates.js's, draws nothing once the editor has closed: before that, a quick close threw "Cannot read properties of null (reading 'maxImages')" and ('keyPriceRates'), which add-sheet and key-box-once caught. - Budgets: app.js and the core +354, said in core_budget_test.go. What was run: - go test -count=1 -timeout 45m ./... on mote at618bfc1a9+ these two commits: 102 packages ok; internal/tui red on TestEveryWordHasZh ("subagent pool", red on main, fixed by6fbc24a05). After rebasing on origin/mainc9e8422fa: internal/gui (budgets), tui, agent, testenv, gateway and provider: all ok. gofmt clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... ok on mica. - At618bfc1a9+ these commits, on mote: provider-max-images 60/0, add-sheet 6/0, add-button 6/0, key-box-once 20/0, nokey-editor 4/0, provider-base-api 4/0, add-sheet-custom 32/0, kimi-subagent-pool 20/0, sync-signins-except 20/0; old-webkit 4/2 (#6030 headerpresets, #5919), i18n-keys 3/1 (#6877), provider-max-output 4/20 (#6209), editor-hints 30/10 (the same at origin/main, in #6934). - The whole GUI suite (1569 files, chromium + webkit, every language) on mote at the pre-fix head under another session's suite: 153 files red. Each red file rerun at the fixed head and at origin/mainad585ccd6on mica (and mote for the close ones). Red at head only: add-button (Escape showed the discard confirm: the dirty draft, fixed), add-sheet and key-box-once (the null draft above, fixed); now 3/0, 6/0, 20/0, provider-max-images 60/0. Every other red file is red the same at origin/main, the same subtests: filed with its numbers as #6934 (the #6782 class). i18n-keys' ", with an image" is #6877, old-webkit #6030/#5919, provider-max-output #6209. Broken by hand (each red, then put back): the relay words left out (TestImageCapLearnedFromRelayWords), per-model lookup by upstream name gone (TestMaxImagesOnAModelListedByItsOwnID), a copy made when nothing applies (TestImageCapNoneIsTheSameBytes), the learned cap over the user's (TestMaxImagesStandsOverTheLearnedCap), the GUI save dropping it (TestProviderSaveKeepsMaxImages), the CLI's empty value (TestProviderSetMaxImages), the cap not moving with a local id, the JS parse without its 1000 limit and the field not unfolding Advanced (provider-max-images), and the draft written on open (provider-max- images' Escape check, 20 red). Not tried: no real 100milionseek or Coarena account (the words are the reporter's literal ones); no GUI run on Windows or Linux; the suite's GUI half ran under load, so many reds are shared timeouts. Co-authored-by: ID-VerNe <yuu_seeing@foxmail.com>
213 lines
7.5 KiB
Go
213 lines
7.5 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/yetone/magpie/internal/lazyre"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// 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.
|
|
//
|
|
// Other vendors hold a request to a cap of their own and say so in their
|
|
// own words (#6849): 100milionseek "At most 8 images per request
|
|
// (MAX_IMAGES)." and Coarena "A request may carry at most 8 images.", the
|
|
// vendor's name first. Those are learned the same way, by provider and
|
|
// model, whatever id the user gave the provider: the words name the
|
|
// vendor. A cap the user sets on a provider (Provider.MaxImages, for all
|
|
// its models or for one) needs no refusal to know, and is fitted before
|
|
// the first request is sent; a refusal naming a smaller one still lowers
|
|
// it, since a request over it can't be served.
|
|
//
|
|
// A request under the cap, and one to a provider with none set or
|
|
// learned, goes as it came.
|
|
|
|
// imageCapRefusal is a vendor's words for a request over a model's image
|
|
// cap, with the cap; copilot is whether only a Copilot account's are
|
|
// read, its words naming no vendor.
|
|
type imageCapRefusal struct {
|
|
words *lazyre.RE
|
|
copilot bool
|
|
}
|
|
|
|
// imageCapWords are the refusals a cap is learned from, as each vendor
|
|
// says them (the bytes are quoted above).
|
|
var imageCapWords = []imageCapRefusal{
|
|
{lazyre.New(`(?i)too many images: maximum allowed for model \S+ is (\d+)`), true},
|
|
{lazyre.New(`100milionseek: At most (\d+) images per request \(MAX_IMAGES\)`), false},
|
|
{lazyre.New(`Coarena: A request may carry at most (\d+) images\.`), false},
|
|
}
|
|
|
|
// 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.]"
|
|
|
|
// copilotAccount is whether p is a Copilot account, whose refusal of too
|
|
// many images names no vendor.
|
|
func copilotAccount(p provider.Provider) bool {
|
|
return p.Account != nil && p.Account.Agent == "copilot"
|
|
}
|
|
|
|
// learnedImageCap is the cap res's body b names for a request over it, as
|
|
// p's vendor words it, 0 for none.
|
|
func learnedImageCap(p provider.Provider, b []byte) int {
|
|
words := string(wordsOf(b))
|
|
for _, r := range imageCapWords {
|
|
if r.copilot && !copilotAccount(p) {
|
|
continue
|
|
}
|
|
if m := r.words.FindStringSubmatch(words); m != nil {
|
|
if n, err := strconv.Atoi(m[1]); err == nil && n > 0 {
|
|
return n
|
|
}
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// under is whether a cap is kept under a key that starts with prefix.
|
|
func (c *bodyCaps) under(prefix string) bool {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
for k := range c.m {
|
|
if strings.HasPrefix(k, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// userImageCap is the cap the user set on p for the model body asks
|
|
// for, 0 for none. The body names the vendor's id for it, and the user
|
|
// set it by the id magpie lists it under, which a model's own upstream
|
|
// name (SetModelID) can tell apart.
|
|
func userImageCap(p provider.Provider, body []byte) int {
|
|
if len(p.MaxImages) == 0 {
|
|
return 0
|
|
}
|
|
model := modelOf(body)
|
|
if n := p.MaxImages[model]; n > 0 {
|
|
return n
|
|
}
|
|
wires := settings.Shared().Wires()
|
|
for id, n := range p.MaxImages {
|
|
if id != "*" && n > 0 && provider.UpstreamNameIn(wires, p.ID, id) == model {
|
|
return n
|
|
}
|
|
}
|
|
return p.MaxImages["*"]
|
|
}
|
|
|
|
// imageCap is the most images one request to p may carry: the smaller of
|
|
// the user's own MaxImages and the cap a refusal taught that model, 0
|
|
// for neither.
|
|
func (s *Server) imageCap(p provider.Provider, body []byte) int {
|
|
if len(p.MaxImages) == 0 && !s.imageCaps.under(p.ID+"\x00") {
|
|
// most requests: nothing read of the body
|
|
return 0
|
|
}
|
|
own, learned := userImageCap(p, body), s.imageCaps.of(imageCapKey(p, body))
|
|
if own > 0 && (learned <= 0 || own < learned) {
|
|
return own
|
|
}
|
|
return learned
|
|
}
|
|
|
|
// withinImageCap is body as it goes to p: its oldest images left out down
|
|
// to the cap p's model takes, 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 countsTokens(path) {
|
|
return body
|
|
}
|
|
n := s.imageCap(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, a refusal of body for too
|
|
// many images that names the cap (imageCapWords): the cap learned, and
|
|
// the request sent again with its oldest images left out, when that
|
|
// brings it under the cap it was sent at.
|
|
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 || countsTokens(path) {
|
|
return res, nil
|
|
}
|
|
b := peekError(res)
|
|
n := learnedImageCap(p, b)
|
|
if n <= 0 {
|
|
return res, nil
|
|
}
|
|
was := s.imageCap(p, body)
|
|
s.imageCaps.learn(imageCapKey(p, body), n)
|
|
if n = s.imageCap(p, body); n == was {
|
|
// sent fitted to it already: the refusal is about the latest
|
|
// message's own images, and asking again changes nothing
|
|
return res, nil
|
|
}
|
|
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)
|
|
}
|