gateway: DeepSeek's own API gets an agent's images once, by file id, not on every turn (#5407)

DeepSeek's API is stateless, so every turn re-sent every inline image in
the history. Now, on api.deepseek.com only (never a relay or another
base), for a model with "flash" in its name (deepseek-flash sees images;
deepseek-v4-pro reads them as "[Unsupported Image]"), each base64 data:
image goes up once through POST /files (purpose=user_data, expires_after
a day) with the candidate's own key, and later turns name it by file id:
- Chat: {"type":"file","file_id":…} (flat, as DeepSeek's vision guide);
- Responses: input_image with file_id in place of image_url;
- Anthropic: source {"type":"file","file_id":…} plus anthropic-beta
  files-api-2025-04-14.
Shapes checked against api-docs.deepseek.com files_api, vision,
responses_api and anthropic_api. The Anthropic guide names the "file"
source type and the beta; the field name file_id is Anthropic's Files
API's, which DeepSeek says it follows. Not confirmed with a real call.

Ids are kept per key hash + image sha256 in deepseek-files.json beside
providers.json (temp+rename, unparseable file moved to .bad), reuploaded
with under an hour left. One upload per image and key however many
requests want it; a request waits at most 8s for its uploads, and what
isn't up goes inline this turn. A failed upload leaves the image inline
and rests that key's uploads for 10 minutes. A 4xx naming a file-api id
or a missing/expired file forgets the ids, uploads again and asks once
more; refused again, the request goes inline. detail:low stays inline.
`magpie provider set <id> image-files=off` turns it off (kept on GUI
save). Doc: docs/subsystems/gateway-routing.md.

Run (mote, at this tree on 498b6419f):
- go test -run 'DeepSeek|DsFileGone' ./internal/gateway: ok; -race -count=3 ok
- go test ./internal/gateway ./internal/provider ./internal/cli: ok
- go test ./internal/gui: TestMainWindowCorners/macOS_26_SDK red, the
  known macOS 27 red on mote (#3949); nothing in gui's code path changed
  but a kept field on save
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... and GOOS=linux -tags nogui ok

Broken by hand, each red: host check removed (InlineElsewhere), switch
ignored (ImageFilesOff), singleflight off (FilesOneUpload), breaker off
(UploadFailsInline), key left out of the cache key (FilesPerKey and
others), beta not added (ImagesByFile/anthropic), retry off
(FileGoneUploadsAgain), store not read from disk (FilesKeptOnDisk), the
flash check removed (InlineElsewhere), the 8s wait cap removed
(UploadSlowGoesInline).

Not tried: a real DeepSeek key (none available in the sandbox), so the
exact refusal text for a gone file and the Anthropic file_id field are
unconfirmed against the live API. Not covered: a custom_tool_call_output's
images (walkImages doesn't read it); files aren't deleted (they expire in
a day).
This commit is contained in:
yetone
2026-11-06 02:46:46 +08:00
parent 7625481b9e
commit 8fbf8e0af6
7 changed files with 1092 additions and 0 deletions
+1
View File
@@ -294,6 +294,7 @@ recorded as a prediction failure (`noPrediction`).
- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving.
- A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat puts them in a user message right after the results, and the result says they follow; Gemini and Code Assist after the function's response. Kiro's results hold text alone, so Kiro's plugin (from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin` and the Kiro plugin's `tool-images.test.mjs`.
- An image's `detail` (`Part.Detail`, read from a Responses `input_image` and a Chat `image_url`, in a message or a tool's output) is carried on a translation to Chat and Responses (`chatImage`, `chatDetail`, `responsesDetail` in [`chat.go`](../../internal/gateway/chat.go)). Chat takes `low`, `high` and `auto` as they came, and Responses' `original`, which Chat lacks, as `high`; an image without one goes without. Responses takes the four as they came, and anything else, none included, as `auto` (#1474). Messages and Gemini have no such field, so it isn't sent there (mysterious_dove on Discord, Codex: `high` and `original` were dropped on the way to Chat; `TestResponsesImageDetailReachesChat`, `TestChatImageDetailReachesResponses`).
- DeepSeek's own API (`api.deepseek.com`, never a relay or another base) is sent an agent's inline images by file id, not their bytes on every turn (#5407, faithleysath; [`deepseek_files.go`](../../internal/gateway/deepseek_files.go)). `withDeepSeekFiles`, in `forwardOnce` after the thinking is put back and before the byte cap, finds each base64 `data:` image a Chat, Responses or Anthropic body holds (`walkImages`: messages and tool outputs) for a model with `flash` in its name (deepseek-flash sees images; deepseek-v4-pro reads each as "[Unsupported Image]"), with the provider's key, not on count_tokens, and not where the provider is set `imageFilesOff` (`magpie provider set <id> image-files=off`). An image asked at `detail: low` stays inline, as a file is read at full size. Each image not held yet goes up once through `POST /files` on the provider's host (multipart, `purpose=user_data`, `expires_after` a day from creation), signed as a Chat request with the candidate's own key; the swap is per key (`dsKeyHash` beside the image's sha256), so an id never goes with another key. The block becomes Chat's flat `{"type":"file","file_id":…}`, a Responses `input_image` with `file_id` in place of `image_url`, or an Anthropic image whose `source` is `{"type":"file","file_id":…}` with `anthropic-beta: files-api-2025-04-14` added, as DeepSeek's files_api, vision, responses_api and anthropic_api guides give them (the Anthropic guide names the `file` source type and the beta; its field name `file_id` is Anthropic's Files API's, which DeepSeek says it follows). The ids are kept in `deepseek-files.json` beside providers.json (temp file and rename; an unparseable one moved to `.bad`), an id with under an hour left uploaded again, at most 4000 kept. One upload runs per image and key however many requests want it (`flights`), at most four at once for a request, outliving a cancelled request with its own deadline (20s, plus a second per 64KiB). A failed upload leaves the image inline and rests the key's uploads for ten minutes (`dsFilesBreak`); a request waits on an upload for `dsWaitMax` at most and sends what isn't up yet inline. A 4xx whose body names a `file-api-` id or says a file is gone (`dsFileGone`) lets the ids go and asks once more with new uploads (`dsRetryGone` in `forward`); refused so again, it goes inline. Uploaded bytes count in the request's upstream bytes (#4456). Not covered: a `custom_tool_call_output`'s images (walkImages doesn't read it), and no file is deleted (`DELETE /files`): each expires in a day. `TestDeepSeekImagesByFile`, `TestDeepSeekImagesInlineElsewhere`, `TestDeepSeekImageFilesOff`, `TestDeepSeekUploadFailsInline`, `TestDeepSeekUploadSlowGoesInline`, `TestDeepSeekFileGoneUploadsAgain`, `TestDeepSeekFilesPerKey`, `TestDeepSeekFilesOneUpload`, `TestDeepSeekFilesKeptOnDisk`.
- A Gemini client's `generationConfig.imageConfig`, the size and shape it asks an image model to draw at (`imageSize`, `aspectRatio`, and Vertex AI's own fields beside them), is carried as it was sent on a translation to an upstream that speaks Gemini: a custom provider's Gemini URL, Vertex AI, and Code Assist and Antigravity inside their envelope (`Request.ImageConfig`, `buildCodeAssistSent` in [`codeassist.go`](../../internal/gateway/codeassist.go)). A relayed request keeps it as sent. Chat, Responses and Messages have no field for it that magpie knows, so it isn't sent there. A request asked for one body that carries it is translated on the Gemini URL even where the provider has a Chat URL too (One try above); one that doesn't goes to Chat there, unless the user set the model's API to Gemini (#3820, GuoJinguang: `imageSize` 4K asked through magpie drew 1024x1024; `TestGeminiImageConfigReachesTheGeminiAPI`, `TestGeminiImageConfigReachesCodeAssist`).
- Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
- A member the user unchecked in its provider's model list is skipped (`unpicked` in [`group.go`](../../internal/provider/group.go), in `membersOff`; #3911, timonwong): the provider has picks and its served models lack it, as the Routing page strikes it, and the Routing card says it is not ready (`provider.ResolveRoute`). A provider with no picks still routes a model its list lacks (#2642), a decision model is still a decision group's, and a request naming the model itself still reaches it (`resolveIn` takes any `provider/model` of a provider that is on). `group_model_pick_test.go`.
+14
View File
@@ -55,6 +55,9 @@ const providerUsage = `usage:
keeps the cache); OpenAI's API and a ChatGPT (Codex) account do so by
default; additional-tools=off puts it with the other tools,
additional-tools=default is magpie's
image-files=off sends DeepSeek's API an agent's images inline on every
turn; image-files=on, the default, uploads each once (for a day)
and names it by its file id
patience=2m keeps a request to it alone (not through a group) that long
while it is busy or briefly rate limited, asking again after a pause
(at most 4m); patience=off hands the agent the error at once;
@@ -1143,6 +1146,17 @@ func applyPairs(p *provider.Provider, pairs []string) error {
default:
return fmt.Errorf("codex=as-sent|default, not %q", v)
}
case "image-files":
// off: DeepSeek's own API is sent an agent's images inline on
// every turn, not uploaded once and named by file id (#5407)
switch strings.ToLower(v) {
case "off", "no", "inline":
p.ImageFilesOff = true
case "on", "yes", "default":
p.ImageFilesOff = false
default:
return fmt.Errorf("image-files=on|off, not %q", v)
}
case "prompt":
// as-written: Antigravity's subscription is sent the system
// prompt exactly as the agent wrote it, the lines Google turns
+598
View File
@@ -0,0 +1,598 @@
package gateway
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/steady"
)
// DeepSeek's official API is stateless, so an agent sends its whole
// history on every turn, and an image sent inline (a data: URL) goes up
// again each time (#5407). DeepSeek's Files API takes an image once and
// lets a request name it by file_id on every API family
// (api-docs.deepseek.com guides/files_api, guides/vision,
// guides/responses_api, guides/anthropic_api):
//
// - POST /files, multipart: file, purpose=user_data,
// expires_after[anchor]=created_at, expires_after[seconds] (3600 to
// 2592000); the reply's id is file-api-…, with expires_at.
// - Chat: {"type":"file","file_id":"file-api-…"}, flat, not OpenAI's
// nested {"file":{"file_id"}}.
// - Responses: input_image with file_id in place of image_url (the two
// are exclusive), in a message or a function_call_output's output.
// - Anthropic: an image's source {"type":"file","file_id":"…"}, which
// the anthropic-beta files-api-2025-04-14 must come with.
//
// So for a model that sees images (deepseek-flash) on api.deepseek.com
// itself, never a relay or another host, each inline image is uploaded
// once per key and named by its id after. Anything that goes wrong leaves
// the image inline, as it was sent before: the turn never fails for it.
const (
// dsFileTTL is how long DeepSeek keeps an uploaded image: a day, not
// the API's default of for ever, as the image is the user's.
dsFileTTL = 24 * time.Hour
// dsFileFresh: a file with less than this left is uploaded again
// rather than named, so it doesn't expire while a turn is under way.
dsFileFresh = time.Hour
// dsFilesBreak is how long a key's uploads are left alone after one
// failed, its images inline meanwhile, so that every turn doesn't
// wait on an upload that fails.
dsFilesBreak = 10 * time.Minute
// dsFilesAtOnce bounds the uploads one request makes at a time.
dsFilesAtOnce = 4
// dsFilesKept bounds the images remembered per file, the least
// lately used let go first. DeepSeek keeps 10000 a user.
dsFilesKept = 4000
// dsFilesMax is the largest image the Files API takes.
dsFilesMax = 64 << 20
// dsFilesBeta is the beta DeepSeek's Anthropic endpoint wants beside
// an image whose source is a file.
dsFilesBeta = "files-api-2025-04-14"
)
// dsFilesOn is whether a request to p on to, at path, has its inline
// images sent as DeepSeek file references: DeepSeek's own host, with a
// key, a model that sees images, a request that asks a reply, and the
// provider not set image-files=off.
func dsFilesOn(p provider.Provider, to provider.Protocol, path string, body []byte) bool {
if p.ImageFilesOff || p.Key == "" || p.Account != nil || p.IsPlugin() || countsTokens(path) {
return false
}
if to != provider.Chat && to != provider.Responses && to != provider.Anthropic {
return false
}
if provider.HostOf(p.Base(to)) != deepseekHost {
return false
}
// deepseek-flash sees images; deepseek-v4-pro reads each as the text
// "[Unsupported Image]" (guides/anthropic_api), so nothing is gained
// uploading one for it
return strings.Contains(strings.ToLower(modelOf(body)), "flash")
}
// dsFileRef is an image DeepSeek holds for a key.
type dsFileRef struct {
ID string `json:"id"`
Expires time.Time `json:"expires"`
Used time.Time `json:"used"`
}
// dsFileStore is the images uploaded for each key, by the key's hash and
// the image's, kept in deepseek-files.json beside providers.json so a
// restart doesn't upload them again.
type dsFileStore struct {
mu sync.Mutex
wmu sync.Mutex // held while the file is written
path string
refs map[string]dsFileRef
flights map[string]*dsFlight
broken map[string]time.Time // a key's hash: when its uploads are tried again
}
// dsFlight is an upload under way, which a request wanting the same
// image for the same key waits for rather than uploading it again.
type dsFlight struct {
done chan struct{}
ref dsFileRef
err error
}
var dsStores = struct {
sync.Mutex
m map[string]*dsFileStore
}{m: map[string]*dsFileStore{}}
// dsNow is the clock the store reads; a test moves it.
var dsNow = time.Now
// dsWaitMax is the longest a request waits on its uploads before it
// sends the images not up yet inline; a test shortens it.
var dsWaitMax = 8 * time.Second
// dsJoined counts the requests that waited on another's upload, for a
// test to wait on.
var dsJoined atomic.Int64
// dsFilesPath is the file the uploaded images are kept in.
func dsFilesPath() string {
return filepath.Join(filepath.Dir(provider.Path()), "deepseek-files.json")
}
// dsStore is the store for this config folder, read from its file once.
// A file that can't be parsed is moved aside and the store starts empty:
// every image is uploaded again, as on a first run.
func dsStore() *dsFileStore {
path := dsFilesPath()
dsStores.Lock()
defer dsStores.Unlock()
if st := dsStores.m[path]; st != nil {
return st
}
st := &dsFileStore{path: path, refs: map[string]dsFileRef{}, flights: map[string]*dsFlight{}, broken: map[string]time.Time{}}
if b, err := os.ReadFile(path); err == nil {
if json.Unmarshal(b, &st.refs) != nil {
st.refs = map[string]dsFileRef{}
os.Rename(path, path+".bad")
}
}
dsStores.m[path] = st
return st
}
// dsKeyHash names a key in the store without keeping the key.
func dsKeyHash(key string) string {
h := sha256.Sum256([]byte("deepseek-files\x00" + key))
return hex.EncodeToString(h[:8])
}
// save writes the store through a file renamed over the old one. The
// write runs outside mu, which requests take to look an image up, under
// wmu, which keeps one save's file from going over a later one's.
func (st *dsFileStore) save() {
st.wmu.Lock()
defer st.wmu.Unlock()
st.mu.Lock()
now := dsNow()
for k, r := range st.refs {
if !r.Expires.After(now) {
delete(st.refs, k)
}
}
if len(st.refs) > dsFilesKept {
keys := make([]string, 0, len(st.refs))
for k := range st.refs {
keys = append(keys, k)
}
slices.SortFunc(keys, func(a, b string) int { return st.refs[a].Used.Compare(st.refs[b].Used) })
for _, k := range keys[:len(keys)-dsFilesKept] {
delete(st.refs, k)
}
}
b, err := json.Marshal(st.refs)
st.mu.Unlock()
if err != nil || os.MkdirAll(filepath.Dir(st.path), 0o700) != nil {
return
}
target, err := edit.Target(st.path)
if err != nil {
return
}
tmp := target + ".magpie-tmp"
if os.WriteFile(tmp, b, 0o600) != nil {
return
}
if steady.Rename(tmp, target) != nil {
os.Remove(tmp)
}
}
// forget lets the images keys named go, after DeepSeek said it has no
// such file.
func (st *dsFileStore) forget(keys []string) {
st.mu.Lock()
for _, k := range keys {
delete(st.refs, k)
}
st.mu.Unlock()
st.save()
}
// breakFor leaves the key's uploads alone for dsFilesBreak.
func (st *dsFileStore) breakFor(acct string) {
st.mu.Lock()
st.broken[acct] = dsNow().Add(dsFilesBreak)
st.mu.Unlock()
}
// dsImage is an inline image of a request: its hash and the base64 it
// came as.
type dsImage struct {
key string // the key's hash, ":", the image's
mime string
b64 string
}
// dsSent is what a try named by file, kept in its context for forward:
// the store's keys of the images, so a reply that says DeepSeek has no
// such file lets them go, and whether this try goes inline instead.
type dsSent struct {
keys []string
inline bool
}
type dsSentKey struct{}
func dsSentOf(ctx context.Context) *dsSent {
s, _ := ctx.Value(dsSentKey{}).(*dsSent)
return s
}
// dsInlineImage reads an image block's data: URL, when it is one the
// Files API can take in its place: base64, not asked at detail low (a
// file is read at full size, which costs more tokens), not over the
// API's size.
func dsInlineImage(to provider.Protocol, im imageAt) (mime, b64 string, ok bool) {
rest, found := strings.CutPrefix(im.Src, "data:")
if !found {
return "", "", false
}
meta, data, found := strings.Cut(rest, ",")
if !found || !strings.HasSuffix(meta, ";base64") || data == "" || len(data)/4*3 > dsFilesMax {
return "", "", false
}
if to != provider.Anthropic {
var block struct {
Detail string `json:"detail"`
ImageURL json.RawMessage `json:"image_url"`
}
decodeJSON(im.Block, &block)
detail := block.Detail
if to == provider.Chat {
var u struct {
Detail string `json:"detail"`
}
decodeJSON(block.ImageURL, &u)
detail = u.Detail
}
if detail == "low" {
return "", "", false
}
}
return strings.TrimSuffix(meta, ";base64"), data, true
}
// withDeepSeekFiles is body with every inline image it can name by file
// sent so, each uploaded first for p's key when DeepSeek doesn't hold it
// yet, and whether any was. An image whose upload failed stays inline.
func (s *Server) withDeepSeekFiles(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte) ([]byte, bool) {
sent := dsSentOf(ctx)
if sent != nil && sent.inline || !dsFilesOn(p, to, path, body) {
return body, false
}
acct := dsKeyHash(p.Key)
var images []dsImage
seen := map[string]bool{}
walkImages(to, body, func(im imageAt) (json.RawMessage, error) {
mime, b64, ok := dsInlineImage(to, im)
if !ok {
return nil, nil
}
h := sha256.Sum256([]byte(b64))
key := acct + ":" + hex.EncodeToString(h[:])
if !seen[key] {
seen[key] = true
images = append(images, dsImage{key: key, mime: mime, b64: b64})
}
return nil, nil
})
if len(images) == 0 {
return body, false
}
ids := s.dsResolve(ctx, p, to, acct, images)
if len(ids) == 0 {
return body, false
}
out, err := walkImages(to, body, func(im imageAt) (json.RawMessage, error) {
_, b64, ok := dsInlineImage(to, im)
if !ok {
return nil, nil
}
h := sha256.Sum256([]byte(b64))
id := ids[acct+":"+hex.EncodeToString(h[:])]
if id == "" {
return nil, nil
}
return dsFileBlock(to, im.Block, id), nil
})
if err != nil || bytes.Equal(out, body) {
return body, false
}
if sent != nil {
for k := range ids {
sent.keys = append(sent.keys, k)
}
}
return out, true
}
// dsFileBlock is an image's block naming the file id in its place, in
// to's shape; the block's other fields (Anthropic's cache_control) stay.
func dsFileBlock(to provider.Protocol, raw json.RawMessage, id string) json.RawMessage {
idJSON, _ := json.Marshal(id)
if to == provider.Chat {
return json.RawMessage(`{"type":"file","file_id":` + string(idJSON) + `}`)
}
var block map[string]json.RawMessage
if decodeJSON(raw, &block) != nil {
return nil
}
if to == provider.Responses {
delete(block, "image_url")
block["file_id"] = idJSON
} else {
block["source"] = json.RawMessage(`{"type":"file","file_id":` + string(idJSON) + `}`)
}
b, err := json.Marshal(block)
if err != nil {
return nil
}
return b
}
// dsResolve is the file id of each image DeepSeek holds, or now holds,
// for the key: those known and not about to expire as they are, the
// others uploaded, a few at a time, one upload for an image however many
// requests want it at once. An image whose upload failed has none, and a
// failure leaves the key's uploads alone for a while.
func (s *Server) dsResolve(ctx context.Context, p provider.Provider, to provider.Protocol, acct string, images []dsImage) map[string]string {
st := dsStore()
now := dsNow()
ids := map[string]string{}
var waits []*dsFlight
var waitKeys []string
var starts []dsImage
st.mu.Lock()
broken := st.broken[acct].After(now)
for _, im := range images {
if r, ok := st.refs[im.key]; ok && r.Expires.Sub(now) > dsFileFresh {
r.Used = now
st.refs[im.key] = r
ids[im.key] = r.ID
continue
}
if f := st.flights[im.key]; f != nil {
waits, waitKeys = append(waits, f), append(waitKeys, im.key)
dsJoined.Add(1)
continue
}
if broken {
continue
}
f := &dsFlight{done: make(chan struct{})}
st.flights[im.key] = f
waits, waitKeys = append(waits, f), append(waitKeys, im.key)
starts = append(starts, im)
}
st.mu.Unlock()
if len(starts) > 0 {
// the uploads outlive a request that is cancelled, for the
// others waiting on them; each has its own deadline
up := context.WithoutCancel(p.Via(ctx))
slots := make(chan struct{}, dsFilesAtOnce)
for _, im := range starts {
go func() {
slots <- struct{}{}
ref, err := s.dsUpload(up, p, to, im)
<-slots
st.mu.Lock()
f := st.flights[im.key]
delete(st.flights, im.key)
if err == nil {
ref.Used = dsNow()
st.refs[im.key] = ref
} else {
st.broken[acct] = dsNow().Add(dsFilesBreak)
}
st.mu.Unlock()
if err == nil {
st.save()
}
if f != nil {
f.ref, f.err = ref, err
close(f.done)
}
}()
}
}
// a turn waits a little for its uploads, not for a slow line: what
// isn't up by then goes inline this once and by file next turn
wait := time.NewTimer(dsWaitMax)
defer wait.Stop()
for i, f := range waits {
select {
case <-f.done:
if f.err == nil && f.ref.ID != "" {
ids[waitKeys[i]] = f.ref.ID
}
case <-wait.C:
return ids
case <-ctx.Done():
return ids
}
}
if n := len(starts); n > 0 {
// the uploads went to the vendor on the request's behalf (#4456)
var up int
for _, im := range starts {
up += len(im.b64) / 4 * 3
}
if u := upBytesOf(ctx); u != nil {
u.wire += up
}
}
return ids
}
// dsUpload sends one image to DeepSeek's Files API for p's key, to expire
// in dsFileTTL. Its deadline grows with the image: a slow line takes a
// while, but an upload that hangs doesn't hold the turn for ever.
func (s *Server) dsUpload(ctx context.Context, p provider.Provider, to provider.Protocol, im dsImage) (dsFileRef, error) {
data, err := base64.StdEncoding.DecodeString(im.b64)
if err != nil {
if data, err = base64.RawStdEncoding.DecodeString(im.b64); err != nil {
return dsFileRef{}, err
}
}
base, err := url.Parse(p.Base(to))
if err != nil || base.Host == "" {
return dsFileRef{}, errors.New("no DeepSeek host")
}
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
mw.WriteField("purpose", "user_data")
mw.WriteField("expires_after[anchor]", "created_at")
mw.WriteField("expires_after[seconds]", strconv.Itoa(int(dsFileTTL/time.Second)))
h := textproto.MIMEHeader{}
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="image%s"`, dsExt(im.mime)))
if im.mime != "" {
h.Set("Content-Type", im.mime)
}
fw, err := mw.CreatePart(h)
if err != nil {
return dsFileRef{}, err
}
fw.Write(data)
mw.Close()
ctx, cancel := context.WithTimeout(ctx, 20*time.Second+time.Duration(len(data)/(64<<10))*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base.Scheme+"://"+base.Host+"/files", bytes.NewReader(buf.Bytes()))
if err != nil {
return dsFileRef{}, err
}
// the key as a Chat request carries it (Authorization: Bearer)
if err := p.Sign(ctx, req, provider.Chat, nil); err != nil {
return dsFileRef{}, err
}
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", userAgentFor(p, ""))
res, err := p.Do(s.client, req)
if err != nil {
return dsFileRef{}, err
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if res.StatusCode/100 != 2 {
return dsFileRef{}, fmt.Errorf("upload: %d %s", res.StatusCode, b)
}
var got struct {
ID string `json:"id"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
}
if json.Unmarshal(b, &got) != nil || got.ID == "" {
return dsFileRef{}, fmt.Errorf("upload: no file id in %s", b)
}
ref := dsFileRef{ID: got.ID, Expires: dsNow().Add(dsFileTTL)}
if got.ExpiresAt > 0 {
ref.Expires = time.Unix(got.ExpiresAt, 0)
}
return ref, nil
}
// dsExt is a file name's extension for an image's media type. DeepSeek
// reads the format from the bytes; the name is only a name.
func dsExt(mime string) string {
switch mime {
case "image/jpeg", "image/jpg":
return ".jpg"
case "image/gif":
return ".gif"
case "image/webp":
return ".webp"
}
return ".png"
}
// dsFileGone is whether DeepSeek's refusal of a request that named
// files says one of them is gone: expired, deleted, or never this key's
// account's. Its exact words aren't documented, so a 4xx that names a
// file id sent, or a file and its being missing, counts.
func dsFileGone(code int, body []byte) bool {
if code < 400 || code >= 500 || code == http.StatusTooManyRequests {
return false
}
low := strings.ToLower(string(body))
if strings.Contains(low, "file-api-") {
return true
}
if !strings.Contains(low, "file") {
return false
}
for _, w := range []string{"not found", "not exist", "expired", "no such", "deleted", "invalid file", "unknown file"} {
if strings.Contains(low, w) {
return true
}
}
return false
}
// dsBeta is betas with the Files API's added, for an Anthropic request
// that names an image by file.
func dsBeta(betas []string) []string {
if slices.Contains(betas, dsFilesBeta) {
return betas
}
return append(slices.Clone(betas), dsFilesBeta)
}
// dsRetryGone asks again a request DeepSeek refused because a file it
// named is gone (expired early, deleted, or the store out of date): the
// images are let go and uploaded again, once; refused again so, the
// request goes with them inline, and the key's uploads rest a while.
func (s *Server) dsRetryGone(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) {
sent := dsSentOf(ctx)
for try := 0; sent != nil && len(sent.keys) > 0 && !sent.inline && try < 2; try++ {
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if !dsFileGone(res.StatusCode, b) {
return res, nil
}
st := dsStore()
st.forget(sent.keys)
sent.keys = nil
if try == 1 {
st.breakFor(dsKeyHash(p.Key))
sent.inline = true
}
var err error
if res, err = s.forwardOnce(ctx, p, to, path, body, in); err != nil || res.StatusCode < 400 {
return res, err
}
}
return res, nil
}
+452
View File
@@ -0,0 +1,452 @@
package gateway
import (
"context"
"encoding/base64"
"fmt"
"io"
"maps"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
const responsesWholeOK = `{"id":"resp_1","object":"response","status":"completed","model":"m1","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`
// dsFilesUp stands for api.deepseek.com and the other hosts the tests
// send to: its Files API hands out file-api-N ids, and its three APIs
// keep what they were sent.
type dsFilesUp struct {
t *testing.T
mu sync.Mutex
uploads []string // each upload's key
sent map[string][]string
betas []string
failUploads bool
slowUpload chan struct{} // an upload waits for it to close
gone int // requests naming a file answered 404, at most
n int
}
func (u *dsFilesUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/files" {
if u.slowUpload != nil {
<-u.slowUpload
}
if err := r.ParseMultipartForm(1 << 20); err != nil {
u.t.Errorf("upload not multipart: %v", err)
}
f := r.MultipartForm
if f == nil || f.Value["purpose"][0] != "user_data" || f.Value["expires_after[anchor]"][0] != "created_at" || f.Value["expires_after[seconds]"][0] != "86400" || len(f.File["file"]) != 1 {
u.t.Errorf("upload fields: %+v", f)
}
u.mu.Lock()
u.uploads = append(u.uploads, r.Header.Get("Authorization"))
u.n++
n, fail := u.n, u.failUploads
u.mu.Unlock()
if fail {
http.Error(w, `{"error":{"message":"busy"}}`, 503)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"id":"file-api-%d","object":"file","bytes":10,"created_at":%d,"filename":"image.png","purpose":"user_data","expires_at":%d}`, n, time.Now().Unix(), time.Now().Add(24*time.Hour).Unix())
return
}
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
if u.sent == nil {
u.sent = map[string][]string{}
}
u.sent[r.URL.Path] = append(u.sent[r.URL.Path], string(b))
if r.URL.Path == "/anthropic/v1/messages" {
u.betas = append(u.betas, r.Header.Get("anthropic-beta"))
}
gone := u.gone > 0 && strings.Contains(string(b), "file-api-")
if gone {
u.gone--
}
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if gone {
w.WriteHeader(404)
w.Write([]byte(`{"error":{"message":"File not found","type":"invalid_request_error"}}`))
return
}
switch {
case strings.HasSuffix(r.URL.Path, "/chat/completions"):
w.Write([]byte(chatWholeOK))
case strings.HasSuffix(r.URL.Path, "/responses"):
w.Write([]byte(responsesWholeOK))
default:
w.Write([]byte(anthropicWholeOK))
}
}
func (u *dsFilesUp) last(path string) string {
u.mu.Lock()
defer u.mu.Unlock()
s := u.sent[path]
if len(s) == 0 {
return ""
}
return s[len(s)-1]
}
func (u *dsFilesUp) count(path string) int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.sent[path])
}
func (u *dsFilesUp) uploaded() []string {
u.mu.Lock()
defer u.mu.Unlock()
return append([]string(nil), u.uploads...)
}
// dsSetup saves DeepSeek's own API, a relay serving its model, and
// another vendor, all answered by one fake that every host dials.
func dsSetup(t *testing.T, ps ...provider.Provider) (*Server, *dsFilesUp) {
t.Helper()
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
u := &dsFilesUp{t: t}
up := httptest.NewServer(u)
t.Cleanup(up.Close)
if len(ps) == 0 {
ps = []provider.Provider{
{ID: "deepseek", Name: "DeepSeek", Key: "k1", Models: []string{"deepseek-flash", "deepseek-v4-pro"}, Chat: "http://api.deepseek.com/v1", Responses: "http://api.deepseek.com/v1", Anthropic: "http://api.deepseek.com/anthropic"},
{ID: "relay", Name: "Relay", Key: "k1", Models: []string{"deepseek-flash"}, Chat: "http://relay.example.com/v1", Responses: "http://relay.example.com/v1", Anthropic: "http://relay.example.com/anthropic"},
{ID: "kimi", Name: "Kimi", Key: "k1", Models: []string{"kimi-k2.5-flash"}, Chat: "http://api.moonshot.ai/v1", Anthropic: "http://api.moonshot.ai/anthropic"},
}
}
for _, p := range ps {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
addr := strings.TrimPrefix(up.URL, "http://")
s.client = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr)
}}}
return s, u
}
var (
dsPNG1 = base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\nfirst image"))
dsPNG2 = base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\nsecond image"))
)
// dsBodies are a request with an image on each API, by its path.
func dsBody(api, model, img string) (path, upPath, body string) {
switch api {
case "chat":
return "/v1/chat/completions", "/v1/chat/completions", `{"model":"` + model + `","stream":false,"messages":[{"role":"user","content":[{"type":"text","text":"what is it"},{"type":"image_url","image_url":{"url":"data:image/png;base64,` + img + `"}}]}]}`
case "responses":
return "/v1/responses", "/v1/responses", `{"model":"` + model + `","stream":false,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"what is it"},{"type":"input_image","image_url":"data:image/png;base64,` + img + `","detail":"auto"}]}]}`
}
return "/v1/messages", "/anthropic/v1/messages", `{"model":"` + model + `","max_tokens":100,"stream":false,"messages":[{"role":"user","content":[{"type":"text","text":"what is it"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + img + `"},"cache_control":{"type":"ephemeral"}}]}]}`
}
// On DeepSeek's own API an inline image goes up once and every turn
// after names it by file id, in each API's shape (#5407); the Anthropic
// request carries the Files API's beta.
func TestDeepSeekImagesByFile(t *testing.T) {
for _, c := range []struct{ api, want string }{
{"chat", `{"type":"file","file_id":"file-api-1"}`},
{"responses", `"file_id":"file-api-1"`},
{"anthropic", `"source":{"type":"file","file_id":"file-api-1"}`},
} {
t.Run(c.api, func(t *testing.T) {
s, u := dsSetup(t)
path, upPath, body := dsBody(c.api, "deepseek/deepseek-flash", dsPNG1)
for turn := range 2 {
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("turn %d: %d %s", turn, code, reply)
}
got := u.last(upPath)
if !strings.Contains(got, c.want) || strings.Contains(got, dsPNG1) {
t.Fatalf("turn %d: the image not named by file: %s", turn, got)
}
}
if ups := u.uploaded(); len(ups) != 1 || ups[0] != "Bearer k1" {
t.Errorf("uploads %v, want one with the key", ups)
}
if c.api == "responses" && strings.Contains(u.last(upPath), `"image_url"`) {
t.Errorf("image_url kept beside file_id: %s", u.last(upPath))
}
if c.api == "anthropic" {
if !strings.Contains(u.last(upPath), `"cache_control"`) {
t.Errorf("cache_control lost: %s", u.last(upPath))
}
if b := u.betas[len(u.betas)-1]; !strings.Contains(b, dsFilesBeta) {
t.Errorf("anthropic-beta %q, want %s", b, dsFilesBeta)
}
}
})
}
}
// A relay serving DeepSeek's model, another vendor, DeepSeek's model that
// doesn't see images, and an image at detail low all go inline as sent,
// and nothing is uploaded for them.
func TestDeepSeekImagesInlineElsewhere(t *testing.T) {
s, u := dsSetup(t)
for _, c := range []struct{ api, model string }{
{"chat", "relay/deepseek-flash"},
{"anthropic", "relay/deepseek-flash"},
{"responses", "relay/deepseek-flash"},
{"chat", "kimi/kimi-k2.5-flash"},
{"anthropic", "kimi/kimi-k2.5-flash"},
{"chat", "deepseek/deepseek-v4-pro"},
} {
path, upPath, body := dsBody(c.api, c.model, dsPNG1)
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%s %s: %d %s", c.api, c.model, code, reply)
}
if got := u.last(upPath); !strings.Contains(got, dsPNG1) || strings.Contains(got, "file-api-") {
t.Errorf("%s %s: not sent inline: %s", c.api, c.model, got)
}
}
low := `{"model":"deepseek/deepseek-flash","stream":false,"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,` + dsPNG1 + `","detail":"low"}}]}]}`
if code, reply := postTo(t, s, "/v1/chat/completions", low); code != 200 {
t.Fatalf("low: %d %s", code, reply)
}
if got := u.last("/v1/chat/completions"); !strings.Contains(got, dsPNG1) {
t.Errorf("detail low not inline: %s", got)
}
if ups := u.uploaded(); len(ups) != 0 {
t.Errorf("uploaded %d, want none", len(ups))
}
if b := u.betas; len(b) > 0 && strings.Contains(strings.Join(b, ","), dsFilesBeta) {
t.Errorf("files beta sent off DeepSeek: %v", b)
}
}
// image-files=off sends DeepSeek its images inline.
func TestDeepSeekImageFilesOff(t *testing.T) {
s, u := dsSetup(t, provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k1", Models: []string{"deepseek-flash"}, Chat: "http://api.deepseek.com/v1", ImageFilesOff: true})
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", dsPNG1)
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%d %s", code, reply)
}
if got := u.last(upPath); !strings.Contains(got, dsPNG1) || len(u.uploaded()) != 0 {
t.Errorf("not inline with the switch off: %s, %d uploads", got, len(u.uploaded()))
}
}
// A failed upload leaves the image inline and the turn answered, and the
// key's uploads aren't tried again on the next turns for a while.
func TestDeepSeekUploadFailsInline(t *testing.T) {
s, u := dsSetup(t)
u.failUploads = true
for turn := range 3 {
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", []string{dsPNG1, dsPNG2, dsPNG1}[turn])
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("turn %d: %d %s", turn, code, reply)
}
if got := u.last(upPath); strings.Contains(got, "file-api-") || !strings.Contains(got, "base64,") {
t.Errorf("turn %d: not inline: %s", turn, got)
}
}
if n := len(u.uploaded()); n != 1 {
t.Errorf("%d uploads, want 1 before the key's uploads rest", n)
}
}
// An upload that hangs doesn't hold the turn: past dsWaitMax the image
// goes inline, and once the upload is done the next turn names it.
func TestDeepSeekUploadSlowGoesInline(t *testing.T) {
s, u := dsSetup(t)
u.slowUpload = make(chan struct{})
var release sync.Once
letGo := func() { release.Do(func() { close(u.slowUpload) }) }
defer letGo()
old := dsWaitMax
dsWaitMax = 100 * time.Millisecond
t.Cleanup(func() { dsWaitMax = old })
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", dsPNG1)
start := time.Now()
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%d %s", code, reply)
}
if d := time.Since(start); d > 5*time.Second {
t.Errorf("the turn waited %v on the upload", d)
}
if got := u.last(upPath); strings.Contains(got, "file-api-") || !strings.Contains(got, dsPNG1) {
t.Errorf("not inline while the upload hangs: %s", got)
}
letGo()
for deadline := time.Now().Add(10 * time.Second); len(dsWaitingFlights()) > 0 || len(u.uploaded()) == 0; {
if time.Now().After(deadline) {
t.Fatal("the upload never ended")
}
time.Sleep(5 * time.Millisecond)
}
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%d %s", code, reply)
}
if got := u.last(upPath); !strings.Contains(got, "file-api-1") {
t.Errorf("not named by file once uploaded: %s", got)
}
}
// A file DeepSeek says is gone is uploaded again and the request asked
// once more with the new id; gone again, the request goes inline.
func TestDeepSeekFileGoneUploadsAgain(t *testing.T) {
s, u := dsSetup(t)
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", dsPNG1)
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%d %s", code, reply)
}
u.mu.Lock()
u.gone = 1
u.mu.Unlock()
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("after gone: %d %s", code, reply)
}
if got := u.last(upPath); !strings.Contains(got, `"file_id":"file-api-2"`) {
t.Errorf("not asked again with a new upload: %s", got)
}
u.mu.Lock()
u.gone = 5
u.mu.Unlock()
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("gone twice: %d %s", code, reply)
}
if got := u.last(upPath); strings.Contains(got, "file-api-") || !strings.Contains(got, dsPNG1) {
t.Errorf("not inline after the file was gone twice: %s", got)
}
}
// Each key uploads its own: an id never goes with another key.
func TestDeepSeekFilesPerKey(t *testing.T) {
s, u := dsSetup(t,
provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k1", Models: []string{"deepseek-flash"}, Chat: "http://api.deepseek.com/v1"},
provider.Provider{ID: "deepseek-2", Name: "DeepSeek 2", Key: "k2", Models: []string{"deepseek-flash"}, Chat: "http://api.deepseek.com/v1"},
)
for _, m := range []string{"deepseek/deepseek-flash", "deepseek-2/deepseek-flash", "deepseek/deepseek-flash"} {
path, _, body := dsBody("chat", m, dsPNG1)
if code, reply := postTo(t, s, path, body); code != 200 {
t.Fatalf("%s: %d %s", m, code, reply)
}
}
if ups := u.uploaded(); len(ups) != 2 || ups[0] != "Bearer k1" || ups[1] != "Bearer k2" {
t.Errorf("uploads %v, want one per key", ups)
}
if got := u.last("/v1/chat/completions"); !strings.Contains(got, "file-api-1") {
t.Errorf("the first key not sent its own id: %s", got)
}
}
// Requests wanting one image at once upload it once.
func TestDeepSeekFilesOneUpload(t *testing.T) {
s, u := dsSetup(t)
u.slowUpload = make(chan struct{})
var wg sync.WaitGroup
var release sync.Once
letGo := func() { release.Do(func() { close(u.slowUpload) }) }
// a red run doesn't leave its requests waiting on the upload
defer func() {
letGo()
wg.Wait()
}()
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", dsPNG1)
for range 4 {
wg.Go(func() {
if code, reply := postTo(t, s, path, body); code != 200 {
t.Errorf("%d %s", code, reply)
}
})
}
// the other three wait on the first one's upload
joined := dsJoined.Load()
for deadline := time.Now().Add(20 * time.Second); dsJoined.Load()-joined < 3 || len(dsWaitingFlights()) != 1; {
if time.Now().After(deadline) {
t.Fatalf("joined %d, flights %d", dsJoined.Load()-joined, len(dsWaitingFlights()))
}
time.Sleep(5 * time.Millisecond)
}
letGo()
wg.Wait()
if n := len(u.uploaded()); n != 1 {
t.Errorf("%d uploads, want 1", n)
}
if u.count(upPath) != 4 || !strings.Contains(u.last(upPath), "file-api-1") {
t.Errorf("requests %d: %s", u.count(upPath), u.last(upPath))
}
}
// The ids are kept on disk: after a restart the image isn't uploaded
// again, and an expired one is. A file that can't be read is set aside.
func TestDeepSeekFilesKeptOnDisk(t *testing.T) {
s, u := dsSetup(t)
path, upPath, body := dsBody("chat", "deepseek/deepseek-flash", dsPNG1)
postTo(t, s, path, body)
forgetStores := func() {
dsStores.Lock()
delete(dsStores.m, dsFilesPath())
dsStores.Unlock()
}
forgetStores()
postTo(t, s, path, body)
if n := len(u.uploaded()); n != 1 || !strings.Contains(u.last(upPath), "file-api-1") {
t.Errorf("after a restart: %d uploads, %s", n, u.last(upPath))
}
// a day on, the file has expired: uploaded again
dsNow = func() time.Time { return time.Now().Add(23*time.Hour + 30*time.Minute) }
t.Cleanup(func() { dsNow = time.Now })
postTo(t, s, path, body)
if n := len(u.uploaded()); n != 2 || !strings.Contains(u.last(upPath), "file-api-2") {
t.Errorf("near expiry: %d uploads, %s", n, u.last(upPath))
}
dsNow = time.Now
forgetStores()
if err := os.WriteFile(dsFilesPath(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
postTo(t, s, path, body)
if b, err := os.ReadFile(dsFilesPath() + ".bad"); err != nil || string(b) != "{not json" {
t.Errorf("unreadable file not set aside: %q %v", b, err)
}
if !strings.Contains(u.last(upPath), "file-api-3") {
t.Errorf("after an unreadable file: %s", u.last(upPath))
}
}
func TestDsFileGone(t *testing.T) {
for _, c := range []struct {
code int
body string
want bool
}{
{404, `{"error":{"message":"File not found"}}`, true},
{400, `{"error":{"message":"file-api-12 does not exist"}}`, true},
{400, `{"error":{"message":"The file has expired"}}`, true},
{400, `{"error":{"message":"max_tokens too large"}}`, false},
{429, `{"error":{"message":"file not found"}}`, false},
{500, `{"error":{"message":"file not found"}}`, false},
} {
if got := dsFileGone(c.code, []byte(c.body)); got != c.want {
t.Errorf("%d %s: %v", c.code, c.body, got)
}
}
}
func dsWaitingFlights() map[string]*dsFlight {
st := dsStore()
st.mu.Lock()
defer st.mu.Unlock()
return maps.Clone(st.flights)
}
+16
View File
@@ -5347,7 +5347,16 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
heardNet() // the network is up (offline.go)
}
}()
if provider.HostOf(p.Base(to)) == deepseekHost {
// which images a try named by file (deepseek_files.go)
ctx = context.WithValue(ctx, dsSentKey{}, &dsSent{})
}
res, err = s.forwardOnce(ctx, p, to, path, body, in)
if err == nil && res.StatusCode >= 400 {
// a file DeepSeek no longer holds: uploaded again, or the
// images sent inline (deepseek_files.go)
res, err = s.dsRetryGone(ctx, p, to, path, body, in, res)
}
if err == nil && res.StatusCode >= 400 {
// a body over the provider's byte cap: asked again with its
// oldest images left out, or said as a 413 (body_cap.go)
@@ -5413,6 +5422,7 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
// forwardOnce is one request to the provider, as forward makes it.
func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header) (*http.Response, error) {
reqCtx := ctx
ctx = s.metered(p.Via(ctx), p, "")
body = deepseekToolPatterns(p, to, body)
body = grokToolPatterns(p, to, body)
@@ -5429,6 +5439,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
// the tool turns' thinking a provider's model asked for before
// (thinking_back.go)
body = s.withThinkingBack(p, to, body)
// DeepSeek's own API: inline images it holds for this key named by
// file id, uploaded once (deepseek_files.go)
body, byFile := s.withDeepSeekFiles(reqCtx, p, to, path, body)
// under the byte cap the provider refused a larger request over,
// its oldest images left out (body_cap.go)
body = s.withinCap(p, to, path, body)
@@ -5480,6 +5493,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
}
// auto mode's review goes to Claude alone (automode.go)
betas, body = s.serverReview(p, asked, body)
if byFile {
betas = dsBeta(betas)
}
}
// the conversation ${sessionId} and ${threadId} stand for in the
// user's own fields and headers for the provider (conversation.go);
+5
View File
@@ -1909,6 +1909,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if !in.CodexAsSent && old != nil {
in.CodexAsSent = old.CodexAsSent
}
// and DeepSeek's images sent inline, set with `magpie
// provider set <id> image-files=off` (#5407)
if !in.ImageFilesOff && old != nil {
in.ImageFilesOff = old.ImageFilesOff
}
// and Antigravity's prompt as written, set with `magpie
// provider set antigravity prompt=as-written`
if !in.PromptAsWritten && old != nil {
+6
View File
@@ -318,6 +318,12 @@ type Provider struct {
// fitting, which a backend that isn't OpenAI's needs (#350).
CodexAsSent bool `json:"codexAsSent,omitempty"`
// ImageFilesOff, `image-files=off`, has DeepSeek's own API sent an
// agent's inline images inline on every turn. By default each goes up
// once through DeepSeek's Files API, for a day, and the turns name it
// by its file id (gateway's deepseek_files.go, #5407).
ImageFilesOff bool `json:"imageFilesOff,omitempty"`
// PromptAsWritten, on Antigravity's subscription, has the system prompt
// go to Google exactly as the agent wrote it. By default the few lines
// Google answers with a 429 "Resource has been exhausted" whatever