gateway: an inline image is counted in the context map by its vendor's rule, from its size (paiven_x on X)
@paiven_x on X: a Codex session (gpt-6.1-terra) of a few hundred small
screenshots sent ~42 MB a request, and the context map showed 764K
tokens, 413K of them images, while Codex's own count was about 371K.
Every inline image was taken at a flat 1600 tokens (imageTokens), so
~258 small screenshots read as 413K where OpenAI counts an 800x500
one at 480.
Now an image's width and height are read from its header alone
(image.DecodeConfig over a streaming base64 decoder: a few KB of a PNG,
a JPEG up to its frame header, a lean body's imageRef through
keptImageOf), and counted by the rule of the protocol's vendor
(prompt_image.go):
- Anthropic: 28 px patches, ceil(w/28)*ceil(h/28), after the reference
resizedSize; 2576 px / 4784 tokens for Claude 4.7 and later, 1568 /
1568 before.
- OpenAI patch models (GPT-5.2 and after, the minis): 32 px patches
times the model's multiplier, in the side and patch budget each
detail sets (low/high/original/auto per model, as the vision guide
lists them).
- OpenAI tile models (gpt-4o, gpt-4.1, o1/o3, gpt-5/5.1): base plus
512 px tiles after 2048 and 768 fitting; low is the base.
A link, a file, a document, an unreadable image and a Gemini request
stay at 1600; the vendor's count still scales them all (calibrate).
The 475K Codex never reached is Codex's own: 95% (its
effective_context_window_percent) of the 500K its bundled catalog gives
gpt-6.1-terra. magpie writes no auto_compact_token_limit for Terra
unless the user set one (Working keeps its own 500K). Codex compares
the usage the vendor reported (~381K), which was under it, so nothing
compacted until /compact. No workaround added.
Tests: TestPromptImageTokensByVendor builds real PNG and JPEG bytes
(image/png, image/jpeg Encode) and checks each vendor's own doc
numbers: Terra 800x500 auto 480, 2880x1800 high 2949, gpt-5.5 low 192,
gpt-4o 1024x1024 high 765 and low 85, Claude 1920x1080 2691 (high
tier) and 1560 (Sonnet 4.5), 3840x2160 4784, a JPEG behind a 40 KB
APP1 330, \/-escaped base64 480. TestPromptImageSizeReadsHeaderOnly
reads 2880x1800 from the first 4 KB of the base64 and falls back to
1600 for a link, a file and undecodable bytes.
Broken by hand: imageTokensOf replaced by the constant, all 10 cases
of TestPromptImageTokensByVendor red at 1600.
Run at this head (e67b0f4fa, rebased on origin/main 352b124b3): gofmt -l
clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... ok
(mica); go test -count=1 -timeout 45m ./... on mote: every package ok except
internal/gateway, whose only --- FAIL is
TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes, red on origin/main without
this change (#7117). A recovered "close of closed channel" from doneHold.serve
(continuation_test.go:781) is in the log, filed as #6690 and #6505; it fails
no test. TestCoreScriptBudget is in that run (no GUI file changed).
Not tried: a real Codex session with hundreds of screenshots; the counts are
checked against OpenAI's and Anthropic's documented examples only.
This commit is contained in:
File diff suppressed because one or more lines are too long
+50
-11
@@ -131,6 +131,17 @@ type promptBuilder struct {
|
||||
// so its bytes count once
|
||||
sent sentSizes
|
||||
again bool
|
||||
// from and model: the protocol the request speaks and the model it
|
||||
// names, whose vendor's rule an inline image is counted by
|
||||
// (imageTokensOf)
|
||||
from provider.Protocol
|
||||
model string
|
||||
}
|
||||
|
||||
// image is what an inline image of src takes, at detail when the request
|
||||
// named one.
|
||||
func (b *promptBuilder) image(detail string, src []byte) int {
|
||||
return imageTokensOf(b.from, b.model, detail, src)
|
||||
}
|
||||
|
||||
// PromptPiece is a stretch of an item's text as the request sent it: a
|
||||
@@ -790,10 +801,12 @@ func (b *promptBuilder) anthropic(body []byte) bool {
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"messages"`
|
||||
Tools []json.RawMessage `json:"tools"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if decodeJSONView(body, &req) != nil {
|
||||
return false
|
||||
}
|
||||
b.from, b.model = provider.Anthropic, req.Model
|
||||
for _, s := range blocksOf(req.System) {
|
||||
if strings.HasPrefix(s.Text, "x-anthropic-billing-header") {
|
||||
b.add(PartSystem, "billing", "", tokensOf(s.Text), txt("system", s.Text))
|
||||
@@ -929,7 +942,7 @@ func (b *promptBuilder) anthropicBlock(role string, x rawBlock) {
|
||||
for _, c := range blocksOf(x.Content) {
|
||||
switch c.Type {
|
||||
case "image", "document":
|
||||
b.add(PartFiles, c.Type, "image", imageTokens, imgPiece(c.Source))
|
||||
b.add(PartFiles, c.Type, "image", b.sourceTokens(c.Type, c.Source), imgPiece(c.Source))
|
||||
default:
|
||||
n += tokensOf(c.Text)
|
||||
texts = append(texts, c.Text)
|
||||
@@ -946,7 +959,7 @@ func (b *promptBuilder) anthropicBlock(role string, x rawBlock) {
|
||||
b.add(PartFiles, "document", "image", rawTokens(x.Source), rawPiece("", "", x.Source))
|
||||
return
|
||||
}
|
||||
b.add(PartFiles, x.Type, "image", imageTokens, imgPiece(x.Source))
|
||||
b.add(PartFiles, x.Type, "image", b.sourceTokens(x.Type, x.Source), imgPiece(x.Source))
|
||||
default:
|
||||
b.chat(tokensOf(x.Text), txt(role, x.Text))
|
||||
}
|
||||
@@ -960,10 +973,12 @@ func (b *promptBuilder) responses(body []byte) bool {
|
||||
Input json.RawMessage `json:"input"`
|
||||
Tools []json.RawMessage `json:"tools"`
|
||||
Previous string `json:"previous_response_id"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if decodeJSONView(body, &req) != nil {
|
||||
return false
|
||||
}
|
||||
b.from, b.model = provider.Responses, req.Model
|
||||
b.held = req.Previous != ""
|
||||
var ins string
|
||||
if decodeJSONView(req.Instructions, &ins) == nil && ins != "" {
|
||||
@@ -1067,7 +1082,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) {
|
||||
}
|
||||
for _, p := range parts {
|
||||
if p.image {
|
||||
b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src))
|
||||
b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src))
|
||||
continue
|
||||
}
|
||||
b.userText(p.text)
|
||||
@@ -1111,7 +1126,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) {
|
||||
var texts []string
|
||||
for _, p := range responsesContent(it.Output) {
|
||||
if p.image {
|
||||
b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src))
|
||||
b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src))
|
||||
continue
|
||||
}
|
||||
n += tokensOf(p.text)
|
||||
@@ -1133,9 +1148,29 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) {
|
||||
}
|
||||
|
||||
type rPart struct {
|
||||
text string
|
||||
image bool
|
||||
src json.RawMessage // an image's image_url
|
||||
text string
|
||||
image bool
|
||||
src json.RawMessage // an image's image_url
|
||||
detail string // a Responses image's detail, beside its image_url
|
||||
file bool // an input_file: a document, not a picture
|
||||
}
|
||||
|
||||
// partImage is what a Responses or Chat image part takes; a file at the
|
||||
// estimate for a picture.
|
||||
func (b *promptBuilder) partImage(p rPart) int {
|
||||
if p.file {
|
||||
return imageTokens
|
||||
}
|
||||
return b.image(p.detail, p.src)
|
||||
}
|
||||
|
||||
// sourceTokens is what an Anthropic image or document block takes: a
|
||||
// document at the estimate for a picture.
|
||||
func (b *promptBuilder) sourceTokens(typ string, src []byte) int {
|
||||
if typ != "image" {
|
||||
return imageTokens
|
||||
}
|
||||
return b.image("", src)
|
||||
}
|
||||
|
||||
func responsesContent(c json.RawMessage) []rPart {
|
||||
@@ -1147,11 +1182,13 @@ func responsesContent(c json.RawMessage) []rPart {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
ImageURL json.RawMessage `json:"image_url"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
_ = decodeJSONView(c, &ps)
|
||||
out := make([]rPart, 0, len(ps))
|
||||
for _, p := range ps {
|
||||
out = append(out, rPart{text: p.Text, image: p.Type == "input_image" || p.Type == "input_file" || p.Type == "image_url", src: p.ImageURL})
|
||||
out = append(out, rPart{text: p.Text, image: p.Type == "input_image" || p.Type == "input_file" || p.Type == "image_url", src: p.ImageURL,
|
||||
detail: p.Detail, file: p.Type == "input_file"})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1174,10 +1211,12 @@ func (b *promptBuilder) chatCompletions(body []byte) bool {
|
||||
} `json:"tool_calls"`
|
||||
} `json:"messages"`
|
||||
Tools []json.RawMessage `json:"tools"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if decodeJSONView(body, &req) != nil {
|
||||
return false
|
||||
}
|
||||
b.from, b.model = provider.Chat, req.Model
|
||||
for _, t := range req.Tools {
|
||||
b.responsesTool(t)
|
||||
}
|
||||
@@ -1194,7 +1233,7 @@ func (b *promptBuilder) chatCompletions(body []byte) bool {
|
||||
}
|
||||
for _, p := range parts {
|
||||
if p.image {
|
||||
b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src))
|
||||
b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src))
|
||||
continue
|
||||
}
|
||||
b.userText(p.text)
|
||||
@@ -1204,7 +1243,7 @@ func (b *promptBuilder) chatCompletions(body []byte) bool {
|
||||
var texts []string
|
||||
for _, p := range parts {
|
||||
if p.image {
|
||||
b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src))
|
||||
b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src))
|
||||
continue
|
||||
}
|
||||
n += tokensOf(p.text)
|
||||
@@ -1302,7 +1341,7 @@ func (b *promptBuilder) gemini(body []byte) bool {
|
||||
}
|
||||
b.result(id, rawTokens(p.FunctionResponse.Response), rawPiece("result", "", p.FunctionResponse.Response))
|
||||
case len(p.InlineData) > 0 || len(p.FileData) > 0:
|
||||
b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.InlineData))
|
||||
b.add(PartFiles, "image", "image", b.image("", p.InlineData), imgPiece(p.InlineData))
|
||||
case c.Role == "model":
|
||||
role := "assistant"
|
||||
if p.Thought {
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
package gateway
|
||||
|
||||
// What an image a request sends inline takes of the model's context, by
|
||||
// the rule of the vendor whose protocol the request speaks, from the
|
||||
// image's own size. The size is read from the image's header alone, the
|
||||
// base64 decoded as a stream as far as the format needs (a few KB of a
|
||||
// PNG, a JPEG up to its frame header), never the picture, so a request
|
||||
// carrying hundreds of screenshots costs a few KB read for each.
|
||||
//
|
||||
// Every image used to be taken at 1600 tokens (imageTokens). A Codex
|
||||
// session of a few hundred small screenshots then showed 413K of images in
|
||||
// a 764K prompt that OpenAI counted at about 371K (@paiven_x on X): small
|
||||
// pictures cost OpenAI a few hundred tokens each. An image whose size
|
||||
// can't be read (a link, a file id, a document) is still taken at
|
||||
// imageTokens, and the vendor's count, once it answers, scales them all
|
||||
// (calibrate).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
_ "image/gif" // DecodeConfig of a GIF
|
||||
_ "image/jpeg" // of a JPEG
|
||||
_ "image/png" // of a PNG
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
_ "golang.org/x/image/webp" // of a WebP
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// imageTokensOf is what an inline image takes of the context: src as the
|
||||
// request sent it (an Anthropic source, a Responses image_url, a Chat
|
||||
// image_url object, Gemini's inlineData), at detail when the request
|
||||
// named one, to model, by the rule of the vendor of protocol from.
|
||||
// imageTokens when its size can't be read.
|
||||
func imageTokensOf(from provider.Protocol, model, detail string, src []byte) int {
|
||||
w, h, ok := inlineImageSize(src)
|
||||
if !ok {
|
||||
return imageTokens
|
||||
}
|
||||
if detail == "" {
|
||||
detail = jsonField(src, "detail")
|
||||
}
|
||||
switch from {
|
||||
case provider.Anthropic:
|
||||
return claudeImageTokens(w, h, model)
|
||||
case provider.Responses, provider.Chat:
|
||||
return openAIImageTokens(w, h, detail, model)
|
||||
}
|
||||
return imageTokens
|
||||
}
|
||||
|
||||
// inlineImageSize is an inline image's width and height, read from its header.
|
||||
func inlineImageSize(src []byte) (w, h int, ok bool) {
|
||||
b64 := imageBase64(src)
|
||||
if len(b64) == 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
var r io.Reader = bytes.NewReader(b64)
|
||||
if bytes.IndexByte(b64, '\\') >= 0 {
|
||||
r = unescaped{r} // a JSON encoder's \/
|
||||
}
|
||||
if ref, isRef := bytes.CutPrefix(b64, []byte(imageRef)); isRef {
|
||||
// a picture a lean body kept apart (leanImages)
|
||||
data, found := keptImageOf(string(ref))
|
||||
if !found {
|
||||
return 0, 0, false
|
||||
}
|
||||
r = strings.NewReader(data)
|
||||
}
|
||||
cfg, _, err := image.DecodeConfig(base64.NewDecoder(base64.StdEncoding, r))
|
||||
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
return cfg.Width, cfg.Height, true
|
||||
}
|
||||
|
||||
// imageBase64 is the base64 of an inline image's source, where it sits in
|
||||
// the source's JSON, not copied: after a data: URL's comma, else Anthropic's
|
||||
// and Gemini's "data" string. nil for a link or a file.
|
||||
func imageBase64(src []byte) []byte {
|
||||
var s []byte
|
||||
if i := bytes.Index(src, []byte(";base64,")); i >= 0 {
|
||||
s = src[i+len(";base64,"):]
|
||||
} else if i := bytes.Index(src, []byte(`"data"`)); i >= 0 {
|
||||
s = bytes.TrimLeft(src[i+len(`"data"`):], " \t\r\n:")
|
||||
if len(s) == 0 || s[0] != '"' {
|
||||
return nil
|
||||
}
|
||||
s = s[1:]
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
if end := bytes.IndexByte(s, '"'); end >= 0 {
|
||||
s = s[:end]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// unescaped reads a JSON string's bytes without its backslashes, which
|
||||
// base64 has none of.
|
||||
type unescaped struct{ r io.Reader }
|
||||
|
||||
func (u unescaped) Read(p []byte) (int, error) {
|
||||
n, err := u.r.Read(p)
|
||||
k := 0
|
||||
for _, c := range p[:n] {
|
||||
if c != '\\' {
|
||||
p[k] = c
|
||||
k++
|
||||
}
|
||||
}
|
||||
return k, err
|
||||
}
|
||||
|
||||
// jsonField is a short string field of a small JSON object, "" when it
|
||||
// has none: a Chat image_url's detail, read past its url.
|
||||
func jsonField(obj []byte, key string) string {
|
||||
if len(obj) == 0 || obj[0] != '{' {
|
||||
return ""
|
||||
}
|
||||
q := []byte(`"` + key + `"`)
|
||||
i := bytes.LastIndex(obj, q)
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
s := bytes.TrimLeft(obj[i+len(q):], " \t\r\n:")
|
||||
if len(s) < 2 || s[0] != '"' {
|
||||
return ""
|
||||
}
|
||||
end := bytes.IndexByte(s[1:], '"')
|
||||
if end < 0 || end > 16 {
|
||||
return ""
|
||||
}
|
||||
return string(s[1 : 1+end])
|
||||
}
|
||||
|
||||
// modelSlug is a model id as its vendor names it: lower case, without
|
||||
// magpie's provider prefix.
|
||||
func modelSlug(model string) string {
|
||||
m := strings.ToLower(model)
|
||||
if i := strings.LastIndexByte(m, '/'); i >= 0 {
|
||||
m = m[i+1:]
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// --- Anthropic ---
|
||||
|
||||
// claudeImageTokens is Anthropic's count of a w×h image: a token for each
|
||||
// 28 px patch, ⌈w/28⌉×⌈h/28⌉, once the image is scaled to the largest
|
||||
// size that fits the model's tier (platform.claude.com, Vision and
|
||||
// "How Claude resizes and pads images"): Claude 4.7 and later 2576 px
|
||||
// a side and 4784 tokens, the models before 1568 and 1568.
|
||||
func claudeImageTokens(w, h int, model string) int {
|
||||
edge, most := 2576, 4784
|
||||
if claudeStandardTier(model) {
|
||||
edge, most = 1568, 1568
|
||||
}
|
||||
w, h = claudeResized(w, h, edge, most)
|
||||
return claudePatches(w, h)
|
||||
}
|
||||
|
||||
func claudePatches(w, h int) int { return ((w + 27) / 28) * ((h + 27) / 28) }
|
||||
|
||||
// claudeResized is Anthropic's reference resizedSize: the largest
|
||||
// aspect-kept size whose padded sides fit edge and whose patches fit most.
|
||||
func claudeResized(w, h, edge, most int) (int, int) {
|
||||
fits := func(w, h int) bool {
|
||||
return (w+27)/28*28 <= edge && (h+27)/28*28 <= edge && claudePatches(w, h) <= most
|
||||
}
|
||||
if fits(w, h) {
|
||||
return w, h
|
||||
}
|
||||
if h > w {
|
||||
rh, rw := claudeResized(h, w, edge, most)
|
||||
return rw, rh
|
||||
}
|
||||
ratio := float64(w) / float64(h)
|
||||
short := func(long int) int { return max(int(math.RoundToEven(float64(long)/ratio)), 1) }
|
||||
lo, hi := 1, w
|
||||
for lo+1 < hi {
|
||||
mid := (lo + hi) / 2
|
||||
if fits(mid, short(mid)) {
|
||||
lo = mid
|
||||
} else {
|
||||
hi = mid
|
||||
}
|
||||
}
|
||||
return lo, short(lo)
|
||||
}
|
||||
|
||||
// claudeStandardTier: a Claude model before 4.7 (Opus 4.6, Sonnet 4.5,
|
||||
// Haiku 4.5, the 3s). Any other, a model magpie doesn't know among them,
|
||||
// is taken at the high-resolution tier of the models Claude Code runs now.
|
||||
func claudeStandardTier(model string) bool {
|
||||
m := modelSlug(model)
|
||||
if !strings.HasPrefix(m, "claude-") {
|
||||
return false
|
||||
}
|
||||
// claude-opus-4-6, claude-sonnet-4-5-20250929, claude-3-5-sonnet-…
|
||||
var nums []int
|
||||
for _, f := range strings.FieldsFunc(m, func(r rune) bool { return r == '-' || r == '.' || r == '[' }) {
|
||||
if n, err := strconv.Atoi(f); err == nil && len(f) <= 2 {
|
||||
nums = append(nums, n)
|
||||
}
|
||||
}
|
||||
if len(nums) == 0 {
|
||||
return false
|
||||
}
|
||||
major, minor := nums[0], 0
|
||||
if len(nums) > 1 {
|
||||
minor = nums[1]
|
||||
}
|
||||
return major < 4 || major == 4 && minor < 7
|
||||
}
|
||||
|
||||
// --- OpenAI ---
|
||||
|
||||
// openAIImageTokens is OpenAI's count of a w×h image at detail on model
|
||||
// (developers.openai.com, Images and vision: "Calculating costs"). The
|
||||
// models before GPT-5.2 count 512 px tiles; the rest 32 px patches, times
|
||||
// the model's multiplier, in limits each detail sets.
|
||||
func openAIImageTokens(w, h int, detail, model string) int {
|
||||
m := modelSlug(model)
|
||||
if base, tile, ok := openAITiles(m); ok {
|
||||
if detail == "low" {
|
||||
return base
|
||||
}
|
||||
// fit 2048×2048, then the shortest side to 768, as tiles of 512
|
||||
fw, fh := fitSide(w, h, 2048)
|
||||
if s := min(fw, fh); s > 768 {
|
||||
r := 768 / float64(s)
|
||||
fw, fh = int(float64(fw)*r), int(float64(fh)*r)
|
||||
if fw < fh {
|
||||
fw = 768
|
||||
} else {
|
||||
fh = 768
|
||||
}
|
||||
}
|
||||
return base + tile*((fw+511)/512)*((fh+511)/512)
|
||||
}
|
||||
side, budget := openAIPatchLimits(m, detail)
|
||||
pw, ph := fitSide(w, h, side)
|
||||
if budget > 0 && openAIPatches(pw, ph) > budget {
|
||||
fw, fh := float64(pw), float64(ph)
|
||||
s := math.Sqrt(32 * 32 * float64(budget) / (fw * fh))
|
||||
s *= min(math.Floor(fw*s/32)/(fw*s/32), math.Floor(fh*s/32)/(fh*s/32))
|
||||
pw, ph = max(int(fw*s), 1), max(int(fh*s), 1)
|
||||
}
|
||||
return int(math.Ceil(float64(openAIPatches(pw, ph)) * openAIMultiplier(m)))
|
||||
}
|
||||
|
||||
func openAIPatches(w, h int) int { return ((w + 31) / 32) * ((h + 31) / 32) }
|
||||
|
||||
// fitSide scales w×h to fit side×side, never up.
|
||||
func fitSide(w, h, side int) (int, int) {
|
||||
if side <= 0 || w <= side && h <= side {
|
||||
return w, h
|
||||
}
|
||||
r := float64(side) / float64(max(w, h))
|
||||
return max(int(math.Round(float64(w)*r)), 1), max(int(math.Round(float64(h)*r)), 1)
|
||||
}
|
||||
|
||||
// openAITiles: the base and per-tile tokens of a model that counts tiles.
|
||||
func openAITiles(m string) (base, tile int, ok bool) {
|
||||
switch {
|
||||
case strings.HasPrefix(m, "gpt-4o-mini"):
|
||||
return 2833, 5667, true
|
||||
case strings.HasPrefix(m, "gpt-4o"), m == "gpt-4.1" || strings.HasPrefix(m, "gpt-4.1-20"):
|
||||
return 85, 170, true
|
||||
case m == "o1" || strings.HasPrefix(m, "o1-"), m == "o3" || strings.HasPrefix(m, "o3-pro") || strings.HasPrefix(m, "o3-20"):
|
||||
return 75, 150, true
|
||||
case strings.HasPrefix(m, "gpt-5.1"),
|
||||
strings.HasPrefix(m, "gpt-5") && !strings.HasPrefix(m, "gpt-5.") && !strings.HasPrefix(m, "gpt-5-mini") && !strings.HasPrefix(m, "gpt-5-nano"):
|
||||
return 70, 140, true
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
// openAIMultiplier is a patch model's multiplier: 1.2 for GPT-5.2 and
|
||||
// after, and for a model OpenAI doesn't list.
|
||||
func openAIMultiplier(m string) float64 {
|
||||
switch {
|
||||
case strings.HasPrefix(m, "gpt-5-nano"):
|
||||
return 1.5
|
||||
case strings.HasPrefix(m, "gpt-4.1-mini"):
|
||||
return 1.62
|
||||
case strings.HasPrefix(m, "gpt-4.1-nano"):
|
||||
return 2.46
|
||||
case strings.HasPrefix(m, "o4-mini"):
|
||||
return 1.72
|
||||
}
|
||||
return 1.2
|
||||
}
|
||||
|
||||
// openAIPatchLimits is the longest side and the patch budget (0: none) a
|
||||
// patch model holds an image to at detail; auto is the model's default.
|
||||
func openAIPatchLimits(m, detail string) (side, budget int) {
|
||||
switch {
|
||||
case strings.HasPrefix(m, "gpt-5.2"), strings.HasPrefix(m, "gpt-4.1-"), strings.HasPrefix(m, "gpt-5-mini"),
|
||||
strings.HasPrefix(m, "gpt-5-nano"), strings.HasPrefix(m, "o4-mini"):
|
||||
return 2048, 6144 // every detail alike
|
||||
case strings.HasPrefix(m, "gpt-5.4"), strings.HasPrefix(m, "gpt-5.3"):
|
||||
switch detail {
|
||||
case "low":
|
||||
return 2048, 6144
|
||||
case "original":
|
||||
return 6000, 10000
|
||||
}
|
||||
return 2048, 2500 // high, auto
|
||||
}
|
||||
// GPT-5.5 and after, and models OpenAI doesn't list: auto is original
|
||||
switch detail {
|
||||
case "low":
|
||||
return 512, 0
|
||||
case "high":
|
||||
return 2048, 2500
|
||||
}
|
||||
if strings.HasPrefix(m, "gpt-5.5") {
|
||||
return 6000, 10000
|
||||
}
|
||||
return 65535, 0
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// pngB64 is a real PNG of w×h, as base64.
|
||||
func pngB64(t *testing.T, w, h int) string {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for x := 0; x < w; x += 7 {
|
||||
img.Set(x, x%h, color.RGBA{R: byte(x), G: 90, B: 200, A: 255})
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
// jpegB64 is a real JPEG of w×h with a 40 KB APP1 segment (EXIF's place)
|
||||
// before its frame header, as a camera's or a phone's has.
|
||||
func jpegB64(t *testing.T, w, h int) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, image.NewGray(image.Rect(0, 0, w, h)), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := buf.Bytes()
|
||||
app := make([]byte, 40000)
|
||||
seg := append([]byte{0xFF, 0xE1, byte((len(app) + 2) >> 8), byte(len(app) + 2)}, app...)
|
||||
out := append(append(append([]byte{}, raw[:2]...), seg...), raw[2:]...)
|
||||
return base64.StdEncoding.EncodeToString(out)
|
||||
}
|
||||
|
||||
// An inline image is counted by the vendor's rule from its own size, not
|
||||
// at 1600 whatever it is: a Codex session of a few hundred small
|
||||
// screenshots showed 413K of images in a prompt OpenAI counted at about
|
||||
// 371K in all (@paiven_x on X). The numbers are the vendors' own docs'.
|
||||
func TestPromptImageTokensByVendor(t *testing.T) {
|
||||
small, shot, hd := pngB64(t, 800, 500), pngB64(t, 2880, 1800), pngB64(t, 1920, 1080)
|
||||
resp := func(model, detail, b64 string) string {
|
||||
d := ""
|
||||
if detail != "" {
|
||||
d = `,"detail":"` + detail + `"`
|
||||
}
|
||||
return `{"model":"` + model + `","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"look"},{"type":"input_image","image_url":"data:image/png;base64,` + b64 + `"` + d + `}]}]}`
|
||||
}
|
||||
chat := func(model, detail, b64 string) string {
|
||||
return `{"model":"` + model + `","messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,` + b64 + `","detail":"` + detail + `"}}]}]}`
|
||||
}
|
||||
anth := func(model, b64 string) string {
|
||||
return `{"model":"` + model + `","messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + b64 + `"}}]}]}`
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
from provider.Protocol
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
// 32 px patches, 25×16, times 1.2; auto is original on GPT-6
|
||||
{"codex small screenshot", provider.Responses, resp("codex/gpt-6.1-terra", "", small), 480},
|
||||
// high: 2048 a side, then the 2500-patch budget: 1996×1248, 63×39 patches
|
||||
{"retina at high", provider.Responses, resp("gpt-6.1-terra", "high", shot), 2949},
|
||||
// low on GPT-5.5 and after: fits 512×512, 16×10 patches
|
||||
{"low", provider.Responses, resp("gpt-5.5", "low", small), 192},
|
||||
// tiles: 1024² is 768² at high, 4 tiles of 170 and 85 (OpenAI's example)
|
||||
{"gpt-4o tiles", provider.Chat, chat("gpt-4o", "high", pngB64(t, 1024, 1024)), 765},
|
||||
{"gpt-4o low", provider.Chat, chat("gpt-4o", "low", shot), 85},
|
||||
// Anthropic's table: 1920×1080 is 2691 on the high-resolution tier,
|
||||
// 1456×819 and 1560 on the standard
|
||||
{"claude high tier", provider.Anthropic, anth("claude-opus-5-5", hd), 2691},
|
||||
{"claude standard tier", provider.Anthropic, anth("anthropic/claude-sonnet-4-5-20250929", hd), 1560},
|
||||
// 3840×2160: 2576×1449, 4784
|
||||
{"claude 4k", provider.Anthropic, anth("claude-opus-4-7", pngB64(t, 3840, 2160)), 4784},
|
||||
// a JPEG's frame header behind 40 KB of EXIF is still read: 600×400
|
||||
// on the standard tier is 22×15
|
||||
{"jpeg behind exif", provider.Anthropic, strings.Replace(anth("claude-haiku-4-5", jpegB64(t, 600, 400)), "image/png", "image/jpeg", 1), 330},
|
||||
// a JSON encoder's \/ in the base64
|
||||
{"escaped slashes", provider.Responses, strings.ReplaceAll(resp("gpt-6.1-terra", "", small), "/", `\/`), 480},
|
||||
}
|
||||
for _, c := range cases {
|
||||
p := promptOf(c.from, []byte(c.body))
|
||||
if p == nil {
|
||||
t.Fatalf("%s: no prompt", c.name)
|
||||
}
|
||||
it, ok := itemOf(p, PartFiles, "image")
|
||||
if !ok || it.Tokens != c.want {
|
||||
t.Errorf("%s: image %+v, want %d tokens", c.name, it, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only the image's header is read: its size comes out of the base64 of a
|
||||
// PNG's first few KB, the rest of it never decoded, so hundreds of
|
||||
// screenshots in one Codex request cost a few KB read each.
|
||||
func TestPromptImageSizeReadsHeaderOnly(t *testing.T) {
|
||||
b64 := pngB64(t, 2880, 1800)
|
||||
src := []byte(`"data:image/png;base64,` + b64[:4096] + `"`)
|
||||
w, h, ok := inlineImageSize(src)
|
||||
if !ok || w != 2880 || h != 1800 {
|
||||
t.Fatalf("size %d×%d %v", w, h, ok)
|
||||
}
|
||||
// a link, a file, bytes that aren't an image: the estimate for a picture
|
||||
for _, s := range []string{`"https://example.com/a.png"`, `{"type":"url","url":"https://x/a.png"}`, `"data:image/png;base64,AAAA"`} {
|
||||
if n := imageTokensOf(provider.Responses, "gpt-6.1-terra", "", []byte(s)); n != imageTokens {
|
||||
t.Fatalf("%s: %d", s, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user